DeepSeekService.php 935 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008
  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\Models\MpTaskCenter;
  11. use App\Models\MpUserPointsDetail;
  12. use App\Services\AIGeneration\AIImageGenerationService;
  13. use App\Services\PointsService;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Log;
  16. use Illuminate\Support\Facades\Redis;
  17. use OSS\Core\OssException;
  18. use OSS\OssClient;
  19. use Smalot\PdfParser\Parser as PdfParser;
  20. use TCPDF;
  21. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  22. use Predis\Command\Traits\Get\Get;
  23. class DeepSeekService
  24. {
  25. private $url;
  26. private $api_key;
  27. private $sys_message;
  28. private $headers;
  29. private $valid_text_models;
  30. private $gpt_text_models;
  31. private $gemini_text_models;
  32. protected $aiImageGenerationService;
  33. protected $pointsService;
  34. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  35. $this->aiImageGenerationService = $aiImageGenerationService;
  36. $this->pointsService = $pointsService;
  37. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  38. $this->api_key = env('DEEPSEEK_API_KEY');
  39. $this->headers = [
  40. 'Authorization' => 'Bearer '.$this->api_key,
  41. 'Content-Type' => 'application/json; charset=UTF-8'
  42. ];
  43. // 火山引擎模型列表
  44. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  45. // GPT文本模型列表
  46. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  47. // Gemini文本模型列表
  48. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  49. $this->sys_message = [
  50. 'role' => 'system',
  51. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  52. 强制要求:\n
  53. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  54. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  55. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  56. 普通要求:\n
  57. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  58. 2.<分集剧本>的要求如下:
  59.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  60.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  61.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  62.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  63. \n\n
  64. 示例如下:\n
  65. ###剧本名:西昆仑
  66. ###故事梗概
  67. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  68. ###剧本亮点
  69. 亮点1:绝境奇药,生死一线
  70. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  71. 亮点2:结拜兄妹,化解尴尬
  72. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  73. 亮点3:纤发夺命,情愫暗涌
  74. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  75. ###人物关系
  76. 阿雪与梁萧之间存在兄妹之情。
  77. ###核心矛盾
  78. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  79. ###主体列表
  80. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  81. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  82. 阴阳球:天地异宝,能化生精气,救人于危难。
  83. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  84. ###美术风格
  85. 基础画风风格词:厚涂古风
  86. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  87. ###场景列表
  88. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  89. ###分集剧本
  90. ##分集01
  91. 第1集: 第一集的标题
  92. 场景描述:地点、时间、场景
  93. 运镜:固定近距离
  94. 出场角色:男主、女主
  95. 台词内容:
  96. 女主: 女主对话
  97. 男主:男主对话
  98. 女主: 女主对话
  99. 男主: 男主对话
  100. ##分集02
  101. 第2集: 第二集的标题
  102. 场景描述:地点、时间、场景
  103. 运镜:固定近距离
  104. 出场角色:男主、女主
  105. 台词内容:
  106. 女主: 女主对话
  107. 男主:男主对话
  108. 女主: 女主对话
  109. 男主: 男主对话"
  110. ];
  111. }
  112. /**
  113. * 通用文生文方法 - 支持多模型流式输出、图片输入;视频输入仅 Gemini 模型支持
  114. *
  115. * @param array $data 请求参数
  116. * @return \Generator 返回生成器,用于流式输出
  117. */
  118. public function generateText($data) {
  119. // 获取请求参数
  120. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  121. $messages = getProp($data, 'messages', []);
  122. $systemPrompt = getProp($data, 'system_prompt', '');
  123. $prompt = getProp($data, 'prompt', '');
  124. $images = getProp($data, 'images', []); // 支持多张图片
  125. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  126. $videos = getProp($data, 'videos', []); // Gemini 支持视频文件
  127. $videoUrls = getProp($data, 'video_urls', []); // Gemini 支持视频URL
  128. $isGeminiModel = in_array($model, $this->gemini_text_models);
  129. if ((!empty($videos) || !empty($videoUrls)) && !$isGeminiModel) {
  130. Utils::throwError('20003:仅Gemini模型支持视频输入');
  131. }
  132. // 计费预检:纯文生文按 normal 档(3);有参考图/视频输入按模型固定价格(图生文)
  133. $uid = Site::getUid();
  134. $chargeModality = '';
  135. $chargePoints = 0;
  136. $hasImageMedia = !empty($images) || !empty($imageUrls)
  137. || $this->messagesContainMedia($messages, ['image_url', 'image']);
  138. $hasVideoMedia = !empty($videos) || !empty($videoUrls)
  139. || $this->messagesContainMedia($messages, ['video_url', 'video']);
  140. if ($hasImageMedia || $hasVideoMedia) {
  141. $chargeModality = $hasVideoMedia ? 'video' : 'image';
  142. $chargePoints = $this->pointsService->getImageChatChargePoints($model);
  143. } else {
  144. $chargeModality = 'text';
  145. $chargePoints = $this->pointsService->getChatChargePoints('', 'normal');
  146. }
  147. if ($chargePoints > 0) {
  148. $this->pointsService->checkUserPointsEnough($chargePoints, $uid);
  149. }
  150. // 如果没有提供messages,则根据system_prompt、content和images构建
  151. if (empty($messages)) {
  152. $messages = [];
  153. // 添加系统提示词
  154. if (!empty($systemPrompt)) {
  155. $messages[] = [
  156. 'role' => 'system',
  157. 'content' => $systemPrompt
  158. ];
  159. }
  160. // 构建用户消息内容(支持文本+图片)
  161. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  162. $userMessage = [
  163. 'role' => 'user',
  164. 'content' => []
  165. ];
  166. // 添加文本内容
  167. if (!empty($prompt)) {
  168. $userMessage['content'][] = [
  169. 'type' => 'text',
  170. 'text' => $prompt
  171. ];
  172. }
  173. // 处理上传的图片文件
  174. if (!empty($images)) {
  175. if (!is_array($images)) {
  176. $images = [$images];
  177. }
  178. foreach ($images as $image) {
  179. $imageBase64 = $this->processImageToBase64($image);
  180. if ($imageBase64) {
  181. $userMessage['content'][] = [
  182. 'type' => 'image_url',
  183. 'image_url' => [
  184. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  185. ]
  186. ];
  187. }
  188. }
  189. }
  190. // 处理图片URL
  191. if (!empty($imageUrls)) {
  192. if (!is_array($imageUrls)) {
  193. $imageUrls = [$imageUrls];
  194. }
  195. foreach ($imageUrls as $url) {
  196. if (!empty($url)) {
  197. $userMessage['content'][] = [
  198. 'type' => 'image_url',
  199. 'image_url' => [
  200. 'url' => $url
  201. ]
  202. ];
  203. }
  204. }
  205. }
  206. // 处理上传的视频文件(仅 Gemini)
  207. if (!empty($videos) && $isGeminiModel) {
  208. if (!is_array($videos)) {
  209. $videos = [$videos];
  210. }
  211. foreach ($videos as $video) {
  212. $inlineData = $this->processMediaToInlineData($video);
  213. if ($inlineData) {
  214. $userMessage['content'][] = [
  215. 'type' => 'video',
  216. 'inline_data' => $inlineData
  217. ];
  218. }
  219. }
  220. }
  221. // 处理视频URL(仅 Gemini)
  222. if (!empty($videoUrls) && $isGeminiModel) {
  223. if (!is_array($videoUrls)) {
  224. $videoUrls = [$videoUrls];
  225. }
  226. foreach ($videoUrls as $url) {
  227. if (!empty($url)) {
  228. $userMessage['content'][] = [
  229. 'type' => 'video_url',
  230. 'video_url' => ['url' => $url]
  231. ];
  232. }
  233. }
  234. }
  235. // 如果只有文本内容,简化为字符串格式
  236. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  237. $userMessage['content'] = $userMessage['content'][0]['text'];
  238. }
  239. $messages[] = $userMessage;
  240. }
  241. }
  242. // 验证messages不为空
  243. if (empty($messages)) {
  244. Utils::throwError('20003:请提供有效的对话内容');
  245. }
  246. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  247. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  248. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  249. if ($model === 'deepseek-chat') {
  250. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  251. $model = 'deepseek-v4-flash';
  252. $thinkingMode = 'disabled';
  253. } elseif ($model === 'deepseek-reasoner') {
  254. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  255. $model = 'deepseek-v4-flash';
  256. $thinkingMode = 'enabled';
  257. }
  258. // 构建请求参数
  259. $post_data = [
  260. 'model' => $model,
  261. 'messages' => $messages,
  262. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  263. 'temperature' => getProp($data, 'temperature', 1),
  264. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  265. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  266. 'thinking' => ['type' => $thinkingMode],
  267. 'stream' => true // 启用流式输出
  268. ];
  269. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  270. // 添加可选参数
  271. if (isset($data['top_p'])) {
  272. $post_data['top_p'] = $data['top_p'];
  273. }
  274. if (isset($data['response_format'])) {
  275. $post_data['response_format'] = $data['response_format'];
  276. }
  277. // 根据模型类型选择调用方法
  278. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  279. // DeepSeek 官方模型使用 DeepSeek API
  280. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  281. } else if (in_array($model, $this->gpt_text_models)) {
  282. // GPT 模型使用 TokenRouter API
  283. $streamGenerator = $this->gpt54StreamResponse($post_data);
  284. } else if (in_array($model, $this->gemini_text_models)) {
  285. // Gemini 模型使用 Gemini API
  286. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  287. } else if (in_array($model, $this->valid_text_models)) {
  288. // 火山引擎支持的模型使用火山引擎 API
  289. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  290. } else {
  291. Utils::throwError('20003:不支持的模型: ' . $model);
  292. }
  293. if ($chargePoints > 0) {
  294. return $this->wrapGenerateTextCharge($streamGenerator, $uid, $model, $chargePoints, $chargeModality);
  295. }
  296. // 免费场景(0 积分):流式生成成功后仅记录 token 使用明细
  297. return $this->wrapGenerateTextTokenRecord($streamGenerator, $uid, $model);
  298. }
  299. /**
  300. * 流式生成成功后仅记录 token 明细(纯文本免费场景,不扣积分)
  301. *
  302. * @param \Generator $generator
  303. * @param int $uid
  304. * @param string $model
  305. * @return \Generator
  306. */
  307. private function wrapGenerateTextTokenRecord(\Generator $generator, int $uid, string $model, string $source = 'generateText'): \Generator
  308. {
  309. $recorded = false;
  310. foreach ($generator as $chunk) {
  311. if (!$recorded && isset($chunk['type']) && $chunk['type'] === 'done') {
  312. $this->recordTextTokenOnly($uid, $this->pointsService->getTokensFromUsage(getProp($chunk, 'usage', [])), [
  313. 'model' => $model,
  314. 'source' => $source,
  315. ], $model);
  316. $recorded = true;
  317. }
  318. yield $chunk;
  319. }
  320. }
  321. /**
  322. * 流式生成成功后再按档位/模型规则扣费(文生文 normal 档 / 图生文按模型固定价格)
  323. *
  324. * @param \Generator $generator
  325. * @param int $uid
  326. * @param string $model
  327. * @param int $points
  328. * @param string $modality
  329. * @return \Generator
  330. */
  331. private function wrapGenerateTextCharge(\Generator $generator, int $uid, string $model, int $points, string $modality): \Generator
  332. {
  333. $charged = false;
  334. foreach ($generator as $chunk) {
  335. if (!$charged && isset($chunk['type']) && $chunk['type'] === 'done') {
  336. $fullContent = (string)getProp($chunk, 'full_content', getProp($chunk, 'answer', ''));
  337. if ($fullContent !== '') {
  338. $this->chargeMultimodal($uid, $model, $points, $modality, getProp($chunk, 'usage', []));
  339. $charged = true;
  340. }
  341. }
  342. yield $chunk;
  343. }
  344. }
  345. /**
  346. * AI 对话(含图片/视频 -> 文本)成功后扣费并记录积分与 token 明细
  347. *
  348. * @param int $uid
  349. * @param string $model
  350. * @param int $points
  351. * @param string $modality
  352. * @param mixed $usage
  353. * @return void
  354. */
  355. private function chargeMultimodal(int $uid, string $model, int $points, string $modality, $usage): void
  356. {
  357. $result = $this->pointsService->recordChatCharge(
  358. $uid,
  359. $points,
  360. $this->pointsService->getTokensFromUsage($usage),
  361. [
  362. 'model' => $model,
  363. 'modality' => $modality,
  364. 'source' => 'generateText',
  365. ],
  366. '',
  367. $model
  368. );
  369. if (empty($result['charged'])) {
  370. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  371. }
  372. }
  373. /**
  374. * 检查 OpenAI 风格消息中是否包含指定媒体类型
  375. *
  376. * @param array $messages
  377. * @param array $mediaTypes
  378. * @return bool
  379. */
  380. private function messagesContainMedia(array $messages, array $mediaTypes): bool
  381. {
  382. foreach ($messages as $message) {
  383. $content = getProp($message, 'content', '');
  384. if (!is_array($content)) {
  385. continue;
  386. }
  387. foreach ($content as $part) {
  388. if (is_array($part) && in_array(getProp($part, 'type', ''), $mediaTypes, true)) {
  389. return true;
  390. }
  391. }
  392. }
  393. return false;
  394. }
  395. public function createGenerateText($data) {
  396. $file = getProp($data, 'file');
  397. $episode_num = getProp($data, 'episode_num');
  398. $uid = Site::getUid();
  399. $cpid = Site::getCpid();
  400. if (!$file) {
  401. Utils::throwError('20003:请上传文件');
  402. }
  403. // 提取文件内容
  404. $content = $this->extractFileContent($file);
  405. if (!$content) {
  406. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  407. }
  408. // 拆分章节并校验章节总数、标题连续性
  409. if ($episode_num) {
  410. $this->validateGenerateTextChapters($content, (int)$episode_num);
  411. }
  412. // 获取原始文件名(不含扩展名)作为script_name
  413. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  414. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  415. // 字节安全剥离,不依赖服务器locale设置
  416. $originalName = $file->getClientOriginalName();
  417. $extension = $file->getClientOriginalExtension();
  418. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  419. ? substr($originalName, 0, -strlen($extension) - 1)
  420. : $originalName;
  421. if ($script_name === '') {
  422. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  423. }
  424. // 如果同一用户的剧本名存在则提示
  425. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  426. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  427. }
  428. // 插入数据到mp_scripts表
  429. $script_id = DB::table('mp_scripts')->insertGetId([
  430. 'script_name' => $script_name,
  431. 'user_id' => $uid,
  432. 'cpid' => $cpid,
  433. 'content' => $content,
  434. 'created_at' => date('Y-m-d H:i:s'),
  435. 'updated_at' => date('Y-m-d H:i:s')
  436. ]);
  437. return [
  438. 'script_id' => $script_id,
  439. 'script_name' => $script_name
  440. ];
  441. }
  442. /**
  443. * AI对话调用成功后的积分扣费(返回结果前调用)
  444. *
  445. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  446. *
  447. * @param int $uid
  448. * @param int $tokens
  449. * @param array $chargeInfo
  450. * @return void
  451. */
  452. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo, string $chargeType = 'special'): void
  453. {
  454. // api_type 记录真实模型名(缺失时回退 deepseek 大类),保证明细与统计口径准确
  455. $model = (string)getProp($chargeInfo, 'model', '');
  456. $result = $this->pointsService->recordChatCharge(
  457. $uid,
  458. $this->pointsService->getChatChargePoints($model, $chargeType),
  459. $tokens,
  460. $chargeInfo,
  461. '',
  462. $model !== '' ? $model : 'deepseek'
  463. );
  464. if (empty($result['charged'])) {
  465. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  466. }
  467. }
  468. /**
  469. * 安全获取当前登录用户ID
  470. *
  471. * 命令行/队列等无用户上下文的场景返回 0,由记录方法自行跳过。
  472. *
  473. * @return int
  474. */
  475. private function getCurrentUid(): int
  476. {
  477. try {
  478. return (int)Site::getUid();
  479. } catch (\Throwable $e) {
  480. return 0;
  481. }
  482. }
  483. /**
  484. * 记录文生文 token 使用明细(仅记录,不扣积分)
  485. *
  486. * 用于不按积分计费的文生文接口;记录失败不影响主流程。
  487. *
  488. * @param int $uid 用户ID(0 时跳过)
  489. * @param int $tokens 消耗 token 数
  490. * @param array $chargeInfo 计费/来源信息(model、source 等)
  491. * @param string $apiType API 类型/模型标识
  492. * @return void
  493. */
  494. private function recordTextTokenOnly(int $uid, int $tokens, array $chargeInfo, string $apiType = ''): void
  495. {
  496. try {
  497. $this->pointsService->recordTokenOnlyDetail(
  498. $uid,
  499. $tokens,
  500. $chargeInfo,
  501. MpUserPointsDetail::TYPE_CHAT,
  502. $apiType,
  503. ''
  504. );
  505. } catch (\Throwable $e) {
  506. dLog('points')->warning('token明细记录异常(不影响主流程): ' . $e->getMessage(), [
  507. 'uid' => $uid,
  508. 'source' => $chargeInfo['source'] ?? '',
  509. ]);
  510. }
  511. }
  512. /**
  513. * 拆分剧本内容并校验章节总数与标题连续性
  514. *
  515. * @param string $content
  516. * @param int $episodeNum
  517. * @return void
  518. */
  519. private function validateGenerateTextChapters($content, $episodeNum)
  520. {
  521. $chapters = splitContent($content);
  522. if (count($chapters) !== $episodeNum) {
  523. Utils::throwError('20003:章节总数与集数不一致,请检查上传内容');
  524. }
  525. if (empty($chapters)) {
  526. return;
  527. }
  528. // 先尝试从标题正则中解析序号,确认是否从1开始连续递增
  529. $numbers = [];
  530. $unparsedIndex = null;
  531. foreach ($chapters as $index => $chapter) {
  532. $num = $this->parseChapterNumber($chapter['title']);
  533. if ($num === null) {
  534. $unparsedIndex = $index;
  535. break;
  536. }
  537. $numbers[] = $num;
  538. }
  539. if ($unparsedIndex === null) {
  540. $expected = 1;
  541. foreach ($numbers as $index => $num) {
  542. if ($num !== $expected) {
  543. $title = mb_substr(trim((string)$chapters[$index]['title']), 0, 40);
  544. Utils::throwError('20003:章节序号不连续:第' . ($index + 1) . '个章节“' . $title . '”序号为' . $num . ',预期为' . $expected);
  545. }
  546. $expected++;
  547. }
  548. return;
  549. }
  550. // 标题格式无法用正则确认时,交给模型分析
  551. $titles = array_column($chapters, 'title');
  552. $aiResult = $this->validateChapterSequenceByAI($titles);
  553. if ($aiResult['valid'] === false) {
  554. $badIndex = $aiResult['invalid_index'] ?: $unparsedIndex + 1;
  555. if (isset($chapters[$badIndex - 1])) {
  556. $title = mb_substr(trim((string)$chapters[$badIndex - 1]['title']), 0, 40);
  557. Utils::throwError('20003:章节序号不连续:第' . $badIndex . '个章节“' . $title . '”序号异常,请检查');
  558. }
  559. Utils::throwError('20003:章节序号不连续,请检查章节标题格式');
  560. }
  561. if ($aiResult['valid'] === null) {
  562. if (isset($chapters[$unparsedIndex])) {
  563. $title = mb_substr(trim((string)$chapters[$unparsedIndex]['title']), 0, 40);
  564. Utils::throwError('20003:无法确认第' . ($unparsedIndex + 1) . '个章节“' . $title . '”的章节序号,请检查标题格式');
  565. }
  566. Utils::throwError('20003:无法确认章节标题连续性,请检查章节标题格式');
  567. }
  568. }
  569. /**
  570. * 从章节标题中解析序号,支持阿拉伯数字和中文数字
  571. *
  572. * @param string $title
  573. * @return int|null
  574. */
  575. private function parseChapterNumber($title)
  576. {
  577. if (!preg_match('/第\s*([一二两三四五六七八九十百千万0-9]+)\s*[章节集幕场回话]/u', $title, $match)) {
  578. return null;
  579. }
  580. return $this->convertChineseNumber($match[1]);
  581. }
  582. /**
  583. * 中文数字转阿拉伯数字(支持到千)
  584. *
  585. * @param string $numStr
  586. * @return int
  587. */
  588. private function convertChineseNumber($numStr)
  589. {
  590. if (preg_match('/^\d+$/', $numStr)) {
  591. return (int)$numStr;
  592. }
  593. $map = [
  594. '零' => 0,
  595. '一' => 1,
  596. '二' => 2,
  597. '两' => 2,
  598. '三' => 3,
  599. '四' => 4,
  600. '五' => 5,
  601. '六' => 6,
  602. '七' => 7,
  603. '八' => 8,
  604. '九' => 9
  605. ];
  606. $total = 0;
  607. $section = 0;
  608. $length = mb_strlen($numStr);
  609. for ($i = 0; $i < $length; $i++) {
  610. $char = mb_substr($numStr, $i, 1);
  611. if (isset($map[$char])) {
  612. $section = $map[$char];
  613. } elseif ($char === '十') {
  614. $total += $section === 0 ? 10 : $section * 10;
  615. $section = 0;
  616. } elseif ($char === '百') {
  617. $total += $section === 0 ? 100 : $section * 100;
  618. $section = 0;
  619. } elseif ($char === '千') {
  620. $total += $section === 0 ? 1000 : $section * 1000;
  621. $section = 0;
  622. }
  623. }
  624. return $total + $section;
  625. }
  626. /**
  627. * 用 deepseek-v4-flash 非流式判断章节标题是否从1开始连续编号
  628. *
  629. * @param array $titles
  630. * @return array{valid: bool|null, invalid_index: int|null}
  631. */
  632. private function validateChapterSequenceByAI($titles)
  633. {
  634. $titleLines = [];
  635. foreach (array_slice($titles, 0, 200) as $index => $title) {
  636. $titleLines[] = ($index + 1) . '. ' . mb_substr(trim((string)$title), 0, 80);
  637. }
  638. $result = [
  639. 'valid' => null,
  640. 'invalid_index' => null
  641. ];
  642. $post_data = [
  643. 'model' => 'deepseek-v4-flash',
  644. 'messages' => [
  645. [
  646. 'role' => 'system',
  647. 'content' => '你是剧本章节校验助手。用户会给出章节标题列表,请判断这些标题中的编号是否从第1章/第1集开始连续递增,支持阿拉伯数字和中文数字。只输出 JSON,格式为 {"valid":true};若不连续则输出 {"valid":false,"invalid_index":N},其中 N 是第一个序号异常的章节序号(从1开始),不要输出其他内容。',
  648. ],
  649. [
  650. 'role' => 'user',
  651. 'content' => implode("\n", $titleLines),
  652. ],
  653. ],
  654. 'temperature' => 0,
  655. 'frequency_penalty' => 0,
  656. 'presence_penalty' => 0,
  657. 'stream' => false,
  658. ];
  659. try {
  660. $result = $this->chatOnly($post_data, 8);
  661. $content = trim((string)($result['fullContent'] ?? ''));
  662. if (preg_match('/"valid"\s*:\s*(true|false)/i', $content, $match)) {
  663. $result['valid'] = strtolower($match[1]) === 'true';
  664. }
  665. if (preg_match('/"invalid_index"\s*:\s*(\d+)/i', $content, $match)) {
  666. $result['invalid_index'] = (int)$match[1];
  667. }
  668. // 仅记录 token 使用明细(不扣积分):该校验为流程内的额外模型调用
  669. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  670. 'model' => 'deepseek-v4-flash',
  671. 'source' => 'validateChapterSequenceByAI',
  672. ], 'deepseek-v4-flash');
  673. } catch (\Exception $e) {
  674. dLog('deepseek')->error('章节连续性AI校验失败: ' . $e->getMessage());
  675. }
  676. return $result;
  677. }
  678. /**
  679. * 通用文生文(流式版本)- newGenerateText 的 stream=1 分支
  680. * 支持与 newGenerateText 相同的参数(模板/剧本/JSON输出/图片输入),
  681. * 输出格式与 generateText 一致:yield type=content / reasoning / done
  682. *
  683. * @param array $data 请求参数
  684. * @return \Generator
  685. */
  686. public function newGenerateTextStream($data) {
  687. $model = getProp($data, 'model', 'deepseek-v4-pro');
  688. $messages = getProp($data, 'messages', []);
  689. $systemPrompt = getProp($data, 'system_prompt', '');
  690. $prompt = getProp($data, 'prompt', '');
  691. $images = getProp($data, 'images', []);
  692. $imageUrls = getProp($data, 'image_urls', []);
  693. $responseFormat = getProp($data, 'response_format', 'text');
  694. $templateId = getProp($data, 'template_id', 0);
  695. $script_id = getProp($data, 'script_id', 0);
  696. $sequence = getProp($data, 'sequence', 0);
  697. $generateTaskId = 0;
  698. $uid = Site::getUid();
  699. if ($script_id > 0) {
  700. $existingTask = DB::table('mp_script_generate_tasks')
  701. ->where('uid', $uid)
  702. ->where('script_id', $script_id)
  703. ->orderByDesc('id')
  704. ->first();
  705. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  706. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  707. }
  708. }
  709. // 如果提供了script_id,从数据库获取剧本内容作为原文
  710. $originalContent = '';
  711. $hasValidScript = false;
  712. $rawPrompt = $prompt; // 保存用户原始输入,供模板一致性判断
  713. if ($script_id > 0) {
  714. $script = DB::table('mp_scripts')
  715. ->where('id', $script_id)
  716. ->where('is_deleted', 0)
  717. ->first();
  718. if (!$script) {
  719. Utils::throwError('20003:剧本不存在或已删除');
  720. }
  721. $originalContent = $script->content ?? '';
  722. if (empty($originalContent)) {
  723. Utils::throwError('20003:剧本内容为空');
  724. }
  725. $hasValidScript = true;
  726. if (!empty($prompt)) {
  727. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  728. } else {
  729. $prompt = "原文内容:\n" . $originalContent;
  730. }
  731. }
  732. // 如果提供了template_id,从数据库获取template_prompt
  733. if ($templateId > 0) {
  734. $template = DB::table('mp_prompt_templates')
  735. ->where('id', $templateId)
  736. ->where('is_deleted', 0)
  737. ->first();
  738. if (!$template) {
  739. Utils::throwError('20003:模板不存在或已删除');
  740. }
  741. $templatePrompt = $template->template_prompt ?? '';
  742. if (!empty($templatePrompt)) {
  743. // 模板提示词与用户输入基本一致时只保留一个,避免重复提示词
  744. // 剧本模式下当前 prompt 含原文内容需保留,其余情况以模板内容为准
  745. $trimmedRawPrompt = trim((string)$rawPrompt);
  746. if ($trimmedRawPrompt !== '' && mb_strtolower($trimmedRawPrompt) === mb_strtolower(trim($templatePrompt))) {
  747. if (!$hasValidScript) {
  748. $prompt = $templatePrompt;
  749. }
  750. } elseif (!empty($prompt)) {
  751. $prompt = $templatePrompt . "\n\n" . $prompt;
  752. } else {
  753. $prompt = $templatePrompt;
  754. }
  755. }
  756. }
  757. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  758. if (empty($messages)) {
  759. $messages = [];
  760. if (!empty($systemPrompt)) {
  761. $messages[] = [
  762. 'role' => 'system',
  763. 'content' => $systemPrompt
  764. ];
  765. }
  766. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  767. $userMessage = [
  768. 'role' => 'user',
  769. 'content' => []
  770. ];
  771. if (!empty($prompt)) {
  772. $userMessage['content'][] = [
  773. 'type' => 'text',
  774. 'text' => $prompt
  775. ];
  776. }
  777. if (!empty($images)) {
  778. if (!is_array($images)) {
  779. $images = [$images];
  780. }
  781. foreach ($images as $image) {
  782. $imageBase64 = $this->processImageToBase64($image);
  783. if ($imageBase64) {
  784. $userMessage['content'][] = [
  785. 'type' => 'image_url',
  786. 'image_url' => [
  787. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  788. ]
  789. ];
  790. }
  791. }
  792. }
  793. if (!empty($imageUrls)) {
  794. if (!is_array($imageUrls)) {
  795. $imageUrls = [$imageUrls];
  796. }
  797. foreach ($imageUrls as $url) {
  798. if (!empty($url)) {
  799. $userMessage['content'][] = [
  800. 'type' => 'image_url',
  801. 'image_url' => [
  802. 'url' => $url
  803. ]
  804. ];
  805. }
  806. }
  807. }
  808. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  809. $userMessage['content'] = $userMessage['content'][0]['text'];
  810. }
  811. $messages[] = $userMessage;
  812. }
  813. }
  814. if (empty($messages)) {
  815. Utils::throwError('20003:请提供有效的对话内容');
  816. }
  817. // 模型兼容性处理
  818. $thinkingMode = getProp($data, 'thinking', 'disabled');
  819. $reasoningEffort = getProp($data, 'reasoning_effort', 'high');
  820. if ($model === 'deepseek-chat') {
  821. $model = 'deepseek-v4-flash';
  822. $thinkingMode = 'disabled';
  823. } elseif ($model === 'deepseek-reasoner') {
  824. $model = 'deepseek-v4-flash';
  825. $thinkingMode = 'enabled';
  826. }
  827. // 构建请求参数(流式)
  828. $post_data = [
  829. 'model' => $model,
  830. 'messages' => $messages,
  831. 'temperature' => getProp($data, 'temperature', 1),
  832. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  833. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  834. 'thinking' => ['type' => $thinkingMode],
  835. 'stream' => true
  836. ];
  837. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  838. if (isset($data['top_p'])) {
  839. $post_data['top_p'] = $data['top_p'];
  840. }
  841. // response_format=json 时附加 JSON 说明与响应格式(与 newGenerateText 一致)
  842. if ($responseFormat === 'json') {
  843. $hasJsonKeyword = false;
  844. foreach ($post_data['messages'] as $message) {
  845. if (isset($message['content'])) {
  846. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  847. if (stripos($content, 'json') !== false) {
  848. $hasJsonKeyword = true;
  849. break;
  850. }
  851. }
  852. }
  853. if (!$hasJsonKeyword) {
  854. $lastMessageIndex = count($post_data['messages']) - 1;
  855. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  856. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  857. if (is_string($lastContent)) {
  858. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  859. } elseif (is_array($lastContent)) {
  860. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  861. if ($contentPart['type'] === 'text') {
  862. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  863. break;
  864. }
  865. }
  866. }
  867. }
  868. }
  869. $post_data['response_format'] = ['type' => 'json_object'];
  870. }
  871. // 如果提供了script_id,创建剧本资产生成任务
  872. if ($script_id > 0) {
  873. $uid = Site::getUid();
  874. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  875. 'uid' => $uid,
  876. 'script_id' => $script_id,
  877. 'sequence' => $sequence,
  878. 'status' => 'processing',
  879. 'prompt' => getProp($data, 'prompt', ''),
  880. 'started_at' => date('Y-m-d H:i:s'),
  881. 'created_at' => date('Y-m-d H:i:s'),
  882. 'updated_at' => date('Y-m-d H:i:s')
  883. ]);
  884. }
  885. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  886. if ($hasValidScript) {
  887. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  888. }
  889. // 根据模型类型选择流式调用方法
  890. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  891. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  892. } elseif (in_array($model, $this->gpt_text_models)) {
  893. $streamGenerator = $this->gpt54StreamResponse($post_data);
  894. } elseif (in_array($model, $this->gemini_text_models)) {
  895. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  896. } elseif (in_array($model, $this->valid_text_models)) {
  897. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  898. } else {
  899. Utils::throwError('20003:不支持的模型: ' . $model);
  900. }
  901. // 流式输出包装:done 时更新任务状态、扣费并保存对话记录
  902. return $this->wrapNewGenerateTextStream($streamGenerator, [
  903. 'uid' => $uid,
  904. 'model' => $model,
  905. 'generate_task_id' => $generateTaskId,
  906. 'has_valid_script' => $hasValidScript,
  907. 'script_id' => $script_id,
  908. 'sequence' => $sequence,
  909. 'original_prompt' => getProp($data, 'prompt', ''),
  910. 'response_format' => $responseFormat,
  911. ]);
  912. }
  913. /**
  914. * 流式生成收尾包装:done 时更新剧本资产生成任务、扣除积分并保存对话记录
  915. *
  916. * @param \Generator $generator
  917. * @param array $ctx
  918. * @return \Generator
  919. */
  920. private function wrapNewGenerateTextStream(\Generator $generator, array $ctx): \Generator
  921. {
  922. $fullContent = '';
  923. $usage = [];
  924. $finished = false;
  925. try {
  926. foreach ($generator as $chunk) {
  927. if (isset($chunk['type']) && $chunk['type'] === 'content') {
  928. $fullContent .= (string)getProp($chunk, 'content', '');
  929. }
  930. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  931. $fullContent = (string)getProp($chunk, 'full_content', $fullContent);
  932. $usage = getProp($chunk, 'usage', []);
  933. // 流式场景下部分模型/中转站不强制 JSON 输出,兜底提取标准 JSON
  934. if (($ctx['response_format'] ?? 'text') === 'json') {
  935. $fullContent = $this->extractJsonContent($fullContent);
  936. }
  937. $finished = true;
  938. // 保存对话记录并将 records 附加到 done 消息(无论 script_id 是否有值都返回 records 数组)
  939. $chunk['records'] = [];
  940. if (!empty($ctx['script_id'])) {
  941. try {
  942. $now = now();
  943. DB::table('mp_script_records')->insert([
  944. [
  945. 'uid' => $ctx['uid'],
  946. 'script_id' => $ctx['script_id'],
  947. 'sequence' => $ctx['sequence'],
  948. 'role' => 'user',
  949. 'content' => $ctx['original_prompt'],
  950. 'created_at' => $now,
  951. 'updated_at' => $now,
  952. ],
  953. [
  954. 'uid' => $ctx['uid'],
  955. 'script_id' => $ctx['script_id'],
  956. 'sequence' => $ctx['sequence'],
  957. 'role' => 'assistant',
  958. 'content' => $fullContent,
  959. 'created_at' => $now,
  960. 'updated_at' => $now,
  961. ],
  962. ]);
  963. $chunk['records'] = DB::table('mp_script_records')
  964. ->where('uid', $ctx['uid'])
  965. ->where('script_id', $ctx['script_id'])
  966. ->where('sequence', $ctx['sequence'])
  967. ->orderBy('id', 'desc')
  968. ->limit(2)
  969. ->get()
  970. ->map(function ($record) {
  971. return [
  972. 'rid' => $record->id,
  973. 'script_id' => $record->script_id,
  974. 'sequence' => $record->sequence,
  975. 'role' => $record->role,
  976. 'content' => $record->content,
  977. 'created_at' => $record->created_at,
  978. ];
  979. })
  980. ->reverse()
  981. ->values()
  982. ->toArray();
  983. } catch (\Exception $e) {
  984. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  985. $chunk['records'] = [];
  986. }
  987. }
  988. }
  989. yield $chunk;
  990. }
  991. if ($finished) {
  992. if (!empty($ctx['generate_task_id'])) {
  993. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  994. 'status' => 'success',
  995. 'result' => $fullContent,
  996. 'completed_at' => date('Y-m-d H:i:s'),
  997. 'updated_at' => date('Y-m-d H:i:s'),
  998. ]);
  999. }
  1000. if ($ctx['has_valid_script'] && $fullContent !== '') {
  1001. $this->chargeChatSuccess($ctx['uid'], $this->pointsService->getTokensFromUsage($usage), [
  1002. 'model' => $ctx['model'],
  1003. 'script_id' => $ctx['script_id'],
  1004. 'sequence' => $ctx['sequence'],
  1005. 'source' => 'newGenerateText',
  1006. ]);
  1007. }
  1008. }
  1009. } catch (\Throwable $e) {
  1010. if (!empty($ctx['generate_task_id'])) {
  1011. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  1012. 'status' => 'failed',
  1013. 'error_message' => $e->getMessage(),
  1014. 'completed_at' => date('Y-m-d H:i:s'),
  1015. 'updated_at' => date('Y-m-d H:i:s'),
  1016. ]);
  1017. }
  1018. yield [
  1019. 'type' => 'error',
  1020. 'message' => $e->getMessage(),
  1021. ];
  1022. }
  1023. }
  1024. /**
  1025. * 从模型输出中提取标准 JSON(剥离 markdown 代码块及前后说明文字)
  1026. *
  1027. * @param string $content
  1028. * @return string
  1029. */
  1030. private function extractJsonContent(string $content): string
  1031. {
  1032. $content = trim($content);
  1033. if ($content === '') {
  1034. return $content;
  1035. }
  1036. // 剥离 ```json ... ``` 代码块
  1037. if (preg_match('/```(?:json)?\s*(.*?)```/s', $content, $m)) {
  1038. $content = trim($m[1]);
  1039. }
  1040. // 提取第一个 { 到最后一个 } 之间的内容(去除前后说明文字)
  1041. $first = strpos($content, '{');
  1042. $last = strrpos($content, '}');
  1043. if ($first !== false && $last !== false && $last > $first) {
  1044. $content = substr($content, $first, $last - $first + 1);
  1045. }
  1046. // 校验是否为合法 JSON,非法则原样返回(不强行截断)
  1047. json_decode($content, true);
  1048. if (json_last_error() !== JSON_ERROR_NONE) {
  1049. return trim($content);
  1050. }
  1051. return $content;
  1052. }
  1053. /**
  1054. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  1055. *
  1056. * @param array $data 请求参数
  1057. * @return array 返回结果数组
  1058. */
  1059. public function newGenerateText($data) {
  1060. // stream=1 时改为流式请求大模型(输出格式参考 generateText:yield type=content/reasoning/done)
  1061. if ((int)getProp($data, 'stream', 0) === 1) {
  1062. return $this->newGenerateTextStream($data);
  1063. }
  1064. // 获取请求参数
  1065. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  1066. $messages = getProp($data, 'messages', []);
  1067. $systemPrompt = getProp($data, 'system_prompt', '');
  1068. $prompt = getProp($data, 'prompt', '');
  1069. $images = getProp($data, 'images', []); // 支持多张图片
  1070. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  1071. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  1072. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  1073. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  1074. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  1075. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  1076. $generateTaskId = 0;
  1077. $uid = Site::getUid();
  1078. if ($script_id > 0) {
  1079. $existingTask = DB::table('mp_script_generate_tasks')
  1080. ->where('uid', $uid)
  1081. ->where('script_id', $script_id)
  1082. ->orderByDesc('id')
  1083. ->first();
  1084. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  1085. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  1086. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  1087. }
  1088. }
  1089. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  1090. $originalContent = '';
  1091. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  1092. $rawPrompt = $prompt; // 保存用户原始输入,供模板一致性判断
  1093. if ($script_id > 0) {
  1094. $script = DB::table('mp_scripts')
  1095. ->where('id', $script_id)
  1096. ->where('is_deleted', 0)
  1097. ->first();
  1098. if (!$script) {
  1099. Utils::throwError('20003:剧本不存在或已删除');
  1100. }
  1101. $originalContent = $script->content ?? '';
  1102. if (empty($originalContent)) {
  1103. Utils::throwError('20003:剧本内容为空');
  1104. }
  1105. $hasValidScript = true;
  1106. // 将剧本内容添加到提示词前面
  1107. if (!empty($originalContent)) {
  1108. if (!empty($prompt)) {
  1109. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  1110. } else {
  1111. $prompt = "原文内容:\n" . $originalContent;
  1112. }
  1113. }
  1114. }
  1115. // 新增: 如果提供了template_id,从数据库获取template_prompt
  1116. if ($templateId > 0) {
  1117. $template = DB::table('mp_prompt_templates')
  1118. ->where('id', $templateId)
  1119. ->where('is_deleted', 0)
  1120. ->first();
  1121. if (!$template) {
  1122. Utils::throwError('20003:模板不存在或已删除');
  1123. }
  1124. $templatePrompt = $template->template_prompt ?? '';
  1125. // 将模板提示词和用户输入的prompt组合
  1126. // 模板为准,用户输入作为补充要求
  1127. // 模板提示词与用户输入基本一致时只保留一个,避免重复提示词
  1128. // 剧本模式下当前 prompt 含原文内容需保留,其余情况以模板内容为准
  1129. if (!empty($templatePrompt)) {
  1130. $trimmedRawPrompt = trim((string)$rawPrompt);
  1131. if ($trimmedRawPrompt !== '' && mb_strtolower($trimmedRawPrompt) === mb_strtolower(trim($templatePrompt))) {
  1132. if (!$hasValidScript) {
  1133. $prompt = $templatePrompt;
  1134. }
  1135. } elseif (!empty($prompt)) {
  1136. $prompt = $templatePrompt . "\n\n" . $prompt;
  1137. } else {
  1138. $prompt = $templatePrompt;
  1139. }
  1140. }
  1141. }
  1142. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  1143. if (empty($messages)) {
  1144. $messages = [];
  1145. // 添加系统提示词
  1146. if (!empty($systemPrompt)) {
  1147. $messages[] = [
  1148. 'role' => 'system',
  1149. 'content' => $systemPrompt
  1150. ];
  1151. }
  1152. // 构建用户消息内容(支持文本+图片)
  1153. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1154. $userMessage = [
  1155. 'role' => 'user',
  1156. 'content' => []
  1157. ];
  1158. // 添加文本内容
  1159. if (!empty($prompt)) {
  1160. $userMessage['content'][] = [
  1161. 'type' => 'text',
  1162. 'text' => $prompt
  1163. ];
  1164. }
  1165. // 处理上传的图片文件
  1166. if (!empty($images)) {
  1167. if (!is_array($images)) {
  1168. $images = [$images];
  1169. }
  1170. foreach ($images as $image) {
  1171. $imageBase64 = $this->processImageToBase64($image);
  1172. if ($imageBase64) {
  1173. $userMessage['content'][] = [
  1174. 'type' => 'image_url',
  1175. 'image_url' => [
  1176. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  1177. ]
  1178. ];
  1179. }
  1180. }
  1181. }
  1182. // 处理图片URL
  1183. if (!empty($imageUrls)) {
  1184. if (!is_array($imageUrls)) {
  1185. $imageUrls = [$imageUrls];
  1186. }
  1187. foreach ($imageUrls as $url) {
  1188. if (!empty($url)) {
  1189. $userMessage['content'][] = [
  1190. 'type' => 'image_url',
  1191. 'image_url' => [
  1192. 'url' => $url
  1193. ]
  1194. ];
  1195. }
  1196. }
  1197. }
  1198. // 如果只有文本内容,简化为字符串格式
  1199. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  1200. $userMessage['content'] = $userMessage['content'][0]['text'];
  1201. }
  1202. $messages[] = $userMessage;
  1203. }
  1204. }
  1205. // 验证messages不为空
  1206. if (empty($messages)) {
  1207. Utils::throwError('20003:请提供有效的对话内容');
  1208. }
  1209. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1210. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1211. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1212. if ($model === 'deepseek-chat') {
  1213. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1214. $model = 'deepseek-v4-flash';
  1215. $thinkingMode = 'disabled';
  1216. } elseif ($model === 'deepseek-reasoner') {
  1217. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1218. $model = 'deepseek-v4-flash';
  1219. $thinkingMode = 'enabled';
  1220. }
  1221. // 构建请求参数(非流式)
  1222. $post_data = [
  1223. 'model' => $model,
  1224. 'messages' => $messages,
  1225. 'temperature' => getProp($data, 'temperature', 1),
  1226. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  1227. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  1228. 'thinking' => ['type' => $thinkingMode],
  1229. 'stream' => false // 非流式输出
  1230. ];
  1231. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1232. // 添加可选参数
  1233. if (isset($data['top_p'])) {
  1234. $post_data['top_p'] = $data['top_p'];
  1235. }
  1236. // 新增: 根据response_format设置响应格式
  1237. if ($responseFormat === 'json') {
  1238. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  1239. $hasJsonKeyword = false;
  1240. foreach ($post_data['messages'] as $message) {
  1241. if (isset($message['content'])) {
  1242. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  1243. if (stripos($content, 'json') !== false) {
  1244. $hasJsonKeyword = true;
  1245. break;
  1246. }
  1247. }
  1248. }
  1249. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  1250. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  1251. if (!$hasJsonKeyword) {
  1252. $lastMessageIndex = count($post_data['messages']) - 1;
  1253. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  1254. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  1255. // 如果content是字符串,直接追加
  1256. if (is_string($lastContent)) {
  1257. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  1258. }
  1259. // 如果content是数组(包含文本和图片),在文本部分追加
  1260. else if (is_array($lastContent)) {
  1261. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  1262. if ($contentPart['type'] === 'text') {
  1263. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  1264. break;
  1265. }
  1266. }
  1267. }
  1268. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  1269. }
  1270. }
  1271. // 设置response_format参数(所有支持的模型)
  1272. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1273. // DeepSeek模型
  1274. $post_data['response_format'] = ['type' => 'json_object'];
  1275. } else if (in_array($model, $this->gpt_text_models)) {
  1276. // GPT模型
  1277. $post_data['response_format'] = ['type' => 'json_object'];
  1278. } else if (in_array($model, $this->valid_text_models)) {
  1279. // 火山引擎模型
  1280. $post_data['response_format'] = ['type' => 'json_object'];
  1281. }
  1282. }
  1283. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  1284. if ($script_id > 0) {
  1285. $uid = Site::getUid();
  1286. // 创建新的生成任务
  1287. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  1288. 'uid' => $uid,
  1289. 'script_id' => $script_id,
  1290. 'sequence' => $sequence,
  1291. 'status' => 'processing',
  1292. 'prompt' => getProp($data, 'prompt', ''),
  1293. 'started_at' => date('Y-m-d H:i:s'),
  1294. 'created_at' => date('Y-m-d H:i:s'),
  1295. 'updated_at' => date('Y-m-d H:i:s')
  1296. ]);
  1297. }
  1298. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  1299. if ($hasValidScript) {
  1300. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  1301. }
  1302. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  1303. try {
  1304. $aiResult = null;
  1305. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1306. // DeepSeek 官方模型使用现有的 chatOnly 方法
  1307. $result = $this->chatOnly($post_data);
  1308. // 记录实际使用的模型
  1309. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  1310. $aiResult = [
  1311. 'content' => $result['fullContent'],
  1312. 'reasoning_content' => $result['fullReasoningContent'],
  1313. 'usage' => $result['usage'],
  1314. 'model' => $model,
  1315. 'finish_reason' => 'stop'
  1316. ];
  1317. } else if (in_array($model, $this->gpt_text_models)) {
  1318. // GPT 模型使用现有的 gpt54ChatOnly 方法
  1319. $result = $this->gpt54ChatOnly($post_data);
  1320. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  1321. $aiResult = [
  1322. 'content' => $result['fullContent'],
  1323. 'reasoning_content' => '',
  1324. 'usage' => $result['usage'],
  1325. 'model' => $model,
  1326. 'finish_reason' => 'stop'
  1327. ];
  1328. } else if (in_array($model, $this->gemini_text_models)) {
  1329. // Gemini 模型使用 Gemini API(非流式)
  1330. $result = $this->geminiChatOnly($post_data, $model);
  1331. dLog('deepseek')->info('newGenerateText使用Gemini模型', ['requested_model' => $model]);
  1332. $aiResult = [
  1333. 'content' => $result['fullContent'],
  1334. 'reasoning_content' => $result['fullReasoningContent'] ?? '',
  1335. 'usage' => $result['usage'],
  1336. 'model' => $model,
  1337. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  1338. ];
  1339. } else if (in_array($model, $this->valid_text_models)) {
  1340. // 火山引擎支持的模型使用火山引擎 API(非流式)
  1341. $post_data['stream'] = false;
  1342. $result = $this->volcEngineChatCompletion($post_data);
  1343. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  1344. 'requested_model' => $model,
  1345. 'result_keys' => array_keys($result),
  1346. 'has_fullContent' => isset($result['fullContent']),
  1347. 'has_content' => isset($result['content'])
  1348. ]);
  1349. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  1350. $aiResult = [
  1351. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  1352. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  1353. 'usage' => $result['usage'] ?? [],
  1354. 'model' => $model,
  1355. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  1356. ];
  1357. } else {
  1358. Utils::throwError('20003:不支持的模型: ' . $model);
  1359. }
  1360. } catch (\Exception $e) {
  1361. // 生成失败,更新任务状态
  1362. if ($generateTaskId) {
  1363. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1364. 'status' => 'failed',
  1365. 'error_message' => $e->getMessage(),
  1366. 'completed_at' => date('Y-m-d H:i:s'),
  1367. 'updated_at' => date('Y-m-d H:i:s')
  1368. ]);
  1369. }
  1370. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  1371. }
  1372. // 生成成功,更新任务状态
  1373. if ($generateTaskId && $aiResult) {
  1374. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1375. 'status' => 'success',
  1376. 'result' => getProp($aiResult, 'content', ''),
  1377. 'completed_at' => date('Y-m-d H:i:s'),
  1378. 'updated_at' => date('Y-m-d H:i:s')
  1379. ]);
  1380. $aiResult['generate_task_id'] = $generateTaskId;
  1381. }
  1382. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  1383. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  1384. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  1385. 'model' => $model,
  1386. 'script_id' => $script_id,
  1387. 'sequence' => $sequence,
  1388. 'source' => 'newGenerateText',
  1389. ]);
  1390. }
  1391. // 新增: 如果提供了script_id,保存对话记录
  1392. if ($script_id > 0 && $aiResult) {
  1393. try {
  1394. $uid = Site::getUid();
  1395. $now = now();
  1396. // 获取用户原始的prompt(不包含剧本内容)
  1397. $originalPrompt = getProp($data, 'prompt', '');
  1398. $recordsToInsert = [
  1399. [
  1400. 'uid' => $uid,
  1401. 'script_id' => $script_id,
  1402. 'sequence' => $sequence,
  1403. 'role' => 'user',
  1404. 'content' => $originalPrompt,
  1405. 'created_at' => $now,
  1406. 'updated_at' => $now,
  1407. ],
  1408. [
  1409. 'uid' => $uid,
  1410. 'script_id' => $script_id,
  1411. 'sequence' => $sequence,
  1412. 'role' => 'assistant',
  1413. 'content' => $aiResult['content'],
  1414. 'created_at' => $now,
  1415. 'updated_at' => $now,
  1416. ]
  1417. ];
  1418. DB::table('mp_script_records')->insert($recordsToInsert);
  1419. // 获取刚插入的记录ID(假设按插入顺序返回)
  1420. $insertedRecords = DB::table('mp_script_records')
  1421. ->where('uid', $uid)
  1422. ->where('script_id', $script_id)
  1423. ->where('sequence', $sequence)
  1424. ->orderBy('id', 'desc')
  1425. ->limit(2)
  1426. ->get()
  1427. ->map(function ($record) {
  1428. return [
  1429. 'rid' => $record->id,
  1430. 'script_id' => $record->script_id,
  1431. 'sequence' => $record->sequence,
  1432. 'role' => $record->role,
  1433. 'content' => $record->content,
  1434. 'created_at' => $record->created_at,
  1435. ];
  1436. })
  1437. ->reverse()
  1438. ->values()
  1439. ->toArray();
  1440. // 将记录信息添加到返回结果中
  1441. $aiResult['records'] = $insertedRecords;
  1442. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  1443. } catch (\Exception $e) {
  1444. // 记录错误但不影响主流程
  1445. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  1446. }
  1447. }
  1448. // 未提供 script_id 或保存失败时,也返回 records 数组(保持返回结构一致)
  1449. if (!isset($aiResult['records'])) {
  1450. $aiResult['records'] = [];
  1451. }
  1452. return $aiResult;
  1453. }
  1454. /**
  1455. * 通用 Gemini 文生文方法(支持流式和非流式)
  1456. *
  1457. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  1458. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  1459. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  1460. * system_prompt 系统提示词(可选)
  1461. * prompt 用户提示词(可选)
  1462. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  1463. * image_urls 图片/视频URL列表(可选,同上)
  1464. * temperature 温度(可选,默认 1)
  1465. * top_p 核采样(可选)
  1466. * max_tokens 最大输出 token(可选,默认 8192)
  1467. * response_format text/json(可选)
  1468. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  1469. * thinking_budget 思考预算(可选,默认 20)
  1470. * stream 是否流式(可选,默认 false)
  1471. *
  1472. * @param array $data 请求参数
  1473. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  1474. */
  1475. public function geminiGenerateText($data) {
  1476. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  1477. $isStream = (bool)getProp($data, 'stream', false);
  1478. if (!in_array($model, $this->gemini_text_models)) {
  1479. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  1480. }
  1481. $requestData = $this->buildGeminiRequestBody($data, $model);
  1482. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  1483. if ($isStream) {
  1484. // 流式返回生成器,成功后记录 token 使用明细(不扣积分)
  1485. return $this->wrapGenerateTextTokenRecord(
  1486. $this->geminiStreamResponse($requestData, $model),
  1487. $this->getCurrentUid(),
  1488. $model,
  1489. 'geminiGenerateText'
  1490. );
  1491. }
  1492. // 非流式:成功后记录 token 使用明细(不扣积分)
  1493. $result = $this->geminiChatOnly($requestData, $model);
  1494. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  1495. 'model' => $model,
  1496. 'source' => 'geminiGenerateText',
  1497. ], $model);
  1498. return $result;
  1499. }
  1500. /**
  1501. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  1502. */
  1503. private function geminiMediaMaxBytes() {
  1504. return 14 * 1024 * 1024;
  1505. }
  1506. /**
  1507. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  1508. */
  1509. private function buildGeminiRequestBody($data, $model) {
  1510. $messages = getProp($data, 'messages', []);
  1511. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  1512. if (empty($messages)) {
  1513. $systemPrompt = getProp($data, 'system_prompt', '');
  1514. $prompt = getProp($data, 'prompt', '');
  1515. $images = getProp($data, 'images', []);
  1516. $imageUrls = getProp($data, 'image_urls', []);
  1517. $messages = [];
  1518. if (!empty($systemPrompt)) {
  1519. $messages[] = [
  1520. 'role' => 'system',
  1521. 'content' => $systemPrompt
  1522. ];
  1523. }
  1524. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1525. $userMessage = ['role' => 'user', 'content' => []];
  1526. if (!empty($prompt)) {
  1527. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  1528. }
  1529. if (!empty($images)) {
  1530. if (!is_array($images)) {
  1531. $images = [$images];
  1532. }
  1533. foreach ($images as $image) {
  1534. $inlineData = $this->processMediaToInlineData($image);
  1535. if ($inlineData) {
  1536. $userMessage['content'][] = [
  1537. 'type' => 'image',
  1538. 'inline_data' => $inlineData
  1539. ];
  1540. }
  1541. }
  1542. }
  1543. if (!empty($imageUrls)) {
  1544. if (!is_array($imageUrls)) {
  1545. $imageUrls = [$imageUrls];
  1546. }
  1547. foreach ($imageUrls as $url) {
  1548. if (!empty($url)) {
  1549. $inlineData = $this->processMediaToInlineData($url);
  1550. if ($inlineData) {
  1551. $userMessage['content'][] = [
  1552. 'type' => 'image',
  1553. 'inline_data' => $inlineData
  1554. ];
  1555. }
  1556. }
  1557. }
  1558. }
  1559. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  1560. $userMessage['content'] = $userMessage['content'][0]['text'];
  1561. }
  1562. $messages[] = $userMessage;
  1563. }
  1564. }
  1565. if (empty($messages)) {
  1566. Utils::throwError('20003:请提供有效的对话内容');
  1567. }
  1568. // 转换为 Gemini contents 格式
  1569. $systemInstruction = '';
  1570. $contents = [];
  1571. foreach ($messages as $message) {
  1572. $role = getProp($message, 'role', 'user');
  1573. $content = getProp($message, 'content', '');
  1574. if ($role === 'system') {
  1575. if (is_array($content)) {
  1576. $systemInstruction = $this->extractGeminiTextFromParts($content);
  1577. } else {
  1578. $systemInstruction = (string)$content;
  1579. }
  1580. continue;
  1581. }
  1582. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  1583. $parts = [];
  1584. if (is_array($content)) {
  1585. foreach ($content as $part) {
  1586. $partType = getProp($part, 'type', 'text');
  1587. if ($partType === 'text') {
  1588. $text = (string)getProp($part, 'text', '');
  1589. if ($text !== '') {
  1590. $parts[] = ['text' => $text];
  1591. }
  1592. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  1593. if (in_array($partType, ['image_url', 'video_url'])) {
  1594. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  1595. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  1596. } elseif (isset($part['inline_data'])) {
  1597. // 已处理过的 inline_data 直接使用
  1598. $parts[] = ['inline_data' => $part['inline_data']];
  1599. continue;
  1600. } else {
  1601. $url = '';
  1602. }
  1603. $inlineData = $this->processMediaToInlineData($url);
  1604. if ($inlineData) {
  1605. $parts[] = ['inline_data' => $inlineData];
  1606. }
  1607. }
  1608. }
  1609. } else {
  1610. $text = (string)$content;
  1611. if ($text !== '') {
  1612. $parts[] = ['text' => $text];
  1613. }
  1614. }
  1615. if (!empty($parts)) {
  1616. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  1617. }
  1618. }
  1619. if (empty($contents)) {
  1620. Utils::throwError('20003:请提供有效的对话内容');
  1621. }
  1622. // 构建生成配置
  1623. $generationConfig = [];
  1624. if (getProp($data, 'temperature', null) !== null) {
  1625. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  1626. }
  1627. if (getProp($data, 'top_p', null) !== null) {
  1628. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  1629. }
  1630. if (getProp($data, 'frequency_penalty', null) !== null) {
  1631. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  1632. }
  1633. if (getProp($data, 'presence_penalty', null) !== null) {
  1634. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  1635. }
  1636. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  1637. if ($maxOutputTokens <= 0) {
  1638. $maxOutputTokens = 8192;
  1639. }
  1640. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  1641. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  1642. $maxOutputTokens = 32768;
  1643. }
  1644. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  1645. // response_format 映射:text -> text/plain,json -> application/json
  1646. $responseFormat = getProp($data, 'response_format', 'text');
  1647. if (is_array($responseFormat)) {
  1648. $responseFormat = getProp($responseFormat, 'type', 'text');
  1649. }
  1650. if (in_array($responseFormat, ['json', 'json_object'])) {
  1651. $generationConfig['responseMimeType'] = 'application/json';
  1652. } else {
  1653. $generationConfig['responseMimeType'] = 'text/plain';
  1654. }
  1655. $requestData = [
  1656. 'contents' => $contents,
  1657. 'generationConfig' => $generationConfig,
  1658. ];
  1659. if ($systemInstruction !== '') {
  1660. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  1661. }
  1662. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  1663. $thinkingMode = getProp($data, 'thinking', null);
  1664. if (is_array($thinkingMode)) {
  1665. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  1666. }
  1667. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  1668. if ($thinkingMode === null) {
  1669. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  1670. }
  1671. if ($thinkingMode === 'enabled') {
  1672. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  1673. if ($thinkingBudget <= 0) {
  1674. $thinkingBudget = 20;
  1675. }
  1676. $requestData['generationConfig']['thinkingConfig'] = [
  1677. 'thinkingBudget' => $thinkingBudget
  1678. ];
  1679. } elseif ($defaultThinking) {
  1680. // 该模型仅支持思考模式,传 0 会返回 400
  1681. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  1682. } else {
  1683. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  1684. }
  1685. return $requestData;
  1686. }
  1687. /**
  1688. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  1689. *
  1690. * 模型名 -> env 变量名映射:
  1691. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  1692. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  1693. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  1694. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  1695. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  1696. */
  1697. private function getGeminiApiKey($model) {
  1698. $map = [
  1699. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  1700. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  1701. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  1702. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  1703. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  1704. ];
  1705. if (isset($map[$model])) {
  1706. $key = env($map[$model]);
  1707. if (!empty($key)) {
  1708. return $key;
  1709. }
  1710. }
  1711. return env('GEMINI_API_KEY', '');
  1712. }
  1713. /**
  1714. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  1715. */
  1716. private function geminiChatOnly($requestData, $model) {
  1717. $apiKey = $this->getGeminiApiKey($model);
  1718. if (empty($apiKey)) {
  1719. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1720. }
  1721. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1722. if (isset($requestData['messages'])) {
  1723. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1724. }
  1725. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1726. . '/models/' . $model . ':generateContent';
  1727. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1728. $headers = [
  1729. 'Authorization' => 'Bearer ' . $apiKey,
  1730. 'Content-Type' => 'application/json'
  1731. ];
  1732. $maxRetries = $this->gptRetryTimes();
  1733. $interval = $this->gptRetryInterval();
  1734. $attempt = 0;
  1735. while (true) {
  1736. try {
  1737. $response = $client->post($url, [
  1738. 'json' => $requestData,
  1739. 'headers' => $headers
  1740. ]);
  1741. $responseArr = json_decode($response->getBody()->getContents(), true);
  1742. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  1743. $fullContent = $this->extractGeminiContent($responseArr);
  1744. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  1745. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  1746. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  1747. ? $responseArr['candidates'][0]['finishReason']
  1748. : '';
  1749. return [
  1750. 'fullContent' => $fullContent,
  1751. 'fullReasoningContent' => $fullReasoningContent,
  1752. 'usage' => $usage,
  1753. 'finish_reason' => $finishReason
  1754. ];
  1755. } catch (\Exception $e) {
  1756. $retryable = true;
  1757. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1758. $status = $e->getResponse()->getStatusCode();
  1759. $retryable = $status >= 500 || $status == 429;
  1760. }
  1761. if (!$retryable || $attempt >= $maxRetries) {
  1762. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  1763. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  1764. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  1765. }
  1766. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  1767. 'retry' => $attempt + 1,
  1768. 'max_retries' => $maxRetries,
  1769. 'error' => $e->getMessage()
  1770. ]);
  1771. sleep($interval);
  1772. $attempt++;
  1773. }
  1774. }
  1775. }
  1776. /**
  1777. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  1778. */
  1779. private function geminiStreamResponse($requestData, $model) {
  1780. $apiKey = $this->getGeminiApiKey($model);
  1781. if (empty($apiKey)) {
  1782. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1783. }
  1784. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1785. if (isset($requestData['messages'])) {
  1786. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1787. }
  1788. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1789. . '/models/' . $model . ':generateContent?alt=sse';
  1790. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1791. $headers = [
  1792. 'Authorization' => 'Bearer ' . $apiKey,
  1793. 'Content-Type' => 'application/json'
  1794. ];
  1795. try {
  1796. $response = $client->post($url, [
  1797. 'json' => $requestData,
  1798. 'headers' => $headers,
  1799. 'stream' => true
  1800. ]);
  1801. $body = $response->getBody();
  1802. $fullContent = '';
  1803. $fullReasoningContent = '';
  1804. $usage = [];
  1805. $buffer = '';
  1806. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1807. while (!$body->eof()) {
  1808. $chunk = $body->read(1024);
  1809. $buffer .= $chunk;
  1810. $lines = explode("\n", $buffer);
  1811. $buffer = array_pop($lines);
  1812. foreach ($lines as $line) {
  1813. $line = trim($line);
  1814. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1815. continue;
  1816. }
  1817. $data = substr($line, 6);
  1818. if ($data === '[DONE]') {
  1819. break 2;
  1820. }
  1821. try {
  1822. $json = json_decode($data, true);
  1823. if (json_last_error() !== JSON_ERROR_NONE) {
  1824. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1825. continue;
  1826. }
  1827. // 思考内容(thoughts)
  1828. $thoughts = $this->extractGeminiThoughts($json);
  1829. if ($thoughts !== '') {
  1830. $fullReasoningContent .= $thoughts;
  1831. yield [
  1832. 'type' => 'reasoning',
  1833. 'content' => $thoughts,
  1834. 'full_reasoning' => $fullReasoningContent
  1835. ];
  1836. }
  1837. // 回答内容
  1838. $partText = $this->extractGeminiContent($json);
  1839. if ($partText !== '') {
  1840. $fullContent .= $partText;
  1841. yield [
  1842. 'type' => 'content',
  1843. 'content' => $partText,
  1844. ];
  1845. }
  1846. // 使用统计
  1847. if (isset($json['usageMetadata'])) {
  1848. $usage = $json['usageMetadata'];
  1849. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  1850. }
  1851. } catch (\Exception $e) {
  1852. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1853. continue;
  1854. }
  1855. }
  1856. }
  1857. dLog('deepseek')->info('Gemini流式读取完成', [
  1858. 'content_length' => strlen($fullContent),
  1859. 'reasoning_length' => strlen($fullReasoningContent)
  1860. ]);
  1861. yield [
  1862. 'type' => 'done',
  1863. 'full_content' => $fullContent,
  1864. 'full_reasoning' => $fullReasoningContent,
  1865. 'usage' => $usage
  1866. ];
  1867. } catch (\Exception $e) {
  1868. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  1869. yield [
  1870. 'type' => 'error',
  1871. 'msg' => $e->getMessage(),
  1872. 'code' => $e->getCode()
  1873. ];
  1874. }
  1875. }
  1876. /**
  1877. * 从 Gemini 响应中提取回答文本
  1878. */
  1879. private function extractGeminiContent($responseArr) {
  1880. $text = '';
  1881. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  1882. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  1883. if (isset($part['text'])) {
  1884. $text .= $part['text'];
  1885. }
  1886. }
  1887. }
  1888. return $text;
  1889. }
  1890. /**
  1891. * 从 Gemini 响应中提取思考内容
  1892. */
  1893. private function extractGeminiReasoningContent($responseArr) {
  1894. $reasoning = '';
  1895. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1896. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1897. if (isset($thought['text'])) {
  1898. $reasoning .= $thought['text'];
  1899. }
  1900. }
  1901. }
  1902. return $reasoning;
  1903. }
  1904. /**
  1905. * 从 Gemini 流式响应中提取本次增量思考内容
  1906. */
  1907. private function extractGeminiThoughts($responseArr) {
  1908. $thoughts = '';
  1909. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1910. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1911. if (isset($thought['text'])) {
  1912. $thoughts .= $thought['text'];
  1913. }
  1914. }
  1915. }
  1916. return $thoughts;
  1917. }
  1918. /**
  1919. * 提取消息数组中的纯文本
  1920. */
  1921. private function extractGeminiTextFromParts($parts) {
  1922. $text = '';
  1923. if (is_array($parts)) {
  1924. foreach ($parts as $part) {
  1925. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  1926. $text .= (string)getProp($part, 'text', '');
  1927. }
  1928. }
  1929. }
  1930. return $text;
  1931. }
  1932. /**
  1933. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  1934. *
  1935. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  1936. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  1937. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  1938. *
  1939. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  1940. * @return array|null ['mime_type' => string, 'data' => string]
  1941. */
  1942. private function processMediaToInlineData($media) {
  1943. if (empty($media)) {
  1944. return null;
  1945. }
  1946. $localPath = null;
  1947. $isTempFile = false;
  1948. try {
  1949. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  1950. if (is_string($media) && strpos($media, 'data:') === 0) {
  1951. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  1952. return [
  1953. 'mime_type' => $matches[1],
  1954. 'data' => $matches[2]
  1955. ];
  1956. }
  1957. return null;
  1958. }
  1959. // 2. 获取本地文件路径
  1960. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  1961. $localPath = $this->downloadMediaToTemp($media);
  1962. $isTempFile = true;
  1963. } elseif (is_string($media)) {
  1964. $localPath = $media;
  1965. } else {
  1966. // Laravel UploadedFile 对象
  1967. $localPath = $media->getRealPath();
  1968. }
  1969. if (!$localPath || !file_exists($localPath)) {
  1970. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  1971. return null;
  1972. }
  1973. $fileSize = filesize($localPath);
  1974. $maxBytes = $this->geminiMediaMaxBytes();
  1975. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  1976. $mimeType = $this->detectMediaMime($localPath);
  1977. $isVideo = strpos($mimeType, 'video/') === 0;
  1978. $needCompress = $fileSize > $maxBytes;
  1979. $duration = 0;
  1980. if ($isVideo) {
  1981. $duration = $this->getMediaDuration($localPath);
  1982. if ($duration > 300) {
  1983. $needCompress = true;
  1984. }
  1985. }
  1986. $finalPath = $localPath;
  1987. $compressedPath = null;
  1988. if ($needCompress && $this->ffmpegAvailable()) {
  1989. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  1990. if ($compressed && file_exists($compressed)) {
  1991. $compressedPath = $compressed;
  1992. if (filesize($compressed) < $fileSize || $isVideo) {
  1993. $finalPath = $compressed;
  1994. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  1995. } else {
  1996. @unlink($compressed);
  1997. $compressedPath = null;
  1998. }
  1999. }
  2000. }
  2001. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  2002. $finalSize = filesize($finalPath);
  2003. if ($finalSize > $maxBytes) {
  2004. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  2005. 'path' => $localPath,
  2006. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  2007. 'limit_mb' => 14
  2008. ]);
  2009. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  2010. }
  2011. // 兜底校验:视频时长超过5分钟且未能压缩成功
  2012. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  2013. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  2014. }
  2015. $data = base64_encode(file_get_contents($finalPath));
  2016. return [
  2017. 'mime_type' => $mimeType,
  2018. 'data' => $data
  2019. ];
  2020. } catch (\App\Exceptions\ApiException $e) {
  2021. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  2022. throw $e;
  2023. } catch (\Exception $e) {
  2024. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  2025. return null;
  2026. } finally {
  2027. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  2028. @unlink($compressedPath);
  2029. }
  2030. if ($isTempFile && $localPath && file_exists($localPath)) {
  2031. @unlink($localPath);
  2032. }
  2033. }
  2034. }
  2035. /**
  2036. * 下载远程多媒体到临时目录
  2037. *
  2038. * @return string|null 本地临时文件路径
  2039. */
  2040. private function downloadMediaToTemp($url) {
  2041. try {
  2042. $tempDir = storage_path('app/temp/gemini');
  2043. if (!is_dir($tempDir)) {
  2044. mkdir($tempDir, 0775, true);
  2045. }
  2046. $extension = 'tmp';
  2047. $pathInfo = parse_url($url, PHP_URL_PATH);
  2048. if ($pathInfo) {
  2049. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  2050. if ($ext && strlen($ext) <= 10) {
  2051. $extension = strtolower($ext);
  2052. }
  2053. }
  2054. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  2055. $client = new Client(['timeout' => 300, 'verify' => false]);
  2056. $response = $client->get($url, ['sink' => $tmpFile]);
  2057. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  2058. @unlink($tmpFile);
  2059. return null;
  2060. }
  2061. return $tmpFile;
  2062. } catch (\Exception $e) {
  2063. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  2064. return null;
  2065. }
  2066. }
  2067. /**
  2068. * 检测多媒体文件 MIME 类型
  2069. */
  2070. private function detectMediaMime($filePath) {
  2071. $imageInfo = @getimagesize($filePath);
  2072. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  2073. return $imageInfo['mime'];
  2074. }
  2075. // 视频按扩展名粗略判断
  2076. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  2077. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  2078. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  2079. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  2080. if (isset($videoExts[$ext])) {
  2081. return $videoExts[$ext];
  2082. }
  2083. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  2084. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  2085. if (isset($imageExts[$ext])) {
  2086. return $imageExts[$ext];
  2087. }
  2088. return 'application/octet-stream';
  2089. }
  2090. /**
  2091. * 获取多媒体时长(秒),非视频或失败返回 0
  2092. */
  2093. private function getMediaDuration($filePath) {
  2094. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  2095. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  2096. $output = trim((string)shell_exec($cmd));
  2097. $duration = (float)$output;
  2098. return $duration > 0 ? $duration : 0;
  2099. }
  2100. /**
  2101. * 检查 ffmpeg 是否可用
  2102. */
  2103. private function ffmpegAvailable() {
  2104. static $available = null;
  2105. if ($available !== null) {
  2106. return $available;
  2107. }
  2108. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2109. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  2110. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  2111. $available = false;
  2112. return $available;
  2113. }
  2114. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  2115. $output = shell_exec($cmd);
  2116. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  2117. return $available;
  2118. }
  2119. /**
  2120. * 使用 ffmpeg 压缩多媒体文件
  2121. *
  2122. * @param string $inputFile 输入文件路径
  2123. * @param bool $isVideo 是否为视频
  2124. * @param float $duration 视频时长(秒),非视频传 0
  2125. * @return string|null 压缩后的文件路径,失败返回 null
  2126. */
  2127. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  2128. try {
  2129. $tempDir = storage_path('app/temp/gemini');
  2130. if (!is_dir($tempDir)) {
  2131. mkdir($tempDir, 0775, true);
  2132. }
  2133. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2134. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  2135. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  2136. if ($isVideo) {
  2137. // 视频:时长超过5分钟则加速压缩到5分钟以内
  2138. $speedFactor = 1.0;
  2139. if ($duration > 300) {
  2140. $speedFactor = $duration / 300;
  2141. }
  2142. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  2143. $finalDuration = $duration / max(1.0, $speedFactor);
  2144. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  2145. $targetBitrate = max(300, min(6000, $targetBitrate));
  2146. $filters = [];
  2147. $filters[] = 'scale=min(1280,iw):-2';
  2148. $filters[] = 'fps=24';
  2149. if ($speedFactor > 1.0) {
  2150. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  2151. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  2152. $fullCount = (int)ceil($speedFactor / 2.0);
  2153. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2154. if ($lastTempo < 0.5) {
  2155. $fullCount++;
  2156. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2157. }
  2158. for ($i = 0; $i < $fullCount; $i++) {
  2159. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  2160. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  2161. }
  2162. }
  2163. $filterStr = implode(',', $filters);
  2164. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  2165. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  2166. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  2167. } else {
  2168. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  2169. $imageInfo = @getimagesize($inputFile);
  2170. $scaleW = 2048;
  2171. $scaleH = 2048;
  2172. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  2173. if ($imageInfo[0] >= $imageInfo[1]) {
  2174. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  2175. $scaleW = 2048;
  2176. } else {
  2177. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  2178. $scaleH = 2048;
  2179. }
  2180. }
  2181. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  2182. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  2183. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  2184. }
  2185. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  2186. $output = shell_exec($cmd);
  2187. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  2188. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  2189. 'input' => $inputFile,
  2190. 'output' => $output
  2191. ]);
  2192. @unlink($outputFile);
  2193. return null;
  2194. }
  2195. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  2196. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  2197. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  2198. ]);
  2199. return $outputFile;
  2200. } catch (\Exception $e) {
  2201. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  2202. return null;
  2203. }
  2204. }
  2205. /**
  2206. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  2207. *
  2208. * @param array $data
  2209. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  2210. */
  2211. public function getScriptGenerateTasks($data) {
  2212. $uid = Site::getUid();
  2213. return DB::table('mp_script_generate_tasks as t')
  2214. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  2215. ->where('t.uid', $uid)
  2216. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  2217. ->orderByDesc('t.id')
  2218. ->paginate(15);
  2219. }
  2220. public function saveScriptChatHistory($data) {
  2221. $uid = Site::getUid();
  2222. $rid = getProp($data, 'rid');
  2223. $script_id = getProp($data, 'script_id');
  2224. $sequence = getProp($data, 'sequence', 0);
  2225. $content = getProp($data, 'content');
  2226. if (!$rid) {
  2227. Utils::throwError('20003:请选择对话记录ID');
  2228. }
  2229. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  2230. if (!$record) {
  2231. Utils::throwError('20003:对话记录不存在');
  2232. }
  2233. if (!$script_id) {
  2234. Utils::throwError('20003:请选择剧本');
  2235. }
  2236. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  2237. if (!$script) {
  2238. Utils::throwError('20003:剧本不存在');
  2239. }
  2240. // 批量插入数据
  2241. return DB::table('mp_script_records')->where('id', $rid)->update([
  2242. 'content' => $content,
  2243. 'updated_at' => date('Y-m-d H:i:s')
  2244. ]);
  2245. }
  2246. /**
  2247. * 获取剧本的历史对话记录
  2248. *
  2249. * @param array $data 请求参数
  2250. * @return array 返回历史记录数组
  2251. */
  2252. public function getScriptChatHistory($data) {
  2253. $uid = Site::getUid();
  2254. $script_id = getProp($data, 'script_id');
  2255. $rid = getProp($data, 'rid');
  2256. $sequence = getProp($data, 'sequence', null);
  2257. if (!$script_id) {
  2258. Utils::throwError('20003:请提供剧本ID');
  2259. }
  2260. // 验证剧本是否存在
  2261. $script = DB::table('mp_scripts')
  2262. ->where('id', $script_id)
  2263. ->where('is_deleted', 0)
  2264. ->first();
  2265. if (!$script) {
  2266. Utils::throwError('20003:剧本不存在');
  2267. }
  2268. // 构建查询
  2269. $query = DB::table('mp_script_records')
  2270. ->where('script_id', $script_id);
  2271. // ->where('uid', $uid);
  2272. // 如果提供了 sequence,则过滤指定剧集
  2273. if ($sequence !== null) {
  2274. $query->where('sequence', $sequence);
  2275. }
  2276. // 记录ID筛选
  2277. if ($rid) {
  2278. $query->where('id', $rid);
  2279. }
  2280. // 查询记录并按 id 正序排序
  2281. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  2282. ->orderBy('created_at', 'asc')
  2283. ->orderBy('id', 'asc')
  2284. ->get()
  2285. ->map(function ($record) {
  2286. return [
  2287. 'rid' => $record->id,
  2288. 'script_id' => $record->script_id,
  2289. 'sequence' => $record->sequence,
  2290. 'role' => $record->role,
  2291. 'content' => $record->content,
  2292. 'products' => $record->products ? json_decode($record->products) : [],
  2293. 'created_at' => $record->created_at,
  2294. ];
  2295. })
  2296. ->toArray();
  2297. return $records;
  2298. }
  2299. /**
  2300. * 处理图片转换为base64
  2301. *
  2302. * @param mixed $image 图片文件对象或文件路径
  2303. * @return string|null base64编码的图片数据
  2304. */
  2305. private function processImageToBase64($image) {
  2306. try {
  2307. // 获取文件路径
  2308. if (is_string($image)) {
  2309. $filePath = $image;
  2310. } else {
  2311. // Laravel UploadedFile 对象
  2312. $filePath = $image->getRealPath();
  2313. }
  2314. if (!file_exists($filePath)) {
  2315. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  2316. return null;
  2317. }
  2318. // 验证是否为图片文件
  2319. $imageInfo = @getimagesize($filePath);
  2320. if ($imageInfo === false) {
  2321. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  2322. return null;
  2323. }
  2324. // 读取图片并转换为base64
  2325. $imageData = file_get_contents($filePath);
  2326. $base64Image = base64_encode($imageData);
  2327. dLog('deepseek')->info('图片转换成功', [
  2328. 'size' => strlen($imageData),
  2329. 'type' => $imageInfo['mime']
  2330. ]);
  2331. return $base64Image;
  2332. } catch (\Exception $e) {
  2333. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  2334. return null;
  2335. }
  2336. }
  2337. private function getArtStylePromptMappings($art_style='')
  2338. {
  2339. // 优先从画风表读取(入库后以表数据为准,保持原返回结构:['画风名' => ['aliases' => [...], 'prompt' => "..."]]
  2340. $dbRows = DB::table('mp_art_styles')
  2341. ->where('is_deleted', 0)
  2342. ->orderBy('id')
  2343. ->get(['art_style', 'aliases', 'prompt']);
  2344. if ($dbRows->isNotEmpty()) {
  2345. $arr = [];
  2346. foreach ($dbRows as $row) {
  2347. $arr[$row->art_style] = [
  2348. 'aliases' => is_string($row->aliases) ? json_decode($row->aliases, true) : [],
  2349. 'prompt' => (string)$row->prompt,
  2350. ];
  2351. }
  2352. if ($art_style) {
  2353. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2354. }
  2355. return $arr;
  2356. }
  2357. $arr = [
  2358. '唯美真人风格' => [
  2359. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2360. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  2361. ],
  2362. '真人古风风格' => [
  2363. 'aliases' => ['真人古风风格', '真人古风'],
  2364. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  2365. ],
  2366. '日系动漫风格' => [
  2367. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2368. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  2369. ],
  2370. '国漫风格' => [
  2371. 'aliases' => ['国漫风格', '国漫'],
  2372. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  2373. ],
  2374. 'Q版卡通风格' => [
  2375. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2376. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  2377. ],
  2378. '简约扁平风格' => [
  2379. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2380. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  2381. ],
  2382. '武侠风格' => [
  2383. 'aliases' => ['武侠风格', '武侠'],
  2384. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  2385. ],
  2386. '古风仙侠风格' => [
  2387. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2388. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  2389. ],
  2390. '新中式水墨风格' => [
  2391. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2392. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  2393. ],
  2394. '写实插画风格' => [
  2395. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2396. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  2397. ],
  2398. '3D卡通风格' => [
  2399. 'aliases' => ['3D卡通风格', '3D卡通'],
  2400. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  2401. ],
  2402. '条漫风格' => [
  2403. 'aliases' => ['条漫风格', '条漫'],
  2404. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  2405. ],
  2406. '赛博朋克风格' => [
  2407. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2408. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  2409. ],
  2410. '暗黑悬疑风格' => [
  2411. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2412. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  2413. ],
  2414. '治愈清新风格' => [
  2415. 'aliases' => ['治愈清新风格', '治愈清新'],
  2416. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  2417. ],
  2418. '3D真人风格' => [
  2419. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  2420. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  2421. ],
  2422. ];
  2423. if($art_style) {
  2424. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2425. }
  2426. return $arr;
  2427. $arr = [
  2428. '唯美真人风格' => [
  2429. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2430. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  2431. 2. 色彩色调
  2432. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  2433. 3. 画质精度
  2434. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  2435. 4. 画面观感
  2436. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  2437. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  2438. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  2439. ],
  2440. '真人古风风格' => [
  2441. 'aliases' => ['真人古风风格', '真人古风'],
  2442. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  2443. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  2444. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  2445. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  2446. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  2447. ],
  2448. '日系动漫风格' => [
  2449. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2450. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  2451. 正向提示词(中文)
  2452. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  2453. 必须遵守规则
  2454. • 全程保持日系动漫风格,不混入其他画风
  2455. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  2456. • 画面适配所选画面比例,构图居中,主体突出
  2457. • 线条干净、色彩统一,不杂乱、不突兀
  2458. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  2459. ],
  2460. '国漫风格' => [
  2461. 'aliases' => ['国漫风格', '国漫'],
  2462. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  2463. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  2464. 必须遵守规则
  2465. • 严格保持国漫画风,不串风格、不混画风
  2466. • 角色形象统一,不随意改变五官、身材、服饰
  2467. • 画面构图稳定,适合漫剧叙事展示
  2468. • 色调统一,不出现脏色、杂色
  2469. 禁止/避免词汇
  2470. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  2471. ],
  2472. 'Q版卡通风格' => [
  2473. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2474. 'prompt' => "风格说明
  2475. 头大身小,造型可爱圆润,简约干净
  2476. 正向提示词(中文)
  2477. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  2478. 必须遵守规则
  2479. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  2480. • 角色造型统一,表情可爱,不诡异
  2481. • 画面简洁清爽,无多余复杂元素
  2482. • 色彩明亮柔和,不刺眼
  2483. 禁止/避免词汇
  2484. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  2485. ],
  2486. '简约扁平风格' => [
  2487. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2488. 'prompt' => "风格说明
  2489. 色块简洁、无复杂渐变,现代极简风
  2490. 正向提示词(中文)
  2491. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  2492. 必须遵守规则
  2493. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  2494. • 构图简洁,主体突出,无多余装饰
  2495. • 色彩统一、干净,不杂乱
  2496. 禁止/避免词汇
  2497. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  2498. ],
  2499. '武侠风格' => [
  2500. 'aliases' => ['武侠风格', '武侠'],
  2501. 'prompt' => "风格说明
  2502. 江湖气息,线条硬朗,动作感强
  2503. 正向提示词(中文)
  2504. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  2505. 必须遵守规则
  2506. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  2507. • 角色形象、服饰、身材比例统一
  2508. • 画面动作自然,不扭曲、不畸形
  2509. 禁止/避免词汇
  2510. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  2511. ],
  2512. '古风仙侠风格' => [
  2513. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2514. 'prompt' => "风格说明
  2515. 飘逸汉服、云雾仙气、唯美空灵
  2516. 正向提示词(中文)
  2517. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  2518. 必须遵守规则
  2519. • 保持古风仙侠统一画风,不混入现代、科幻元素
  2520. • 角色服饰、发型、形象前后一致
  2521. • 场景仙气飘逸,色调清雅统一
  2522. • 画面唯美柔和,不阴暗、不诡异
  2523. 禁止/避免词汇
  2524. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  2525. ],
  2526. '新中式水墨风格' => [
  2527. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2528. 'prompt' => "风格说明
  2529. 淡墨渲染,毛笔笔触,留白意境
  2530. 正向提示词(中文)
  2531. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  2532. 必须遵守规则
  2533. • 严格保持水墨质感,不混入厚涂、写实、卡通
  2534. • 色调淡雅统一,不浓艳杂乱
  2535. • 画面干净有意境,不堆砌元素
  2536. 禁止/避免词汇
  2537. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  2538. ],
  2539. '写实插画风格' => [
  2540. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2541. 'prompt' => "风格说明
  2542. 接近真人比例,光影真实,质感细腻
  2543. 正向提示词(中文)
  2544. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  2545. 必须遵守规则
  2546. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  2547. • 角色五官、身材、服饰高度统一
  2548. • 画面清晰、光影自然、不扭曲
  2549. 禁止/避免词汇
  2550. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  2551. ],
  2552. '3D卡通风格' => [
  2553. 'aliases' => ['3D卡通风格', '3D卡通'],
  2554. 'prompt' => "风格说明
  2555. 3D建模质感,柔和渲染,圆润可爱
  2556. 正向提示词(中文)
  2557. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  2558. 必须遵守规则
  2559. • 保持3D卡通统一质感,不出现2D杂乱线条
  2560. • 角色模型、比例、形象前后一致
  2561. • 画面干净,不模糊、不穿模
  2562. 禁止/避免词汇
  2563. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  2564. ],
  2565. '条漫风格' => [
  2566. 'aliases' => ['条漫风格', '条漫'],
  2567. 'prompt' => "风格说明
  2568. 纵向分镜,上下滑动阅读,轻量化
  2569. 正向提示词(中文)
  2570. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  2571. 必须遵守规则
  2572. • 保持条漫纵向阅读逻辑,构图简洁
  2573. • 画风统一,不混写实、3D、水墨
  2574. • 画面干净,不杂乱
  2575. 禁止/避免词汇
  2576. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  2577. ],
  2578. '赛博朋克风格' => [
  2579. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2580. 'prompt' => "风格说明
  2581. 霓虹灯光、未来都市、暗色调、科技机械
  2582. 正向提示词(中文)
  2583. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  2584. 必须遵守规则
  2585. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  2586. • 色调以暗调+霓虹为主,色彩统一
  2587. • 画面科技感强,不杂乱
  2588. 禁止/避免词汇
  2589. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  2590. ],
  2591. '暗黑悬疑风格' => [
  2592. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2593. 'prompt' => "风格说明
  2594. 低饱和、冷色调、阴影重、神秘压抑
  2595. 正向提示词(中文)
  2596. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  2597. 必须遵守规则
  2598. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  2599. • 画面氛围压抑神秘,但不低俗、不血腥
  2600. • 角色形象统一,不崩坏
  2601. 禁止/避免词汇
  2602. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  2603. ],
  2604. '治愈清新风格' => [
  2605. 'aliases' => ['治愈清新风格', '治愈清新'],
  2606. 'prompt' => "风格说明
  2607. 马卡龙色系、柔光、温暖干净
  2608. 正向提示词(中文)
  2609. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  2610. 必须遵守规则
  2611. • 保持治愈清新统一色调,不阴暗、不诡异
  2612. • 画面柔和干净,无杂乱元素
  2613. • 角色形象柔和可爱,不狰狞
  2614. 禁止/避免词汇
  2615. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  2616. ],
  2617. ];
  2618. return $arr;
  2619. }
  2620. public function getArtStylePromptByInput($inputArtStyle): string
  2621. {
  2622. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  2623. if ($normalizedInput === '') {
  2624. return '';
  2625. }
  2626. return $this->getArtStylePromptMappings($normalizedInput);
  2627. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  2628. // foreach ($mapping['aliases'] as $alias) {
  2629. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  2630. // if ($normalizedAlias === '') {
  2631. // continue;
  2632. // }
  2633. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  2634. // return $mapping['prompt'];
  2635. // }
  2636. // }
  2637. // }
  2638. return '';
  2639. }
  2640. public function getArtStyleShortPromptByInput($inputArtStyle) {
  2641. // 优先从画风表读取;character_prefix/scene_prefix 缺失时用通用 prompt 兜底,均缺失则返回空数组
  2642. $row = DB::table('mp_art_styles')
  2643. ->where('art_style', $inputArtStyle)
  2644. ->where('is_deleted', 0)
  2645. ->first(['character_prefix', 'scene_prefix', 'prompt']);
  2646. if ($row) {
  2647. $prompt = (string)$row->prompt;
  2648. $result = [
  2649. 'character_prefix' => (string)$row->character_prefix !== '' ? (string)$row->character_prefix : $prompt,
  2650. 'scene_prefix' => (string)$row->scene_prefix !== '' ? (string)$row->scene_prefix : $prompt,
  2651. ];
  2652. // 前缀与通用提示词均不存在时返回空数组
  2653. if ($result['character_prefix'] === '' && $result['scene_prefix'] === '') {
  2654. return [];
  2655. }
  2656. return $result;
  2657. }
  2658. $stylePrefixes = [
  2659. '唯美真人风格' => [
  2660. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  2661. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强',
  2662. 'prompt' => '唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质'
  2663. ],
  2664. '真人古风风格' => [
  2665. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  2666. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清',
  2667. 'prompt' => '真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清'
  2668. ],
  2669. '日系动漫风格' => [
  2670. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  2671. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强',
  2672. 'prompt' => '日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影'
  2673. ],
  2674. '国漫风格' => [
  2675. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  2676. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染',
  2677. 'prompt' => '国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节'
  2678. ],
  2679. 'Q版卡通风格' => [
  2680. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  2681. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感',
  2682. 'prompt' => 'Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画'
  2683. ],
  2684. '简约扁平风格' => [
  2685. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  2686. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽',
  2687. 'prompt' => '简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽'
  2688. ],
  2689. '武侠风格' => [
  2690. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  2691. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学',
  2692. 'prompt' => '武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制'
  2693. ],
  2694. '古风仙侠风格' => [
  2695. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  2696. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学',
  2697. 'prompt' => '古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面'
  2698. ],
  2699. '新中式水墨风格' => [
  2700. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  2701. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景',
  2702. 'prompt' => '新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感'
  2703. ],
  2704. '写实插画风格' => [
  2705. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  2706. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图',
  2707. 'prompt' => '写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染'
  2708. ],
  2709. '3D卡通风格' => [
  2710. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  2711. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染',
  2712. 'prompt' => '3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富'
  2713. ],
  2714. '条漫风格' => [
  2715. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  2716. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感',
  2717. 'prompt' => '条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制'
  2718. ],
  2719. '赛博朋克风格' => [
  2720. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  2721. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影',
  2722. 'prompt' => '赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染'
  2723. ],
  2724. '暗黑悬疑风格' => [
  2725. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  2726. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图',
  2727. 'prompt' => '暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现'
  2728. ],
  2729. '治愈清新风格' => [
  2730. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  2731. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强',
  2732. 'prompt' => '治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足'
  2733. ]
  2734. ];
  2735. if (isset($stylePrefixes[$inputArtStyle])) {
  2736. $item = $stylePrefixes[$inputArtStyle];
  2737. $prompt = (string)($item['prompt'] ?? '');
  2738. // 前缀缺失时用通用 prompt 兜底
  2739. $result = [
  2740. 'character_prefix' => !empty($item['character_prefix']) ? $item['character_prefix'] : $prompt,
  2741. 'scene_prefix' => !empty($item['scene_prefix']) ? $item['scene_prefix'] : $prompt,
  2742. ];
  2743. // 与表分支一致:前缀与通用提示词均不存在时返回空数组
  2744. if ($result['character_prefix'] === '' && $result['scene_prefix'] === '') {
  2745. return [];
  2746. }
  2747. return $result;
  2748. }
  2749. return [];
  2750. }
  2751. private function normalizeArtStyleInput($value): string
  2752. {
  2753. $value = trim((string)$value);
  2754. if ($value === '') {
  2755. return '';
  2756. }
  2757. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  2758. return mb_strtolower($value, 'UTF-8');
  2759. }
  2760. private function replaceArtStyleSection(string $content, string $artStyle): string
  2761. {
  2762. if ($content === '' || $artStyle === '') {
  2763. return $content;
  2764. }
  2765. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  2766. if (!preg_match($pattern, $content)) {
  2767. return $content;
  2768. }
  2769. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  2770. }
  2771. /**
  2772. * 解开模型偶发返回的 JSON 包装内容
  2773. *
  2774. * @param mixed $content 模型返回的原始内容
  2775. * @return mixed 解开后的内容(若无法解开则原样返回)
  2776. */
  2777. private function unwrapJsonWrappedContent($content) {
  2778. $trimmed = ltrim((string)$content);
  2779. if ($trimmed === '' || ($trimmed[0] !== '{' && $trimmed[0] !== '[')) {
  2780. return $content;
  2781. }
  2782. $decoded = json_decode($trimmed, true);
  2783. if (!is_array($decoded)) {
  2784. return $content;
  2785. }
  2786. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2787. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2788. return $decoded[$key];
  2789. }
  2790. }
  2791. return $content;
  2792. }
  2793. private function deepSeekStreamResponse($post_data) {
  2794. // 设置最大输出tokens
  2795. $post_data['max_tokens'] = 300000;
  2796. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2797. $post_data['stream_options'] = ['include_usage' => true];
  2798. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2799. $response = $client->post($this->url, [
  2800. 'json' => $post_data,
  2801. 'headers' => $this->headers,
  2802. 'stream' => true // 启用流式响应
  2803. ]);
  2804. $body = $response->getBody();
  2805. $fullContent = '';
  2806. $fullReasoningContent = '';
  2807. $usage = [];
  2808. $buffer = '';
  2809. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  2810. // 逐行读取流式响应
  2811. while (!$body->eof()) {
  2812. $chunk = $body->read(1024); // 每次读取 1KB
  2813. $buffer .= $chunk;
  2814. // 按行分割
  2815. $lines = explode("\n", $buffer);
  2816. // 保留最后一个不完整的行
  2817. $buffer = array_pop($lines);
  2818. foreach ($lines as $line) {
  2819. $line = trim($line);
  2820. // 跳过空行
  2821. if (empty($line)) {
  2822. continue;
  2823. }
  2824. // 检查是否是 SSE 数据行
  2825. if (strpos($line, 'data: ') !== 0) {
  2826. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2827. continue;
  2828. }
  2829. $data = substr($line, 6); // 移除 "data: " 前缀
  2830. if ($data === '[DONE]') {
  2831. dLog('deepseek')->info('收到结束标记');
  2832. break 2; // 跳出两层循环
  2833. }
  2834. try {
  2835. $json = json_decode($data, true);
  2836. if (json_last_error() !== JSON_ERROR_NONE) {
  2837. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2838. continue;
  2839. }
  2840. if (isset($json['choices'][0]['delta'])) {
  2841. $delta = $json['choices'][0]['delta'];
  2842. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2843. if (isset($delta['reasoning_content'])) {
  2844. $fullReasoningContent .= $delta['reasoning_content'];
  2845. yield [
  2846. 'type' => 'reasoning',
  2847. 'content' => $delta['reasoning_content'],
  2848. 'full_reasoning' => $fullReasoningContent
  2849. ];
  2850. }
  2851. // 处理最终回答内容
  2852. if (isset($delta['content'])) {
  2853. $fullContent .= $delta['content'];
  2854. yield [
  2855. 'type' => 'content',
  2856. 'content' => $delta['content'],
  2857. ];
  2858. }
  2859. }
  2860. // 获取使用统计信息
  2861. if (isset($json['usage'])) {
  2862. $usage = $json['usage'];
  2863. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2864. }
  2865. } catch (\Exception $e) {
  2866. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2867. continue;
  2868. }
  2869. }
  2870. }
  2871. dLog('deepseek')->info('流式读取完成', [
  2872. 'content_length' => strlen($fullContent),
  2873. 'reasoning_length' => strlen($fullReasoningContent)
  2874. ]);
  2875. yield [
  2876. 'type' => 'done',
  2877. 'full_content' => $fullContent,
  2878. 'full_reasoning' => $fullReasoningContent,
  2879. 'usage' => $usage
  2880. ];
  2881. }
  2882. /**
  2883. * GPT 重试次数(env 可配置,默认 5 次)
  2884. */
  2885. private function gptRetryTimes()
  2886. {
  2887. return (int)env('GPT_RETRY_TIMES', 5);
  2888. }
  2889. /**
  2890. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  2891. */
  2892. private function gptRetryInterval()
  2893. {
  2894. return (int)env('GPT_RETRY_INTERVAL', 10);
  2895. }
  2896. /**
  2897. * 判断 GPT 请求异常是否可重试
  2898. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  2899. */
  2900. private function isGptRetryableException(\Exception $e)
  2901. {
  2902. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  2903. return false;
  2904. }
  2905. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  2906. $status = $e->getResponse()->getStatusCode();
  2907. return $status >= 500 || $status == 429;
  2908. }
  2909. return true;
  2910. }
  2911. /**
  2912. * GPT 中转站探活:GET /v1/models,5 秒短超时
  2913. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  2914. */
  2915. private function checkGptServiceAvailable($apiKey = null)
  2916. {
  2917. if ($apiKey === null) {
  2918. $apiKey = env('GPT_54_API_KEY');
  2919. }
  2920. if (empty($apiKey)) {
  2921. return false;
  2922. }
  2923. try {
  2924. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  2925. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  2926. 'headers' => [
  2927. 'Authorization' => 'Bearer ' . $apiKey,
  2928. 'Content-Type' => 'application/json'
  2929. ]
  2930. ]);
  2931. $status = $response->getStatusCode();
  2932. return $status < 500 && $status != 429;
  2933. } catch (\Exception $e) {
  2934. return false;
  2935. }
  2936. }
  2937. /**
  2938. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  2939. * 全部失败抛出友好错误
  2940. */
  2941. private function ensureGptServiceAvailable($apiKey = null)
  2942. {
  2943. $maxRetries = $this->gptRetryTimes();
  2944. $interval = $this->gptRetryInterval();
  2945. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  2946. if ($this->checkGptServiceAvailable($apiKey)) {
  2947. return;
  2948. }
  2949. if ($attempt < $maxRetries) {
  2950. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  2951. 'retry' => $attempt + 1,
  2952. 'max_retries' => $maxRetries
  2953. ]);
  2954. sleep($interval);
  2955. }
  2956. }
  2957. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  2958. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  2959. 'max_retries' => $maxRetries,
  2960. 'interval' => $interval
  2961. ]);
  2962. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  2963. }
  2964. /**
  2965. * GPT 流式输出处理方法
  2966. *
  2967. * @param array $post_data GPT API请求参数
  2968. * @return \Generator 返回生成器,用于流式输出
  2969. */
  2970. private function gpt54StreamResponse($post_data) {
  2971. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  2972. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  2973. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  2974. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  2975. $usedLunaFallback = false;
  2976. // 流式请求长时间无任何返回(TTFB)超过该秒数时切换备用 Key(env 可配置,默认 600 秒)
  2977. $ttfbTimeoutSeconds = (int)env('GPT_SWITCH_LUNA_AFTER_SECONDS', 600);
  2978. if (empty($apiKey)) {
  2979. Utils::throwError('20003:GPT API Key未配置');
  2980. }
  2981. // 先探活,服务不可用时自动重试
  2982. $this->ensureGptServiceAvailable($apiKey);
  2983. $client = new Client(['timeout' => 1800, 'verify' => false, 'read_timeout' => $ttfbTimeoutSeconds]);
  2984. // 移除 thinking 参数,GPT-5.4 不支持
  2985. if (isset($post_data['thinking'])) {
  2986. unset($post_data['thinking']);
  2987. }
  2988. if (isset($post_data['reasoning_effort'])) {
  2989. unset($post_data['reasoning_effort']);
  2990. }
  2991. // 流式场景下保留 response_format(json 输出时强制模型输出完整 JSON,与非流式 gpt54ChatOnly 对齐)
  2992. // 中转站对 response_format 的兼容性由请求方控制:仅在需要 json 输出时传入
  2993. $post_data['max_completion_tokens'] = 100000;
  2994. $post_data['max_tokens'] = 100000;
  2995. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2996. $post_data['stream_options'] = ['include_usage' => true];
  2997. $maxRetries = $this->gptRetryTimes();
  2998. $interval = $this->gptRetryInterval();
  2999. $attempt = 0;
  3000. while (true) {
  3001. $fullContent = '';
  3002. $usage = [];
  3003. $buffer = '';
  3004. // JSON 输出场景:不启用"整段正文包成 JSON 字符串"的暂缓缓存,流式过程中直接输出供前端展示
  3005. $isJsonRequest = isset($post_data['response_format'])
  3006. && is_array($post_data['response_format'])
  3007. && ($post_data['response_format']['type'] ?? '') === 'json_object';
  3008. $suspectJsonWrap = false;
  3009. $pendingContent = '';
  3010. $requestStartedAt = microtime(true);
  3011. $headers = [
  3012. 'Authorization' => 'Bearer ' . $apiKey,
  3013. 'Content-Type' => 'application/json',
  3014. 'Accept' => 'text/event-stream'
  3015. ];
  3016. try {
  3017. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  3018. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  3019. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  3020. 'json' => $post_data,
  3021. 'headers' => $headers,
  3022. 'stream' => true // 启用流式响应
  3023. ]);
  3024. $body = $response->getBody();
  3025. dLog('deepseek')->info('开始读取 GPT 流式响应');
  3026. // 逐行读取流式响应
  3027. while (!$body->eof()) {
  3028. // 长时间没有任何内容返回时,切换备用 Key 重试
  3029. if ($fullContent === '' && empty($usage) && (microtime(true) - $requestStartedAt) > $ttfbTimeoutSeconds) {
  3030. throw new \RuntimeException('GPT 流式响应长时间无返回,等待切换备用 Key');
  3031. }
  3032. $chunk = $body->read(1024); // 每次读取 1KB
  3033. $buffer .= $chunk;
  3034. // 按行分割
  3035. $lines = explode("\n", $buffer);
  3036. // 保留最后一个不完整的行
  3037. $buffer = array_pop($lines);
  3038. foreach ($lines as $line) {
  3039. $line = trim($line);
  3040. // 跳过空行
  3041. if (empty($line)) {
  3042. continue;
  3043. }
  3044. // 检查是否是 SSE 数据行
  3045. if (strpos($line, 'data: ') !== 0) {
  3046. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  3047. continue;
  3048. }
  3049. $data = substr($line, 6); // 移除 "data: " 前缀
  3050. if ($data === '[DONE]') {
  3051. dLog('deepseek')->info('收到结束标记');
  3052. break 2; // 跳出 foreach 和流读取循环
  3053. }
  3054. try {
  3055. $json = json_decode($data, true);
  3056. if (json_last_error() !== JSON_ERROR_NONE) {
  3057. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3058. continue;
  3059. }
  3060. if (isset($json['choices'][0]['delta'])) {
  3061. $delta = $json['choices'][0]['delta'];
  3062. // 处理回答内容
  3063. if (isset($delta['content'])) {
  3064. $fullContent .= $delta['content'];
  3065. $trimmed = ltrim($fullContent);
  3066. if (!$suspectJsonWrap && !$isJsonRequest && $trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
  3067. // 可能模型把整段正文包成了 JSON 字符串,先暂缓输出
  3068. $suspectJsonWrap = true;
  3069. }
  3070. if (!$suspectJsonWrap) {
  3071. // 中转可能一次返回大段内容,按小块输出保持流式节奏
  3072. $chunkSize = 256;
  3073. $chunkLength = mb_strlen($delta['content']);
  3074. for ($offset = 0; $offset < $chunkLength; $offset += $chunkSize) {
  3075. yield [
  3076. 'type' => 'content',
  3077. 'content' => mb_substr($delta['content'], $offset, $chunkSize),
  3078. ];
  3079. }
  3080. } else {
  3081. $pendingContent .= $delta['content'];
  3082. }
  3083. }
  3084. }
  3085. // 获取使用统计信息
  3086. if (isset($json['usage'])) {
  3087. $usage = $json['usage'];
  3088. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  3089. }
  3090. } catch (\Exception $e) {
  3091. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3092. continue;
  3093. }
  3094. }
  3095. }
  3096. dLog('deepseek')->info('流式读取完成', [
  3097. 'content_length' => strlen($fullContent)
  3098. ]);
  3099. // 兼容模型偶发把整段正文包裹成 JSON 字符串返回
  3100. if ($suspectJsonWrap) {
  3101. $decoded = json_decode(trim($fullContent), true);
  3102. $unwrapped = null;
  3103. if (is_array($decoded)) {
  3104. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  3105. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  3106. $unwrapped = $decoded[$key];
  3107. break;
  3108. }
  3109. }
  3110. }
  3111. if ($unwrapped !== null) {
  3112. $fullContent = $unwrapped;
  3113. $chunkSize = 256;
  3114. $contentLength = mb_strlen($fullContent);
  3115. for ($offset = 0; $offset < $contentLength; $offset += $chunkSize) {
  3116. yield [
  3117. 'type' => 'content',
  3118. 'content' => mb_substr($fullContent, $offset, $chunkSize),
  3119. ];
  3120. }
  3121. } elseif ($pendingContent !== '') {
  3122. // 误判:补发暂缓内容,避免内容丢失
  3123. yield [
  3124. 'type' => 'content',
  3125. 'content' => $pendingContent,
  3126. ];
  3127. }
  3128. }
  3129. yield [
  3130. 'type' => 'done',
  3131. 'full_content' => $fullContent,
  3132. 'full_reasoning' => '',
  3133. 'usage' => $usage
  3134. ];
  3135. return;
  3136. } catch (\Exception $e) {
  3137. // 报错或长时间无返回时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  3138. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  3139. $usedLunaFallback = true;
  3140. $apiKey = $lunaApiKey;
  3141. dLog('deepseek')->warning('GPT 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  3142. continue;
  3143. }
  3144. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  3145. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  3146. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  3147. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  3148. throw $e;
  3149. }
  3150. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  3151. 'retry' => $attempt + 1,
  3152. 'max_retries' => $maxRetries,
  3153. 'error' => $e->getMessage()
  3154. ]);
  3155. sleep($interval);
  3156. $attempt++;
  3157. }
  3158. }
  3159. }
  3160. // 与推理模型对话
  3161. public function chatWithReasoner($data) {
  3162. // 文生文计费预检(normal 档)
  3163. $uid = Site::getUid();
  3164. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'normal'), $uid);
  3165. $content = getProp($data, 'content');
  3166. $model = getProp($data, 'model', 'r1');
  3167. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3168. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3169. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3170. if ($model == 'r1') {
  3171. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  3172. $thinkingMode = 'disabled';
  3173. } else {
  3174. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  3175. $thinkingMode = 'disabled';
  3176. }
  3177. // 获取可选情感(根据音色可支持情感选)
  3178. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  3179. $emotion_list = [];
  3180. foreach ($timbre_emotion as $emotion) {
  3181. $tmp = explode(',', $emotion);
  3182. $emotion_list = array_merge($emotion_list, $tmp);
  3183. }
  3184. $emotion_list = array_unique($emotion_list);
  3185. $emotion_str = implode('、', $emotion_list);
  3186. // // 获取可选情感
  3187. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  3188. // $emotion_str = implode('、', $emotion_list);
  3189. // 是否启用情感
  3190. $enable_emotion = getProp($data, 'enable_emotion', 0);
  3191. if ($enable_emotion) {
  3192. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  3193. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3194. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  3195. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  3196. }else {
  3197. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  3198. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3199. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  3200. }
  3201. $messages = [
  3202. [
  3203. 'role' => 'system',
  3204. 'content' => $sys_content
  3205. ],
  3206. [
  3207. 'role' => 'user',
  3208. 'content' => $content
  3209. ]
  3210. ];
  3211. $post_data = [
  3212. 'model' => $model,
  3213. 'messages' => $messages,
  3214. // 'max_tokens' => 8192,
  3215. 'temperature' => 1,
  3216. 'frequency_penalty' => 0,
  3217. 'presence_penalty' => 0,
  3218. 'thinking' => ['type' => $thinkingMode],
  3219. 'response_format' => [
  3220. 'type' => 'text'
  3221. ],
  3222. 'stream' => false
  3223. ];
  3224. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3225. // 根据模型类型选择调用方法
  3226. $fullContent = '';
  3227. $usage = [];
  3228. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3229. // DeepSeek 官方模型使用 DeepSeek API
  3230. $chatResult = $this->chatOnly($post_data);
  3231. } else if (in_array($model, $this->gpt_text_models)) {
  3232. // GPT-5.4 模型使用 TokenRouter API
  3233. $chatResult = $this->gpt54ChatOnly($post_data);
  3234. } else {
  3235. // 其他模型使用火山引擎API
  3236. $chatResult = $this->volcEngineChatCompletion($post_data);
  3237. }
  3238. if (is_array($chatResult)) {
  3239. $fullContent = $chatResult['fullContent'];
  3240. $usage = $chatResult['usage'];
  3241. }
  3242. // 处理获取到的剧本数据
  3243. $script_content = handleScriptWords($fullContent, $enable_emotion);
  3244. $result = [
  3245. 'origin_content' => $fullContent,
  3246. 'roles' => getProp($script_content, 'roles'),
  3247. 'words' => getProp($script_content, 'words'),
  3248. ];
  3249. // 文生文成功计费(normal 档):同时记录积分与 token 明细
  3250. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  3251. 'model' => $model,
  3252. 'source' => 'chatWithReasoner',
  3253. ], 'normal');
  3254. return $result;
  3255. }
  3256. public function resetParagraphAudio($data) {
  3257. $bid = getProp($data, 'bid');
  3258. $cid = getProp($data, 'cid');
  3259. $version_id = getProp($data, 'version_id');
  3260. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  3261. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  3262. 'generate_status' => '待制作',
  3263. 'updated_at' => date('Y-m-d H:i:s')
  3264. ]);
  3265. }
  3266. public function saveParagraphAudio($data) {
  3267. $bid = getProp($data, 'bid');
  3268. $cid = getProp($data, 'cid');
  3269. $version_id = getProp($data, 'version_id');
  3270. $sequence = getProp($data, 'sequence');
  3271. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  3272. // 获取所有情感
  3273. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3274. $emotion_list = array_flip($emotion_list);
  3275. // 获取音色支持情感
  3276. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  3277. $timbre_emotion = explode(',', $timbre_emotion);
  3278. $emotion = getProp($data, 'emotion');
  3279. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  3280. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3281. $list = [
  3282. 'bid' => $bid,
  3283. 'cid' => $cid,
  3284. 'version_id' => $version_id,
  3285. 'sequence' => $sequence,
  3286. 'role' => getProp($data, 'role'),
  3287. 'gender' => getProp($data, 'gender'),
  3288. 'text' => trim(getProp($data, 'text')),
  3289. 'emotion' => $emotion,
  3290. 'emotion_type' => $emotion_type,
  3291. 'voice_type' => getProp($data, 'voice_type'),
  3292. 'voice_name' => getProp($data, 'voice_name'),
  3293. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  3294. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  3295. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  3296. 'pitch' => getProp($data, 'pitch', 0),
  3297. // 'paragraph_audio_url' => '',
  3298. 'generate_status' => '制作中',
  3299. 'error_msg' => '',
  3300. 'updated_at' => date('Y-m-d H:i:s')
  3301. ];
  3302. $continue = false;
  3303. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  3304. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  3305. $list['generate_status'] = '制作成功';
  3306. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  3307. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  3308. $continue = true;
  3309. }
  3310. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  3311. if ($id) {
  3312. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  3313. }else {
  3314. $list['created_at'] = date('Y-m-d H:i:s');
  3315. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  3316. $boolen = $id ? true : false;
  3317. }
  3318. // 如果更新成功则加入查询队列
  3319. if ($boolen) {
  3320. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  3321. Redis::sadd($redis_key, $id);
  3322. }
  3323. if ($boolen && !$continue) {
  3324. $boolen = false;
  3325. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3326. // 根据ID通过API通知合成音频
  3327. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  3328. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  3329. $response = $result->getBody()->getContents();
  3330. $response_arr = json_decode($response, true);
  3331. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3332. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3333. Log::info('通知火山生成段落音频失败: '.$error_msg);
  3334. Utils::throwError('20003:通知火山生成段落音频失败');
  3335. }
  3336. $boolen = true;
  3337. }
  3338. return $boolen;
  3339. }
  3340. public function insertAudioEffect($data) {
  3341. $audio_id = getProp($data, 'audio_id');
  3342. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3343. $bid = getProp($chapter_audio, 'bid');
  3344. $version_id = getProp($chapter_audio, 'version_id');
  3345. $cid = getProp($chapter_audio, 'cid');
  3346. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3347. $audio_effect_json = getProp($data, 'audio_effect_json');
  3348. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  3349. try {
  3350. DB::beginTransaction();
  3351. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3352. if (!$count) {
  3353. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3354. }else {
  3355. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3356. }
  3357. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3358. 'audio_effect_status' => '添加中',
  3359. 'audio_effect_json' => $audio_effect_json,
  3360. 'updated_at' => date('Y-m-d H:i:s')
  3361. ]);
  3362. if (!$boolen1) {
  3363. DB::rollBack();
  3364. Utils::throwError('20003:更新生成数据失败');
  3365. }
  3366. $id = DB::table('mp_audio_tasks')->insertGetId([
  3367. 'audio_id' => $audio_id,
  3368. 'generate_status' => '执行中',
  3369. 'generate_json' => json_encode([], 256),
  3370. 'bid' => $bid,
  3371. 'book_name' => getProp($chapter_audio, 'book_name'),
  3372. 'version_id' => $version_id,
  3373. 'version_name' => getProp($chapter_audio, 'version_name'),
  3374. 'cid' => $cid,
  3375. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3376. 'task_name' => $task_name,
  3377. 'created_at' => date('Y-m-d H:i:s'),
  3378. 'updated_at' => date('Y-m-d H:i:s')
  3379. ]);
  3380. if (!$id) {
  3381. DB::rollBack();
  3382. Utils::throwError('20003:创建任务失败');
  3383. }
  3384. }catch (\Exception $e) {
  3385. DB::rollBack();
  3386. Utils::throwError('20003:'.$e->getMessage());
  3387. }
  3388. DB::commit();
  3389. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3390. // 根据ID通过API通知合成音频
  3391. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3392. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3393. $response = $result->getBody()->getContents();
  3394. $response_arr = json_decode($response, true);
  3395. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3396. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3397. Log::info('通知火山插入音效失败: '.$error_msg);
  3398. Utils::throwError('20003:通知火山插入音效失败');
  3399. }
  3400. return true;
  3401. }
  3402. public function insertBgm($data) {
  3403. $audio_id = getProp($data, 'audio_id');
  3404. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3405. $bid = getProp($chapter_audio, 'bid');
  3406. $version_id = getProp($chapter_audio, 'version_id');
  3407. $cid = getProp($chapter_audio, 'cid');
  3408. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3409. $bgm_json = getProp($data, 'bgm_json');
  3410. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3411. if (!$bgm_json) {
  3412. $bgm_json = getProp($data, 'audio_effect_json');
  3413. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3414. }
  3415. try {
  3416. DB::beginTransaction();
  3417. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3418. if (!$count) {
  3419. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3420. }else {
  3421. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3422. }
  3423. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3424. 'bgm_status' => '添加中',
  3425. 'bgm_json' => $bgm_json,
  3426. 'updated_at' => date('Y-m-d H:i:s')
  3427. ]);
  3428. if (!$boolen1) {
  3429. DB::rollBack();
  3430. Utils::throwError('20003:更新生成数据失败');
  3431. }
  3432. $id = DB::table('mp_audio_tasks')->insertGetId([
  3433. 'audio_id' => $audio_id,
  3434. 'generate_status' => '执行中',
  3435. 'generate_json' => json_encode([], 256),
  3436. 'bid' => $bid,
  3437. 'book_name' => getProp($chapter_audio, 'book_name'),
  3438. 'version_id' => $version_id,
  3439. 'version_name' => getProp($chapter_audio, 'version_name'),
  3440. 'cid' => $cid,
  3441. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3442. 'task_name' => $task_name,
  3443. 'created_at' => date('Y-m-d H:i:s'),
  3444. 'updated_at' => date('Y-m-d H:i:s')
  3445. ]);
  3446. if (!$id) {
  3447. DB::rollBack();
  3448. Utils::throwError('20003:创建任务失败');
  3449. }
  3450. }catch (\Exception $e) {
  3451. DB::rollBack();
  3452. Utils::throwError('20003:'.$e->getMessage());
  3453. }
  3454. DB::commit();
  3455. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3456. // 根据ID通过API通知合成音频
  3457. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3458. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3459. $response = $result->getBody()->getContents();
  3460. $response_arr = json_decode($response, true);
  3461. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3462. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3463. Log::info('通知火山插入bgm失败: '.$error_msg);
  3464. Utils::throwError('20003:通知火山插入bgm失败');
  3465. }
  3466. return true;
  3467. }
  3468. public function getParagraphAudios($data) {
  3469. $bid = getProp($data, 'bid');
  3470. $cid = getProp($data, 'cid');
  3471. $version_id = getProp($data, 'version_id');
  3472. $sequence = getProp($data, 'sequence');
  3473. // 获取已生成的音频
  3474. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  3475. if ($sequence) $query->where('sequence', $sequence);
  3476. $paragraph_audios = $query->orderBy('sequence')->get();
  3477. $result = [];
  3478. foreach($paragraph_audios as $item) {
  3479. $result[] = [
  3480. 'sequence' => getProp($item, 'sequence'),
  3481. 'role' => getProp($item, 'role'),
  3482. 'gender' => getProp($item, 'gender'),
  3483. 'text' => trim(getProp($item, 'text')),
  3484. 'emotion' => getProp($item, 'emotion'),
  3485. 'emotion_type' => getProp($item, 'emotion_type'),
  3486. 'voice_type' => getProp($item, 'voice_type'),
  3487. 'voice_name' => getProp($item, 'voice_name'),
  3488. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3489. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3490. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3491. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3492. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  3493. ];
  3494. }
  3495. return $result;
  3496. }
  3497. // 新增合成任务
  3498. public function addGenerateTask($data) {
  3499. $bid = getProp($data, 'bid');
  3500. $cid = getProp($data, 'cid');
  3501. $version_id = getProp($data, 'version_id');
  3502. $generate_json = getProp($data, 'generate_json');
  3503. // 获取已生成的音频
  3504. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  3505. $paragraph_list = [];
  3506. foreach($paragraph_audios as $item) {
  3507. $paragraph_list[getProp($item, 'sequence')] = [
  3508. 'role' => getProp($item, 'role'),
  3509. 'gender' => getProp($item, 'gender'),
  3510. 'text' => trim(getProp($item, 'text')),
  3511. 'emotion' => getProp($item, 'emotion'),
  3512. 'emotion_type' => getProp($item, 'emotion_type'),
  3513. 'voice_type' => getProp($item, 'voice_type'),
  3514. 'voice_name' => getProp($item, 'voice_name'),
  3515. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3516. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3517. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3518. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3519. ];
  3520. }
  3521. // 更新角色-音色信息
  3522. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  3523. $existed_role_info = json_decode($existed_role_info, true);
  3524. if (!$existed_role_info) $existed_role_info = [];
  3525. // 获取情感信息
  3526. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3527. $emotion_list = array_flip($emotion_list);
  3528. // 获取音色对应情感组
  3529. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  3530. $timbre_emotion_list = [];
  3531. foreach($timbre_emotions as $item) {
  3532. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  3533. }
  3534. // 构造生成音频的json
  3535. $words = json_decode($generate_json, true);
  3536. // 最终合成前的参数组
  3537. $mp_chapter_paragraph_audios = [];
  3538. $sequence = 1;
  3539. $complete_paragraph_sequences = [];
  3540. foreach($words as &$word) {
  3541. 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:参数格式有误');
  3542. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  3543. $role = getProp($word, 'role');
  3544. $word['gender'] = (int)$word['gender'];
  3545. // 判断音色对应情感是否支持,不支持则调整为中性
  3546. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  3547. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  3548. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  3549. if (isset($emotion_list[getProp($word, 'emotion')])) {
  3550. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  3551. }else {
  3552. $word['emotion'] = '中性';
  3553. $word['emotion_type'] = 'neutral';
  3554. }
  3555. $existed_role_info[$role] = [
  3556. 'timbre_type' => $word['voice_type'],
  3557. 'timbre_name' => $word['voice_name'],
  3558. 'emotion' => $word['emotion'],
  3559. 'emotion_type' => $word['emotion_type'],
  3560. 'speed_ratio' => $word['speed_ratio'],
  3561. 'loudness_ratio'=> $word['loudness_ratio'],
  3562. 'emotion_scale' => $word['emotion_scale'],
  3563. 'pitch' => $word['pitch']
  3564. ];
  3565. $word['paragraph_audio_url'] = '';
  3566. // 判断生成参数是否相同,相同则直接使用已生成的音频
  3567. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  3568. // 如果音频存在并且参数都未改变则使用已生成的音频
  3569. if (getProp($paragraph, 'paragraph_audio_url')) {
  3570. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  3571. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  3572. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  3573. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  3574. // {
  3575. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3576. // }
  3577. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3578. }
  3579. $tmp = $word;
  3580. // 组装章节分句音频数据
  3581. // $tmp['sequence'] = getProp($word, 'sequence');
  3582. // $tmp['text'] = getProp($word, 'text');
  3583. // $tmp['emotion'] = getProp($word, 'emotion');
  3584. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  3585. // $tmp['voice_name'] = getProp($word, 'voice_name');
  3586. // $tmp['voice_type'] = getProp($word, 'voice_type');
  3587. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  3588. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  3589. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  3590. $tmp['bid'] = $bid;
  3591. $tmp['version_id'] = $version_id;
  3592. $tmp['cid'] = $cid;
  3593. $tmp['sequence'] = $sequence;
  3594. $tmp['created_at'] = date('Y-m-d H:i:s');
  3595. $tmp['updated_at'] = date('Y-m-d H:i:s');
  3596. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  3597. $mp_chapter_paragraph_audios[] = $tmp;
  3598. $complete_paragraph_sequences[] = $sequence;
  3599. $sequence++;
  3600. }
  3601. $generate_json = json_encode($words, 256);
  3602. // 判断是否有未生成字幕的段落
  3603. $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();
  3604. if ($no_subtitle_sequences) {
  3605. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  3606. }
  3607. try {
  3608. DB::beginTransaction();
  3609. $role_info = json_encode($existed_role_info, 256);
  3610. $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')]);
  3611. if (!$boolen) {
  3612. DB::rollBack();
  3613. Utils::throwError('20003:更新角色信息失败');
  3614. }
  3615. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  3616. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  3617. if (!$count) {
  3618. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3619. }else {
  3620. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3621. }
  3622. $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')]);
  3623. if (!$boolen1) {
  3624. DB::rollBack();
  3625. Utils::throwError('20003:更新生成数据失败');
  3626. }
  3627. $id = DB::table('mp_audio_tasks')->insertGetId([
  3628. 'audio_id' => getProp($chapter_audio, 'id'),
  3629. 'generate_status' => '执行中',
  3630. 'generate_json' => $generate_json,
  3631. 'bid' => $bid,
  3632. 'book_name' => getProp($chapter_audio, 'book_name'),
  3633. 'version_id' => $version_id,
  3634. 'version_name' => getProp($chapter_audio, 'version_name'),
  3635. 'cid' => $cid,
  3636. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3637. 'task_name' => $task_name,
  3638. 'created_at' => date('Y-m-d H:i:s'),
  3639. 'updated_at' => date('Y-m-d H:i:s')
  3640. ]);
  3641. if (!$id) {
  3642. DB::rollBack();
  3643. Utils::throwError('20003:创建任务失败');
  3644. }
  3645. // 删除不在段落序号范围内的其他数据
  3646. if ($complete_paragraph_sequences) {
  3647. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  3648. }
  3649. // // 删除章节分句音频数据并重新插入
  3650. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  3651. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  3652. // if (!$boolen3) {
  3653. // DB::rollBack();
  3654. // Utils::throwError('20003:更新章节分句音频失败');
  3655. // }
  3656. } catch (\Exception $e) {
  3657. DB::rollBack();
  3658. Utils::throwError('20003:'.$e->getMessage());
  3659. }
  3660. DB::commit();
  3661. // 通知火山生成音频
  3662. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3663. // 根据ID通过API通知合成音频
  3664. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  3665. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  3666. $response = $result->getBody()->getContents();
  3667. $response_arr = json_decode($response, true);
  3668. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3669. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3670. Log::info('通知火山生成音频失败: '.$error_msg);
  3671. Utils::throwError('20003:通知火山生成音频失败');
  3672. }
  3673. return true;
  3674. }
  3675. public function timbreList($data) {
  3676. $gender = getProp($data, 'gender');
  3677. $timbre_name = getProp($data, 'voice_name');
  3678. $category_id = getProp($data, 'category_id');
  3679. $age_stage = getProp($data, 'age_stage');
  3680. $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');
  3681. if ($gender) {
  3682. $query->where('gender', $gender);
  3683. }
  3684. if ($timbre_name) {
  3685. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  3686. }
  3687. if ($category_id) {
  3688. $query->where(function ($query) use ($category_id) {
  3689. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  3690. });
  3691. }
  3692. if ($age_stage) {
  3693. $query->where('age_stage', $age_stage);
  3694. }
  3695. $list = $query->get()->map(function ($value) {
  3696. $value = (array)$value;
  3697. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  3698. return $value;
  3699. })->toArray();
  3700. return $list;
  3701. }
  3702. // 生成火山临时token
  3703. public function setStsToken() {
  3704. // ************* 配置参数 *************
  3705. $method = 'GET';
  3706. $service = 'sts';
  3707. $host = 'open.volcengineapi.com';
  3708. $region = env('VOLC_REGION');
  3709. $endpoint = 'https://open.volcengineapi.com';
  3710. // $endpoint = 'https://tos-cn-beijing.volces.com';
  3711. $access_key = env('VOLC_AK');
  3712. $secret_key = env('VOLC_SK');
  3713. // 获取缓存中的token,如果没有则请求接口
  3714. $token = Redis::get('volc_sts_token');
  3715. if (!$token) {
  3716. // 查询参数
  3717. $query_parameters = [
  3718. 'Action' => 'AssumeRole',
  3719. 'RoleSessionName' => 'user@zw',
  3720. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  3721. 'Version' => '2018-01-01'
  3722. ];
  3723. // 生成URL编码的查询字符串
  3724. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  3725. // 获取签名头信息
  3726. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  3727. // 构建完整URL
  3728. $request_url = $endpoint . '?' . $request_parameters;
  3729. $client = new Client(['verify' => false]);
  3730. $response = $client->get($request_url, ['headers' => $headers]);
  3731. $response_arr = json_decode($response->getBody()->getContents(), true);
  3732. $result = [
  3733. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  3734. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  3735. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  3736. 'Region' => env('VOLC_REGION'),
  3737. 'Endpoint' => env('VOLC_END_POINT'),
  3738. 'Bucket' => env('VOLC_BUCKET'),
  3739. ];
  3740. // 缓存token
  3741. Redis::setex('volc_sts_token', 3000, json_encode($result));
  3742. return $result;
  3743. } else {
  3744. return json_decode($token, true);
  3745. }
  3746. // $response = $response['Response'];
  3747. // $access_key = $response['Credentials']['AccessKeyId'];
  3748. // $secret_key = $response['Credentials']['AccessKeySecret'];
  3749. // $security_token = $response['Credentials']['SecurityToken'];
  3750. // $expiration = $response['Credentials']['Expiration'];
  3751. // dd($response_arr);
  3752. }
  3753. public function emotionGroups($data) {
  3754. $id = getProp($data, 'group_id');
  3755. $group_name = getProp($data, 'group_name');
  3756. $voice_type = getProp($data, 'voice_type');
  3757. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  3758. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  3759. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  3760. if ($group_name) {
  3761. $query->where('group_name', 'like', "%{$group_name}%");
  3762. }
  3763. if ($id) {
  3764. $query->where('id', $id);
  3765. }
  3766. if ($voice_type) {
  3767. $query->where('voice_type', $voice_type);
  3768. }
  3769. return $query->orderBy('id')->get()->map(function ($value) {
  3770. return (array)$value;
  3771. })->toArray();
  3772. }
  3773. private function sign($key, $msg) {
  3774. return hash_hmac('sha256', $msg, $key, true);
  3775. }
  3776. // 生成签名密钥
  3777. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  3778. $kDate = $this->sign($key, $dateStamp);
  3779. $kRegion = $this->sign($kDate, $regionName);
  3780. $kService = $this->sign($kRegion, $serviceName);
  3781. $kSigning = $this->sign($kService, 'request');
  3782. return $kSigning;
  3783. }
  3784. // 获取签名头信息
  3785. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  3786. $contenttype = 'application/x-www-form-urlencoded';
  3787. $accept = 'application/json';
  3788. // 获取当前UTC时间
  3789. $t = new DateTime('now', new DateTimeZone('UTC'));
  3790. $xdate = $t->format('Ymd\THis\Z');
  3791. $datestamp = $t->format('Ymd');
  3792. // 1. 拼接规范请求串
  3793. $canonical_uri = '/';
  3794. $canonical_querystring = $request_parameters;
  3795. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  3796. $signed_headers = 'content-type;host;x-date';
  3797. // 空请求体的SHA256哈希
  3798. $payload_hash = hash('sha256', '');
  3799. $canonical_request = implode("\n", [
  3800. $method,
  3801. $canonical_uri,
  3802. $canonical_querystring,
  3803. $canonical_headers,
  3804. $signed_headers,
  3805. $payload_hash
  3806. ]);
  3807. // 2. 拼接待签名字符串
  3808. $algorithm = 'HMAC-SHA256';
  3809. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  3810. $hashed_canonical_request = hash('sha256', $canonical_request);
  3811. $string_to_sign = implode("\n", [
  3812. $algorithm,
  3813. $xdate,
  3814. $credential_scope,
  3815. $hashed_canonical_request
  3816. ]);
  3817. // 3. 计算签名
  3818. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  3819. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  3820. // 4. 添加签名到请求头
  3821. $authorization_header = sprintf(
  3822. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  3823. $algorithm,
  3824. $access_key,
  3825. $credential_scope,
  3826. $signed_headers,
  3827. $signature
  3828. );
  3829. return [
  3830. 'Accept' => $accept,
  3831. 'Content-Type' => $contenttype,
  3832. 'X-Date' => $xdate,
  3833. 'Authorization' => $authorization_header
  3834. ];
  3835. }
  3836. // 文字合成语音(火山引擎)
  3837. public function tts($data) {
  3838. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  3839. $headers = [
  3840. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  3841. 'Content-Type' => 'application/json; charset=UTF-8'
  3842. ];
  3843. $post_data = [
  3844. 'app' => [
  3845. 'appid' => env('VOLC_APPID'),
  3846. 'token' => env('VOLC_TOKEN'),
  3847. 'cluster' => 'volcano_tts'
  3848. ],
  3849. 'user' => [
  3850. 'uid' => 'mp_audio'
  3851. ],
  3852. // 'audio' => [
  3853. // 'voice_type' =>
  3854. // ],
  3855. ];
  3856. }
  3857. public function scriptList($data) {
  3858. $uid = Site::getUid();
  3859. $script_id = getProp($data, 'script_id');
  3860. $script_name = getProp($data, 'script_name');
  3861. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  3862. if ($script_id) {
  3863. $query->where('id', $script_id);
  3864. }
  3865. if ($script_name) {
  3866. $query->where('script_name', 'like', "%{$script_name}%");
  3867. }
  3868. return $query->orderBy('created_at', 'desc')->paginate(12);
  3869. }
  3870. public function scripts($data) {
  3871. $uid = Site::getUid();
  3872. $script_id = getProp($data, 'script_id');
  3873. $script_name = getProp($data, 'script_name');
  3874. $is_products = getProp($data, 'is_products');
  3875. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  3876. if ($script_id) {
  3877. $query->where('id', $script_id);
  3878. }
  3879. if ($is_products !== '') {
  3880. $query->where('is_products', $is_products);
  3881. }
  3882. if ($script_name) {
  3883. $query->where('script_name', 'like', "%{$script_name}%");
  3884. }
  3885. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  3886. return (array)$value;
  3887. })->toArray();
  3888. }
  3889. public function scriptInfo($data) {
  3890. $uid = Site::getUid();
  3891. $script_id = getProp($data, 'script_id');
  3892. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  3893. // ->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();
  3894. ->selectRaw('id as script_id, script_name')->first();
  3895. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3896. $script = (array)$script;
  3897. // 获取分集组信息
  3898. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  3899. ->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')
  3900. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  3901. $value = (array)$value;
  3902. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  3903. return (array)$value;
  3904. })->toArray();
  3905. $script['group'] = $groups;
  3906. return $script;
  3907. }
  3908. public function createScript($data) {
  3909. $script_name = getProp($data, 'script_name');
  3910. $uid = Site::getUid(); // 获取当前用户ID
  3911. $cpid = Site::getCpid(); // 获取当前公司组ID
  3912. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  3913. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  3914. $script_name .= '_'.date('YmdHis');
  3915. }
  3916. return DB::table('mp_scripts')->insertGetId([
  3917. 'script_name' => $script_name,
  3918. 'user_id' => $uid,
  3919. 'cpid' => $cpid,
  3920. 'created_at' => date('Y-m-d H:i:s'),
  3921. 'updated_at' => date('Y-m-d H:i:s')
  3922. ]);
  3923. }
  3924. public function editScript($data) {
  3925. $script_id = getProp($data, 'script_id');
  3926. $script_name = getProp($data, 'script_name');
  3927. $uid = Site::getUid(); // 获取当前用户ID
  3928. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  3929. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  3930. if ($id && (int)$id !== (int)$script_id) {
  3931. $script_name .= '_'.date('YmdHis');
  3932. }
  3933. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3934. 'script_name' => $script_name,
  3935. 'updated_at' => date('Y-m-d H:i:s')
  3936. ]);
  3937. }
  3938. public function delScript($data) {
  3939. $script_id = getProp($data, 'script_id');
  3940. $uid = Site::getUid(); // 获取当前用户ID
  3941. if (!$script_id) Utils::throwError('20003:请选择剧本');
  3942. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3943. 'is_deleted' => 1,
  3944. 'updated_at' => date('Y-m-d H:i:s')
  3945. ]);
  3946. }
  3947. public function createEpisode($data) {
  3948. $script_id = getProp($data, 'script_id');
  3949. $group_name = getProp($data, 'group_name');
  3950. $remark = getProp($data, 'remark');
  3951. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  3952. $uid = Site::getUid(); // 获取当前用户ID
  3953. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  3954. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  3955. $group_name .= '_'.date('YmdHis');
  3956. }
  3957. return DB::table('mp_script_episode_group')->insertGetId([
  3958. 'script_id' => $script_id,
  3959. 'group_name' => $group_name,
  3960. 'user_id' => $uid,
  3961. 'remark' => $remark,
  3962. 'created_at' => date('Y-m-d H:i:s'),
  3963. 'updated_at' => date('Y-m-d H:i:s')
  3964. ]);
  3965. }
  3966. public function editEpisode($data) {
  3967. $group_id = getProp($data, 'group_id');
  3968. $start_episode_number = getProp($data, 'start_episode_number');
  3969. $end_episode_number = getProp($data, 'end_episode_number');
  3970. $group_name = getProp($data, 'group_name');
  3971. $uid = Site::getUid(); // 获取当前用户ID
  3972. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  3973. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  3974. if ($id && (int)$id !== (int)$group_id) {
  3975. $group_name .= '_'.date('YmdHis');
  3976. }
  3977. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3978. 'group_name' => $group_name,
  3979. 'start_episode_number' => $start_episode_number,
  3980. 'end_episode_number' => $end_episode_number,
  3981. 'updated_at' => date('Y-m-d H:i:s')
  3982. ]);
  3983. }
  3984. public function delEpisode($data) {
  3985. $group_id = getProp($data, 'group_id');
  3986. $uid = Site::getUid(); // 获取当前用户ID
  3987. if (!$group_id) Utils::throwError('20003:请选择分集');
  3988. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3989. 'is_deleted' => 1,
  3990. 'updated_at' => date('Y-m-d H:i:s')
  3991. ]);
  3992. }
  3993. /**
  3994. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3995. *
  3996. * @param array $data 包含以下参数:
  3997. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3998. * - question: 用户问题(可选)
  3999. * - model: 使用的模型(r1 或 v3,默认 v3)
  4000. * @return \Generator 返回生成器,用于流式输出
  4001. */
  4002. public function generateEpisodes($data) {
  4003. // 文生文计费预检(special 档,每次调用扣 10)
  4004. $uid = Site::getUid();
  4005. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  4006. $script_id = getProp($data, 'script_id');
  4007. $group_id = getProp($data, 'group_id');
  4008. // $file = getProp($data, 'file');
  4009. $file = '';
  4010. $content = getProp($data, 'content', '');
  4011. // $bid = getProp($data, 'bid', 0);
  4012. $bid = 0;
  4013. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4014. if (!$group) {
  4015. Utils::throwError('20003:剧本分集不存在');
  4016. }
  4017. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  4018. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  4019. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  4020. $prompt = getProp($data, 'prompt');
  4021. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  4022. $model = getProp($data, 'model');
  4023. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4024. Utils::throwError('20003:该模型不存在!');
  4025. }
  4026. // 检查是否存在重叠的剧集序号范围
  4027. $exists_groups = DB::table('mp_script_episode_group')
  4028. ->where('script_id', $script_id)
  4029. ->where('id', '<>', $group_id) // 排除当前组
  4030. ->where('is_deleted', 0)
  4031. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4032. // 检查新范围是否与现有范围重叠
  4033. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4034. // 新范围的开始在现有范围内
  4035. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4036. ->where('end_episode_number', '>=', $start_episode_sequence);
  4037. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4038. // 新范围的结束在现有范围内
  4039. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4040. ->where('end_episode_number', '>=', $end_episode_sequence);
  4041. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4042. // 新范围完全包含现有范围
  4043. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4044. ->where('end_episode_number', '<=', $end_episode_sequence);
  4045. });
  4046. })
  4047. ->select('start_episode_number', 'end_episode_number')
  4048. ->get();
  4049. if ($exists_groups->isNotEmpty()) {
  4050. $conflict_ranges = [];
  4051. foreach ($exists_groups as $group) {
  4052. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4053. }
  4054. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4055. }
  4056. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4057. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4058. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4059. if ($model === 'deepseek-chat') {
  4060. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4061. $model = 'deepseek-v4-flash';
  4062. $thinkingMode = 'disabled';
  4063. } elseif ($model === 'deepseek-reasoner') {
  4064. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4065. $model = 'deepseek-v4-flash';
  4066. $thinkingMode = 'enabled';
  4067. }
  4068. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4069. if (!$script) {
  4070. Utils::throwError('20003:剧本不存在');
  4071. }
  4072. $content = getProp($group, 'content');
  4073. if (!$file && !$content && !$bid) {
  4074. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4075. }
  4076. // 提取文件内容
  4077. if ($file) {
  4078. $content = $this->extractFileContent($file);
  4079. if (!$content) {
  4080. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4081. }
  4082. } elseif ($bid) {
  4083. $content = $this->getContentByBid($bid);
  4084. if (!$content) {
  4085. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4086. }
  4087. } elseif ($content) {
  4088. $content = filterContent($content);
  4089. } elseif ($prompt) {
  4090. $content = filterContent($prompt);
  4091. } else {
  4092. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4093. }
  4094. // 构建消息
  4095. $messages = [
  4096. $this->sys_message,
  4097. [
  4098. 'role' => 'user',
  4099. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4100. ]
  4101. ];
  4102. $post_data = [
  4103. 'model' => $model,
  4104. 'messages' => $messages,
  4105. // 'max_tokens' => 8192,
  4106. 'temperature' => 0.7,
  4107. 'frequency_penalty' => 0,
  4108. 'presence_penalty' => 0,
  4109. 'thinking' => ['type' => $thinkingMode],
  4110. 'response_format' => ['type' => 'text'],
  4111. 'stream' => true
  4112. ];
  4113. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4114. // 根据模型类型选择调用方法
  4115. $fullContent = '';
  4116. $fullReasoningContent = '';
  4117. $usage = [];
  4118. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4119. // DeepSeek 官方模型使用 DeepSeek API
  4120. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4121. } else if (in_array($model, $this->gpt_text_models)) {
  4122. // GPT-5.4 模型使用 TokenRouter API
  4123. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4124. } else if (in_array($model, $this->gemini_text_models)) {
  4125. // Gemini 模型使用 Gemini API
  4126. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4127. } else {
  4128. // 其他模型使用火山引擎API
  4129. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4130. }
  4131. // 处理流式输出
  4132. foreach ($streamGenerator as $chunk) {
  4133. if (isset($chunk['type'])) {
  4134. if ($chunk['type'] === 'done') {
  4135. // 最终结果
  4136. $fullContent = $chunk['full_content'];
  4137. $fullReasoningContent = $chunk['full_reasoning'];
  4138. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4139. } else {
  4140. // 逐块yield数据
  4141. yield $chunk;
  4142. }
  4143. }
  4144. }
  4145. dLog('deepseek')->info('完整内容: '.$fullContent);
  4146. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4147. // 处理完整内容并返回最终结果
  4148. $script_arr = [];
  4149. if ($fullContent) {
  4150. $script_arr = extractScriptContent($fullContent);
  4151. }
  4152. logDB('deepseek', 'info', '解析内容', $script_arr);
  4153. if (!$script_arr['episodes']) {
  4154. Utils::throwError('20003:未生成剧本相关信息');
  4155. // yield [
  4156. // 'type' => 'done',
  4157. // 'script' => $script_arr,
  4158. // 'msg' => '未生成剧本相关信息',
  4159. // 'answer' => $fullContent,
  4160. // 'reasoning' => $fullReasoningContent,
  4161. // 'usage' => $usage
  4162. // ];
  4163. // return ;
  4164. }
  4165. try {
  4166. DB::beginTransaction();
  4167. // // 返回前保存剧本内容
  4168. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4169. // 'content' => $content,
  4170. // 'updated_at' => date('Y-m-d H:i:s')
  4171. // ]);
  4172. // if (!$boolen) {
  4173. // Utils::throwError('20003:保存剧本内容失败');
  4174. // }
  4175. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4176. // 'start_episode_number' => $start_episode_sequence,
  4177. // 'end_episode_number' => $end_episode_sequence,
  4178. // 'updated_at' => date('Y-m-d H:i:s')
  4179. // ]);
  4180. // if (!$boolen1) {
  4181. // Utils::throwError('20003:保存分集失败');
  4182. // }
  4183. $episode_content = '';
  4184. $episodes = [];
  4185. foreach ($script_arr['episodes'] as $item) {
  4186. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  4187. // $episodes[] = [
  4188. // 'script_id' => $script_id,
  4189. // 'episode_number' => $item['episode_number'],
  4190. // 'episode_name' => $item['episode_name'],
  4191. // 'episode_content' => $item['episode_content'],
  4192. // 'created_at' => date('Y-m-d H:i:s'),
  4193. // 'updated_at' => date('Y-m-d H:i:s'),
  4194. // ];
  4195. }
  4196. if ($episode_content) {
  4197. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4198. 'episode_content' => $episode_content,
  4199. 'updated_at' => date('Y-m-d H:i:s')
  4200. ]);
  4201. if (!$boolen2) {
  4202. Utils::throwError('20003:保存分集内容失败');
  4203. }
  4204. }else {
  4205. Utils::throwError('20003:分集剧本解析失败');
  4206. }
  4207. // 文生文成功计费(special 档):与落库同事务
  4208. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  4209. 'model' => $model,
  4210. 'script_id' => $script_id,
  4211. 'group_id' => $group_id,
  4212. 'source' => 'generateEpisodes',
  4213. ]);
  4214. }catch (\Exception $e) {
  4215. DB::rollBack();
  4216. Utils::throwError('20003:'.$e->getMessage());
  4217. }
  4218. DB::commit();
  4219. yield [
  4220. 'type' => 'done',
  4221. 'script' => $script_arr,
  4222. 'episode_content' => $episode_content,
  4223. 'answer' => $fullContent,
  4224. 'reasoning' => $fullReasoningContent,
  4225. 'usage' => $usage
  4226. ];
  4227. }
  4228. public function chatWithFileStream($data) {
  4229. // 剧本解析资产表计费预检(special 档)
  4230. $uid = Site::getUid();
  4231. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  4232. $script_id = getProp($data, 'script_id');
  4233. $group_id = getProp($data, 'group_id');
  4234. $file = getProp($data, 'file');
  4235. $content = getProp($data, 'content', '');
  4236. $bid = getProp($data, 'bid', 0);
  4237. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4238. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4239. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  4240. $prompt = getProp($data, 'prompt');
  4241. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4242. if (!empty($prompt)) {
  4243. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4244. }
  4245. $question = getProp($data, 'question', $baseQuestion);
  4246. $model = getProp($data, 'model');
  4247. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4248. Utils::throwError('20003:该模型不存在!');
  4249. }
  4250. // 检查是否存在重叠的剧集序号范围
  4251. $exists_groups = DB::table('mp_script_episode_group')
  4252. ->where('script_id', $script_id)
  4253. ->where('id', '<>', $group_id)
  4254. ->where('is_deleted', 0)
  4255. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4256. // 检查新范围是否与现有范围重叠
  4257. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4258. // 新范围的开始在现有范围内
  4259. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4260. ->where('end_episode_number', '>=', $start_episode_sequence);
  4261. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4262. // 新范围的结束在现有范围内
  4263. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4264. ->where('end_episode_number', '>=', $end_episode_sequence);
  4265. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4266. // 新范围完全包含现有范围
  4267. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4268. ->where('end_episode_number', '<=', $end_episode_sequence);
  4269. });
  4270. })
  4271. ->select('start_episode_number', 'end_episode_number')
  4272. ->get();
  4273. if ($exists_groups->isNotEmpty()) {
  4274. $conflict_ranges = [];
  4275. foreach ($exists_groups as $group) {
  4276. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4277. }
  4278. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4279. }
  4280. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4281. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4282. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4283. if ($model === 'deepseek-chat') {
  4284. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4285. $model = 'deepseek-v4-flash';
  4286. $thinkingMode = 'disabled';
  4287. } elseif ($model === 'deepseek-reasoner') {
  4288. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4289. $model = 'deepseek-v4-flash';
  4290. $thinkingMode = 'enabled';
  4291. }
  4292. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4293. if (!$script) {
  4294. Utils::throwError('20003:剧本不存在');
  4295. }
  4296. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4297. if (!$group) {
  4298. Utils::throwError('20003:剧本分集不存在');
  4299. }
  4300. if (!$file && !$content && !$bid) {
  4301. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4302. }
  4303. // 提取文件内容
  4304. if ($file) {
  4305. $content = $this->extractFileContent($file);
  4306. if (!$content) {
  4307. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4308. }
  4309. } elseif ($bid) {
  4310. $content = $this->getContentByBid($bid);
  4311. if (!$content) {
  4312. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4313. }
  4314. } elseif ($content) {
  4315. $content = filterContent($content);
  4316. } elseif ($prompt) {
  4317. $content = filterContent($prompt);
  4318. } else {
  4319. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4320. }
  4321. // 构建消息
  4322. $messages = [
  4323. [
  4324. 'role' => 'system',
  4325. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4326. 强制要求:\n
  4327. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4328. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4329. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  4330. 普通要求:\n
  4331. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  4332. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  4333. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  4334. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  4335. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  4336. 示例如下:\n
  4337. ###剧本名:西昆仑
  4338. ###故事梗概
  4339. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4340. ###剧本亮点
  4341. 亮点1:绝境奇药,生死一线
  4342. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4343. 亮点2:结拜兄妹,化解尴尬
  4344. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4345. 亮点3:纤发夺命,情愫暗涌
  4346. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4347. ###人物关系
  4348. 阿雪与梁萧之间存在兄妹之情。
  4349. ###核心矛盾
  4350. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4351. ###主体列表
  4352. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  4353. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  4354. 阴阳球:天地异宝,能化生精气,救人于危难。
  4355. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  4356. ###美术风格
  4357. 基础画风风格词:厚涂古风
  4358. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4359. ###场景列表
  4360. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  4361. [
  4362. 'role' => 'user',
  4363. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4364. ]
  4365. ];
  4366. $post_data = [
  4367. 'model' => $model,
  4368. 'messages' => $messages,
  4369. // 'max_tokens' => 8192,
  4370. 'temperature' => 0.7,
  4371. 'frequency_penalty' => 0,
  4372. 'presence_penalty' => 0,
  4373. 'thinking' => ['type' => $thinkingMode],
  4374. 'response_format' => ['type' => 'text'],
  4375. 'stream' => true
  4376. ];
  4377. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4378. // 根据模型类型选择调用方法
  4379. $fullContent = '';
  4380. $fullReasoningContent = '';
  4381. $usage = [];
  4382. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4383. // DeepSeek 官方模型使用 DeepSeek API
  4384. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4385. } else if (in_array($model, $this->gpt_text_models)) {
  4386. // GPT-5.4 模型使用 TokenRouter API
  4387. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4388. } else if (in_array($model, $this->gemini_text_models)) {
  4389. // Gemini 模型使用 Gemini API
  4390. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4391. } else {
  4392. // 其他模型使用火山引擎API
  4393. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4394. }
  4395. // 处理流式输出
  4396. foreach ($streamGenerator as $chunk) {
  4397. if (isset($chunk['type'])) {
  4398. if ($chunk['type'] === 'done') {
  4399. // 最终结果
  4400. $fullContent = $chunk['full_content'];
  4401. $fullReasoningContent = $chunk['full_reasoning'];
  4402. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4403. } else {
  4404. // 逐块yield数据
  4405. yield $chunk;
  4406. }
  4407. }
  4408. }
  4409. dLog('deepseek')->info('完整内容: '.$fullContent);
  4410. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4411. // 处理完整内容并返回最终结果
  4412. $script_arr = [];
  4413. if ($fullContent) {
  4414. $script_arr = extractScriptContent($fullContent);
  4415. }
  4416. logDB('deepseek', 'info', '解析内容', $script_arr);
  4417. if (!$script_arr['roles']) {
  4418. Utils::throwError('20003:未生成剧本相关信息');
  4419. // yield [
  4420. // 'type' => 'done',
  4421. // 'script' => $script_arr,
  4422. // 'msg' => '未生成剧本相关信息',
  4423. // 'answer' => $fullContent,
  4424. // 'reasoning' => $fullReasoningContent,
  4425. // 'usage' => $usage
  4426. // ];
  4427. }
  4428. try {
  4429. DB::beginTransaction();
  4430. // // 返回前保存剧本内容
  4431. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4432. // 'content' => $content,
  4433. // 'status' => '解析完成',
  4434. // 'updated_at' => date('Y-m-d H:i:s')
  4435. // ]);
  4436. // if (!$boolen) {
  4437. // Utils::throwError('20003:保存剧本内容失败');
  4438. // }
  4439. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4440. 'start_episode_number' => $start_episode_sequence,
  4441. 'end_episode_number' => $end_episode_sequence,
  4442. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4443. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4444. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4445. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4446. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4447. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4448. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4449. 'status' => '解析完成',
  4450. 'content' => $content,
  4451. 'updated_at' => date('Y-m-d H:i:s')
  4452. ]);
  4453. if (!$boolen1) {
  4454. Utils::throwError('20003:保存分集失败');
  4455. }
  4456. // 剧本解析资产表成功计费(special 档):与落库同事务
  4457. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  4458. 'model' => $model,
  4459. 'script_id' => $script_id,
  4460. 'group_id' => $group_id,
  4461. 'source' => 'chatWithFileStream',
  4462. ], 'special');
  4463. // $episodes = [];
  4464. // foreach ($script_arr['episodes'] as $item) {
  4465. // $episodes[] = [
  4466. // 'script_id' => $script_id,
  4467. // 'episode_number' => $item['episode_number'],
  4468. // 'episode_name' => $item['episode_name'],
  4469. // 'episode_content' => $item['episode_content'],
  4470. // 'created_at' => date('Y-m-d H:i:s'),
  4471. // 'updated_at' => date('Y-m-d H:i:s'),
  4472. // ];
  4473. // }
  4474. // if ($episodes) {
  4475. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4476. // if (!$boolen2) {
  4477. // Utils::throwError('20003:保存分集内容失败');
  4478. // }
  4479. // }else {
  4480. // Utils::throwError('20003:分集剧本解析失败');
  4481. // }
  4482. }catch (\Exception $e) {
  4483. DB::rollBack();
  4484. Utils::throwError('20003:'.$e->getMessage());
  4485. }
  4486. DB::commit();
  4487. yield [
  4488. 'type' => 'done',
  4489. 'script' => $script_arr,
  4490. 'answer' => $fullContent,
  4491. 'reasoning' => $fullReasoningContent,
  4492. 'usage' => $usage
  4493. ];
  4494. }
  4495. /**
  4496. * 上传文件识别文字内容并与 DeepSeek 进行对话
  4497. *
  4498. * @param array $data 包含以下参数:
  4499. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4500. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  4501. * - model: 使用的模型(r1 或 v3,默认 v3)
  4502. * @return array
  4503. */
  4504. public function chatWithFile($data) {
  4505. // 剧本解析资产表计费预检(special 档)
  4506. $uid = Site::getUid();
  4507. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  4508. $script_id = getProp($data, 'script_id');
  4509. $file = getProp($data, 'file');
  4510. $content = getProp($data, 'content', '');
  4511. $bid = getProp($data, 'bid', 0);
  4512. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4513. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4514. $prompt = getProp($data, 'prompt');
  4515. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4516. if (!empty($prompt)) {
  4517. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4518. }
  4519. $question = getProp($data, 'question', $baseQuestion);
  4520. // 处理文本模型
  4521. $model = getProp($data, 'model');
  4522. if (!$model) {
  4523. // 用户没有输入,使用默认值
  4524. $model = 'doubao-seed-2-0-mini-260215';
  4525. }
  4526. // 验证模型是否在可用模型表中
  4527. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4528. $model = 'doubao-seed-2-0-mini-260215';
  4529. }
  4530. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4531. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4532. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4533. if ($model === 'deepseek-chat') {
  4534. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4535. $model = 'deepseek-v4-flash';
  4536. $thinkingMode = 'disabled';
  4537. } elseif ($model === 'deepseek-reasoner') {
  4538. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4539. $model = 'deepseek-v4-flash';
  4540. $thinkingMode = 'enabled';
  4541. }
  4542. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4543. if (!$script) {
  4544. Utils::throwError('20003:剧本不存在');
  4545. }
  4546. if (!$file && !$content && !$bid) {
  4547. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4548. }
  4549. // 提取文件内容
  4550. if ($file) {
  4551. $content = $this->extractFileContent($file);
  4552. if (!$content) {
  4553. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4554. }
  4555. } elseif ($bid) {
  4556. $content = $this->getContentByBid($bid);
  4557. if (!$content) {
  4558. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4559. }
  4560. } elseif ($content) {
  4561. $content = filterContent($content);
  4562. } elseif ($prompt) {
  4563. $content = filterContent($prompt);
  4564. } else {
  4565. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4566. }
  4567. // 构建消息
  4568. $messages = [
  4569. $this->sys_message,
  4570. [
  4571. 'role' => 'user',
  4572. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4573. ]
  4574. ];
  4575. $post_data = [
  4576. 'model' => $model,
  4577. 'messages' => $messages,
  4578. // 'max_tokens' => 8192,
  4579. 'temperature' => 0.7,
  4580. 'frequency_penalty' => 0,
  4581. 'presence_penalty' => 0,
  4582. 'thinking' => ['type' => $thinkingMode],
  4583. 'response_format' => ['type' => 'text'],
  4584. 'stream' => false
  4585. ];
  4586. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4587. // 根据模型类型选择调用方法
  4588. $fullContent = '';
  4589. $usage = [];
  4590. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4591. // DeepSeek 官方模型使用 DeepSeek API
  4592. $chatResult = $this->chatOnly($post_data);
  4593. } else if (in_array($model, $this->gpt_text_models)) {
  4594. // GPT-5.4 模型使用 TokenRouter API
  4595. $chatResult = $this->gpt54ChatOnly($post_data);
  4596. } else {
  4597. // 其他模型使用火山引擎API
  4598. $chatResult = $this->volcEngineChatCompletion($post_data);
  4599. }
  4600. if (is_array($chatResult)) {
  4601. $fullContent = $chatResult['fullContent'];
  4602. $usage = $chatResult['usage'];
  4603. }
  4604. $script_arr = [];
  4605. // 处理结果
  4606. if ($fullContent) {
  4607. $script_arr = extractScriptContent($fullContent);
  4608. }
  4609. // 返回前保存剧本内容
  4610. DB::table('mp_scripts')->where('id', $script_id)->update([
  4611. 'content' => $content,
  4612. 'updated_at' => date('Y-m-d H:i:s')
  4613. ]);
  4614. // 剧本解析资产表成功计费(special 档):同时记录积分与 token 明细
  4615. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  4616. 'model' => $model,
  4617. 'script_id' => $script_id,
  4618. 'source' => 'chatWithFile',
  4619. ], 'special');
  4620. return [
  4621. 'script' => $script_arr,
  4622. 'answer' => $fullContent,
  4623. 'usage' => $usage
  4624. ];
  4625. }
  4626. public function getEpisodeContent($data) {
  4627. $group_id = getProp($data, 'group_id');
  4628. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  4629. }
  4630. public function saveEpisodeContent($data) {
  4631. $script_id = getProp($data, 'script_id');
  4632. $group_id = getProp($data, 'group_id');
  4633. $start_episode_sequence = getProp($data, 'start_episode_number');
  4634. $end_episode_sequence = getProp($data, 'end_episode_number');
  4635. // 检查是否存在重叠的剧集序号范围
  4636. $exists_groups = DB::table('mp_script_episode_group')
  4637. ->where('script_id', $script_id)
  4638. ->where('id', '<>', $group_id) // 排除当前组
  4639. ->where('is_deleted', 0)
  4640. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4641. // 检查新范围是否与现有范围重叠
  4642. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4643. // 新范围的开始在现有范围内
  4644. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4645. ->where('end_episode_number', '>=', $start_episode_sequence);
  4646. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4647. // 新范围的结束在现有范围内
  4648. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4649. ->where('end_episode_number', '>=', $end_episode_sequence);
  4650. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4651. // 新范围完全包含现有范围
  4652. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4653. ->where('end_episode_number', '<=', $end_episode_sequence);
  4654. });
  4655. })
  4656. ->select('start_episode_number', 'end_episode_number')
  4657. ->get();
  4658. if ($exists_groups->isNotEmpty()) {
  4659. $conflict_ranges = [];
  4660. foreach ($exists_groups as $group) {
  4661. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4662. }
  4663. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4664. }
  4665. $episode_content = getProp($data, 'episode_content');
  4666. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  4667. 'content' => $episode_content,
  4668. 'start_episode_number' => $start_episode_sequence,
  4669. 'end_episode_number' => $end_episode_sequence,
  4670. 'updated_at' => date('Y-m-d H:i:s')
  4671. ]);
  4672. $script_arr =getProp($data, 'script', []);
  4673. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  4674. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4675. $script_id = getProp($data, 'script_id');
  4676. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  4677. try {
  4678. DB::beginTransaction();
  4679. $update_data = [
  4680. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4681. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4682. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4683. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4684. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4685. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4686. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4687. 'status' => 3,
  4688. 'start_episode_sequence' => $start_episode_sequence,
  4689. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  4690. 'episode_num' => count($script_arr['episodes']),
  4691. 'updated_at' => date('Y-m-d H:i:s')
  4692. ];
  4693. // 保存剧本内容
  4694. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  4695. if (!$boolen) {
  4696. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  4697. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  4698. Utils::throwError('20003:剧本内容保存失败');
  4699. }
  4700. // 保存分集内容
  4701. // 删除历史分集内容
  4702. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  4703. $episodes = [];
  4704. $sequence = 1;
  4705. foreach ($script_arr['episodes'] as $episode) {
  4706. $segment_number = 1;
  4707. foreach($episode['segments'] as $segment) {
  4708. $episodes[] = [
  4709. 'script_id' => $script_id,
  4710. 'episode_number' => $episode['episode_number'],
  4711. 'title' => $episode['title'],
  4712. // 'content' => $episode['content'],
  4713. 'content' => '',
  4714. 'segment_number' => $segment_number,
  4715. 'segment_content' => $segment['segment_content'],
  4716. 'sequence' => $sequence,
  4717. 'created_at' => date('Y-m-d H:i:s'),
  4718. 'updated_at' => date('Y-m-d H:i:s')
  4719. ];
  4720. $sequence++;
  4721. $segment_number++;
  4722. }
  4723. }
  4724. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4725. if (!$boolen2) {
  4726. dLog('deepseek')->info('分集内容保存失败', $episodes);
  4727. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  4728. Utils::throwError('20003:分集内容保存失败');
  4729. }
  4730. } catch (\Exception $e) {
  4731. DB::rollBack();
  4732. Utils::throwError('20003:'.$e->getMessage());
  4733. }
  4734. DB::commit();
  4735. return true;
  4736. }
  4737. public function getBookContent($data) {
  4738. $bid = getProp($data, 'bid');
  4739. $start_sequence = getProp($data, 'start_sequence');
  4740. $end_sequence = getProp($data, 'end_sequence');
  4741. $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])
  4742. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  4743. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  4744. return $return_content;
  4745. }
  4746. public function exportScript($data) {
  4747. $filename = getProp($data, 'filename');
  4748. $script_id = getProp($data, 'script_id');
  4749. $group_id = getProp($data, 'group_id');
  4750. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  4751. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  4752. if (!$script) Utils::throwError('20003:该剧本不存在!');
  4753. $script = (array)$script;
  4754. // 获取分集组信息
  4755. if ($group_id) {
  4756. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4757. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4758. ->get()->map(function($value) {
  4759. return (array)$value;
  4760. })->toArray();
  4761. }else {
  4762. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4763. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4764. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  4765. return (array)$value;
  4766. })->toArray();
  4767. }
  4768. if (!$groups) Utils::throwError('20003:分集不存在');
  4769. $script['group'] = $groups;
  4770. $export_type = getProp($data, 'export_type', 'txt');
  4771. // 生成文件名
  4772. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  4773. // 根据导出类型生成不同格式的文件
  4774. switch ($export_type) {
  4775. case 'txt':
  4776. return $this->exportScriptAsTxt($script, $filename);
  4777. case 'pdf':
  4778. return $this->exportScriptAsPdf($script, $filename);
  4779. default:
  4780. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  4781. }
  4782. }
  4783. /**
  4784. * 导出剧本为TXT格式
  4785. */
  4786. private function exportScriptAsTxt($script, $filename) {
  4787. // 构建TXT内容
  4788. $content = $this->buildScriptContent($script);
  4789. // 设置响应头,直接下载
  4790. header('Content-Type: text/plain; charset=utf-8');
  4791. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  4792. header('Content-Length: ' . strlen($content));
  4793. // 输出内容并结束
  4794. echo $content;
  4795. exit();
  4796. }
  4797. /**
  4798. * 导出剧本为PDF格式
  4799. */
  4800. private function exportScriptAsPdf($script, $filename) {
  4801. // 使用HTML转PDF的方式来更好地支持中文
  4802. $htmlContent = $this->buildScriptHtmlForPdf($script);
  4803. // 创建PDF实例
  4804. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  4805. // 设置文档信息
  4806. $pdf->SetCreator('剧本导出系统');
  4807. $pdf->SetAuthor('系统');
  4808. $pdf->SetTitle($script['script_name']);
  4809. $pdf->SetSubject('剧本导出');
  4810. // 设置边距
  4811. $pdf->SetMargins(15, 15, 15);
  4812. $pdf->SetAutoPageBreak(TRUE, 15);
  4813. // 添加页面
  4814. $pdf->AddPage();
  4815. // 注册并使用 simsun.ttf 字体
  4816. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  4817. // 使用HTML内容生成PDF
  4818. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  4819. // 直接输出PDF文件供下载
  4820. header('Content-Type: application/pdf');
  4821. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  4822. // 直接输出PDF内容
  4823. $pdf->Output($filename . '.pdf', 'D');
  4824. exit();
  4825. }
  4826. /**
  4827. * 构建用于PDF的HTML内容
  4828. */
  4829. private function buildScriptHtmlForPdf($script) {
  4830. $html = '<style>
  4831. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  4832. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  4833. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  4834. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  4835. .info { margin-bottom: 8px; }
  4836. .group { margin-bottom: 30px; page-break-inside: avoid; }
  4837. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  4838. .segment { margin-bottom: 10px; margin-left: 20px; }
  4839. .episode-content { white-space: pre-wrap; }
  4840. </style>';
  4841. // 标题
  4842. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  4843. // 处理分组数据
  4844. if (!empty($script['group']) && is_array($script['group'])) {
  4845. $groups = (array)$script['group'];
  4846. foreach ($groups as $group) {
  4847. $html .= '<div class="group">';
  4848. // 分组标题
  4849. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  4850. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  4851. // 故事梗概
  4852. if (!empty($group['intro'])) {
  4853. $html .= '<h3>故事梗概</h3>';
  4854. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  4855. }
  4856. // 剧本亮点
  4857. if (!empty($group['highlights'])) {
  4858. $html .= '<h3>剧本亮点</h3>';
  4859. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  4860. }
  4861. // 人物关系
  4862. if (!empty($group['role_relationship'])) {
  4863. $html .= '<h3>人物关系</h3>';
  4864. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  4865. }
  4866. // 核心矛盾
  4867. if (!empty($group['core_contradiction'])) {
  4868. $html .= '<h3>核心矛盾</h3>';
  4869. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  4870. }
  4871. // 主体列表
  4872. if (!empty($group['roles']) && is_array($group['roles'])) {
  4873. $html .= '<h3>主体列表</h3>';
  4874. $html .= '<ul>';
  4875. foreach ($group['roles'] as $role) {
  4876. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  4877. }
  4878. $html .= '</ul>';
  4879. }
  4880. // 美术风格
  4881. if (!empty($group['art_style'])) {
  4882. $html .= '<h3>美术风格</h3>';
  4883. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  4884. }
  4885. // 场景列表
  4886. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4887. $html .= '<h3>场景列表</h3>';
  4888. $html .= '<ul>';
  4889. foreach ($group['scenes'] as $scene) {
  4890. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  4891. }
  4892. $html .= '</ul>';
  4893. }
  4894. // 分集剧本
  4895. if (!empty($group['episode_content'])) {
  4896. $html .= '<h3>分集剧本</h3>';
  4897. // 去除零宽字符和其他不可见字符
  4898. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  4899. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  4900. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  4901. }
  4902. $html .= '</div>';
  4903. }
  4904. }
  4905. return $html;
  4906. }
  4907. /**
  4908. * 构建PDF内容
  4909. */
  4910. private function buildPdfContent($pdf, $script) {
  4911. // 标题
  4912. $pdf->SetFont('dejavusans', 'B', 18);
  4913. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  4914. $pdf->Ln(5);
  4915. // 基本信息
  4916. $pdf->SetFont('dejavusans', '', 12);
  4917. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  4918. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  4919. $pdf->Ln(5);
  4920. // 剧本简介
  4921. if (!empty($script['intro'])) {
  4922. $pdf->SetFont('dejavusans', 'B', 14);
  4923. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  4924. $pdf->SetFont('dejavusans', '', 12);
  4925. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  4926. $pdf->Ln(3);
  4927. }
  4928. // 亮点
  4929. if (!empty($script['highlights'])) {
  4930. $pdf->SetFont('dejavusans', 'B', 14);
  4931. $pdf->Cell(0, 10, '亮点', 0, 1);
  4932. $pdf->SetFont('dejavusans', '', 12);
  4933. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  4934. $pdf->Ln(3);
  4935. }
  4936. // 核心矛盾
  4937. if (!empty($script['core_contradiction'])) {
  4938. $pdf->SetFont('dejavusans', 'B', 14);
  4939. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  4940. $pdf->SetFont('dejavusans', '', 12);
  4941. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  4942. $pdf->Ln(3);
  4943. }
  4944. // 艺术风格
  4945. if (!empty($script['art_style'])) {
  4946. $pdf->SetFont('dejavusans', 'B', 14);
  4947. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  4948. $pdf->SetFont('dejavusans', '', 12);
  4949. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  4950. $pdf->Ln(3);
  4951. }
  4952. // 备注
  4953. if (!empty($script['remark'])) {
  4954. $pdf->SetFont('dejavusans', 'B', 14);
  4955. $pdf->Cell(0, 10, '备注', 0, 1);
  4956. $pdf->SetFont('dejavusans', '', 12);
  4957. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  4958. $pdf->Ln(3);
  4959. }
  4960. // 角色列表
  4961. if (!empty($script['roles']) && is_array($script['roles'])) {
  4962. $pdf->SetFont('dejavusans', 'B', 14);
  4963. $pdf->Cell(0, 10, '角色列表', 0, 1);
  4964. $pdf->SetFont('dejavusans', '', 12);
  4965. foreach ($script['roles'] as $index => $role) {
  4966. if (is_array($role) || is_object($role)) {
  4967. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  4968. } else {
  4969. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  4970. }
  4971. }
  4972. $pdf->Ln(3);
  4973. }
  4974. // 角色关系
  4975. if (!empty($script['role_relationship'])) {
  4976. $pdf->SetFont('dejavusans', 'B', 14);
  4977. $pdf->Cell(0, 10, '角色关系', 0, 1);
  4978. $pdf->SetFont('dejavusans', '', 12);
  4979. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  4980. $pdf->Ln(3);
  4981. }
  4982. // 场景列表
  4983. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  4984. $pdf->SetFont('dejavusans', 'B', 14);
  4985. $pdf->Cell(0, 10, '场景列表', 0, 1);
  4986. $pdf->SetFont('dejavusans', '', 12);
  4987. foreach ($script['scenes'] as $index => $scene) {
  4988. if (is_array($scene) || is_object($scene)) {
  4989. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  4990. } else {
  4991. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  4992. }
  4993. }
  4994. $pdf->Ln(5);
  4995. }
  4996. // 分集内容
  4997. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  4998. $pdf->SetFont('dejavusans', 'B', 16);
  4999. $pdf->Cell(0, 12, '分集内容', 0, 1);
  5000. $pdf->Ln(3);
  5001. foreach ($script['episodes'] as $episode) {
  5002. // 检查是否需要新页面
  5003. if ($pdf->GetY() > 250) {
  5004. $pdf->AddPage();
  5005. }
  5006. $pdf->SetFont('dejavusans', 'B', 14);
  5007. $episodeTitle = '第' . $episode['episode_number'] . '集';
  5008. if (!empty($episode['title'])) {
  5009. $episodeTitle .= ':' . $episode['title'];
  5010. }
  5011. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  5012. // 处理分段内容
  5013. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  5014. $pdf->SetFont('dejavusans', '', 12);
  5015. foreach ($episode['segments'] as $segment) {
  5016. if (!empty($segment['segment_content'])) {
  5017. // 如果有分段编号,显示分段标题
  5018. if (!empty($segment['segment_number'])) {
  5019. $pdf->SetFont('dejavusans', 'B', 12);
  5020. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  5021. $pdf->SetFont('dejavusans', '', 12);
  5022. }
  5023. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  5024. $pdf->Ln(2);
  5025. }
  5026. }
  5027. }
  5028. $pdf->Ln(5);
  5029. }
  5030. }
  5031. }
  5032. /**
  5033. * 构建剧本文本内容
  5034. */
  5035. private function buildScriptContent($script) {
  5036. $content = '';
  5037. $groups = $script['group'];
  5038. $groups = (array)$groups;
  5039. foreach ($groups as $group) {
  5040. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  5041. // 剧本基本信息
  5042. if (!empty($group['intro'])) {
  5043. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  5044. }
  5045. if (!empty($group['highlights'])) {
  5046. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  5047. }
  5048. if (!empty($group['role_relationship'])) {
  5049. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  5050. }
  5051. if (!empty($group['core_contradiction'])) {
  5052. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  5053. }
  5054. if (!empty($group['roles']) && is_array($group['roles'])) {
  5055. $content .= "###主体列表\n";
  5056. foreach ($group['roles'] as $role) {
  5057. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  5058. }
  5059. $content .= "\n\n";
  5060. }
  5061. if (!empty($group['art_style'])) {
  5062. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  5063. }
  5064. // 场景信息
  5065. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  5066. $content .= "###场景列表\n";
  5067. foreach ($group['scenes'] as $scene) {
  5068. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  5069. }
  5070. $content .= "\n\n";
  5071. }
  5072. // 分集内容
  5073. if (!empty($group['episode_content'])) {
  5074. $content .= "###分集剧本\n";
  5075. $content .= $group['episode_content'];
  5076. // foreach ($script['episodes'] as $episode) {
  5077. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  5078. // // if (!empty($episode['episode_name'])) {
  5079. // // $content .= ":" . $episode['episode_name'];
  5080. // // }
  5081. // // $content .= "\n";
  5082. // $content .= $episode['episode_content'] . "\n\n";
  5083. // }
  5084. }
  5085. }
  5086. return $content;
  5087. }
  5088. /**
  5089. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  5090. *
  5091. * @param array $data 包含以下参数:
  5092. * - file: 上传的文件(UploadedFile 对象)或文件路径
  5093. * - question: 用户问题(可选)
  5094. * - model: 使用的模型(r1 或 v3,默认 v3)
  5095. * @return \Generator 返回生成器,用于流式输出
  5096. */
  5097. public function addChat($data) {
  5098. $uid = Site::getUid();
  5099. $anime_id = getProp($data, 'anime_id');
  5100. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5101. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5102. if (!$anime) Utils::throwError('20003:对话不存在');
  5103. $file = getProp($data, 'file');
  5104. $content = getProp($data, 'content', '');
  5105. $bid = getProp($data, 'bid', 0);
  5106. $script_id = getProp($data, 'script_id', 0);
  5107. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5108. $prompt = getProp($data, 'prompt');
  5109. $user_anime_name = getProp($anime, 'anime_name');
  5110. // 处理文本模型
  5111. $model = getProp($data, 'model');
  5112. if (!$model) {
  5113. // 用户没有输入,从anime表获取
  5114. $model = getProp($anime, 'model');
  5115. if (!$model) {
  5116. // anime表也没有,使用默认值
  5117. $model = 'doubao-seed-2-0-mini-260215';
  5118. }
  5119. }
  5120. // 验证模型是否在可用模型表中
  5121. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5122. $model = 'doubao-seed-2-0-mini-260215';
  5123. }
  5124. $is_multi = getProp($anime, 'is_multi');
  5125. $is_single = (int)$is_multi !== 1;
  5126. // 积分余额预检(仅单剧集模式收费)
  5127. if ($is_single) {
  5128. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5129. }
  5130. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5131. if ($prompt) {
  5132. $question .= "本次修改要求如下:\n{$prompt}";
  5133. }
  5134. // if (!$file && !$content && !$bid) {
  5135. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5136. // }
  5137. // 提取文件内容
  5138. if ($file) {
  5139. $content = $this->extractFileContent($file);
  5140. if (!$content) {
  5141. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5142. }
  5143. } elseif ($script_id) {
  5144. $content = $this->getContentByScriptId($script_id);
  5145. if (!$content) {
  5146. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5147. }
  5148. } elseif ($bid) {
  5149. $content = $this->getContentByBid($bid);
  5150. if (!$content) {
  5151. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5152. }
  5153. } elseif ($content) {
  5154. $content = filterContent($content);
  5155. } else {
  5156. $content = getProp($anime, 'content');
  5157. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5158. $need_generate_content = true;
  5159. }
  5160. }
  5161. // 美术风格
  5162. $input_art_style = getProp($data, 'art_style');
  5163. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5164. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5165. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5166. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5167. 中年女:邻居阿姨
  5168. 老年男:幽默大爷
  5169. 老年女:婆婆
  5170. 萌娃:奶气萌娃";
  5171. // 判断是否需要生成原文内容
  5172. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5173. // 如果需要生成原文内容,添加额外的要求
  5174. $content_generation_requirement = $need_generate_content
  5175. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5176. : "";
  5177. // 美术风格
  5178. if (!$mappedArtStyle) {
  5179. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5180. }else {
  5181. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5182. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5183. }else {
  5184. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5185. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5186. }
  5187. }
  5188. $systemPrompt = $is_single
  5189. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5190. 强制要求:
  5191. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5192. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5193. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5194. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5195. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5196. 普通要求:
  5197. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5198. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5199. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  5200. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5201. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5202. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5203. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5204. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5205. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5206. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5207. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5208. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5209. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5210. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5211. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5212. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5213. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5214. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5215. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5216. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5217. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5218. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5219. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5220. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5221. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5222. 5.{$mappedArtStyle_prompt}\n\n
  5223. 示例如下:\n
  5224. ###剧本名:西昆仑
  5225. ###故事梗概
  5226. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5227. ###剧本亮点
  5228. 亮点1:绝境奇药,生死一线
  5229. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5230. 亮点2:结拜兄妹,化解尴尬
  5231. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5232. 亮点3:纤发夺命,情愫暗涌
  5233. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5234. ###人物关系
  5235. 阿雪与梁萧之间存在兄妹之情。
  5236. ###核心矛盾
  5237. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5238. ###主体列表
  5239. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5240. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5241. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5242. 姿态:站立。}{{甜心小美}}
  5243. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5244. 全景,正面拍摄,青年女性,亚洲人。
  5245. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5246. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5247. 姿态:站立。}{{阳光青年}}
  5248. ###美术风格
  5249. 基础画风风格词:厚涂古风
  5250. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5251. ###场景列表
  5252. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5253. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5254. 无人物。}
  5255. ###分镜剧本
  5256. ##第1幕:徐家老旧厨房 白天 室内
  5257. 分镜1
  5258. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5259. 场景:徐家老旧厨房
  5260. 构图设计:全景,低角度仰视
  5261. 运镜调度:手持拍摄
  5262. 配音角色:旁白
  5263. 出镜角色:许芸-校服装、徐母
  5264. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5265. 画面类型:普通画面
  5266. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5267. 分镜2
  5268. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5269. 场景:徐家老旧厨房
  5270. 构图设计:近景,徐母面部特写
  5271. 运镜调度:固定镜头
  5272. 配音角色:徐母
  5273. 出镜角色:徐母
  5274. 台词内容:问我夜不归宿死哪儿去了。
  5275. 画面类型:对口型
  5276. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5277. ##第2幕:徐家简陋客厅 黄昏 室内
  5278. 分镜3
  5279. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5280. 场景:徐家简陋客厅
  5281. 构图设计:全景,景深虚化
  5282. 运镜调度:固定镜头
  5283. 配音角色:旁白
  5284. 出镜角色:无
  5285. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5286. 画面类型:普通画面
  5287. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5288. 分镜4
  5289. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5290. 场景:徐家简陋客厅
  5291. 构图设计:特写,火车票
  5292. 运镜调度:固定镜头
  5293. 配音角色:旁白
  5294. 出镜角色:无
  5295. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5296. 画面类型:普通画面
  5297. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5298. "
  5299. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5300. 强制要求:\n
  5301. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5302. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5303. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5304. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5305. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5306. 普通要求:\n
  5307. 1.剧本名(必须生成)必须与文档内容高度相关
  5308. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5309. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5310. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5311. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5312. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5313. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5314. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5315. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5316. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5317. 4.{$mappedArtStyle_prompt}\n\n
  5318. 示例如下:\n
  5319. ###剧本名:西昆仑
  5320. ###故事梗概
  5321. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5322. ###剧本亮点
  5323. 亮点1:绝境奇药,生死一线
  5324. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5325. 亮点2:结拜兄妹,化解尴尬
  5326. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5327. 亮点3:纤发夺命,情愫暗涌
  5328. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5329. ###人物关系
  5330. 阿雪与梁萧之间存在兄妹之情。
  5331. ###核心矛盾
  5332. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5333. ###主体列表
  5334. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5335. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5336. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5337. 姿态:站立。}{{甜心小美}}
  5338. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5339. 全景,正面拍摄,青年女性,亚洲人。
  5340. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5341. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5342. 姿态:站立。}{{阳光青年}}
  5343. ###美术风格
  5344. 基础画风风格词:厚涂古风
  5345. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5346. ###场景列表
  5347. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5348. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5349. 无人物。}";
  5350. // 构建消息
  5351. $messages = [
  5352. [
  5353. 'role' => 'system',
  5354. 'content' => $systemPrompt
  5355. ],
  5356. [
  5357. 'role' => 'user',
  5358. 'content' => "以下是文档内容:
  5359. {$content}
  5360. 用户问题:
  5361. {$question}"
  5362. ]
  5363. ];
  5364. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5365. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5366. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5367. if ($model === 'deepseek-chat') {
  5368. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5369. $model = 'deepseek-v4-flash';
  5370. $thinkingMode = 'disabled';
  5371. } elseif ($model === 'deepseek-reasoner') {
  5372. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5373. $model = 'deepseek-v4-flash';
  5374. $thinkingMode = 'enabled';
  5375. }
  5376. $post_data = [
  5377. 'model' => $model,
  5378. 'messages' => $messages,
  5379. // 'max_tokens' => 8192,
  5380. 'temperature' => 0.7,
  5381. 'frequency_penalty' => 0,
  5382. 'presence_penalty' => 0,
  5383. 'response_format' => ['type' => 'text'],
  5384. 'thinking' => ['type'=>$thinkingMode],
  5385. 'stream' => true // 启用流式输出
  5386. ];
  5387. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5388. // 根据模型类型选择调用方法
  5389. $fullContent = '';
  5390. $fullReasoningContent = '';
  5391. $usage = [];
  5392. try {
  5393. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5394. // DeepSeek 官方模型使用 DeepSeek API
  5395. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5396. } else if (in_array($model, $this->gpt_text_models)) {
  5397. // GPT-5.4 模型使用 TokenRouter API
  5398. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5399. } else if (in_array($model, $this->gemini_text_models)) {
  5400. // Gemini 模型使用 Gemini API
  5401. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  5402. } else {
  5403. // 其他模型使用火山引擎API
  5404. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5405. }
  5406. // 验证返回值类型
  5407. if (!is_iterable($streamGenerator)) {
  5408. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5409. dLog('deepseek')->error('addChat流式生成器无效', [
  5410. 'generator_type' => $errorType,
  5411. 'model' => $model,
  5412. 'anime_id' => $anime_id
  5413. ]);
  5414. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5415. 'type' => $errorType,
  5416. 'model' => $model
  5417. ]);
  5418. yield [
  5419. 'type' => 'error',
  5420. 'script' => [],
  5421. 'episode' => [],
  5422. 'answer' => '',
  5423. 'reasoning' => '',
  5424. 'usage' => [],
  5425. 'error' => '接口返回数据异常,请重新请求'
  5426. ];
  5427. return;
  5428. }
  5429. // 处理流式输出
  5430. foreach ($streamGenerator as $chunk) {
  5431. if (isset($chunk['type'])) {
  5432. if ($chunk['type'] === 'done') {
  5433. // 最终结果
  5434. $fullContent = $chunk['full_content'];
  5435. $fullReasoningContent = $chunk['full_reasoning'];
  5436. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5437. } else {
  5438. // 逐块yield数据
  5439. yield $chunk;
  5440. }
  5441. }
  5442. }
  5443. } catch (\Exception $e) {
  5444. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5445. 'model' => $model,
  5446. 'anime_id' => $anime_id,
  5447. 'trace' => $e->getTraceAsString()
  5448. ]);
  5449. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5450. 'error' => $e->getMessage(),
  5451. 'model' => $model
  5452. ]);
  5453. yield [
  5454. 'type' => 'error',
  5455. 'script' => [],
  5456. 'episode' => [],
  5457. 'answer' => '',
  5458. 'reasoning' => '',
  5459. 'usage' => [],
  5460. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5461. ];
  5462. return;
  5463. }
  5464. dLog('deepseek')->info('完整内容: '.$fullContent);
  5465. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5466. // 处理完整内容并返回最终结果
  5467. $script_arr = [];
  5468. if ($fullContent) {
  5469. $script_arr = handleScriptContent($fullContent);
  5470. dLog('deepseek')->info('解析内容', $script_arr);
  5471. logDB('deepseek', 'info', '解析内容', $script_arr);
  5472. }
  5473. if (empty($script_arr['roles'])) {
  5474. // 未生成剧本相关内容,保存对话记录并返回提示
  5475. dLog('deepseek')->info('未生成剧本相关的内容');
  5476. try {
  5477. DB::beginTransaction();
  5478. $now = date('Y-m-d H:i:s');
  5479. // 保存对话记录
  5480. $records = [
  5481. [
  5482. 'uid' => $uid,
  5483. 'anime_id' => $anime_id,
  5484. 'sequence' => 0,
  5485. 'role' => 'user',
  5486. 'content' => $prompt,
  5487. 'created_at' => $now,
  5488. 'updated_at' => $now
  5489. ],
  5490. [
  5491. 'uid' => $uid,
  5492. 'anime_id' => $anime_id,
  5493. 'sequence' => 0,
  5494. 'role' => 'assistant',
  5495. // 'content' => $fullContent,
  5496. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5497. 'created_at' => $now,
  5498. 'updated_at' => $now
  5499. ]
  5500. ];
  5501. DB::table('mp_anime_records')->insert($records);
  5502. DB::commit();
  5503. } catch (\Exception $e) {
  5504. DB::rollBack();
  5505. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5506. }
  5507. yield [
  5508. 'type' => 'done',
  5509. 'script' => [],
  5510. 'episode' => [],
  5511. 'answer' => $fullContent,
  5512. 'reasoning' => $fullReasoningContent,
  5513. 'usage' => $usage,
  5514. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5515. ];
  5516. return;
  5517. }
  5518. // 如果需要生成原文内容,从script_arr中提取
  5519. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5520. $content = $script_arr['content'];
  5521. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5522. if (!$content) {
  5523. yield [
  5524. 'type' => 'done',
  5525. 'script' => [],
  5526. 'episode' => [],
  5527. 'answer' => $fullContent,
  5528. 'reasoning' => $fullReasoningContent,
  5529. 'usage' => $usage,
  5530. 'error' => '未生成剧本内容,请调整提示词再试'
  5531. ];
  5532. return;
  5533. }
  5534. }
  5535. // 替换美术风格
  5536. if ($mappedArtStyle !== '') {
  5537. $script_arr['art_style'] = $mappedArtStyle;
  5538. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5539. }
  5540. // 新建动漫
  5541. if ($user_anime_name == '新剧本策划') {
  5542. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5543. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5544. // if (!$anime_name) {
  5545. // // 未识别到剧本名,保存对话记录并返回提示
  5546. // dLog('deepseek')->info('未能识别到剧本名称');
  5547. // try {
  5548. // DB::beginTransaction();
  5549. // $now = date('Y-m-d H:i:s');
  5550. // // 保存对话记录
  5551. // $records = [
  5552. // [
  5553. // 'uid' => $uid,
  5554. // 'anime_id' => $anime_id,
  5555. // 'sequence' => 0,
  5556. // 'role' => 'user',
  5557. // 'content' => $prompt,
  5558. // 'created_at' => $now,
  5559. // 'updated_at' => $now
  5560. // ],
  5561. // [
  5562. // 'uid' => $uid,
  5563. // 'anime_id' => $anime_id,
  5564. // 'sequence' => 0,
  5565. // 'role' => 'assistant',
  5566. // 'content' => '未能生成剧本名称,请重试',
  5567. // 'created_at' => $now,
  5568. // 'updated_at' => $now
  5569. // ]
  5570. // ];
  5571. // DB::table('mp_anime_records')->insert($records);
  5572. // DB::commit();
  5573. // } catch (\Exception $e) {
  5574. // DB::rollBack();
  5575. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5576. // }
  5577. // yield [
  5578. // 'type' => 'done',
  5579. // 'script' => [],
  5580. // 'episode' => [],
  5581. // 'answer' => $fullContent,
  5582. // 'reasoning' => $fullReasoningContent,
  5583. // 'usage' => $usage,
  5584. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  5585. // ];
  5586. // return;
  5587. // }
  5588. // 确认对话名称唯一性
  5589. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5590. $anime_name = $anime_name . '_' . date('YmdHis');
  5591. }
  5592. }else {
  5593. $anime_name = $user_anime_name;
  5594. }
  5595. $table_data = [
  5596. 'user_id' => $uid,
  5597. 'anime_name' => $anime_name,
  5598. 'model' => $model,
  5599. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5600. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5601. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5602. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5603. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5604. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5605. 'art_style_type' => $input_art_style,
  5606. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5607. 'status' => '解析完成',
  5608. 'content' => $content,
  5609. 'is_multi' => $is_multi,
  5610. 'ace_mode' => $ace_mode,
  5611. 'generate_status' => '待执行',
  5612. 'updated_at' => date('Y-m-d H:i:s')
  5613. ];
  5614. if ($table_data['content']) {
  5615. $chapters = splitContent($table_data['content']);
  5616. $chapter_count = count($chapters);
  5617. if ($chapter_count > 0) {
  5618. $table_data['start_episode_sequence'] = 1;
  5619. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5620. }
  5621. }
  5622. // 如果有剧本ID则进行绑定
  5623. if ($script_id) {
  5624. $table_data['script_id'] = $script_id;
  5625. }
  5626. $single_episode = [];
  5627. try {
  5628. DB::beginTransaction();
  5629. $now = date('Y-m-d H:i:s');
  5630. // 更新动漫大纲
  5631. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5632. if (!$boolen) {
  5633. dLog('deepseek')->info('动漫保存失败', $table_data);
  5634. Utils::throwError('20003:动漫保存失败');
  5635. }
  5636. // 保存对话记录
  5637. $records = [
  5638. [
  5639. 'uid' => $uid,
  5640. 'anime_id' => $anime_id,
  5641. 'sequence' => 0,
  5642. 'role' => 'user',
  5643. 'content' => $prompt,
  5644. 'created_at' => date('Y-m-d H:i:s'),
  5645. 'updated_at' => date('Y-m-d H:i:s')
  5646. ],
  5647. [
  5648. 'uid' => $uid,
  5649. 'anime_id' => $anime_id,
  5650. 'sequence' => 0,
  5651. 'role' => 'assistant',
  5652. 'content' => $fullContent,
  5653. 'created_at' => date('Y-m-d H:i:s'),
  5654. 'updated_at' => date('Y-m-d H:i:s')
  5655. ]
  5656. ];
  5657. // 保存对话记录
  5658. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5659. if (!$boolen3) {
  5660. Utils::throwError('20003:对话记录保存失败');
  5661. }
  5662. if ($is_single) {
  5663. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5664. if (empty($episode_arr['acts'])) {
  5665. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5666. }
  5667. $saveResult = $this->saveEpisodeVersionData(
  5668. $anime_id,
  5669. 1,
  5670. $episode_arr,
  5671. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5672. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5673. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5674. null,
  5675. null,
  5676. false,
  5677. $content,
  5678. $now
  5679. );
  5680. $single_episode = $saveResult['episode'];
  5681. $episode_id = $saveResult['episode_id'];
  5682. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5683. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5684. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5685. 'props' => json_encode($saveResult['merged_props'], 256),
  5686. 'updated_at' => $now
  5687. ]);
  5688. if ($boolen5 === false) {
  5689. Utils::throwError('20003:单剧集主表资源同步失败');
  5690. }
  5691. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5692. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5693. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5694. $episode_record_content = '确认分镜大纲';
  5695. if ($content !== '') {
  5696. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5697. }
  5698. $episode_records = [
  5699. [
  5700. 'uid' => $uid,
  5701. 'anime_id' => $anime_id,
  5702. 'role' => 'user',
  5703. 'content' => $episode_record_content,
  5704. 'sequence' => 1,
  5705. 'episode_id' => $episode_id,
  5706. 'created_at' => $now,
  5707. 'updated_at' => $now
  5708. ],
  5709. [
  5710. 'uid' => $uid,
  5711. 'anime_id' => $anime_id,
  5712. 'role' => 'assistant',
  5713. 'content' => $fullContent,
  5714. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5715. 'sequence' => 1,
  5716. 'episode_id' => $episode_id,
  5717. 'created_at' => $now,
  5718. 'updated_at' => $now
  5719. ]
  5720. ];
  5721. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5722. if (!$boolen4) {
  5723. Utils::throwError('20003:单剧集分镜记录保存失败');
  5724. }
  5725. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  5726. if ($is_single && !empty($single_episode)) {
  5727. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5728. 'anime_id' => $anime_id,
  5729. 'episode_id' => $episode_id ?? 0,
  5730. 'model' => $model,
  5731. 'source' => 'addChat',
  5732. ]);
  5733. }
  5734. }
  5735. }catch (\Exception $e) {
  5736. DB::rollBack();
  5737. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5738. yield [
  5739. 'type' => 'done',
  5740. 'answer' => $fullContent,
  5741. 'reasoning' => $fullReasoningContent,
  5742. 'usage' => $usage,
  5743. 'error' => $e->getMessage(),
  5744. ];
  5745. return;
  5746. }
  5747. DB::commit();
  5748. dLog('deepseek')->info('保存完毕');
  5749. if ($is_single && !empty($single_episode)) {
  5750. // $this->batchSetGlobalRoleImg([
  5751. // 'anime_id' => $anime_id,
  5752. // ]);
  5753. // $this->batchSetGlobalSceneImg([
  5754. // 'anime_id' => $anime_id,
  5755. // ]);
  5756. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5757. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5758. }
  5759. $table_data['anime_id'] = $anime_id;
  5760. $table_data['roles'] = json_decode($table_data['roles'], true);
  5761. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5762. // $table_data['episodes'] = $script_arr['episodes'];
  5763. unset($table_data['created_at']);
  5764. unset($table_data['updated_at']);
  5765. unset($table_data['status']);
  5766. dLog('deepseek')->info('开始返回');
  5767. yield [
  5768. 'type' => 'done',
  5769. 'script' => $table_data,
  5770. 'episode' => $single_episode,
  5771. 'answer' => $fullContent,
  5772. 'reasoning' => $fullReasoningContent,
  5773. 'usage' => $usage
  5774. ];
  5775. }
  5776. public function reGenerateAnime($data) {
  5777. $uid = Site::getUid();
  5778. $file = getProp($data, 'file');
  5779. $content = getProp($data, 'content', '');
  5780. $bid = getProp($data, 'bid', 0);
  5781. $script_id = getProp($data, 'script_id', 0);
  5782. $anime_id = getProp($data, 'anime_id');
  5783. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5784. if (!$anime) {
  5785. Utils::throwError('20003:该对话不存在');
  5786. }
  5787. $user_anime_name = getProp($anime, 'anime_name');
  5788. $prompt = getProp($data, 'prompt');
  5789. // 处理文本模型
  5790. $model = getProp($data, 'model');
  5791. if (!$model) {
  5792. // 用户没有输入,从anime表获取
  5793. $model = getProp($anime, 'model');
  5794. if (!$model) {
  5795. // anime表也没有,使用默认值
  5796. $model = 'doubao-seed-2-0-mini-260215';
  5797. }
  5798. }
  5799. // 验证模型是否在可用模型表中
  5800. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5801. $model = 'doubao-seed-2-0-mini-260215';
  5802. }
  5803. $is_multi = getProp($anime, 'is_multi', 1);
  5804. $is_single = (int)$is_multi !== 1;
  5805. // 积分余额预检(仅单剧集模式收费)
  5806. if ($is_single) {
  5807. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5808. }
  5809. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  5810. if ($is_single) {
  5811. $episode_exists = DB::table('mp_anime_episodes')
  5812. ->where('anime_id', $anime_id)
  5813. ->where('sequence', 1)
  5814. ->exists();
  5815. if ($episode_exists) {
  5816. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  5817. }
  5818. }
  5819. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5820. if ($prompt) {
  5821. $question .= "本次修改要求如下:\n{$prompt}";
  5822. }
  5823. // 提取文件内容
  5824. if ($file) {
  5825. $content = $this->extractFileContent($file);
  5826. if (!$content) {
  5827. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5828. }
  5829. } elseif ($script_id) {
  5830. $content = $this->getContentByScriptId($script_id);
  5831. if (!$content) {
  5832. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5833. }
  5834. } elseif ($bid) {
  5835. $content = $this->getContentByBid($bid);
  5836. if (!$content) {
  5837. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5838. }
  5839. } elseif ($content) {
  5840. $content = filterContent($content);
  5841. }else {
  5842. $content = filterContent(getProp($anime, 'content'));
  5843. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5844. $need_generate_content = true;
  5845. }
  5846. }
  5847. // 判断是否需要生成原文内容
  5848. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5849. // 如果需要生成原文内容,添加额外的要求
  5850. $content_generation_requirement = $need_generate_content
  5851. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5852. : "";
  5853. // 美术风格
  5854. $input_art_style = getProp($anime, 'art_style');
  5855. if (!$input_art_style) {
  5856. $input_art_style = getProp($data, 'art_style');
  5857. }
  5858. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5859. // 美术风格
  5860. if (!$mappedArtStyle) {
  5861. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5862. }else {
  5863. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5864. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5865. }else {
  5866. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5867. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5868. }
  5869. }
  5870. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5871. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5872. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5873. 中年女:邻居阿姨
  5874. 老年男:幽默大爷
  5875. 老年女:婆婆
  5876. 萌娃:奶气萌娃";
  5877. $system_message = ['role'=>'system', 'content'=>$is_single
  5878. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5879. 强制要求:
  5880. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5881. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5882. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5883. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5884. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5885. 普通要求:
  5886. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5887. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5888. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5889. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5890. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5891. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5892. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5893. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5894. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5895. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5896. 3.$mappedArtStyle_prompt\n\n
  5897. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5898. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5899. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5900. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5901. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5902. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5903. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5904. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5905. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5906. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5907. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5908. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5909. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5910. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5911. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5912. 示例如下:\n
  5913. ###剧本名:西昆仑
  5914. ###故事梗概
  5915. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5916. ###剧本亮点
  5917. 亮点1:绝境奇药,生死一线
  5918. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5919. 亮点2:结拜兄妹,化解尴尬
  5920. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5921. 亮点3:纤发夺命,情愫暗涌
  5922. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5923. ###人物关系
  5924. 阿雪与梁萧之间存在兄妹之情。
  5925. ###核心矛盾
  5926. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5927. ###主体列表
  5928. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5929. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5930. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5931. 姿态:站立。}{{甜心小美}}
  5932. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5933. 全景,正面拍摄,青年女性,亚洲人。
  5934. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5935. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5936. 姿态:站立。}{{阳光青年}}
  5937. ###美术风格
  5938. 基础画风风格词:厚涂古风
  5939. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5940. ###场景列表
  5941. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5942. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5943. 无人物。}
  5944. ###分镜剧本
  5945. ##第1幕:徐家老旧厨房 白天 室内
  5946. 分镜1
  5947. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5948. 场景:徐家老旧厨房
  5949. 构图设计:全景,低角度仰视
  5950. 运镜调度:手持拍摄
  5951. 配音角色:旁白
  5952. 出镜角色:许芸-校服装、徐母
  5953. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5954. 画面类型:普通画面
  5955. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5956. 分镜2
  5957. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5958. 场景:徐家老旧厨房
  5959. 构图设计:近景,徐母面部特写
  5960. 运镜调度:固定镜头
  5961. 配音角色:徐母
  5962. 出镜角色:徐母
  5963. 台词内容:问我夜不归宿死哪儿去了。
  5964. 画面类型:对口型
  5965. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5966. ##第2幕:徐家简陋客厅 黄昏 室内
  5967. 分镜3
  5968. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5969. 场景:徐家简陋客厅
  5970. 构图设计:全景,景深虚化
  5971. 运镜调度:固定镜头
  5972. 配音角色:旁白
  5973. 出镜角色:无
  5974. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5975. 画面类型:普通画面
  5976. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5977. 分镜4
  5978. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5979. 场景:徐家简陋客厅
  5980. 构图设计:特写,火车票
  5981. 运镜调度:固定镜头
  5982. 配音角色:旁白
  5983. 出镜角色:无
  5984. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5985. 画面类型:普通画面
  5986. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5987. "
  5988. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5989. 强制要求:\n
  5990. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5991. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5992. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5993. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5994. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5995. 普通要求:\n
  5996. 1.剧本名(必须生成)必须与文档内容高度相关
  5997. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5998. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5999. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6000. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6001. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6002. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6003. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6004. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6005. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6006. 4.$mappedArtStyle_prompt\n\n
  6007. 示例如下:\n
  6008. ###剧本名:西昆仑
  6009. ###故事梗概
  6010. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6011. ###剧本亮点
  6012. 亮点1:绝境奇药,生死一线
  6013. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6014. 亮点2:结拜兄妹,化解尴尬
  6015. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6016. 亮点3:纤发夺命,情愫暗涌
  6017. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6018. ###人物关系
  6019. 阿雪与梁萧之间存在兄妹之情。
  6020. ###核心矛盾
  6021. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6022. ###主体列表
  6023. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6024. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6025. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6026. 姿态:站立。}{{甜心小美}}
  6027. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6028. 全景,正面拍摄,青年女性,亚洲人。
  6029. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6030. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6031. 姿态:站立。}{{阳光青年}}
  6032. ###美术风格
  6033. 基础画风风格词:厚涂古风
  6034. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6035. ###场景列表
  6036. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6037. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6038. 无人物。}"];
  6039. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6040. $episode_count = $this->extractEpisodeNumber($prompt);
  6041. if ((int)getProp($anime, 'is_multi') !== 1) {
  6042. yield [
  6043. 'type' => 'done',
  6044. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6045. 'reasoning' => '',
  6046. 'usage' => []
  6047. ];
  6048. return;
  6049. }
  6050. if ($episode_count) {
  6051. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6052. $system_message = [
  6053. 'role' => 'system',
  6054. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6055. 强制要求:\n
  6056. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6057. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6058. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6059. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6060. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6061. 普通要求:\n
  6062. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6063. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6064. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6065. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6066. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6067. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6068. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6069. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6070. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6071. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6072. 示例如下:\n
  6073. ###剧本名:西昆仑
  6074. ###故事梗概
  6075. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6076. ###剧本亮点
  6077. 亮点1:绝境奇药,生死一线
  6078. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6079. 亮点2:结拜兄妹,化解尴尬
  6080. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6081. 亮点3:纤发夺命,情愫暗涌
  6082. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6083. ###人物关系
  6084. 阿雪与梁萧之间存在兄妹之情。
  6085. ###核心矛盾
  6086. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6087. ###主体列表
  6088. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6089. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6090. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6091. 姿态:站立。}{{甜心小美}}
  6092. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6093. 全景,正面拍摄,青年女性,亚洲人。
  6094. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6095. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6096. 姿态:站立。}{{阳光青年}}
  6097. ###美术风格
  6098. 基础画风风格词:厚涂古风
  6099. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6100. ###场景列表
  6101. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6102. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6103. 无人物。}
  6104. ###分集详细内容
  6105. ##第1章 重生
  6106. 我重生了。
  6107. 源于一个男人偏执的暗恋。
  6108. ##第2章 相救
  6109. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6110. 我眼睛扫向站在锅炉后的卞大伟。"
  6111. ];
  6112. // 构建消息
  6113. $messages = [
  6114. $system_message,
  6115. [
  6116. 'role' => 'user',
  6117. 'content' => "以下是文档内容:
  6118. {$content}
  6119. 用户问题:
  6120. {$question}"
  6121. ]
  6122. ];
  6123. }else {
  6124. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6125. // 构建消息
  6126. $messages = [
  6127. $system_message,
  6128. [
  6129. 'role' => 'user',
  6130. 'content' => "以下是文档内容:
  6131. {$content}
  6132. 用户问题:
  6133. {$question}"
  6134. ]
  6135. ];
  6136. }else {
  6137. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6138. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6139. return (array)$value;
  6140. })->toArray();
  6141. array_unshift($messages, $system_message);
  6142. $messages[] = [
  6143. 'role' => 'user',
  6144. 'content' => $prompt
  6145. ];
  6146. }
  6147. }
  6148. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6149. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6150. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6151. if ($model === 'deepseek-chat') {
  6152. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6153. $model = 'deepseek-v4-flash';
  6154. $thinkingMode = 'disabled';
  6155. } elseif ($model === 'deepseek-reasoner') {
  6156. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6157. $model = 'deepseek-v4-flash';
  6158. $thinkingMode = 'enabled';
  6159. }
  6160. $post_data = [
  6161. 'model' => $model,
  6162. 'messages' => $messages,
  6163. // 'max_tokens' => 8192,
  6164. 'temperature' => 0.7,
  6165. 'frequency_penalty' => 0,
  6166. 'presence_penalty' => 0,
  6167. 'response_format' => ['type' => 'text'],
  6168. 'thinking' => ['type' => $thinkingMode],
  6169. 'stream' => true // 启用流式输出
  6170. ];
  6171. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6172. // 根据模型类型选择调用方法
  6173. $fullContent = '';
  6174. $fullReasoningContent = '';
  6175. $usage = [];
  6176. // dd($post_data);
  6177. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6178. try {
  6179. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6180. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6181. } else if (in_array($model, $this->gpt_text_models)) {
  6182. // GPT-5.4 模型使用 TokenRouter API
  6183. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6184. } else if (in_array($model, $this->gemini_text_models)) {
  6185. // Gemini 模型使用 Gemini API
  6186. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6187. } else {
  6188. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6189. }
  6190. // 验证返回值类型
  6191. if (!is_iterable($streamGenerator)) {
  6192. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6193. dLog('deepseek')->error('方法名流式生成器无效', [
  6194. 'generator_type' => $errorType,
  6195. 'model' => $model,
  6196. // 添加其他上下文信息
  6197. ]);
  6198. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6199. 'type' => $errorType,
  6200. 'model' => $model
  6201. ]);
  6202. yield [
  6203. 'type' => 'error',
  6204. // 根据方法返回相应的空数据结构
  6205. 'answer' => '',
  6206. 'reasoning' => '',
  6207. 'usage' => [],
  6208. 'error' => '接口返回数据异常,请重新请求'
  6209. ];
  6210. return;
  6211. }
  6212. // 处理流式输出
  6213. foreach ($streamGenerator as $chunk) {
  6214. if (isset($chunk['type'])) {
  6215. if ($chunk['type'] === 'done') {
  6216. $fullContent = $chunk['full_content'];
  6217. $fullReasoningContent = $chunk['full_reasoning'];
  6218. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6219. } else {
  6220. yield $chunk;
  6221. }
  6222. }
  6223. }
  6224. } catch (\Exception $e) {
  6225. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6226. 'model' => $model,
  6227. 'trace' => $e->getTraceAsString()
  6228. ]);
  6229. logDB('deepseek', 'error', '方法名流式处理失败', [
  6230. 'error' => $e->getMessage(),
  6231. 'model' => $model
  6232. ]);
  6233. yield [
  6234. 'type' => 'error',
  6235. // 根据方法返回相应的空数据结构
  6236. 'answer' => '',
  6237. 'reasoning' => '',
  6238. 'usage' => [],
  6239. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6240. ];
  6241. return;
  6242. }
  6243. dLog('deepseek')->info('完整内容: '.$fullContent);
  6244. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6245. // 处理完整内容并返回最终结果
  6246. $script_arr = [];
  6247. if ($fullContent) {
  6248. $script_arr = handleScriptContent($fullContent);
  6249. dLog('deepseek')->info('解析内容', $script_arr);
  6250. logDB('deepseek', 'info', '解析内容', $script_arr);
  6251. }
  6252. if (empty($script_arr['roles'])) {
  6253. // 未生成剧本相关内容,保存对话记录并返回提示
  6254. dLog('deepseek')->info('未生成剧本相关的内容');
  6255. try {
  6256. $now = date('Y-m-d H:i:s');
  6257. // 保存对话记录
  6258. $records = [
  6259. [
  6260. 'uid' => $uid,
  6261. 'anime_id' => $anime_id,
  6262. 'sequence' => 0,
  6263. 'role' => 'user',
  6264. 'content' => $prompt,
  6265. 'created_at' => $now,
  6266. 'updated_at' => $now
  6267. ],
  6268. [
  6269. 'uid' => $uid,
  6270. 'anime_id' => $anime_id,
  6271. 'sequence' => 0,
  6272. 'role' => 'assistant',
  6273. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6274. 'created_at' => $now,
  6275. 'updated_at' => $now
  6276. ]
  6277. ];
  6278. DB::table('mp_anime_records')->insert($records);
  6279. } catch (\Exception $e) {
  6280. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6281. }
  6282. yield [
  6283. 'type' => 'done',
  6284. 'script' => [],
  6285. 'episode' => [],
  6286. 'answer' => $fullContent,
  6287. 'reasoning' => $fullReasoningContent,
  6288. 'usage' => $usage,
  6289. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6290. ];
  6291. return;
  6292. }
  6293. // 替换美术风格
  6294. if ($mappedArtStyle !== '') {
  6295. $script_arr['art_style'] = $mappedArtStyle;
  6296. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6297. }
  6298. if ($user_anime_name != '新剧本策划') {
  6299. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6300. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6301. // 确认对话名称唯一性
  6302. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6303. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6304. }
  6305. }else {
  6306. $anime_name = $user_anime_name;
  6307. }
  6308. $table_data = [
  6309. 'user_id' => $uid,
  6310. 'model' => $model,
  6311. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6312. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6313. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6314. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6315. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6316. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6317. 'art_style_type' => $input_art_style,
  6318. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6319. 'status' => '解析完成',
  6320. 'generate_status' => '待执行',
  6321. 'updated_at' => date('Y-m-d H:i:s')
  6322. ];
  6323. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6324. // 如果是修改集数,则将content内容更新(会改变原文)
  6325. if (isset($episode_count) && $episode_count > 0) {
  6326. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6327. $table_data['start_episode_sequence'] = 1;
  6328. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6329. }else {
  6330. // 如果需要生成原文内容,从script_arr中提取
  6331. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6332. $table_data['content'] = $script_arr['content'];
  6333. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6334. if (!$table_data['content']) {
  6335. yield [
  6336. 'type' => 'done',
  6337. 'script' => [],
  6338. 'episode' => [],
  6339. 'answer' => $fullContent,
  6340. 'reasoning' => $fullReasoningContent,
  6341. 'usage' => $usage,
  6342. 'error' => '未生成剧本内容,请调整提示词再试'
  6343. ];
  6344. return;
  6345. }
  6346. }
  6347. if (isset($table_data['content']) && $table_data['content']) {
  6348. $chapters = splitContent($table_data['content']);
  6349. $chapter_count = count($chapters);
  6350. if ($chapter_count > 0) {
  6351. $table_data['start_episode_sequence'] = 1;
  6352. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6353. }
  6354. }
  6355. }
  6356. $single_episode = [];
  6357. try {
  6358. DB::beginTransaction();
  6359. $now = date('Y-m-d H:i:s');
  6360. // 更新动漫大纲
  6361. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6362. if (!$boolen) {
  6363. dLog('deepseek')->info('对话修改失败', $table_data);
  6364. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6365. Utils::throwError('20003:对话修改失败');
  6366. }
  6367. // 保存对话记录
  6368. $records = [
  6369. [
  6370. 'uid' => $uid,
  6371. 'anime_id' => $anime_id,
  6372. 'sequence' => 0,
  6373. 'role' => 'user',
  6374. 'content' => $prompt,
  6375. 'created_at' => $now,
  6376. 'updated_at' => $now
  6377. ],
  6378. [
  6379. 'uid' => $uid,
  6380. 'anime_id' => $anime_id,
  6381. 'sequence' => 0,
  6382. 'role' => 'assistant',
  6383. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6384. 'content' => $fullContent,
  6385. 'created_at' => $now,
  6386. 'updated_at' => $now
  6387. ]
  6388. ];
  6389. // 保存对话记录
  6390. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6391. if (!$boolen3) {
  6392. Utils::throwError('20003:对话记录保存失败');
  6393. }
  6394. // 单剧集模式:生成并保存剧集信息
  6395. if ($is_single) {
  6396. $anime_name = getProp($anime, 'anime_name', '未命名');
  6397. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6398. if (empty($episode_arr['acts'])) {
  6399. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6400. }
  6401. $saveResult = $this->saveEpisodeVersionData(
  6402. $anime_id,
  6403. 1,
  6404. $episode_arr,
  6405. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6406. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6407. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6408. null,
  6409. null,
  6410. false,
  6411. $content,
  6412. $now
  6413. );
  6414. $single_episode = $saveResult['episode'];
  6415. $episode_id = $saveResult['episode_id'];
  6416. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6417. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6418. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6419. 'props' => json_encode($saveResult['merged_props'], 256),
  6420. 'updated_at' => $now
  6421. ]);
  6422. if ($boolen5 === false) {
  6423. Utils::throwError('20003:单剧集主表资源同步失败');
  6424. }
  6425. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6426. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6427. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6428. $episode_record_content = '确认分镜大纲';
  6429. if ($content !== '') {
  6430. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6431. }
  6432. $episode_records = [
  6433. [
  6434. 'uid' => $uid,
  6435. 'anime_id' => $anime_id,
  6436. 'role' => 'user',
  6437. 'content' => $episode_record_content,
  6438. 'sequence' => 1,
  6439. 'episode_id' => $episode_id,
  6440. 'created_at' => $now,
  6441. 'updated_at' => $now
  6442. ],
  6443. [
  6444. 'uid' => $uid,
  6445. 'anime_id' => $anime_id,
  6446. 'role' => 'assistant',
  6447. 'content' => $fullContent,
  6448. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6449. 'sequence' => 1,
  6450. 'episode_id' => $episode_id,
  6451. 'created_at' => $now,
  6452. 'updated_at' => $now
  6453. ]
  6454. ];
  6455. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6456. if (!$boolen4) {
  6457. Utils::throwError('20003:单剧集分镜记录保存失败');
  6458. }
  6459. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6460. if ($is_single && !empty($single_episode)) {
  6461. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6462. 'anime_id' => $anime_id,
  6463. 'episode_id' => $episode_id ?? 0,
  6464. 'model' => $model,
  6465. 'source' => 'reGenerateAnime',
  6466. ]);
  6467. }
  6468. }
  6469. }catch (\Exception $e) {
  6470. DB::rollBack();
  6471. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  6472. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  6473. yield [
  6474. 'type' => 'done',
  6475. 'answer' => $fullContent,
  6476. 'reasoning' => $fullReasoningContent,
  6477. 'usage' => $usage,
  6478. 'error' => $e->getMessage(),
  6479. ];
  6480. return;
  6481. }
  6482. DB::commit();
  6483. dLog('deepseek')->info('保存完毕');
  6484. if ($is_single && !empty($single_episode)) {
  6485. // $this->batchSetGlobalRoleImg([
  6486. // 'anime_id' => $anime_id,
  6487. // ]);
  6488. // $this->batchSetGlobalSceneImg([
  6489. // 'anime_id' => $anime_id,
  6490. // ]);
  6491. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6492. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6493. }
  6494. $table_data['anime_id'] = $anime_id;
  6495. $table_data['roles'] = json_decode($table_data['roles'], true);
  6496. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6497. unset($table_data['updated_at']);
  6498. unset($table_data['status']);
  6499. yield [
  6500. 'type' => 'done',
  6501. 'script' => $table_data,
  6502. 'episode' => $single_episode,
  6503. 'answer' => $fullContent,
  6504. 'reasoning' => $fullReasoningContent,
  6505. 'usage' => $usage
  6506. ];
  6507. }
  6508. public function chat($data) {
  6509. $uid = Site::getUid();
  6510. // 积分余额预检(不足直接报错)
  6511. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  6512. $anime_id = getProp($data, 'anime_id');
  6513. $file = getProp($data, 'file');
  6514. $content = getProp($data, 'content', '');
  6515. $bid = getProp($data, 'bid', 0);
  6516. $script_id = getProp($data, 'script_id', 0);
  6517. $episode_number = getProp($data, 'episode_number', 1);
  6518. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6519. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6520. if (!$anime) Utils::throwError('20003:该对话不存在!');
  6521. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  6522. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  6523. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  6524. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  6525. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  6526. $roles = is_array($roles) ? $roles : [];
  6527. $scenes = is_array($scenes) ? $scenes : [];
  6528. // 获取最后一集序号
  6529. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  6530. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  6531. // 转换主体列表和场景列表的格式
  6532. // 获取参考主体或场景
  6533. if ((int)$episode_number === 1) {
  6534. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  6535. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  6536. }else {
  6537. $prev_episode_number = $episode_number - 1;
  6538. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  6539. }
  6540. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  6541. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  6542. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  6543. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  6544. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  6545. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  6546. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  6547. 中年女:邻居阿姨
  6548. 老年男:幽默大爷
  6549. 老年女:婆婆
  6550. 萌娃:奶气萌娃";
  6551. if ($roles_content) {
  6552. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  6553. 主体范围:\n {$roles_content}\n
  6554. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  6555. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6556. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6557. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6558. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6559. }else {
  6560. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6561. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6562. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6563. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6564. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6565. }
  6566. if ($scenes_content) {
  6567. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  6568. 场景范围:\n {$scenes_content}\n
  6569. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  6570. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6571. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6572. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  6573. }else {
  6574. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6575. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6576. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6577. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  6578. }
  6579. // 提取文件内容
  6580. if ($file) {
  6581. $uploaded_content = $this->extractFileContent($file);
  6582. if (!$uploaded_content) {
  6583. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6584. }
  6585. } elseif ($script_id) {
  6586. $uploaded_content = $this->getContentByScriptId($script_id);
  6587. if (!$uploaded_content) {
  6588. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6589. }
  6590. } elseif ($bid) {
  6591. $uploaded_content = $this->getContentByBid($bid);
  6592. if (!$uploaded_content) {
  6593. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6594. }
  6595. } elseif ($content) {
  6596. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  6597. }
  6598. // elseif ($prompt) {
  6599. // $uploaded_content = filterContent($prompt);
  6600. // }
  6601. else {
  6602. $uploaded_content = '';
  6603. }
  6604. $input_art_style = getProp($anime, 'art_style');
  6605. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6606. // 美术风格
  6607. if (!$mappedArtStyle) {
  6608. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6609. }else {
  6610. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6611. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6612. }else {
  6613. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6614. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6615. }
  6616. }
  6617. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6618. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6619. // 强制要求:
  6620. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6621. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6622. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6623. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  6624. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  6625. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  6626. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  6627. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  6628. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  6629. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  6630. // - 分镜要和场景列表、人物主体保持一致\n
  6631. // 普通要求:
  6632. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6633. // {$role_demo}
  6634. // {$scene_demo}
  6635. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6636. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6637. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6638. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  6639. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6640. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6641. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6642. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6643. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6644. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6645. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6646. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6647. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6648. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6649. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6650. // 5.$mappedArtStyle_prompt\n\n
  6651. // 示例格式:\n
  6652. // 第1集:隐形的守护者
  6653. // ###故事梗概
  6654. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6655. // ###美术风格
  6656. // 基础画风风格词:韩漫二次元
  6657. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6658. // ###主体列表
  6659. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6660. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6661. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6662. // ###场景列表
  6663. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6664. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6665. // 无人物。}
  6666. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6667. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6668. // 无人物。}
  6669. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6670. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6671. // 无人物。}
  6672. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6673. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6674. // 无人物。}
  6675. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6676. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6677. // 无人物。}
  6678. // ###分镜剧本
  6679. // ##第1幕:徐家老旧厨房 白天 室内
  6680. // 分镜1
  6681. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6682. // 场景:徐家老旧厨房
  6683. // 构图设计:全景,低角度仰视
  6684. // 运镜调度:手持拍摄
  6685. // 配音角色:旁白
  6686. // 出镜角色:许芸-校服装、徐母
  6687. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6688. // 画面类型:普通画面
  6689. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6690. // 分镜2
  6691. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6692. // 场景:徐家老旧厨房
  6693. // 构图设计:近景,徐母面部特写
  6694. // 运镜调度:固定镜头
  6695. // 配音角色:徐母
  6696. // 出镜角色:徐母
  6697. // 台词内容:问我夜不归宿死哪儿去了。
  6698. // 画面类型:对口型
  6699. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6700. // ##第2幕:徐家简陋客厅 黄昏 室内
  6701. // 分镜3
  6702. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6703. // 场景:徐家简陋客厅
  6704. // 构图设计:全景,景深虚化
  6705. // 运镜调度:固定镜头
  6706. // 配音角色:旁白
  6707. // 出镜角色:无
  6708. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6709. // 画面类型:普通画面
  6710. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6711. // 分镜4
  6712. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6713. // 场景:徐家简陋客厅
  6714. // 构图设计:特写,火车票
  6715. // 运镜调度:固定镜头
  6716. // 配音角色:旁白
  6717. // 出镜角色:无
  6718. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6719. // 画面类型:普通画面
  6720. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6721. // \n\n";
  6722. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  6723. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  6724. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  6725. 普通要求:
  6726. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6727. {$role_demo}
  6728. {$scene_demo}
  6729. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6730. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6731. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6732. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6733. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6734. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6735. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6736. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6737. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6738. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6739. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6740. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6741. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6742. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6743. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6744. 5.$mappedArtStyle_prompt
  6745. 6.《情绪-视听语言映射表》:
  6746. 6.1 场景空间与时间心理学 (Scene & Temporality)
  6747. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6748. -----|---------|------------|----------------
  6749. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  6750. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  6751. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  6752. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  6753. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  6754. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6755. -----|---------|------------|----------------
  6756. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  6757. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  6758. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  6759. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  6760. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  6761. --------|---------|--------------|-------------
  6762. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  6763. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  6764. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  6765. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  6766. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  6767. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  6768. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  6769. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  6770. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  6771. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  6772. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  6773. -----|---------|------------|------------
  6774. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  6775. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  6776. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  6777. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  6778. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  6779. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  6780. --------|---------|--------------|----------
  6781. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  6782. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  6783. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  6784. 6.6 声音设计与潜意识影响 (Soundscape)
  6785. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  6786. -----|---------|------------|------------------
  6787. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  6788. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  6789. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  6790. 理论基石:
  6791. - The Five C's of Cinematography by Joseph V. Mascelli
  6792. - Film Art: An Introduction by David Bordwell
  6793. - Sight, Sound, Motion by Herbert Zettl
  6794. - Notes on the Cinematograph by Robert Bresson
  6795. \n\n
  6796. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  6797. 示例格式:\n
  6798. 第1集:隐形的守护者
  6799. ###故事梗概
  6800. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6801. ###美术风格
  6802. 基础画风风格词:韩漫二次元
  6803. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6804. ###主体列表
  6805. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6806. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6807. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6808. ###场景列表
  6809. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6810. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6811. 无人物。}
  6812. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6813. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6814. 无人物。}
  6815. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6816. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6817. 无人物。}
  6818. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6819. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6820. 无人物。}
  6821. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6822. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6823. 无人物。}
  6824. ###分镜剧本
  6825. ##第1幕:徐家老旧厨房 白天 室内
  6826. 分镜1
  6827. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6828. 场景:徐家老旧厨房
  6829. 构图设计:全景,低角度仰视
  6830. 运镜调度:手持拍摄
  6831. 配音角色:旁白
  6832. 出镜角色:许芸-校服装、徐母
  6833. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6834. 画面类型:普通画面
  6835. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6836. 分镜2
  6837. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6838. 场景:徐家老旧厨房
  6839. 构图设计:近景,徐母面部特写
  6840. 运镜调度:固定镜头
  6841. 配音角色:徐母
  6842. 出镜角色:徐母
  6843. 台词内容:问我夜不归宿死哪儿去了。
  6844. 画面类型:对口型
  6845. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6846. ##第2幕:徐家简陋客厅 黄昏 室内
  6847. 分镜3
  6848. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6849. 场景:徐家简陋客厅
  6850. 构图设计:全景,景深虚化
  6851. 运镜调度:固定镜头
  6852. 配音角色:旁白
  6853. 出镜角色:无
  6854. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6855. 画面类型:普通画面
  6856. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6857. 分镜4
  6858. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6859. 场景:徐家简陋客厅
  6860. 构图设计:特写,火车票
  6861. 运镜调度:固定镜头
  6862. 配音角色:旁白
  6863. 出镜角色:无
  6864. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6865. 画面类型:普通画面
  6866. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6867. \n\n";
  6868. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6869. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  6870. $is_regenerate_version = true;
  6871. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  6872. $prompt = $origin_prompt;
  6873. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  6874. // 获取章节内容
  6875. $full_content = getProp($anime, 'content');
  6876. if ($uploaded_content) {
  6877. $full_content = $uploaded_content;
  6878. }
  6879. // 根据章节内容拆分章节
  6880. $chapters = splitContent($full_content);
  6881. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  6882. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  6883. $messages = [];
  6884. if ($prompt == '确认分镜大纲') {
  6885. // 暂时保留
  6886. $content = $chapter_content;
  6887. if ($is_single) $content = $full_content; // 单剧集使用全文
  6888. if (!$content) {
  6889. Utils::throwError('20003:章节内容无法获取,请确认');
  6890. }
  6891. $question = $is_single
  6892. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  6893. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  6894. // 构建消息
  6895. $messages[] =
  6896. [
  6897. 'role' => 'user',
  6898. 'content' => $question
  6899. ];
  6900. }else if ($prompt == '继续策划下一集') {
  6901. if ($is_single) {
  6902. Utils::throwError('20003:单剧集不支持继续策划下一集');
  6903. }
  6904. $content = $chapter_content;
  6905. if (!$content) {
  6906. Utils::throwError('20003:章节内容无法获取,请确认');
  6907. }
  6908. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  6909. // 获取上一集最后记录
  6910. $prev_sequence = $episode_number - 1;
  6911. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  6912. // 构建消息
  6913. $messages[] =
  6914. [
  6915. 'role' => 'user',
  6916. 'content' => $question
  6917. ];
  6918. }else {
  6919. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  6920. if (!$content) {
  6921. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  6922. }
  6923. if (!$content) {
  6924. Utils::throwError('20003:章节内容无法获取,请确认');
  6925. }
  6926. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  6927. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  6928. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  6929. if ($origin_prompt) {
  6930. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  6931. }
  6932. $messages[] =
  6933. [
  6934. 'role' => 'user',
  6935. 'content' => $question
  6936. ];
  6937. }
  6938. // 处理文本模型
  6939. $model = getProp($data, 'model');
  6940. if (!$model) {
  6941. // 用户没有输入,从anime表获取
  6942. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6943. $model = getProp($anime, 'model');
  6944. if (!$model) {
  6945. // anime表也没有,使用默认值
  6946. $model = 'doubao-seed-2-0-mini-260215';
  6947. }
  6948. }
  6949. // 验证模型是否在可用模型表中
  6950. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6951. $model = 'doubao-seed-2-0-mini-260215';
  6952. }
  6953. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6954. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6955. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6956. if ($model === 'deepseek-chat') {
  6957. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6958. $model = 'deepseek-v4-flash';
  6959. $thinkingMode = 'disabled';
  6960. } elseif ($model === 'deepseek-reasoner') {
  6961. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6962. $model = 'deepseek-v4-flash';
  6963. $thinkingMode = 'enabled';
  6964. }
  6965. $post_data = [
  6966. 'model' => $model,
  6967. 'messages' => $messages,
  6968. // 'max_tokens' => 8192,
  6969. 'temperature' => 0.2,
  6970. 'frequency_penalty' => 0,
  6971. 'presence_penalty' => 0,
  6972. 'response_format' => ['type' => 'text'],
  6973. 'thinking' => ['type' => $thinkingMode],
  6974. 'stream' => true // 启用流式输出
  6975. ];
  6976. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6977. // 根据模型类型选择调用方法
  6978. $fullContent = '';
  6979. $fullReasoningContent = '';
  6980. $usage = [];
  6981. try {
  6982. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6983. // DeepSeek 官方模型使用 DeepSeek API
  6984. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6985. } else if (in_array($model, $this->gpt_text_models)) {
  6986. // GPT-5.4 模型使用 TokenRouter API
  6987. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6988. } else if (in_array($model, $this->gemini_text_models)) {
  6989. // Gemini 模型使用 Gemini API
  6990. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6991. } else {
  6992. // 其他模型使用火山引擎API
  6993. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6994. }
  6995. // 验证返回值类型
  6996. if (!is_iterable($streamGenerator)) {
  6997. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6998. dLog('deepseek')->error('chat流式生成器无效', [
  6999. 'generator_type' => $errorType,
  7000. 'model' => $model,
  7001. 'anime_id' => $anime_id,
  7002. 'episode_number' => $episode_number
  7003. ]);
  7004. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7005. 'type' => $errorType,
  7006. 'model' => $model
  7007. ]);
  7008. yield [
  7009. 'type' => 'error',
  7010. 'episode' => [],
  7011. 'answer' => '',
  7012. 'reasoning' => '',
  7013. 'usage' => [],
  7014. 'error' => '接口返回数据异常,请重新请求'
  7015. ];
  7016. return;
  7017. }
  7018. // 处理流式输出
  7019. foreach ($streamGenerator as $chunk) {
  7020. if (isset($chunk['type'])) {
  7021. if ($chunk['type'] === 'done') {
  7022. // 最终结果
  7023. $fullContent = $chunk['full_content'];
  7024. $fullReasoningContent = $chunk['full_reasoning'];
  7025. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7026. } else {
  7027. // 逐块yield数据
  7028. yield $chunk;
  7029. }
  7030. }
  7031. }
  7032. } catch (\Exception $e) {
  7033. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7034. 'model' => $model,
  7035. 'anime_id' => $anime_id,
  7036. 'episode_number' => $episode_number,
  7037. 'trace' => $e->getTraceAsString()
  7038. ]);
  7039. logDB('deepseek', 'error', 'chat流式处理失败', [
  7040. 'error' => $e->getMessage(),
  7041. 'model' => $model
  7042. ]);
  7043. yield [
  7044. 'type' => 'error',
  7045. 'episode' => [],
  7046. 'answer' => '',
  7047. 'reasoning' => '',
  7048. 'usage' => [],
  7049. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7050. ];
  7051. return;
  7052. }
  7053. dLog('deepseek')->info('完整内容: '.$fullContent);
  7054. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7055. // 处理完整内容并返回最终结果
  7056. $episode_arr = handleEpisodeContent($fullContent);
  7057. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7058. if (empty($episode_arr['acts'])) {
  7059. // 未生成剧本相关内容,保存对话记录并返回提示
  7060. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  7061. try {
  7062. $now = date('Y-m-d H:i:s');
  7063. // 保存对话记录
  7064. $records = [
  7065. [
  7066. 'uid' => $uid,
  7067. 'anime_id' => $anime_id,
  7068. 'sequence' => $episode_number,
  7069. 'role' => 'user',
  7070. 'content' => $prompt,
  7071. 'created_at' => $now,
  7072. 'updated_at' => $now
  7073. ],
  7074. [
  7075. 'uid' => $uid,
  7076. 'anime_id' => $anime_id,
  7077. 'sequence' => $episode_number,
  7078. 'role' => 'assistant',
  7079. 'content' => $fullContent,
  7080. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7081. 'created_at' => $now,
  7082. 'updated_at' => $now
  7083. ]
  7084. ];
  7085. DB::table('mp_anime_records')->insert($records);
  7086. } catch (\Exception $e) {
  7087. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7088. }
  7089. yield [
  7090. 'type' => 'done',
  7091. 'episode' => [],
  7092. 'answer' => $fullContent,
  7093. 'reasoning' => $fullReasoningContent,
  7094. 'usage' => $usage,
  7095. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  7096. ];
  7097. return;
  7098. }
  7099. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  7100. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  7101. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  7102. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  7103. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  7104. $existing_props = is_array($existing_props) ? $existing_props : [];
  7105. $now = date('Y-m-d H:i:s');
  7106. try {
  7107. DB::beginTransaction();
  7108. $saveResult = $this->saveEpisodeVersionData(
  7109. $anime_id,
  7110. $episode_number,
  7111. $episode_arr,
  7112. $existing_roles,
  7113. $existing_scenes,
  7114. $existing_props,
  7115. $current_episode,
  7116. $base_episode,
  7117. $is_regenerate_version,
  7118. $content,
  7119. $now
  7120. );
  7121. $episode = $saveResult['episode'];
  7122. $episode_id = $saveResult['episode_id'];
  7123. $merged_roles = $saveResult['merged_roles'];
  7124. $merged_scenes = $saveResult['merged_scenes'];
  7125. $merged_props = $saveResult['merged_props'];
  7126. $record_content = $origin_prompt;
  7127. if ($uploaded_content !== '') {
  7128. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  7129. }
  7130. $records = [
  7131. [
  7132. 'uid' => $uid,
  7133. 'anime_id' => $anime_id,
  7134. 'role' => 'user',
  7135. 'content' => $record_content,
  7136. 'sequence' => $episode_number,
  7137. 'episode_id' => $episode_id,
  7138. 'created_at' => $now,
  7139. 'updated_at' => $now
  7140. ],
  7141. [
  7142. 'uid' => $uid,
  7143. 'anime_id' => $anime_id,
  7144. 'role' => 'assistant',
  7145. 'content' => $fullContent,
  7146. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7147. 'sequence' => $episode_number,
  7148. 'episode_id' => $episode_id,
  7149. 'created_at' => $now,
  7150. 'updated_at' => $now
  7151. ]
  7152. ];
  7153. $boolen4 = DB::table('mp_anime_records')->insert($records);
  7154. if (!$boolen4) {
  7155. Utils::throwError('20003:对话记录保存失败');
  7156. }
  7157. // 保存模型和内容到anime表
  7158. $update_anime_data = [
  7159. 'model' => $model,
  7160. 'updated_at' => $now
  7161. ];
  7162. if ($uploaded_content) {
  7163. $update_anime_data['content'] = $uploaded_content;
  7164. }
  7165. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  7166. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7167. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7168. 'anime_id' => $anime_id,
  7169. 'episode_number' => $episode_number,
  7170. 'model' => $model,
  7171. 'source' => 'chat',
  7172. ]);
  7173. }catch (\Exception $e) {
  7174. DB::rollBack();
  7175. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7176. yield [
  7177. 'type' => 'done',
  7178. 'answer' => $fullContent,
  7179. 'reasoning' => $fullReasoningContent,
  7180. 'usage' => $usage,
  7181. 'error' => $e->getMessage(),
  7182. ];
  7183. return;
  7184. }
  7185. DB::commit();
  7186. if ($is_global_generate_pics) {
  7187. // // 批量生成全局角色图片
  7188. // $this->batchSetGlobalRoleImg([
  7189. // 'anime_id' => $anime_id,
  7190. // ], true);
  7191. // // 批量生成全局场景图片
  7192. // $this->batchSetGlobalSceneImg([
  7193. // 'anime_id' => $anime_id,
  7194. // ], true);
  7195. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7196. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7197. }
  7198. $episode['episode_id'] = $episode_id;
  7199. $episode['roles'] = $merged_roles;
  7200. $episode['scenes'] = $merged_scenes;
  7201. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  7202. yield [
  7203. 'type' => 'done',
  7204. 'episode' => $episode,
  7205. 'answer' => $fullContent,
  7206. 'reasoning' => $fullReasoningContent,
  7207. 'usage' => $usage
  7208. ];
  7209. }
  7210. public function addChatForAce($data) {
  7211. $uid = Site::getUid();
  7212. $anime_id = getProp($data, 'anime_id');
  7213. if (!$anime_id) Utils::throwError('20003:请选择对话');
  7214. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  7215. if (!$anime) Utils::throwError('20003:对话不存在');
  7216. $file = getProp($data, 'file');
  7217. $content = getProp($data, 'content', '');
  7218. $bid = getProp($data, 'bid', 0);
  7219. $script_id = getProp($data, 'script_id', 0);
  7220. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  7221. $prompt = getProp($data, 'prompt');
  7222. $is_multi = getProp($anime, 'is_multi');
  7223. $is_single = (int)$is_multi !== 1;
  7224. // 积分余额预检(仅单剧集模式收费)
  7225. if ($is_single) {
  7226. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  7227. }
  7228. $extra_products = getProp($data, 'products', []);
  7229. if (!$extra_products) {
  7230. $extra_products = getProp($anime, 'extra_products');
  7231. if ($extra_products) {
  7232. $extra_products = json_decode($extra_products, true);
  7233. }else {
  7234. $extra_products = [];
  7235. }
  7236. }else {
  7237. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7238. }
  7239. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7240. $anime_script_id = getProp($anime, 'script_id');
  7241. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  7242. $cpid = Site::getCpid();
  7243. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7244. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7245. ->where('mapping.script_id', $anime_script_id)
  7246. ->where('product.cpid', $cpid)
  7247. ->where('product.is_deleted', 0);
  7248. $mappings = $script_products_mappings->select(
  7249. 'mapping.product_id',
  7250. 'mapping.episode_number',
  7251. 'product.product_name',
  7252. 'product.type',
  7253. 'product.product',
  7254. 'product.pic_prompt',
  7255. 'product.url',
  7256. 'product.pic_task_id',
  7257. 'product.pic_task_status',
  7258. 'product.three_view_image_url'
  7259. )
  7260. ->get();
  7261. // 按 product_id 分组,合并 episode_number
  7262. $productMap = [];
  7263. foreach ($mappings as $item) {
  7264. $product_id = $item->product_id;
  7265. $product_name = $item->product_name;
  7266. // 处理product_name两边的符号
  7267. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7268. if (!isset($productMap[$product_id])) {
  7269. $productMap[$product_id] = [
  7270. 'product_id' => $product_id,
  7271. 'product_name' => $product_name,
  7272. 'type' => (int)$item->type,
  7273. 'product' => (int)$item->product,
  7274. 'pic_prompt' => $item->pic_prompt,
  7275. 'url' => $item->url,
  7276. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7277. 'pic_task_id' => $item->pic_task_id,
  7278. 'pic_task_status' => $item->pic_task_status,
  7279. 'episode_numbers' => [],
  7280. ];
  7281. }
  7282. // 添加 episode_number(去重)
  7283. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7284. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7285. }
  7286. }
  7287. // 将查询到的剧本资产合并到extra_products中
  7288. // 先构建extra_products的索引(以product_id为key,用于去重)
  7289. $extraProductsMap = [];
  7290. foreach ($extra_products as $item) {
  7291. $key = getProp($item, 'product_id');
  7292. if ($key) {
  7293. $extraProductsMap[$key] = $item;
  7294. }
  7295. }
  7296. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7297. foreach ($productMap as $product) {
  7298. $product_id = $product['product_id'];
  7299. // 如果不存在则添加(不带episode_number信息)
  7300. if (!isset($extraProductsMap[$product_id])) {
  7301. $extraProductsMap[$product_id] = [
  7302. 'product_id' => $product['product_id'],
  7303. 'product_name' => $product['product_name'],
  7304. 'type' => $product['type'],
  7305. 'product' => $product['product'],
  7306. 'pic_prompt' => $product['pic_prompt'],
  7307. 'url' => $product['url'],
  7308. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  7309. 'pic_task_id' => $product['pic_task_id'],
  7310. 'pic_task_status' => $product['pic_task_status'],
  7311. ];
  7312. }
  7313. }
  7314. // 重新赋值给extra_products
  7315. $extra_products = array_values($extraProductsMap);
  7316. }
  7317. $user_anime_name = getProp($anime, 'anime_name');
  7318. // 处理提示词
  7319. if ($prompt && $extra_products) {
  7320. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7321. foreach($extra_products as $item) {
  7322. $product_name = getProp($item, 'product_name');
  7323. if ($product_name) {
  7324. // 替换 {product_name} 为 product_name
  7325. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7326. }
  7327. }
  7328. }
  7329. // 处理文本模型
  7330. $model = getProp($data, 'model');
  7331. if (!$model) {
  7332. // 用户没有输入,从anime表获取
  7333. $model = getProp($anime, 'model');
  7334. if (!$model) {
  7335. // anime表也没有,使用默认值
  7336. $model = 'deepseek-v4-pro';
  7337. }
  7338. }
  7339. // 验证模型是否在可用模型表中
  7340. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7341. $model = 'deepseek-v4-pro';
  7342. }
  7343. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7344. if ($prompt) {
  7345. $question .= "本次修改要求如下:\n{$prompt}";
  7346. }
  7347. // if (!$file && !$content && !$bid) {
  7348. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  7349. // }
  7350. // 提取文件内容
  7351. if ($file) {
  7352. $content = $this->extractFileContent($file);
  7353. if (!$content) {
  7354. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7355. }
  7356. } elseif ($script_id) {
  7357. $content = $this->getContentByScriptId($script_id);
  7358. if (!$content) {
  7359. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7360. }
  7361. } elseif ($bid) {
  7362. $content = $this->getContentByBid($bid);
  7363. if (!$content) {
  7364. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7365. }
  7366. } elseif ($content) {
  7367. $content = filterContent($content);
  7368. } else {
  7369. $content = getProp($anime, 'content');
  7370. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7371. $need_generate_content = true;
  7372. }
  7373. }
  7374. // 美术风格
  7375. $input_art_style = getProp($data, 'art_style');
  7376. if (!$input_art_style) {
  7377. $mappedArtStyle = getProp($anime, 'art_style');
  7378. }else {
  7379. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7380. }
  7381. // 判断是否需要生成原文内容
  7382. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7383. // 如果需要生成原文内容,添加额外的要求
  7384. $content_generation_requirement = $need_generate_content
  7385. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7386. : "";
  7387. // 美术风格
  7388. if (!$mappedArtStyle) {
  7389. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7390. }else {
  7391. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7392. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7393. }else {
  7394. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7395. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7396. }
  7397. }
  7398. // 构建主体、场景和道具提示词
  7399. $extra_role_prompt = "\n";
  7400. $extra_scene_prompt = "\n";
  7401. $extra_prop_prompt = "\n";
  7402. $extra_roles = [];
  7403. $extra_scenes = [];
  7404. $extra_props = [];
  7405. $ref_products = []; // 参考资产
  7406. if ($extra_products) {
  7407. foreach($extra_products as $item) {
  7408. $product = getProp($item, 'product');
  7409. $product_name = getProp($item, 'product_name');
  7410. if ($product_name == '旁白') continue;
  7411. $ref_products[$product_name] = $item;
  7412. $pic_prompt = getProp($item, 'pic_prompt');
  7413. if ((int)$product === 1) {
  7414. // 拼接角色信息
  7415. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7416. $extra_roles[$product_name] = [
  7417. 'role' => $product_name,
  7418. 'pic_prompt' => $pic_prompt,
  7419. 'url' => getProp($item, 'url', ''),
  7420. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7421. ];
  7422. } elseif ((int)$product === 2) {
  7423. // 拼接场景信息
  7424. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7425. $extra_scenes[$product_name] = [
  7426. 'scene' => $product_name,
  7427. 'pic_prompt' => $pic_prompt,
  7428. 'url' => getProp($item, 'url', ''),
  7429. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7430. ];
  7431. } elseif ((int)$product === 3) {
  7432. // 拼接道具信息
  7433. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7434. $extra_props[$product_name] = [
  7435. 'prop' => $product_name,
  7436. 'pic_prompt' => $pic_prompt,
  7437. 'url' => getProp($item, 'url', ''),
  7438. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7439. ];
  7440. }
  7441. }
  7442. // 优化提示词,融入剧本
  7443. if (!empty(trim($extra_role_prompt))) {
  7444. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7445. }
  7446. if (!empty(trim($extra_scene_prompt))) {
  7447. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7448. }
  7449. if (!empty(trim($extra_prop_prompt))) {
  7450. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7451. }
  7452. }
  7453. if ($anime_script_id && $is_single) {
  7454. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7455. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7456. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7457. }else {
  7458. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7459. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7460. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7461. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7462. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7463. {$extra_role_prompt}";
  7464. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7465. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7466. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7467. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7468. {$extra_scene_prompt}";
  7469. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7470. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7471. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7472. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7473. {$extra_prop_prompt}";
  7474. }
  7475. $systemPrompt = $is_single
  7476. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7477. 强制要求:
  7478. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7479. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7480. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7481. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7482. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7483. 普通要求:
  7484. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7485. $role_demo
  7486. $scene_demo
  7487. $prop_demo
  7488. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7489. 5.1片段分割逻辑(优先级从高到低):
  7490. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7491. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7492. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7493. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7494. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7495. - 片段数量格式为: 片段数量:8
  7496. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7497. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7498. 5.3分镜结构:每个分镜包含以下字段:
  7499. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  7500. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7501. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7502. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7503. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7504. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7505. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7506. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7507. - 运镜:场景+画面描述+运镜
  7508. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7509. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7510. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7511. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7512. 6.《情绪-视听语言映射表》:
  7513. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7514. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7515. -----|---------|------------|----------------
  7516. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7517. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7518. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7519. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7520. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7521. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7522. -----|---------|------------|----------------
  7523. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7524. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7525. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7526. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7527. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7528. --------|---------|--------------|-------------
  7529. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7530. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7531. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7532. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7533. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7534. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7535. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7536. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7537. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7538. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7539. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7540. -----|---------|------------|------------
  7541. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7542. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7543. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7544. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7545. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7546. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7547. --------|---------|--------------|----------
  7548. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7549. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7550. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7551. 6.6 声音设计与潜意识影响 (Soundscape)
  7552. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7553. -----|---------|------------|------------------
  7554. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7555. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7556. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7557. 理论基石:
  7558. - The Five C's of Cinematography by Joseph V. Mascelli
  7559. - Film Art: An Introduction by David Bordwell
  7560. - Sight, Sound, Motion by Herbert Zettl
  7561. - Notes on the Cinematograph by Robert Bresson
  7562. \n\n
  7563. 7.{$mappedArtStyle_prompt}\n\n
  7564. 示例如下:\n
  7565. ###剧本名:西昆仑
  7566. ###故事梗概
  7567. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7568. ###剧本亮点
  7569. 亮点1:绝境奇药,生死一线
  7570. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7571. 亮点2:结拜兄妹,化解尴尬
  7572. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7573. 亮点3:纤发夺命,情愫暗涌
  7574. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7575. ###人物关系
  7576. 阿雪与梁萧之间存在兄妹之情。
  7577. ###核心矛盾
  7578. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7579. ###主体列表
  7580. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7581. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7582. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7583. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7584. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7585. 全景,正面拍摄,青年女性,亚洲人。
  7586. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7587. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7588. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7589. ###美术风格
  7590. 基础画风风格词:厚涂古风
  7591. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7592. ###场景列表
  7593. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7594. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7595. 无人物。}
  7596. ###分段剧本
  7597. 片段数量:8
  7598. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7599. ##片段1
  7600. 时长:12s
  7601. 分镜1
  7602. 出场角色:刀疤脸
  7603. 场景:边境小镇街道
  7604. 出场道具:酒杯-高脚杯
  7605. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7606. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7607. 配音台词:
  7608. 背景音效:
  7609. 分镜2
  7610. 出场角色:刀疤脸
  7611. 场景:悦来酒馆
  7612. 出场道具:酒杯-高脚杯
  7613. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7614. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7615. 配音台词:
  7616. 背景音效:
  7617. 分镜3
  7618. 出场角色:刀疤脸
  7619. 场景:悦来酒馆
  7620. 出场道具:酒杯-高脚杯
  7621. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7622. 运镜:从中景推向令牌特写。
  7623. 配音台词:
  7624. 背景音效:
  7625. 分镜4
  7626. 出场角色:刀疤脸
  7627. 场景:悦来酒馆
  7628. 出场道具:酒杯-高脚杯
  7629. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7630. 运镜:极速推向酒水溅起的瞬间。
  7631. 配音台词:
  7632. 背景音效:
  7633. 分镜5
  7634. 出场角色:刀疤脸
  7635. 场景:悦来酒馆
  7636. 出场道具:酒杯-高脚杯
  7637. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7638. 运镜:固定机位,利用倾斜构图制造压迫感。
  7639. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7640. 背景音效:
  7641. \n\n"
  7642. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7643. 强制要求:\n
  7644. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7645. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7646. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7647. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7648. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7649. 普通要求:\n
  7650. 1.剧本名(必须生成)必须与文档内容高度相关
  7651. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7652. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7653. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7654. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7655. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7656. {$extra_role_prompt}
  7657. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7658. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7659. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7660. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7661. {$extra_scene_prompt}
  7662. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7663. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7664. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7665. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7666. {$extra_prop_prompt}
  7667. 5.{$mappedArtStyle_prompt}\n\n
  7668. 示例如下:\n
  7669. ###剧本名:西昆仑
  7670. ###故事梗概
  7671. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7672. ###剧本亮点
  7673. 亮点1:绝境奇药,生死一线
  7674. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7675. 亮点2:结拜兄妹,化解尴尬
  7676. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7677. 亮点3:纤发夺命,情愫暗涌
  7678. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7679. ###人物关系
  7680. 阿雪与梁萧之间存在兄妹之情。
  7681. ###核心矛盾
  7682. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7683. ###主体列表
  7684. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7685. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7686. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7687. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7688. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7689. 全景,正面拍摄,青年女性,亚洲人。
  7690. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7691. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7692. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7693. ###美术风格
  7694. 基础画风风格词:厚涂古风
  7695. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7696. ###场景列表
  7697. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7698. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7699. 无人物。}
  7700. ###道具列表
  7701. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  7702. // 构建消息
  7703. $messages = [
  7704. [
  7705. 'role' => 'system',
  7706. 'content' => $systemPrompt
  7707. ],
  7708. [
  7709. 'role' => 'user',
  7710. 'content' => "以下是文档内容:
  7711. {$content}
  7712. 用户问题:
  7713. {$question}"
  7714. ]
  7715. ];
  7716. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7717. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7718. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7719. if ($model === 'deepseek-chat') {
  7720. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7721. $model = 'deepseek-v4-flash';
  7722. $thinkingMode = 'disabled';
  7723. } elseif ($model === 'deepseek-reasoner') {
  7724. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7725. $model = 'deepseek-v4-flash';
  7726. $thinkingMode = 'enabled';
  7727. }
  7728. $post_data = [
  7729. 'model' => $model,
  7730. 'messages' => $messages,
  7731. // 'max_tokens' => 8192,
  7732. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7733. 'frequency_penalty' => 0,
  7734. 'presence_penalty' => 0,
  7735. 'response_format' => ['type' => 'text'],
  7736. 'thinking' => ['type'=>$thinkingMode],
  7737. 'stream' => true // 启用流式输出
  7738. ];
  7739. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7740. // 根据模型类型选择调用方法
  7741. $fullContent = '';
  7742. $fullReasoningContent = '';
  7743. $usage = [];
  7744. try {
  7745. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7746. // DeepSeek 官方模型使用 DeepSeek API
  7747. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7748. } else if (in_array($model, $this->gpt_text_models)) {
  7749. // GPT-5.4 模型使用 TokenRouter API
  7750. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7751. } else if (in_array($model, $this->gemini_text_models)) {
  7752. // Gemini 模型使用 Gemini API
  7753. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  7754. } else {
  7755. // 其他模型使用火山引擎API
  7756. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7757. }
  7758. // 验证返回值类型
  7759. if (!is_iterable($streamGenerator)) {
  7760. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7761. dLog('deepseek')->error('addChat流式生成器无效', [
  7762. 'generator_type' => $errorType,
  7763. 'model' => $model,
  7764. 'anime_id' => $anime_id
  7765. ]);
  7766. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  7767. 'type' => $errorType,
  7768. 'model' => $model
  7769. ]);
  7770. yield [
  7771. 'type' => 'error',
  7772. 'script' => [],
  7773. 'episode' => [],
  7774. 'answer' => '',
  7775. 'reasoning' => '',
  7776. 'usage' => [],
  7777. 'error' => '接口返回数据异常,请重新请求'
  7778. ];
  7779. return;
  7780. }
  7781. // 处理流式输出
  7782. foreach ($streamGenerator as $chunk) {
  7783. if (isset($chunk['type'])) {
  7784. if ($chunk['type'] === 'done') {
  7785. // 最终结果
  7786. $fullContent = $chunk['full_content'];
  7787. $fullReasoningContent = $chunk['full_reasoning'];
  7788. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7789. } else {
  7790. // 逐块yield数据
  7791. yield $chunk;
  7792. }
  7793. }
  7794. }
  7795. } catch (\Exception $e) {
  7796. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  7797. 'model' => $model,
  7798. 'anime_id' => $anime_id,
  7799. 'trace' => $e->getTraceAsString()
  7800. ]);
  7801. logDB('deepseek', 'error', 'addChat流式处理失败', [
  7802. 'error' => $e->getMessage(),
  7803. 'model' => $model
  7804. ]);
  7805. yield [
  7806. 'type' => 'error',
  7807. 'script' => [],
  7808. 'episode' => [],
  7809. 'answer' => '',
  7810. 'reasoning' => '',
  7811. 'usage' => [],
  7812. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7813. ];
  7814. return;
  7815. }
  7816. dLog('deepseek')->info('完整内容: '.$fullContent);
  7817. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7818. // 处理完整内容并返回最终结果
  7819. $script_arr = [];
  7820. if ($fullContent) {
  7821. $script_arr = handleScriptContentForAce($fullContent);
  7822. dLog('deepseek')->info('解析内容', $script_arr);
  7823. logDB('deepseek', 'info', '解析内容', $script_arr);
  7824. }
  7825. if (empty($script_arr['roles'])) {
  7826. // 未生成剧本相关内容,保存对话记录并返回提示
  7827. dLog('deepseek')->info('未生成剧本相关的内容');
  7828. try {
  7829. DB::beginTransaction();
  7830. $now = date('Y-m-d H:i:s');
  7831. // 保存对话记录
  7832. $records = [
  7833. [
  7834. 'uid' => $uid,
  7835. 'anime_id' => $anime_id,
  7836. 'sequence' => 0,
  7837. 'role' => 'user',
  7838. 'content' => $prompt,
  7839. 'created_at' => $now,
  7840. 'updated_at' => $now
  7841. ],
  7842. [
  7843. 'uid' => $uid,
  7844. 'anime_id' => $anime_id,
  7845. 'sequence' => 0,
  7846. 'role' => 'assistant',
  7847. // 'content' => $fullContent,
  7848. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  7849. 'created_at' => $now,
  7850. 'updated_at' => $now
  7851. ]
  7852. ];
  7853. DB::table('mp_anime_records')->insert($records);
  7854. DB::commit();
  7855. } catch (\Exception $e) {
  7856. DB::rollBack();
  7857. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7858. }
  7859. yield [
  7860. 'type' => 'done',
  7861. 'script' => [],
  7862. 'episode' => [],
  7863. 'answer' => $fullContent,
  7864. 'reasoning' => $fullReasoningContent,
  7865. 'usage' => $usage,
  7866. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  7867. ];
  7868. return;
  7869. }
  7870. // 如果需要生成原文内容,从script_arr中提取
  7871. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  7872. $content = $script_arr['content'];
  7873. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  7874. if (!$content) {
  7875. yield [
  7876. 'type' => 'done',
  7877. 'script' => [],
  7878. 'episode' => [],
  7879. 'answer' => $fullContent,
  7880. 'reasoning' => $fullReasoningContent,
  7881. 'usage' => $usage,
  7882. 'error' => '未生成剧本内容,请调整提示词再试'
  7883. ];
  7884. return;
  7885. }
  7886. }
  7887. // 替换美术风格
  7888. if ($mappedArtStyle !== '') {
  7889. $script_arr['art_style'] = $mappedArtStyle;
  7890. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  7891. }
  7892. // 新建动漫
  7893. if ($user_anime_name == '新剧本策划') {
  7894. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  7895. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  7896. // if (!$anime_name) {
  7897. // // 未识别到剧本名,保存对话记录并返回提示
  7898. // dLog('deepseek')->info('未能识别到剧本名称');
  7899. // try {
  7900. // DB::beginTransaction();
  7901. // $now = date('Y-m-d H:i:s');
  7902. // // 保存对话记录
  7903. // $records = [
  7904. // [
  7905. // 'uid' => $uid,
  7906. // 'anime_id' => $anime_id,
  7907. // 'sequence' => 0,
  7908. // 'role' => 'user',
  7909. // 'content' => $prompt,
  7910. // 'created_at' => $now,
  7911. // 'updated_at' => $now
  7912. // ],
  7913. // [
  7914. // 'uid' => $uid,
  7915. // 'anime_id' => $anime_id,
  7916. // 'sequence' => 0,
  7917. // 'role' => 'assistant',
  7918. // 'content' => '未能生成剧本名称,请重试',
  7919. // 'created_at' => $now,
  7920. // 'updated_at' => $now
  7921. // ]
  7922. // ];
  7923. // DB::table('mp_anime_records')->insert($records);
  7924. // DB::commit();
  7925. // } catch (\Exception $e) {
  7926. // DB::rollBack();
  7927. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7928. // }
  7929. // yield [
  7930. // 'type' => 'done',
  7931. // 'script' => [],
  7932. // 'episode' => [],
  7933. // 'answer' => $fullContent,
  7934. // 'reasoning' => $fullReasoningContent,
  7935. // 'usage' => $usage,
  7936. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  7937. // ];
  7938. // return;
  7939. // }
  7940. // 确认对话名称唯一性
  7941. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  7942. $anime_name = $anime_name . '_' . date('YmdHis');
  7943. }
  7944. }else {
  7945. $anime_name = $user_anime_name;
  7946. }
  7947. // 单剧集模式:按 chatForAce 逻辑校验并重试生成剧集与分段剧本
  7948. if ($is_single) {
  7949. $max_retries = 3;
  7950. $retry_count = 0;
  7951. $validation_failed = false;
  7952. $validation_error_msg = '';
  7953. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7954. // 首次校验
  7955. if ($anime_script_id) {
  7956. if (empty($episode_arr['acts'])) {
  7957. $validation_failed = true;
  7958. $validation_error_msg = '未生成分镜剧本相关的内容';
  7959. } else {
  7960. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  7961. $generated_roles = array_filter($generated_roles, function($role) {
  7962. return $role !== '旁白';
  7963. });
  7964. if (empty($generated_roles)) {
  7965. $validation_failed = true;
  7966. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  7967. }
  7968. if (!$validation_failed && !empty($extra_roles)) {
  7969. $expected_roles = array_keys($extra_roles);
  7970. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7971. if (!empty($invalid_roles)) {
  7972. $validation_failed = true;
  7973. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7974. }
  7975. }
  7976. if (!$validation_failed && !empty($extra_scenes)) {
  7977. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  7978. $expected_scenes = array_keys($extra_scenes);
  7979. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7980. if (!empty($invalid_scenes)) {
  7981. $validation_failed = true;
  7982. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7983. }
  7984. }
  7985. if (!$validation_failed && !empty($extra_props)) {
  7986. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  7987. $expected_props = array_keys($extra_props);
  7988. $invalid_props = array_diff($generated_props, $expected_props);
  7989. if (!empty($invalid_props)) {
  7990. $validation_failed = true;
  7991. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  7992. }
  7993. }
  7994. }
  7995. } else {
  7996. if (empty($episode_arr['acts'])) {
  7997. $validation_failed = true;
  7998. $validation_error_msg = '未生成分镜剧本相关的内容';
  7999. } else {
  8000. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8001. $generated_roles = array_filter($generated_roles, function($role) {
  8002. return $role !== '旁白';
  8003. });
  8004. if (empty($generated_roles)) {
  8005. $validation_failed = true;
  8006. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8007. }
  8008. }
  8009. }
  8010. // 重试循环
  8011. while ($validation_failed && $retry_count < $max_retries) {
  8012. $retry_count++;
  8013. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  8014. 'reason' => $validation_error_msg,
  8015. 'anime_id' => $anime_id,
  8016. 'episode_number' => 1
  8017. ]);
  8018. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  8019. 'reason' => $validation_error_msg,
  8020. 'anime_id' => $anime_id
  8021. ]);
  8022. yield [
  8023. 'type' => 'retry',
  8024. 'retry_count' => $retry_count,
  8025. 'reason' => $validation_error_msg
  8026. ];
  8027. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  8028. if ($anime_script_id) {
  8029. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  8030. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  8031. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  8032. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  8033. } else {
  8034. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  8035. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  8036. }
  8037. $messages[] = [
  8038. 'role' => 'assistant',
  8039. 'content' => $fullContent
  8040. ];
  8041. $messages[] = [
  8042. 'role' => 'user',
  8043. 'content' => $retry_prompt
  8044. ];
  8045. $post_data['messages'] = $messages;
  8046. try {
  8047. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8048. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8049. } else if (in_array($model, $this->gpt_text_models)) {
  8050. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8051. } else if (in_array($model, $this->gemini_text_models)) {
  8052. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8053. } else {
  8054. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8055. }
  8056. $fullContent = '';
  8057. $fullReasoningContent = '';
  8058. foreach ($streamGenerator as $chunk) {
  8059. if (isset($chunk['type'])) {
  8060. if ($chunk['type'] === 'done') {
  8061. $fullContent = $chunk['full_content'];
  8062. $fullReasoningContent = $chunk['full_reasoning'];
  8063. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8064. } else {
  8065. yield $chunk;
  8066. }
  8067. }
  8068. }
  8069. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  8070. // 重试接口未返回有效内容时直接失败,避免空内容被兼容放行后保存
  8071. if ($fullContent === '') {
  8072. dLog('deepseek')->error("第{$retry_count}次重试接口未返回有效内容");
  8073. yield [
  8074. 'type' => 'done',
  8075. 'script' => [],
  8076. 'episode' => [],
  8077. 'answer' => '',
  8078. 'reasoning' => $fullReasoningContent,
  8079. 'usage' => $usage,
  8080. 'error' => '生成接口未返回有效内容,请稍后重试'
  8081. ];
  8082. return;
  8083. }
  8084. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  8085. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  8086. $script_arr = handleScriptContentForAce($fullContent);
  8087. if ($mappedArtStyle !== '') {
  8088. $script_arr['art_style'] = $mappedArtStyle;
  8089. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8090. }
  8091. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8092. $validation_failed = false;
  8093. $validation_error_msg = '';
  8094. if ($anime_script_id) {
  8095. if (empty($episode_arr['acts'])) {
  8096. $validation_failed = true;
  8097. $validation_error_msg = '未生成分镜剧本相关的内容';
  8098. } else {
  8099. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8100. $generated_roles = array_filter($generated_roles, function($role) {
  8101. return $role !== '旁白';
  8102. });
  8103. if (empty($generated_roles)) {
  8104. $validation_failed = true;
  8105. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8106. }
  8107. if (!$validation_failed && !empty($extra_roles)) {
  8108. $expected_roles = array_keys($extra_roles);
  8109. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8110. if (!empty($invalid_roles)) {
  8111. $validation_failed = true;
  8112. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8113. }
  8114. }
  8115. if (!$validation_failed && !empty($extra_scenes)) {
  8116. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  8117. $expected_scenes = array_keys($extra_scenes);
  8118. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8119. if (!empty($invalid_scenes)) {
  8120. $validation_failed = true;
  8121. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8122. }
  8123. }
  8124. if (!$validation_failed && !empty($extra_props)) {
  8125. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8126. $expected_props = array_keys($extra_props);
  8127. $invalid_props = array_diff($generated_props, $expected_props);
  8128. if (!empty($invalid_props)) {
  8129. $validation_failed = true;
  8130. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8131. }
  8132. }
  8133. }
  8134. } else {
  8135. if (empty($episode_arr['acts'])) {
  8136. $validation_failed = true;
  8137. $validation_error_msg = '未生成分镜剧本相关的内容';
  8138. } else {
  8139. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8140. $generated_roles = array_filter($generated_roles, function($role) {
  8141. return $role !== '旁白';
  8142. });
  8143. if (empty($generated_roles)) {
  8144. $validation_failed = true;
  8145. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8146. }
  8147. }
  8148. }
  8149. } catch (\Exception $e) {
  8150. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  8151. 'trace' => $e->getTraceAsString()
  8152. ]);
  8153. break;
  8154. }
  8155. }
  8156. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存
  8157. if ($validation_failed && $retry_count >= $max_retries) {
  8158. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  8159. 'retry_count' => $retry_count,
  8160. 'last_error' => $validation_error_msg
  8161. ]);
  8162. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  8163. 'error' => $validation_error_msg,
  8164. 'anime_id' => $anime_id
  8165. ]);
  8166. $validation_failed = false;
  8167. $validation_error_msg = '';
  8168. }
  8169. // 如果重试后仍然失败
  8170. if ($validation_failed) {
  8171. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  8172. 'retry_count' => $retry_count,
  8173. 'last_error' => $validation_error_msg
  8174. ]);
  8175. try {
  8176. $now = date('Y-m-d H:i:s');
  8177. $records = [
  8178. [
  8179. 'uid' => $uid,
  8180. 'anime_id' => $anime_id,
  8181. 'sequence' => 1,
  8182. 'role' => 'user',
  8183. 'content' => $prompt,
  8184. 'created_at' => $now,
  8185. 'updated_at' => $now
  8186. ],
  8187. [
  8188. 'uid' => $uid,
  8189. 'anime_id' => $anime_id,
  8190. 'sequence' => 1,
  8191. 'role' => 'assistant',
  8192. 'content' => $fullContent,
  8193. 'created_at' => $now,
  8194. 'updated_at' => $now
  8195. ]
  8196. ];
  8197. DB::table('mp_anime_records')->insert($records);
  8198. } catch (\Exception $e) {
  8199. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8200. }
  8201. yield [
  8202. 'type' => 'done',
  8203. 'script' => [],
  8204. 'episode' => [],
  8205. 'answer' => $fullContent,
  8206. 'reasoning' => $fullReasoningContent,
  8207. 'usage' => $usage,
  8208. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  8209. ];
  8210. return;
  8211. }
  8212. // 验证成功,记录日志
  8213. if ($retry_count > 0) {
  8214. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  8215. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  8216. }
  8217. }
  8218. $table_data = [
  8219. 'user_id' => $uid,
  8220. 'anime_name' => $anime_name,
  8221. 'model' => $model,
  8222. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  8223. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  8224. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  8225. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  8226. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  8227. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  8228. 'art_style_type' => $input_art_style,
  8229. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  8230. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  8231. 'status' => '解析完成',
  8232. 'content' => $content,
  8233. 'is_multi' => $is_multi,
  8234. 'ace_mode' => $ace_mode,
  8235. 'generate_status' => '待执行',
  8236. 'updated_at' => date('Y-m-d H:i:s')
  8237. ];
  8238. if ($table_data['content']) {
  8239. $chapters = splitContent($table_data['content']);
  8240. $chapter_count = count($chapters);
  8241. if ($chapter_count > 0) {
  8242. $table_data['start_episode_sequence'] = 1;
  8243. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  8244. }
  8245. }
  8246. if ($extra_products) {
  8247. $table_data['extra_products'] = json_encode($extra_products, 256);
  8248. }
  8249. // 如果有剧本ID则进行绑定
  8250. if ($script_id) {
  8251. $table_data['script_id'] = $script_id;
  8252. }
  8253. $single_episode = [];
  8254. try {
  8255. DB::beginTransaction();
  8256. $now = date('Y-m-d H:i:s');
  8257. // 更新动漫大纲
  8258. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  8259. if (!$boolen) {
  8260. dLog('deepseek')->info('动漫保存失败', $table_data);
  8261. Utils::throwError('20003:动漫保存失败');
  8262. }
  8263. // 保存对话记录
  8264. $records = [
  8265. [
  8266. 'uid' => $uid,
  8267. 'anime_id' => $anime_id,
  8268. 'sequence' => 0,
  8269. 'role' => 'user',
  8270. 'content' => $prompt,
  8271. 'created_at' => date('Y-m-d H:i:s'),
  8272. 'updated_at' => date('Y-m-d H:i:s')
  8273. ],
  8274. [
  8275. 'uid' => $uid,
  8276. 'anime_id' => $anime_id,
  8277. 'sequence' => 0,
  8278. 'role' => 'assistant',
  8279. 'content' => $fullContent,
  8280. 'created_at' => date('Y-m-d H:i:s'),
  8281. 'updated_at' => date('Y-m-d H:i:s')
  8282. ]
  8283. ];
  8284. // 保存对话记录
  8285. $boolen3 = DB::table('mp_anime_records')->insert($records);
  8286. if (!$boolen3) {
  8287. Utils::throwError('20003:对话记录保存失败');
  8288. }
  8289. if ($is_single) {
  8290. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8291. if (empty($episode_arr['acts'])) {
  8292. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  8293. }
  8294. $saveResult = $this->saveEpisodeVersionData(
  8295. $anime_id,
  8296. 1,
  8297. $episode_arr,
  8298. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8299. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8300. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  8301. null,
  8302. null,
  8303. false,
  8304. $content,
  8305. $now,
  8306. $ref_products
  8307. );
  8308. $single_episode = $saveResult['episode'];
  8309. $episode_id = $saveResult['episode_id'];
  8310. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  8311. 'roles' => json_encode($saveResult['merged_roles'], 256),
  8312. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  8313. 'props' => json_encode($saveResult['merged_props'], 256),
  8314. 'updated_at' => $now
  8315. ]);
  8316. if ($boolen5 === false) {
  8317. Utils::throwError('20003:单剧集主表资源同步失败');
  8318. }
  8319. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  8320. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  8321. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  8322. $episode_record_content = '确认分镜大纲';
  8323. if ($content !== '') {
  8324. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  8325. }
  8326. $episode_records = [
  8327. [
  8328. 'uid' => $uid,
  8329. 'anime_id' => $anime_id,
  8330. 'role' => 'user',
  8331. 'content' => $episode_record_content,
  8332. 'sequence' => 1,
  8333. 'episode_id' => $episode_id,
  8334. 'created_at' => $now,
  8335. 'updated_at' => $now
  8336. ],
  8337. [
  8338. 'uid' => $uid,
  8339. 'anime_id' => $anime_id,
  8340. 'role' => 'assistant',
  8341. 'content' => $fullContent,
  8342. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8343. 'sequence' => 1,
  8344. 'episode_id' => $episode_id,
  8345. 'created_at' => $now,
  8346. 'updated_at' => $now
  8347. ]
  8348. ];
  8349. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  8350. if (!$boolen4) {
  8351. Utils::throwError('20003:单剧集分镜记录保存失败');
  8352. }
  8353. }
  8354. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8355. if ($is_single && !empty($single_episode)) {
  8356. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8357. 'anime_id' => $anime_id,
  8358. 'episode_id' => $episode_id ?? 0,
  8359. 'model' => $model,
  8360. 'source' => 'addChatForAce',
  8361. ]);
  8362. }
  8363. }catch (\Exception $e) {
  8364. DB::rollBack();
  8365. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  8366. yield [
  8367. 'type' => 'done',
  8368. 'answer' => $fullContent,
  8369. 'reasoning' => $fullReasoningContent,
  8370. 'usage' => $usage,
  8371. 'error' => $e->getMessage(),
  8372. ];
  8373. return;
  8374. }
  8375. DB::commit();
  8376. dLog('deepseek')->info('保存完毕');
  8377. if ($is_single && !empty($single_episode)) {
  8378. // $this->batchSetGlobalRoleImg([
  8379. // 'anime_id' => $anime_id,
  8380. // ]);
  8381. // $this->batchSetGlobalSceneImg([
  8382. // 'anime_id' => $anime_id,
  8383. // ]);
  8384. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8385. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8386. }
  8387. $table_data['anime_id'] = $anime_id;
  8388. $table_data['roles'] = json_decode($table_data['roles'], true);
  8389. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8390. // $table_data['episodes'] = $script_arr['episodes'];
  8391. unset($table_data['created_at']);
  8392. unset($table_data['updated_at']);
  8393. unset($table_data['status']);
  8394. dLog('deepseek')->info('开始返回');
  8395. yield [
  8396. 'type' => 'done',
  8397. 'script' => $table_data,
  8398. 'episode' => $single_episode,
  8399. 'answer' => $fullContent,
  8400. 'reasoning' => $fullReasoningContent,
  8401. 'usage' => $usage
  8402. ];
  8403. }
  8404. public function reGenerateAnimeForAce($data) {
  8405. $uid = Site::getUid();
  8406. $file = getProp($data, 'file');
  8407. $content = getProp($data, 'content', '');
  8408. $bid = getProp($data, 'bid', 0);
  8409. $script_id = getProp($data, 'script_id', 0);
  8410. $anime_id = getProp($data, 'anime_id');
  8411. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8412. if (!$anime) {
  8413. Utils::throwError('20003:该对话不存在');
  8414. }
  8415. $is_multi = getProp($anime, 'is_multi', 1);
  8416. $is_single = (int)$is_multi !== 1;
  8417. // 积分余额预检(仅单剧集模式收费)
  8418. if ($is_single) {
  8419. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  8420. }
  8421. $extra_products = getProp($data, 'products', []);
  8422. if (!$extra_products) {
  8423. $extra_products = getProp($anime, 'extra_products');
  8424. if ($extra_products) {
  8425. $extra_products = json_decode($extra_products, true);
  8426. }else {
  8427. $extra_products = [];
  8428. }
  8429. }else {
  8430. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  8431. }
  8432. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  8433. $anime_script_id = getProp($anime, 'script_id');
  8434. if ($anime_script_id && $is_single) {
  8435. $cpid = Site::getCpid();
  8436. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  8437. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8438. ->where('mapping.script_id', $anime_script_id)
  8439. ->where('product.cpid', $cpid)
  8440. ->where('product.is_deleted', 0);
  8441. $mappings = $script_products_mappings->select(
  8442. 'mapping.product_id',
  8443. 'mapping.episode_number',
  8444. 'product.product_name',
  8445. 'product.type',
  8446. 'product.product',
  8447. 'product.pic_prompt',
  8448. 'product.url',
  8449. 'product.pic_task_id',
  8450. 'product.pic_task_status',
  8451. 'product.three_view_image_url'
  8452. )
  8453. ->get();
  8454. // 按 product_id 分组,合并 episode_number
  8455. $productMap = [];
  8456. foreach ($mappings as $item) {
  8457. $product_id = $item->product_id;
  8458. $product_name = $item->product_name;
  8459. // 处理product_name两边的符号
  8460. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8461. if (!isset($productMap[$product_id])) {
  8462. $productMap[$product_id] = [
  8463. 'product_id' => $product_id,
  8464. 'product_name' => $product_name,
  8465. 'type' => (int)$item->type,
  8466. 'product' => (int)$item->product,
  8467. 'pic_prompt' => $item->pic_prompt,
  8468. 'url' => $item->url,
  8469. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  8470. 'pic_task_id' => $item->pic_task_id,
  8471. 'pic_task_status' => $item->pic_task_status,
  8472. 'episode_numbers' => [],
  8473. ];
  8474. }
  8475. // 添加 episode_number(去重)
  8476. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8477. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8478. }
  8479. }
  8480. // 将查询到的剧本资产合并到extra_products中
  8481. // 先构建extra_products的索引(以product_id为key,用于去重)
  8482. $extraProductsMap = [];
  8483. foreach ($extra_products as $item) {
  8484. $key = getProp($item, 'product_id');
  8485. if ($key) {
  8486. $extraProductsMap[$key] = $item;
  8487. }
  8488. }
  8489. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  8490. foreach ($productMap as $product) {
  8491. $product_id = $product['product_id'];
  8492. // 如果不存在则添加(不带episode_number信息)
  8493. if (!isset($extraProductsMap[$product_id])) {
  8494. $extraProductsMap[$product_id] = [
  8495. 'product_id' => $product['product_id'],
  8496. 'product_name' => $product['product_name'],
  8497. 'type' => $product['type'],
  8498. 'product' => $product['product'],
  8499. 'pic_prompt' => $product['pic_prompt'],
  8500. 'url' => $product['url'],
  8501. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  8502. 'pic_task_id' => $product['pic_task_id'],
  8503. 'pic_task_status' => $product['pic_task_status'],
  8504. ];
  8505. }
  8506. }
  8507. // 重新赋值给extra_products
  8508. $extra_products = array_values($extraProductsMap);
  8509. }
  8510. $user_anime_name = getProp($anime, 'anime_name');
  8511. $prompt = getProp($data, 'prompt');
  8512. // 处理提示词
  8513. if ($prompt && $extra_products) {
  8514. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8515. foreach($extra_products as $item) {
  8516. $product_name = getProp($item, 'product_name');
  8517. if ($product_name) {
  8518. // 替换 {product_name} 为 product_name
  8519. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8520. }
  8521. }
  8522. }
  8523. // 处理文本模型
  8524. $model = getProp($data, 'model');
  8525. if (!$model) {
  8526. // 用户没有输入,从anime表获取
  8527. $model = getProp($anime, 'model');
  8528. if (!$model) {
  8529. // anime表也没有,使用默认值
  8530. $model = 'deepseek-v4-pro';
  8531. }
  8532. }
  8533. // 验证模型是否在可用模型表中
  8534. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8535. $model = 'deepseek-v4-pro';
  8536. }
  8537. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  8538. if ($is_single) {
  8539. $episode_exists = DB::table('mp_anime_episodes')
  8540. ->where('anime_id', $anime_id)
  8541. ->where('sequence', 1)
  8542. ->exists();
  8543. if ($episode_exists) {
  8544. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  8545. }
  8546. }
  8547. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  8548. if ($prompt) {
  8549. $question .= "本次修改要求如下:\n{$prompt}";
  8550. }
  8551. // 提取文件内容
  8552. if ($file) {
  8553. $content = $this->extractFileContent($file);
  8554. if (!$content) {
  8555. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8556. }
  8557. } elseif ($script_id) {
  8558. $content = $this->getContentByScriptId($script_id);
  8559. if (!$content) {
  8560. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  8561. }
  8562. } elseif ($bid) {
  8563. $content = $this->getContentByBid($bid);
  8564. if (!$content) {
  8565. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  8566. }
  8567. } elseif ($content) {
  8568. $content = filterContent($content);
  8569. }else {
  8570. $content = filterContent(getProp($anime, 'content'));
  8571. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  8572. $need_generate_content = true;
  8573. }
  8574. }
  8575. // 判断是否需要生成原文内容
  8576. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  8577. // 如果需要生成原文内容,添加额外的要求
  8578. $content_generation_requirement = $need_generate_content
  8579. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  8580. : "";
  8581. // 美术风格
  8582. $input_art_style = getProp($data, 'art_style');
  8583. if (!$input_art_style) {
  8584. $mappedArtStyle = getProp($anime, 'art_style');
  8585. }else {
  8586. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  8587. }
  8588. if (!$mappedArtStyle) {
  8589. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  8590. }else {
  8591. if (strstr($mappedArtStyle, '基础画风风格词')) {
  8592. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  8593. }else {
  8594. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  8595. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  8596. }
  8597. }
  8598. // 构建主体、场景和道具提示词
  8599. $extra_role_prompt = "\n";
  8600. $extra_scene_prompt = "\n";
  8601. $extra_prop_prompt = "\n";
  8602. $extra_roles = [];
  8603. $extra_scenes = [];
  8604. $extra_props = [];
  8605. $ref_products = []; // 参考资产
  8606. if ($extra_products) {
  8607. foreach($extra_products as $item) {
  8608. $product = getProp($item, 'product');
  8609. $product_name = getProp($item, 'product_name');
  8610. if ($product_name == '旁白') continue;
  8611. $ref_products[$product_name] = $item;
  8612. $pic_prompt = getProp($item, 'pic_prompt');
  8613. if ((int)$product === 1) {
  8614. // 拼接角色信息
  8615. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8616. $extra_roles[$product_name] = [
  8617. 'role' => $product_name,
  8618. 'pic_prompt' => $pic_prompt,
  8619. 'url' => getProp($item, 'url', ''),
  8620. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  8621. ];
  8622. } elseif ((int)$product === 2) {
  8623. // 拼接场景信息
  8624. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8625. $extra_scenes[$product_name] = [
  8626. 'scene' => $product_name,
  8627. 'pic_prompt' => $pic_prompt,
  8628. 'url' => getProp($item, 'url', ''),
  8629. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  8630. ];
  8631. } elseif ((int)$product === 3) {
  8632. // 拼接道具信息
  8633. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8634. $extra_props[$product_name] = [
  8635. 'prop' => $product_name,
  8636. 'pic_prompt' => $pic_prompt,
  8637. 'url' => getProp($item, 'url', ''),
  8638. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  8639. ];
  8640. }
  8641. }
  8642. // 优化提示词,融入剧本
  8643. if (!empty(trim($extra_role_prompt))) {
  8644. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  8645. }
  8646. if (!empty(trim($extra_scene_prompt))) {
  8647. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  8648. }
  8649. if (!empty(trim($extra_prop_prompt))) {
  8650. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  8651. }
  8652. }
  8653. if ($anime_script_id && $is_single) {
  8654. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  8655. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  8656. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  8657. }else {
  8658. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8659. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8660. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8661. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8662. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8663. {$extra_role_prompt}";
  8664. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8665. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  8666. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8667. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8668. {$extra_scene_prompt}";
  8669. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8670. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  8671. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8672. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  8673. {$extra_prop_prompt}";
  8674. }
  8675. $system_message = ['role'=>'system', 'content'=>$is_single
  8676. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  8677. 强制要求:
  8678. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8679. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8680. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8681. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8682. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8683. 普通要求:
  8684. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  8685. $role_demo
  8686. $scene_demo
  8687. $prop_demo
  8688. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8689. 5.1片段分割逻辑(优先级从高到低):
  8690. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8691. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8692. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8693. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8694. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8695. - 片段数量格式为: 片段数量:8
  8696. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8697. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8698. 5.3分镜结构:每个分镜包含以下字段:
  8699. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  8700. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8701. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8702. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8703. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8704. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8705. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8706. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8707. - 运镜:场景+画面描述+运镜
  8708. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8709. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8710. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8711. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  8712. 6.《情绪-视听语言映射表》:
  8713. 6.1 场景空间与时间心理学 (Scene & Temporality)
  8714. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8715. -----|---------|------------|----------------
  8716. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  8717. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  8718. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  8719. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  8720. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  8721. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8722. -----|---------|------------|----------------
  8723. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  8724. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  8725. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  8726. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  8727. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  8728. --------|---------|--------------|-------------
  8729. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  8730. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  8731. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  8732. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  8733. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  8734. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  8735. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  8736. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  8737. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  8738. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  8739. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  8740. -----|---------|------------|------------
  8741. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  8742. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  8743. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  8744. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  8745. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  8746. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  8747. --------|---------|--------------|----------
  8748. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  8749. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  8750. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  8751. 6.6 声音设计与潜意识影响 (Soundscape)
  8752. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  8753. -----|---------|------------|------------------
  8754. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  8755. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  8756. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  8757. 理论基石:
  8758. - The Five C's of Cinematography by Joseph V. Mascelli
  8759. - Film Art: An Introduction by David Bordwell
  8760. - Sight, Sound, Motion by Herbert Zettl
  8761. - Notes on the Cinematograph by Robert Bresson
  8762. \n\n
  8763. 7.{$mappedArtStyle_prompt}\n\n
  8764. 示例如下:\n
  8765. ###剧本名:西昆仑
  8766. ###故事梗概
  8767. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8768. ###剧本亮点
  8769. 亮点1:绝境奇药,生死一线
  8770. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8771. 亮点2:结拜兄妹,化解尴尬
  8772. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8773. 亮点3:纤发夺命,情愫暗涌
  8774. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8775. ###人物关系
  8776. 阿雪与梁萧之间存在兄妹之情。
  8777. ###核心矛盾
  8778. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8779. ###主体列表
  8780. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8781. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8782. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8783. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8784. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8785. 全景,正面拍摄,青年女性,亚洲人。
  8786. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8787. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8788. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8789. ###美术风格
  8790. 基础画风风格词:厚涂古风
  8791. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8792. ###场景列表
  8793. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8794. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8795. 无人物。}
  8796. ###分段剧本
  8797. 片段数量:8
  8798. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8799. ##片段1
  8800. 时长:12s
  8801. 分镜1
  8802. 出场角色:刀疤脸
  8803. 场景:边境小镇街道
  8804. 出场道具:酒杯-高脚杯
  8805. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8806. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8807. 配音台词:
  8808. 背景音效:
  8809. 分镜2
  8810. 出场角色:刀疤脸
  8811. 场景:悦来酒馆
  8812. 出场道具:酒杯-高脚杯
  8813. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8814. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8815. 配音台词:
  8816. 背景音效:
  8817. 分镜3
  8818. 出场角色:刀疤脸
  8819. 场景:悦来酒馆
  8820. 出场道具:酒杯-高脚杯
  8821. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8822. 运镜:从中景推向令牌特写。
  8823. 配音台词:
  8824. 背景音效:
  8825. 分镜4
  8826. 出场角色:刀疤脸
  8827. 场景:悦来酒馆
  8828. 出场道具:酒杯-高脚杯
  8829. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8830. 运镜:极速推向酒水溅起的瞬间。
  8831. 配音台词:
  8832. 背景音效:
  8833. 分镜5
  8834. 出场角色:刀疤脸
  8835. 场景:悦来酒馆
  8836. 出场道具:酒杯-高脚杯
  8837. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8838. 运镜:固定机位,利用倾斜构图制造压迫感。
  8839. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8840. 背景音效:
  8841. \n\n"
  8842. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8843. 强制要求:\n
  8844. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8845. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8846. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8847. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8848. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8849. 普通要求:\n
  8850. 1.剧本名(必须生成)必须与文档内容高度相关
  8851. $role_demo
  8852. $scene_demo
  8853. $prop_demo
  8854. 5.{$mappedArtStyle_prompt}\n\n
  8855. 示例如下:\n
  8856. ###剧本名:西昆仑
  8857. ###故事梗概
  8858. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8859. ###剧本亮点
  8860. 亮点1:绝境奇药,生死一线
  8861. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8862. 亮点2:结拜兄妹,化解尴尬
  8863. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8864. 亮点3:纤发夺命,情愫暗涌
  8865. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8866. ###人物关系
  8867. 阿雪与梁萧之间存在兄妹之情。
  8868. ###核心矛盾
  8869. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8870. ###主体列表
  8871. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8872. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8873. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8874. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8875. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8876. 全景,正面拍摄,青年女性,亚洲人。
  8877. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8878. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8879. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8880. ###美术风格
  8881. 基础画风风格词:厚涂古风
  8882. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8883. ###场景列表
  8884. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8885. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8886. 无人物。}
  8887. ###道具列表
  8888. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  8889. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  8890. $episode_count = $this->extractEpisodeNumber($prompt);
  8891. if ((int)getProp($anime, 'is_multi') !== 1) {
  8892. yield [
  8893. 'type' => 'done',
  8894. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  8895. 'reasoning' => '',
  8896. 'usage' => []
  8897. ];
  8898. return;
  8899. }
  8900. if ($episode_count) {
  8901. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  8902. $system_message = [
  8903. 'role' => 'system',
  8904. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8905. 强制要求:\n
  8906. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8907. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8908. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8909. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8910. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8911. 普通要求:\n
  8912. 1.<故事梗概>控制在200-300字左右
  8913. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8914. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8915. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8916. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8917. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8918. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8919. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8920. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8921. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8922. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  8923. 示例如下:\n
  8924. ###剧本名:西昆仑
  8925. ###故事梗概
  8926. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8927. ###剧本亮点
  8928. 亮点1:绝境奇药,生死一线
  8929. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8930. 亮点2:结拜兄妹,化解尴尬
  8931. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8932. 亮点3:纤发夺命,情愫暗涌
  8933. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8934. ###人物关系
  8935. 阿雪与梁萧之间存在兄妹之情。
  8936. ###核心矛盾
  8937. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8938. ###主体列表
  8939. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8940. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8941. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8942. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8943. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8944. 全景,正面拍摄,青年女性,亚洲人。
  8945. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8946. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8947. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8948. ###美术风格
  8949. 基础画风风格词:厚涂古风
  8950. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8951. ###场景列表
  8952. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8953. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8954. 无人物。}
  8955. ###分集详细内容
  8956. ##第1章 重生
  8957. 我重生了。
  8958. 源于一个男人偏执的暗恋。
  8959. ##第2章 相救
  8960. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  8961. 我眼睛扫向站在锅炉后的卞大伟。"
  8962. ];
  8963. // 构建消息
  8964. $messages = [
  8965. $system_message,
  8966. [
  8967. 'role' => 'user',
  8968. 'content' => "以下是文档内容:
  8969. {$content}
  8970. 用户问题:
  8971. {$question}"
  8972. ]
  8973. ];
  8974. }else {
  8975. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  8976. // 构建消息
  8977. $messages = [
  8978. $system_message,
  8979. [
  8980. 'role' => 'user',
  8981. 'content' => "以下是文档内容:
  8982. {$content}
  8983. 用户问题:
  8984. {$question}"
  8985. ]
  8986. ];
  8987. }else {
  8988. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  8989. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  8990. return (array)$value;
  8991. })->toArray();
  8992. array_unshift($messages, $system_message);
  8993. $messages[] = [
  8994. 'role' => 'user',
  8995. 'content' => $prompt
  8996. ];
  8997. }
  8998. }
  8999. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  9000. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  9001. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  9002. if ($model === 'deepseek-chat') {
  9003. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  9004. $model = 'deepseek-v4-flash';
  9005. $thinkingMode = 'disabled';
  9006. } elseif ($model === 'deepseek-reasoner') {
  9007. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  9008. $model = 'deepseek-v4-flash';
  9009. $thinkingMode = 'enabled';
  9010. }
  9011. $post_data = [
  9012. 'model' => $model,
  9013. 'messages' => $messages,
  9014. // 'max_tokens' => 8192,
  9015. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9016. 'frequency_penalty' => 0,
  9017. 'presence_penalty' => 0,
  9018. 'response_format' => ['type' => 'text'],
  9019. 'thinking' => ['type' => $thinkingMode],
  9020. 'stream' => true // 启用流式输出
  9021. ];
  9022. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9023. // 根据模型类型选择调用方法
  9024. $fullContent = '';
  9025. $fullReasoningContent = '';
  9026. $usage = [];
  9027. // dd($post_data);
  9028. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  9029. try {
  9030. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9031. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9032. } else if (in_array($model, $this->gpt_text_models)) {
  9033. // GPT-5.4 模型使用 TokenRouter API
  9034. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9035. } else if (in_array($model, $this->gemini_text_models)) {
  9036. // Gemini 模型使用 Gemini API
  9037. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9038. } else {
  9039. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9040. }
  9041. // 验证返回值类型
  9042. if (!is_iterable($streamGenerator)) {
  9043. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  9044. dLog('deepseek')->error('方法名流式生成器无效', [
  9045. 'generator_type' => $errorType,
  9046. 'model' => $model,
  9047. // 添加其他上下文信息
  9048. ]);
  9049. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  9050. 'type' => $errorType,
  9051. 'model' => $model
  9052. ]);
  9053. yield [
  9054. 'type' => 'error',
  9055. // 根据方法返回相应的空数据结构
  9056. 'answer' => '',
  9057. 'reasoning' => '',
  9058. 'usage' => [],
  9059. 'error' => '接口返回数据异常,请重新请求'
  9060. ];
  9061. return;
  9062. }
  9063. // 处理流式输出
  9064. foreach ($streamGenerator as $chunk) {
  9065. if (isset($chunk['type'])) {
  9066. if ($chunk['type'] === 'done') {
  9067. $fullContent = $chunk['full_content'];
  9068. $fullReasoningContent = $chunk['full_reasoning'];
  9069. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9070. } else {
  9071. yield $chunk;
  9072. }
  9073. }
  9074. }
  9075. } catch (\Exception $e) {
  9076. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  9077. 'model' => $model,
  9078. 'trace' => $e->getTraceAsString()
  9079. ]);
  9080. logDB('deepseek', 'error', '方法名流式处理失败', [
  9081. 'error' => $e->getMessage(),
  9082. 'model' => $model
  9083. ]);
  9084. yield [
  9085. 'type' => 'error',
  9086. // 根据方法返回相应的空数据结构
  9087. 'answer' => '',
  9088. 'reasoning' => '',
  9089. 'usage' => [],
  9090. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  9091. ];
  9092. return;
  9093. }
  9094. dLog('deepseek')->info('完整内容: '.$fullContent);
  9095. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  9096. // 处理完整内容并返回最终结果
  9097. $script_arr = [];
  9098. if ($fullContent) {
  9099. $script_arr = handleScriptContentForAce($fullContent);
  9100. dLog('deepseek')->info('解析内容', $script_arr);
  9101. logDB('deepseek', 'info', '解析内容', $script_arr);
  9102. }
  9103. if (empty($script_arr['roles'])) {
  9104. // 未生成剧本相关内容,保存对话记录并返回提示
  9105. dLog('deepseek')->info('未生成剧本相关的内容');
  9106. try {
  9107. $now = date('Y-m-d H:i:s');
  9108. // 保存对话记录
  9109. $records = [
  9110. [
  9111. 'uid' => $uid,
  9112. 'anime_id' => $anime_id,
  9113. 'sequence' => 0,
  9114. 'role' => 'user',
  9115. 'content' => $prompt,
  9116. 'created_at' => $now,
  9117. 'updated_at' => $now
  9118. ],
  9119. [
  9120. 'uid' => $uid,
  9121. 'anime_id' => $anime_id,
  9122. 'sequence' => 0,
  9123. 'role' => 'assistant',
  9124. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  9125. 'created_at' => $now,
  9126. 'updated_at' => $now
  9127. ]
  9128. ];
  9129. DB::table('mp_anime_records')->insert($records);
  9130. } catch (\Exception $e) {
  9131. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9132. }
  9133. yield [
  9134. 'type' => 'done',
  9135. 'script' => [],
  9136. 'episode' => [],
  9137. 'answer' => $fullContent,
  9138. 'reasoning' => $fullReasoningContent,
  9139. 'usage' => $usage,
  9140. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  9141. ];
  9142. return;
  9143. }
  9144. // 替换美术风格
  9145. if ($mappedArtStyle !== '') {
  9146. $script_arr['art_style'] = $mappedArtStyle;
  9147. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  9148. }
  9149. if ($user_anime_name != '新剧本策划') {
  9150. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  9151. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  9152. // 确认对话名称唯一性
  9153. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  9154. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  9155. }
  9156. }else {
  9157. $anime_name = $user_anime_name;
  9158. }
  9159. // 单剧集模式:按 chatForAce 逻辑校验并重试生成剧集与分段剧本
  9160. if ($is_single) {
  9161. $max_retries = 3;
  9162. $retry_count = 0;
  9163. $validation_failed = false;
  9164. $validation_error_msg = '';
  9165. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9166. // 首次校验
  9167. if ($anime_script_id) {
  9168. if (empty($episode_arr['acts'])) {
  9169. $validation_failed = true;
  9170. $validation_error_msg = '未生成分镜剧本相关的内容';
  9171. } else {
  9172. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9173. $generated_roles = array_filter($generated_roles, function($role) {
  9174. return $role !== '旁白';
  9175. });
  9176. if (empty($generated_roles)) {
  9177. $validation_failed = true;
  9178. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9179. }
  9180. if (!$validation_failed && !empty($extra_roles)) {
  9181. $expected_roles = array_keys($extra_roles);
  9182. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9183. if (!empty($invalid_roles)) {
  9184. $validation_failed = true;
  9185. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9186. }
  9187. }
  9188. if (!$validation_failed && !empty($extra_scenes)) {
  9189. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  9190. $expected_scenes = array_keys($extra_scenes);
  9191. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9192. if (!empty($invalid_scenes)) {
  9193. $validation_failed = true;
  9194. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9195. }
  9196. }
  9197. if (!$validation_failed && !empty($extra_props)) {
  9198. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9199. $expected_props = array_keys($extra_props);
  9200. $invalid_props = array_diff($generated_props, $expected_props);
  9201. if (!empty($invalid_props)) {
  9202. $validation_failed = true;
  9203. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9204. }
  9205. }
  9206. }
  9207. } else {
  9208. if (empty($episode_arr['acts'])) {
  9209. $validation_failed = true;
  9210. $validation_error_msg = '未生成分镜剧本相关的内容';
  9211. } else {
  9212. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9213. $generated_roles = array_filter($generated_roles, function($role) {
  9214. return $role !== '旁白';
  9215. });
  9216. if (empty($generated_roles)) {
  9217. $validation_failed = true;
  9218. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9219. }
  9220. }
  9221. }
  9222. // 重试循环
  9223. while ($validation_failed && $retry_count < $max_retries) {
  9224. $retry_count++;
  9225. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  9226. 'reason' => $validation_error_msg,
  9227. 'anime_id' => $anime_id,
  9228. 'episode_number' => 1
  9229. ]);
  9230. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  9231. 'reason' => $validation_error_msg,
  9232. 'anime_id' => $anime_id
  9233. ]);
  9234. yield [
  9235. 'type' => 'retry',
  9236. 'retry_count' => $retry_count,
  9237. 'reason' => $validation_error_msg
  9238. ];
  9239. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  9240. if ($anime_script_id) {
  9241. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  9242. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9243. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  9244. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  9245. } else {
  9246. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9247. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  9248. }
  9249. $messages[] = [
  9250. 'role' => 'assistant',
  9251. 'content' => $fullContent
  9252. ];
  9253. $messages[] = [
  9254. 'role' => 'user',
  9255. 'content' => $retry_prompt
  9256. ];
  9257. $post_data['messages'] = $messages;
  9258. try {
  9259. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9260. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9261. } else if (in_array($model, $this->gpt_text_models)) {
  9262. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9263. } else if (in_array($model, $this->gemini_text_models)) {
  9264. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9265. } else {
  9266. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9267. }
  9268. $fullContent = '';
  9269. $fullReasoningContent = '';
  9270. foreach ($streamGenerator as $chunk) {
  9271. if (isset($chunk['type'])) {
  9272. if ($chunk['type'] === 'done') {
  9273. $fullContent = $chunk['full_content'];
  9274. $fullReasoningContent = $chunk['full_reasoning'];
  9275. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9276. } else {
  9277. yield $chunk;
  9278. }
  9279. }
  9280. }
  9281. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9282. // 重试接口未返回有效内容时直接失败,避免空内容被兼容放行后保存
  9283. if ($fullContent === '') {
  9284. dLog('deepseek')->error("第{$retry_count}次重试接口未返回有效内容");
  9285. yield [
  9286. 'type' => 'done',
  9287. 'script' => [],
  9288. 'episode' => [],
  9289. 'answer' => '',
  9290. 'reasoning' => $fullReasoningContent,
  9291. 'usage' => $usage,
  9292. 'error' => '生成接口未返回有效内容,请稍后重试'
  9293. ];
  9294. return;
  9295. }
  9296. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  9297. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  9298. $script_arr = handleScriptContentForAce($fullContent);
  9299. if ($mappedArtStyle !== '') {
  9300. $script_arr['art_style'] = $mappedArtStyle;
  9301. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  9302. }
  9303. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9304. $validation_failed = false;
  9305. $validation_error_msg = '';
  9306. if ($anime_script_id) {
  9307. if (empty($episode_arr['acts'])) {
  9308. $validation_failed = true;
  9309. $validation_error_msg = '未生成分镜剧本相关的内容';
  9310. } else {
  9311. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9312. $generated_roles = array_filter($generated_roles, function($role) {
  9313. return $role !== '旁白';
  9314. });
  9315. if (empty($generated_roles)) {
  9316. $validation_failed = true;
  9317. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9318. }
  9319. if (!$validation_failed && !empty($extra_roles)) {
  9320. $expected_roles = array_keys($extra_roles);
  9321. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9322. if (!empty($invalid_roles)) {
  9323. $validation_failed = true;
  9324. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9325. }
  9326. }
  9327. if (!$validation_failed && !empty($extra_scenes)) {
  9328. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  9329. $expected_scenes = array_keys($extra_scenes);
  9330. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9331. if (!empty($invalid_scenes)) {
  9332. $validation_failed = true;
  9333. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9334. }
  9335. }
  9336. if (!$validation_failed && !empty($extra_props)) {
  9337. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9338. $expected_props = array_keys($extra_props);
  9339. $invalid_props = array_diff($generated_props, $expected_props);
  9340. if (!empty($invalid_props)) {
  9341. $validation_failed = true;
  9342. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9343. }
  9344. }
  9345. }
  9346. } else {
  9347. if (empty($episode_arr['acts'])) {
  9348. $validation_failed = true;
  9349. $validation_error_msg = '未生成分镜剧本相关的内容';
  9350. } else {
  9351. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9352. $generated_roles = array_filter($generated_roles, function($role) {
  9353. return $role !== '旁白';
  9354. });
  9355. if (empty($generated_roles)) {
  9356. $validation_failed = true;
  9357. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9358. }
  9359. }
  9360. }
  9361. } catch (\Exception $e) {
  9362. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  9363. 'trace' => $e->getTraceAsString()
  9364. ]);
  9365. break;
  9366. }
  9367. }
  9368. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存
  9369. if ($validation_failed && $retry_count >= $max_retries) {
  9370. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  9371. 'retry_count' => $retry_count,
  9372. 'last_error' => $validation_error_msg
  9373. ]);
  9374. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  9375. 'error' => $validation_error_msg,
  9376. 'anime_id' => $anime_id
  9377. ]);
  9378. $validation_failed = false;
  9379. $validation_error_msg = '';
  9380. }
  9381. // 如果重试后仍然失败
  9382. if ($validation_failed) {
  9383. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  9384. 'retry_count' => $retry_count,
  9385. 'last_error' => $validation_error_msg
  9386. ]);
  9387. try {
  9388. $now = date('Y-m-d H:i:s');
  9389. $records = [
  9390. [
  9391. 'uid' => $uid,
  9392. 'anime_id' => $anime_id,
  9393. 'sequence' => 1,
  9394. 'role' => 'user',
  9395. 'content' => $prompt,
  9396. 'created_at' => $now,
  9397. 'updated_at' => $now
  9398. ],
  9399. [
  9400. 'uid' => $uid,
  9401. 'anime_id' => $anime_id,
  9402. 'sequence' => 1,
  9403. 'role' => 'assistant',
  9404. 'content' => $fullContent,
  9405. 'created_at' => $now,
  9406. 'updated_at' => $now
  9407. ]
  9408. ];
  9409. DB::table('mp_anime_records')->insert($records);
  9410. } catch (\Exception $e) {
  9411. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9412. }
  9413. yield [
  9414. 'type' => 'done',
  9415. 'script' => [],
  9416. 'episode' => [],
  9417. 'answer' => $fullContent,
  9418. 'reasoning' => $fullReasoningContent,
  9419. 'usage' => $usage,
  9420. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  9421. ];
  9422. return;
  9423. }
  9424. // 验证成功,记录日志
  9425. if ($retry_count > 0) {
  9426. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  9427. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  9428. }
  9429. }
  9430. $table_data = [
  9431. 'user_id' => $uid,
  9432. 'model' => $model,
  9433. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  9434. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  9435. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  9436. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  9437. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  9438. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  9439. 'art_style_type' => $input_art_style,
  9440. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  9441. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  9442. 'status' => '解析完成',
  9443. 'generate_status' => '待执行',
  9444. 'updated_at' => date('Y-m-d H:i:s')
  9445. ];
  9446. if ($anime_name) $table_data['anime_name'] = $anime_name;
  9447. // 如果是修改集数,则将content内容更新(会改变原文)
  9448. if (isset($episode_count) && $episode_count > 0) {
  9449. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  9450. $table_data['start_episode_sequence'] = 1;
  9451. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  9452. }else {
  9453. // 如果需要生成原文内容,从script_arr中提取
  9454. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  9455. $table_data['content'] = $script_arr['content'];
  9456. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  9457. if (!$table_data['content']) {
  9458. yield [
  9459. 'type' => 'done',
  9460. 'script' => [],
  9461. 'episode' => [],
  9462. 'answer' => $fullContent,
  9463. 'reasoning' => $fullReasoningContent,
  9464. 'usage' => $usage,
  9465. 'error' => '未生成剧本内容,请调整提示词再试'
  9466. ];
  9467. return;
  9468. }
  9469. }
  9470. if (isset($table_data['content']) && $table_data['content']) {
  9471. $chapters = splitContent($table_data['content']);
  9472. $chapter_count = count($chapters);
  9473. if ($chapter_count > 0) {
  9474. $table_data['start_episode_sequence'] = 1;
  9475. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  9476. }
  9477. }
  9478. }
  9479. if ($extra_products) {
  9480. $table_data['extra_products'] = json_encode($extra_products, 256);
  9481. }
  9482. $single_episode = [];
  9483. try {
  9484. DB::beginTransaction();
  9485. $now = date('Y-m-d H:i:s');
  9486. // 更新动漫大纲
  9487. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  9488. if (!$boolen) {
  9489. dLog('deepseek')->info('对话修改失败', $table_data);
  9490. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  9491. Utils::throwError('20003:对话修改失败');
  9492. }
  9493. // 保存对话记录
  9494. $records = [
  9495. [
  9496. 'uid' => $uid,
  9497. 'anime_id' => $anime_id,
  9498. 'sequence' => 0,
  9499. 'role' => 'user',
  9500. 'content' => $prompt,
  9501. 'created_at' => $now,
  9502. 'updated_at' => $now
  9503. ],
  9504. [
  9505. 'uid' => $uid,
  9506. 'anime_id' => $anime_id,
  9507. 'sequence' => 0,
  9508. 'role' => 'assistant',
  9509. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  9510. 'content' => $fullContent,
  9511. 'created_at' => $now,
  9512. 'updated_at' => $now
  9513. ]
  9514. ];
  9515. // 保存对话记录
  9516. $boolen3 = DB::table('mp_anime_records')->insert($records);
  9517. if (!$boolen3) {
  9518. Utils::throwError('20003:对话记录保存失败');
  9519. }
  9520. // 单剧集模式:生成并保存剧集信息
  9521. if ($is_single) {
  9522. $anime_name = getProp($anime, 'anime_name', '未命名');
  9523. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9524. if (empty($episode_arr['acts'])) {
  9525. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  9526. }
  9527. $saveResult = $this->saveEpisodeVersionData(
  9528. $anime_id,
  9529. 1,
  9530. $episode_arr,
  9531. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  9532. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  9533. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  9534. null,
  9535. null,
  9536. false,
  9537. $content,
  9538. $now,
  9539. $ref_products
  9540. );
  9541. $single_episode = $saveResult['episode'];
  9542. $episode_id = $saveResult['episode_id'];
  9543. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  9544. 'roles' => json_encode($saveResult['merged_roles'], 256),
  9545. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  9546. 'props' => json_encode($saveResult['merged_props'], 256),
  9547. 'updated_at' => $now
  9548. ]);
  9549. if ($boolen5 === false) {
  9550. Utils::throwError('20003:单剧集主表资源同步失败');
  9551. }
  9552. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  9553. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  9554. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  9555. $episode_record_content = '确认分镜大纲';
  9556. if ($content !== '') {
  9557. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  9558. }
  9559. $episode_records = [
  9560. [
  9561. 'uid' => $uid,
  9562. 'anime_id' => $anime_id,
  9563. 'role' => 'user',
  9564. 'content' => $episode_record_content,
  9565. 'sequence' => 1,
  9566. 'episode_id' => $episode_id,
  9567. 'created_at' => $now,
  9568. 'updated_at' => $now
  9569. ],
  9570. [
  9571. 'uid' => $uid,
  9572. 'anime_id' => $anime_id,
  9573. 'role' => 'assistant',
  9574. 'content' => $fullContent,
  9575. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  9576. 'sequence' => 1,
  9577. 'episode_id' => $episode_id,
  9578. 'created_at' => $now,
  9579. 'updated_at' => $now
  9580. ]
  9581. ];
  9582. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  9583. if (!$boolen4) {
  9584. Utils::throwError('20003:单剧集分镜记录保存失败');
  9585. }
  9586. }
  9587. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  9588. if ($is_single && !empty($single_episode)) {
  9589. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  9590. 'anime_id' => $anime_id,
  9591. 'episode_id' => $episode_id ?? 0,
  9592. 'model' => $model,
  9593. 'source' => 'reGenerateAnimeForAce',
  9594. ]);
  9595. }
  9596. }catch (\Exception $e) {
  9597. DB::rollBack();
  9598. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  9599. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  9600. yield [
  9601. 'type' => 'done',
  9602. 'answer' => $fullContent,
  9603. 'reasoning' => $fullReasoningContent,
  9604. 'usage' => $usage,
  9605. 'error' => $e->getMessage(),
  9606. ];
  9607. return;
  9608. }
  9609. DB::commit();
  9610. dLog('deepseek')->info('保存完毕');
  9611. if ($is_single && !empty($single_episode)) {
  9612. // $this->batchSetGlobalRoleImg([
  9613. // 'anime_id' => $anime_id,
  9614. // ]);
  9615. // $this->batchSetGlobalSceneImg([
  9616. // 'anime_id' => $anime_id,
  9617. // ]);
  9618. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  9619. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  9620. }
  9621. $table_data['anime_id'] = $anime_id;
  9622. $table_data['roles'] = json_decode($table_data['roles'], true);
  9623. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  9624. $table_data['props'] = json_decode($table_data['props'], true);
  9625. unset($table_data['updated_at']);
  9626. unset($table_data['status']);
  9627. yield [
  9628. 'type' => 'done',
  9629. 'script' => $table_data,
  9630. 'episode' => $single_episode,
  9631. 'answer' => $fullContent,
  9632. 'reasoning' => $fullReasoningContent,
  9633. 'usage' => $usage
  9634. ];
  9635. }
  9636. public function chatForAce($data) {
  9637. $uid = Site::getUid();
  9638. // 积分余额预检(不足直接报错)
  9639. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  9640. $anime_id = getProp($data, 'anime_id');
  9641. $file = getProp($data, 'file');
  9642. $content = getProp($data, 'content', '');
  9643. $bid = getProp($data, 'bid', 0);
  9644. $script_id = getProp($data, 'script_id', 0);
  9645. $episode_number = getProp($data, 'episode_number', 1);
  9646. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  9647. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9648. if (!$anime) Utils::throwError('20003:该对话不存在!');
  9649. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  9650. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  9651. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  9652. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  9653. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  9654. $roles = is_array($roles) ? $roles : [];
  9655. $scenes = is_array($scenes) ? $scenes : [];
  9656. $extra_products = getProp($data, 'products', []);
  9657. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  9658. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  9659. $anime_script_id = getProp($anime, 'script_id');
  9660. if ($anime_script_id) {
  9661. $cpid = Site::getCpid();
  9662. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  9663. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9664. ->where('mapping.script_id', $anime_script_id)
  9665. ->where('product.cpid', $cpid)
  9666. ->where('product.is_deleted', 0);
  9667. // 如果提供了 episode_number,则过滤指定集数
  9668. if ($episode_number !== null && $episode_number !== '') {
  9669. $script_products_mappings->where('mapping.episode_number', $episode_number);
  9670. }
  9671. $mappings = $script_products_mappings->select(
  9672. 'mapping.product_id',
  9673. 'mapping.episode_number',
  9674. 'product.product_name',
  9675. 'product.type',
  9676. 'product.product',
  9677. 'product.pic_prompt',
  9678. 'product.url',
  9679. 'product.pic_task_id',
  9680. 'product.pic_task_status',
  9681. 'product.three_view_image_url'
  9682. )
  9683. ->get();
  9684. // 按 product_id 分组,合并 episode_number
  9685. $productMap = [];
  9686. foreach ($mappings as $item) {
  9687. $product_id = $item->product_id;
  9688. $product_name = $item->product_name;
  9689. // 处理product_name两边的符号
  9690. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  9691. if (!isset($productMap[$product_id])) {
  9692. $productMap[$product_id] = [
  9693. 'product_id' => $product_id,
  9694. 'product_name' => $product_name,
  9695. 'type' => (int)$item->type,
  9696. 'product' => (int)$item->product,
  9697. 'pic_prompt' => $item->pic_prompt,
  9698. 'url' => $item->url,
  9699. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9700. 'pic_task_id' => $item->pic_task_id,
  9701. 'pic_task_status' => $item->pic_task_status,
  9702. 'episode_numbers' => [],
  9703. ];
  9704. }
  9705. // 添加 episode_number(去重)
  9706. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  9707. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  9708. }
  9709. }
  9710. // 将查询到的剧本资产合并到extra_products中
  9711. // 先构建extra_products的索引(以product_id+episode_number为key)
  9712. $extraProductsMap = [];
  9713. foreach ($extra_products as $item) {
  9714. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  9715. $extraProductsMap[$key] = $item;
  9716. }
  9717. // 合并剧本资产(去重:product_id+episode_number)
  9718. foreach ($productMap as $product) {
  9719. foreach ($product['episode_numbers'] as $ep_num) {
  9720. $key = $product['product_id'] . '_' . $ep_num;
  9721. // 如果不存在则添加
  9722. if (!isset($extraProductsMap[$key])) {
  9723. $extraProductsMap[$key] = [
  9724. 'product_id' => $product['product_id'],
  9725. 'product_name' => $product['product_name'],
  9726. 'type' => $product['type'],
  9727. 'product' => $product['product'],
  9728. 'pic_prompt' => $product['pic_prompt'],
  9729. 'url' => $product['url'],
  9730. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  9731. 'pic_task_id' => $product['pic_task_id'],
  9732. 'pic_task_status' => $product['pic_task_status'],
  9733. 'episode_number' => $ep_num,
  9734. ];
  9735. }
  9736. }
  9737. }
  9738. // 重新赋值给extra_products
  9739. $extra_products = array_values($extraProductsMap);
  9740. }
  9741. // 处理提示词
  9742. if ($prompt && $extra_products) {
  9743. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  9744. foreach($extra_products as $item) {
  9745. $product_name = getProp($item, 'product_name');
  9746. if ($product_name) {
  9747. // 替换 {product_name} 为 product_name
  9748. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  9749. }
  9750. }
  9751. }
  9752. // 获取最后一集序号
  9753. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  9754. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  9755. // 转换主体列表和场景列表的格式
  9756. // 获取参考主体或场景
  9757. if ((int)$episode_number === 1) {
  9758. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  9759. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  9760. }else {
  9761. $prev_episode_number = $episode_number - 1;
  9762. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  9763. }
  9764. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  9765. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  9766. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  9767. // 合并anime_products和extra_products(extra_products优先,去重)
  9768. $anime_products = getProp($anime, 'extra_products');
  9769. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  9770. $ref_products = [];
  9771. foreach($anime_products as $item) {
  9772. $product_name = getProp($item, 'product_name');
  9773. $ref_products[$product_name] = $item;
  9774. }
  9775. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  9776. $extra_roles = []; // 从extra_products中提取的角色
  9777. $extra_scenes = []; // 从extra_products中提取的场景
  9778. $extra_props = []; // 从extra_products中提取的道具
  9779. if ($extra_products && is_array($extra_products)) {
  9780. foreach($extra_products as $item) {
  9781. $product = (int)getProp($item, 'product');
  9782. $product_name = getProp($item, 'product_name');
  9783. if ($product_name == '旁白') continue;
  9784. $pic_prompt = getProp($item, 'pic_prompt');
  9785. $ref_products[$product_name] = $item;
  9786. if ($product === 1) {
  9787. // 角色
  9788. $extra_roles[$product_name] = [
  9789. 'role' => $product_name,
  9790. 'pic_prompt' => $pic_prompt,
  9791. 'url' => getProp($item, 'url', ''),
  9792. ];
  9793. } elseif ($product === 2) {
  9794. // 场景
  9795. $extra_scenes[$product_name] = [
  9796. 'scene' => $product_name,
  9797. 'pic_prompt' => $pic_prompt,
  9798. 'url' => getProp($item, 'url', ''),
  9799. ];
  9800. } elseif ($product === 3) {
  9801. // 道具
  9802. $extra_props[$product_name] = [
  9803. 'prop' => $product_name,
  9804. 'pic_prompt' => $pic_prompt,
  9805. 'url' => getProp($item, 'url', ''),
  9806. ];
  9807. }
  9808. }
  9809. }
  9810. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  9811. $merged_roles = [];
  9812. foreach($ref_roles as $role) {
  9813. $role_name = getProp($role, 'role');
  9814. if (!isset($extra_roles[$role_name])) {
  9815. $merged_roles[$role_name] = $role;
  9816. }
  9817. }
  9818. // 添加extra_roles
  9819. foreach($extra_roles as $role_name => $role) {
  9820. $merged_roles[$role_name] = $role;
  9821. }
  9822. $ref_roles = array_values($merged_roles);
  9823. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  9824. $merged_scenes = [];
  9825. foreach($ref_scenes as $scene) {
  9826. $scene_name = getProp($scene, 'scene');
  9827. if (!isset($extra_scenes[$scene_name])) {
  9828. $merged_scenes[$scene_name] = $scene;
  9829. }
  9830. }
  9831. // 添加extra_scenes
  9832. foreach($extra_scenes as $scene_name => $scene) {
  9833. $merged_scenes[$scene_name] = $scene;
  9834. }
  9835. $ref_scenes = array_values($merged_scenes);
  9836. // 合并ref_props和extra_props(extra_props优先,去重)
  9837. $merged_props = [];
  9838. foreach($ref_props as $prop) {
  9839. $prop_name = getProp($prop, 'prop');
  9840. if (!isset($extra_props[$prop_name])) {
  9841. $merged_props[$prop_name] = $prop;
  9842. }
  9843. }
  9844. // 添加extra_props
  9845. foreach($extra_props as $prop_name => $prop) {
  9846. $merged_props[$prop_name] = $prop;
  9847. }
  9848. $ref_props = array_values($merged_props);
  9849. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  9850. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  9851. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  9852. // 构建强制主体、场景和道具提示词
  9853. $forced_roles_prompt = "";
  9854. $forced_scenes_prompt = "";
  9855. $forced_props_prompt = "";
  9856. if (!empty($extra_roles)) {
  9857. $forced_roles_list = "";
  9858. foreach($extra_roles as $role_name => $role) {
  9859. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  9860. }
  9861. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  9862. }
  9863. if (!empty($extra_scenes)) {
  9864. $forced_scenes_list = "";
  9865. foreach($extra_scenes as $scene_name => $scene) {
  9866. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  9867. }
  9868. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  9869. }
  9870. if (!empty($extra_props)) {
  9871. $forced_props_list = "";
  9872. foreach($extra_props as $prop_name => $prop) {
  9873. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  9874. }
  9875. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  9876. }
  9877. if ($anime_script_id) {
  9878. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  9879. }else if ($roles_content) {
  9880. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  9881. 主体范围:\n {$roles_content}\n
  9882. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  9883. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9884. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  9885. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9886. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  9887. }else {
  9888. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  9889. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9890. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  9891. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9892. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  9893. }
  9894. if ($anime_script_id) {
  9895. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  9896. }else if ($scenes_content) {
  9897. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  9898. 场景范围:\n {$scenes_content}\n
  9899. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  9900. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  9901. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9902. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  9903. }else {
  9904. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9905. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  9906. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9907. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  9908. }
  9909. if ($anime_script_id) {
  9910. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  9911. }else if ($props_content) {
  9912. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  9913. 道具范围:\n {$props_content}\n
  9914. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  9915. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  9916. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  9917. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  9918. }else {
  9919. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9920. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  9921. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  9922. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  9923. }
  9924. // 提取文件内容
  9925. if ($file) {
  9926. $uploaded_content = $this->extractFileContent($file);
  9927. if (!$uploaded_content) {
  9928. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  9929. }
  9930. } elseif ($script_id) {
  9931. $uploaded_content = $this->getContentByScriptId($script_id);
  9932. if (!$uploaded_content) {
  9933. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  9934. }
  9935. } elseif ($bid) {
  9936. $uploaded_content = $this->getContentByBid($bid);
  9937. if (!$uploaded_content) {
  9938. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  9939. }
  9940. } elseif ($content) {
  9941. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  9942. }
  9943. // elseif ($prompt) {
  9944. // $uploaded_content = filterContent($prompt);
  9945. // }
  9946. else {
  9947. $uploaded_content = '';
  9948. }
  9949. // 美术风格
  9950. $input_art_style = getProp($data, 'art_style');
  9951. if (!$input_art_style) {
  9952. $mappedArtStyle = getProp($anime, 'art_style');
  9953. }else {
  9954. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  9955. }
  9956. if (!$mappedArtStyle) {
  9957. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  9958. }else {
  9959. if (strstr($mappedArtStyle, '基础画风风格词')) {
  9960. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  9961. }else {
  9962. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  9963. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  9964. }
  9965. }
  9966. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  9967. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  9968. // 强制要求:
  9969. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9970. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9971. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9972. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  9973. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  9974. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  9975. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  9976. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  9977. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  9978. // 10.分镜要和场景列表、人物主体保持一致\n
  9979. // 普通要求:
  9980. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  9981. // {$role_demo}
  9982. // {$scene_demo}
  9983. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9984. // 4.1片段分割逻辑(优先级从高到低):
  9985. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9986. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9987. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9988. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9989. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9990. // - 片段数量格式为: 片段数量:8
  9991. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9992. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9993. // 4.3分镜结构:每个分镜包含以下字段:
  9994. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  9995. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  9996. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9997. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  9998. // - 运镜:场景+画面描述+运镜
  9999. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  10000. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10001. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10002. // 5.$mappedArtStyle_prompt\n\n
  10003. // 示例格式:\n
  10004. // 第1集:隐形的守护者
  10005. // ###故事梗概
  10006. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10007. // ###美术风格
  10008. // 基础画风风格词:胡金铨武侠
  10009. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10010. // ###主体列表
  10011. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10012. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10013. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10014. // ###场景列表
  10015. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10016. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10017. // ###分段剧本
  10018. // 片段数量:8
  10019. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10020. // ##片段1
  10021. // 时长:12s
  10022. // 分镜1
  10023. // 场景:边境小镇街道
  10024. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10025. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10026. // 配音台词:
  10027. // 背景音效:
  10028. // 分镜2
  10029. // 场景:悦来酒馆
  10030. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10031. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10032. // 配音台词:
  10033. // 背景音效:
  10034. // 分镜3
  10035. // 场景:悦来酒馆
  10036. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10037. // 运镜:从中景推向令牌特写。
  10038. // 配音台词:
  10039. // 背景音效:
  10040. // 分镜4
  10041. // 场景:悦来酒馆
  10042. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10043. // 运镜:极速推向酒水溅起的瞬间。
  10044. // 配音台词:
  10045. // 背景音效:
  10046. // 分镜5
  10047. // 镜头描述
  10048. // 场景:悦来酒馆
  10049. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10050. // 运镜:固定机位,利用倾斜构图制造压迫感。
  10051. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10052. // 背景音效:
  10053. // \n\n";
  10054. /*
  10055. // ====== 旧版 $demo(缓存优化前版本,动态数据内嵌在规则中间) ======
  10056. // 如需换回:删除下方新版 $demo,并把本块恢复为活动代码(去掉首尾注释标记)
  10057. // ===================================================================
  10058. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  10059. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  10060. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  10061. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  10062. 强制要求:
  10063. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  10064. 普通要求:
  10065. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  10066. {$role_demo}
  10067. {$scene_demo}
  10068. {$prop_demo}
  10069. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10070. 5.1片段分割逻辑(优先级从高到低):
  10071. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10072. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10073. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10074. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10075. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10076. - 片段数量格式为: 片段数量:8
  10077. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10078. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10079. 5.3分镜结构:每个分镜包含以下字段:
  10080. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  10081. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10082. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10083. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10084. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10085. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10086. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10087. - 运镜:场景+画面描述+运镜
  10088. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  10089. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  10090. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10091. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10092. 6.《情绪-视听语言映射表》:
  10093. 6.1 场景空间与时间心理学 (Scene & Temporality)
  10094. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10095. -----|---------|------------|----------------
  10096. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  10097. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  10098. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  10099. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  10100. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  10101. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10102. -----|---------|------------|----------------
  10103. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  10104. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  10105. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  10106. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  10107. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  10108. --------|---------|--------------|-------------
  10109. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  10110. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  10111. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  10112. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  10113. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  10114. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  10115. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  10116. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  10117. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  10118. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  10119. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  10120. -----|---------|------------|------------
  10121. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  10122. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  10123. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  10124. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  10125. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  10126. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  10127. --------|---------|--------------|----------
  10128. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  10129. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  10130. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  10131. 6.6 声音设计与潜意识影响 (Soundscape)
  10132. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  10133. -----|---------|------------|------------------
  10134. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  10135. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  10136. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  10137. 理论基石:
  10138. - The Five C's of Cinematography by Joseph V. Mascelli
  10139. - Film Art: An Introduction by David Bordwell
  10140. - Sight, Sound, Motion by Herbert Zettl
  10141. - Notes on the Cinematograph by Robert Bresson
  10142. \n\n
  10143. 7.{$mappedArtStyle_prompt}
  10144. 示例格式:\n
  10145. 第1集:隐形的守护者
  10146. ###故事梗概
  10147. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10148. ###美术风格
  10149. 基础画风风格词:胡金铨武侠
  10150. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10151. ###主体列表
  10152. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10153. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10154. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10155. ###场景列表
  10156. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10157. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10158. ###道具列表
  10159. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  10160. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  10161. ###分段剧本
  10162. 片段数量:8
  10163. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10164. ##片段1
  10165. 时长:12s
  10166. 分镜1
  10167. 出场角色:刀疤脸
  10168. 场景:边境小镇街道
  10169. 出场道具:酒杯-高脚杯
  10170. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10171. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10172. 配音台词:
  10173. 背景音效:
  10174. 分镜2
  10175. 出场角色:刀疤脸
  10176. 场景:悦来酒馆
  10177. 出场道具:酒杯-高脚杯
  10178. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10179. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10180. 配音台词:
  10181. 背景音效:
  10182. 分镜3
  10183. 出场角色:刀疤脸
  10184. 场景:悦来酒馆
  10185. 出场道具:酒杯-高脚杯
  10186. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10187. 运镜:从中景推向令牌特写。
  10188. 配音台词:
  10189. 背景音效:
  10190. 分镜4
  10191. 出场角色:刀疤脸
  10192. 场景:悦来酒馆
  10193. 出场道具:酒杯-高脚杯
  10194. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10195. 运镜:极速推向酒水溅起的瞬间。
  10196. 配音台词:
  10197. 背景音效:
  10198. 分镜5
  10199. 出场角色:刀疤脸
  10200. 场景:悦来酒馆
  10201. 出场道具:酒杯-高脚杯
  10202. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10203. 运镜:固定机位,利用倾斜构图制造压迫感。
  10204. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10205. 背景音效:
  10206. \n\n";
  10207. */
  10208. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  10209. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  10210. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  10211. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  10212. 强制要求:
  10213. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  10214. 普通要求:
  10215. 1.剧集标题必须与文档内容高度相关,剧集序号见文末【本次剧集信息】。
  10216. 2.<主体列表>的详细规则和可选范围见文末【本次生成数据-主体列表】。
  10217. 3.<场景列表>的详细规则和可选范围见文末【本次生成数据-场景列表】。
  10218. 4.<道具列表>的详细规则和可选范围见文末【本次生成数据-道具列表】。
  10219. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10220. 5.1片段分割逻辑(优先级从高到低):
  10221. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10222. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10223. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10224. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10225. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10226. - 片段数量格式为: 片段数量:8
  10227. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10228. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10229. 5.3分镜结构:每个分镜包含以下字段:
  10230. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  10231. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  10232. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10233. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10234. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10235. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10236. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10237. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10238. - 运镜:场景+画面描述+运镜
  10239. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  10240. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  10241. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10242. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10243. 6.《情绪-视听语言映射表》:
  10244. 6.1 场景空间与时间心理学 (Scene & Temporality)
  10245. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10246. -----|---------|------------|----------------
  10247. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  10248. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  10249. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  10250. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  10251. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  10252. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10253. -----|---------|------------|----------------
  10254. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  10255. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  10256. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  10257. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  10258. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  10259. --------|---------|--------------|-------------
  10260. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  10261. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  10262. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  10263. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  10264. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  10265. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  10266. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  10267. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  10268. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  10269. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  10270. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  10271. -----|---------|------------|------------
  10272. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  10273. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  10274. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  10275. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  10276. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  10277. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  10278. --------|---------|--------------|----------
  10279. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  10280. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  10281. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  10282. 6.6 声音设计与潜意识影响 (Soundscape)
  10283. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  10284. -----|---------|------------|------------------
  10285. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  10286. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  10287. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  10288. 理论基石:
  10289. - The Five C's of Cinematography by Joseph V. Mascelli
  10290. - Film Art: An Introduction by David Bordwell
  10291. - Sight, Sound, Motion by Herbert Zettl
  10292. - Notes on the Cinematograph by Robert Bresson
  10293. \n\n
  10294. 7.美术风格要求见文末【本次生成数据-美术风格】。
  10295. 示例格式:\n
  10296. 第1集:隐形的守护者
  10297. ###故事梗概
  10298. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10299. ###美术风格
  10300. 基础画风风格词:胡金铨武侠
  10301. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10302. ###主体列表
  10303. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10304. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10305. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10306. ###场景列表
  10307. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10308. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10309. ###道具列表
  10310. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  10311. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  10312. ###分段剧本
  10313. 片段数量:8
  10314. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10315. ##片段1
  10316. 时长:12s
  10317. 分镜1
  10318. 出场角色:刀疤脸
  10319. 场景:边境小镇街道
  10320. 出场道具:酒杯-高脚杯
  10321. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10322. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10323. 配音台词:
  10324. 背景音效:
  10325. 分镜2
  10326. 出场角色:刀疤脸
  10327. 场景:悦来酒馆
  10328. 出场道具:酒杯-高脚杯
  10329. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10330. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10331. 配音台词:
  10332. 背景音效:
  10333. 分镜3
  10334. 出场角色:刀疤脸
  10335. 场景:悦来酒馆
  10336. 出场道具:酒杯-高脚杯
  10337. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10338. 运镜:从中景推向令牌特写。
  10339. 配音台词:
  10340. 背景音效:
  10341. 分镜4
  10342. 出场角色:刀疤脸
  10343. 场景:悦来酒馆
  10344. 出场道具:酒杯-高脚杯
  10345. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10346. 运镜:极速推向酒水溅起的瞬间。
  10347. 配音台词:
  10348. 背景音效:
  10349. 分镜5
  10350. 出场角色:刀疤脸
  10351. 场景:悦来酒馆
  10352. 出场道具:酒杯-高脚杯
  10353. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10354. 运镜:固定机位,利用倾斜构图制造压迫感。
  10355. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10356. 背景音效:
  10357. \n\n本次生成数据(以上规则的动态数据均在此处,优先级等同对应编号规则):
  10358. 【本次剧集信息】剧集序号是{$episode_number}。
  10359. 【本次生成数据-主体列表】{$role_demo}
  10360. 【本次生成数据-场景列表】{$scene_demo}
  10361. 【本次生成数据-道具列表】{$prop_demo}
  10362. 【本次生成数据-美术风格】{$mappedArtStyle_prompt}
  10363. \n\n";
  10364. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10365. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  10366. // $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  10367. $is_regenerate_version = true;
  10368. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  10369. $prompt = $origin_prompt;
  10370. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  10371. // 获取章节内容
  10372. $full_content = getProp($anime, 'content');
  10373. if ($uploaded_content) {
  10374. $full_content = $uploaded_content;
  10375. }
  10376. // 根据章节内容拆分章节
  10377. $chapters = splitContent($full_content);
  10378. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  10379. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  10380. $messages = [];
  10381. if ($prompt == '确认分镜大纲') {
  10382. // 暂时保留
  10383. $content = $chapter_content;
  10384. if ($is_single) $content = $full_content; // 单剧集使用全文
  10385. if (!$content) {
  10386. Utils::throwError('20003:章节内容无法获取,请确认');
  10387. }
  10388. $question = $is_single
  10389. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  10390. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  10391. // 构建消息
  10392. $messages[] =
  10393. [
  10394. 'role' => 'user',
  10395. 'content' => $question
  10396. ];
  10397. }else if ($prompt == '继续策划下一集') {
  10398. if ($is_single) {
  10399. Utils::throwError('20003:单剧集不支持继续策划下一集');
  10400. }
  10401. $content = $chapter_content;
  10402. if (!$content) {
  10403. Utils::throwError('20003:章节内容无法获取,请确认');
  10404. }
  10405. // 获取上一集最后记录
  10406. $prev_sequence = $episode_number - 1;
  10407. $messages = array_merge(
  10408. [
  10409. [
  10410. 'role' => 'system',
  10411. 'content' => $demo
  10412. ]
  10413. ],
  10414. $this->getEpisodeChatContent($anime_id, $prev_sequence, $content)
  10415. );
  10416. // 构建消息
  10417. $messages[] =
  10418. [
  10419. 'role' => 'user',
  10420. 'content' => "请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)"
  10421. ];
  10422. /*
  10423. // 旧版逻辑
  10424. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  10425. // 构建消息
  10426. $messages[] =
  10427. [
  10428. 'role' => 'user',
  10429. 'content' => $question
  10430. ];
  10431. */
  10432. // dd($messages);
  10433. }else {
  10434. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  10435. if (!$content) {
  10436. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  10437. }
  10438. if (!$content) {
  10439. Utils::throwError('20003:章节内容无法获取,请确认');
  10440. }
  10441. $messages = array_merge(
  10442. [
  10443. [
  10444. 'role' => 'system',
  10445. 'content' => $demo
  10446. ]
  10447. ],
  10448. $this->getEpisodeChatMessages($anime_id, $episode_number)
  10449. );
  10450. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  10451. $question = "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  10452. if ($origin_prompt) {
  10453. $question .= "本次修改要求如下:\n{$origin_prompt}";
  10454. }
  10455. // 将本集原文加入消息,供模型逐字摘录原文台词(修复重新生成时配音台词全部为"无"的问题)
  10456. $messages[] = [
  10457. 'role' => 'user',
  10458. 'content' => "本集剧情内容:\n\n{$content}\n"
  10459. ];
  10460. $messages[] =
  10461. [
  10462. 'role' => 'user',
  10463. 'content' => $question
  10464. ];
  10465. }
  10466. // 处理文本模型
  10467. $model = getProp($data, 'model');
  10468. if (!$model) {
  10469. // 用户没有输入,从anime表获取
  10470. $model = getProp($anime, 'model');
  10471. if (!$model) {
  10472. // anime表也没有,使用默认值
  10473. $model = 'deepseek-v4-pro';
  10474. }
  10475. }
  10476. // 验证模型是否在可用模型表中
  10477. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10478. $model = 'deepseek-v4-pro';
  10479. }
  10480. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  10481. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  10482. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  10483. if ($model === 'deepseek-chat') {
  10484. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  10485. $model = 'deepseek-v4-flash';
  10486. $thinkingMode = 'disabled';
  10487. } elseif ($model === 'deepseek-reasoner') {
  10488. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  10489. $model = 'deepseek-v4-flash';
  10490. $thinkingMode = 'enabled';
  10491. }
  10492. $post_data = [
  10493. 'model' => $model,
  10494. 'messages' => $messages,
  10495. // 'max_tokens' => 8192,
  10496. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  10497. 'frequency_penalty' => 0,
  10498. 'presence_penalty' => 0,
  10499. 'response_format' => ['type' => 'text'],
  10500. 'thinking' => ['type' => $thinkingMode],
  10501. 'stream' => true // 启用流式输出
  10502. ];
  10503. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  10504. // 根据模型类型选择调用方法
  10505. $fullContent = '';
  10506. $fullReasoningContent = '';
  10507. $usage = [];
  10508. try {
  10509. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10510. // DeepSeek 官方模型使用 DeepSeek API
  10511. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  10512. } else if (in_array($model, $this->gpt_text_models)) {
  10513. // GPT-5.4 模型使用 TokenRouter API
  10514. $streamGenerator = $this->gpt54StreamResponse($post_data);
  10515. } else if (in_array($model, $this->gemini_text_models)) {
  10516. // Gemini 模型使用 Gemini API
  10517. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  10518. } else {
  10519. // 其他模型使用火山引擎API
  10520. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  10521. }
  10522. // 验证返回值类型
  10523. if (!is_iterable($streamGenerator)) {
  10524. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  10525. dLog('deepseek')->error('chat流式生成器无效', [
  10526. 'generator_type' => $errorType,
  10527. 'model' => $model,
  10528. 'anime_id' => $anime_id,
  10529. 'episode_number' => $episode_number
  10530. ]);
  10531. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  10532. 'type' => $errorType,
  10533. 'model' => $model
  10534. ]);
  10535. yield [
  10536. 'type' => 'error',
  10537. 'episode' => [],
  10538. 'answer' => '',
  10539. 'reasoning' => '',
  10540. 'usage' => [],
  10541. 'error' => '接口返回数据异常,请重新请求'
  10542. ];
  10543. return;
  10544. }
  10545. // 处理流式输出
  10546. foreach ($streamGenerator as $chunk) {
  10547. if (isset($chunk['type'])) {
  10548. if ($chunk['type'] === 'done') {
  10549. // 最终结果
  10550. $fullContent = $chunk['full_content'];
  10551. $fullReasoningContent = $chunk['full_reasoning'];
  10552. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  10553. } else {
  10554. // 逐块yield数据
  10555. yield $chunk;
  10556. }
  10557. }
  10558. }
  10559. } catch (\Exception $e) {
  10560. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  10561. 'model' => $model,
  10562. 'anime_id' => $anime_id,
  10563. 'episode_number' => $episode_number,
  10564. 'trace' => $e->getTraceAsString()
  10565. ]);
  10566. logDB('deepseek', 'error', 'chat流式处理失败', [
  10567. 'error' => $e->getMessage(),
  10568. 'model' => $model
  10569. ]);
  10570. yield [
  10571. 'type' => 'error',
  10572. 'episode' => [],
  10573. 'answer' => '',
  10574. 'reasoning' => '',
  10575. 'usage' => [],
  10576. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  10577. ];
  10578. return;
  10579. }
  10580. // 兼容模型偶发将整段正文包裹成 JSON 字符串返回
  10581. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  10582. dLog('deepseek')->info('完整内容: '.$fullContent);
  10583. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  10584. // 处理完整内容并返回最终结果
  10585. $episode_arr = handleEpisodeContentForAce($fullContent);
  10586. dLog('deepseek')->info('解析内容: ', $episode_arr);
  10587. logDB('deepseek', 'info', '解析内容', $episode_arr);
  10588. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  10589. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  10590. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  10591. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  10592. // }
  10593. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  10594. $max_retries = 3;
  10595. $retry_count = 0;
  10596. $validation_failed = false;
  10597. $validation_error_msg = '';
  10598. // 验证生成的内容
  10599. if ($anime_script_id) {
  10600. // 检查是否有acts数据
  10601. if (empty($episode_arr['acts'])) {
  10602. $validation_failed = true;
  10603. $validation_error_msg = '未生成分镜剧本相关的内容';
  10604. } else {
  10605. // 校验主体列表:不能为空主体(旁白不算)
  10606. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  10607. // 过滤掉"旁白"角色
  10608. $generated_roles = array_filter($generated_roles, function($role) {
  10609. return $role !== '旁白';
  10610. });
  10611. if (empty($generated_roles)) {
  10612. $validation_failed = true;
  10613. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  10614. }
  10615. // 仅当存在强制主体设定时校验主体列表
  10616. if (!$validation_failed && !empty($extra_roles)) {
  10617. $expected_roles = array_keys($extra_roles);
  10618. // 找出生成的主体中不在预期列表中的主体
  10619. $invalid_roles = array_diff($generated_roles, $expected_roles);
  10620. if (!empty($invalid_roles)) {
  10621. $validation_failed = true;
  10622. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  10623. }
  10624. }
  10625. // 仅当存在强制场景设定时校验场景列表
  10626. if (!$validation_failed && !empty($extra_scenes)) {
  10627. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  10628. $expected_scenes = array_keys($extra_scenes);
  10629. // 找出生成的场景中不在预期列表中的场景
  10630. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  10631. if (!empty($invalid_scenes)) {
  10632. $validation_failed = true;
  10633. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  10634. }
  10635. }
  10636. // 仅当存在强制道具设定时校验道具列表
  10637. if (!$validation_failed && !empty($extra_props)) {
  10638. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  10639. $expected_props = array_keys($extra_props);
  10640. // 找出生成的道具中不在预期列表中的道具
  10641. $invalid_props = array_diff($generated_props, $expected_props);
  10642. if (!empty($invalid_props)) {
  10643. $validation_failed = true;
  10644. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  10645. }
  10646. }
  10647. }
  10648. } else {
  10649. // 如果没有anime_script_id,只检查是否有acts数据
  10650. if (empty($episode_arr['acts'])) {
  10651. $validation_failed = true;
  10652. $validation_error_msg = '未生成分镜剧本相关的内容';
  10653. } else {
  10654. // 校验主体列表:不能为空主体(旁白不算)
  10655. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  10656. // 过滤掉"旁白"角色
  10657. $generated_roles = array_filter($generated_roles, function($role) {
  10658. return $role !== '旁白';
  10659. });
  10660. if (empty($generated_roles)) {
  10661. $validation_failed = true;
  10662. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  10663. }
  10664. }
  10665. }
  10666. // 重试逻辑
  10667. while ($validation_failed && $retry_count < $max_retries) {
  10668. $retry_count++;
  10669. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  10670. 'reason' => $validation_error_msg,
  10671. 'anime_id' => $anime_id,
  10672. 'episode_number' => $episode_number
  10673. ]);
  10674. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  10675. 'reason' => $validation_error_msg,
  10676. 'anime_id' => $anime_id
  10677. ]);
  10678. // 发送流式重试提示
  10679. yield [
  10680. 'type' => 'retry',
  10681. 'retry_count' => $retry_count,
  10682. 'reason' => $validation_error_msg
  10683. ];
  10684. // 构建重试提示词
  10685. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  10686. if ($anime_script_id) {
  10687. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  10688. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  10689. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  10690. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  10691. } else {
  10692. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  10693. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  10694. }
  10695. // 添加重试消息到messages
  10696. $messages[] = [
  10697. 'role' => 'assistant',
  10698. 'content' => $fullContent
  10699. ];
  10700. $messages[] = [
  10701. 'role' => 'user',
  10702. 'content' => $retry_prompt
  10703. ];
  10704. // 更新post_data的messages
  10705. $post_data['messages'] = $messages;
  10706. // 重新调用API
  10707. try {
  10708. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10709. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  10710. } else if (in_array($model, $this->gpt_text_models)) {
  10711. $streamGenerator = $this->gpt54StreamResponse($post_data);
  10712. } else if (in_array($model, $this->gemini_text_models)) {
  10713. // Gemini 模型使用 Gemini API
  10714. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  10715. } else {
  10716. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  10717. }
  10718. // 处理流式输出
  10719. $fullContent = '';
  10720. $fullReasoningContent = '';
  10721. foreach ($streamGenerator as $chunk) {
  10722. if (isset($chunk['type'])) {
  10723. if ($chunk['type'] === 'done') {
  10724. $fullContent = $chunk['full_content'];
  10725. $fullReasoningContent = $chunk['full_reasoning'];
  10726. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  10727. } else {
  10728. yield $chunk;
  10729. }
  10730. }
  10731. }
  10732. // 重新解析内容
  10733. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  10734. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  10735. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  10736. $episode_arr = handleEpisodeContentForAce($fullContent);
  10737. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  10738. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  10739. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  10740. // }
  10741. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  10742. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  10743. // 重新验证
  10744. $validation_failed = false;
  10745. $validation_error_msg = '';
  10746. if ($anime_script_id) {
  10747. if (empty($episode_arr['acts'])) {
  10748. $validation_failed = true;
  10749. $validation_error_msg = '未生成分镜剧本相关的内容';
  10750. } else {
  10751. // 校验主体列表:不能为空主体(旁白不算)
  10752. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  10753. // 过滤掉"旁白"角色
  10754. $generated_roles = array_filter($generated_roles, function($role) {
  10755. return $role !== '旁白';
  10756. });
  10757. if (empty($generated_roles)) {
  10758. $validation_failed = true;
  10759. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  10760. }
  10761. // 仅当存在强制主体设定时校验主体列表
  10762. if (!$validation_failed && !empty($extra_roles)) {
  10763. $expected_roles = array_keys($extra_roles);
  10764. $invalid_roles = array_diff($generated_roles, $expected_roles);
  10765. if (!empty($invalid_roles)) {
  10766. $validation_failed = true;
  10767. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  10768. }
  10769. }
  10770. // 仅当存在强制场景设定时校验场景列表
  10771. if (!$validation_failed && !empty($extra_scenes)) {
  10772. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  10773. $expected_scenes = array_keys($extra_scenes);
  10774. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  10775. if (!empty($invalid_scenes)) {
  10776. $validation_failed = true;
  10777. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  10778. }
  10779. }
  10780. // 仅当存在强制道具设定时校验道具列表
  10781. if (!$validation_failed && !empty($extra_props)) {
  10782. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  10783. $expected_props = array_keys($extra_props);
  10784. $invalid_props = array_diff($generated_props, $expected_props);
  10785. if (!empty($invalid_props)) {
  10786. $validation_failed = true;
  10787. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  10788. }
  10789. }
  10790. }
  10791. } else {
  10792. if (empty($episode_arr['acts'])) {
  10793. $validation_failed = true;
  10794. $validation_error_msg = '未生成分镜剧本相关的内容';
  10795. } else {
  10796. // 校验主体列表:不能为空主体(旁白不算)
  10797. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  10798. // 过滤掉"旁白"角色
  10799. $generated_roles = array_filter($generated_roles, function($role) {
  10800. return $role !== '旁白';
  10801. });
  10802. if (empty($generated_roles)) {
  10803. $validation_failed = true;
  10804. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  10805. }
  10806. }
  10807. }
  10808. } catch (\Exception $e) {
  10809. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  10810. 'trace' => $e->getTraceAsString()
  10811. ]);
  10812. break;
  10813. }
  10814. }
  10815. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  10816. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  10817. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  10818. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  10819. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  10820. if ($validation_failed && $retry_count >= $max_retries) {
  10821. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  10822. 'retry_count' => $retry_count,
  10823. 'last_error' => $validation_error_msg
  10824. ]);
  10825. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  10826. 'error' => $validation_error_msg,
  10827. 'anime_id' => $anime_id
  10828. ]);
  10829. $validation_failed = false;
  10830. $validation_error_msg = '';
  10831. }
  10832. // 如果重试后仍然失败
  10833. if ($validation_failed) {
  10834. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  10835. 'retry_count' => $retry_count,
  10836. 'last_error' => $validation_error_msg
  10837. ]);
  10838. try {
  10839. $now = date('Y-m-d H:i:s');
  10840. $records = [
  10841. [
  10842. 'uid' => $uid,
  10843. 'anime_id' => $anime_id,
  10844. 'sequence' => $episode_number,
  10845. 'role' => 'user',
  10846. 'content' => $prompt,
  10847. 'created_at' => $now,
  10848. 'updated_at' => $now
  10849. ],
  10850. [
  10851. 'uid' => $uid,
  10852. 'anime_id' => $anime_id,
  10853. 'sequence' => $episode_number,
  10854. 'role' => 'assistant',
  10855. 'content' => $fullContent,
  10856. 'created_at' => $now,
  10857. 'updated_at' => $now
  10858. ]
  10859. ];
  10860. DB::table('mp_anime_records')->insert($records);
  10861. } catch (\Exception $e) {
  10862. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  10863. }
  10864. yield [
  10865. 'type' => 'done',
  10866. 'episode' => [],
  10867. 'answer' => $fullContent,
  10868. 'reasoning' => $fullReasoningContent,
  10869. 'usage' => $usage,
  10870. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  10871. ];
  10872. return;
  10873. }
  10874. // 验证成功,记录日志
  10875. if ($retry_count > 0) {
  10876. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  10877. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  10878. }
  10879. // 老逻辑
  10880. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  10881. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  10882. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  10883. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  10884. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  10885. $existing_props = is_array($existing_props) ? $existing_props : [];
  10886. $now = date('Y-m-d H:i:s');
  10887. try {
  10888. DB::beginTransaction();
  10889. $saveResult = $this->saveEpisodeVersionData(
  10890. $anime_id,
  10891. $episode_number,
  10892. $episode_arr,
  10893. $existing_roles,
  10894. $existing_scenes,
  10895. $existing_props,
  10896. $current_episode,
  10897. $base_episode,
  10898. $is_regenerate_version,
  10899. $content,
  10900. $now,
  10901. $ref_products
  10902. );
  10903. $episode = $saveResult['episode'];
  10904. $episode_id = $saveResult['episode_id'];
  10905. $merged_roles = $saveResult['merged_roles'];
  10906. $merged_scenes = $saveResult['merged_scenes'];
  10907. $merged_props = $saveResult['merged_props'];
  10908. $record_content = $origin_prompt;
  10909. if ($uploaded_content !== '') {
  10910. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  10911. }
  10912. $records = [
  10913. [
  10914. 'uid' => $uid,
  10915. 'anime_id' => $anime_id,
  10916. 'role' => 'user',
  10917. 'content' => $record_content,
  10918. 'sequence' => $episode_number,
  10919. 'episode_id' => $episode_id,
  10920. 'created_at' => $now,
  10921. 'updated_at' => $now
  10922. ],
  10923. [
  10924. 'uid' => $uid,
  10925. 'anime_id' => $anime_id,
  10926. 'role' => 'assistant',
  10927. 'content' => $fullContent,
  10928. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  10929. 'sequence' => $episode_number,
  10930. 'episode_id' => $episode_id,
  10931. 'created_at' => $now,
  10932. 'updated_at' => $now
  10933. ]
  10934. ];
  10935. $boolen4 = DB::table('mp_anime_records')->insert($records);
  10936. if (!$boolen4) {
  10937. Utils::throwError('20003:对话记录保存失败');
  10938. }
  10939. // 保存模型到anime表
  10940. $update_anime_data = [
  10941. 'model' => $model,
  10942. 'updated_at' => $now
  10943. ];
  10944. if ($uploaded_content) {
  10945. $update_anime_data['content'] = $uploaded_content;
  10946. }
  10947. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  10948. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  10949. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  10950. 'anime_id' => $anime_id,
  10951. 'episode_number' => $episode_number,
  10952. 'model' => $model,
  10953. 'source' => 'chatForAce',
  10954. ]);
  10955. }catch (\Exception $e) {
  10956. DB::rollBack();
  10957. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  10958. yield [
  10959. 'type' => 'done',
  10960. 'answer' => $fullContent,
  10961. 'reasoning' => $fullReasoningContent,
  10962. 'usage' => $usage,
  10963. 'error' => $e->getMessage(),
  10964. ];
  10965. return;
  10966. }
  10967. DB::commit();
  10968. if ($is_global_generate_pics) {
  10969. // // 批量生成全局角色图片
  10970. // $this->batchSetGlobalRoleImg([
  10971. // 'anime_id' => $anime_id,
  10972. // ], true);
  10973. // // 批量生成全局场景图片
  10974. // $this->batchSetGlobalSceneImg([
  10975. // 'anime_id' => $anime_id,
  10976. // ], true);
  10977. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  10978. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  10979. }
  10980. $episode['episode_id'] = $episode_id;
  10981. $episode['roles'] = $merged_roles;
  10982. $episode['scenes'] = $merged_scenes;
  10983. $episode['props'] = $merged_props;
  10984. $episode['end_episode_sequence'] = $end_episode_sequence;
  10985. // 获取mp_animes表中的视频参数
  10986. $episode['video_params'] = [
  10987. 'video_model' => getProp($anime, 'video_model'),
  10988. 'video_resolution' => getProp($anime, 'video_resolution'),
  10989. 'ratio' => getProp($anime, 'video_ratio'),
  10990. ];
  10991. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  10992. yield [
  10993. 'type' => 'done',
  10994. 'episode' => $episode,
  10995. 'answer' => $fullContent,
  10996. 'reasoning' => $fullReasoningContent,
  10997. 'usage' => $usage
  10998. ];
  10999. }
  11000. /**
  11001. * chatForAce的非流式版本 - 用于定时任务
  11002. * 只获取最终 type=done 的数据,并验证必要字段
  11003. *
  11004. * @param array $data 请求数据
  11005. * @return array 生成结果
  11006. */
  11007. public function chatForAceNonStream($data) {
  11008. $finalResult = null;
  11009. // 调用流式方法,只保存 type=done 的数据
  11010. foreach ($this->chatForAce($data) as $chunk) {
  11011. // 只关注最终结果
  11012. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  11013. $finalResult = $chunk;
  11014. break; // 找到 done 就退出循环
  11015. }
  11016. }
  11017. // 验证最终结果
  11018. if (!$finalResult) {
  11019. return ['error' => '生成失败:未获取到最终结果'];
  11020. }
  11021. // 检查是否有错误
  11022. if (isset($finalResult['error']) && $finalResult['error']) {
  11023. return $finalResult;
  11024. }
  11025. // 验证必要字段
  11026. $episode = $finalResult['episode'] ?? [];
  11027. // 验证 roles(旁白不算主体,过滤后不能为空)
  11028. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  11029. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  11030. }
  11031. $nonNarratorRoles = array_filter(array_column($episode['roles'], 'role'), function($role) {
  11032. return $role !== '旁白';
  11033. });
  11034. if (empty($nonNarratorRoles)) {
  11035. return ['error' => '生成失败:主体列表(roles)为空或格式错误(旁白不算)'];
  11036. }
  11037. // 验证 scenes
  11038. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  11039. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  11040. }
  11041. // 验证 props(道具可以为空,但必须存在且为数组)
  11042. if (!isset($episode['props']) || !is_array($episode['props'])) {
  11043. $episode['props'] = [];
  11044. }
  11045. // 验证 acts(分镜剧本)
  11046. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  11047. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  11048. }
  11049. // 更新验证后的 episode 数据
  11050. $finalResult['episode'] = $episode;
  11051. // 记录验证成功日志
  11052. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  11053. 'roles_count' => count($episode['roles']),
  11054. 'scenes_count' => count($episode['scenes']),
  11055. 'props_count' => count($episode['props']),
  11056. 'acts_count' => count($episode['acts'])
  11057. ]);
  11058. return $finalResult;
  11059. }
  11060. /**
  11061. * 批量生成多个分集
  11062. *
  11063. * @param array $data 请求数据
  11064. * @return array 任务信息
  11065. */
  11066. public function batchGenerateEpisodes($data) {
  11067. $uid = Site::getUid();
  11068. $cpid = Site::getCpid();
  11069. $anime_id = getProp($data, 'anime_id');
  11070. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  11071. $start_episode_number = getProp($data, 'start_episode_number');
  11072. $end_episode_number = getProp($data, 'end_episode_number');
  11073. if (!$anime_id) {
  11074. Utils::throwError('20003:anime_id参数缺失');
  11075. }
  11076. if ($generate_episode_number < 1) {
  11077. Utils::throwError('20003:生成集数必须大于0');
  11078. }
  11079. // 获取动漫信息
  11080. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  11081. if (!$anime) {
  11082. Utils::throwError('20003:该剧集不存在');
  11083. }
  11084. // 检查是否是全能模式
  11085. if ((int)getProp($anime, 'ace_mode') !== 1) {
  11086. Utils::throwError('20003:只有全能模式才支持批量生成');
  11087. }
  11088. // 检查是否是多剧集模式
  11089. if ((int)getProp($anime, 'is_multi') !== 1) {
  11090. Utils::throwError('20003:单剧集不支持批量生成');
  11091. }
  11092. // 指定起始/结束剧集序号时的校验
  11093. $hasSpecifiedRange = ($start_episode_number !== null && $start_episode_number !== '')
  11094. || ($end_episode_number !== null && $end_episode_number !== '');
  11095. if ($hasSpecifiedRange) {
  11096. if ($start_episode_number === null || $start_episode_number === ''
  11097. || $end_episode_number === null || $end_episode_number === '') {
  11098. Utils::throwError('20003:起始剧集序号和结束剧集序号必须同时提供');
  11099. }
  11100. $start_episode_number = (int)$start_episode_number;
  11101. $end_episode_number = (int)$end_episode_number;
  11102. if ($start_episode_number < 1 || $end_episode_number < $start_episode_number) {
  11103. Utils::throwError('20003:剧集序号范围错误,结束剧集序号不能小于起始剧集序号');
  11104. }
  11105. // 起始序号必须是已有剧集(is_default=1)的下一个序号,不允许跨序号创建
  11106. $currentMaxEpisode = DB::table('mp_anime_episodes')
  11107. ->where('anime_id', $anime_id)
  11108. ->where('is_default', 1)
  11109. ->max('episode_number');
  11110. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  11111. $nextEpisodeNumber = $currentMaxEpisode + 1;
  11112. if ($start_episode_number !== $nextEpisodeNumber) {
  11113. Utils::throwError('20003:起始剧集序号必须是已有剧集的下一个序号(第' . $nextEpisodeNumber . '集),不允许跨序号创建');
  11114. }
  11115. $startEpisodeNumber = $start_episode_number;
  11116. $endEpisodeNumber = $end_episode_number;
  11117. } else {
  11118. // 未指定范围时,以 generate_episode_number 判断要生成的集数,从当前已生成的最大集数的下一集开始
  11119. $currentMaxEpisode = DB::table('mp_anime_episodes')
  11120. ->where('anime_id', $anime_id)
  11121. ->where('is_default', 1)
  11122. ->max('episode_number');
  11123. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  11124. // 确定起始集数
  11125. $startEpisodeNumber = $currentMaxEpisode + 1;
  11126. // 计算结束集数
  11127. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  11128. }
  11129. // 本次实际生成的集数
  11130. $totalEpisodeCount = $endEpisodeNumber - $startEpisodeNumber + 1;
  11131. // 检查是否超过总集数限制
  11132. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  11133. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  11134. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  11135. }
  11136. // 创建任务前验重:批量任务表与剧集表中是否已存在范围内的剧集序号
  11137. $duplicatedBatchEpisodes = DB::table('mp_batch_episode_generation_details')
  11138. ->where('anime_id', $anime_id)
  11139. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11140. ->pluck('episode_number')
  11141. ->unique()
  11142. ->sort()
  11143. ->values()
  11144. ->toArray();
  11145. $duplicatedAnimeEpisodes = DB::table('mp_anime_episodes')
  11146. ->where('anime_id', $anime_id)
  11147. ->where('is_default', 1)
  11148. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11149. ->pluck('episode_number')
  11150. ->unique()
  11151. ->sort()
  11152. ->values()
  11153. ->toArray();
  11154. if (!empty($duplicatedBatchEpisodes) || !empty($duplicatedAnimeEpisodes)) {
  11155. $duplicateMessages = [];
  11156. if (!empty($duplicatedBatchEpisodes)) {
  11157. $duplicateMessages[] = '批量生成任务中已存在第' . implode('、', $duplicatedBatchEpisodes) . '集';
  11158. }
  11159. if (!empty($duplicatedAnimeEpisodes)) {
  11160. $duplicateMessages[] = '剧集中已存在第' . implode('、', $duplicatedAnimeEpisodes) . '集';
  11161. }
  11162. Utils::throwError('20003:' . implode(';', $duplicateMessages) . ',请勿重复创建');
  11163. }
  11164. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  11165. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  11166. ->where('anime_id', $anime_id)
  11167. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11168. ->whereIn('status', ['pending', 'processing', 'completed'])
  11169. ->count();
  11170. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  11171. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  11172. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  11173. if ($needEpisodeCount > 0) {
  11174. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints() * $needEpisodeCount, $uid);
  11175. }
  11176. $now = date('Y-m-d H:i:s');
  11177. $createdTasks = [];
  11178. $skippedTasks = [];
  11179. // 为每一集创建详情记录
  11180. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  11181. // 检查是否已有该集的任务记录
  11182. $existingTask = DB::table('mp_batch_episode_generation_details')
  11183. ->where('anime_id', $anime_id)
  11184. ->where('episode_number', $episodeNumber)
  11185. ->first();
  11186. if ($existingTask) {
  11187. // 如果已存在且未完成,跳过
  11188. if (in_array($existingTask->status, ['pending', 'processing'])) {
  11189. $skippedTasks[] = $episodeNumber;
  11190. continue;
  11191. }
  11192. // 如果是失败状态,可以重新创建(删除旧记录)
  11193. if ($existingTask->status === 'failed') {
  11194. DB::table('mp_batch_episode_generation_details')
  11195. ->where('id', $existingTask->id)
  11196. ->delete();
  11197. }
  11198. // 如果是已完成状态,也跳过
  11199. if ($existingTask->status === 'completed') {
  11200. $skippedTasks[] = $episodeNumber;
  11201. continue;
  11202. }
  11203. }
  11204. // 准备任务数据
  11205. $taskData = [
  11206. 'anime_id' => $anime_id,
  11207. 'uid' => $uid,
  11208. 'cpid' => $cpid,
  11209. 'episode_number' => $episodeNumber,
  11210. 'status' => 'pending',
  11211. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  11212. 'retry_count' => 0,
  11213. 'created_at' => $now,
  11214. 'updated_at' => $now
  11215. ];
  11216. // 创建任务记录
  11217. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  11218. if ($taskId) {
  11219. $createdTasks[] = $episodeNumber;
  11220. }
  11221. }
  11222. if (empty($createdTasks)) {
  11223. if (!empty($skippedTasks)) {
  11224. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  11225. } else {
  11226. Utils::throwError('20003:创建批量生成任务失败');
  11227. }
  11228. }
  11229. // 创建/复用任务中心记录(按入参+type验重,避免重复任务)
  11230. $taskCenterId = $this->createBatchGenerateEpisodesTaskCenter(
  11231. $uid,
  11232. $cpid,
  11233. $anime_id,
  11234. $generate_episode_number,
  11235. $startEpisodeNumber,
  11236. $endEpisodeNumber
  11237. );
  11238. return [
  11239. 'anime_id' => $anime_id,
  11240. 'start_episode' => $startEpisodeNumber,
  11241. 'end_episode' => $endEpisodeNumber,
  11242. 'total_episodes' => $totalEpisodeCount,
  11243. 'created_episodes' => $createdTasks,
  11244. 'skipped_episodes' => $skippedTasks,
  11245. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$totalEpisodeCount}集。" .
  11246. "已创建: " . implode(',', $createdTasks) .
  11247. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : ""),
  11248. 'task_center_id' => $taskCenterId
  11249. ];
  11250. }
  11251. /**
  11252. * 根据入参创建或复用批量生成分集的任务中心记录
  11253. *
  11254. * 以入参(anime_id、generate_episode_number)计算 md5 存入 params_md5 字段用于验重:
  11255. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  11256. * 避免生成重复任务;唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复。
  11257. *
  11258. * @param int|string $uid
  11259. * @param int|string $cpid
  11260. * @param int|string $anime_id
  11261. * @param int $generate_episode_number
  11262. * @param int $startEpisodeNumber
  11263. * @param int $endEpisodeNumber
  11264. * @return int 任务中心ID
  11265. */
  11266. private function createBatchGenerateEpisodesTaskCenter($uid, $cpid, $anime_id, $generate_episode_number, $startEpisodeNumber, $endEpisodeNumber) {
  11267. $params = [
  11268. 'anime_id' => (int)$anime_id,
  11269. 'generate_episode_number' => (int)$generate_episode_number,
  11270. 'start_episode' => (int)$startEpisodeNumber,
  11271. 'end_episode' => (int)$endEpisodeNumber,
  11272. ];
  11273. // 验重键:入参 + 生成范围(anime_id + generate_episode_number + start/end)+ task_type
  11274. $paramsMd5 = md5(json_encode([
  11275. 'anime_id' => (int)$anime_id,
  11276. 'generate_episode_number' => (int)$generate_episode_number,
  11277. 'start_episode' => (int)$startEpisodeNumber,
  11278. 'end_episode' => (int)$endEpisodeNumber,
  11279. ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  11280. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  11281. $existing = DB::table('mp_task_center')
  11282. ->where('uid', (int)$uid)
  11283. ->where('cpid', (int)$cpid)
  11284. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11285. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  11286. ->where('params_md5', $paramsMd5)
  11287. ->orderBy('id', 'desc')
  11288. ->first();
  11289. if ($existing) {
  11290. dLog('deepseek')->info('复用批量生成分集任务中心记录,避免重复任务', [
  11291. 'anime_id' => $anime_id,
  11292. 'task_center_id' => $existing->id,
  11293. 'params_md5' => $paramsMd5,
  11294. ]);
  11295. return (int)$existing->id;
  11296. }
  11297. $now = date('Y-m-d H:i:s');
  11298. DB::table('mp_task_center')->insertOrIgnore([
  11299. 'uid' => (int)$uid,
  11300. 'cpid' => (int)$cpid,
  11301. 'task_type' => MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES,
  11302. 'title' => '批量生成分集',
  11303. 'ref_task_id' => 0,
  11304. 'status' => MpTaskCenter::STATUS_PROCESSING,
  11305. 'result' => null,
  11306. 'error_message' => null,
  11307. 'prompt' => null,
  11308. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  11309. 'params_md5' => $paramsMd5,
  11310. 'created_at' => $now,
  11311. 'updated_at' => $now,
  11312. ]);
  11313. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  11314. $taskId = (int)DB::table('mp_task_center')
  11315. ->where('uid', (int)$uid)
  11316. ->where('cpid', (int)$cpid)
  11317. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11318. ->where('params_md5', $paramsMd5)
  11319. ->orderBy('id', 'desc')
  11320. ->value('id');
  11321. dLog('deepseek')->info('创建批量生成分集任务中心记录', [
  11322. 'anime_id' => $anime_id,
  11323. 'task_center_id' => $taskId,
  11324. 'params_md5' => $paramsMd5,
  11325. ]);
  11326. return $taskId;
  11327. }
  11328. /**
  11329. * 批量生成分集全部结束后,更新任务中心记录的状态和结果
  11330. *
  11331. * 由批量生成 worker 子进程在退出前调用。分集详情任务的状态会在多处更新
  11332. * (completed/failed/pending/processing),这里只在所有详情任务均已结束时
  11333. * 统一汇总更新,避免在每个更新点重复处理。
  11334. *
  11335. * @param int|string $animeId
  11336. * @return int 更新的任务中心记录数
  11337. */
  11338. public function finishBatchGenerateEpisodesTaskCenters($animeId) {
  11339. $animeId = (int)$animeId;
  11340. $updated = 0;
  11341. // 该 anime 是否还有未结束的详情任务
  11342. $hasUnfinished = DB::table('mp_batch_episode_generation_details')
  11343. ->where('anime_id', $animeId)
  11344. ->whereIn('status', ['pending', 'processing'])
  11345. ->exists();
  11346. // 扫描该 anime 相关的未完成任务中心记录
  11347. $tasks = DB::table('mp_task_center')
  11348. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11349. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  11350. ->orderBy('id', 'desc')
  11351. ->limit(500)
  11352. ->get();
  11353. if ($hasUnfinished && !$tasks) {
  11354. return 0;
  11355. }
  11356. foreach ($tasks as $task) {
  11357. try {
  11358. $taskParams = json_decode((string)$task->params, true);
  11359. if (!is_array($taskParams) || (int)($taskParams['anime_id'] ?? 0) !== $animeId) {
  11360. continue;
  11361. }
  11362. $startEpisode = (int)($taskParams['start_episode'] ?? 0);
  11363. $endEpisode = (int)($taskParams['end_episode'] ?? 0);
  11364. if ($startEpisode < 1 || $endEpisode < $startEpisode) {
  11365. continue;
  11366. }
  11367. $details = DB::table('mp_batch_episode_generation_details')
  11368. ->where('anime_id', $animeId)
  11369. ->whereBetween('episode_number', [$startEpisode, $endEpisode])
  11370. ->get();
  11371. // 该批次范围内存在缺失记录,等待下一次检查
  11372. if ($details->isEmpty() || $details->count() < ($endEpisode - $startEpisode + 1)) {
  11373. continue;
  11374. }
  11375. $completedEpisodes = [];
  11376. $failedEpisodes = [];
  11377. $allFinished = true;
  11378. foreach ($details as $detail) {
  11379. if ($detail->status === 'completed') {
  11380. $completedEpisodes[] = $detail->episode_number;
  11381. } elseif ($detail->status === 'failed') {
  11382. $failedEpisodes[] = [
  11383. 'episode_number' => $detail->episode_number,
  11384. 'error_message' => $detail->error_message ?? '',
  11385. ];
  11386. } else {
  11387. // pending/processing(防御处理,正常不会走到)
  11388. $allFinished = false;
  11389. break;
  11390. }
  11391. }
  11392. if (!$allFinished) {
  11393. continue;
  11394. }
  11395. $result = json_encode([
  11396. 'anime_id' => $animeId,
  11397. 'start_episode' => $startEpisode,
  11398. 'end_episode' => $endEpisode,
  11399. 'total_episodes' => count($details),
  11400. 'completed_count' => count($completedEpisodes),
  11401. 'failed_count' => count($failedEpisodes),
  11402. 'completed_episodes' => $completedEpisodes,
  11403. 'failed_episodes' => $failedEpisodes,
  11404. ], JSON_UNESCAPED_UNICODE);
  11405. DB::table('mp_task_center')
  11406. ->where('id', $task->id)
  11407. ->update([
  11408. 'status' => !empty($failedEpisodes) ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  11409. 'result' => $result,
  11410. 'error_message' => !empty($failedEpisodes) ? ('有 ' . count($failedEpisodes) . ' 集生成失败') : null,
  11411. 'updated_at' => date('Y-m-d H:i:s'),
  11412. ]);
  11413. $updated++;
  11414. dLog('command')->info('批量生成分集任务已完成,更新任务中心', [
  11415. 'task_center_id' => $task->id,
  11416. 'anime_id' => $animeId,
  11417. 'start_episode' => $startEpisode,
  11418. 'end_episode' => $endEpisode,
  11419. ]);
  11420. } catch (\Exception $e) {
  11421. dLog('command')->error('更新批量生成分集任务中心异常', [
  11422. 'task_center_id' => $task->id,
  11423. 'anime_id' => $animeId,
  11424. 'error' => $e->getMessage(),
  11425. ]);
  11426. }
  11427. }
  11428. return $updated;
  11429. }
  11430. /**
  11431. * 获取批量生成任务状态
  11432. *
  11433. * @param array $data 请求数据
  11434. * @return array 任务状态信息
  11435. */
  11436. public function getBatchGenerationTaskStatus($data) {
  11437. $anime_id = getProp($data, 'anime_id');
  11438. if (!$anime_id) {
  11439. Utils::throwError('20003:anime_id参数缺失');
  11440. }
  11441. // 获取该anime的所有任务
  11442. $tasks = DB::table('mp_batch_episode_generation_details')
  11443. ->where('anime_id', $anime_id)
  11444. ->orderBy('episode_number')
  11445. ->get()
  11446. ->map(function($item) {
  11447. return [
  11448. 'id' => $item->id,
  11449. 'episode_number' => $item->episode_number,
  11450. 'status' => $item->status,
  11451. 'error_message' => $item->error_message,
  11452. 'retry_count' => $item->retry_count,
  11453. 'created_at' => $item->created_at,
  11454. 'updated_at' => $item->updated_at,
  11455. 'completed_at' => $item->completed_at
  11456. ];
  11457. })
  11458. ->toArray();
  11459. if (empty($tasks)) {
  11460. Utils::throwError('20003:该剧集没有批量生成任务');
  11461. }
  11462. // 统计各状态数量
  11463. $totalCount = count($tasks);
  11464. $pendingCount = 0;
  11465. $processingCount = 0;
  11466. $completedCount = 0;
  11467. $failedCount = 0;
  11468. $failed_episodes = [];
  11469. foreach ($tasks as $task) {
  11470. switch ($task['status']) {
  11471. case 'pending':
  11472. $pendingCount++;
  11473. break;
  11474. case 'processing':
  11475. $processingCount++;
  11476. break;
  11477. case 'completed':
  11478. $completedCount++;
  11479. break;
  11480. case 'failed':
  11481. $failedCount++;
  11482. // 组装失败分集对象(新对象):分集序号、错误原因
  11483. $failed_episodes[] = [
  11484. 'episode_number' => $task['episode_number'],
  11485. 'error_message' => $task['error_message'] ?? ''
  11486. ];
  11487. break;
  11488. }
  11489. }
  11490. // 计算进度百分比
  11491. $progress = 0;
  11492. if ($totalCount > 0) {
  11493. $progress = round(($completedCount / $totalCount) * 100, 2);
  11494. }
  11495. // 判断整体状态
  11496. $overallStatus = 'processing';
  11497. if ($completedCount === $totalCount) {
  11498. $overallStatus = 'completed';
  11499. } elseif ($pendingCount === $totalCount) {
  11500. $overallStatus = 'pending';
  11501. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  11502. $overallStatus = 'failed';
  11503. }
  11504. return [
  11505. 'anime_id' => $anime_id,
  11506. 'total_episodes' => $totalCount,
  11507. 'pending_count' => $pendingCount,
  11508. 'processing_count' => $processingCount,
  11509. 'completed_count' => $completedCount,
  11510. 'failed_count' => $failedCount,
  11511. 'progress' => $progress,
  11512. 'overall_status' => $overallStatus,
  11513. 'failed_episodes' => $failed_episodes,
  11514. 'tasks' => $tasks
  11515. ];
  11516. }
  11517. /**
  11518. * 将生成内容中不在强制列表中的资源合并进强制列表
  11519. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  11520. *
  11521. * @param array $generated 生成内容中的资源列表
  11522. * @param array $forced 强制资源列表(key为资源名称)
  11523. * @param string $type 资源类型:role、scene、prop
  11524. * @return array
  11525. */
  11526. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  11527. {
  11528. foreach ($generated as $item) {
  11529. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  11530. if ($name === null || $name === '') {
  11531. continue;
  11532. }
  11533. if ($name === '旁白') {
  11534. continue;
  11535. }
  11536. if (!isset($forced[$name])) {
  11537. $forced[$name] = $item;
  11538. }
  11539. }
  11540. return $forced;
  11541. }
  11542. /**
  11543. * 智能匹配并替换主体和场景名称
  11544. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  11545. *
  11546. * @param array $episode_arr 解析后的剧集数据
  11547. * @param array $extra_roles 强制主体设定(key为主体名称)
  11548. * @param array $extra_scenes 强制场景设定(key为场景名称)
  11549. * @return array 替换后的剧集数据
  11550. */
  11551. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  11552. $replaced_count = 0;
  11553. // 1. 处理主体列表
  11554. if (!empty($episode_arr['roles'])) {
  11555. foreach ($episode_arr['roles'] as &$role) {
  11556. $generated_role_name = $role['role'] ?? '';
  11557. // 跳过旁白
  11558. if ($generated_role_name === '旁白') {
  11559. continue;
  11560. }
  11561. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  11562. if (!isset($extra_roles[$generated_role_name])) {
  11563. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  11564. if ($matched_role) {
  11565. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  11566. $role['role'] = $matched_role;
  11567. $replaced_count++;
  11568. }
  11569. }
  11570. }
  11571. }
  11572. // 2. 处理场景列表
  11573. if (!empty($episode_arr['scenes'])) {
  11574. foreach ($episode_arr['scenes'] as &$scene) {
  11575. $generated_scene_name = $scene['scene'] ?? '';
  11576. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  11577. if (!isset($extra_scenes[$generated_scene_name])) {
  11578. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  11579. if ($matched_scene) {
  11580. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  11581. $scene['scene'] = $matched_scene;
  11582. $replaced_count++;
  11583. }
  11584. }
  11585. }
  11586. }
  11587. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  11588. if (!empty($episode_arr['acts'])) {
  11589. foreach ($episode_arr['acts'] as &$act) {
  11590. if (!empty($act['segments'])) {
  11591. foreach ($act['segments'] as &$segment) {
  11592. if (!empty($segment['segment_content'])) {
  11593. $original_content = $segment['segment_content'];
  11594. $replaced_content = $original_content;
  11595. // 替换场景名 - 在文本中查找并替换
  11596. foreach (array_keys($extra_scenes) as $full_scene_name) {
  11597. // 尝试找到可能的短名称
  11598. $potential_short_names = [];
  11599. // 提取场景名的主要部分(冒号之前)
  11600. if (mb_strpos($full_scene_name, ':') !== false) {
  11601. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  11602. $potential_short_names[] = $short_name;
  11603. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  11604. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  11605. $potential_short_names[] = $short_name;
  11606. }
  11607. // 替换场景字段中的短名称
  11608. foreach ($potential_short_names as $short_name) {
  11609. if ($short_name !== $full_scene_name) {
  11610. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  11611. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  11612. if ($new_content !== $replaced_content) {
  11613. $replaced_content = $new_content;
  11614. $replaced_count++;
  11615. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  11616. }
  11617. }
  11618. }
  11619. }
  11620. // 替换配音角色名(跳过旁白)
  11621. foreach (array_keys($extra_roles) as $full_role_name) {
  11622. if ($full_role_name === '旁白') {
  11623. continue;
  11624. }
  11625. // 尝试找到可能的短名称
  11626. $potential_short_names = [];
  11627. // 提取角色名的主要部分(短横线之前)
  11628. if (mb_strpos($full_role_name, '-') !== false) {
  11629. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  11630. $potential_short_names[] = $short_name;
  11631. }
  11632. // 替换配音台词中的短名称
  11633. foreach ($potential_short_names as $short_name) {
  11634. if ($short_name !== $full_role_name) {
  11635. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  11636. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  11637. if ($new_content !== $replaced_content) {
  11638. $replaced_content = $new_content;
  11639. $replaced_count++;
  11640. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  11641. }
  11642. }
  11643. }
  11644. }
  11645. // 如果有替换,更新segment_content
  11646. if ($replaced_content !== $original_content) {
  11647. $segment['segment_content'] = $replaced_content;
  11648. }
  11649. }
  11650. }
  11651. }
  11652. }
  11653. }
  11654. if ($replaced_count > 0) {
  11655. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  11656. 'replaced_count' => $replaced_count
  11657. ]);
  11658. }
  11659. return $episode_arr;
  11660. }
  11661. /**
  11662. * 查找匹配的名称
  11663. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  11664. *
  11665. * @param string $generated_name 生成的名称
  11666. * @param array $expected_names 预期的名称列表
  11667. * @return string|null 匹配到的名称,如果没有匹配则返回null
  11668. */
  11669. private function findMatchingName($generated_name, $expected_names) {
  11670. if (empty($generated_name)) {
  11671. return null;
  11672. }
  11673. // 尝试精确匹配
  11674. if (in_array($generated_name, $expected_names)) {
  11675. return $generated_name;
  11676. }
  11677. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  11678. foreach ($expected_names as $expected_name) {
  11679. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  11680. if (mb_strpos($expected_name, $generated_name) === 0) {
  11681. return $expected_name;
  11682. }
  11683. }
  11684. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  11685. // 这样可以处理一些变体,但优先级较低
  11686. foreach ($expected_names as $expected_name) {
  11687. if (mb_strpos($expected_name, $generated_name) !== false) {
  11688. return $expected_name;
  11689. }
  11690. }
  11691. return null;
  11692. }
  11693. /**
  11694. * 重新生成分段剧本
  11695. * @param array $data 包含以下字段:
  11696. * - prompt: string|null 用户修改要求(可选)
  11697. * - template_id: int|null 提示词模板ID(可选)
  11698. * - act_id: int|null 单个片段ID(与episode_id二选一)
  11699. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  11700. * @return array 返回生成结果
  11701. */
  11702. public function regenerateSegmentScript($data) {
  11703. $uid = Site::getUid();
  11704. $prompt = trim((string)getProp($data, 'prompt', ''));
  11705. $template_id = getProp($data, 'template_id', 0);
  11706. $act_id = getProp($data, 'act_id', 0);
  11707. $episode_id = getProp($data, 'episode_id', 0);
  11708. $check_mode = (int)getProp($data, 'check_mode', 0); // 1=预览确认模式(仅 act_id 模式生效,不落库,返回 editAct 入参)
  11709. // 单片段模式:act_id 可以是数据库真实ID(数字)或预览生成的虚拟ID(字符串),非空即单片段模式
  11710. $isActIdMode = !empty($act_id);
  11711. // 验证:prompt和template_id至少提供一个
  11712. if (empty($prompt) && empty($template_id)) {
  11713. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  11714. }
  11715. // 验证:act_id和episode_id二选一
  11716. if (empty($act_id) && empty($episode_id)) {
  11717. Utils::throwError('20003:请提供片段ID或剧集ID');
  11718. }
  11719. if (!empty($act_id) && !empty($episode_id)) {
  11720. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  11721. }
  11722. // 积分余额预检:act_id 单片段模式按 normal 档,episode_id 剧集模式按 special 档
  11723. $chargeType = $isActIdMode ? 'normal' : 'special';
  11724. if ($isActIdMode) {
  11725. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', $chargeType), $uid);
  11726. } else {
  11727. $is_generated = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('is_generated');
  11728. if ($is_generated) Utils::throwError('20003:该分集已不支持重新生成片段,请创建副本后重试!');
  11729. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', $chargeType), $uid);
  11730. }
  11731. // 如果提供了template_id,获取模板提示词
  11732. $template_prompt = '';
  11733. if ($template_id > 0) {
  11734. $template = DB::table('mp_prompt_templates')
  11735. ->where('id', $template_id)
  11736. ->where('is_deleted', 0)
  11737. ->first();
  11738. if (!$template) {
  11739. Utils::throwError('20003:提示词模板不存在或已删除');
  11740. }
  11741. $template_prompt = $template->template_prompt ?? '';
  11742. }
  11743. // 合并用户提示词和模板提示词(模板提示词与用户输入基本一致时只保留一个,避免重复提示词)
  11744. $final_prompt = '';
  11745. if (!empty($template_prompt)) {
  11746. $trimmedPrompt = trim((string)$prompt);
  11747. if ($trimmedPrompt !== '' && mb_strtolower($trimmedPrompt) === mb_strtolower(trim($template_prompt))) {
  11748. $final_prompt = $template_prompt;
  11749. } elseif (!empty($prompt)) {
  11750. $final_prompt = $template_prompt . "\n\n补充要求:" . $prompt;
  11751. } else {
  11752. $final_prompt = $template_prompt;
  11753. }
  11754. } else {
  11755. $final_prompt = $prompt;
  11756. }
  11757. // 获取需要重新生成的内容参考
  11758. $reference_content = '';
  11759. $target_episode_id = 0;
  11760. $target_anime_id = 0;
  11761. $target_episode_number = 0;
  11762. if ($isActIdMode) {
  11763. // 单个片段模式:获取该片段的内容
  11764. $segment = DB::table('mp_episode_segments')
  11765. ->where('id', $act_id)
  11766. ->first();
  11767. // 数据库不存在时,尝试从预览虚拟 act_id 保存的 redis 数据中恢复
  11768. if (!$segment) {
  11769. $previewData = Redis::get($this->buildActPreviewKey($act_id));
  11770. if ($previewData) {
  11771. $previewData = json_decode($previewData, true);
  11772. $segment = (object)[
  11773. 'anime_id' => getProp($previewData, 'anime_id'),
  11774. 'episode_id' => getProp($previewData, 'episode_id'),
  11775. 'episode_number' => getProp($previewData, 'episode_number'),
  11776. 'act_number' => getProp($previewData, 'act_number'),
  11777. 'act_duration' => getProp($previewData, 'act_duration'),
  11778. 'act_content' => getProp($previewData, 'act_content'),
  11779. ];
  11780. }
  11781. }
  11782. if (!$segment) {
  11783. Utils::throwError('20003:片段不存在');
  11784. }
  11785. $target_episode_id = $segment->episode_id;
  11786. $target_anime_id = $segment->anime_id;
  11787. $target_episode_number = $segment->episode_number;
  11788. $reference_content = $segment->act_content ?? '';
  11789. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  11790. } else {
  11791. // 整个剧集模式:获取所有片段的内容
  11792. $segments = DB::table('mp_episode_segments')
  11793. ->where('episode_id', $episode_id)
  11794. ->orderBy('act_number')
  11795. ->get();
  11796. if ($segments->isEmpty()) {
  11797. Utils::throwError('20003:该剧集没有片段数据');
  11798. }
  11799. $target_episode_id = $episode_id;
  11800. $target_anime_id = $segments[0]->anime_id;
  11801. $target_episode_number = $segments[0]->episode_number;
  11802. // 拼接所有片段内容,保留格式用于AI理解
  11803. $act_contents = [];
  11804. foreach ($segments as $seg) {
  11805. $act_number = $seg->act_number;
  11806. $act_content = $seg->act_content ?? '';
  11807. if (!empty($act_content)) {
  11808. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  11809. }
  11810. }
  11811. $reference_content = implode("\n\n", $act_contents);
  11812. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  11813. if ($episode_content) {
  11814. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【原分段剧本内容】\n{$reference_content}";
  11815. //$reference_content = "\n\n【本集原始内容】\n{$episode_content}";
  11816. }else {
  11817. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  11818. }
  11819. }
  11820. if (empty($reference_content)) {
  11821. Utils::throwError('20003:没有可参考的片段内容');
  11822. }
  11823. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  11824. $episode = DB::table('mp_anime_episodes')
  11825. ->where('id', $target_episode_id)
  11826. ->first();
  11827. if (!$episode) {
  11828. Utils::throwError('20003:剧集不存在');
  11829. }
  11830. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  11831. $anime_script_id = getProp($anime, 'script_id');
  11832. $intro = $episode->intro ?? '';
  11833. $art_style = $episode->art_style ?? '';
  11834. $roles = json_decode($episode->roles ?? '[]', true);
  11835. $scenes = json_decode($episode->scenes ?? '[]', true);
  11836. $props = json_decode($episode->props ?? '[]', true);
  11837. // 构建提示词中的主体列表和场景列表参考
  11838. $roles_ref = '';
  11839. if (!empty($roles) && is_array($roles)) {
  11840. $roles_list = [];
  11841. foreach ($roles as $role) {
  11842. $role_name = getProp($role, 'role', '');
  11843. $role_desc = getProp($role, 'description', '');
  11844. $pic_prompt = getProp($role, 'pic_prompt', '');
  11845. $voice_prompt = getProp($role, 'voice_prompt', '');
  11846. if (!empty($role_name)) {
  11847. $role_line = $role_name;
  11848. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  11849. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  11850. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  11851. $roles_list[] = $role_line;
  11852. }
  11853. }
  11854. if (!empty($roles_list)) {
  11855. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  11856. }
  11857. }
  11858. $scenes_ref = '';
  11859. if (!empty($scenes) && is_array($scenes)) {
  11860. $scenes_list = [];
  11861. foreach ($scenes as $scene) {
  11862. $scene_name = getProp($scene, 'scene', '');
  11863. $scene_desc = getProp($scene, 'description', '');
  11864. $pic_prompt = getProp($scene, 'pic_prompt', '');
  11865. if (!empty($scene_name)) {
  11866. $scene_line = $scene_name;
  11867. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  11868. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  11869. $scenes_list[] = $scene_line;
  11870. }
  11871. }
  11872. if (!empty($scenes_list)) {
  11873. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  11874. }
  11875. }
  11876. $props_ref = '';
  11877. if (!empty($props) && is_array($props)) {
  11878. $props_list = [];
  11879. foreach ($props as $prop) {
  11880. $prop_name = getProp($prop, 'prop', '');
  11881. $prop_desc = getProp($prop, 'description', '');
  11882. $pic_prompt = getProp($prop, 'pic_prompt', '');
  11883. if (!empty($prop_name)) {
  11884. $prop_line = $prop_name;
  11885. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  11886. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  11887. $props_list[] = $prop_line;
  11888. }
  11889. }
  11890. if (!empty($props_list)) {
  11891. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  11892. }
  11893. }
  11894. // 构建美术风格参考
  11895. $art_style_ref = '';
  11896. if (!empty($art_style)) {
  11897. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  11898. }
  11899. // 构建内容简介参考
  11900. $intro_ref = '';
  11901. if (!empty($intro)) {
  11902. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  11903. }
  11904. // 构建完整的AI提示词
  11905. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  11906. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  11907. $user_prompt .= $intro_ref;
  11908. $user_prompt .= $art_style_ref;
  11909. $user_prompt .= $reference_content;
  11910. $user_prompt .= "\n\n【生成要求】\n- 请以【原分段剧本内容】为蓝本,保留剧情脉络、角色、场景与分段结构,但必须围绕【用户要求】对相关片段进行实质性修改;若【用户要求】未指定具体修改点,也需对画面、运镜、台词等描述进行改写,禁止整段原样复制。\n";
  11911. // $user_prompt .= $roles_ref;
  11912. // $user_prompt .= $scenes_ref;
  11913. // 输出格式铁律(用户消息侧再次强制,避免模型自由发挥)
  11914. $user_prompt .= "\n\n【输出格式铁律-必须严格遵守】\n";
  11915. if ($isActIdMode) {
  11916. $user_prompt .= "- 请直接以“##片段1”开头,紧跟“时长:X s”行,然后输出本片段的完整分镜内容(分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效),分镜从1开始连续编号。\n";
  11917. $user_prompt .= "- 只允许根据【原分段剧本内容】生成一个片段(即“##片段1”),禁止生成多个片段。\n";
  11918. } else {
  11919. $user_prompt .= "- 请以“###分段剧本”开头,依次输出“片段数量:N”、“旁白音色:...”,然后按“##片段N”逐段输出,每段必须紧跟“时长:X s”行,再输出该片段的完整分镜内容(分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效),分镜从1开始连续编号。\n";
  11920. }
  11921. $user_prompt .= "- 缺少“##片段N”标题或“时长:”行即为格式错误;输出前必须检查格式,不得输出其他任何内容。\n";
  11922. $user_prompt .= "- 片段时长必须在4秒到15秒之间(4s≤时长≤15s),超过15秒必须拆分为多个片段,不得输出低于4秒或超过15秒的片段。\n";
  11923. // 整集模式:强制生成与原来一致的片段数量
  11924. if ($episode_id > 0 && isset($segments)) {
  11925. $originSegmentCount = count($segments);
  11926. $user_prompt .= "- 本集原有{$originSegmentCount}个片段,必须严格生成{$originSegmentCount}个片段(##片段1 到 ##片段{$originSegmentCount}),不得多不得少。\n";
  11927. }
  11928. $system_prompt = "\n\n【输出格式铁律-最高优先级】\n";
  11929. if ($isActIdMode) {
  11930. $system_prompt .= "- 直接以“##片段1”开头,紧跟“时长:X s”行,然后输出本片段分镜内容\n";
  11931. $system_prompt .= "- 只允许根据【原分段剧本内容】生成一个片段(即“##片段1”),禁止生成多个片段。\n";
  11932. } else {
  11933. $system_prompt .= "- 以“###分段剧本”开头,输出“片段数量:N”、“旁白音色:...”\n";
  11934. $system_prompt .= "- 然后按“##片段N”逐段输出,每段紧跟“时长:X s”行\n";
  11935. }
  11936. $system_prompt .= "- 每个片段必须严格以“##片段N”开头(N从1开始连续),并且必须包含“时长:X s”行,缺少即为格式错误\n";
  11937. $system_prompt .= "- 片段时长必须在4~15秒之间(4s≤时长≤15s),超过15秒必须拆分为多个片段,禁止输出低于4秒或超过15秒的片段\n";
  11938. $system_prompt .= "- 输出前检查:若缺少##片段N标题或时长行,视为输出无效,必须修正后输出\n\n";
  11939. $system_prompt .= "【强制要求】\n";
  11940. // $system_prompt .= "- 请严格参考【本集原始内容】或【原分段剧本内容】进行本次生成,注意新生成的分段剧本内容一定不要跟【原分段剧本内容】一致,要进行一定程度调整\n";
  11941. $system_prompt .= "- 【重要】必须参考【本集原始内容】与【原分段剧本内容】中的剧情脉络、角色、场景、道具和分段结构,但严禁原样复制或几乎照抄原文;必须围绕【用户要求】对相关内容进行实质性修改,若生成结果与【原分段剧本内容】完全一致或未体现用户要求,视为生成失败\n";
  11942. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:\n";
  11943. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)\n";
  11944. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  11945. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  11946. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  11947. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  11948. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  11949. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  11950. $system_prompt .= "- 【重要】每个片段必须以“##片段N”开头(N为序号),并且必须包含“时长:X s”行,缺少片段标题或时长视为格式错误\n";
  11951. // 按模式构造强制输出格式:只传 act_id(单片段)时不需要 ###分段剧本/片段数量/旁白音色;传 episode_id(整集)时需要完整格式
  11952. $segmentHeader = '';
  11953. if ($episode_id > 0) {
  11954. $segmentHeader = "###分段剧本\n片段数量:8\n旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。\n\n";
  11955. }
  11956. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:\n" . $segmentHeader . "##片段1\n时长:12s\n分镜1\n出场角色:刀疤脸\n场景:边境小镇街道\n出场道具:酒杯-高脚杯\n画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。\n运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。\n配音台词:\n背景音效:\n\n分镜2\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。\n运镜:缓慢横移,掠过阴影中瑟缩的食客。\n配音台词:\n背景音效:\n\n分镜3\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。\n运镜:从中景推向令牌特写。\n配音台词:\n背景音效:\n\n分镜4\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。\n运镜:极速推向酒水溅起的瞬间。\n配音台词:\n背景音效:\n\n分镜5\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。\n运镜:固定机位,利用倾斜构图制造压迫感。\n配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?\n背景音效:";
  11957. // 获取模型配置
  11958. $model = getProp($data, 'model');
  11959. if (!$model) {
  11960. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  11961. }
  11962. // 验证模型是否在可用模型表中
  11963. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  11964. $model = 'deepseek-v4-pro';
  11965. }
  11966. // 模型兼容性处理
  11967. $thinkingMode = 'disabled';
  11968. $reasoningEffort = 'high';
  11969. if ($model === 'deepseek-chat') {
  11970. $model = 'deepseek-v4-flash';
  11971. $thinkingMode = 'disabled';
  11972. } elseif ($model === 'deepseek-reasoner') {
  11973. $model = 'deepseek-v4-flash';
  11974. $thinkingMode = 'enabled';
  11975. }
  11976. // 构建消息
  11977. $messages = [
  11978. [
  11979. 'role' => 'system',
  11980. 'content' => $system_prompt
  11981. ],
  11982. [
  11983. 'role' => 'user',
  11984. 'content' => $user_prompt
  11985. ]
  11986. ];
  11987. // dd($messages);
  11988. // 构建请求参数
  11989. $post_data = [
  11990. 'model' => $model,
  11991. 'messages' => $messages,
  11992. 'temperature' => 1.35,
  11993. 'frequency_penalty' => 0.3,
  11994. 'presence_penalty' => 0,
  11995. 'response_format' => ['type' => 'text'],
  11996. 'thinking' => ['type' => $thinkingMode],
  11997. 'stream' => false // 非流式输出
  11998. ];
  11999. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  12000. // 调用AI生成新的分段剧本
  12001. try {
  12002. $fullContent = '';
  12003. $usage = [];
  12004. // 根据模型类型选择调用方法
  12005. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  12006. // DeepSeek 官方模型使用 DeepSeek API
  12007. $chatResult = $this->chatOnly($post_data);
  12008. } else if (in_array($model, $this->gpt_text_models)) {
  12009. // GPT 模型使用 TokenRouter API
  12010. $chatResult = $this->gpt54ChatOnly($post_data);
  12011. } else {
  12012. // 其他模型使用火山引擎API
  12013. $chatResult = $this->volcEngineChatCompletion($post_data);
  12014. }
  12015. if (is_array($chatResult)) {
  12016. $fullContent = $chatResult['fullContent'] ?? '';
  12017. $usage = $chatResult['usage'] ?? [];
  12018. }
  12019. $generated_content = $fullContent;
  12020. // 归一化"场景:"标签换行格式:场景:\n场景名\n => 场景:场景名\n,保证场景字段为一行
  12021. $generated_content = preg_replace('/场景[::]\s*\n\s*([^\n]+)/u', '场景:$1', $generated_content);
  12022. if (empty($generated_content)) {
  12023. Utils::throwError('20003:AI生成内容为空,请重试');
  12024. }
  12025. dLog('deepseek')->info('regenerateSegmentScript AI生成内容', [
  12026. 'act_id' => $act_id,
  12027. 'episode_id' => $episode_id,
  12028. 'content_length' => mb_strlen($generated_content),
  12029. 'content_head' => mb_substr($generated_content, 0, 500),
  12030. 'content_tail' => mb_substr($generated_content, -200),
  12031. ]);
  12032. // 解析生成的内容 - 按片段分割
  12033. $parsed_segments = [];
  12034. // 先在开头添加换行符,确保第1片段也能被正确分割
  12035. $normalizedText = "\n" . $generated_content;
  12036. $parts = preg_split('/\n\s*##/', $normalizedText);
  12037. foreach ($parts as $part) {
  12038. $part = trim($part);
  12039. if (empty($part)) continue;
  12040. // 匹配"片段X"格式
  12041. if (!preg_match('/^片段\d+/', $part)) {
  12042. continue;
  12043. }
  12044. // 分离标题和内容
  12045. $lines = explode("\n", $part, 2);
  12046. $actTitle = trim($lines[0]);
  12047. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  12048. // 解析标题,提取序号
  12049. $actNumber = 0;
  12050. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  12051. $actNumber = intval($segmentTitleMatch[1]);
  12052. } else {
  12053. $actNumber = count($parsed_segments) + 1;
  12054. }
  12055. // 提取时长(仅保留数字)
  12056. $actDuration = 0;
  12057. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  12058. $actDurationStr = trim($actDurationMatch[1]);
  12059. // 提取数字部分(支持整数和小数)
  12060. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  12061. $actDuration = (float)$numMatch[1];
  12062. }
  12063. }
  12064. // 时长范围约束:4~15秒,超限兜底修正(0=未知按最低4秒)
  12065. if ($actDuration > 15) {
  12066. $actDuration = 15;
  12067. }
  12068. if ($actDuration < 4) {
  12069. $actDuration = 4;
  12070. }
  12071. // 清理act_content:去除时长、旁白音色等非分镜内容行,只保留分镜内容
  12072. $cleaned_content = $this->cleanSegmentContent($actContent);
  12073. $parsed_segments[] = [
  12074. 'act_number' => $actNumber,
  12075. 'act_title' => $actTitle,
  12076. 'act_duration' => $actDuration,
  12077. 'act_content' => $cleaned_content,
  12078. ];
  12079. }
  12080. // 兜底:模型未输出 ##片段N 标题时(如直接输出分镜正文),将整个生成内容作为单个片段解析(act_id 单片段场景)
  12081. if (empty($parsed_segments)) {
  12082. $fallbackContent = $this->cleanSegmentContent($generated_content);
  12083. if ($fallbackContent !== '') {
  12084. $fallbackDuration = 0;
  12085. if (preg_match('/时长[::]\s*([^\n]+)/u', $generated_content, $durationMatch)) {
  12086. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $durationMatch[1], $numMatch)) {
  12087. $fallbackDuration = (float)$numMatch[1];
  12088. }
  12089. }
  12090. // 内容未带时长时,单片段模式沿用原片段的时长
  12091. if ($fallbackDuration <= 0 && $isActIdMode && !empty($segment->act_duration)) {
  12092. $fallbackDuration = (float)$segment->act_duration;
  12093. }
  12094. // 时长范围约束:4~15秒,超限兜底修正(0=未知按最低4秒)
  12095. if ($fallbackDuration > 15) {
  12096. $fallbackDuration = 15;
  12097. }
  12098. if ($fallbackDuration < 4) {
  12099. $fallbackDuration = 4;
  12100. }
  12101. $parsed_segments[] = [
  12102. 'act_number' => 1,
  12103. 'act_title' => '片段1',
  12104. 'act_duration' => $fallbackDuration,
  12105. 'act_content' => $fallbackContent,
  12106. ];
  12107. }
  12108. }
  12109. // act_id 单片段模式:只允许一个片段,多余片段丢弃,仅保留第一个
  12110. if ($isActIdMode && count($parsed_segments) > 1) {
  12111. dLog('deepseek')->info('regenerateSegmentScript act_id 模式仅保留第一个片段', [
  12112. 'act_id' => $act_id,
  12113. 'original_count' => count($parsed_segments),
  12114. ]);
  12115. $parsed_segments = array_slice($parsed_segments, 0, 1);
  12116. }
  12117. dLog('deepseek')->info('regenerateSegmentScript 解析结果', [
  12118. 'act_id' => $act_id,
  12119. 'episode_id' => $episode_id,
  12120. 'segment_count' => count($parsed_segments),
  12121. 'segments' => array_map(function ($seg) {
  12122. return [
  12123. 'act_number' => $seg['act_number'],
  12124. 'act_duration' => $seg['act_duration'],
  12125. 'content_length' => mb_strlen($seg['act_content']),
  12126. ];
  12127. }, $parsed_segments),
  12128. ]);
  12129. if (empty($parsed_segments)) {
  12130. dLog('deepseek')->error('regenerateSegmentScript 无法解析生成的分段剧本', [
  12131. 'act_id' => $act_id,
  12132. 'episode_id' => $episode_id,
  12133. 'content_length' => mb_strlen($generated_content),
  12134. 'content_head' => mb_substr($generated_content, 0, 1000),
  12135. 'content_tail' => mb_substr($generated_content, -300),
  12136. ]);
  12137. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  12138. }
  12139. // 收集所有资产名称(角色、场景、道具)
  12140. $product_names = [];
  12141. // 收集角色名称
  12142. if (!empty($roles) && is_array($roles)) {
  12143. foreach ($roles as $role) {
  12144. $role_name = getProp($role, 'role', '');
  12145. if (!empty($role_name)) {
  12146. $product_names[] = $role_name;
  12147. }
  12148. }
  12149. }
  12150. // 收集场景名称
  12151. if (!empty($scenes) && is_array($scenes)) {
  12152. foreach ($scenes as $scene) {
  12153. $scene_name = getProp($scene, 'scene', '');
  12154. if (!empty($scene_name)) {
  12155. $product_names[] = $scene_name;
  12156. }
  12157. }
  12158. }
  12159. // 收集道具名称
  12160. if (!empty($props) && is_array($props)) {
  12161. foreach ($props as $prop) {
  12162. $prop_name = getProp($prop, 'prop', '');
  12163. if (!empty($prop_name)) {
  12164. $product_names[] = $prop_name;
  12165. }
  12166. }
  12167. }
  12168. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  12169. $product_names = array_unique($product_names);
  12170. usort($product_names, function($a, $b) {
  12171. return mb_strlen($b) - mb_strlen($a);
  12172. });
  12173. // 处理每个片段的 act_show_content
  12174. foreach ($parsed_segments as &$segment) {
  12175. $act_content = getProp($segment, 'act_content', '');
  12176. if (empty($act_content)) {
  12177. $segment['act_show_content'] = '';
  12178. continue;
  12179. }
  12180. $processed_content = $act_content;
  12181. // 统一替换所有资产名称为 {资产名} 格式
  12182. // 使用占位符避免嵌套替换问题
  12183. $placeholder_map = [];
  12184. $placeholder_index = 0;
  12185. foreach ($product_names as $product_name) {
  12186. // 转义特殊字符
  12187. $escaped_product = preg_quote($product_name, '/');
  12188. // 检查是否匹配且未被 {} 包裹
  12189. $processed_content = preg_replace_callback(
  12190. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  12191. function($matches) use (&$placeholder_map, &$placeholder_index) {
  12192. // 使用唯一占位符
  12193. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  12194. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  12195. $placeholder_index++;
  12196. return $placeholder;
  12197. },
  12198. $processed_content
  12199. );
  12200. }
  12201. // 将所有占位符替换回实际内容
  12202. foreach ($placeholder_map as $placeholder => $replacement) {
  12203. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  12204. }
  12205. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  12206. $shot_counter = 0;
  12207. $processed_content = preg_replace_callback(
  12208. // 兼容“【镜头 1】”“【分镜 1】”等分镜/镜头与数字间带空格的情况
  12209. '/【(?:镜头|分镜)\s*(\d+)】/u',
  12210. function($matches) use (&$shot_counter) {
  12211. $shot_counter++;
  12212. return '【镜头' . $shot_counter . '】';
  12213. },
  12214. $processed_content
  12215. );
  12216. $segment['act_show_content'] = $processed_content;
  12217. }
  12218. unset($segment); // 解除引用
  12219. // 保存到数据库
  12220. $now = date('Y-m-d H:i:s');
  12221. $saved_acts = []; // 用于记录保存后的片段信息
  12222. if ($isActIdMode) {
  12223. // 单个片段模式:更新单条记录
  12224. if (count($parsed_segments) > 0) {
  12225. $new_segment = $parsed_segments[0];
  12226. // 预览确认模式(check_mode=1):不落库,组装 editAct 入参返回,由前端确认后调用 editAct 更新
  12227. if ($check_mode === 1) {
  12228. // 单片段预览生成即按 normal 档扣费
  12229. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12230. 'anime_id' => $target_anime_id,
  12231. 'episode_id' => $target_episode_id,
  12232. 'model' => $model,
  12233. 'source' => 'regenerateSegmentScript',
  12234. ], 'normal');
  12235. return [
  12236. 'check_mode' => 1,
  12237. 'act_id' => $act_id,
  12238. 'act_title' => getProp($new_segment, 'act_title', ''),
  12239. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  12240. 'act_content' => getProp($new_segment, 'act_show_content', ''),
  12241. ];
  12242. }
  12243. // 虚拟 act_id 仅用于预览/参考,不允许直接保存到数据库
  12244. if (!is_numeric($act_id)) {
  12245. Utils::throwError('20003:该片段不可直接保存');
  12246. }
  12247. $update_data = [
  12248. 'act_content' => getProp($new_segment, 'act_content', ''),
  12249. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  12250. 'act_title' => getProp($new_segment, 'act_title', ''),
  12251. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  12252. 'updated_at' => $now,
  12253. ];
  12254. DB::table('mp_episode_segments')
  12255. ->where('id', $act_id)
  12256. ->update($update_data);
  12257. // 获取更新后的记录
  12258. $updated_act = DB::table('mp_episode_segments')
  12259. ->where('id', $act_id)
  12260. ->first();
  12261. if ($updated_act) {
  12262. $saved_acts[] = [
  12263. 'act_id' => $updated_act->id,
  12264. 'act_number' => $updated_act->act_number,
  12265. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  12266. 'act_content' => $updated_act->act_content,
  12267. 'act_show_content' => $updated_act->act_show_content,
  12268. 'video_url' => $updated_act->video_url ?? '',
  12269. 'video_duration' => $updated_act->video_duration ?? 0,
  12270. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  12271. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  12272. ];
  12273. }
  12274. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  12275. // 单片段模式成功扣费(normal 档)
  12276. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12277. 'anime_id' => $target_anime_id,
  12278. 'episode_id' => $target_episode_id,
  12279. 'model' => $model,
  12280. 'source' => 'regenerateSegmentScript',
  12281. ], 'normal');
  12282. }
  12283. } else {
  12284. // 预览确认模式(check_mode=1):不落库,返回展示参数供前端确认后调用 saveEpisodeActs 保存
  12285. if ($check_mode === 1) {
  12286. // 剧集模式预览生成即扣除积分并记录 token 明细(special 档)
  12287. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12288. 'anime_id' => $target_anime_id,
  12289. 'episode_id' => $target_episode_id,
  12290. 'model' => $model,
  12291. 'source' => 'regenerateSegmentScript',
  12292. ], 'special');
  12293. // 为每个片段生成虚拟 act_id 并写入 redis(1天有效),供后续按虚拟 act_id 恢复片段数据
  12294. $previewActs = [];
  12295. foreach ($parsed_segments as $seg) {
  12296. $virtualActId = 'preview_' . time() . '_' . uniqid();
  12297. Redis::setex($this->buildActPreviewKey($virtualActId), 86400, json_encode([
  12298. 'anime_id' => $target_anime_id,
  12299. 'episode_id' => $target_episode_id,
  12300. 'episode_number' => $target_episode_number,
  12301. 'act_number' => $seg['act_number'],
  12302. 'act_title' => $seg['act_title'],
  12303. 'act_duration' => $seg['act_duration'],
  12304. 'act_content' => $seg['act_content'],
  12305. 'act_show_content'=> $seg['act_show_content'],
  12306. ], JSON_UNESCAPED_UNICODE));
  12307. $previewActs[] = [
  12308. 'act_id' => $virtualActId,
  12309. 'act_number' => $seg['act_number'],
  12310. 'act_title' => $seg['act_title'],
  12311. 'act_duration' => $seg['act_duration'],
  12312. 'act_content' => $seg['act_content'],
  12313. 'act_show_content' => $seg['act_show_content'],
  12314. 'video_url' => '',
  12315. 'video_duration' => 0,
  12316. 'video_time_point_start' => 0,
  12317. 'video_time_point_end' => 0,
  12318. 'last_frame_url' => '',
  12319. 'current_type' => 0,
  12320. ];
  12321. }
  12322. return [
  12323. 'check_mode' => 1,
  12324. 'anime_id' => $target_anime_id,
  12325. 'episode_id' => $target_episode_id,
  12326. 'title' => getProp($episode, 'title', ''),
  12327. 'episode_number' => $target_episode_number,
  12328. 'is_generated' => getProp($episode, 'is_generated', 0),
  12329. 'acts' => $previewActs,
  12330. ];
  12331. }
  12332. // 整个剧集模式:删除原有记录并批量保存新记录
  12333. DB::beginTransaction();
  12334. try {
  12335. // 删除原有的所有片段记录
  12336. DB::table('mp_episode_segments')
  12337. ->where('episode_id', $target_episode_id)
  12338. ->delete();
  12339. // 批量插入新的片段记录
  12340. $segments_to_insert = [];
  12341. foreach ($parsed_segments as $index => $segment) {
  12342. $act_number = $index + 1;
  12343. $segments_to_insert[] = [
  12344. 'anime_id' => $target_anime_id,
  12345. 'episode_id' => $target_episode_id,
  12346. 'episode_number' => $target_episode_number,
  12347. 'act_number' => $act_number,
  12348. 'act_title' => getProp($segment, 'act_title', ''),
  12349. 'act_duration' => getProp($segment, 'act_duration', 0),
  12350. 'act_content' => getProp($segment, 'act_content', ''),
  12351. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  12352. 'created_at' => $now,
  12353. 'updated_at' => $now,
  12354. ];
  12355. }
  12356. if (!empty($segments_to_insert)) {
  12357. DB::table('mp_episode_segments')->insert($segments_to_insert);
  12358. }
  12359. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(special 档,与保存同事务)
  12360. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12361. 'anime_id' => $target_anime_id,
  12362. 'episode_id' => $target_episode_id,
  12363. 'model' => $model,
  12364. 'source' => 'regenerateSegmentScript',
  12365. ], 'special');
  12366. DB::commit();
  12367. // 查询保存后的所有片段记录
  12368. $saved_segments = DB::table('mp_episode_segments')
  12369. ->where('episode_id', $target_episode_id)
  12370. ->orderBy('act_number')
  12371. ->get();
  12372. foreach ($saved_segments as $saved_segment) {
  12373. $saved_acts[] = [
  12374. 'act_id' => $saved_segment->id,
  12375. 'act_number' => $saved_segment->act_number,
  12376. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  12377. 'act_content' => $saved_segment->act_content,
  12378. 'act_show_content' => $saved_segment->act_show_content,
  12379. 'video_url' => $saved_segment->video_url ?? '',
  12380. 'video_duration' => $saved_segment->video_duration ?? 0,
  12381. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  12382. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  12383. ];
  12384. }
  12385. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  12386. 'episode_id' => $target_episode_id,
  12387. 'segments_count' => count($segments_to_insert)
  12388. ]);
  12389. } catch (\Exception $e) {
  12390. DB::rollBack();
  12391. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  12392. Utils::throwError('20003:保存失败,请重试');
  12393. }
  12394. }
  12395. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  12396. return [
  12397. 'anime_id' => $target_anime_id,
  12398. 'episode_id' => $target_episode_id,
  12399. 'title' => getProp($episode, 'title', ''),
  12400. 'episode_number' => $target_episode_number,
  12401. 'is_generated' => getProp($episode, 'is_generated', 0),
  12402. 'acts' => $saved_acts,
  12403. ];
  12404. } catch (\Exception $e) {
  12405. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  12406. throw $e;
  12407. }
  12408. }
  12409. /**
  12410. * 保存剧集片段(预览确认模式使用):删除旧数据并批量保存新数据到 mp_episode_segments
  12411. *
  12412. * 逻辑与 regenerateSegmentScript 的 episode_id + check_mode=0 保存保持一致。
  12413. *
  12414. * @param array $data 请求参数:episode_id 必填,acts 必填(预览返回的片段数组)
  12415. * @return array
  12416. */
  12417. public function saveEpisodeActs($data) {
  12418. $uid = Site::getUid();
  12419. $episode_id = (int)getProp($data, 'episode_id', 0);
  12420. $acts = getProp($data, 'acts', []);
  12421. if (!$episode_id) {
  12422. Utils::throwError('20003:请提供剧集ID');
  12423. }
  12424. if (!is_array($acts) || empty($acts)) {
  12425. Utils::throwError('20003:请提供片段数据');
  12426. }
  12427. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  12428. if (!$episode) {
  12429. Utils::throwError('20003:剧集不存在');
  12430. }
  12431. // 用户校验:只能调整自己的剧集
  12432. $anime = DB::table('mp_animes')->where('id', $episode->anime_id)->first();
  12433. if (!$anime || (int)$anime->user_id !== (int)$uid) {
  12434. Utils::throwError('20003:没有权限操作该剧集');
  12435. }
  12436. $anime_id = (int)$episode->anime_id;
  12437. $episode_number = (int)$episode->episode_number;
  12438. $now = date('Y-m-d H:i:s');
  12439. try {
  12440. DB::beginTransaction();
  12441. // 删除原有的所有片段记录
  12442. DB::table('mp_episode_segments')
  12443. ->where('episode_id', $episode_id)
  12444. ->delete();
  12445. // 批量插入新的片段记录
  12446. $segments_to_insert = [];
  12447. $index = 0;
  12448. foreach ($acts as $act) {
  12449. if (!is_array($act)) {
  12450. continue;
  12451. }
  12452. $index++;
  12453. $segments_to_insert[] = [
  12454. 'anime_id' => $anime_id,
  12455. 'episode_id' => $episode_id,
  12456. 'episode_number' => $episode_number,
  12457. 'act_number' => (int)getProp($act, 'act_number', $index),
  12458. 'act_title' => (string)getProp($act, 'act_title', ''),
  12459. 'act_duration' => (float)getProp($act, 'act_duration', 0),
  12460. 'act_content' => (string)getProp($act, 'act_content', ''),
  12461. // 'act_show_content' => (string)getProp($act, 'act_show_content', ''),
  12462. 'created_at' => $now,
  12463. 'updated_at' => $now,
  12464. ];
  12465. }
  12466. if (empty($segments_to_insert)) {
  12467. DB::rollBack();
  12468. Utils::throwError('20003:没有有效的片段数据');
  12469. }
  12470. DB::table('mp_episode_segments')->insert($segments_to_insert);
  12471. DB::commit();
  12472. } catch (\Exception $e) {
  12473. DB::rollBack();
  12474. dLog('deepseek')->error('保存剧集片段失败: ' . $e->getMessage(), [
  12475. 'episode_id' => $episode_id,
  12476. ]);
  12477. Utils::throwError('20003:保存失败,请重试');
  12478. }
  12479. // 查询保存后的所有片段记录(数组化,与 episodeInfoForAce 处理一致)
  12480. $saved_segments = DB::table('mp_episode_segments')
  12481. ->where('episode_id', $episode_id)
  12482. ->orderBy('act_number')
  12483. ->get()
  12484. ->map(function ($value) {
  12485. return (array)$value;
  12486. })
  12487. ->toArray();
  12488. // 构造与 episodeInfoForAce 一致的 acts 与 total_duration
  12489. $acts = [];
  12490. $totalDuration = 0;
  12491. foreach ($saved_segments as $segment) {
  12492. $videoDuration = getProp($segment, 'video_duration');
  12493. $actDuration = getProp($segment, 'act_duration');
  12494. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  12495. $totalDuration += floatval($videoDuration);
  12496. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  12497. $totalDuration += floatval($actDuration);
  12498. } else {
  12499. $totalDuration += 5;
  12500. }
  12501. $acts[] = [
  12502. 'act_id' => getProp($segment, 'id'),
  12503. 'act_number' => getProp($segment, 'act_number'),
  12504. 'act_title' => getProp($segment, 'act_title'),
  12505. 'act_duration' => getProp($segment, 'act_duration'),
  12506. 'act_content' => getProp($segment, 'act_content'),
  12507. 'video_url' => getProp($segment, 'video_url'),
  12508. 'video_duration' => getProp($segment, 'video_duration', 0),
  12509. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  12510. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  12511. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  12512. 'current_type' => getProp($segment, 'current_type'),
  12513. ];
  12514. }
  12515. // 顶层与 episodeInfoForAce 一致
  12516. $result = [
  12517. 'episode_id' => $episode_id,
  12518. 'anime_id' => $anime_id,
  12519. 'episode_number' => $episode_number,
  12520. 'title' => getProp($episode, 'title'),
  12521. 'intro' => getProp($episode, 'intro'),
  12522. 'art_style' => getProp($episode, 'art_style'),
  12523. 'roles' => json_decode(getProp($episode, 'roles', '[]'), true),
  12524. 'scenes' => json_decode(getProp($episode, 'scenes', '[]'), true),
  12525. 'props' => getProp($episode, 'props') ? json_decode(getProp($episode, 'props'), true) : [],
  12526. 'is_generated' => getProp($episode, 'is_generated'),
  12527. 'acts' => array_values($acts),
  12528. 'total_duration' => intval(round($totalDuration)),
  12529. ];
  12530. // video_params(从 mp_animes 取,与 episodeInfoForAce 一致)
  12531. $animeRow = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  12532. $result['video_params'] = [
  12533. 'video_model' => getProp($animeRow, 'video_model'),
  12534. 'video_resolution' => getProp($animeRow, 'video_resolution'),
  12535. 'ratio' => getProp($animeRow, 'video_ratio'),
  12536. ];
  12537. return $result;
  12538. }
  12539. /**
  12540. * 预览虚拟 act_id 在 redis 中的键
  12541. *
  12542. * @param mixed $actId
  12543. * @return string
  12544. */
  12545. private function buildActPreviewKey($actId): string
  12546. {
  12547. return 'anime_act_preview:' . $actId;
  12548. }
  12549. /**
  12550. * 清理分镜内容:去除时长、旁白音色等非分镜行,只保留完整分镜内容(分镜标记统一为【分镜N】/【镜头N】)
  12551. *
  12552. * @param string $actContent
  12553. * @return string
  12554. */
  12555. private function cleanSegmentContent(string $actContent): string
  12556. {
  12557. $cleaned_content = '';
  12558. $content_lines = explode("\n", $actContent);
  12559. $is_capturing = false; // 标记是否开始捕获分镜内容
  12560. $count = 0;
  12561. foreach ($content_lines as $line) {
  12562. $trimmed_line = trim($line);
  12563. // 跳过时长、旁白音色等非分镜行
  12564. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  12565. continue;
  12566. }
  12567. // 检测分镜开始(支持【分镜X】【镜头X】、分镜X、镜头X,以及分镜/镜头与数字间带空格的情况)
  12568. if (preg_match('/^(?:【)?(分镜|镜头)\s*(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  12569. $count++;
  12570. $is_capturing = true;
  12571. // 统一归一化为【分镜N】/【镜头N】(兼容“镜头 1”“【镜头 1】”等写法)
  12572. $trimmed_line = preg_replace('/^(?:【)?(分镜|镜头)\s*(\d+)(?:】)?/u', '【$1$2】', $trimmed_line);
  12573. if ($count > 1) {
  12574. $trimmed_line = "\n" . $trimmed_line;
  12575. }
  12576. }
  12577. if ($is_capturing && !empty($trimmed_line)) {
  12578. $cleaned_content .= $trimmed_line . "\n";
  12579. }
  12580. }
  12581. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  12582. return $cleaned_content;
  12583. }
  12584. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  12585. {
  12586. $episode_arr = [
  12587. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  12588. 'intro' => getProp($script_arr, 'intro'),
  12589. 'art_style' => getProp($script_arr, 'art_style'),
  12590. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  12591. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  12592. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  12593. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  12594. ];
  12595. if (empty($episode_arr['acts'])) {
  12596. $fallback_episode_arr = handleEpisodeContent($fullContent);
  12597. if (!empty($fallback_episode_arr['acts'])) {
  12598. $episode_arr = array_merge($fallback_episode_arr, [
  12599. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  12600. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  12601. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  12602. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  12603. ]);
  12604. }
  12605. }
  12606. // if (!getProp($episode_arr, 'episode_title')) {
  12607. // $episode_title = '';
  12608. // $episodes = getProp($script_arr, 'episodes', []);
  12609. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  12610. // $episode_title = '第1集:' . $episodes[0]['title'];
  12611. // }
  12612. // if (!$episode_title) {
  12613. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  12614. // }
  12615. // $episode_arr['episode_title'] = $episode_title;
  12616. // }
  12617. return $episode_arr;
  12618. }
  12619. private function saveEpisodeVersionData(
  12620. int $anime_id,
  12621. int $episode_number,
  12622. array $episode_arr,
  12623. array $existing_roles,
  12624. array $existing_scenes,
  12625. array $existing_props,
  12626. $current_episode,
  12627. $base_episode,
  12628. bool $is_regenerate_version,
  12629. string $content,
  12630. string $now,
  12631. array $ref_products = []
  12632. ): array {
  12633. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  12634. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  12635. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  12636. // 过滤掉关键字段为空的条目
  12637. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  12638. return !empty($item['role'] ?? null);
  12639. }));
  12640. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  12641. return !empty($item['scene'] ?? null);
  12642. }));
  12643. $merged_props = array_values(array_filter($generated_props, function ($item) {
  12644. return !empty($item['prop'] ?? null);
  12645. }));
  12646. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  12647. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  12648. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  12649. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  12650. $ace_mode = getProp($anime, 'ace_mode');
  12651. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  12652. $global_roles = json_decode(getProp($anime, 'roles'), true);
  12653. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  12654. $global_roles = is_array($global_roles) ? $global_roles : [];
  12655. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  12656. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  12657. $art_style_type = getProp($anime, 'art_style_type');
  12658. // 检查并创建 roles 的图片生成任务
  12659. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  12660. // 检查并创建 scenes 的图片生成任务
  12661. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  12662. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  12663. if ($arr && is_array($arr)) {
  12664. $merged_roles = $arr['roles'];
  12665. $merged_scenes = $arr['scenes'];
  12666. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  12667. }
  12668. // 确保数据是数组类型
  12669. if (!is_array($merged_roles)) {
  12670. dLog('deepseek')->error('merged_roles不是数组类型', [
  12671. 'type' => gettype($merged_roles),
  12672. 'value' => $merged_roles
  12673. ]);
  12674. $merged_roles = [];
  12675. }
  12676. if (!is_array($merged_scenes)) {
  12677. dLog('deepseek')->error('merged_scenes不是数组类型', [
  12678. 'type' => gettype($merged_scenes),
  12679. 'value' => $merged_scenes
  12680. ]);
  12681. $merged_scenes = [];
  12682. }
  12683. if (!is_array($merged_props)) {
  12684. dLog('deepseek')->error('merged_props不是数组类型', [
  12685. 'type' => gettype($merged_props),
  12686. 'value' => $merged_props
  12687. ]);
  12688. $merged_props = [];
  12689. }
  12690. // 同步新出现的主体和场景到全局
  12691. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  12692. $role_arr = [];
  12693. foreach ($merged_roles as $item) {
  12694. $role_arr[$item['role']] = $item;
  12695. }
  12696. $version_count = DB::table('mp_anime_episodes')
  12697. ->where('anime_id', $anime_id)
  12698. ->where('episode_number', $episode_number)
  12699. ->count('id');
  12700. $episode = [
  12701. 'anime_id' => $anime_id,
  12702. 'episode_number' => $episode_number,
  12703. 'title' => getProp($episode_arr, 'episode_title'),
  12704. 'content' => $content,
  12705. 'intro' => getProp($episode_arr, 'intro'),
  12706. 'art_style' => getProp($episode_arr, 'art_style'),
  12707. 'roles' => json_encode($merged_roles, 256),
  12708. 'scenes' => json_encode($merged_scenes, 256),
  12709. 'props' => json_encode($merged_props, 256),
  12710. 'generate_status' => '待执行',
  12711. 'generate_at' => $now,
  12712. 'is_default' => 1,
  12713. 'updated_at' => $now,
  12714. ];
  12715. $del_flag = false;
  12716. if ($is_regenerate_version) {
  12717. DB::table('mp_anime_episodes')
  12718. ->where('anime_id', $anime_id)
  12719. ->where('episode_number', $episode_number)
  12720. ->update(['is_default' => 0, 'updated_at' => $now]);
  12721. $episode['sequence'] = $version_count + 1;
  12722. $episode['created_at'] = $now;
  12723. $episode['cpid'] = Site::getCpid();
  12724. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  12725. if (!$episode_id) {
  12726. Utils::throwError('20003:创建剧集版本失败');
  12727. }
  12728. } else {
  12729. $target_episode = $current_episode ?: $base_episode;
  12730. if ($target_episode) {
  12731. $episode_id = getProp($target_episode, 'id');
  12732. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  12733. DB::table('mp_anime_episodes')
  12734. ->where('anime_id', $anime_id)
  12735. ->where('episode_number', $episode_number)
  12736. ->where('id', '<>', $episode_id)
  12737. ->update(['is_default' => 0, 'updated_at' => $now]);
  12738. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  12739. if ($boolen === false) {
  12740. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  12741. Utils::throwError('20003:分集内容保存失败');
  12742. }
  12743. $del_flag = true;
  12744. } else {
  12745. DB::table('mp_anime_episodes')
  12746. ->where('anime_id', $anime_id)
  12747. ->where('episode_number', $episode_number)
  12748. ->update(['is_default' => 0, 'updated_at' => $now]);
  12749. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  12750. $episode['created_at'] = $now;
  12751. $episode['cpid'] = Site::getCpid();
  12752. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  12753. if (!$episode_id) {
  12754. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  12755. Utils::throwError('20003:分集内容保存失败');
  12756. }
  12757. }
  12758. }
  12759. $segments = [];
  12760. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  12761. // 如果是第2集及以后,获取上一集的主体音色数据
  12762. $previous_roles_voice = [];
  12763. if ($episode_number >= 2) {
  12764. $previous_episode = DB::table('mp_anime_episodes')
  12765. ->where('anime_id', $anime_id)
  12766. ->where('episode_number', $episode_number - 1)
  12767. ->where('is_default', 1)
  12768. ->first();
  12769. if ($previous_episode) {
  12770. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  12771. if (is_array($previous_roles)) {
  12772. foreach ($previous_roles as $prev_role) {
  12773. $role_name = getProp($prev_role, 'role');
  12774. if ($role_name) {
  12775. $previous_roles_voice[$role_name] = [
  12776. 'voice_name' => getProp($prev_role, 'voice_name'),
  12777. 'voice_type' => getProp($prev_role, 'voice_type'),
  12778. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  12779. ];
  12780. $voice_prompt = getProp($prev_role, 'voice_prompt');
  12781. if ($voice_prompt) {
  12782. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  12783. }
  12784. }
  12785. }
  12786. }
  12787. }
  12788. }
  12789. // 将继承的音色数据同步到当前集的主体列表
  12790. if (!empty($previous_roles_voice)) {
  12791. foreach ($merged_roles as &$role) {
  12792. $role_name = getProp($role, 'role');
  12793. if ($role_name && isset($previous_roles_voice[$role_name])) {
  12794. // 强制继承上一集的音色数据
  12795. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  12796. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  12797. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  12798. // 如果上一集有 voice_prompt 则继承,否则跳过
  12799. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  12800. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  12801. }
  12802. }
  12803. }
  12804. unset($role); // 解除引用
  12805. // 更新 role_arr 以便后续使用
  12806. $role_arr = [];
  12807. foreach ($merged_roles as $item) {
  12808. $role_arr[$item['role']] = $item;
  12809. }
  12810. }
  12811. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  12812. $emotion_list = array_flip($emotion_list);
  12813. foreach ($acts as $act) {
  12814. $act_segments = getProp($act, 'segments', []);
  12815. if (!is_array($act_segments)) {
  12816. continue;
  12817. }
  12818. if ((int)$ace_mode === 1) {
  12819. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  12820. $merged_parts = [];
  12821. foreach ($act_segments as $seg) {
  12822. $seg_num = getProp($seg, 'segment_number');
  12823. $seg_content = getProp($seg, 'segment_content');
  12824. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  12825. }
  12826. $act_content = implode("\n", $merged_parts);
  12827. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  12828. $segments[] = [
  12829. 'anime_id' => $anime_id,
  12830. 'episode_id' => $episode_id,
  12831. 'episode_number' => $episode_number,
  12832. 'act_number' => getProp($act, 'act_number'),
  12833. 'act_title' => getProp($act, 'act_title'),
  12834. 'act_duration' => getProp($act, 'act_duration'),
  12835. 'act_content' => $act_content,
  12836. 'created_at' => $now,
  12837. 'updated_at' => $now
  12838. ];
  12839. } else {
  12840. foreach ($act_segments as $segment) {
  12841. $voice_actor = getProp($segment, 'voice_actor');
  12842. // 优先从上一集继承音色数据
  12843. $timbre_info = [];
  12844. if (isset($previous_roles_voice[$voice_actor])) {
  12845. // 从上一集继承音色数据
  12846. $timbre_info = $previous_roles_voice[$voice_actor];
  12847. } elseif (isset($role_arr[$voice_actor])) {
  12848. // 使用当前集的主体音色数据
  12849. $timbre_info = $role_arr[$voice_actor];
  12850. }
  12851. $voice_type = getProp($timbre_info, 'voice_type');
  12852. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  12853. if ($timbre_emotion) {
  12854. $timbre_emotion = explode(',', $timbre_emotion);
  12855. } else {
  12856. $timbre_emotion = [];
  12857. }
  12858. $emotion = getProp($segment, 'emotion', '中性');
  12859. if (!in_array($emotion, $timbre_emotion)) {
  12860. $emotion = '中性';
  12861. }
  12862. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  12863. $segments[] = [
  12864. 'anime_id' => $anime_id,
  12865. 'episode_id' => $episode_id,
  12866. 'episode_number' => $episode_number,
  12867. 'act_number' => getProp($act, 'act_number'),
  12868. 'act_title' => getProp($act, 'act_title'),
  12869. 'act_duration' => getProp($act, 'act_duration'),
  12870. 'segment_id' => getProp($segment, 'segment_id'),
  12871. 'segment_number' => getProp($segment, 'segment_number'),
  12872. 'segment_content' => getProp($segment, 'segment_content'),
  12873. 'description' => getProp($segment, 'description'),
  12874. 'composition' => getProp($segment, 'composition'),
  12875. 'camera_movement' => getProp($segment, 'camera_movement'),
  12876. 'voice_actor' => $voice_actor,
  12877. 'dialogue' => getProp($segment, 'dialogue'),
  12878. 'frame_type' => getProp($segment, 'frame_type'),
  12879. 'scene' => getProp($segment, 'scene'),
  12880. 'characters' => getProp($segment, 'characters'),
  12881. 'tail_frame' => getProp($segment, 'tail_frame'),
  12882. 'voice_name' => getProp($timbre_info, 'voice_name'),
  12883. 'voice_type' => $voice_type,
  12884. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  12885. 'emotion' => $emotion,
  12886. 'emotion_type' => $emotion_type,
  12887. 'gender' => getProp($segment, 'gender', '0'),
  12888. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  12889. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  12890. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  12891. 'pitch' => getProp($segment, 'pitch', 0),
  12892. 'created_at' => $now,
  12893. 'updated_at' => $now
  12894. ];
  12895. }
  12896. }
  12897. }
  12898. if ($segments) {
  12899. if ($del_flag) {
  12900. DB::table('mp_episode_segments')
  12901. ->where('anime_id', $anime_id)
  12902. ->where('episode_id', $episode_id)
  12903. ->delete();
  12904. }
  12905. $boolen = DB::table('mp_episode_segments')->insert($segments);
  12906. if (!$boolen) {
  12907. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  12908. Utils::throwError('20003:分镜内容保存失败');
  12909. }
  12910. }
  12911. dLog('deepseek')->info('segments', $segments);
  12912. // ace_mode=1: acts 返回值按合并格式调整
  12913. if ((int)$ace_mode === 1) {
  12914. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  12915. $act_map = [];
  12916. foreach ($table_act_data as $item) {
  12917. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  12918. }
  12919. $restructured_acts = [];
  12920. foreach ($acts as $act) {
  12921. $act_segments = getProp($act, 'segments', []);
  12922. if (!is_array($act_segments)) {
  12923. continue;
  12924. }
  12925. $merged_parts = [];
  12926. foreach ($act_segments as $seg) {
  12927. $seg_num = getProp($seg, 'segment_number');
  12928. $seg_content = getProp($seg, 'segment_content');
  12929. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  12930. }
  12931. $act_content = implode("\n", $merged_parts);
  12932. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  12933. $restructured_acts[] = [
  12934. 'anime_id' => $anime_id,
  12935. 'episode_id' => $episode_id,
  12936. 'episode_number' => $episode_number,
  12937. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  12938. 'act_number' => getProp($act, 'act_number'),
  12939. 'act_title' => getProp($act, 'act_title'),
  12940. 'act_duration' => getProp($act, 'act_duration'),
  12941. 'act_content' => $act_content,
  12942. 'created_at' => $now,
  12943. 'updated_at' => $now,
  12944. ];
  12945. }
  12946. $acts = $restructured_acts;
  12947. }
  12948. $episode['episode_id'] = $episode_id;
  12949. $episode['roles'] = $merged_roles;
  12950. $episode['scenes'] = $merged_scenes;
  12951. $episode['props'] = $merged_props;
  12952. $episode['acts'] = $acts;
  12953. return [
  12954. 'episode' => $episode,
  12955. 'episode_id' => $episode_id,
  12956. 'merged_roles' => $merged_roles,
  12957. 'merged_scenes' => $merged_scenes,
  12958. 'merged_props' => $merged_props,
  12959. ];
  12960. }
  12961. private function buildEpisodeItemContent(array $items, string $nameKey): string
  12962. {
  12963. $content = '';
  12964. foreach ($items as $item) {
  12965. $name = trim((string)getProp($item, $nameKey));
  12966. if ($name === '' || $name === '旁白') {
  12967. continue;
  12968. }
  12969. $description = trim((string)getProp($item, 'description'));
  12970. $content .= $name . ': ' . $description;
  12971. if ($nameKey == 'role') {
  12972. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  12973. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  12974. $voice_name = trim(getProp($item, 'voice_name'));
  12975. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  12976. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  12977. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  12978. }else {
  12979. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  12980. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  12981. }
  12982. $content .= "\n";
  12983. }
  12984. return trim($content);
  12985. }
  12986. private function getEpisodeChatContent($animeId, $sequence, $content) {
  12987. if ((int)$sequence <= 0) {
  12988. return [];
  12989. }
  12990. $origin_content = '';
  12991. if ($content) {
  12992. $origin_content = '本集剧情内容:'.$content;
  12993. }else {
  12994. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  12995. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  12996. }
  12997. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  12998. // 获取分集信息
  12999. $episode = DB::table('mp_anime_episodes')
  13000. ->where('anime_id', $animeId)
  13001. ->where('episode_number', $sequence)
  13002. ->where('is_default', 1)
  13003. ->first();
  13004. if (!$episode) {
  13005. return [];
  13006. }
  13007. $episode_id = getProp($episode, 'id');
  13008. $episode_number = getProp($episode, 'episode_number');
  13009. $title = getProp($episode, 'title');
  13010. $intro = getProp($episode, 'intro');
  13011. $art_style = getProp($episode, 'art_style');
  13012. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  13013. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  13014. // 组装纯文本内容
  13015. $content = '';
  13016. // 添加分集标题和梗概
  13017. $content .= "###第{$episode_number}集:{$title}\n\n";
  13018. $content .= "###故事梗概\n";
  13019. $content .= trim($intro) . "\n\n";
  13020. // 添加美术风格
  13021. $content .= "###美术风格\n";
  13022. $content .= trim($art_style) . "\n\n";
  13023. // 添加主体列表
  13024. $content .= "###主体列表\n";
  13025. $pangbai_voice_prompt = "";
  13026. foreach ($roles as $role) {
  13027. $name = getProp($role, 'role');
  13028. $description = getProp($role, 'description');
  13029. $pic_prompt = getProp($role, 'pic_prompt');
  13030. $voice_prompt = getProp($role, 'voice_prompt');
  13031. $voice_name = getProp($role, 'voice_name');
  13032. $content .= "{$name}: {$description}";
  13033. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13034. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  13035. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  13036. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  13037. $content .= "\n";
  13038. }
  13039. $content .= "\n";
  13040. // 添加场景列表
  13041. $content .= "###场景列表\n";
  13042. foreach ($scenes as $scene) {
  13043. $name = getProp($scene, 'scene');
  13044. $description = getProp($scene, 'description');
  13045. $pic_prompt = getProp($scene, 'pic_prompt');
  13046. $content .= "{$name}: {$description}";
  13047. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13048. $content .= "\n";
  13049. }
  13050. $content .= "\n";
  13051. // 获取分镜信息
  13052. $segments = DB::table('mp_episode_segments')
  13053. ->where('anime_id', $animeId)
  13054. ->where('episode_id', $episode_id)
  13055. ->orderBy('segment_number')
  13056. ->get();
  13057. if ($segments && count($segments) > 0) {
  13058. if ((int)$ace_mode === 1) {
  13059. $content .= "###分段剧本\n";
  13060. // 获取片段数量
  13061. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  13062. $content .= "片段数量:{$act_count}\n";
  13063. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  13064. $content .= "\n";
  13065. }else {
  13066. $content .= "###分镜剧本\n";
  13067. }
  13068. // 按幕分组
  13069. $currentAct = null;
  13070. foreach ($segments as $segment) {
  13071. $act_number = getProp($segment, 'act_number');
  13072. $act_title = getProp($segment, 'act_title');
  13073. $act_duration = getProp($segment, 'act_duration');
  13074. $segment_number = getProp($segment, 'segment_number');
  13075. $segment_content = getProp($segment, 'segment_content');
  13076. $scene_description = getProp($segment, 'scene_description');
  13077. $scene_name = getProp($segment, 'scene_name');
  13078. $composition = getProp($segment, 'composition');
  13079. $camera_movement = getProp($segment, 'camera_movement');
  13080. $voice_type = getProp($segment, 'voice_type');
  13081. $characters = getProp($segment, 'characters');
  13082. $dialogue = getProp($segment, 'dialogue');
  13083. $frame_type = getProp($segment, 'frame_type');
  13084. $tail_frame_description = getProp($segment, 'tail_frame_description');
  13085. // 判断是否是全能模式
  13086. if ((int)$ace_mode === 1) { // 全能模式
  13087. // 如果是新的分段,添加分段标题
  13088. if ($act_number !== $currentAct) {
  13089. $currentAct = $act_number;
  13090. $content .= "##{$act_title}\n";
  13091. $content .= "时长:{$act_duration}s\n";
  13092. }
  13093. }else {
  13094. // 如果是新的幕,添加幕标题
  13095. if ($act_number !== $currentAct) {
  13096. $currentAct = $act_number;
  13097. $content .= "##第{$act_number}幕:{$scene_name}\n";
  13098. }
  13099. }
  13100. // 添加分镜信息
  13101. $content .= "分镜{$segment_number}\n";
  13102. $content .= "分镜内容:\n{$segment_content}\n";
  13103. // $content .= "画面描述:{$scene_description}\n";
  13104. // $content .= "场景:{$scene_name}\n";
  13105. // $content .= "构图设计:{$composition}\n";
  13106. // $content .= "运镜调度:{$camera_movement}\n";
  13107. // if (!empty($voice_type)) {
  13108. // $content .= "配音角色:{$voice_type}\n";
  13109. // }
  13110. // if (!empty($characters)) {
  13111. // $content .= "出镜角色:{$characters}\n";
  13112. // }
  13113. // if (!empty($dialogue)) {
  13114. // $content .= "台词内容:\"{$dialogue}\"\n";
  13115. // }
  13116. // $content .= "画面类型:{$frame_type}\n";
  13117. // $content .= "尾帧描述:{$tail_frame_description}\n";
  13118. $content .= "\n";
  13119. }
  13120. }
  13121. $content = trim($content);
  13122. if($content) $content = "上集剧本内容:\n{$content}";
  13123. return [
  13124. [
  13125. 'role' => 'user',
  13126. 'content' => $origin_content
  13127. ],
  13128. [
  13129. 'role' => 'assistant',
  13130. 'content' => $content
  13131. ]
  13132. ];
  13133. }
  13134. private function getEpisodeChatMessages($animeId, $sequence): array
  13135. {
  13136. if ((int)$sequence <= 0) {
  13137. return [];
  13138. }
  13139. return DB::table('mp_anime_records')
  13140. ->where('anime_id', $animeId)
  13141. ->where('sequence', $sequence)
  13142. ->where('episode_id', '>', 0)
  13143. ->select('role', 'content')
  13144. ->orderBy('created_at')
  13145. ->orderBy('id')
  13146. ->get()
  13147. ->map(function ($value) {
  13148. return (array)$value;
  13149. })
  13150. ->toArray();
  13151. }
  13152. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  13153. {
  13154. $existingMap = [];
  13155. foreach ($existingItems as $item) {
  13156. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13157. if ($itemKey === '') {
  13158. continue;
  13159. }
  13160. $existingMap[$itemKey] = $item;
  13161. }
  13162. if (!$generatedItems) {
  13163. return array_values($existingItems);
  13164. }
  13165. $merged = [];
  13166. foreach ($generatedItems as $item) {
  13167. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13168. if ($itemKey === '') {
  13169. continue;
  13170. }
  13171. if (isset($existingMap[$itemKey])) {
  13172. if (trim((string)getProp($item, 'description')) === '') {
  13173. $merged[] = $existingMap[$itemKey];
  13174. continue;
  13175. }
  13176. // 检查内容是否发生变化
  13177. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  13178. if (!$isChanged) {
  13179. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  13180. $mergedItem = [
  13181. $nameKey => trim((string)getProp($item, $nameKey)),
  13182. 'description' => trim((string)getProp($item, 'description')),
  13183. ];
  13184. // 如果有 pic_prompt,添加到合并项中
  13185. $picPrompt = getProp($item, 'pic_prompt');
  13186. if (!empty($picPrompt)) {
  13187. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  13188. }
  13189. // 继承现有项的 URL
  13190. $existingUrl = getProp($existingMap[$itemKey], 'url');
  13191. if (!empty($existingUrl)) {
  13192. $mergedItem['url'] = $existingUrl;
  13193. }
  13194. // 继承现有项的 task_id
  13195. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  13196. if (!empty($existingTaskId)) {
  13197. $mergedItem['task_id'] = $existingTaskId;
  13198. }
  13199. // 继承现有项的 task_status
  13200. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  13201. if (!empty($existingTaskStatus)) {
  13202. $mergedItem['task_status'] = $existingTaskStatus;
  13203. }
  13204. // 保留生成项的音色字段
  13205. $voiceName = getProp($item, 'voice_name');
  13206. if (!empty($voiceName)) {
  13207. $mergedItem['voice_name'] = $voiceName;
  13208. }
  13209. $voiceType = getProp($item, 'voice_type');
  13210. if (!empty($voiceType)) {
  13211. $mergedItem['voice_type'] = $voiceType;
  13212. }
  13213. $audioUrl = getProp($item, 'voice_audio_url');
  13214. if (!empty($audioUrl)) {
  13215. $mergedItem['voice_audio_url'] = $audioUrl;
  13216. }
  13217. $merged[] = $mergedItem;
  13218. } else {
  13219. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  13220. $mergedItem = [
  13221. $nameKey => trim((string)getProp($item, $nameKey)),
  13222. 'description' => trim((string)getProp($item, 'description')),
  13223. ];
  13224. // 如果有 pic_prompt,添加到合并项中
  13225. $picPrompt = getProp($item, 'pic_prompt');
  13226. if (!empty($picPrompt)) {
  13227. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  13228. }
  13229. // 保留生成项的音色字段
  13230. $voiceName = getProp($item, 'voice_name');
  13231. if (!empty($voiceName)) {
  13232. $mergedItem['voice_name'] = $voiceName;
  13233. }
  13234. $voiceType = getProp($item, 'voice_type');
  13235. if (!empty($voiceType)) {
  13236. $mergedItem['voice_type'] = $voiceType;
  13237. }
  13238. $audioUrl = getProp($item, 'voice_audio_url');
  13239. if (!empty($audioUrl)) {
  13240. $mergedItem['voice_audio_url'] = $audioUrl;
  13241. }
  13242. // 不继承 URL、task_id 和 task_status(重置状态)
  13243. $merged[] = $mergedItem;
  13244. }
  13245. } else {
  13246. // 新增项,保留生成项的所有字段
  13247. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  13248. }
  13249. }
  13250. return $merged ?: array_values($existingItems);
  13251. }
  13252. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  13253. {
  13254. $resetItem = [
  13255. $nameKey => trim((string)getProp($item, $nameKey)),
  13256. 'description' => trim((string)getProp($item, 'description')),
  13257. ];
  13258. // 保留指定的字段
  13259. foreach ($preserveFields as $field) {
  13260. $value = getProp($item, $field);
  13261. if (!empty($value)) {
  13262. $resetItem[$field] = $value;
  13263. }
  13264. }
  13265. return $resetItem;
  13266. }
  13267. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  13268. {
  13269. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  13270. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  13271. if ($existingKey !== $generatedKey) {
  13272. return true;
  13273. }
  13274. // 比较 description 是否变化
  13275. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  13276. return true;
  13277. }
  13278. // 比较 pic_prompt 是否变化
  13279. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  13280. }
  13281. private function normalizeEpisodeResourceKey($value): string
  13282. {
  13283. $value = trim((string)$value);
  13284. if ($value === '') {
  13285. return '';
  13286. }
  13287. return strtolower((string)preg_replace('/\s+/u', '', $value));
  13288. }
  13289. // 生成全局角色图片
  13290. private function batchSetGlobalRoleImg($data, $is_force=false) {
  13291. $anime_id = getProp($data, 'anime_id');
  13292. if (!$anime_id) Utils::throwError('1002:请选择对话');
  13293. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  13294. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  13295. $art_style = getProp($anime, 'art_style');
  13296. $update_flag = false;
  13297. foreach ($roles as &$role) {
  13298. $role_name = getProp($role, 'role');
  13299. if ($role_name == '旁白') continue;
  13300. // 优先使用 pic_prompt,如果没有则使用 description
  13301. $pic_prompt = getProp($role, 'pic_prompt');
  13302. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  13303. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  13304. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  13305. // 参考图地址
  13306. $ref_img_url = getProp($role, 'url');
  13307. if (!$is_force && $ref_img_url) continue;
  13308. $update_flag = true;
  13309. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  13310. try {
  13311. $params = [
  13312. 'prompt' => $description,
  13313. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  13314. 'ref_img_urls' => []
  13315. ];
  13316. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13317. $task_id = $task->id;
  13318. if (!$task_id) {
  13319. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  13320. }
  13321. $role['task_id'] = $task_id;
  13322. $role['task_status'] = 'processing';
  13323. } catch (\Exception $e) {
  13324. Utils::throwError("20003:" . $e->getMessage());
  13325. }
  13326. }
  13327. if (!$update_flag) return true;
  13328. // 保存角色信息
  13329. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  13330. 'roles' => json_encode($roles, 256),
  13331. 'generate_status' => '执行中',
  13332. 'generate_at' => date('Y-m-d H:i:s'),
  13333. 'updated_at' => date('Y-m-d H:i:s')
  13334. ]);
  13335. if (!$boolen) {
  13336. Utils::throwError('20003:保存角色信息失败');
  13337. }
  13338. return $boolen;
  13339. }
  13340. // 生成全局场景图片
  13341. private function batchSetGlobalSceneImg($data, $is_force=false) {
  13342. $anime_id = getProp($data, 'anime_id');
  13343. if (!$anime_id) Utils::throwError('1002:请选择对话');
  13344. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  13345. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  13346. $art_style = getProp($anime, 'art_style');
  13347. $update_flag = false;
  13348. foreach ($scenes as &$scene) {
  13349. $scene_name = getProp($scene, 'scene');
  13350. // 优先使用 pic_prompt,如果没有则使用 description
  13351. $pic_prompt = getProp($scene, 'pic_prompt');
  13352. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  13353. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  13354. // 参考图地址
  13355. $ref_img_url = getProp($scene, 'url');
  13356. if (!$is_force && $ref_img_url) continue;
  13357. $update_flag = true;
  13358. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  13359. try {
  13360. $params = [
  13361. 'prompt' => $description,
  13362. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  13363. 'ref_img_urls' => []
  13364. ];
  13365. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13366. $task_id = $task->id;
  13367. if (!$task_id) {
  13368. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  13369. }
  13370. $scene['task_id'] = $task_id;
  13371. $scene['task_status'] = 'processing';
  13372. } catch (\Exception $e) {
  13373. Utils::throwError("20003:" . $e->getMessage());
  13374. }
  13375. }
  13376. if (!$update_flag) return true;
  13377. // 保存角色信息
  13378. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  13379. 'scenes' => json_encode($scenes, 256),
  13380. 'generate_status' => '执行中',
  13381. 'generate_at' => date('Y-m-d H:i:s'),
  13382. 'updated_at' => date('Y-m-d H:i:s')
  13383. ]);
  13384. if (!$boolen) {
  13385. Utils::throwError('20003:保存角色信息失败');
  13386. }
  13387. return $boolen;
  13388. }
  13389. // 生成分镜主体、场景和道具图片
  13390. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  13391. $character_prefix = '';
  13392. $scene_prefix = '';
  13393. $prop_prefix = '';
  13394. if ($art_style_type) {
  13395. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  13396. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  13397. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  13398. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  13399. }
  13400. $update_flag = false;
  13401. // 获取上一集的roles、scenes和props数据
  13402. $prev_roles = [];
  13403. $prev_scenes = [];
  13404. $prev_props = [];
  13405. if ($episode_number > 1) {
  13406. $prev_episode = DB::table('mp_anime_episodes')
  13407. ->where('anime_id', $anime_id)
  13408. ->where('episode_number', $episode_number - 1)
  13409. ->where('is_default', 1)
  13410. ->first();
  13411. if ($prev_episode) {
  13412. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  13413. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  13414. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  13415. dLog('deepseek')->info("获取上一集数据成功", [
  13416. 'anime_id' => $anime_id,
  13417. 'prev_episode_number' => $episode_number - 1,
  13418. 'prev_roles_count' => count($prev_roles),
  13419. 'prev_scenes_count' => count($prev_scenes),
  13420. 'prev_props_count' => count($prev_props)
  13421. ]);
  13422. }
  13423. }
  13424. // 处理角色图片生成
  13425. foreach ($roles as &$role) {
  13426. $role_name = getProp($role, 'role');
  13427. if ($role_name == '旁白') continue;
  13428. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  13429. if (isset($ref_products[$role_name])) {
  13430. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  13431. $role['three_view_image_url'] = isset($ref_products[$role_name]['three_view_image_url']) ? $ref_products[$role_name]['three_view_image_url'] : '';
  13432. if ($role['url']) continue;
  13433. }
  13434. $role_description = getProp($role, 'description');
  13435. $role_pic_prompt = getProp($role, 'pic_prompt');
  13436. $role_url = getProp($role, 'url');
  13437. // 检查是否可以从上一集继承
  13438. $inherited = false;
  13439. if (!$is_force && !empty($prev_roles)) {
  13440. foreach ($prev_roles as $prev_role) {
  13441. $prev_role_name = getProp($prev_role, 'role');
  13442. $prev_description = getProp($prev_role, 'description');
  13443. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  13444. $prev_url = getProp($prev_role, 'url');
  13445. $prev_task_id = getProp($prev_role, 'task_id');
  13446. $prev_task_status = getProp($prev_role, 'task_status');
  13447. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  13448. if ($role_name == $prev_role_name
  13449. && $role_description == $prev_description
  13450. && $role_pic_prompt == $prev_pic_prompt
  13451. && !empty($prev_url)) {
  13452. $role['task_id'] = $prev_task_id;
  13453. $role['task_status'] = $prev_task_status;
  13454. $role['url'] = $prev_url;
  13455. $inherited = true;
  13456. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  13457. 'anime_id' => $anime_id,
  13458. 'episode_number' => $episode_number,
  13459. 'task_id' => $prev_task_id,
  13460. 'url' => $prev_url
  13461. ]);
  13462. break;
  13463. }
  13464. }
  13465. }
  13466. // 如果已继承或已有url,跳过生成
  13467. if ($inherited || (!$is_force && $role_url)) {
  13468. continue;
  13469. }
  13470. // 优先使用 pic_prompt,如果没有则使用 description
  13471. $pic_prompt = getProp($role, 'pic_prompt');
  13472. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  13473. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  13474. $update_flag = true;
  13475. // 调用AIImageGenerationService的生成图片任务接口
  13476. try {
  13477. $params = [
  13478. 'prompt' => $description,
  13479. 'ref_img_urls' => []
  13480. ];
  13481. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13482. $task_id = $task->id;
  13483. if (!$task_id) {
  13484. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  13485. continue; // 不中断,继续处理其他角色
  13486. }
  13487. $role['task_id'] = $task_id;
  13488. $role['task_status'] = 'processing';
  13489. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  13490. 'anime_id' => $anime_id,
  13491. 'episode_number' => $episode_number,
  13492. 'task_id' => $task_id
  13493. ]);
  13494. } catch (\Exception $e) {
  13495. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  13496. // 不抛出异常,继续处理其他角色
  13497. }
  13498. }
  13499. // 处理场景图片生成
  13500. foreach ($scenes as &$scene) {
  13501. $scene_name = getProp($scene, 'scene');
  13502. $scene_description = getProp($scene, 'description');
  13503. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  13504. $scene_url = getProp($scene, 'url');
  13505. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  13506. if (isset($ref_products[$scene_name])) {
  13507. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  13508. $scene['three_view_image_url'] = isset($ref_products[$scene_name]['three_view_image_url']) ? $ref_products[$scene_name]['three_view_image_url'] : '';
  13509. if ($scene['url']) continue;
  13510. }
  13511. // 检查是否可以从上一集继承
  13512. $inherited = false;
  13513. if (!$is_force && !empty($prev_scenes)) {
  13514. foreach ($prev_scenes as $prev_scene) {
  13515. $prev_scene_name = getProp($prev_scene, 'scene');
  13516. $prev_description = getProp($prev_scene, 'description');
  13517. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  13518. $prev_url = getProp($prev_scene, 'url');
  13519. $prev_task_id = getProp($prev_scene, 'task_id');
  13520. $prev_task_status = getProp($prev_scene, 'task_status');
  13521. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  13522. if ($scene_name == $prev_scene_name
  13523. && $scene_description == $prev_description
  13524. && $scene_pic_prompt == $prev_pic_prompt
  13525. && !empty($prev_url)) {
  13526. $scene['task_id'] = $prev_task_id;
  13527. $scene['task_status'] = $prev_task_status;
  13528. $scene['url'] = $prev_url;
  13529. $inherited = true;
  13530. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  13531. 'anime_id' => $anime_id,
  13532. 'episode_number' => $episode_number,
  13533. 'task_id' => $prev_task_id,
  13534. 'url' => $prev_url
  13535. ]);
  13536. break;
  13537. }
  13538. }
  13539. }
  13540. // 如果已继承或已有url,跳过生成
  13541. if ($inherited || (!$is_force && $scene_url)) {
  13542. continue;
  13543. }
  13544. // 优先使用 pic_prompt,如果没有则使用 description
  13545. $pic_prompt = getProp($scene, 'pic_prompt');
  13546. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  13547. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  13548. $update_flag = true;
  13549. // 调用AIImageGenerationService的生成图片任务接口
  13550. try {
  13551. $params = [
  13552. 'prompt' => $description,
  13553. 'ref_img_urls' => []
  13554. ];
  13555. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13556. $task_id = $task->id;
  13557. if (!$task_id) {
  13558. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  13559. continue; // 不中断,继续处理其他场景
  13560. }
  13561. $scene['task_id'] = $task_id;
  13562. $scene['task_status'] = 'processing';
  13563. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  13564. 'anime_id' => $anime_id,
  13565. 'episode_number' => $episode_number,
  13566. 'task_id' => $task_id
  13567. ]);
  13568. } catch (\Exception $e) {
  13569. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  13570. // 不抛出异常,继续处理其他场景
  13571. }
  13572. }
  13573. // 处理道具图片生成(逻辑与场景一致)
  13574. foreach ($props as &$prop) {
  13575. $prop_name = getProp($prop, 'prop');
  13576. $prop_description = getProp($prop, 'description');
  13577. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  13578. $prop_url = getProp($prop, 'url');
  13579. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  13580. if (isset($ref_products[$prop_name])) {
  13581. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  13582. $prop['three_view_image_url'] = isset($ref_products[$prop_name]['three_view_image_url']) ? $ref_products[$prop_name]['three_view_image_url'] : '';
  13583. if ($prop['url']) continue;
  13584. }
  13585. // 检查是否可以从上一集继承
  13586. $inherited = false;
  13587. if (!$is_force && !empty($prev_props)) {
  13588. foreach ($prev_props as $prev_prop) {
  13589. $prev_prop_name = getProp($prev_prop, 'prop');
  13590. $prev_description = getProp($prev_prop, 'description');
  13591. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  13592. $prev_url = getProp($prev_prop, 'url');
  13593. $prev_task_id = getProp($prev_prop, 'task_id');
  13594. $prev_task_status = getProp($prev_prop, 'task_status');
  13595. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  13596. if ($prop_name == $prev_prop_name
  13597. && $prop_description == $prev_description
  13598. && $prop_pic_prompt == $prev_pic_prompt
  13599. && !empty($prev_url)) {
  13600. $prop['task_id'] = $prev_task_id;
  13601. $prop['task_status'] = $prev_task_status;
  13602. $prop['url'] = $prev_url;
  13603. $inherited = true;
  13604. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  13605. 'anime_id' => $anime_id,
  13606. 'episode_number' => $episode_number,
  13607. 'task_id' => $prev_task_id,
  13608. 'url' => $prev_url
  13609. ]);
  13610. break;
  13611. }
  13612. }
  13613. }
  13614. // 如果已继承或已有url,跳过生成
  13615. if ($inherited || (!$is_force && $prop_url)) {
  13616. continue;
  13617. }
  13618. // 优先使用 pic_prompt,如果没有则使用 description
  13619. $pic_prompt = getProp($prop, 'pic_prompt');
  13620. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  13621. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  13622. $update_flag = true;
  13623. // 调用AIImageGenerationService的生成图片任务接口
  13624. try {
  13625. $params = [
  13626. 'prompt' => $description,
  13627. 'ref_img_urls' => []
  13628. ];
  13629. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13630. $task_id = $task->id;
  13631. if (!$task_id) {
  13632. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  13633. continue; // 不中断,继续处理其他道具
  13634. }
  13635. $prop['task_id'] = $task_id;
  13636. $prop['task_status'] = 'processing';
  13637. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  13638. 'anime_id' => $anime_id,
  13639. 'episode_number' => $episode_number,
  13640. 'task_id' => $task_id
  13641. ]);
  13642. } catch (\Exception $e) {
  13643. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  13644. // 不抛出异常,继续处理其他道具
  13645. }
  13646. }
  13647. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  13648. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  13649. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  13650. // // 保存剧集的角色和场景信息
  13651. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  13652. // 'roles' => json_encode($roles, 256),
  13653. // 'scenes' => json_encode($scenes, 256),
  13654. // 'generate_status' => '执行中',
  13655. // 'generate_at' => date('Y-m-d H:i:s'),
  13656. // 'updated_at' => date('Y-m-d H:i:s')
  13657. // ]);
  13658. // if (!$boolen) {
  13659. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  13660. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  13661. // }
  13662. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  13663. // 'episode_id' => $episode_id,
  13664. 'roles_count' => count($roles),
  13665. 'scenes_count' => count($scenes),
  13666. 'props_count' => count($props)
  13667. ]);
  13668. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  13669. }
  13670. /**
  13671. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  13672. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  13673. *
  13674. * @param int $anime_id 动漫对话ID
  13675. * @param array $episode_roles 剧集角色数据
  13676. * @param array $episode_scenes 剧集场景数据
  13677. * @param array $episode_props 剧集道具数据
  13678. * @return bool
  13679. */
  13680. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  13681. // 获取全局数据
  13682. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  13683. if (!$anime) {
  13684. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  13685. return false;
  13686. }
  13687. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  13688. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  13689. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  13690. $roles_added = false;
  13691. $roles_updated = false;
  13692. $scenes_added = false;
  13693. $props_added = false;
  13694. // 处理角色同步
  13695. foreach ($episode_roles as $episode_role) {
  13696. $episode_role_name = getProp($episode_role, 'role');
  13697. $episode_description = getProp($episode_role, 'description');
  13698. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  13699. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  13700. // 跳过旁白
  13701. if ($episode_role_name == '旁白') {
  13702. continue;
  13703. }
  13704. // 检查全局中是否已存在相同的角色
  13705. $exists = false;
  13706. $global_role_index = -1;
  13707. foreach ($global_roles as $index => $global_role) {
  13708. $global_role_name = getProp($global_role, 'role');
  13709. $global_description = getProp($global_role, 'description');
  13710. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  13711. // 如果role、description、pic_prompt三项都一致,则认为已存在
  13712. if ($episode_role_name == $global_role_name
  13713. && $episode_description == $global_description
  13714. && $episode_pic_prompt == $global_pic_prompt) {
  13715. $exists = true;
  13716. $global_role_index = $index;
  13717. break;
  13718. }
  13719. }
  13720. // 如果不存在,则添加到全局
  13721. if (!$exists) {
  13722. $global_roles[] = $episode_role;
  13723. $roles_added = true;
  13724. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  13725. 'anime_id' => $anime_id,
  13726. 'role' => $episode_role_name
  13727. ]);
  13728. } else {
  13729. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  13730. if (!empty($episode_voice_prompt)) {
  13731. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  13732. // 如果全局没有voice_prompt或与剧集不一致,则更新
  13733. if ($global_voice_prompt !== $episode_voice_prompt) {
  13734. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  13735. $roles_updated = true;
  13736. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  13737. 'anime_id' => $anime_id,
  13738. 'role' => $episode_role_name,
  13739. 'voice_prompt' => $episode_voice_prompt
  13740. ]);
  13741. }
  13742. }
  13743. }
  13744. }
  13745. // 处理场景同步
  13746. foreach ($episode_scenes as $episode_scene) {
  13747. $episode_scene_name = getProp($episode_scene, 'scene');
  13748. $episode_description = getProp($episode_scene, 'description');
  13749. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  13750. // 检查全局中是否已存在相同的场景
  13751. $exists = false;
  13752. foreach ($global_scenes as $global_scene) {
  13753. $global_scene_name = getProp($global_scene, 'scene');
  13754. $global_description = getProp($global_scene, 'description');
  13755. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  13756. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  13757. if ($episode_scene_name == $global_scene_name
  13758. && $episode_description == $global_description
  13759. && $episode_pic_prompt == $global_pic_prompt) {
  13760. $exists = true;
  13761. break;
  13762. }
  13763. }
  13764. // 如果不存在,则添加到全局
  13765. if (!$exists) {
  13766. $global_scenes[] = $episode_scene;
  13767. $scenes_added = true;
  13768. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  13769. 'anime_id' => $anime_id,
  13770. 'scene' => $episode_scene_name
  13771. ]);
  13772. }
  13773. }
  13774. // 处理道具同步(逻辑与场景一致)
  13775. foreach ($episode_props as $episode_prop) {
  13776. $episode_prop_name = getProp($episode_prop, 'prop');
  13777. $episode_description = getProp($episode_prop, 'description');
  13778. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  13779. // 检查全局中是否已存在相同的道具
  13780. $exists = false;
  13781. foreach ($global_props as $global_prop) {
  13782. $global_prop_name = getProp($global_prop, 'prop');
  13783. $global_description = getProp($global_prop, 'description');
  13784. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  13785. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  13786. if ($episode_prop_name == $global_prop_name
  13787. && $episode_description == $global_description
  13788. && $episode_pic_prompt == $global_pic_prompt) {
  13789. $exists = true;
  13790. break;
  13791. }
  13792. }
  13793. // 如果不存在,则添加到全局
  13794. if (!$exists) {
  13795. $global_props[] = $episode_prop;
  13796. $props_added = true;
  13797. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  13798. 'anime_id' => $anime_id,
  13799. 'prop' => $episode_prop_name
  13800. ]);
  13801. }
  13802. }
  13803. // 如果有新增或更新,则更新全局数据
  13804. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  13805. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  13806. if ($roles_added || $roles_updated) {
  13807. $update_data['roles'] = json_encode($global_roles, 256);
  13808. }
  13809. if ($scenes_added) {
  13810. $update_data['scenes'] = json_encode($global_scenes, 256);
  13811. }
  13812. if ($props_added) {
  13813. $update_data['props'] = json_encode($global_props, 256);
  13814. }
  13815. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  13816. dLog('deepseek')->info('剧集数据同步到全局完成', [
  13817. 'anime_id' => $anime_id,
  13818. 'roles_added' => $roles_added,
  13819. 'roles_updated' => $roles_updated,
  13820. 'scenes_added' => $scenes_added,
  13821. 'props_added' => $props_added,
  13822. 'global_roles_count' => count($global_roles),
  13823. 'global_scenes_count' => count($global_scenes),
  13824. 'global_props_count' => count($global_props)
  13825. ]);
  13826. }
  13827. return true;
  13828. }
  13829. /**
  13830. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  13831. *
  13832. * @param int $anime_id 动漫对话ID
  13833. * @param int $episode_id 分集ID
  13834. * @return bool
  13835. */
  13836. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  13837. // 获取全局角色和场景数据
  13838. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  13839. if (!$anime) {
  13840. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  13841. return false;
  13842. }
  13843. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  13844. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  13845. // 获取指定的分集
  13846. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  13847. if (!$episode) {
  13848. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  13849. return false;
  13850. }
  13851. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  13852. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  13853. $roles_updated = false;
  13854. $scenes_updated = false;
  13855. // 继承角色的task_id、task_status和url
  13856. foreach ($episode_roles as &$episode_role) {
  13857. $episode_role_name = getProp($episode_role, 'role');
  13858. $episode_description = getProp($episode_role, 'description');
  13859. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  13860. $episode_url = getProp($episode_role, 'url');
  13861. // 跳过旁白角色
  13862. if ($episode_role_name == '旁白') {
  13863. continue;
  13864. }
  13865. // 如果剧集中已有URL,跳过
  13866. if (!empty($episode_url)) {
  13867. continue;
  13868. }
  13869. // 遍历全局角色数据,查找匹配的角色
  13870. foreach ($global_roles as $global_role) {
  13871. $global_role_name = getProp($global_role, 'role');
  13872. $global_description = getProp($global_role, 'description');
  13873. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  13874. $global_url = getProp($global_role, 'url');
  13875. $global_task_id = getProp($global_role, 'task_id');
  13876. $global_task_status = getProp($global_role, 'task_status');
  13877. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  13878. if ($episode_role_name == $global_role_name
  13879. && $episode_description == $global_description
  13880. && $episode_pic_prompt == $global_pic_prompt) {
  13881. // 继承 task_id、task_status 和 url
  13882. if (!empty($global_task_id)) {
  13883. $episode_role['task_id'] = $global_task_id;
  13884. $episode_role['task_status'] = $global_task_status;
  13885. $roles_updated = true;
  13886. dLog('deepseek')->info('剧集角色继承全局task_id', [
  13887. 'episode_id' => $episode_id,
  13888. 'role' => $episode_role_name,
  13889. 'task_id' => $global_task_id,
  13890. 'task_status' => $global_task_status
  13891. ]);
  13892. }
  13893. if (!empty($global_url)) {
  13894. $episode_role['url'] = $global_url;
  13895. $roles_updated = true;
  13896. dLog('deepseek')->info('剧集角色继承全局url', [
  13897. 'episode_id' => $episode_id,
  13898. 'role' => $episode_role_name,
  13899. 'url' => $global_url
  13900. ]);
  13901. }
  13902. break;
  13903. }
  13904. }
  13905. }
  13906. // 继承场景的task_id、task_status和url
  13907. foreach ($episode_scenes as &$episode_scene) {
  13908. $episode_scene_name = getProp($episode_scene, 'scene');
  13909. $episode_description = getProp($episode_scene, 'description');
  13910. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  13911. $episode_url = getProp($episode_scene, 'url');
  13912. // 如果剧集中已有URL,跳过
  13913. if (!empty($episode_url)) {
  13914. continue;
  13915. }
  13916. // 遍历全局场景数据,查找匹配的场景
  13917. foreach ($global_scenes as $global_scene) {
  13918. $global_scene_name = getProp($global_scene, 'scene');
  13919. $global_description = getProp($global_scene, 'description');
  13920. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  13921. $global_url = getProp($global_scene, 'url');
  13922. $global_task_id = getProp($global_scene, 'task_id');
  13923. $global_task_status = getProp($global_scene, 'task_status');
  13924. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  13925. if ($episode_scene_name == $global_scene_name
  13926. && $episode_description == $global_description
  13927. && $episode_pic_prompt == $global_pic_prompt) {
  13928. // 继承 task_id、task_status 和 url
  13929. if (!empty($global_task_id)) {
  13930. $episode_scene['task_id'] = $global_task_id;
  13931. $episode_scene['task_status'] = $global_task_status;
  13932. $scenes_updated = true;
  13933. dLog('deepseek')->info('剧集场景继承全局task_id', [
  13934. 'episode_id' => $episode_id,
  13935. 'scene' => $episode_scene_name,
  13936. 'task_id' => $global_task_id,
  13937. 'task_status' => $global_task_status
  13938. ]);
  13939. }
  13940. if (!empty($global_url)) {
  13941. $episode_scene['url'] = $global_url;
  13942. $scenes_updated = true;
  13943. dLog('deepseek')->info('剧集场景继承全局url', [
  13944. 'episode_id' => $episode_id,
  13945. 'scene' => $episode_scene_name,
  13946. 'url' => $global_url
  13947. ]);
  13948. }
  13949. break;
  13950. }
  13951. }
  13952. }
  13953. // 如果有更新,则保存到数据库
  13954. if ($roles_updated || $scenes_updated) {
  13955. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  13956. if ($roles_updated) {
  13957. $update_data['roles'] = json_encode($episode_roles, 256);
  13958. }
  13959. if ($scenes_updated) {
  13960. $update_data['scenes'] = json_encode($episode_scenes, 256);
  13961. }
  13962. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  13963. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  13964. 'episode_id' => $episode_id,
  13965. 'roles_updated' => $roles_updated,
  13966. 'scenes_updated' => $scenes_updated
  13967. ]);
  13968. }
  13969. return true;
  13970. }
  13971. public function chatChangeImg($data) {
  13972. // 文生文计费预检(normal 档)
  13973. $uid = Site::getUid();
  13974. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'normal'), $uid);
  13975. $segment = getProp($data, 'segment');
  13976. $segment_content = getProp($segment, 'segment_content');
  13977. $prompt = getProp($data, 'prompt');
  13978. $ref_img = getProp($data, 'ref_img');
  13979. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  13980. // 处理文本模型
  13981. $model = getProp($data, 'model');
  13982. if (!$model) {
  13983. // 用户没有输入,从anime表获取
  13984. $segment_id = getProp($segment, 'segment_id');
  13985. if ($segment_id) {
  13986. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  13987. if ($episode_id) {
  13988. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  13989. if ($anime_id) {
  13990. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  13991. }
  13992. }
  13993. }
  13994. if (!$model) {
  13995. // anime表也没有,使用默认值
  13996. $model = 'doubao-seed-2-0-mini-260215';
  13997. }
  13998. }
  13999. // 验证模型是否在可用模型表中
  14000. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  14001. $model = 'doubao-seed-2-0-mini-260215';
  14002. }
  14003. $messages[] =
  14004. [
  14005. 'role' => 'user',
  14006. 'content' => $question
  14007. ];
  14008. $post_data = [
  14009. 'model' => $model,
  14010. 'messages' => $messages,
  14011. // 'max_tokens' => 8192,
  14012. 'temperature' => 0.7,
  14013. 'frequency_penalty' => 0,
  14014. 'presence_penalty' => 0,
  14015. 'response_format' => ['type' => 'text'],
  14016. 'stream' => false // 是否启用流式输出
  14017. ];
  14018. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  14019. // DeepSeek 官方模型使用 DeepSeek API
  14020. $chatResult = $this->chatOnly($post_data);
  14021. } else if (in_array($model, $this->gpt_text_models)) {
  14022. // GPT-5.4 模型使用 TokenRouter API
  14023. $chatResult = $this->gpt54ChatOnly($post_data);
  14024. } else {
  14025. // 其他模型使用火山引擎API
  14026. $chatResult = $this->volcEngineChatCompletion($post_data);
  14027. }
  14028. if (is_array($chatResult)) {
  14029. extract($chatResult);
  14030. }else {
  14031. Utils::throwError('20003: 接口调用失败!');
  14032. }
  14033. // 文生文成功计费(normal 档):同时记录积分与 token 明细
  14034. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  14035. 'model' => $model,
  14036. 'source' => 'chatChangeImg',
  14037. ], 'normal');
  14038. return [
  14039. 'type' => 'done',
  14040. // 'episode' => $episode,
  14041. 'answer' => $fullContent,
  14042. 'reasoning' => $fullReasoningContent,
  14043. 'usage' => $usage
  14044. ];
  14045. }
  14046. /**
  14047. * 仅调用 deepseek 对话接口(非流式)
  14048. *
  14049. * @param array $post_data
  14050. * @param int $timeout
  14051. * @return array
  14052. */
  14053. private function chatOnly($post_data, $timeout = 1800) {
  14054. $post_data['max_tokens'] = 300000;
  14055. $client = new Client(['timeout' => $timeout, 'verify' => false]);
  14056. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  14057. $response = $result->getBody()->getContents();
  14058. $response_arr = json_decode($response, true);
  14059. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  14060. $fullContent = '';
  14061. $fullReasoningContent = [];
  14062. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  14063. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  14064. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  14065. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  14066. }
  14067. return [
  14068. 'fullContent' => $fullContent,
  14069. 'fullReasoningContent' => $fullReasoningContent,
  14070. 'usage' => $usage
  14071. ];
  14072. }
  14073. /**
  14074. * 用 deepseek-v4-flash 非流式分析报错,返回不超过50字的用户友好提示
  14075. *
  14076. * @param string $errorMessage
  14077. * @return string|null
  14078. */
  14079. public function analyzeErrorMessage($errorMessage)
  14080. {
  14081. try {
  14082. $post_data = [
  14083. 'model' => 'deepseek-v4-flash',
  14084. 'messages' => [
  14085. [
  14086. 'role' => 'system',
  14087. 'content' => '你是视频生成任务的报错分析助手。请根据用户给出的原始报错,用一句中文提示告诉用户问题原因和下一步怎么做,不超过50个字,直接输出提示内容,不要解释、不要输出代码。',
  14088. ],
  14089. [
  14090. 'role' => 'user',
  14091. 'content' => (string)$errorMessage,
  14092. ],
  14093. ],
  14094. 'temperature' => 0.3,
  14095. 'frequency_penalty' => 0,
  14096. 'presence_penalty' => 0,
  14097. 'response_format' => ['type' => 'text'],
  14098. 'stream' => false,
  14099. ];
  14100. $result = $this->chatOnly($post_data, 8);
  14101. // 调用成功即记录 token 使用明细(不扣积分),保证错误分析这类隐性 AI 调用进入统计口径
  14102. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  14103. 'model' => 'deepseek-v4-flash',
  14104. 'source' => 'analyzeErrorMessage',
  14105. ], 'deepseek-v4-flash');
  14106. $content = trim((string)($result['fullContent'] ?? ''));
  14107. if ($content === '') {
  14108. return null;
  14109. }
  14110. return mb_substr($content, 0, 50);
  14111. } catch (\Exception $e) {
  14112. dLog('deepseek')->error('视频任务报错分析失败: ' . $e->getMessage(), [
  14113. 'error_message' => $errorMessage
  14114. ]);
  14115. return null;
  14116. }
  14117. }
  14118. // 仅调用 GPT-5.4 对话接口(非流式)
  14119. private function gpt54ChatOnly($post_data) {
  14120. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  14121. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  14122. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  14123. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  14124. $usedLunaFallback = false;
  14125. if (empty($apiKey)) {
  14126. Utils::throwError('20003:GPT-5.4 API Key未配置');
  14127. }
  14128. // 先探活,服务不可用时自动重试
  14129. $this->ensureGptServiceAvailable($apiKey);
  14130. $client = new Client(['timeout' => 1800, 'verify' => false]);
  14131. // 移除 thinking 参数,GPT-5.4 不支持
  14132. if (isset($post_data['thinking'])) {
  14133. unset($post_data['thinking']);
  14134. }
  14135. if (isset($post_data['reasoning_effort'])) {
  14136. unset($post_data['reasoning_effort']);
  14137. }
  14138. $post_data['max_completion_tokens'] = 100000;
  14139. // 确保 stream 为 false
  14140. $post_data['stream'] = false;
  14141. $maxRetries = $this->gptRetryTimes();
  14142. $interval = $this->gptRetryInterval();
  14143. $attempt = 0;
  14144. while (true) {
  14145. try {
  14146. $headers = [
  14147. 'Authorization' => 'Bearer ' . $apiKey,
  14148. 'Content-Type' => 'application/json'
  14149. ];
  14150. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  14151. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  14152. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  14153. 'json' => $post_data,
  14154. 'headers' => $headers
  14155. ]);
  14156. $response = $result->getBody()->getContents();
  14157. $response_arr = json_decode($response, true);
  14158. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  14159. $fullContent = '';
  14160. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  14161. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  14162. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  14163. }
  14164. return [
  14165. 'fullContent' => $fullContent,
  14166. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  14167. 'usage' => $usage
  14168. ];
  14169. } catch (\Exception $e) {
  14170. // 报错或超时时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  14171. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  14172. $usedLunaFallback = true;
  14173. $apiKey = $lunaApiKey;
  14174. dLog('deepseek')->warning('GPT-5.4 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  14175. continue;
  14176. }
  14177. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  14178. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  14179. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  14180. throw $e;
  14181. }
  14182. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  14183. 'retry' => $attempt + 1,
  14184. 'max_retries' => $maxRetries,
  14185. 'error' => $e->getMessage()
  14186. ]);
  14187. sleep($interval);
  14188. $attempt++;
  14189. }
  14190. }
  14191. }
  14192. public function getContentByBid($bid) {
  14193. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  14194. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  14195. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  14196. $content = '';
  14197. foreach ($chapters as $chapter) {
  14198. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  14199. }
  14200. return $content;
  14201. }
  14202. public function getContentByScriptId($script_id) {
  14203. $content = '';
  14204. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  14205. if ($contents) {
  14206. $content = implode(PHP_EOL, $contents);
  14207. }else {
  14208. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  14209. }
  14210. return $content;
  14211. }
  14212. /**
  14213. * 根据文件类型提取文本内容
  14214. *
  14215. * @param mixed $file 文件对象或文件路径
  14216. * @return string
  14217. */
  14218. public function extractFileContent($file) {
  14219. // 获取文件路径和扩展名
  14220. if (is_string($file)) {
  14221. $filePath = $file;
  14222. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  14223. } else {
  14224. // Laravel UploadedFile 对象
  14225. $filePath = $file->getRealPath();
  14226. $extension = strtolower($file->getClientOriginalExtension());
  14227. }
  14228. $content = '';
  14229. switch ($extension) {
  14230. case 'txt':
  14231. $content = $this->extractTxtContent($filePath);
  14232. break;
  14233. case 'pdf':
  14234. $content = $this->extractPdfContent($filePath);
  14235. break;
  14236. case 'doc':
  14237. case 'docx':
  14238. $content = $this->extractWordContent($filePath);
  14239. break;
  14240. // case 'jpg':
  14241. // case 'jpeg':
  14242. // case 'png':
  14243. // case 'gif':
  14244. // case 'bmp':
  14245. // case 'webp':
  14246. // $content = $this->extractImageContent($filePath);
  14247. // break;
  14248. default:
  14249. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  14250. }
  14251. // 移除非法 UTF-8 字节,避免后续 JSON 编码或正则解析异常
  14252. if (!mb_check_encoding($content, 'UTF-8')) {
  14253. $cleaned = @iconv('UTF-8', 'UTF-8//IGNORE', $content);
  14254. $content = $cleaned === false ? $content : $cleaned;
  14255. }
  14256. return $content;
  14257. }
  14258. /**
  14259. * 提取 TXT 文件内容
  14260. */
  14261. private function extractTxtContent($filePath) {
  14262. if (!file_exists($filePath)) {
  14263. Utils::throwError('20003:文件不存在');
  14264. }
  14265. $content = file_get_contents($filePath);
  14266. // 尝试检测并转换编码
  14267. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  14268. if ($encoding && $encoding !== 'UTF-8') {
  14269. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  14270. }
  14271. return trim($content);
  14272. }
  14273. /**
  14274. * 提取 PDF 文件内容
  14275. */
  14276. private function extractPdfContent($filePath) {
  14277. if (!file_exists($filePath)) {
  14278. Utils::throwError('20003:文件不存在');
  14279. }
  14280. try {
  14281. $parser = new PdfParser();
  14282. $pdf = $parser->parseFile($filePath);
  14283. $content = $pdf->getText();
  14284. return trim($content);
  14285. } catch (\Exception $e) {
  14286. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  14287. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  14288. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  14289. }
  14290. }
  14291. /**
  14292. * 提取 Word 文件内容(支持 doc 和 docx)
  14293. */
  14294. private function extractWordContent($filePath) {
  14295. if (!file_exists($filePath)) {
  14296. Utils::throwError('20003:文件不存在');
  14297. }
  14298. try {
  14299. $phpWord = WordIOFactory::load($filePath);
  14300. $content = '';
  14301. foreach ($phpWord->getSections() as $section) {
  14302. foreach ($section->getElements() as $element) {
  14303. $content .= $this->extractWordElementText($element);
  14304. // 段落边界补换行(段落内的软换行已在元素递归中处理)
  14305. $content .= "\n";
  14306. }
  14307. }
  14308. return trim($content);
  14309. } catch (\Exception $e) {
  14310. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  14311. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  14312. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  14313. }
  14314. }
  14315. /**
  14316. * 递归提取 Word 元素中的文本
  14317. */
  14318. private function extractWordElementText($element) {
  14319. $text = '';
  14320. if ($element instanceof \PhpOffice\PhpWord\Element\TextBreak
  14321. || $element instanceof \PhpOffice\PhpWord\Element\LineBreak) {
  14322. // 软换行:保留 Word 中的换行显示,避免"第X集"标题与正文粘连
  14323. $text .= "\n";
  14324. } elseif (method_exists($element, 'getElements')) {
  14325. foreach ($element->getElements() as $childElement) {
  14326. $text .= $this->extractWordElementText($childElement);
  14327. }
  14328. } elseif (method_exists($element, 'getText')) {
  14329. $text .= $element->getText();
  14330. }
  14331. return $text;
  14332. }
  14333. /**
  14334. * 提取图片内容(使用火山引擎 OCR)
  14335. */
  14336. private function extractImageContent($filePath) {
  14337. if (!file_exists($filePath)) {
  14338. Utils::throwError('20003:文件不存在');
  14339. }
  14340. try {
  14341. // 读取图片并转换为 base64
  14342. $imageData = file_get_contents($filePath);
  14343. $base64Image = base64_encode($imageData);
  14344. // 调用火山引擎 OCR 服务
  14345. $content = $this->callVolcEngineOCR($base64Image);
  14346. return trim($content);
  14347. } catch (\Exception $e) {
  14348. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  14349. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  14350. Utils::throwError('20003:图片识别失败');
  14351. }
  14352. }
  14353. /**
  14354. * 调用火山引擎 OCR 服务识别图片文字
  14355. *
  14356. * @param string $base64Image base64 编码的图片数据
  14357. * @return string 识别的文字内容
  14358. */
  14359. private function callVolcEngineOCR($base64Image) {
  14360. $method = 'POST';
  14361. $service = 'cv';
  14362. $host = 'visual.volcengineapi.com';
  14363. $region = env('VOLC_REGION', 'cn-north-1');
  14364. $access_key = env('VOLC_AK');
  14365. $secret_key = env('VOLC_SK');
  14366. $action = 'OCRNormal';
  14367. $version = '2020-08-26';
  14368. if (!$access_key || !$secret_key) {
  14369. Utils::throwError('20003:请配置火山引擎 AK/SK');
  14370. }
  14371. // 请求体
  14372. $body = json_encode([
  14373. 'image_base64' => $base64Image
  14374. ]);
  14375. // 生成签名
  14376. $headers = $this->getVolcEngineSignHeaders(
  14377. $method, $service, $host, $region,
  14378. "Action={$action}&Version={$version}",
  14379. $access_key, $secret_key, $body
  14380. );
  14381. $client = new Client(['timeout' => 1800, 'verify' => false]);
  14382. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  14383. 'headers' => $headers,
  14384. 'body' => $body
  14385. ]);
  14386. $response_arr = json_decode($response->getBody()->getContents(), true);
  14387. // 提取识别的文字
  14388. $textLines = [];
  14389. if (isset($response_arr['data']['line_texts'])) {
  14390. $textLines = $response_arr['data']['line_texts'];
  14391. } elseif (isset($response_arr['data']['ocr_infos'])) {
  14392. foreach ($response_arr['data']['ocr_infos'] as $info) {
  14393. if (isset($info['text'])) {
  14394. $textLines[] = $info['text'];
  14395. }
  14396. }
  14397. }
  14398. if (empty($textLines)) {
  14399. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  14400. return '';
  14401. }
  14402. return implode("\n", $textLines);
  14403. }
  14404. /**
  14405. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  14406. */
  14407. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  14408. $contentType = 'application/json';
  14409. $accept = 'application/json';
  14410. // 获取当前UTC时间
  14411. $t = new DateTime('now', new DateTimeZone('UTC'));
  14412. $xDate = $t->format('Ymd\THis\Z');
  14413. $dateStamp = $t->format('Ymd');
  14414. // 计算 body 的 sha256 哈希
  14415. $payloadHash = hash('sha256', $body);
  14416. // 1. 拼接规范请求串
  14417. $canonicalUri = '/';
  14418. $canonicalQueryString = $queryString;
  14419. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  14420. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  14421. $canonicalRequest = implode("\n", [
  14422. $method,
  14423. $canonicalUri,
  14424. $canonicalQueryString,
  14425. $canonicalHeaders,
  14426. $signedHeaders,
  14427. $payloadHash
  14428. ]);
  14429. // 2. 拼接待签名字符串
  14430. $algorithm = 'HMAC-SHA256';
  14431. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  14432. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  14433. $stringToSign = implode("\n", [
  14434. $algorithm,
  14435. $xDate,
  14436. $credentialScope,
  14437. $hashedCanonicalRequest
  14438. ]);
  14439. // 3. 计算签名
  14440. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  14441. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  14442. // 4. 添加签名到请求头
  14443. $authorizationHeader = sprintf(
  14444. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  14445. $algorithm,
  14446. $access_key,
  14447. $credentialScope,
  14448. $signedHeaders,
  14449. $signature
  14450. );
  14451. return [
  14452. 'Accept' => $accept,
  14453. 'Content-Type' => $contentType,
  14454. 'Host' => $host,
  14455. 'X-Date' => $xDate,
  14456. 'X-Content-Sha256'=> $payloadHash,
  14457. 'Authorization' => $authorizationHeader
  14458. ];
  14459. }
  14460. public function generateScriptWords($cid, $model = 'r1') {
  14461. ini_set('max_execution_time', 0);
  14462. if (!$cid) Utils::throwError('20003: 请选择章节!');
  14463. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  14464. // 模型兼容性处理和思考模式设置
  14465. $thinkingMode = 'disabled';
  14466. $reasoningEffort = 'high';
  14467. if ($model == 'r1') {
  14468. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  14469. $thinkingMode = 'enabled';
  14470. } else {
  14471. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  14472. $thinkingMode = 'disabled';
  14473. }
  14474. $messages = [
  14475. [
  14476. 'role' => 'system',
  14477. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  14478. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  14479. 2.非对话部分请全部用旁白角色代替
  14480. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  14481. ],
  14482. [
  14483. 'role' => 'user',
  14484. 'content' => $content
  14485. ]
  14486. ];
  14487. $post_data = [
  14488. 'model' => $model,
  14489. 'messages' => $messages,
  14490. // 'max_tokens' => 8192,
  14491. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  14492. 'frequency_penalty' => 0,
  14493. 'presence_penalty' => 0,
  14494. 'thinking' => ['type' => $thinkingMode],
  14495. 'response_format' => [
  14496. 'type' => 'text'
  14497. ],
  14498. 'stream' => false
  14499. ];
  14500. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  14501. // 根据模型类型选择调用方法
  14502. $fullContent = '';
  14503. $usage = [];
  14504. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  14505. // DeepSeek 官方模型使用 DeepSeek API
  14506. $chatResult = $this->chatOnly($post_data);
  14507. } else if (in_array($model, $this->gpt_text_models)) {
  14508. // GPT-5.4 模型使用 TokenRouter API
  14509. $chatResult = $this->gpt54ChatOnly($post_data);
  14510. } else {
  14511. // 其他模型使用火山引擎API
  14512. $chatResult = $this->volcEngineChatCompletion($post_data);
  14513. }
  14514. if (is_array($chatResult)) {
  14515. $fullContent = $chatResult['fullContent'];
  14516. $usage = $chatResult['usage'] ?? [];
  14517. }
  14518. // 仅记录 token 使用明细(不扣积分)
  14519. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  14520. 'model' => $model,
  14521. 'cid' => $cid,
  14522. 'source' => 'generateScriptWords',
  14523. ], $model);
  14524. return $fullContent;
  14525. }
  14526. /**
  14527. * 智能化解析集数信息
  14528. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  14529. *
  14530. * @param string $prompt 用户输入的提示词
  14531. * @return int|null 解析出的集数,如果没有找到则返回null
  14532. */
  14533. private function extractEpisodeNumber($prompt)
  14534. {
  14535. if (empty($prompt)) {
  14536. return null;
  14537. }
  14538. // 定义各种可能的表达模式
  14539. $patterns = [
  14540. // 基本模式:改成N集、调整成N集、修改成N集
  14541. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  14542. // 扩展模式:分成N集、拆分成N集、分割成N集
  14543. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  14544. // 数量模式:N集、共N集、总共N集
  14545. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  14546. // 制作模式:制作N集、生成N集、创建N集
  14547. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  14548. // 计划模式:计划N集、预计N集、打算N集
  14549. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  14550. // 需要模式:需要N集、要N集
  14551. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  14552. // 中文数字模式:改成三集、调整成五集等
  14553. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  14554. // 英文数字模式
  14555. '/(?: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',
  14556. ];
  14557. // 中文数字转阿拉伯数字的映射
  14558. $chineseNumbers = [
  14559. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  14560. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  14561. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  14562. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  14563. ];
  14564. // 逐个尝试匹配模式
  14565. foreach ($patterns as $pattern) {
  14566. if (preg_match($pattern, $prompt, $matches)) {
  14567. $number = trim($matches[1]);
  14568. // 如果是中文数字,转换为阿拉伯数字
  14569. if (isset($chineseNumbers[$number])) {
  14570. return $chineseNumbers[$number];
  14571. }
  14572. // 如果是阿拉伯数字,直接返回
  14573. if (is_numeric($number)) {
  14574. $episodeNum = intval($number);
  14575. // 合理性检查:集数应该在1-100之间
  14576. if ($episodeNum >= 1 && $episodeNum <= 100) {
  14577. return $episodeNum;
  14578. }
  14579. }
  14580. }
  14581. }
  14582. return null;
  14583. }
  14584. /**
  14585. * 调用火山引擎对话(Chat) API
  14586. *
  14587. * @param array $params 包含以下参数:
  14588. * - model: 模型ID(必填)
  14589. * - messages: 消息列表(必填)
  14590. * - stream: 是否流式输出(可选,默认false)
  14591. * - max_tokens: 最大输出token数(可选)
  14592. * - temperature: 采样温度(可选,默认1)
  14593. * - top_p: 核采样概率(可选,默认0.7)
  14594. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  14595. * - presence_penalty: 存在惩罚系数(可选,默认0)
  14596. * - stop: 停止词(可选)
  14597. * - tools: 工具列表(可选)
  14598. * @return array|Generator 非流式返回数组,流式返回生成器
  14599. */
  14600. public function volcEngineChatCompletion(array $params)
  14601. {
  14602. $apiKey = env('VOLC_AI_API_KEY');
  14603. if (empty($apiKey)) {
  14604. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  14605. }
  14606. // 构建请求参数
  14607. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  14608. $requestData = [
  14609. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  14610. 'messages' => $params['messages'] ?? [],
  14611. ];
  14612. if (!in_array($originalModel, $this->valid_text_models)) {
  14613. Utils::throwError('20003:该模型不支持!');
  14614. }
  14615. // 添加可选参数
  14616. if (isset($params['stream'])) {
  14617. $requestData['stream'] = $params['stream'];
  14618. }
  14619. if (isset($params['stream_options'])) {
  14620. $requestData['stream_options'] = $params['stream_options'];
  14621. }
  14622. if (isset($params['max_tokens'])) {
  14623. $requestData['max_tokens'] = $params['max_tokens'];
  14624. }else if (isset($params['max_completion_tokens'])) {
  14625. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  14626. }else {
  14627. $requestData['max_completion_tokens'] = 100000;
  14628. }
  14629. if (isset($params['temperature'])) {
  14630. $requestData['temperature'] = $params['temperature'];
  14631. }
  14632. if (isset($params['top_p'])) {
  14633. $requestData['top_p'] = $params['top_p'];
  14634. }
  14635. if (isset($params['frequency_penalty'])) {
  14636. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  14637. }
  14638. if (isset($params['presence_penalty'])) {
  14639. $requestData['presence_penalty'] = $params['presence_penalty'];
  14640. }
  14641. if (isset($params['stop'])) {
  14642. $requestData['stop'] = $params['stop'];
  14643. }
  14644. if (isset($params['tools'])) {
  14645. $requestData['tools'] = $params['tools'];
  14646. }
  14647. if (isset($params['tool_choice'])) {
  14648. $requestData['tool_choice'] = $params['tool_choice'];
  14649. }
  14650. if (isset($params['response_format'])) {
  14651. $requestData['response_format'] = $params['response_format'];
  14652. }
  14653. if (isset($params['thinking'])) {
  14654. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  14655. if (is_array($params['thinking'])) {
  14656. $requestData['thinking'] = $params['thinking'];
  14657. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  14658. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  14659. }
  14660. } else {
  14661. $requestData['thinking'] = ['type' => $params['thinking']];
  14662. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  14663. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  14664. }
  14665. }
  14666. } else {
  14667. $requestData['thinking'] = ['type' => 'disabled'];
  14668. }
  14669. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  14670. $client = new Client(['verify' => false, 'timeout' => 1800]);
  14671. try {
  14672. // 判断是否为流式输出
  14673. $isStream = isset($params['stream']) && $params['stream'] === true;
  14674. if ($isStream) {
  14675. // 流式输出
  14676. // 流式请求默认声明返回 usage(未显式传参时)
  14677. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  14678. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  14679. } else {
  14680. // 非流式输出
  14681. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  14682. 'headers' => [
  14683. 'Authorization' => 'Bearer ' . $apiKey,
  14684. 'Content-Type' => 'application/json',
  14685. ],
  14686. 'json' => $requestData
  14687. ]);
  14688. $responseData = json_decode($response->getBody(), true);
  14689. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  14690. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  14691. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  14692. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  14693. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  14694. }
  14695. return [
  14696. 'fullContent' => $fullContent,
  14697. 'fullReasoningContent' => $fullReasoningContent,
  14698. 'usage' => $usage
  14699. ];
  14700. }
  14701. } catch (\Exception $e) {
  14702. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  14703. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  14704. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  14705. }
  14706. }
  14707. /**
  14708. * 火山引擎对话API流式输出
  14709. *
  14710. * @param Client $client HTTP客户端
  14711. * @param string $apiKey API密钥
  14712. * @param array $requestData 请求数据
  14713. * @return Generator
  14714. */
  14715. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  14716. {
  14717. try {
  14718. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  14719. 'headers' => [
  14720. 'Authorization' => 'Bearer ' . $apiKey,
  14721. 'Content-Type' => 'application/json',
  14722. ],
  14723. 'json' => $requestData,
  14724. 'stream' => true
  14725. ]);
  14726. $body = $response->getBody();
  14727. $buffer = '';
  14728. $fullContent = '';
  14729. $fullReasoningContent = '';
  14730. $usage = [];
  14731. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  14732. // 逐行读取流式响应
  14733. while (!$body->eof()) {
  14734. $chunk = $body->read(1024);
  14735. $buffer .= $chunk;
  14736. // 按行分割
  14737. $lines = explode("\n", $buffer);
  14738. $buffer = array_pop($lines);
  14739. foreach ($lines as $line) {
  14740. $line = trim($line);
  14741. if (empty($line)) {
  14742. continue;
  14743. }
  14744. // 检查是否是SSE数据行
  14745. if (strpos($line, 'data: ') !== 0) {
  14746. continue;
  14747. }
  14748. $data = substr($line, 6);
  14749. if ($data === '[DONE]') {
  14750. dLog('deepseek')->info('收到结束标记');
  14751. break 2;
  14752. }
  14753. try {
  14754. $json = json_decode($data, true);
  14755. if (json_last_error() !== JSON_ERROR_NONE) {
  14756. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  14757. continue;
  14758. }
  14759. if (isset($json['choices'][0]['delta'])) {
  14760. $delta = $json['choices'][0]['delta'];
  14761. // 处理思维链内容
  14762. if (isset($delta['reasoning_content'])) {
  14763. $fullReasoningContent .= $delta['reasoning_content'];
  14764. yield [
  14765. 'type' => 'reasoning',
  14766. 'content' => $delta['reasoning_content'],
  14767. 'full_reasoning' => $fullReasoningContent
  14768. ];
  14769. }
  14770. // 处理回答内容
  14771. if (isset($delta['content'])) {
  14772. $fullContent .= $delta['content'];
  14773. yield [
  14774. 'type' => 'content',
  14775. 'content' => $delta['content'],
  14776. ];
  14777. }
  14778. }
  14779. // 获取使用统计信息
  14780. if (isset($json['usage'])) {
  14781. $usage = $json['usage'];
  14782. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  14783. }
  14784. } catch (\Exception $e) {
  14785. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  14786. continue;
  14787. }
  14788. }
  14789. }
  14790. dLog('deepseek')->info('流式读取完成', [
  14791. 'content_length' => strlen($fullContent),
  14792. 'reasoning_length' => strlen($fullReasoningContent)
  14793. ]);
  14794. yield [
  14795. 'type' => 'done',
  14796. 'full_content' => $fullContent,
  14797. 'full_reasoning' => $fullReasoningContent,
  14798. 'usage' => $usage
  14799. ];
  14800. } catch (\Exception $e) {
  14801. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  14802. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  14803. throw $e;
  14804. }
  14805. }
  14806. /**
  14807. * 检查并创建图片生成任务
  14808. *
  14809. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  14810. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  14811. * @param string $nameKey 资源名称字段('role' 或 'scene')
  14812. * @param string $art_style 美术风格
  14813. * @return array 更新后的资源列表
  14814. */
  14815. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  14816. {
  14817. // 确保参数为数组
  14818. $merged_items = is_array($merged_items) ? $merged_items : [];
  14819. $global_items = is_array($global_items) ? $global_items : [];
  14820. // 构建全局资源映射表,用于快速查找
  14821. $global_map = [];
  14822. foreach ($global_items as $item) {
  14823. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  14824. if ($itemKey === '') {
  14825. continue;
  14826. }
  14827. $global_map[$itemKey] = $item;
  14828. }
  14829. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  14830. foreach ($merged_items as &$item) {
  14831. $item_name = getProp($item, $nameKey);
  14832. $item_description = getProp($item, 'description');
  14833. // $item_url = getProp($item, 'url');
  14834. // // 如果已有图片URL,跳过
  14835. // if (!empty($item_url)) {
  14836. // continue;
  14837. // }
  14838. // 如果是旁白角色,跳过
  14839. if ($nameKey === 'role' && $item_name === '旁白') {
  14840. continue;
  14841. }
  14842. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  14843. if ($itemKey === '') {
  14844. continue;
  14845. }
  14846. $need_create_task = false;
  14847. // 条件1:在全局资源中找不到匹配的名称
  14848. if (!isset($global_map[$itemKey])) {
  14849. $need_create_task = true;
  14850. } else {
  14851. // 条件2:名称匹配但描述或 pic_prompt 不一致
  14852. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  14853. $current_description = trim((string)$item_description);
  14854. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  14855. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  14856. // 如果 description 或 pic_prompt 有变化,需要重新生成
  14857. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  14858. $need_create_task = true;
  14859. }
  14860. }
  14861. // 如果需要创建任务,调用图片生成服务
  14862. if ($need_create_task) {
  14863. try {
  14864. // 优先使用 pic_prompt,如果没有则使用 description
  14865. $pic_prompt = getProp($item, 'pic_prompt');
  14866. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  14867. // 添加美术风格前缀
  14868. if ($art_style) {
  14869. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  14870. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  14871. $description = "{$prefix}:{$description}";
  14872. }
  14873. $params = [
  14874. 'prompt' => $description,
  14875. 'ref_img_urls' => []
  14876. ];
  14877. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  14878. $task_id = $task->id;
  14879. if ($task_id) {
  14880. $item['task_id'] = $task_id;
  14881. $item['task_status'] = 'processing';
  14882. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  14883. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  14884. }
  14885. } catch (\Exception $e) {
  14886. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  14887. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  14888. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  14889. // 不抛出异常,继续处理其他资源
  14890. }
  14891. }
  14892. }
  14893. return $merged_items;
  14894. }
  14895. /**
  14896. * 同步新出现的主体和场景到全局
  14897. *
  14898. * @param int $anime_id 动漫ID
  14899. * @param array $merged_roles 合并后的角色列表
  14900. * @param array $merged_scenes 合并后的场景列表
  14901. * @param array $global_roles 全局角色列表
  14902. * @param array $global_scenes 全局场景列表
  14903. * @return void
  14904. */
  14905. private function syncNewResourcesToGlobal(
  14906. int $anime_id,
  14907. array $merged_roles,
  14908. array $merged_scenes,
  14909. array $global_roles,
  14910. array $global_scenes
  14911. ): void {
  14912. // 构建全局角色映射表
  14913. $global_role_map = [];
  14914. foreach ($global_roles as $role) {
  14915. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  14916. if ($roleKey !== '') {
  14917. $global_role_map[$roleKey] = $role;
  14918. }
  14919. }
  14920. // 构建全局场景映射表
  14921. $global_scene_map = [];
  14922. foreach ($global_scenes as $scene) {
  14923. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  14924. if ($sceneKey !== '') {
  14925. $global_scene_map[$sceneKey] = $scene;
  14926. }
  14927. }
  14928. $need_update = false;
  14929. $new_global_roles = $global_roles;
  14930. $new_global_scenes = $global_scenes;
  14931. // 检查并添加新角色到全局
  14932. foreach ($merged_roles as $role) {
  14933. $role_name = getProp($role, 'role');
  14934. // 跳过旁白
  14935. if ($role_name === '旁白') {
  14936. continue;
  14937. }
  14938. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  14939. if ($roleKey === '') {
  14940. continue;
  14941. }
  14942. // 如果全局中不存在该角色,添加到全局
  14943. if (!isset($global_role_map[$roleKey])) {
  14944. $new_global_roles[] = [
  14945. 'role' => $role_name,
  14946. 'description' => getProp($role, 'description', ''),
  14947. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  14948. 'voice_name' => getProp($role, 'voice_name', ''),
  14949. 'voice_type' => getProp($role, 'voice_type', ''),
  14950. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  14951. 'url' => getProp($role, 'url', ''),
  14952. 'task_id' => getProp($role, 'task_id', ''),
  14953. 'task_status' => getProp($role, 'task_status', ''),
  14954. ];
  14955. $global_role_map[$roleKey] = true; // 标记已添加
  14956. $need_update = true;
  14957. dLog('deepseek')->info("新角色同步到全局", [
  14958. 'anime_id' => $anime_id,
  14959. 'role' => $role_name,
  14960. 'task_id' => getProp($role, 'task_id', ''),
  14961. ]);
  14962. }
  14963. // else {
  14964. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  14965. // $global_role = $global_role_map[$roleKey];
  14966. // if (is_array($global_role)) {
  14967. // $updated = false;
  14968. // $update_fields = [];
  14969. // // 检查描述是否更新
  14970. // $current_description = trim((string)getProp($role, 'description'));
  14971. // $global_description = trim((string)getProp($global_role, 'description'));
  14972. // if ($current_description !== '' && $current_description !== $global_description) {
  14973. // $updated = true;
  14974. // $update_fields[] = 'description';
  14975. // }
  14976. // // 检查pic_prompt是否更新
  14977. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  14978. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  14979. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  14980. // $updated = true;
  14981. // $update_fields[] = 'pic_prompt';
  14982. // }
  14983. // // 检查图片任务信息是否更新
  14984. // $current_task_id = getProp($role, 'task_id');
  14985. // $global_task_id = getProp($global_role, 'task_id');
  14986. // if ($current_task_id && $current_task_id !== $global_task_id) {
  14987. // $updated = true;
  14988. // $update_fields[] = 'task_id';
  14989. // }
  14990. // // 如果有更新,同步到全局
  14991. // if ($updated) {
  14992. // foreach ($new_global_roles as &$global_role_item) {
  14993. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  14994. // if ($global_role_key === $roleKey) {
  14995. // if (in_array('description', $update_fields)) {
  14996. // $global_role_item['description'] = $current_description;
  14997. // }
  14998. // if (in_array('pic_prompt', $update_fields)) {
  14999. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  15000. // }
  15001. // if (in_array('task_id', $update_fields)) {
  15002. // $global_role_item['task_id'] = $current_task_id;
  15003. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  15004. // $global_role_item['url'] = getProp($role, 'url', '');
  15005. // }
  15006. // break;
  15007. // }
  15008. // }
  15009. // $need_update = true;
  15010. // dLog('deepseek')->info("角色信息更新到全局", [
  15011. // 'anime_id' => $anime_id,
  15012. // 'role' => $role_name,
  15013. // 'update_fields' => implode(',', $update_fields),
  15014. // ]);
  15015. // }
  15016. // }
  15017. // }
  15018. }
  15019. // 检查并添加新场景到全局
  15020. foreach ($merged_scenes as $scene) {
  15021. $scene_name = getProp($scene, 'scene');
  15022. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  15023. if ($sceneKey === '') {
  15024. continue;
  15025. }
  15026. // 如果全局中不存在该场景,添加到全局
  15027. if (!isset($global_scene_map[$sceneKey])) {
  15028. $new_global_scenes[] = [
  15029. 'scene' => $scene_name,
  15030. 'description' => getProp($scene, 'description', ''),
  15031. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  15032. 'url' => getProp($scene, 'url', ''),
  15033. 'task_id' => getProp($scene, 'task_id', ''),
  15034. 'task_status' => getProp($scene, 'task_status', ''),
  15035. ];
  15036. $global_scene_map[$sceneKey] = true; // 标记已添加
  15037. $need_update = true;
  15038. dLog('deepseek')->info("新场景同步到全局", [
  15039. 'anime_id' => $anime_id,
  15040. 'scene' => $scene_name,
  15041. 'task_id' => getProp($scene, 'task_id', ''),
  15042. ]);
  15043. }
  15044. // else {
  15045. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  15046. // $global_scene = $global_scene_map[$sceneKey];
  15047. // if (is_array($global_scene)) {
  15048. // $updated = false;
  15049. // $update_fields = [];
  15050. // // 检查描述是否更新
  15051. // $current_description = trim((string)getProp($scene, 'description'));
  15052. // $global_description = trim((string)getProp($global_scene, 'description'));
  15053. // if ($current_description !== '' && $current_description !== $global_description) {
  15054. // $updated = true;
  15055. // $update_fields[] = 'description';
  15056. // }
  15057. // // 检查pic_prompt是否更新
  15058. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  15059. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  15060. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  15061. // $updated = true;
  15062. // $update_fields[] = 'pic_prompt';
  15063. // }
  15064. // // 检查图片任务信息是否更新
  15065. // $current_task_id = getProp($scene, 'task_id');
  15066. // $global_task_id = getProp($global_scene, 'task_id');
  15067. // if ($current_task_id && $current_task_id !== $global_task_id) {
  15068. // $updated = true;
  15069. // $update_fields[] = 'task_id';
  15070. // }
  15071. // // 如果有更新,同步到全局
  15072. // if ($updated) {
  15073. // foreach ($new_global_scenes as &$global_scene_item) {
  15074. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  15075. // if ($global_scene_key === $sceneKey) {
  15076. // if (in_array('description', $update_fields)) {
  15077. // $global_scene_item['description'] = $current_description;
  15078. // }
  15079. // if (in_array('pic_prompt', $update_fields)) {
  15080. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  15081. // }
  15082. // if (in_array('task_id', $update_fields)) {
  15083. // $global_scene_item['task_id'] = $current_task_id;
  15084. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  15085. // $global_scene_item['url'] = getProp($scene, 'url', '');
  15086. // }
  15087. // break;
  15088. // }
  15089. // }
  15090. // $need_update = true;
  15091. // dLog('deepseek')->info("场景信息更新到全局", [
  15092. // 'anime_id' => $anime_id,
  15093. // 'scene' => $scene_name,
  15094. // 'update_fields' => implode(',', $update_fields),
  15095. // ]);
  15096. // }
  15097. // }
  15098. // }
  15099. }
  15100. // 如果有新增或更新,更新数据库
  15101. if ($need_update) {
  15102. $update_data = [
  15103. 'roles' => json_encode($new_global_roles, 256),
  15104. 'scenes' => json_encode($new_global_scenes, 256),
  15105. 'updated_at' => date('Y-m-d H:i:s'),
  15106. ];
  15107. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  15108. if ($result !== false) {
  15109. dLog('deepseek')->info("全局角色和场景更新成功", [
  15110. 'anime_id' => $anime_id,
  15111. 'roles_count' => count($new_global_roles),
  15112. 'scenes_count' => count($new_global_scenes),
  15113. ]);
  15114. } else {
  15115. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  15116. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  15117. }
  15118. }
  15119. }
  15120. }