DeepSeekService.php 841 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427
  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. // Gemini 多模态(图片/视频 -> 文本)按模型预检积分;纯文本不扣费
  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 ($isGeminiModel && ($hasImageMedia || $hasVideoMedia)) {
  141. $chargeModality = $hasVideoMedia ? 'video' : 'image';
  142. $pricingModel = $this->geminiMultimodalPricingModel($model);
  143. if ($pricingModel !== '') {
  144. $chargePoints = $this->pointsService->getVideoChargePoints(['model' => $pricingModel]);
  145. if ($chargePoints > 0) {
  146. $this->pointsService->checkUserPointsEnough($chargePoints, $uid);
  147. }
  148. }
  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. // 纯文本(不扣积分):流式生成成功后仅记录 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. * 流式生成成功后再按 Gemini 多模态规则扣费
  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->chargeGeminiMultimodal($uid, $model, $points, $modality, getProp($chunk, 'usage', []));
  339. $charged = true;
  340. }
  341. }
  342. yield $chunk;
  343. }
  344. }
  345. /**
  346. * Gemini 多模态(图片/视频 -> 文本)成功后扣费并记录 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 chargeGeminiMultimodal(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('Gemini多模态计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  371. }
  372. }
  373. /**
  374. * Gemini 文本模型 ID 转 mp_video_models 中的按次计费模型 ID
  375. *
  376. * @param string $model
  377. * @return string
  378. */
  379. private function geminiMultimodalPricingModel(string $model): string
  380. {
  381. $map = [
  382. 'gemini-3.1-flash-image-preview-t' => 'gemini-3.1-flash',
  383. 'gemini-3.1-pro-preview' => 'gemini-3.1-pro',
  384. 'gemini-3-flash-preview' => 'gemini-3.0-flash',
  385. 'gemini-3-pro-preview' => 'gemini-3.0-pro',
  386. 'gemini-3.6-flash' => 'gemini-3.6-flash',
  387. ];
  388. return $map[$model] ?? '';
  389. }
  390. /**
  391. * 检查 OpenAI 风格消息中是否包含指定媒体类型
  392. *
  393. * @param array $messages
  394. * @param array $mediaTypes
  395. * @return bool
  396. */
  397. private function messagesContainMedia(array $messages, array $mediaTypes): bool
  398. {
  399. foreach ($messages as $message) {
  400. $content = getProp($message, 'content', '');
  401. if (!is_array($content)) {
  402. continue;
  403. }
  404. foreach ($content as $part) {
  405. if (is_array($part) && in_array(getProp($part, 'type', ''), $mediaTypes, true)) {
  406. return true;
  407. }
  408. }
  409. }
  410. return false;
  411. }
  412. public function createGenerateText($data) {
  413. $file = getProp($data, 'file');
  414. $episode_num = getProp($data, 'episode_num');
  415. $uid = Site::getUid();
  416. $cpid = Site::getCpid();
  417. if (!$file) {
  418. Utils::throwError('20003:请上传文件');
  419. }
  420. // 提取文件内容
  421. $content = $this->extractFileContent($file);
  422. if (!$content) {
  423. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  424. }
  425. // 拆分章节并校验章节总数、标题连续性
  426. if ($episode_num) {
  427. $this->validateGenerateTextChapters($content, (int)$episode_num);
  428. }
  429. // 获取原始文件名(不含扩展名)作为script_name
  430. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  431. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  432. // 字节安全剥离,不依赖服务器locale设置
  433. $originalName = $file->getClientOriginalName();
  434. $extension = $file->getClientOriginalExtension();
  435. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  436. ? substr($originalName, 0, -strlen($extension) - 1)
  437. : $originalName;
  438. if ($script_name === '') {
  439. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  440. }
  441. // 如果同一用户的剧本名存在则提示
  442. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  443. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  444. }
  445. // 插入数据到mp_scripts表
  446. $script_id = DB::table('mp_scripts')->insertGetId([
  447. 'script_name' => $script_name,
  448. 'user_id' => $uid,
  449. 'cpid' => $cpid,
  450. 'content' => $content,
  451. 'created_at' => date('Y-m-d H:i:s'),
  452. 'updated_at' => date('Y-m-d H:i:s')
  453. ]);
  454. return [
  455. 'script_id' => $script_id,
  456. 'script_name' => $script_name
  457. ];
  458. }
  459. /**
  460. * AI对话调用成功后的积分扣费(返回结果前调用)
  461. *
  462. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  463. *
  464. * @param int $uid
  465. * @param int $tokens
  466. * @param array $chargeInfo
  467. * @return void
  468. */
  469. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo): void
  470. {
  471. $result = $this->pointsService->recordChatCharge(
  472. $uid,
  473. $this->pointsService->getChatChargePoints((string)getProp($chargeInfo, 'model', '')),
  474. $tokens,
  475. $chargeInfo
  476. );
  477. if (empty($result['charged'])) {
  478. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  479. }
  480. }
  481. /**
  482. * 安全获取当前登录用户ID
  483. *
  484. * 命令行/队列等无用户上下文的场景返回 0,由记录方法自行跳过。
  485. *
  486. * @return int
  487. */
  488. private function getCurrentUid(): int
  489. {
  490. try {
  491. return (int)Site::getUid();
  492. } catch (\Throwable $e) {
  493. return 0;
  494. }
  495. }
  496. /**
  497. * 记录文生文 token 使用明细(仅记录,不扣积分)
  498. *
  499. * 用于不按积分计费的文生文接口;记录失败不影响主流程。
  500. *
  501. * @param int $uid 用户ID(0 时跳过)
  502. * @param int $tokens 消耗 token 数
  503. * @param array $chargeInfo 计费/来源信息(model、source 等)
  504. * @param string $apiType API 类型/模型标识
  505. * @return void
  506. */
  507. private function recordTextTokenOnly(int $uid, int $tokens, array $chargeInfo, string $apiType = ''): void
  508. {
  509. try {
  510. $this->pointsService->recordTokenOnlyDetail(
  511. $uid,
  512. $tokens,
  513. $chargeInfo,
  514. MpUserPointsDetail::TYPE_CHAT,
  515. $apiType,
  516. ''
  517. );
  518. } catch (\Throwable $e) {
  519. dLog('points')->warning('token明细记录异常(不影响主流程): ' . $e->getMessage(), [
  520. 'uid' => $uid,
  521. 'source' => $chargeInfo['source'] ?? '',
  522. ]);
  523. }
  524. }
  525. /**
  526. * 拆分剧本内容并校验章节总数与标题连续性
  527. *
  528. * @param string $content
  529. * @param int $episodeNum
  530. * @return void
  531. */
  532. private function validateGenerateTextChapters($content, $episodeNum)
  533. {
  534. $chapters = splitContent($content);
  535. if (count($chapters) !== $episodeNum) {
  536. Utils::throwError('20003:章节总数与集数不一致,请检查上传内容');
  537. }
  538. if (empty($chapters)) {
  539. return;
  540. }
  541. // 先尝试从标题正则中解析序号,确认是否从1开始连续递增
  542. $numbers = [];
  543. $unparsedIndex = null;
  544. foreach ($chapters as $index => $chapter) {
  545. $num = $this->parseChapterNumber($chapter['title']);
  546. if ($num === null) {
  547. $unparsedIndex = $index;
  548. break;
  549. }
  550. $numbers[] = $num;
  551. }
  552. if ($unparsedIndex === null) {
  553. $expected = 1;
  554. foreach ($numbers as $index => $num) {
  555. if ($num !== $expected) {
  556. $title = mb_substr(trim((string)$chapters[$index]['title']), 0, 40);
  557. Utils::throwError('20003:章节序号不连续:第' . ($index + 1) . '个章节“' . $title . '”序号为' . $num . ',预期为' . $expected);
  558. }
  559. $expected++;
  560. }
  561. return;
  562. }
  563. // 标题格式无法用正则确认时,交给模型分析
  564. $titles = array_column($chapters, 'title');
  565. $aiResult = $this->validateChapterSequenceByAI($titles);
  566. if ($aiResult['valid'] === false) {
  567. $badIndex = $aiResult['invalid_index'] ?: $unparsedIndex + 1;
  568. if (isset($chapters[$badIndex - 1])) {
  569. $title = mb_substr(trim((string)$chapters[$badIndex - 1]['title']), 0, 40);
  570. Utils::throwError('20003:章节序号不连续:第' . $badIndex . '个章节“' . $title . '”序号异常,请检查');
  571. }
  572. Utils::throwError('20003:章节序号不连续,请检查章节标题格式');
  573. }
  574. if ($aiResult['valid'] === null) {
  575. if (isset($chapters[$unparsedIndex])) {
  576. $title = mb_substr(trim((string)$chapters[$unparsedIndex]['title']), 0, 40);
  577. Utils::throwError('20003:无法确认第' . ($unparsedIndex + 1) . '个章节“' . $title . '”的章节序号,请检查标题格式');
  578. }
  579. Utils::throwError('20003:无法确认章节标题连续性,请检查章节标题格式');
  580. }
  581. }
  582. /**
  583. * 从章节标题中解析序号,支持阿拉伯数字和中文数字
  584. *
  585. * @param string $title
  586. * @return int|null
  587. */
  588. private function parseChapterNumber($title)
  589. {
  590. if (!preg_match('/第\s*([一二两三四五六七八九十百千万0-9]+)\s*[章节集幕场回话]/u', $title, $match)) {
  591. return null;
  592. }
  593. return $this->convertChineseNumber($match[1]);
  594. }
  595. /**
  596. * 中文数字转阿拉伯数字(支持到千)
  597. *
  598. * @param string $numStr
  599. * @return int
  600. */
  601. private function convertChineseNumber($numStr)
  602. {
  603. if (preg_match('/^\d+$/', $numStr)) {
  604. return (int)$numStr;
  605. }
  606. $map = [
  607. '零' => 0,
  608. '一' => 1,
  609. '二' => 2,
  610. '两' => 2,
  611. '三' => 3,
  612. '四' => 4,
  613. '五' => 5,
  614. '六' => 6,
  615. '七' => 7,
  616. '八' => 8,
  617. '九' => 9
  618. ];
  619. $total = 0;
  620. $section = 0;
  621. $length = mb_strlen($numStr);
  622. for ($i = 0; $i < $length; $i++) {
  623. $char = mb_substr($numStr, $i, 1);
  624. if (isset($map[$char])) {
  625. $section = $map[$char];
  626. } elseif ($char === '十') {
  627. $total += $section === 0 ? 10 : $section * 10;
  628. $section = 0;
  629. } elseif ($char === '百') {
  630. $total += $section === 0 ? 100 : $section * 100;
  631. $section = 0;
  632. } elseif ($char === '千') {
  633. $total += $section === 0 ? 1000 : $section * 1000;
  634. $section = 0;
  635. }
  636. }
  637. return $total + $section;
  638. }
  639. /**
  640. * 用 deepseek-v4-flash 非流式判断章节标题是否从1开始连续编号
  641. *
  642. * @param array $titles
  643. * @return array{valid: bool|null, invalid_index: int|null}
  644. */
  645. private function validateChapterSequenceByAI($titles)
  646. {
  647. $titleLines = [];
  648. foreach (array_slice($titles, 0, 200) as $index => $title) {
  649. $titleLines[] = ($index + 1) . '. ' . mb_substr(trim((string)$title), 0, 80);
  650. }
  651. $result = [
  652. 'valid' => null,
  653. 'invalid_index' => null
  654. ];
  655. $post_data = [
  656. 'model' => 'deepseek-v4-flash',
  657. 'messages' => [
  658. [
  659. 'role' => 'system',
  660. 'content' => '你是剧本章节校验助手。用户会给出章节标题列表,请判断这些标题中的编号是否从第1章/第1集开始连续递增,支持阿拉伯数字和中文数字。只输出 JSON,格式为 {"valid":true};若不连续则输出 {"valid":false,"invalid_index":N},其中 N 是第一个序号异常的章节序号(从1开始),不要输出其他内容。',
  661. ],
  662. [
  663. 'role' => 'user',
  664. 'content' => implode("\n", $titleLines),
  665. ],
  666. ],
  667. 'temperature' => 0,
  668. 'frequency_penalty' => 0,
  669. 'presence_penalty' => 0,
  670. 'stream' => false,
  671. ];
  672. try {
  673. $result = $this->chatOnly($post_data, 8);
  674. $content = trim((string)($result['fullContent'] ?? ''));
  675. if (preg_match('/"valid"\s*:\s*(true|false)/i', $content, $match)) {
  676. $result['valid'] = strtolower($match[1]) === 'true';
  677. }
  678. if (preg_match('/"invalid_index"\s*:\s*(\d+)/i', $content, $match)) {
  679. $result['invalid_index'] = (int)$match[1];
  680. }
  681. // 仅记录 token 使用明细(不扣积分):该校验为流程内的额外模型调用
  682. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  683. 'model' => 'deepseek-v4-flash',
  684. 'source' => 'validateChapterSequenceByAI',
  685. ], 'deepseek-v4-flash');
  686. } catch (\Exception $e) {
  687. dLog('deepseek')->error('章节连续性AI校验失败: ' . $e->getMessage());
  688. }
  689. return $result;
  690. }
  691. /**
  692. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  693. *
  694. * @param array $data 请求参数
  695. * @return array 返回结果数组
  696. */
  697. public function newGenerateText($data) {
  698. // 获取请求参数
  699. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  700. $messages = getProp($data, 'messages', []);
  701. $systemPrompt = getProp($data, 'system_prompt', '');
  702. $prompt = getProp($data, 'prompt', '');
  703. $images = getProp($data, 'images', []); // 支持多张图片
  704. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  705. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  706. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  707. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  708. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  709. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  710. $generateTaskId = 0;
  711. $uid = Site::getUid();
  712. if ($script_id > 0) {
  713. $existingTask = DB::table('mp_script_generate_tasks')
  714. ->where('uid', $uid)
  715. ->where('script_id', $script_id)
  716. ->orderByDesc('id')
  717. ->first();
  718. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  719. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  720. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  721. }
  722. }
  723. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  724. $originalContent = '';
  725. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  726. if ($script_id > 0) {
  727. $script = DB::table('mp_scripts')
  728. ->where('id', $script_id)
  729. ->where('is_deleted', 0)
  730. ->first();
  731. if (!$script) {
  732. Utils::throwError('20003:剧本不存在或已删除');
  733. }
  734. $originalContent = $script->content ?? '';
  735. if (empty($originalContent)) {
  736. Utils::throwError('20003:剧本内容为空');
  737. }
  738. $hasValidScript = true;
  739. // 将剧本内容添加到提示词前面
  740. if (!empty($originalContent)) {
  741. if (!empty($prompt)) {
  742. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  743. } else {
  744. $prompt = "原文内容:\n" . $originalContent;
  745. }
  746. }
  747. }
  748. // 新增: 如果提供了template_id,从数据库获取template_prompt
  749. if ($templateId > 0) {
  750. $template = DB::table('mp_prompt_templates')
  751. ->where('id', $templateId)
  752. ->where('is_deleted', 0)
  753. ->first();
  754. if (!$template) {
  755. Utils::throwError('20003:模板不存在或已删除');
  756. }
  757. $templatePrompt = $template->template_prompt ?? '';
  758. // 将模板提示词和用户输入的prompt组合
  759. // 模板为准,用户输入作为补充要求
  760. if (!empty($templatePrompt)) {
  761. if (!empty($prompt)) {
  762. $prompt = $templatePrompt . "\n\n" . $prompt;
  763. } else {
  764. $prompt = $templatePrompt;
  765. }
  766. }
  767. }
  768. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  769. if (empty($messages)) {
  770. $messages = [];
  771. // 添加系统提示词
  772. if (!empty($systemPrompt)) {
  773. $messages[] = [
  774. 'role' => 'system',
  775. 'content' => $systemPrompt
  776. ];
  777. }
  778. // 构建用户消息内容(支持文本+图片)
  779. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  780. $userMessage = [
  781. 'role' => 'user',
  782. 'content' => []
  783. ];
  784. // 添加文本内容
  785. if (!empty($prompt)) {
  786. $userMessage['content'][] = [
  787. 'type' => 'text',
  788. 'text' => $prompt
  789. ];
  790. }
  791. // 处理上传的图片文件
  792. if (!empty($images)) {
  793. if (!is_array($images)) {
  794. $images = [$images];
  795. }
  796. foreach ($images as $image) {
  797. $imageBase64 = $this->processImageToBase64($image);
  798. if ($imageBase64) {
  799. $userMessage['content'][] = [
  800. 'type' => 'image_url',
  801. 'image_url' => [
  802. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  803. ]
  804. ];
  805. }
  806. }
  807. }
  808. // 处理图片URL
  809. if (!empty($imageUrls)) {
  810. if (!is_array($imageUrls)) {
  811. $imageUrls = [$imageUrls];
  812. }
  813. foreach ($imageUrls as $url) {
  814. if (!empty($url)) {
  815. $userMessage['content'][] = [
  816. 'type' => 'image_url',
  817. 'image_url' => [
  818. 'url' => $url
  819. ]
  820. ];
  821. }
  822. }
  823. }
  824. // 如果只有文本内容,简化为字符串格式
  825. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  826. $userMessage['content'] = $userMessage['content'][0]['text'];
  827. }
  828. $messages[] = $userMessage;
  829. }
  830. }
  831. // 验证messages不为空
  832. if (empty($messages)) {
  833. Utils::throwError('20003:请提供有效的对话内容');
  834. }
  835. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  836. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  837. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  838. if ($model === 'deepseek-chat') {
  839. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  840. $model = 'deepseek-v4-flash';
  841. $thinkingMode = 'disabled';
  842. } elseif ($model === 'deepseek-reasoner') {
  843. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  844. $model = 'deepseek-v4-flash';
  845. $thinkingMode = 'enabled';
  846. }
  847. // 构建请求参数(非流式)
  848. $post_data = [
  849. 'model' => $model,
  850. 'messages' => $messages,
  851. 'temperature' => getProp($data, 'temperature', 1),
  852. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  853. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  854. 'thinking' => ['type' => $thinkingMode],
  855. 'stream' => false // 非流式输出
  856. ];
  857. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  858. // 添加可选参数
  859. if (isset($data['top_p'])) {
  860. $post_data['top_p'] = $data['top_p'];
  861. }
  862. // 新增: 根据response_format设置响应格式
  863. if ($responseFormat === 'json') {
  864. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  865. $hasJsonKeyword = false;
  866. foreach ($post_data['messages'] as $message) {
  867. if (isset($message['content'])) {
  868. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  869. if (stripos($content, 'json') !== false) {
  870. $hasJsonKeyword = true;
  871. break;
  872. }
  873. }
  874. }
  875. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  876. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  877. if (!$hasJsonKeyword) {
  878. $lastMessageIndex = count($post_data['messages']) - 1;
  879. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  880. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  881. // 如果content是字符串,直接追加
  882. if (is_string($lastContent)) {
  883. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  884. }
  885. // 如果content是数组(包含文本和图片),在文本部分追加
  886. else if (is_array($lastContent)) {
  887. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  888. if ($contentPart['type'] === 'text') {
  889. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  890. break;
  891. }
  892. }
  893. }
  894. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  895. }
  896. }
  897. // 设置response_format参数(所有支持的模型)
  898. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  899. // DeepSeek模型
  900. $post_data['response_format'] = ['type' => 'json_object'];
  901. } else if (in_array($model, $this->gpt_text_models)) {
  902. // GPT模型
  903. $post_data['response_format'] = ['type' => 'json_object'];
  904. } else if (in_array($model, $this->valid_text_models)) {
  905. // 火山引擎模型
  906. $post_data['response_format'] = ['type' => 'json_object'];
  907. }
  908. }
  909. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  910. if ($script_id > 0) {
  911. $uid = Site::getUid();
  912. // 创建新的生成任务
  913. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  914. 'uid' => $uid,
  915. 'script_id' => $script_id,
  916. 'sequence' => $sequence,
  917. 'status' => 'processing',
  918. 'prompt' => getProp($data, 'prompt', ''),
  919. 'started_at' => date('Y-m-d H:i:s'),
  920. 'created_at' => date('Y-m-d H:i:s'),
  921. 'updated_at' => date('Y-m-d H:i:s')
  922. ]);
  923. }
  924. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  925. if ($hasValidScript) {
  926. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  927. }
  928. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  929. try {
  930. $aiResult = null;
  931. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  932. // DeepSeek 官方模型使用现有的 chatOnly 方法
  933. $result = $this->chatOnly($post_data);
  934. // 记录实际使用的模型
  935. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  936. $aiResult = [
  937. 'content' => $result['fullContent'],
  938. 'reasoning_content' => $result['fullReasoningContent'],
  939. 'usage' => $result['usage'],
  940. 'model' => $model,
  941. 'finish_reason' => 'stop'
  942. ];
  943. } else if (in_array($model, $this->gpt_text_models)) {
  944. // GPT 模型使用现有的 gpt54ChatOnly 方法
  945. $result = $this->gpt54ChatOnly($post_data);
  946. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  947. $aiResult = [
  948. 'content' => $result['fullContent'],
  949. 'reasoning_content' => '',
  950. 'usage' => $result['usage'],
  951. 'model' => $model,
  952. 'finish_reason' => 'stop'
  953. ];
  954. } else if (in_array($model, $this->gemini_text_models)) {
  955. // Gemini 模型使用 Gemini API(非流式)
  956. $result = $this->geminiChatOnly($post_data, $model);
  957. dLog('deepseek')->info('newGenerateText使用Gemini模型', ['requested_model' => $model]);
  958. $aiResult = [
  959. 'content' => $result['fullContent'],
  960. 'reasoning_content' => $result['fullReasoningContent'] ?? '',
  961. 'usage' => $result['usage'],
  962. 'model' => $model,
  963. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  964. ];
  965. } else if (in_array($model, $this->valid_text_models)) {
  966. // 火山引擎支持的模型使用火山引擎 API(非流式)
  967. $post_data['stream'] = false;
  968. $result = $this->volcEngineChatCompletion($post_data);
  969. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  970. 'requested_model' => $model,
  971. 'result_keys' => array_keys($result),
  972. 'has_fullContent' => isset($result['fullContent']),
  973. 'has_content' => isset($result['content'])
  974. ]);
  975. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  976. $aiResult = [
  977. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  978. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  979. 'usage' => $result['usage'] ?? [],
  980. 'model' => $model,
  981. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  982. ];
  983. } else {
  984. Utils::throwError('20003:不支持的模型: ' . $model);
  985. }
  986. } catch (\Exception $e) {
  987. // 生成失败,更新任务状态
  988. if ($generateTaskId) {
  989. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  990. 'status' => 'failed',
  991. 'error_message' => $e->getMessage(),
  992. 'completed_at' => date('Y-m-d H:i:s'),
  993. 'updated_at' => date('Y-m-d H:i:s')
  994. ]);
  995. }
  996. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  997. }
  998. // 生成成功,更新任务状态
  999. if ($generateTaskId && $aiResult) {
  1000. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1001. 'status' => 'success',
  1002. 'result' => getProp($aiResult, 'content', ''),
  1003. 'completed_at' => date('Y-m-d H:i:s'),
  1004. 'updated_at' => date('Y-m-d H:i:s')
  1005. ]);
  1006. $aiResult['generate_task_id'] = $generateTaskId;
  1007. }
  1008. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  1009. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  1010. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  1011. 'model' => $model,
  1012. 'script_id' => $script_id,
  1013. 'sequence' => $sequence,
  1014. 'source' => 'newGenerateText',
  1015. ]);
  1016. }
  1017. // 新增: 如果提供了script_id,保存对话记录
  1018. if ($script_id > 0 && $aiResult) {
  1019. try {
  1020. $uid = Site::getUid();
  1021. $now = now();
  1022. // 获取用户原始的prompt(不包含剧本内容)
  1023. $originalPrompt = getProp($data, 'prompt', '');
  1024. $recordsToInsert = [
  1025. [
  1026. 'uid' => $uid,
  1027. 'script_id' => $script_id,
  1028. 'sequence' => $sequence,
  1029. 'role' => 'user',
  1030. 'content' => $originalPrompt,
  1031. 'created_at' => $now,
  1032. 'updated_at' => $now,
  1033. ],
  1034. [
  1035. 'uid' => $uid,
  1036. 'script_id' => $script_id,
  1037. 'sequence' => $sequence,
  1038. 'role' => 'assistant',
  1039. 'content' => $aiResult['content'],
  1040. 'created_at' => $now,
  1041. 'updated_at' => $now,
  1042. ]
  1043. ];
  1044. DB::table('mp_script_records')->insert($recordsToInsert);
  1045. // 获取刚插入的记录ID(假设按插入顺序返回)
  1046. $insertedRecords = DB::table('mp_script_records')
  1047. ->where('uid', $uid)
  1048. ->where('script_id', $script_id)
  1049. ->where('sequence', $sequence)
  1050. ->orderBy('id', 'desc')
  1051. ->limit(2)
  1052. ->get()
  1053. ->map(function ($record) {
  1054. return [
  1055. 'rid' => $record->id,
  1056. 'script_id' => $record->script_id,
  1057. 'sequence' => $record->sequence,
  1058. 'role' => $record->role,
  1059. 'content' => $record->content,
  1060. 'created_at' => $record->created_at,
  1061. ];
  1062. })
  1063. ->reverse()
  1064. ->values()
  1065. ->toArray();
  1066. // 将记录信息添加到返回结果中
  1067. $aiResult['records'] = $insertedRecords;
  1068. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  1069. } catch (\Exception $e) {
  1070. // 记录错误但不影响主流程
  1071. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  1072. }
  1073. }
  1074. return $aiResult;
  1075. }
  1076. /**
  1077. * 通用 Gemini 文生文方法(支持流式和非流式)
  1078. *
  1079. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  1080. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  1081. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  1082. * system_prompt 系统提示词(可选)
  1083. * prompt 用户提示词(可选)
  1084. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  1085. * image_urls 图片/视频URL列表(可选,同上)
  1086. * temperature 温度(可选,默认 1)
  1087. * top_p 核采样(可选)
  1088. * max_tokens 最大输出 token(可选,默认 8192)
  1089. * response_format text/json(可选)
  1090. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  1091. * thinking_budget 思考预算(可选,默认 20)
  1092. * stream 是否流式(可选,默认 false)
  1093. *
  1094. * @param array $data 请求参数
  1095. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  1096. */
  1097. public function geminiGenerateText($data) {
  1098. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  1099. $isStream = (bool)getProp($data, 'stream', false);
  1100. if (!in_array($model, $this->gemini_text_models)) {
  1101. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  1102. }
  1103. $requestData = $this->buildGeminiRequestBody($data, $model);
  1104. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  1105. if ($isStream) {
  1106. // 流式返回生成器,成功后记录 token 使用明细(不扣积分)
  1107. return $this->wrapGenerateTextTokenRecord(
  1108. $this->geminiStreamResponse($requestData, $model),
  1109. $this->getCurrentUid(),
  1110. $model,
  1111. 'geminiGenerateText'
  1112. );
  1113. }
  1114. // 非流式:成功后记录 token 使用明细(不扣积分)
  1115. $result = $this->geminiChatOnly($requestData, $model);
  1116. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  1117. 'model' => $model,
  1118. 'source' => 'geminiGenerateText',
  1119. ], $model);
  1120. return $result;
  1121. }
  1122. /**
  1123. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  1124. */
  1125. private function geminiMediaMaxBytes() {
  1126. return 14 * 1024 * 1024;
  1127. }
  1128. /**
  1129. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  1130. */
  1131. private function buildGeminiRequestBody($data, $model) {
  1132. $messages = getProp($data, 'messages', []);
  1133. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  1134. if (empty($messages)) {
  1135. $systemPrompt = getProp($data, 'system_prompt', '');
  1136. $prompt = getProp($data, 'prompt', '');
  1137. $images = getProp($data, 'images', []);
  1138. $imageUrls = getProp($data, 'image_urls', []);
  1139. $messages = [];
  1140. if (!empty($systemPrompt)) {
  1141. $messages[] = [
  1142. 'role' => 'system',
  1143. 'content' => $systemPrompt
  1144. ];
  1145. }
  1146. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1147. $userMessage = ['role' => 'user', 'content' => []];
  1148. if (!empty($prompt)) {
  1149. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  1150. }
  1151. if (!empty($images)) {
  1152. if (!is_array($images)) {
  1153. $images = [$images];
  1154. }
  1155. foreach ($images as $image) {
  1156. $inlineData = $this->processMediaToInlineData($image);
  1157. if ($inlineData) {
  1158. $userMessage['content'][] = [
  1159. 'type' => 'image',
  1160. 'inline_data' => $inlineData
  1161. ];
  1162. }
  1163. }
  1164. }
  1165. if (!empty($imageUrls)) {
  1166. if (!is_array($imageUrls)) {
  1167. $imageUrls = [$imageUrls];
  1168. }
  1169. foreach ($imageUrls as $url) {
  1170. if (!empty($url)) {
  1171. $inlineData = $this->processMediaToInlineData($url);
  1172. if ($inlineData) {
  1173. $userMessage['content'][] = [
  1174. 'type' => 'image',
  1175. 'inline_data' => $inlineData
  1176. ];
  1177. }
  1178. }
  1179. }
  1180. }
  1181. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  1182. $userMessage['content'] = $userMessage['content'][0]['text'];
  1183. }
  1184. $messages[] = $userMessage;
  1185. }
  1186. }
  1187. if (empty($messages)) {
  1188. Utils::throwError('20003:请提供有效的对话内容');
  1189. }
  1190. // 转换为 Gemini contents 格式
  1191. $systemInstruction = '';
  1192. $contents = [];
  1193. foreach ($messages as $message) {
  1194. $role = getProp($message, 'role', 'user');
  1195. $content = getProp($message, 'content', '');
  1196. if ($role === 'system') {
  1197. if (is_array($content)) {
  1198. $systemInstruction = $this->extractGeminiTextFromParts($content);
  1199. } else {
  1200. $systemInstruction = (string)$content;
  1201. }
  1202. continue;
  1203. }
  1204. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  1205. $parts = [];
  1206. if (is_array($content)) {
  1207. foreach ($content as $part) {
  1208. $partType = getProp($part, 'type', 'text');
  1209. if ($partType === 'text') {
  1210. $text = (string)getProp($part, 'text', '');
  1211. if ($text !== '') {
  1212. $parts[] = ['text' => $text];
  1213. }
  1214. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  1215. if (in_array($partType, ['image_url', 'video_url'])) {
  1216. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  1217. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  1218. } elseif (isset($part['inline_data'])) {
  1219. // 已处理过的 inline_data 直接使用
  1220. $parts[] = ['inline_data' => $part['inline_data']];
  1221. continue;
  1222. } else {
  1223. $url = '';
  1224. }
  1225. $inlineData = $this->processMediaToInlineData($url);
  1226. if ($inlineData) {
  1227. $parts[] = ['inline_data' => $inlineData];
  1228. }
  1229. }
  1230. }
  1231. } else {
  1232. $text = (string)$content;
  1233. if ($text !== '') {
  1234. $parts[] = ['text' => $text];
  1235. }
  1236. }
  1237. if (!empty($parts)) {
  1238. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  1239. }
  1240. }
  1241. if (empty($contents)) {
  1242. Utils::throwError('20003:请提供有效的对话内容');
  1243. }
  1244. // 构建生成配置
  1245. $generationConfig = [];
  1246. if (getProp($data, 'temperature', null) !== null) {
  1247. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  1248. }
  1249. if (getProp($data, 'top_p', null) !== null) {
  1250. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  1251. }
  1252. if (getProp($data, 'frequency_penalty', null) !== null) {
  1253. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  1254. }
  1255. if (getProp($data, 'presence_penalty', null) !== null) {
  1256. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  1257. }
  1258. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  1259. if ($maxOutputTokens <= 0) {
  1260. $maxOutputTokens = 8192;
  1261. }
  1262. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  1263. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  1264. $maxOutputTokens = 32768;
  1265. }
  1266. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  1267. // response_format 映射:text -> text/plain,json -> application/json
  1268. $responseFormat = getProp($data, 'response_format', 'text');
  1269. if (is_array($responseFormat)) {
  1270. $responseFormat = getProp($responseFormat, 'type', 'text');
  1271. }
  1272. if (in_array($responseFormat, ['json', 'json_object'])) {
  1273. $generationConfig['responseMimeType'] = 'application/json';
  1274. } else {
  1275. $generationConfig['responseMimeType'] = 'text/plain';
  1276. }
  1277. $requestData = [
  1278. 'contents' => $contents,
  1279. 'generationConfig' => $generationConfig,
  1280. ];
  1281. if ($systemInstruction !== '') {
  1282. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  1283. }
  1284. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  1285. $thinkingMode = getProp($data, 'thinking', null);
  1286. if (is_array($thinkingMode)) {
  1287. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  1288. }
  1289. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  1290. if ($thinkingMode === null) {
  1291. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  1292. }
  1293. if ($thinkingMode === 'enabled') {
  1294. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  1295. if ($thinkingBudget <= 0) {
  1296. $thinkingBudget = 20;
  1297. }
  1298. $requestData['generationConfig']['thinkingConfig'] = [
  1299. 'thinkingBudget' => $thinkingBudget
  1300. ];
  1301. } elseif ($defaultThinking) {
  1302. // 该模型仅支持思考模式,传 0 会返回 400
  1303. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  1304. } else {
  1305. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  1306. }
  1307. return $requestData;
  1308. }
  1309. /**
  1310. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  1311. *
  1312. * 模型名 -> env 变量名映射:
  1313. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  1314. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  1315. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  1316. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  1317. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  1318. */
  1319. private function getGeminiApiKey($model) {
  1320. $map = [
  1321. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  1322. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  1323. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  1324. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  1325. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  1326. ];
  1327. if (isset($map[$model])) {
  1328. $key = env($map[$model]);
  1329. if (!empty($key)) {
  1330. return $key;
  1331. }
  1332. }
  1333. return env('GEMINI_API_KEY', '');
  1334. }
  1335. /**
  1336. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  1337. */
  1338. private function geminiChatOnly($requestData, $model) {
  1339. $apiKey = $this->getGeminiApiKey($model);
  1340. if (empty($apiKey)) {
  1341. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1342. }
  1343. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1344. if (isset($requestData['messages'])) {
  1345. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1346. }
  1347. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1348. . '/models/' . $model . ':generateContent';
  1349. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1350. $headers = [
  1351. 'Authorization' => 'Bearer ' . $apiKey,
  1352. 'Content-Type' => 'application/json'
  1353. ];
  1354. $maxRetries = $this->gptRetryTimes();
  1355. $interval = $this->gptRetryInterval();
  1356. $attempt = 0;
  1357. while (true) {
  1358. try {
  1359. $response = $client->post($url, [
  1360. 'json' => $requestData,
  1361. 'headers' => $headers
  1362. ]);
  1363. $responseArr = json_decode($response->getBody()->getContents(), true);
  1364. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  1365. $fullContent = $this->extractGeminiContent($responseArr);
  1366. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  1367. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  1368. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  1369. ? $responseArr['candidates'][0]['finishReason']
  1370. : '';
  1371. return [
  1372. 'fullContent' => $fullContent,
  1373. 'fullReasoningContent' => $fullReasoningContent,
  1374. 'usage' => $usage,
  1375. 'finish_reason' => $finishReason
  1376. ];
  1377. } catch (\Exception $e) {
  1378. $retryable = true;
  1379. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1380. $status = $e->getResponse()->getStatusCode();
  1381. $retryable = $status >= 500 || $status == 429;
  1382. }
  1383. if (!$retryable || $attempt >= $maxRetries) {
  1384. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  1385. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  1386. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  1387. }
  1388. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  1389. 'retry' => $attempt + 1,
  1390. 'max_retries' => $maxRetries,
  1391. 'error' => $e->getMessage()
  1392. ]);
  1393. sleep($interval);
  1394. $attempt++;
  1395. }
  1396. }
  1397. }
  1398. /**
  1399. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  1400. */
  1401. private function geminiStreamResponse($requestData, $model) {
  1402. $apiKey = $this->getGeminiApiKey($model);
  1403. if (empty($apiKey)) {
  1404. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1405. }
  1406. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1407. if (isset($requestData['messages'])) {
  1408. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1409. }
  1410. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1411. . '/models/' . $model . ':generateContent?alt=sse';
  1412. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1413. $headers = [
  1414. 'Authorization' => 'Bearer ' . $apiKey,
  1415. 'Content-Type' => 'application/json'
  1416. ];
  1417. try {
  1418. $response = $client->post($url, [
  1419. 'json' => $requestData,
  1420. 'headers' => $headers,
  1421. 'stream' => true
  1422. ]);
  1423. $body = $response->getBody();
  1424. $fullContent = '';
  1425. $fullReasoningContent = '';
  1426. $usage = [];
  1427. $buffer = '';
  1428. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1429. while (!$body->eof()) {
  1430. $chunk = $body->read(1024);
  1431. $buffer .= $chunk;
  1432. $lines = explode("\n", $buffer);
  1433. $buffer = array_pop($lines);
  1434. foreach ($lines as $line) {
  1435. $line = trim($line);
  1436. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1437. continue;
  1438. }
  1439. $data = substr($line, 6);
  1440. if ($data === '[DONE]') {
  1441. break 2;
  1442. }
  1443. try {
  1444. $json = json_decode($data, true);
  1445. if (json_last_error() !== JSON_ERROR_NONE) {
  1446. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1447. continue;
  1448. }
  1449. // 思考内容(thoughts)
  1450. $thoughts = $this->extractGeminiThoughts($json);
  1451. if ($thoughts !== '') {
  1452. $fullReasoningContent .= $thoughts;
  1453. yield [
  1454. 'type' => 'reasoning',
  1455. 'content' => $thoughts,
  1456. 'full_reasoning' => $fullReasoningContent
  1457. ];
  1458. }
  1459. // 回答内容
  1460. $partText = $this->extractGeminiContent($json);
  1461. if ($partText !== '') {
  1462. $fullContent .= $partText;
  1463. yield [
  1464. 'type' => 'content',
  1465. 'content' => $partText,
  1466. ];
  1467. }
  1468. // 使用统计
  1469. if (isset($json['usageMetadata'])) {
  1470. $usage = $json['usageMetadata'];
  1471. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  1472. }
  1473. } catch (\Exception $e) {
  1474. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1475. continue;
  1476. }
  1477. }
  1478. }
  1479. dLog('deepseek')->info('Gemini流式读取完成', [
  1480. 'content_length' => strlen($fullContent),
  1481. 'reasoning_length' => strlen($fullReasoningContent)
  1482. ]);
  1483. yield [
  1484. 'type' => 'done',
  1485. 'full_content' => $fullContent,
  1486. 'full_reasoning' => $fullReasoningContent,
  1487. 'usage' => $usage
  1488. ];
  1489. } catch (\Exception $e) {
  1490. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  1491. yield [
  1492. 'type' => 'error',
  1493. 'msg' => $e->getMessage(),
  1494. 'code' => $e->getCode()
  1495. ];
  1496. }
  1497. }
  1498. /**
  1499. * 从 Gemini 响应中提取回答文本
  1500. */
  1501. private function extractGeminiContent($responseArr) {
  1502. $text = '';
  1503. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  1504. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  1505. if (isset($part['text'])) {
  1506. $text .= $part['text'];
  1507. }
  1508. }
  1509. }
  1510. return $text;
  1511. }
  1512. /**
  1513. * 从 Gemini 响应中提取思考内容
  1514. */
  1515. private function extractGeminiReasoningContent($responseArr) {
  1516. $reasoning = '';
  1517. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1518. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1519. if (isset($thought['text'])) {
  1520. $reasoning .= $thought['text'];
  1521. }
  1522. }
  1523. }
  1524. return $reasoning;
  1525. }
  1526. /**
  1527. * 从 Gemini 流式响应中提取本次增量思考内容
  1528. */
  1529. private function extractGeminiThoughts($responseArr) {
  1530. $thoughts = '';
  1531. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1532. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1533. if (isset($thought['text'])) {
  1534. $thoughts .= $thought['text'];
  1535. }
  1536. }
  1537. }
  1538. return $thoughts;
  1539. }
  1540. /**
  1541. * 提取消息数组中的纯文本
  1542. */
  1543. private function extractGeminiTextFromParts($parts) {
  1544. $text = '';
  1545. if (is_array($parts)) {
  1546. foreach ($parts as $part) {
  1547. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  1548. $text .= (string)getProp($part, 'text', '');
  1549. }
  1550. }
  1551. }
  1552. return $text;
  1553. }
  1554. /**
  1555. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  1556. *
  1557. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  1558. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  1559. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  1560. *
  1561. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  1562. * @return array|null ['mime_type' => string, 'data' => string]
  1563. */
  1564. private function processMediaToInlineData($media) {
  1565. if (empty($media)) {
  1566. return null;
  1567. }
  1568. $localPath = null;
  1569. $isTempFile = false;
  1570. try {
  1571. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  1572. if (is_string($media) && strpos($media, 'data:') === 0) {
  1573. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  1574. return [
  1575. 'mime_type' => $matches[1],
  1576. 'data' => $matches[2]
  1577. ];
  1578. }
  1579. return null;
  1580. }
  1581. // 2. 获取本地文件路径
  1582. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  1583. $localPath = $this->downloadMediaToTemp($media);
  1584. $isTempFile = true;
  1585. } elseif (is_string($media)) {
  1586. $localPath = $media;
  1587. } else {
  1588. // Laravel UploadedFile 对象
  1589. $localPath = $media->getRealPath();
  1590. }
  1591. if (!$localPath || !file_exists($localPath)) {
  1592. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  1593. return null;
  1594. }
  1595. $fileSize = filesize($localPath);
  1596. $maxBytes = $this->geminiMediaMaxBytes();
  1597. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  1598. $mimeType = $this->detectMediaMime($localPath);
  1599. $isVideo = strpos($mimeType, 'video/') === 0;
  1600. $needCompress = $fileSize > $maxBytes;
  1601. $duration = 0;
  1602. if ($isVideo) {
  1603. $duration = $this->getMediaDuration($localPath);
  1604. if ($duration > 300) {
  1605. $needCompress = true;
  1606. }
  1607. }
  1608. $finalPath = $localPath;
  1609. $compressedPath = null;
  1610. if ($needCompress && $this->ffmpegAvailable()) {
  1611. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  1612. if ($compressed && file_exists($compressed)) {
  1613. $compressedPath = $compressed;
  1614. if (filesize($compressed) < $fileSize || $isVideo) {
  1615. $finalPath = $compressed;
  1616. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  1617. } else {
  1618. @unlink($compressed);
  1619. $compressedPath = null;
  1620. }
  1621. }
  1622. }
  1623. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  1624. $finalSize = filesize($finalPath);
  1625. if ($finalSize > $maxBytes) {
  1626. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  1627. 'path' => $localPath,
  1628. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  1629. 'limit_mb' => 14
  1630. ]);
  1631. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  1632. }
  1633. // 兜底校验:视频时长超过5分钟且未能压缩成功
  1634. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  1635. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  1636. }
  1637. $data = base64_encode(file_get_contents($finalPath));
  1638. return [
  1639. 'mime_type' => $mimeType,
  1640. 'data' => $data
  1641. ];
  1642. } catch (\App\Exceptions\ApiException $e) {
  1643. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  1644. throw $e;
  1645. } catch (\Exception $e) {
  1646. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  1647. return null;
  1648. } finally {
  1649. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  1650. @unlink($compressedPath);
  1651. }
  1652. if ($isTempFile && $localPath && file_exists($localPath)) {
  1653. @unlink($localPath);
  1654. }
  1655. }
  1656. }
  1657. /**
  1658. * 下载远程多媒体到临时目录
  1659. *
  1660. * @return string|null 本地临时文件路径
  1661. */
  1662. private function downloadMediaToTemp($url) {
  1663. try {
  1664. $tempDir = storage_path('app/temp/gemini');
  1665. if (!is_dir($tempDir)) {
  1666. mkdir($tempDir, 0775, true);
  1667. }
  1668. $extension = 'tmp';
  1669. $pathInfo = parse_url($url, PHP_URL_PATH);
  1670. if ($pathInfo) {
  1671. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  1672. if ($ext && strlen($ext) <= 10) {
  1673. $extension = strtolower($ext);
  1674. }
  1675. }
  1676. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  1677. $client = new Client(['timeout' => 300, 'verify' => false]);
  1678. $response = $client->get($url, ['sink' => $tmpFile]);
  1679. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  1680. @unlink($tmpFile);
  1681. return null;
  1682. }
  1683. return $tmpFile;
  1684. } catch (\Exception $e) {
  1685. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  1686. return null;
  1687. }
  1688. }
  1689. /**
  1690. * 检测多媒体文件 MIME 类型
  1691. */
  1692. private function detectMediaMime($filePath) {
  1693. $imageInfo = @getimagesize($filePath);
  1694. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  1695. return $imageInfo['mime'];
  1696. }
  1697. // 视频按扩展名粗略判断
  1698. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  1699. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  1700. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  1701. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  1702. if (isset($videoExts[$ext])) {
  1703. return $videoExts[$ext];
  1704. }
  1705. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  1706. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  1707. if (isset($imageExts[$ext])) {
  1708. return $imageExts[$ext];
  1709. }
  1710. return 'application/octet-stream';
  1711. }
  1712. /**
  1713. * 获取多媒体时长(秒),非视频或失败返回 0
  1714. */
  1715. private function getMediaDuration($filePath) {
  1716. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  1717. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  1718. $output = trim((string)shell_exec($cmd));
  1719. $duration = (float)$output;
  1720. return $duration > 0 ? $duration : 0;
  1721. }
  1722. /**
  1723. * 检查 ffmpeg 是否可用
  1724. */
  1725. private function ffmpegAvailable() {
  1726. static $available = null;
  1727. if ($available !== null) {
  1728. return $available;
  1729. }
  1730. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1731. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  1732. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  1733. $available = false;
  1734. return $available;
  1735. }
  1736. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  1737. $output = shell_exec($cmd);
  1738. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  1739. return $available;
  1740. }
  1741. /**
  1742. * 使用 ffmpeg 压缩多媒体文件
  1743. *
  1744. * @param string $inputFile 输入文件路径
  1745. * @param bool $isVideo 是否为视频
  1746. * @param float $duration 视频时长(秒),非视频传 0
  1747. * @return string|null 压缩后的文件路径,失败返回 null
  1748. */
  1749. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  1750. try {
  1751. $tempDir = storage_path('app/temp/gemini');
  1752. if (!is_dir($tempDir)) {
  1753. mkdir($tempDir, 0775, true);
  1754. }
  1755. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1756. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  1757. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  1758. if ($isVideo) {
  1759. // 视频:时长超过5分钟则加速压缩到5分钟以内
  1760. $speedFactor = 1.0;
  1761. if ($duration > 300) {
  1762. $speedFactor = $duration / 300;
  1763. }
  1764. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  1765. $finalDuration = $duration / max(1.0, $speedFactor);
  1766. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  1767. $targetBitrate = max(300, min(6000, $targetBitrate));
  1768. $filters = [];
  1769. $filters[] = 'scale=min(1280,iw):-2';
  1770. $filters[] = 'fps=24';
  1771. if ($speedFactor > 1.0) {
  1772. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  1773. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  1774. $fullCount = (int)ceil($speedFactor / 2.0);
  1775. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1776. if ($lastTempo < 0.5) {
  1777. $fullCount++;
  1778. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1779. }
  1780. for ($i = 0; $i < $fullCount; $i++) {
  1781. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  1782. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  1783. }
  1784. }
  1785. $filterStr = implode(',', $filters);
  1786. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  1787. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  1788. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  1789. } else {
  1790. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  1791. $imageInfo = @getimagesize($inputFile);
  1792. $scaleW = 2048;
  1793. $scaleH = 2048;
  1794. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  1795. if ($imageInfo[0] >= $imageInfo[1]) {
  1796. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  1797. $scaleW = 2048;
  1798. } else {
  1799. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  1800. $scaleH = 2048;
  1801. }
  1802. }
  1803. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  1804. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  1805. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  1806. }
  1807. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  1808. $output = shell_exec($cmd);
  1809. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  1810. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  1811. 'input' => $inputFile,
  1812. 'output' => $output
  1813. ]);
  1814. @unlink($outputFile);
  1815. return null;
  1816. }
  1817. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  1818. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  1819. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  1820. ]);
  1821. return $outputFile;
  1822. } catch (\Exception $e) {
  1823. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  1824. return null;
  1825. }
  1826. }
  1827. /**
  1828. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  1829. *
  1830. * @param array $data
  1831. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  1832. */
  1833. public function getScriptGenerateTasks($data) {
  1834. $uid = Site::getUid();
  1835. return DB::table('mp_script_generate_tasks as t')
  1836. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  1837. ->where('t.uid', $uid)
  1838. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  1839. ->orderByDesc('t.id')
  1840. ->paginate(15);
  1841. }
  1842. public function saveScriptChatHistory($data) {
  1843. $uid = Site::getUid();
  1844. $rid = getProp($data, 'rid');
  1845. $script_id = getProp($data, 'script_id');
  1846. $sequence = getProp($data, 'sequence', 0);
  1847. $content = getProp($data, 'content');
  1848. if (!$rid) {
  1849. Utils::throwError('20003:请选择对话记录ID');
  1850. }
  1851. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  1852. if (!$record) {
  1853. Utils::throwError('20003:对话记录不存在');
  1854. }
  1855. if (!$script_id) {
  1856. Utils::throwError('20003:请选择剧本');
  1857. }
  1858. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  1859. if (!$script) {
  1860. Utils::throwError('20003:剧本不存在');
  1861. }
  1862. // 批量插入数据
  1863. return DB::table('mp_script_records')->where('id', $rid)->update([
  1864. 'content' => $content,
  1865. 'updated_at' => date('Y-m-d H:i:s')
  1866. ]);
  1867. }
  1868. /**
  1869. * 获取剧本的历史对话记录
  1870. *
  1871. * @param array $data 请求参数
  1872. * @return array 返回历史记录数组
  1873. */
  1874. public function getScriptChatHistory($data) {
  1875. $uid = Site::getUid();
  1876. $script_id = getProp($data, 'script_id');
  1877. $rid = getProp($data, 'rid');
  1878. $sequence = getProp($data, 'sequence', null);
  1879. if (!$script_id) {
  1880. Utils::throwError('20003:请提供剧本ID');
  1881. }
  1882. // 验证剧本是否存在
  1883. $script = DB::table('mp_scripts')
  1884. ->where('id', $script_id)
  1885. ->where('is_deleted', 0)
  1886. ->first();
  1887. if (!$script) {
  1888. Utils::throwError('20003:剧本不存在');
  1889. }
  1890. // 构建查询
  1891. $query = DB::table('mp_script_records')
  1892. ->where('script_id', $script_id);
  1893. // ->where('uid', $uid);
  1894. // 如果提供了 sequence,则过滤指定剧集
  1895. if ($sequence !== null) {
  1896. $query->where('sequence', $sequence);
  1897. }
  1898. // 记录ID筛选
  1899. if ($rid) {
  1900. $query->where('id', $rid);
  1901. }
  1902. // 查询记录并按 id 正序排序
  1903. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  1904. ->orderBy('created_at', 'asc')
  1905. ->orderBy('id', 'asc')
  1906. ->get()
  1907. ->map(function ($record) {
  1908. return [
  1909. 'rid' => $record->id,
  1910. 'script_id' => $record->script_id,
  1911. 'sequence' => $record->sequence,
  1912. 'role' => $record->role,
  1913. 'content' => $record->content,
  1914. 'products' => $record->products ? json_decode($record->products) : [],
  1915. 'created_at' => $record->created_at,
  1916. ];
  1917. })
  1918. ->toArray();
  1919. return $records;
  1920. }
  1921. /**
  1922. * 处理图片转换为base64
  1923. *
  1924. * @param mixed $image 图片文件对象或文件路径
  1925. * @return string|null base64编码的图片数据
  1926. */
  1927. private function processImageToBase64($image) {
  1928. try {
  1929. // 获取文件路径
  1930. if (is_string($image)) {
  1931. $filePath = $image;
  1932. } else {
  1933. // Laravel UploadedFile 对象
  1934. $filePath = $image->getRealPath();
  1935. }
  1936. if (!file_exists($filePath)) {
  1937. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  1938. return null;
  1939. }
  1940. // 验证是否为图片文件
  1941. $imageInfo = @getimagesize($filePath);
  1942. if ($imageInfo === false) {
  1943. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  1944. return null;
  1945. }
  1946. // 读取图片并转换为base64
  1947. $imageData = file_get_contents($filePath);
  1948. $base64Image = base64_encode($imageData);
  1949. dLog('deepseek')->info('图片转换成功', [
  1950. 'size' => strlen($imageData),
  1951. 'type' => $imageInfo['mime']
  1952. ]);
  1953. return $base64Image;
  1954. } catch (\Exception $e) {
  1955. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  1956. return null;
  1957. }
  1958. }
  1959. private function getArtStylePromptMappings($art_style='')
  1960. {
  1961. $arr = [
  1962. '唯美真人风格' => [
  1963. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  1964. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  1965. ],
  1966. '真人古风风格' => [
  1967. 'aliases' => ['真人古风风格', '真人古风'],
  1968. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  1969. ],
  1970. '日系动漫风格' => [
  1971. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  1972. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  1973. ],
  1974. '国漫风格' => [
  1975. 'aliases' => ['国漫风格', '国漫'],
  1976. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  1977. ],
  1978. 'Q版卡通风格' => [
  1979. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  1980. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  1981. ],
  1982. '简约扁平风格' => [
  1983. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  1984. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  1985. ],
  1986. '武侠风格' => [
  1987. 'aliases' => ['武侠风格', '武侠'],
  1988. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  1989. ],
  1990. '古风仙侠风格' => [
  1991. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  1992. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  1993. ],
  1994. '新中式水墨风格' => [
  1995. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  1996. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  1997. ],
  1998. '写实插画风格' => [
  1999. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2000. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  2001. ],
  2002. '3D卡通风格' => [
  2003. 'aliases' => ['3D卡通风格', '3D卡通'],
  2004. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  2005. ],
  2006. '条漫风格' => [
  2007. 'aliases' => ['条漫风格', '条漫'],
  2008. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  2009. ],
  2010. '赛博朋克风格' => [
  2011. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2012. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  2013. ],
  2014. '暗黑悬疑风格' => [
  2015. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2016. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  2017. ],
  2018. '治愈清新风格' => [
  2019. 'aliases' => ['治愈清新风格', '治愈清新'],
  2020. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  2021. ],
  2022. '3D真人风格' => [
  2023. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  2024. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  2025. ],
  2026. ];
  2027. if($art_style) {
  2028. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2029. }
  2030. return $arr;
  2031. $arr = [
  2032. '唯美真人风格' => [
  2033. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2034. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  2035. 2. 色彩色调
  2036. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  2037. 3. 画质精度
  2038. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  2039. 4. 画面观感
  2040. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  2041. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  2042. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  2043. ],
  2044. '真人古风风格' => [
  2045. 'aliases' => ['真人古风风格', '真人古风'],
  2046. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  2047. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  2048. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  2049. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  2050. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  2051. ],
  2052. '日系动漫风格' => [
  2053. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2054. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  2055. 正向提示词(中文)
  2056. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  2057. 必须遵守规则
  2058. • 全程保持日系动漫风格,不混入其他画风
  2059. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  2060. • 画面适配所选画面比例,构图居中,主体突出
  2061. • 线条干净、色彩统一,不杂乱、不突兀
  2062. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  2063. ],
  2064. '国漫风格' => [
  2065. 'aliases' => ['国漫风格', '国漫'],
  2066. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  2067. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  2068. 必须遵守规则
  2069. • 严格保持国漫画风,不串风格、不混画风
  2070. • 角色形象统一,不随意改变五官、身材、服饰
  2071. • 画面构图稳定,适合漫剧叙事展示
  2072. • 色调统一,不出现脏色、杂色
  2073. 禁止/避免词汇
  2074. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  2075. ],
  2076. 'Q版卡通风格' => [
  2077. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2078. 'prompt' => "风格说明
  2079. 头大身小,造型可爱圆润,简约干净
  2080. 正向提示词(中文)
  2081. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  2082. 必须遵守规则
  2083. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  2084. • 角色造型统一,表情可爱,不诡异
  2085. • 画面简洁清爽,无多余复杂元素
  2086. • 色彩明亮柔和,不刺眼
  2087. 禁止/避免词汇
  2088. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  2089. ],
  2090. '简约扁平风格' => [
  2091. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2092. 'prompt' => "风格说明
  2093. 色块简洁、无复杂渐变,现代极简风
  2094. 正向提示词(中文)
  2095. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  2096. 必须遵守规则
  2097. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  2098. • 构图简洁,主体突出,无多余装饰
  2099. • 色彩统一、干净,不杂乱
  2100. 禁止/避免词汇
  2101. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  2102. ],
  2103. '武侠风格' => [
  2104. 'aliases' => ['武侠风格', '武侠'],
  2105. 'prompt' => "风格说明
  2106. 江湖气息,线条硬朗,动作感强
  2107. 正向提示词(中文)
  2108. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  2109. 必须遵守规则
  2110. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  2111. • 角色形象、服饰、身材比例统一
  2112. • 画面动作自然,不扭曲、不畸形
  2113. 禁止/避免词汇
  2114. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  2115. ],
  2116. '古风仙侠风格' => [
  2117. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2118. 'prompt' => "风格说明
  2119. 飘逸汉服、云雾仙气、唯美空灵
  2120. 正向提示词(中文)
  2121. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  2122. 必须遵守规则
  2123. • 保持古风仙侠统一画风,不混入现代、科幻元素
  2124. • 角色服饰、发型、形象前后一致
  2125. • 场景仙气飘逸,色调清雅统一
  2126. • 画面唯美柔和,不阴暗、不诡异
  2127. 禁止/避免词汇
  2128. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  2129. ],
  2130. '新中式水墨风格' => [
  2131. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2132. 'prompt' => "风格说明
  2133. 淡墨渲染,毛笔笔触,留白意境
  2134. 正向提示词(中文)
  2135. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  2136. 必须遵守规则
  2137. • 严格保持水墨质感,不混入厚涂、写实、卡通
  2138. • 色调淡雅统一,不浓艳杂乱
  2139. • 画面干净有意境,不堆砌元素
  2140. 禁止/避免词汇
  2141. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  2142. ],
  2143. '写实插画风格' => [
  2144. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2145. 'prompt' => "风格说明
  2146. 接近真人比例,光影真实,质感细腻
  2147. 正向提示词(中文)
  2148. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  2149. 必须遵守规则
  2150. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  2151. • 角色五官、身材、服饰高度统一
  2152. • 画面清晰、光影自然、不扭曲
  2153. 禁止/避免词汇
  2154. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  2155. ],
  2156. '3D卡通风格' => [
  2157. 'aliases' => ['3D卡通风格', '3D卡通'],
  2158. 'prompt' => "风格说明
  2159. 3D建模质感,柔和渲染,圆润可爱
  2160. 正向提示词(中文)
  2161. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  2162. 必须遵守规则
  2163. • 保持3D卡通统一质感,不出现2D杂乱线条
  2164. • 角色模型、比例、形象前后一致
  2165. • 画面干净,不模糊、不穿模
  2166. 禁止/避免词汇
  2167. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  2168. ],
  2169. '条漫风格' => [
  2170. 'aliases' => ['条漫风格', '条漫'],
  2171. 'prompt' => "风格说明
  2172. 纵向分镜,上下滑动阅读,轻量化
  2173. 正向提示词(中文)
  2174. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  2175. 必须遵守规则
  2176. • 保持条漫纵向阅读逻辑,构图简洁
  2177. • 画风统一,不混写实、3D、水墨
  2178. • 画面干净,不杂乱
  2179. 禁止/避免词汇
  2180. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  2181. ],
  2182. '赛博朋克风格' => [
  2183. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2184. 'prompt' => "风格说明
  2185. 霓虹灯光、未来都市、暗色调、科技机械
  2186. 正向提示词(中文)
  2187. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  2188. 必须遵守规则
  2189. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  2190. • 色调以暗调+霓虹为主,色彩统一
  2191. • 画面科技感强,不杂乱
  2192. 禁止/避免词汇
  2193. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  2194. ],
  2195. '暗黑悬疑风格' => [
  2196. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2197. 'prompt' => "风格说明
  2198. 低饱和、冷色调、阴影重、神秘压抑
  2199. 正向提示词(中文)
  2200. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  2201. 必须遵守规则
  2202. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  2203. • 画面氛围压抑神秘,但不低俗、不血腥
  2204. • 角色形象统一,不崩坏
  2205. 禁止/避免词汇
  2206. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  2207. ],
  2208. '治愈清新风格' => [
  2209. 'aliases' => ['治愈清新风格', '治愈清新'],
  2210. 'prompt' => "风格说明
  2211. 马卡龙色系、柔光、温暖干净
  2212. 正向提示词(中文)
  2213. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  2214. 必须遵守规则
  2215. • 保持治愈清新统一色调,不阴暗、不诡异
  2216. • 画面柔和干净,无杂乱元素
  2217. • 角色形象柔和可爱,不狰狞
  2218. 禁止/避免词汇
  2219. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  2220. ],
  2221. ];
  2222. return $arr;
  2223. }
  2224. public function getArtStylePromptByInput($inputArtStyle): string
  2225. {
  2226. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  2227. if ($normalizedInput === '') {
  2228. return '';
  2229. }
  2230. return $this->getArtStylePromptMappings($normalizedInput);
  2231. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  2232. // foreach ($mapping['aliases'] as $alias) {
  2233. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  2234. // if ($normalizedAlias === '') {
  2235. // continue;
  2236. // }
  2237. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  2238. // return $mapping['prompt'];
  2239. // }
  2240. // }
  2241. // }
  2242. return '';
  2243. }
  2244. public function getArtStyleShortPromptByInput($inputArtStyle) {
  2245. $stylePrefixes = [
  2246. '唯美真人风格' => [
  2247. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  2248. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  2249. ],
  2250. '真人古风风格' => [
  2251. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  2252. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  2253. ],
  2254. '日系动漫风格' => [
  2255. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  2256. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  2257. ],
  2258. '国漫风格' => [
  2259. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  2260. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  2261. ],
  2262. 'Q版卡通风格' => [
  2263. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  2264. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  2265. ],
  2266. '简约扁平风格' => [
  2267. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  2268. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  2269. ],
  2270. '武侠风格' => [
  2271. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  2272. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  2273. ],
  2274. '古风仙侠风格' => [
  2275. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  2276. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  2277. ],
  2278. '新中式水墨风格' => [
  2279. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  2280. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  2281. ],
  2282. '写实插画风格' => [
  2283. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  2284. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  2285. ],
  2286. '3D卡通风格' => [
  2287. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  2288. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  2289. ],
  2290. '条漫风格' => [
  2291. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  2292. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  2293. ],
  2294. '赛博朋克风格' => [
  2295. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  2296. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  2297. ],
  2298. '暗黑悬疑风格' => [
  2299. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  2300. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  2301. ],
  2302. '治愈清新风格' => [
  2303. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  2304. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  2305. ]
  2306. ];
  2307. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  2308. }
  2309. private function normalizeArtStyleInput($value): string
  2310. {
  2311. $value = trim((string)$value);
  2312. if ($value === '') {
  2313. return '';
  2314. }
  2315. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  2316. return mb_strtolower($value, 'UTF-8');
  2317. }
  2318. private function replaceArtStyleSection(string $content, string $artStyle): string
  2319. {
  2320. if ($content === '' || $artStyle === '') {
  2321. return $content;
  2322. }
  2323. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  2324. if (!preg_match($pattern, $content)) {
  2325. return $content;
  2326. }
  2327. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  2328. }
  2329. /**
  2330. * DeepSeek流式输出处理方法
  2331. *
  2332. * @param array $post_data DeepSeek API请求参数
  2333. * @return \Generator 返回生成器,用于流式输出
  2334. */
  2335. private function unwrapJsonWrappedContent($content) {
  2336. $trimmed = ltrim((string)$content);
  2337. if ($trimmed === '' || ($trimmed[0] !== '{' && $trimmed[0] !== '[')) {
  2338. return $content;
  2339. }
  2340. $decoded = json_decode($trimmed, true);
  2341. if (!is_array($decoded)) {
  2342. return $content;
  2343. }
  2344. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2345. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2346. return $decoded[$key];
  2347. }
  2348. }
  2349. return $content;
  2350. }
  2351. private function deepSeekStreamResponse($post_data) {
  2352. // 设置最大输出tokens
  2353. $post_data['max_tokens'] = 300000;
  2354. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2355. $post_data['stream_options'] = ['include_usage' => true];
  2356. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2357. $response = $client->post($this->url, [
  2358. 'json' => $post_data,
  2359. 'headers' => $this->headers,
  2360. 'stream' => true // 启用流式响应
  2361. ]);
  2362. $body = $response->getBody();
  2363. $fullContent = '';
  2364. $fullReasoningContent = '';
  2365. $usage = [];
  2366. $buffer = '';
  2367. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  2368. // 逐行读取流式响应
  2369. while (!$body->eof()) {
  2370. $chunk = $body->read(1024); // 每次读取 1KB
  2371. $buffer .= $chunk;
  2372. // 按行分割
  2373. $lines = explode("\n", $buffer);
  2374. // 保留最后一个不完整的行
  2375. $buffer = array_pop($lines);
  2376. foreach ($lines as $line) {
  2377. $line = trim($line);
  2378. // 跳过空行
  2379. if (empty($line)) {
  2380. continue;
  2381. }
  2382. // 检查是否是 SSE 数据行
  2383. if (strpos($line, 'data: ') !== 0) {
  2384. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2385. continue;
  2386. }
  2387. $data = substr($line, 6); // 移除 "data: " 前缀
  2388. if ($data === '[DONE]') {
  2389. dLog('deepseek')->info('收到结束标记');
  2390. break 2; // 跳出两层循环
  2391. }
  2392. try {
  2393. $json = json_decode($data, true);
  2394. if (json_last_error() !== JSON_ERROR_NONE) {
  2395. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2396. continue;
  2397. }
  2398. if (isset($json['choices'][0]['delta'])) {
  2399. $delta = $json['choices'][0]['delta'];
  2400. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2401. if (isset($delta['reasoning_content'])) {
  2402. $fullReasoningContent .= $delta['reasoning_content'];
  2403. yield [
  2404. 'type' => 'reasoning',
  2405. 'content' => $delta['reasoning_content'],
  2406. 'full_reasoning' => $fullReasoningContent
  2407. ];
  2408. }
  2409. // 处理最终回答内容
  2410. if (isset($delta['content'])) {
  2411. $fullContent .= $delta['content'];
  2412. yield [
  2413. 'type' => 'content',
  2414. 'content' => $delta['content'],
  2415. ];
  2416. }
  2417. }
  2418. // 获取使用统计信息
  2419. if (isset($json['usage'])) {
  2420. $usage = $json['usage'];
  2421. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2422. }
  2423. } catch (\Exception $e) {
  2424. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2425. continue;
  2426. }
  2427. }
  2428. }
  2429. dLog('deepseek')->info('流式读取完成', [
  2430. 'content_length' => strlen($fullContent),
  2431. 'reasoning_length' => strlen($fullReasoningContent)
  2432. ]);
  2433. yield [
  2434. 'type' => 'done',
  2435. 'full_content' => $fullContent,
  2436. 'full_reasoning' => $fullReasoningContent,
  2437. 'usage' => $usage
  2438. ];
  2439. }
  2440. /**
  2441. * GPT 重试次数(env 可配置,默认 5 次)
  2442. */
  2443. private function gptRetryTimes()
  2444. {
  2445. return (int)env('GPT_RETRY_TIMES', 5);
  2446. }
  2447. /**
  2448. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  2449. */
  2450. private function gptRetryInterval()
  2451. {
  2452. return (int)env('GPT_RETRY_INTERVAL', 10);
  2453. }
  2454. /**
  2455. * 判断 GPT 请求异常是否可重试
  2456. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  2457. */
  2458. private function isGptRetryableException(\Exception $e)
  2459. {
  2460. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  2461. return false;
  2462. }
  2463. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  2464. $status = $e->getResponse()->getStatusCode();
  2465. return $status >= 500 || $status == 429;
  2466. }
  2467. return true;
  2468. }
  2469. /**
  2470. * GPT 中转站探活:GET /v1/models,5 秒短超时
  2471. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  2472. */
  2473. private function checkGptServiceAvailable()
  2474. {
  2475. $apiKey = env('GPT_54_API_KEY');
  2476. if (empty($apiKey)) {
  2477. return false;
  2478. }
  2479. try {
  2480. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  2481. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  2482. 'headers' => [
  2483. 'Authorization' => 'Bearer ' . $apiKey,
  2484. 'Content-Type' => 'application/json'
  2485. ]
  2486. ]);
  2487. $status = $response->getStatusCode();
  2488. return $status < 500 && $status != 429;
  2489. } catch (\Exception $e) {
  2490. return false;
  2491. }
  2492. }
  2493. /**
  2494. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  2495. * 全部失败抛出友好错误
  2496. */
  2497. private function ensureGptServiceAvailable()
  2498. {
  2499. $maxRetries = $this->gptRetryTimes();
  2500. $interval = $this->gptRetryInterval();
  2501. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  2502. if ($this->checkGptServiceAvailable()) {
  2503. return;
  2504. }
  2505. if ($attempt < $maxRetries) {
  2506. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  2507. 'retry' => $attempt + 1,
  2508. 'max_retries' => $maxRetries
  2509. ]);
  2510. sleep($interval);
  2511. }
  2512. }
  2513. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  2514. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  2515. 'max_retries' => $maxRetries,
  2516. 'interval' => $interval
  2517. ]);
  2518. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  2519. }
  2520. /**
  2521. * GPT 流式输出处理方法
  2522. *
  2523. * @param array $post_data GPT API请求参数
  2524. * @return \Generator 返回生成器,用于流式输出
  2525. */
  2526. private function gpt54StreamResponse($post_data) {
  2527. $apiKey = env('GPT_54_API_KEY');
  2528. if (empty($apiKey)) {
  2529. Utils::throwError('20003:GPT API Key未配置');
  2530. }
  2531. // 先探活,服务不可用时自动重试
  2532. $this->ensureGptServiceAvailable();
  2533. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2534. $headers = [
  2535. 'Authorization' => 'Bearer ' . $apiKey,
  2536. 'Content-Type' => 'application/json',
  2537. 'Accept' => 'text/event-stream'
  2538. ];
  2539. // 移除 thinking 参数,GPT-5.4 不支持
  2540. if (isset($post_data['thinking'])) {
  2541. unset($post_data['thinking']);
  2542. }
  2543. if (isset($post_data['reasoning_effort'])) {
  2544. unset($post_data['reasoning_effort']);
  2545. }
  2546. // 中转站不识别 response_format,可能被误转成 JSON 输出模式
  2547. if (isset($post_data['response_format'])) {
  2548. unset($post_data['response_format']);
  2549. }
  2550. $post_data['max_completion_tokens'] = 100000;
  2551. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2552. $post_data['stream_options'] = ['include_usage' => true];
  2553. $maxRetries = $this->gptRetryTimes();
  2554. $interval = $this->gptRetryInterval();
  2555. $attempt = 0;
  2556. while (true) {
  2557. $fullContent = '';
  2558. $usage = [];
  2559. $buffer = '';
  2560. $suspectJsonWrap = false;
  2561. $pendingContent = '';
  2562. try {
  2563. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  2564. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  2565. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  2566. 'json' => $post_data,
  2567. 'headers' => $headers,
  2568. 'stream' => true // 启用流式响应
  2569. ]);
  2570. $body = $response->getBody();
  2571. dLog('deepseek')->info('开始读取 GPT 流式响应');
  2572. // 逐行读取流式响应
  2573. while (!$body->eof()) {
  2574. $chunk = $body->read(1024); // 每次读取 1KB
  2575. $buffer .= $chunk;
  2576. // 按行分割
  2577. $lines = explode("\n", $buffer);
  2578. // 保留最后一个不完整的行
  2579. $buffer = array_pop($lines);
  2580. foreach ($lines as $line) {
  2581. $line = trim($line);
  2582. // 跳过空行
  2583. if (empty($line)) {
  2584. continue;
  2585. }
  2586. // 检查是否是 SSE 数据行
  2587. if (strpos($line, 'data: ') !== 0) {
  2588. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2589. continue;
  2590. }
  2591. $data = substr($line, 6); // 移除 "data: " 前缀
  2592. if ($data === '[DONE]') {
  2593. dLog('deepseek')->info('收到结束标记');
  2594. break 2; // 跳出 foreach 和流读取循环
  2595. }
  2596. try {
  2597. $json = json_decode($data, true);
  2598. if (json_last_error() !== JSON_ERROR_NONE) {
  2599. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2600. continue;
  2601. }
  2602. if (isset($json['choices'][0]['delta'])) {
  2603. $delta = $json['choices'][0]['delta'];
  2604. // 处理回答内容
  2605. if (isset($delta['content'])) {
  2606. $fullContent .= $delta['content'];
  2607. $trimmed = ltrim($fullContent);
  2608. if (!$suspectJsonWrap && $trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
  2609. // 可能模型把整段正文包成了 JSON 字符串,先暂缓输出
  2610. $suspectJsonWrap = true;
  2611. }
  2612. if (!$suspectJsonWrap) {
  2613. // 中转可能一次返回大段内容,按小块输出保持流式节奏
  2614. $chunkSize = 256;
  2615. $chunkLength = mb_strlen($delta['content']);
  2616. for ($offset = 0; $offset < $chunkLength; $offset += $chunkSize) {
  2617. yield [
  2618. 'type' => 'content',
  2619. 'content' => mb_substr($delta['content'], $offset, $chunkSize),
  2620. ];
  2621. }
  2622. } else {
  2623. $pendingContent .= $delta['content'];
  2624. }
  2625. }
  2626. }
  2627. // 获取使用统计信息
  2628. if (isset($json['usage'])) {
  2629. $usage = $json['usage'];
  2630. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2631. }
  2632. } catch (\Exception $e) {
  2633. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2634. continue;
  2635. }
  2636. }
  2637. }
  2638. dLog('deepseek')->info('流式读取完成', [
  2639. 'content_length' => strlen($fullContent)
  2640. ]);
  2641. // 兼容模型偶发把整段正文包裹成 JSON 字符串返回
  2642. if ($suspectJsonWrap) {
  2643. $decoded = json_decode(trim($fullContent), true);
  2644. $unwrapped = null;
  2645. if (is_array($decoded)) {
  2646. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2647. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2648. $unwrapped = $decoded[$key];
  2649. break;
  2650. }
  2651. }
  2652. }
  2653. if ($unwrapped !== null) {
  2654. $fullContent = $unwrapped;
  2655. $chunkSize = 256;
  2656. $contentLength = mb_strlen($fullContent);
  2657. for ($offset = 0; $offset < $contentLength; $offset += $chunkSize) {
  2658. yield [
  2659. 'type' => 'content',
  2660. 'content' => mb_substr($fullContent, $offset, $chunkSize),
  2661. ];
  2662. }
  2663. } elseif ($pendingContent !== '') {
  2664. // 误判:补发暂缓内容,避免内容丢失
  2665. yield [
  2666. 'type' => 'content',
  2667. 'content' => $pendingContent,
  2668. ];
  2669. }
  2670. }
  2671. yield [
  2672. 'type' => 'done',
  2673. 'full_content' => $fullContent,
  2674. 'full_reasoning' => '',
  2675. 'usage' => $usage
  2676. ];
  2677. return;
  2678. } catch (\Exception $e) {
  2679. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  2680. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  2681. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  2682. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  2683. throw $e;
  2684. }
  2685. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  2686. 'retry' => $attempt + 1,
  2687. 'max_retries' => $maxRetries,
  2688. 'error' => $e->getMessage()
  2689. ]);
  2690. sleep($interval);
  2691. $attempt++;
  2692. }
  2693. }
  2694. }
  2695. // 与推理模型对话
  2696. public function chatWithReasoner($data) {
  2697. $content = getProp($data, 'content');
  2698. $model = getProp($data, 'model', 'r1');
  2699. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2700. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2701. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2702. if ($model == 'r1') {
  2703. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  2704. $thinkingMode = 'disabled';
  2705. } else {
  2706. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  2707. $thinkingMode = 'disabled';
  2708. }
  2709. // 获取可选情感(根据音色可支持情感选)
  2710. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  2711. $emotion_list = [];
  2712. foreach ($timbre_emotion as $emotion) {
  2713. $tmp = explode(',', $emotion);
  2714. $emotion_list = array_merge($emotion_list, $tmp);
  2715. }
  2716. $emotion_list = array_unique($emotion_list);
  2717. $emotion_str = implode('、', $emotion_list);
  2718. // // 获取可选情感
  2719. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  2720. // $emotion_str = implode('、', $emotion_list);
  2721. // 是否启用情感
  2722. $enable_emotion = getProp($data, 'enable_emotion', 0);
  2723. if ($enable_emotion) {
  2724. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  2725. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2726. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  2727. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  2728. }else {
  2729. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  2730. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2731. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  2732. }
  2733. $messages = [
  2734. [
  2735. 'role' => 'system',
  2736. 'content' => $sys_content
  2737. ],
  2738. [
  2739. 'role' => 'user',
  2740. 'content' => $content
  2741. ]
  2742. ];
  2743. $post_data = [
  2744. 'model' => $model,
  2745. 'messages' => $messages,
  2746. // 'max_tokens' => 8192,
  2747. 'temperature' => 1,
  2748. 'frequency_penalty' => 0,
  2749. 'presence_penalty' => 0,
  2750. 'thinking' => ['type' => $thinkingMode],
  2751. 'response_format' => [
  2752. 'type' => 'text'
  2753. ],
  2754. 'stream' => false
  2755. ];
  2756. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2757. // 根据模型类型选择调用方法
  2758. $fullContent = '';
  2759. $usage = [];
  2760. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2761. // DeepSeek 官方模型使用 DeepSeek API
  2762. $chatResult = $this->chatOnly($post_data);
  2763. } else if (in_array($model, $this->gpt_text_models)) {
  2764. // GPT-5.4 模型使用 TokenRouter API
  2765. $chatResult = $this->gpt54ChatOnly($post_data);
  2766. } else {
  2767. // 其他模型使用火山引擎API
  2768. $chatResult = $this->volcEngineChatCompletion($post_data);
  2769. }
  2770. if (is_array($chatResult)) {
  2771. $fullContent = $chatResult['fullContent'];
  2772. $usage = $chatResult['usage'];
  2773. }
  2774. // 处理获取到的剧本数据
  2775. $script_content = handleScriptWords($fullContent, $enable_emotion);
  2776. $result = [
  2777. 'origin_content' => $fullContent,
  2778. 'roles' => getProp($script_content, 'roles'),
  2779. 'words' => getProp($script_content, 'words'),
  2780. ];
  2781. // 仅记录 token 使用明细(不扣积分)
  2782. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  2783. 'model' => $model,
  2784. 'source' => 'chatWithReasoner',
  2785. ], $model);
  2786. return $result;
  2787. }
  2788. public function resetParagraphAudio($data) {
  2789. $bid = getProp($data, 'bid');
  2790. $cid = getProp($data, 'cid');
  2791. $version_id = getProp($data, 'version_id');
  2792. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  2793. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  2794. 'generate_status' => '待制作',
  2795. 'updated_at' => date('Y-m-d H:i:s')
  2796. ]);
  2797. }
  2798. public function saveParagraphAudio($data) {
  2799. $bid = getProp($data, 'bid');
  2800. $cid = getProp($data, 'cid');
  2801. $version_id = getProp($data, 'version_id');
  2802. $sequence = getProp($data, 'sequence');
  2803. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  2804. // 获取所有情感
  2805. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  2806. $emotion_list = array_flip($emotion_list);
  2807. // 获取音色支持情感
  2808. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  2809. $timbre_emotion = explode(',', $timbre_emotion);
  2810. $emotion = getProp($data, 'emotion');
  2811. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  2812. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  2813. $list = [
  2814. 'bid' => $bid,
  2815. 'cid' => $cid,
  2816. 'version_id' => $version_id,
  2817. 'sequence' => $sequence,
  2818. 'role' => getProp($data, 'role'),
  2819. 'gender' => getProp($data, 'gender'),
  2820. 'text' => trim(getProp($data, 'text')),
  2821. 'emotion' => $emotion,
  2822. 'emotion_type' => $emotion_type,
  2823. 'voice_type' => getProp($data, 'voice_type'),
  2824. 'voice_name' => getProp($data, 'voice_name'),
  2825. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  2826. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  2827. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  2828. 'pitch' => getProp($data, 'pitch', 0),
  2829. // 'paragraph_audio_url' => '',
  2830. 'generate_status' => '制作中',
  2831. 'error_msg' => '',
  2832. 'updated_at' => date('Y-m-d H:i:s')
  2833. ];
  2834. $continue = false;
  2835. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  2836. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  2837. $list['generate_status'] = '制作成功';
  2838. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2839. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  2840. $continue = true;
  2841. }
  2842. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  2843. if ($id) {
  2844. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  2845. }else {
  2846. $list['created_at'] = date('Y-m-d H:i:s');
  2847. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  2848. $boolen = $id ? true : false;
  2849. }
  2850. // 如果更新成功则加入查询队列
  2851. if ($boolen) {
  2852. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  2853. Redis::sadd($redis_key, $id);
  2854. }
  2855. if ($boolen && !$continue) {
  2856. $boolen = false;
  2857. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2858. // 根据ID通过API通知合成音频
  2859. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  2860. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  2861. $response = $result->getBody()->getContents();
  2862. $response_arr = json_decode($response, true);
  2863. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2864. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2865. Log::info('通知火山生成段落音频失败: '.$error_msg);
  2866. Utils::throwError('20003:通知火山生成段落音频失败');
  2867. }
  2868. $boolen = true;
  2869. }
  2870. return $boolen;
  2871. }
  2872. public function insertAudioEffect($data) {
  2873. $audio_id = getProp($data, 'audio_id');
  2874. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2875. $bid = getProp($chapter_audio, 'bid');
  2876. $version_id = getProp($chapter_audio, 'version_id');
  2877. $cid = getProp($chapter_audio, 'cid');
  2878. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2879. $audio_effect_json = getProp($data, 'audio_effect_json');
  2880. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  2881. try {
  2882. DB::beginTransaction();
  2883. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2884. if (!$count) {
  2885. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2886. }else {
  2887. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2888. }
  2889. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2890. 'audio_effect_status' => '添加中',
  2891. 'audio_effect_json' => $audio_effect_json,
  2892. 'updated_at' => date('Y-m-d H:i:s')
  2893. ]);
  2894. if (!$boolen1) {
  2895. DB::rollBack();
  2896. Utils::throwError('20003:更新生成数据失败');
  2897. }
  2898. $id = DB::table('mp_audio_tasks')->insertGetId([
  2899. 'audio_id' => $audio_id,
  2900. 'generate_status' => '执行中',
  2901. 'generate_json' => json_encode([], 256),
  2902. 'bid' => $bid,
  2903. 'book_name' => getProp($chapter_audio, 'book_name'),
  2904. 'version_id' => $version_id,
  2905. 'version_name' => getProp($chapter_audio, 'version_name'),
  2906. 'cid' => $cid,
  2907. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2908. 'task_name' => $task_name,
  2909. 'created_at' => date('Y-m-d H:i:s'),
  2910. 'updated_at' => date('Y-m-d H:i:s')
  2911. ]);
  2912. if (!$id) {
  2913. DB::rollBack();
  2914. Utils::throwError('20003:创建任务失败');
  2915. }
  2916. }catch (\Exception $e) {
  2917. DB::rollBack();
  2918. Utils::throwError('20003:'.$e->getMessage());
  2919. }
  2920. DB::commit();
  2921. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2922. // 根据ID通过API通知合成音频
  2923. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2924. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2925. $response = $result->getBody()->getContents();
  2926. $response_arr = json_decode($response, true);
  2927. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2928. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2929. Log::info('通知火山插入音效失败: '.$error_msg);
  2930. Utils::throwError('20003:通知火山插入音效失败');
  2931. }
  2932. return true;
  2933. }
  2934. public function insertBgm($data) {
  2935. $audio_id = getProp($data, 'audio_id');
  2936. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2937. $bid = getProp($chapter_audio, 'bid');
  2938. $version_id = getProp($chapter_audio, 'version_id');
  2939. $cid = getProp($chapter_audio, 'cid');
  2940. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2941. $bgm_json = getProp($data, 'bgm_json');
  2942. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2943. if (!$bgm_json) {
  2944. $bgm_json = getProp($data, 'audio_effect_json');
  2945. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2946. }
  2947. try {
  2948. DB::beginTransaction();
  2949. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2950. if (!$count) {
  2951. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2952. }else {
  2953. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2954. }
  2955. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2956. 'bgm_status' => '添加中',
  2957. 'bgm_json' => $bgm_json,
  2958. 'updated_at' => date('Y-m-d H:i:s')
  2959. ]);
  2960. if (!$boolen1) {
  2961. DB::rollBack();
  2962. Utils::throwError('20003:更新生成数据失败');
  2963. }
  2964. $id = DB::table('mp_audio_tasks')->insertGetId([
  2965. 'audio_id' => $audio_id,
  2966. 'generate_status' => '执行中',
  2967. 'generate_json' => json_encode([], 256),
  2968. 'bid' => $bid,
  2969. 'book_name' => getProp($chapter_audio, 'book_name'),
  2970. 'version_id' => $version_id,
  2971. 'version_name' => getProp($chapter_audio, 'version_name'),
  2972. 'cid' => $cid,
  2973. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2974. 'task_name' => $task_name,
  2975. 'created_at' => date('Y-m-d H:i:s'),
  2976. 'updated_at' => date('Y-m-d H:i:s')
  2977. ]);
  2978. if (!$id) {
  2979. DB::rollBack();
  2980. Utils::throwError('20003:创建任务失败');
  2981. }
  2982. }catch (\Exception $e) {
  2983. DB::rollBack();
  2984. Utils::throwError('20003:'.$e->getMessage());
  2985. }
  2986. DB::commit();
  2987. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2988. // 根据ID通过API通知合成音频
  2989. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2990. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2991. $response = $result->getBody()->getContents();
  2992. $response_arr = json_decode($response, true);
  2993. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2994. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2995. Log::info('通知火山插入bgm失败: '.$error_msg);
  2996. Utils::throwError('20003:通知火山插入bgm失败');
  2997. }
  2998. return true;
  2999. }
  3000. public function getParagraphAudios($data) {
  3001. $bid = getProp($data, 'bid');
  3002. $cid = getProp($data, 'cid');
  3003. $version_id = getProp($data, 'version_id');
  3004. $sequence = getProp($data, 'sequence');
  3005. // 获取已生成的音频
  3006. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  3007. if ($sequence) $query->where('sequence', $sequence);
  3008. $paragraph_audios = $query->orderBy('sequence')->get();
  3009. $result = [];
  3010. foreach($paragraph_audios as $item) {
  3011. $result[] = [
  3012. 'sequence' => getProp($item, 'sequence'),
  3013. 'role' => getProp($item, 'role'),
  3014. 'gender' => getProp($item, 'gender'),
  3015. 'text' => trim(getProp($item, 'text')),
  3016. 'emotion' => getProp($item, 'emotion'),
  3017. 'emotion_type' => getProp($item, 'emotion_type'),
  3018. 'voice_type' => getProp($item, 'voice_type'),
  3019. 'voice_name' => getProp($item, 'voice_name'),
  3020. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3021. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3022. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3023. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3024. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  3025. ];
  3026. }
  3027. return $result;
  3028. }
  3029. // 新增合成任务
  3030. public function addGenerateTask($data) {
  3031. $bid = getProp($data, 'bid');
  3032. $cid = getProp($data, 'cid');
  3033. $version_id = getProp($data, 'version_id');
  3034. $generate_json = getProp($data, 'generate_json');
  3035. // 获取已生成的音频
  3036. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  3037. $paragraph_list = [];
  3038. foreach($paragraph_audios as $item) {
  3039. $paragraph_list[getProp($item, 'sequence')] = [
  3040. 'role' => getProp($item, 'role'),
  3041. 'gender' => getProp($item, 'gender'),
  3042. 'text' => trim(getProp($item, 'text')),
  3043. 'emotion' => getProp($item, 'emotion'),
  3044. 'emotion_type' => getProp($item, 'emotion_type'),
  3045. 'voice_type' => getProp($item, 'voice_type'),
  3046. 'voice_name' => getProp($item, 'voice_name'),
  3047. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3048. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3049. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3050. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3051. ];
  3052. }
  3053. // 更新角色-音色信息
  3054. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  3055. $existed_role_info = json_decode($existed_role_info, true);
  3056. if (!$existed_role_info) $existed_role_info = [];
  3057. // 获取情感信息
  3058. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3059. $emotion_list = array_flip($emotion_list);
  3060. // 获取音色对应情感组
  3061. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  3062. $timbre_emotion_list = [];
  3063. foreach($timbre_emotions as $item) {
  3064. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  3065. }
  3066. // 构造生成音频的json
  3067. $words = json_decode($generate_json, true);
  3068. // 最终合成前的参数组
  3069. $mp_chapter_paragraph_audios = [];
  3070. $sequence = 1;
  3071. $complete_paragraph_sequences = [];
  3072. foreach($words as &$word) {
  3073. 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:参数格式有误');
  3074. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  3075. $role = getProp($word, 'role');
  3076. $word['gender'] = (int)$word['gender'];
  3077. // 判断音色对应情感是否支持,不支持则调整为中性
  3078. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  3079. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  3080. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  3081. if (isset($emotion_list[getProp($word, 'emotion')])) {
  3082. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  3083. }else {
  3084. $word['emotion'] = '中性';
  3085. $word['emotion_type'] = 'neutral';
  3086. }
  3087. $existed_role_info[$role] = [
  3088. 'timbre_type' => $word['voice_type'],
  3089. 'timbre_name' => $word['voice_name'],
  3090. 'emotion' => $word['emotion'],
  3091. 'emotion_type' => $word['emotion_type'],
  3092. 'speed_ratio' => $word['speed_ratio'],
  3093. 'loudness_ratio'=> $word['loudness_ratio'],
  3094. 'emotion_scale' => $word['emotion_scale'],
  3095. 'pitch' => $word['pitch']
  3096. ];
  3097. $word['paragraph_audio_url'] = '';
  3098. // 判断生成参数是否相同,相同则直接使用已生成的音频
  3099. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  3100. // 如果音频存在并且参数都未改变则使用已生成的音频
  3101. if (getProp($paragraph, 'paragraph_audio_url')) {
  3102. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  3103. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  3104. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  3105. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  3106. // {
  3107. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3108. // }
  3109. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3110. }
  3111. $tmp = $word;
  3112. // 组装章节分句音频数据
  3113. // $tmp['sequence'] = getProp($word, 'sequence');
  3114. // $tmp['text'] = getProp($word, 'text');
  3115. // $tmp['emotion'] = getProp($word, 'emotion');
  3116. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  3117. // $tmp['voice_name'] = getProp($word, 'voice_name');
  3118. // $tmp['voice_type'] = getProp($word, 'voice_type');
  3119. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  3120. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  3121. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  3122. $tmp['bid'] = $bid;
  3123. $tmp['version_id'] = $version_id;
  3124. $tmp['cid'] = $cid;
  3125. $tmp['sequence'] = $sequence;
  3126. $tmp['created_at'] = date('Y-m-d H:i:s');
  3127. $tmp['updated_at'] = date('Y-m-d H:i:s');
  3128. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  3129. $mp_chapter_paragraph_audios[] = $tmp;
  3130. $complete_paragraph_sequences[] = $sequence;
  3131. $sequence++;
  3132. }
  3133. $generate_json = json_encode($words, 256);
  3134. // 判断是否有未生成字幕的段落
  3135. $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();
  3136. if ($no_subtitle_sequences) {
  3137. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  3138. }
  3139. try {
  3140. DB::beginTransaction();
  3141. $role_info = json_encode($existed_role_info, 256);
  3142. $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')]);
  3143. if (!$boolen) {
  3144. DB::rollBack();
  3145. Utils::throwError('20003:更新角色信息失败');
  3146. }
  3147. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  3148. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  3149. if (!$count) {
  3150. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3151. }else {
  3152. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3153. }
  3154. $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')]);
  3155. if (!$boolen1) {
  3156. DB::rollBack();
  3157. Utils::throwError('20003:更新生成数据失败');
  3158. }
  3159. $id = DB::table('mp_audio_tasks')->insertGetId([
  3160. 'audio_id' => getProp($chapter_audio, 'id'),
  3161. 'generate_status' => '执行中',
  3162. 'generate_json' => $generate_json,
  3163. 'bid' => $bid,
  3164. 'book_name' => getProp($chapter_audio, 'book_name'),
  3165. 'version_id' => $version_id,
  3166. 'version_name' => getProp($chapter_audio, 'version_name'),
  3167. 'cid' => $cid,
  3168. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3169. 'task_name' => $task_name,
  3170. 'created_at' => date('Y-m-d H:i:s'),
  3171. 'updated_at' => date('Y-m-d H:i:s')
  3172. ]);
  3173. if (!$id) {
  3174. DB::rollBack();
  3175. Utils::throwError('20003:创建任务失败');
  3176. }
  3177. // 删除不在段落序号范围内的其他数据
  3178. if ($complete_paragraph_sequences) {
  3179. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  3180. }
  3181. // // 删除章节分句音频数据并重新插入
  3182. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  3183. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  3184. // if (!$boolen3) {
  3185. // DB::rollBack();
  3186. // Utils::throwError('20003:更新章节分句音频失败');
  3187. // }
  3188. } catch (\Exception $e) {
  3189. DB::rollBack();
  3190. Utils::throwError('20003:'.$e->getMessage());
  3191. }
  3192. DB::commit();
  3193. // 通知火山生成音频
  3194. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3195. // 根据ID通过API通知合成音频
  3196. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  3197. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  3198. $response = $result->getBody()->getContents();
  3199. $response_arr = json_decode($response, true);
  3200. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3201. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3202. Log::info('通知火山生成音频失败: '.$error_msg);
  3203. Utils::throwError('20003:通知火山生成音频失败');
  3204. }
  3205. return true;
  3206. }
  3207. public function timbreList($data) {
  3208. $gender = getProp($data, 'gender');
  3209. $timbre_name = getProp($data, 'voice_name');
  3210. $category_id = getProp($data, 'category_id');
  3211. $age_stage = getProp($data, 'age_stage');
  3212. $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');
  3213. if ($gender) {
  3214. $query->where('gender', $gender);
  3215. }
  3216. if ($timbre_name) {
  3217. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  3218. }
  3219. if ($category_id) {
  3220. $query->where(function ($query) use ($category_id) {
  3221. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  3222. });
  3223. }
  3224. if ($age_stage) {
  3225. $query->where('age_stage', $age_stage);
  3226. }
  3227. $list = $query->get()->map(function ($value) {
  3228. $value = (array)$value;
  3229. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  3230. return $value;
  3231. })->toArray();
  3232. return $list;
  3233. }
  3234. // 生成火山临时token
  3235. public function setStsToken() {
  3236. // ************* 配置参数 *************
  3237. $method = 'GET';
  3238. $service = 'sts';
  3239. $host = 'open.volcengineapi.com';
  3240. $region = env('VOLC_REGION');
  3241. $endpoint = 'https://open.volcengineapi.com';
  3242. // $endpoint = 'https://tos-cn-beijing.volces.com';
  3243. $access_key = env('VOLC_AK');
  3244. $secret_key = env('VOLC_SK');
  3245. // 获取缓存中的token,如果没有则请求接口
  3246. $token = Redis::get('volc_sts_token');
  3247. if (!$token) {
  3248. // 查询参数
  3249. $query_parameters = [
  3250. 'Action' => 'AssumeRole',
  3251. 'RoleSessionName' => 'user@zw',
  3252. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  3253. 'Version' => '2018-01-01'
  3254. ];
  3255. // 生成URL编码的查询字符串
  3256. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  3257. // 获取签名头信息
  3258. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  3259. // 构建完整URL
  3260. $request_url = $endpoint . '?' . $request_parameters;
  3261. $client = new Client(['verify' => false]);
  3262. $response = $client->get($request_url, ['headers' => $headers]);
  3263. $response_arr = json_decode($response->getBody()->getContents(), true);
  3264. $result = [
  3265. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  3266. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  3267. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  3268. 'Region' => env('VOLC_REGION'),
  3269. 'Endpoint' => env('VOLC_END_POINT'),
  3270. 'Bucket' => env('VOLC_BUCKET'),
  3271. ];
  3272. // 缓存token
  3273. Redis::setex('volc_sts_token', 3000, json_encode($result));
  3274. return $result;
  3275. } else {
  3276. return json_decode($token, true);
  3277. }
  3278. // $response = $response['Response'];
  3279. // $access_key = $response['Credentials']['AccessKeyId'];
  3280. // $secret_key = $response['Credentials']['AccessKeySecret'];
  3281. // $security_token = $response['Credentials']['SecurityToken'];
  3282. // $expiration = $response['Credentials']['Expiration'];
  3283. // dd($response_arr);
  3284. }
  3285. public function emotionGroups($data) {
  3286. $id = getProp($data, 'group_id');
  3287. $group_name = getProp($data, 'group_name');
  3288. $voice_type = getProp($data, 'voice_type');
  3289. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  3290. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  3291. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  3292. if ($group_name) {
  3293. $query->where('group_name', 'like', "%{$group_name}%");
  3294. }
  3295. if ($id) {
  3296. $query->where('id', $id);
  3297. }
  3298. if ($voice_type) {
  3299. $query->where('voice_type', $voice_type);
  3300. }
  3301. return $query->orderBy('id')->get()->map(function ($value) {
  3302. return (array)$value;
  3303. })->toArray();
  3304. }
  3305. private function sign($key, $msg) {
  3306. return hash_hmac('sha256', $msg, $key, true);
  3307. }
  3308. // 生成签名密钥
  3309. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  3310. $kDate = $this->sign($key, $dateStamp);
  3311. $kRegion = $this->sign($kDate, $regionName);
  3312. $kService = $this->sign($kRegion, $serviceName);
  3313. $kSigning = $this->sign($kService, 'request');
  3314. return $kSigning;
  3315. }
  3316. // 获取签名头信息
  3317. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  3318. $contenttype = 'application/x-www-form-urlencoded';
  3319. $accept = 'application/json';
  3320. // 获取当前UTC时间
  3321. $t = new DateTime('now', new DateTimeZone('UTC'));
  3322. $xdate = $t->format('Ymd\THis\Z');
  3323. $datestamp = $t->format('Ymd');
  3324. // 1. 拼接规范请求串
  3325. $canonical_uri = '/';
  3326. $canonical_querystring = $request_parameters;
  3327. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  3328. $signed_headers = 'content-type;host;x-date';
  3329. // 空请求体的SHA256哈希
  3330. $payload_hash = hash('sha256', '');
  3331. $canonical_request = implode("\n", [
  3332. $method,
  3333. $canonical_uri,
  3334. $canonical_querystring,
  3335. $canonical_headers,
  3336. $signed_headers,
  3337. $payload_hash
  3338. ]);
  3339. // 2. 拼接待签名字符串
  3340. $algorithm = 'HMAC-SHA256';
  3341. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  3342. $hashed_canonical_request = hash('sha256', $canonical_request);
  3343. $string_to_sign = implode("\n", [
  3344. $algorithm,
  3345. $xdate,
  3346. $credential_scope,
  3347. $hashed_canonical_request
  3348. ]);
  3349. // 3. 计算签名
  3350. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  3351. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  3352. // 4. 添加签名到请求头
  3353. $authorization_header = sprintf(
  3354. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  3355. $algorithm,
  3356. $access_key,
  3357. $credential_scope,
  3358. $signed_headers,
  3359. $signature
  3360. );
  3361. return [
  3362. 'Accept' => $accept,
  3363. 'Content-Type' => $contenttype,
  3364. 'X-Date' => $xdate,
  3365. 'Authorization' => $authorization_header
  3366. ];
  3367. }
  3368. // 文字合成语音(火山引擎)
  3369. public function tts($data) {
  3370. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  3371. $headers = [
  3372. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  3373. 'Content-Type' => 'application/json; charset=UTF-8'
  3374. ];
  3375. $post_data = [
  3376. 'app' => [
  3377. 'appid' => env('VOLC_APPID'),
  3378. 'token' => env('VOLC_TOKEN'),
  3379. 'cluster' => 'volcano_tts'
  3380. ],
  3381. 'user' => [
  3382. 'uid' => 'mp_audio'
  3383. ],
  3384. // 'audio' => [
  3385. // 'voice_type' =>
  3386. // ],
  3387. ];
  3388. }
  3389. public function scriptList($data) {
  3390. $uid = Site::getUid();
  3391. $script_id = getProp($data, 'script_id');
  3392. $script_name = getProp($data, 'script_name');
  3393. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  3394. if ($script_id) {
  3395. $query->where('id', $script_id);
  3396. }
  3397. if ($script_name) {
  3398. $query->where('script_name', 'like', "%{$script_name}%");
  3399. }
  3400. return $query->orderBy('created_at', 'desc')->paginate(12);
  3401. }
  3402. public function scripts($data) {
  3403. $uid = Site::getUid();
  3404. $script_id = getProp($data, 'script_id');
  3405. $script_name = getProp($data, 'script_name');
  3406. $is_products = getProp($data, 'is_products');
  3407. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  3408. if ($script_id) {
  3409. $query->where('id', $script_id);
  3410. }
  3411. if ($is_products !== '') {
  3412. $query->where('is_products', $is_products);
  3413. }
  3414. if ($script_name) {
  3415. $query->where('script_name', 'like', "%{$script_name}%");
  3416. }
  3417. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  3418. return (array)$value;
  3419. })->toArray();
  3420. }
  3421. public function scriptInfo($data) {
  3422. $uid = Site::getUid();
  3423. $script_id = getProp($data, 'script_id');
  3424. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  3425. // ->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();
  3426. ->selectRaw('id as script_id, script_name')->first();
  3427. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3428. $script = (array)$script;
  3429. // 获取分集组信息
  3430. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  3431. ->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')
  3432. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  3433. $value = (array)$value;
  3434. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  3435. return (array)$value;
  3436. })->toArray();
  3437. $script['group'] = $groups;
  3438. return $script;
  3439. }
  3440. public function createScript($data) {
  3441. $script_name = getProp($data, 'script_name');
  3442. $uid = Site::getUid(); // 获取当前用户ID
  3443. $cpid = Site::getCpid(); // 获取当前公司组ID
  3444. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  3445. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  3446. $script_name .= '_'.date('YmdHis');
  3447. }
  3448. return DB::table('mp_scripts')->insertGetId([
  3449. 'script_name' => $script_name,
  3450. 'user_id' => $uid,
  3451. 'cpid' => $cpid,
  3452. 'created_at' => date('Y-m-d H:i:s'),
  3453. 'updated_at' => date('Y-m-d H:i:s')
  3454. ]);
  3455. }
  3456. public function editScript($data) {
  3457. $script_id = getProp($data, 'script_id');
  3458. $script_name = getProp($data, 'script_name');
  3459. $uid = Site::getUid(); // 获取当前用户ID
  3460. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  3461. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  3462. if ($id && (int)$id !== (int)$script_id) {
  3463. $script_name .= '_'.date('YmdHis');
  3464. }
  3465. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3466. 'script_name' => $script_name,
  3467. 'updated_at' => date('Y-m-d H:i:s')
  3468. ]);
  3469. }
  3470. public function delScript($data) {
  3471. $script_id = getProp($data, 'script_id');
  3472. $uid = Site::getUid(); // 获取当前用户ID
  3473. if (!$script_id) Utils::throwError('20003:请选择剧本');
  3474. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3475. 'is_deleted' => 1,
  3476. 'updated_at' => date('Y-m-d H:i:s')
  3477. ]);
  3478. }
  3479. public function createEpisode($data) {
  3480. $script_id = getProp($data, 'script_id');
  3481. $group_name = getProp($data, 'group_name');
  3482. $remark = getProp($data, 'remark');
  3483. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  3484. $uid = Site::getUid(); // 获取当前用户ID
  3485. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  3486. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  3487. $group_name .= '_'.date('YmdHis');
  3488. }
  3489. return DB::table('mp_script_episode_group')->insertGetId([
  3490. 'script_id' => $script_id,
  3491. 'group_name' => $group_name,
  3492. 'user_id' => $uid,
  3493. 'remark' => $remark,
  3494. 'created_at' => date('Y-m-d H:i:s'),
  3495. 'updated_at' => date('Y-m-d H:i:s')
  3496. ]);
  3497. }
  3498. public function editEpisode($data) {
  3499. $group_id = getProp($data, 'group_id');
  3500. $start_episode_number = getProp($data, 'start_episode_number');
  3501. $end_episode_number = getProp($data, 'end_episode_number');
  3502. $group_name = getProp($data, 'group_name');
  3503. $uid = Site::getUid(); // 获取当前用户ID
  3504. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  3505. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  3506. if ($id && (int)$id !== (int)$group_id) {
  3507. $group_name .= '_'.date('YmdHis');
  3508. }
  3509. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3510. 'group_name' => $group_name,
  3511. 'start_episode_number' => $start_episode_number,
  3512. 'end_episode_number' => $end_episode_number,
  3513. 'updated_at' => date('Y-m-d H:i:s')
  3514. ]);
  3515. }
  3516. public function delEpisode($data) {
  3517. $group_id = getProp($data, 'group_id');
  3518. $uid = Site::getUid(); // 获取当前用户ID
  3519. if (!$group_id) Utils::throwError('20003:请选择分集');
  3520. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3521. 'is_deleted' => 1,
  3522. 'updated_at' => date('Y-m-d H:i:s')
  3523. ]);
  3524. }
  3525. /**
  3526. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3527. *
  3528. * @param array $data 包含以下参数:
  3529. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3530. * - question: 用户问题(可选)
  3531. * - model: 使用的模型(r1 或 v3,默认 v3)
  3532. * @return \Generator 返回生成器,用于流式输出
  3533. */
  3534. public function generateEpisodes($data) {
  3535. $script_id = getProp($data, 'script_id');
  3536. $group_id = getProp($data, 'group_id');
  3537. // $file = getProp($data, 'file');
  3538. $file = '';
  3539. $content = getProp($data, 'content', '');
  3540. // $bid = getProp($data, 'bid', 0);
  3541. $bid = 0;
  3542. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3543. if (!$group) {
  3544. Utils::throwError('20003:剧本分集不存在');
  3545. }
  3546. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  3547. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  3548. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  3549. $prompt = getProp($data, 'prompt');
  3550. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  3551. $model = getProp($data, 'model');
  3552. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3553. Utils::throwError('20003:该模型不存在!');
  3554. }
  3555. // 检查是否存在重叠的剧集序号范围
  3556. $exists_groups = DB::table('mp_script_episode_group')
  3557. ->where('script_id', $script_id)
  3558. ->where('id', '<>', $group_id) // 排除当前组
  3559. ->where('is_deleted', 0)
  3560. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3561. // 检查新范围是否与现有范围重叠
  3562. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3563. // 新范围的开始在现有范围内
  3564. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3565. ->where('end_episode_number', '>=', $start_episode_sequence);
  3566. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3567. // 新范围的结束在现有范围内
  3568. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3569. ->where('end_episode_number', '>=', $end_episode_sequence);
  3570. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3571. // 新范围完全包含现有范围
  3572. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3573. ->where('end_episode_number', '<=', $end_episode_sequence);
  3574. });
  3575. })
  3576. ->select('start_episode_number', 'end_episode_number')
  3577. ->get();
  3578. if ($exists_groups->isNotEmpty()) {
  3579. $conflict_ranges = [];
  3580. foreach ($exists_groups as $group) {
  3581. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3582. }
  3583. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3584. }
  3585. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3586. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3587. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3588. if ($model === 'deepseek-chat') {
  3589. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3590. $model = 'deepseek-v4-flash';
  3591. $thinkingMode = 'disabled';
  3592. } elseif ($model === 'deepseek-reasoner') {
  3593. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3594. $model = 'deepseek-v4-flash';
  3595. $thinkingMode = 'enabled';
  3596. }
  3597. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3598. if (!$script) {
  3599. Utils::throwError('20003:剧本不存在');
  3600. }
  3601. $content = getProp($group, 'content');
  3602. if (!$file && !$content && !$bid) {
  3603. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3604. }
  3605. // 提取文件内容
  3606. if ($file) {
  3607. $content = $this->extractFileContent($file);
  3608. if (!$content) {
  3609. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3610. }
  3611. } elseif ($bid) {
  3612. $content = $this->getContentByBid($bid);
  3613. if (!$content) {
  3614. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3615. }
  3616. } elseif ($content) {
  3617. $content = filterContent($content);
  3618. } elseif ($prompt) {
  3619. $content = filterContent($prompt);
  3620. } else {
  3621. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3622. }
  3623. // 构建消息
  3624. $messages = [
  3625. $this->sys_message,
  3626. [
  3627. 'role' => 'user',
  3628. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3629. ]
  3630. ];
  3631. $post_data = [
  3632. 'model' => $model,
  3633. 'messages' => $messages,
  3634. // 'max_tokens' => 8192,
  3635. 'temperature' => 0.7,
  3636. 'frequency_penalty' => 0,
  3637. 'presence_penalty' => 0,
  3638. 'thinking' => ['type' => $thinkingMode],
  3639. 'response_format' => ['type' => 'text'],
  3640. 'stream' => true
  3641. ];
  3642. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3643. // 根据模型类型选择调用方法
  3644. $fullContent = '';
  3645. $fullReasoningContent = '';
  3646. $usage = [];
  3647. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3648. // DeepSeek 官方模型使用 DeepSeek API
  3649. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3650. } else if (in_array($model, $this->gpt_text_models)) {
  3651. // GPT-5.4 模型使用 TokenRouter API
  3652. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3653. } else if (in_array($model, $this->gemini_text_models)) {
  3654. // Gemini 模型使用 Gemini API
  3655. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3656. } else {
  3657. // 其他模型使用火山引擎API
  3658. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3659. }
  3660. // 处理流式输出
  3661. foreach ($streamGenerator as $chunk) {
  3662. if (isset($chunk['type'])) {
  3663. if ($chunk['type'] === 'done') {
  3664. // 最终结果
  3665. $fullContent = $chunk['full_content'];
  3666. $fullReasoningContent = $chunk['full_reasoning'];
  3667. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3668. } else {
  3669. // 逐块yield数据
  3670. yield $chunk;
  3671. }
  3672. }
  3673. }
  3674. dLog('deepseek')->info('完整内容: '.$fullContent);
  3675. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3676. // 处理完整内容并返回最终结果
  3677. $script_arr = [];
  3678. if ($fullContent) {
  3679. $script_arr = extractScriptContent($fullContent);
  3680. }
  3681. logDB('deepseek', 'info', '解析内容', $script_arr);
  3682. if (!$script_arr['episodes']) {
  3683. Utils::throwError('20003:未生成剧本相关信息');
  3684. // yield [
  3685. // 'type' => 'done',
  3686. // 'script' => $script_arr,
  3687. // 'msg' => '未生成剧本相关信息',
  3688. // 'answer' => $fullContent,
  3689. // 'reasoning' => $fullReasoningContent,
  3690. // 'usage' => $usage
  3691. // ];
  3692. // return ;
  3693. }
  3694. try {
  3695. DB::beginTransaction();
  3696. // // 返回前保存剧本内容
  3697. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3698. // 'content' => $content,
  3699. // 'updated_at' => date('Y-m-d H:i:s')
  3700. // ]);
  3701. // if (!$boolen) {
  3702. // Utils::throwError('20003:保存剧本内容失败');
  3703. // }
  3704. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3705. // 'start_episode_number' => $start_episode_sequence,
  3706. // 'end_episode_number' => $end_episode_sequence,
  3707. // 'updated_at' => date('Y-m-d H:i:s')
  3708. // ]);
  3709. // if (!$boolen1) {
  3710. // Utils::throwError('20003:保存分集失败');
  3711. // }
  3712. $episode_content = '';
  3713. $episodes = [];
  3714. foreach ($script_arr['episodes'] as $item) {
  3715. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  3716. // $episodes[] = [
  3717. // 'script_id' => $script_id,
  3718. // 'episode_number' => $item['episode_number'],
  3719. // 'episode_name' => $item['episode_name'],
  3720. // 'episode_content' => $item['episode_content'],
  3721. // 'created_at' => date('Y-m-d H:i:s'),
  3722. // 'updated_at' => date('Y-m-d H:i:s'),
  3723. // ];
  3724. }
  3725. if ($episode_content) {
  3726. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3727. 'episode_content' => $episode_content,
  3728. 'updated_at' => date('Y-m-d H:i:s')
  3729. ]);
  3730. if (!$boolen2) {
  3731. Utils::throwError('20003:保存分集内容失败');
  3732. }
  3733. }else {
  3734. Utils::throwError('20003:分集剧本解析失败');
  3735. }
  3736. }catch (\Exception $e) {
  3737. DB::rollBack();
  3738. Utils::throwError('20003:'.$e->getMessage());
  3739. }
  3740. DB::commit();
  3741. // 仅记录 token 使用明细(不扣积分)
  3742. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  3743. 'model' => $model,
  3744. 'script_id' => $script_id,
  3745. 'group_id' => $group_id,
  3746. 'source' => 'generateEpisodes',
  3747. ], $model);
  3748. yield [
  3749. 'type' => 'done',
  3750. 'script' => $script_arr,
  3751. 'episode_content' => $episode_content,
  3752. 'answer' => $fullContent,
  3753. 'reasoning' => $fullReasoningContent,
  3754. 'usage' => $usage
  3755. ];
  3756. }
  3757. public function chatWithFileStream($data) {
  3758. $script_id = getProp($data, 'script_id');
  3759. $group_id = getProp($data, 'group_id');
  3760. $file = getProp($data, 'file');
  3761. $content = getProp($data, 'content', '');
  3762. $bid = getProp($data, 'bid', 0);
  3763. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3764. $total_episode_num = getProp($data, 'total_episode_num', 30);
  3765. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  3766. $prompt = getProp($data, 'prompt');
  3767. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  3768. if (!empty($prompt)) {
  3769. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  3770. }
  3771. $question = getProp($data, 'question', $baseQuestion);
  3772. $model = getProp($data, 'model');
  3773. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3774. Utils::throwError('20003:该模型不存在!');
  3775. }
  3776. // 检查是否存在重叠的剧集序号范围
  3777. $exists_groups = DB::table('mp_script_episode_group')
  3778. ->where('script_id', $script_id)
  3779. ->where('id', '<>', $group_id)
  3780. ->where('is_deleted', 0)
  3781. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3782. // 检查新范围是否与现有范围重叠
  3783. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3784. // 新范围的开始在现有范围内
  3785. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3786. ->where('end_episode_number', '>=', $start_episode_sequence);
  3787. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3788. // 新范围的结束在现有范围内
  3789. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3790. ->where('end_episode_number', '>=', $end_episode_sequence);
  3791. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3792. // 新范围完全包含现有范围
  3793. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3794. ->where('end_episode_number', '<=', $end_episode_sequence);
  3795. });
  3796. })
  3797. ->select('start_episode_number', 'end_episode_number')
  3798. ->get();
  3799. if ($exists_groups->isNotEmpty()) {
  3800. $conflict_ranges = [];
  3801. foreach ($exists_groups as $group) {
  3802. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3803. }
  3804. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3805. }
  3806. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3807. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3808. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3809. if ($model === 'deepseek-chat') {
  3810. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3811. $model = 'deepseek-v4-flash';
  3812. $thinkingMode = 'disabled';
  3813. } elseif ($model === 'deepseek-reasoner') {
  3814. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3815. $model = 'deepseek-v4-flash';
  3816. $thinkingMode = 'enabled';
  3817. }
  3818. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3819. if (!$script) {
  3820. Utils::throwError('20003:剧本不存在');
  3821. }
  3822. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3823. if (!$group) {
  3824. Utils::throwError('20003:剧本分集不存在');
  3825. }
  3826. if (!$file && !$content && !$bid) {
  3827. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3828. }
  3829. // 提取文件内容
  3830. if ($file) {
  3831. $content = $this->extractFileContent($file);
  3832. if (!$content) {
  3833. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3834. }
  3835. } elseif ($bid) {
  3836. $content = $this->getContentByBid($bid);
  3837. if (!$content) {
  3838. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3839. }
  3840. } elseif ($content) {
  3841. $content = filterContent($content);
  3842. } elseif ($prompt) {
  3843. $content = filterContent($prompt);
  3844. } else {
  3845. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3846. }
  3847. // 构建消息
  3848. $messages = [
  3849. [
  3850. 'role' => 'system',
  3851. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3852. 强制要求:\n
  3853. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3854. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  3855. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  3856. 普通要求:\n
  3857. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  3858. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  3859. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  3860. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  3861. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  3862. 示例如下:\n
  3863. ###剧本名:西昆仑
  3864. ###故事梗概
  3865. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3866. ###剧本亮点
  3867. 亮点1:绝境奇药,生死一线
  3868. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3869. 亮点2:结拜兄妹,化解尴尬
  3870. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3871. 亮点3:纤发夺命,情愫暗涌
  3872. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3873. ###人物关系
  3874. 阿雪与梁萧之间存在兄妹之情。
  3875. ###核心矛盾
  3876. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3877. ###主体列表
  3878. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  3879. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  3880. 阴阳球:天地异宝,能化生精气,救人于危难。
  3881. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  3882. ###美术风格
  3883. 基础画风风格词:厚涂古风
  3884. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3885. ###场景列表
  3886. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  3887. [
  3888. 'role' => 'user',
  3889. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3890. ]
  3891. ];
  3892. $post_data = [
  3893. 'model' => $model,
  3894. 'messages' => $messages,
  3895. // 'max_tokens' => 8192,
  3896. 'temperature' => 0.7,
  3897. 'frequency_penalty' => 0,
  3898. 'presence_penalty' => 0,
  3899. 'thinking' => ['type' => $thinkingMode],
  3900. 'response_format' => ['type' => 'text'],
  3901. 'stream' => true
  3902. ];
  3903. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3904. // 根据模型类型选择调用方法
  3905. $fullContent = '';
  3906. $fullReasoningContent = '';
  3907. $usage = [];
  3908. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3909. // DeepSeek 官方模型使用 DeepSeek API
  3910. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3911. } else if (in_array($model, $this->gpt_text_models)) {
  3912. // GPT-5.4 模型使用 TokenRouter API
  3913. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3914. } else if (in_array($model, $this->gemini_text_models)) {
  3915. // Gemini 模型使用 Gemini API
  3916. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3917. } else {
  3918. // 其他模型使用火山引擎API
  3919. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3920. }
  3921. // 处理流式输出
  3922. foreach ($streamGenerator as $chunk) {
  3923. if (isset($chunk['type'])) {
  3924. if ($chunk['type'] === 'done') {
  3925. // 最终结果
  3926. $fullContent = $chunk['full_content'];
  3927. $fullReasoningContent = $chunk['full_reasoning'];
  3928. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3929. } else {
  3930. // 逐块yield数据
  3931. yield $chunk;
  3932. }
  3933. }
  3934. }
  3935. dLog('deepseek')->info('完整内容: '.$fullContent);
  3936. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3937. // 处理完整内容并返回最终结果
  3938. $script_arr = [];
  3939. if ($fullContent) {
  3940. $script_arr = extractScriptContent($fullContent);
  3941. }
  3942. logDB('deepseek', 'info', '解析内容', $script_arr);
  3943. if (!$script_arr['roles']) {
  3944. Utils::throwError('20003:未生成剧本相关信息');
  3945. // yield [
  3946. // 'type' => 'done',
  3947. // 'script' => $script_arr,
  3948. // 'msg' => '未生成剧本相关信息',
  3949. // 'answer' => $fullContent,
  3950. // 'reasoning' => $fullReasoningContent,
  3951. // 'usage' => $usage
  3952. // ];
  3953. }
  3954. try {
  3955. DB::beginTransaction();
  3956. // // 返回前保存剧本内容
  3957. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3958. // 'content' => $content,
  3959. // 'status' => '解析完成',
  3960. // 'updated_at' => date('Y-m-d H:i:s')
  3961. // ]);
  3962. // if (!$boolen) {
  3963. // Utils::throwError('20003:保存剧本内容失败');
  3964. // }
  3965. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3966. 'start_episode_number' => $start_episode_sequence,
  3967. 'end_episode_number' => $end_episode_sequence,
  3968. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3969. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3970. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3971. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3972. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3973. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3974. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3975. 'status' => '解析完成',
  3976. 'content' => $content,
  3977. 'updated_at' => date('Y-m-d H:i:s')
  3978. ]);
  3979. if (!$boolen1) {
  3980. Utils::throwError('20003:保存分集失败');
  3981. }
  3982. // $episodes = [];
  3983. // foreach ($script_arr['episodes'] as $item) {
  3984. // $episodes[] = [
  3985. // 'script_id' => $script_id,
  3986. // 'episode_number' => $item['episode_number'],
  3987. // 'episode_name' => $item['episode_name'],
  3988. // 'episode_content' => $item['episode_content'],
  3989. // 'created_at' => date('Y-m-d H:i:s'),
  3990. // 'updated_at' => date('Y-m-d H:i:s'),
  3991. // ];
  3992. // }
  3993. // if ($episodes) {
  3994. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  3995. // if (!$boolen2) {
  3996. // Utils::throwError('20003:保存分集内容失败');
  3997. // }
  3998. // }else {
  3999. // Utils::throwError('20003:分集剧本解析失败');
  4000. // }
  4001. }catch (\Exception $e) {
  4002. DB::rollBack();
  4003. Utils::throwError('20003:'.$e->getMessage());
  4004. }
  4005. DB::commit();
  4006. // 仅记录 token 使用明细(不扣积分)
  4007. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  4008. 'model' => $model,
  4009. 'script_id' => $script_id,
  4010. 'group_id' => $group_id,
  4011. 'source' => 'chatWithFileStream',
  4012. ], $model);
  4013. yield [
  4014. 'type' => 'done',
  4015. 'script' => $script_arr,
  4016. 'answer' => $fullContent,
  4017. 'reasoning' => $fullReasoningContent,
  4018. 'usage' => $usage
  4019. ];
  4020. }
  4021. /**
  4022. * 上传文件识别文字内容并与 DeepSeek 进行对话
  4023. *
  4024. * @param array $data 包含以下参数:
  4025. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4026. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  4027. * - model: 使用的模型(r1 或 v3,默认 v3)
  4028. * @return array
  4029. */
  4030. public function chatWithFile($data) {
  4031. $script_id = getProp($data, 'script_id');
  4032. $file = getProp($data, 'file');
  4033. $content = getProp($data, 'content', '');
  4034. $bid = getProp($data, 'bid', 0);
  4035. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4036. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4037. $prompt = getProp($data, 'prompt');
  4038. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4039. if (!empty($prompt)) {
  4040. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4041. }
  4042. $question = getProp($data, 'question', $baseQuestion);
  4043. // 处理文本模型
  4044. $model = getProp($data, 'model');
  4045. if (!$model) {
  4046. // 用户没有输入,使用默认值
  4047. $model = 'doubao-seed-2-0-mini-260215';
  4048. }
  4049. // 验证模型是否在可用模型表中
  4050. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4051. $model = 'doubao-seed-2-0-mini-260215';
  4052. }
  4053. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4054. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4055. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4056. if ($model === 'deepseek-chat') {
  4057. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4058. $model = 'deepseek-v4-flash';
  4059. $thinkingMode = 'disabled';
  4060. } elseif ($model === 'deepseek-reasoner') {
  4061. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4062. $model = 'deepseek-v4-flash';
  4063. $thinkingMode = 'enabled';
  4064. }
  4065. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4066. if (!$script) {
  4067. Utils::throwError('20003:剧本不存在');
  4068. }
  4069. if (!$file && !$content && !$bid) {
  4070. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4071. }
  4072. // 提取文件内容
  4073. if ($file) {
  4074. $content = $this->extractFileContent($file);
  4075. if (!$content) {
  4076. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4077. }
  4078. } elseif ($bid) {
  4079. $content = $this->getContentByBid($bid);
  4080. if (!$content) {
  4081. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4082. }
  4083. } elseif ($content) {
  4084. $content = filterContent($content);
  4085. } elseif ($prompt) {
  4086. $content = filterContent($prompt);
  4087. } else {
  4088. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4089. }
  4090. // 构建消息
  4091. $messages = [
  4092. $this->sys_message,
  4093. [
  4094. 'role' => 'user',
  4095. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4096. ]
  4097. ];
  4098. $post_data = [
  4099. 'model' => $model,
  4100. 'messages' => $messages,
  4101. // 'max_tokens' => 8192,
  4102. 'temperature' => 0.7,
  4103. 'frequency_penalty' => 0,
  4104. 'presence_penalty' => 0,
  4105. 'thinking' => ['type' => $thinkingMode],
  4106. 'response_format' => ['type' => 'text'],
  4107. 'stream' => false
  4108. ];
  4109. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4110. // 根据模型类型选择调用方法
  4111. $fullContent = '';
  4112. $usage = [];
  4113. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4114. // DeepSeek 官方模型使用 DeepSeek API
  4115. $chatResult = $this->chatOnly($post_data);
  4116. } else if (in_array($model, $this->gpt_text_models)) {
  4117. // GPT-5.4 模型使用 TokenRouter API
  4118. $chatResult = $this->gpt54ChatOnly($post_data);
  4119. } else {
  4120. // 其他模型使用火山引擎API
  4121. $chatResult = $this->volcEngineChatCompletion($post_data);
  4122. }
  4123. if (is_array($chatResult)) {
  4124. $fullContent = $chatResult['fullContent'];
  4125. $usage = $chatResult['usage'];
  4126. }
  4127. $script_arr = [];
  4128. // 处理结果
  4129. if ($fullContent) {
  4130. $script_arr = extractScriptContent($fullContent);
  4131. }
  4132. // 返回前保存剧本内容
  4133. DB::table('mp_scripts')->where('id', $script_id)->update([
  4134. 'content' => $content,
  4135. 'updated_at' => date('Y-m-d H:i:s')
  4136. ]);
  4137. // 仅记录 token 使用明细(不扣积分)
  4138. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  4139. 'model' => $model,
  4140. 'script_id' => $script_id,
  4141. 'source' => 'chatWithFile',
  4142. ], $model);
  4143. return [
  4144. 'script' => $script_arr,
  4145. 'answer' => $fullContent,
  4146. 'usage' => $usage
  4147. ];
  4148. }
  4149. public function getEpisodeContent($data) {
  4150. $group_id = getProp($data, 'group_id');
  4151. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  4152. }
  4153. public function saveEpisodeContent($data) {
  4154. $script_id = getProp($data, 'script_id');
  4155. $group_id = getProp($data, 'group_id');
  4156. $start_episode_sequence = getProp($data, 'start_episode_number');
  4157. $end_episode_sequence = getProp($data, 'end_episode_number');
  4158. // 检查是否存在重叠的剧集序号范围
  4159. $exists_groups = DB::table('mp_script_episode_group')
  4160. ->where('script_id', $script_id)
  4161. ->where('id', '<>', $group_id) // 排除当前组
  4162. ->where('is_deleted', 0)
  4163. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4164. // 检查新范围是否与现有范围重叠
  4165. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4166. // 新范围的开始在现有范围内
  4167. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4168. ->where('end_episode_number', '>=', $start_episode_sequence);
  4169. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4170. // 新范围的结束在现有范围内
  4171. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4172. ->where('end_episode_number', '>=', $end_episode_sequence);
  4173. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4174. // 新范围完全包含现有范围
  4175. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4176. ->where('end_episode_number', '<=', $end_episode_sequence);
  4177. });
  4178. })
  4179. ->select('start_episode_number', 'end_episode_number')
  4180. ->get();
  4181. if ($exists_groups->isNotEmpty()) {
  4182. $conflict_ranges = [];
  4183. foreach ($exists_groups as $group) {
  4184. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4185. }
  4186. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4187. }
  4188. $episode_content = getProp($data, 'episode_content');
  4189. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  4190. 'content' => $episode_content,
  4191. 'start_episode_number' => $start_episode_sequence,
  4192. 'end_episode_number' => $end_episode_sequence,
  4193. 'updated_at' => date('Y-m-d H:i:s')
  4194. ]);
  4195. $script_arr =getProp($data, 'script', []);
  4196. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  4197. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4198. $script_id = getProp($data, 'script_id');
  4199. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  4200. try {
  4201. DB::beginTransaction();
  4202. $update_data = [
  4203. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4204. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4205. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4206. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4207. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4208. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4209. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4210. 'status' => 3,
  4211. 'start_episode_sequence' => $start_episode_sequence,
  4212. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  4213. 'episode_num' => count($script_arr['episodes']),
  4214. 'updated_at' => date('Y-m-d H:i:s')
  4215. ];
  4216. // 保存剧本内容
  4217. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  4218. if (!$boolen) {
  4219. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  4220. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  4221. Utils::throwError('20003:剧本内容保存失败');
  4222. }
  4223. // 保存分集内容
  4224. // 删除历史分集内容
  4225. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  4226. $episodes = [];
  4227. $sequence = 1;
  4228. foreach ($script_arr['episodes'] as $episode) {
  4229. $segment_number = 1;
  4230. foreach($episode['segments'] as $segment) {
  4231. $episodes[] = [
  4232. 'script_id' => $script_id,
  4233. 'episode_number' => $episode['episode_number'],
  4234. 'title' => $episode['title'],
  4235. // 'content' => $episode['content'],
  4236. 'content' => '',
  4237. 'segment_number' => $segment_number,
  4238. 'segment_content' => $segment['segment_content'],
  4239. 'sequence' => $sequence,
  4240. 'created_at' => date('Y-m-d H:i:s'),
  4241. 'updated_at' => date('Y-m-d H:i:s')
  4242. ];
  4243. $sequence++;
  4244. $segment_number++;
  4245. }
  4246. }
  4247. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4248. if (!$boolen2) {
  4249. dLog('deepseek')->info('分集内容保存失败', $episodes);
  4250. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  4251. Utils::throwError('20003:分集内容保存失败');
  4252. }
  4253. } catch (\Exception $e) {
  4254. DB::rollBack();
  4255. Utils::throwError('20003:'.$e->getMessage());
  4256. }
  4257. DB::commit();
  4258. return true;
  4259. }
  4260. public function getBookContent($data) {
  4261. $bid = getProp($data, 'bid');
  4262. $start_sequence = getProp($data, 'start_sequence');
  4263. $end_sequence = getProp($data, 'end_sequence');
  4264. $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])
  4265. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  4266. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  4267. return $return_content;
  4268. }
  4269. public function exportScript($data) {
  4270. $filename = getProp($data, 'filename');
  4271. $script_id = getProp($data, 'script_id');
  4272. $group_id = getProp($data, 'group_id');
  4273. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  4274. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  4275. if (!$script) Utils::throwError('20003:该剧本不存在!');
  4276. $script = (array)$script;
  4277. // 获取分集组信息
  4278. if ($group_id) {
  4279. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4280. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4281. ->get()->map(function($value) {
  4282. return (array)$value;
  4283. })->toArray();
  4284. }else {
  4285. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4286. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4287. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  4288. return (array)$value;
  4289. })->toArray();
  4290. }
  4291. if (!$groups) Utils::throwError('20003:分集不存在');
  4292. $script['group'] = $groups;
  4293. $export_type = getProp($data, 'export_type', 'txt');
  4294. // 生成文件名
  4295. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  4296. // 根据导出类型生成不同格式的文件
  4297. switch ($export_type) {
  4298. case 'txt':
  4299. return $this->exportScriptAsTxt($script, $filename);
  4300. case 'pdf':
  4301. return $this->exportScriptAsPdf($script, $filename);
  4302. default:
  4303. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  4304. }
  4305. }
  4306. /**
  4307. * 导出剧本为TXT格式
  4308. */
  4309. private function exportScriptAsTxt($script, $filename) {
  4310. // 构建TXT内容
  4311. $content = $this->buildScriptContent($script);
  4312. // 设置响应头,直接下载
  4313. header('Content-Type: text/plain; charset=utf-8');
  4314. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  4315. header('Content-Length: ' . strlen($content));
  4316. // 输出内容并结束
  4317. echo $content;
  4318. exit();
  4319. }
  4320. /**
  4321. * 导出剧本为PDF格式
  4322. */
  4323. private function exportScriptAsPdf($script, $filename) {
  4324. // 使用HTML转PDF的方式来更好地支持中文
  4325. $htmlContent = $this->buildScriptHtmlForPdf($script);
  4326. // 创建PDF实例
  4327. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  4328. // 设置文档信息
  4329. $pdf->SetCreator('剧本导出系统');
  4330. $pdf->SetAuthor('系统');
  4331. $pdf->SetTitle($script['script_name']);
  4332. $pdf->SetSubject('剧本导出');
  4333. // 设置边距
  4334. $pdf->SetMargins(15, 15, 15);
  4335. $pdf->SetAutoPageBreak(TRUE, 15);
  4336. // 添加页面
  4337. $pdf->AddPage();
  4338. // 注册并使用 simsun.ttf 字体
  4339. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  4340. // 使用HTML内容生成PDF
  4341. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  4342. // 直接输出PDF文件供下载
  4343. header('Content-Type: application/pdf');
  4344. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  4345. // 直接输出PDF内容
  4346. $pdf->Output($filename . '.pdf', 'D');
  4347. exit();
  4348. }
  4349. /**
  4350. * 构建用于PDF的HTML内容
  4351. */
  4352. private function buildScriptHtmlForPdf($script) {
  4353. $html = '<style>
  4354. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  4355. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  4356. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  4357. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  4358. .info { margin-bottom: 8px; }
  4359. .group { margin-bottom: 30px; page-break-inside: avoid; }
  4360. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  4361. .segment { margin-bottom: 10px; margin-left: 20px; }
  4362. .episode-content { white-space: pre-wrap; }
  4363. </style>';
  4364. // 标题
  4365. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  4366. // 处理分组数据
  4367. if (!empty($script['group']) && is_array($script['group'])) {
  4368. $groups = (array)$script['group'];
  4369. foreach ($groups as $group) {
  4370. $html .= '<div class="group">';
  4371. // 分组标题
  4372. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  4373. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  4374. // 故事梗概
  4375. if (!empty($group['intro'])) {
  4376. $html .= '<h3>故事梗概</h3>';
  4377. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  4378. }
  4379. // 剧本亮点
  4380. if (!empty($group['highlights'])) {
  4381. $html .= '<h3>剧本亮点</h3>';
  4382. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  4383. }
  4384. // 人物关系
  4385. if (!empty($group['role_relationship'])) {
  4386. $html .= '<h3>人物关系</h3>';
  4387. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  4388. }
  4389. // 核心矛盾
  4390. if (!empty($group['core_contradiction'])) {
  4391. $html .= '<h3>核心矛盾</h3>';
  4392. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  4393. }
  4394. // 主体列表
  4395. if (!empty($group['roles']) && is_array($group['roles'])) {
  4396. $html .= '<h3>主体列表</h3>';
  4397. $html .= '<ul>';
  4398. foreach ($group['roles'] as $role) {
  4399. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  4400. }
  4401. $html .= '</ul>';
  4402. }
  4403. // 美术风格
  4404. if (!empty($group['art_style'])) {
  4405. $html .= '<h3>美术风格</h3>';
  4406. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  4407. }
  4408. // 场景列表
  4409. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4410. $html .= '<h3>场景列表</h3>';
  4411. $html .= '<ul>';
  4412. foreach ($group['scenes'] as $scene) {
  4413. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  4414. }
  4415. $html .= '</ul>';
  4416. }
  4417. // 分集剧本
  4418. if (!empty($group['episode_content'])) {
  4419. $html .= '<h3>分集剧本</h3>';
  4420. // 去除零宽字符和其他不可见字符
  4421. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  4422. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  4423. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  4424. }
  4425. $html .= '</div>';
  4426. }
  4427. }
  4428. return $html;
  4429. }
  4430. /**
  4431. * 构建PDF内容
  4432. */
  4433. private function buildPdfContent($pdf, $script) {
  4434. // 标题
  4435. $pdf->SetFont('dejavusans', 'B', 18);
  4436. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  4437. $pdf->Ln(5);
  4438. // 基本信息
  4439. $pdf->SetFont('dejavusans', '', 12);
  4440. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  4441. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  4442. $pdf->Ln(5);
  4443. // 剧本简介
  4444. if (!empty($script['intro'])) {
  4445. $pdf->SetFont('dejavusans', 'B', 14);
  4446. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  4447. $pdf->SetFont('dejavusans', '', 12);
  4448. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  4449. $pdf->Ln(3);
  4450. }
  4451. // 亮点
  4452. if (!empty($script['highlights'])) {
  4453. $pdf->SetFont('dejavusans', 'B', 14);
  4454. $pdf->Cell(0, 10, '亮点', 0, 1);
  4455. $pdf->SetFont('dejavusans', '', 12);
  4456. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  4457. $pdf->Ln(3);
  4458. }
  4459. // 核心矛盾
  4460. if (!empty($script['core_contradiction'])) {
  4461. $pdf->SetFont('dejavusans', 'B', 14);
  4462. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  4463. $pdf->SetFont('dejavusans', '', 12);
  4464. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  4465. $pdf->Ln(3);
  4466. }
  4467. // 艺术风格
  4468. if (!empty($script['art_style'])) {
  4469. $pdf->SetFont('dejavusans', 'B', 14);
  4470. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  4471. $pdf->SetFont('dejavusans', '', 12);
  4472. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  4473. $pdf->Ln(3);
  4474. }
  4475. // 备注
  4476. if (!empty($script['remark'])) {
  4477. $pdf->SetFont('dejavusans', 'B', 14);
  4478. $pdf->Cell(0, 10, '备注', 0, 1);
  4479. $pdf->SetFont('dejavusans', '', 12);
  4480. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  4481. $pdf->Ln(3);
  4482. }
  4483. // 角色列表
  4484. if (!empty($script['roles']) && is_array($script['roles'])) {
  4485. $pdf->SetFont('dejavusans', 'B', 14);
  4486. $pdf->Cell(0, 10, '角色列表', 0, 1);
  4487. $pdf->SetFont('dejavusans', '', 12);
  4488. foreach ($script['roles'] as $index => $role) {
  4489. if (is_array($role) || is_object($role)) {
  4490. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  4491. } else {
  4492. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  4493. }
  4494. }
  4495. $pdf->Ln(3);
  4496. }
  4497. // 角色关系
  4498. if (!empty($script['role_relationship'])) {
  4499. $pdf->SetFont('dejavusans', 'B', 14);
  4500. $pdf->Cell(0, 10, '角色关系', 0, 1);
  4501. $pdf->SetFont('dejavusans', '', 12);
  4502. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  4503. $pdf->Ln(3);
  4504. }
  4505. // 场景列表
  4506. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  4507. $pdf->SetFont('dejavusans', 'B', 14);
  4508. $pdf->Cell(0, 10, '场景列表', 0, 1);
  4509. $pdf->SetFont('dejavusans', '', 12);
  4510. foreach ($script['scenes'] as $index => $scene) {
  4511. if (is_array($scene) || is_object($scene)) {
  4512. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  4513. } else {
  4514. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  4515. }
  4516. }
  4517. $pdf->Ln(5);
  4518. }
  4519. // 分集内容
  4520. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  4521. $pdf->SetFont('dejavusans', 'B', 16);
  4522. $pdf->Cell(0, 12, '分集内容', 0, 1);
  4523. $pdf->Ln(3);
  4524. foreach ($script['episodes'] as $episode) {
  4525. // 检查是否需要新页面
  4526. if ($pdf->GetY() > 250) {
  4527. $pdf->AddPage();
  4528. }
  4529. $pdf->SetFont('dejavusans', 'B', 14);
  4530. $episodeTitle = '第' . $episode['episode_number'] . '集';
  4531. if (!empty($episode['title'])) {
  4532. $episodeTitle .= ':' . $episode['title'];
  4533. }
  4534. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  4535. // 处理分段内容
  4536. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  4537. $pdf->SetFont('dejavusans', '', 12);
  4538. foreach ($episode['segments'] as $segment) {
  4539. if (!empty($segment['segment_content'])) {
  4540. // 如果有分段编号,显示分段标题
  4541. if (!empty($segment['segment_number'])) {
  4542. $pdf->SetFont('dejavusans', 'B', 12);
  4543. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  4544. $pdf->SetFont('dejavusans', '', 12);
  4545. }
  4546. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  4547. $pdf->Ln(2);
  4548. }
  4549. }
  4550. }
  4551. $pdf->Ln(5);
  4552. }
  4553. }
  4554. }
  4555. /**
  4556. * 构建剧本文本内容
  4557. */
  4558. private function buildScriptContent($script) {
  4559. $content = '';
  4560. $groups = $script['group'];
  4561. $groups = (array)$groups;
  4562. foreach ($groups as $group) {
  4563. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  4564. // 剧本基本信息
  4565. if (!empty($group['intro'])) {
  4566. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  4567. }
  4568. if (!empty($group['highlights'])) {
  4569. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  4570. }
  4571. if (!empty($group['role_relationship'])) {
  4572. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  4573. }
  4574. if (!empty($group['core_contradiction'])) {
  4575. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  4576. }
  4577. if (!empty($group['roles']) && is_array($group['roles'])) {
  4578. $content .= "###主体列表\n";
  4579. foreach ($group['roles'] as $role) {
  4580. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  4581. }
  4582. $content .= "\n\n";
  4583. }
  4584. if (!empty($group['art_style'])) {
  4585. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  4586. }
  4587. // 场景信息
  4588. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4589. $content .= "###场景列表\n";
  4590. foreach ($group['scenes'] as $scene) {
  4591. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  4592. }
  4593. $content .= "\n\n";
  4594. }
  4595. // 分集内容
  4596. if (!empty($group['episode_content'])) {
  4597. $content .= "###分集剧本\n";
  4598. $content .= $group['episode_content'];
  4599. // foreach ($script['episodes'] as $episode) {
  4600. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  4601. // // if (!empty($episode['episode_name'])) {
  4602. // // $content .= ":" . $episode['episode_name'];
  4603. // // }
  4604. // // $content .= "\n";
  4605. // $content .= $episode['episode_content'] . "\n\n";
  4606. // }
  4607. }
  4608. }
  4609. return $content;
  4610. }
  4611. /**
  4612. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4613. *
  4614. * @param array $data 包含以下参数:
  4615. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4616. * - question: 用户问题(可选)
  4617. * - model: 使用的模型(r1 或 v3,默认 v3)
  4618. * @return \Generator 返回生成器,用于流式输出
  4619. */
  4620. public function addChat($data) {
  4621. $uid = Site::getUid();
  4622. $anime_id = getProp($data, 'anime_id');
  4623. if (!$anime_id) Utils::throwError('20003:请选择对话');
  4624. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4625. if (!$anime) Utils::throwError('20003:对话不存在');
  4626. $file = getProp($data, 'file');
  4627. $content = getProp($data, 'content', '');
  4628. $bid = getProp($data, 'bid', 0);
  4629. $script_id = getProp($data, 'script_id', 0);
  4630. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  4631. $prompt = getProp($data, 'prompt');
  4632. $user_anime_name = getProp($anime, 'anime_name');
  4633. // 处理文本模型
  4634. $model = getProp($data, 'model');
  4635. if (!$model) {
  4636. // 用户没有输入,从anime表获取
  4637. $model = getProp($anime, 'model');
  4638. if (!$model) {
  4639. // anime表也没有,使用默认值
  4640. $model = 'doubao-seed-2-0-mini-260215';
  4641. }
  4642. }
  4643. // 验证模型是否在可用模型表中
  4644. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4645. $model = 'doubao-seed-2-0-mini-260215';
  4646. }
  4647. $is_multi = getProp($anime, 'is_multi');
  4648. $is_single = (int)$is_multi !== 1;
  4649. // 积分余额预检(仅单剧集模式收费)
  4650. if ($is_single) {
  4651. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  4652. }
  4653. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4654. if ($prompt) {
  4655. $question .= "本次修改要求如下:\n{$prompt}";
  4656. }
  4657. // if (!$file && !$content && !$bid) {
  4658. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4659. // }
  4660. // 提取文件内容
  4661. if ($file) {
  4662. $content = $this->extractFileContent($file);
  4663. if (!$content) {
  4664. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4665. }
  4666. } elseif ($script_id) {
  4667. $content = $this->getContentByScriptId($script_id);
  4668. if (!$content) {
  4669. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4670. }
  4671. } elseif ($bid) {
  4672. $content = $this->getContentByBid($bid);
  4673. if (!$content) {
  4674. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4675. }
  4676. } elseif ($content) {
  4677. $content = filterContent($content);
  4678. } else {
  4679. $content = getProp($anime, 'content');
  4680. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4681. $need_generate_content = true;
  4682. }
  4683. }
  4684. // 美术风格
  4685. $input_art_style = getProp($data, 'art_style');
  4686. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4687. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4688. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4689. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4690. 中年女:邻居阿姨
  4691. 老年男:幽默大爷
  4692. 老年女:婆婆
  4693. 萌娃:奶气萌娃";
  4694. // 判断是否需要生成原文内容
  4695. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4696. // 如果需要生成原文内容,添加额外的要求
  4697. $content_generation_requirement = $need_generate_content
  4698. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4699. : "";
  4700. // 美术风格
  4701. if (!$mappedArtStyle) {
  4702. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4703. }else {
  4704. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4705. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4706. }else {
  4707. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4708. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4709. }
  4710. }
  4711. $systemPrompt = $is_single
  4712. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4713. 强制要求:
  4714. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4715. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4716. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4717. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4718. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4719. 普通要求:
  4720. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4721. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4722. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  4723. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4724. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4725. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4726. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4727. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4728. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4729. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4730. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4731. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4732. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4733. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4734. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4735. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4736. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4737. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4738. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4739. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4740. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4741. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4742. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4743. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4744. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4745. 5.{$mappedArtStyle_prompt}\n\n
  4746. 示例如下:\n
  4747. ###剧本名:西昆仑
  4748. ###故事梗概
  4749. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4750. ###剧本亮点
  4751. 亮点1:绝境奇药,生死一线
  4752. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4753. 亮点2:结拜兄妹,化解尴尬
  4754. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4755. 亮点3:纤发夺命,情愫暗涌
  4756. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4757. ###人物关系
  4758. 阿雪与梁萧之间存在兄妹之情。
  4759. ###核心矛盾
  4760. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4761. ###主体列表
  4762. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4763. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4764. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4765. 姿态:站立。}{{甜心小美}}
  4766. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4767. 全景,正面拍摄,青年女性,亚洲人。
  4768. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4769. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4770. 姿态:站立。}{{阳光青年}}
  4771. ###美术风格
  4772. 基础画风风格词:厚涂古风
  4773. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4774. ###场景列表
  4775. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4776. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4777. 无人物。}
  4778. ###分镜剧本
  4779. ##第1幕:徐家老旧厨房 白天 室内
  4780. 分镜1
  4781. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4782. 场景:徐家老旧厨房
  4783. 构图设计:全景,低角度仰视
  4784. 运镜调度:手持拍摄
  4785. 配音角色:旁白
  4786. 出镜角色:许芸-校服装、徐母
  4787. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4788. 画面类型:普通画面
  4789. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4790. 分镜2
  4791. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4792. 场景:徐家老旧厨房
  4793. 构图设计:近景,徐母面部特写
  4794. 运镜调度:固定镜头
  4795. 配音角色:徐母
  4796. 出镜角色:徐母
  4797. 台词内容:问我夜不归宿死哪儿去了。
  4798. 画面类型:对口型
  4799. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4800. ##第2幕:徐家简陋客厅 黄昏 室内
  4801. 分镜3
  4802. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4803. 场景:徐家简陋客厅
  4804. 构图设计:全景,景深虚化
  4805. 运镜调度:固定镜头
  4806. 配音角色:旁白
  4807. 出镜角色:无
  4808. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4809. 画面类型:普通画面
  4810. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4811. 分镜4
  4812. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4813. 场景:徐家简陋客厅
  4814. 构图设计:特写,火车票
  4815. 运镜调度:固定镜头
  4816. 配音角色:旁白
  4817. 出镜角色:无
  4818. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4819. 画面类型:普通画面
  4820. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4821. "
  4822. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4823. 强制要求:\n
  4824. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4825. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4826. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4827. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4828. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4829. 普通要求:\n
  4830. 1.剧本名(必须生成)必须与文档内容高度相关
  4831. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4832. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4833. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4834. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4835. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4836. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4837. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4838. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4839. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4840. 4.{$mappedArtStyle_prompt}\n\n
  4841. 示例如下:\n
  4842. ###剧本名:西昆仑
  4843. ###故事梗概
  4844. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4845. ###剧本亮点
  4846. 亮点1:绝境奇药,生死一线
  4847. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4848. 亮点2:结拜兄妹,化解尴尬
  4849. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4850. 亮点3:纤发夺命,情愫暗涌
  4851. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4852. ###人物关系
  4853. 阿雪与梁萧之间存在兄妹之情。
  4854. ###核心矛盾
  4855. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4856. ###主体列表
  4857. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4858. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4859. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4860. 姿态:站立。}{{甜心小美}}
  4861. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4862. 全景,正面拍摄,青年女性,亚洲人。
  4863. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4864. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4865. 姿态:站立。}{{阳光青年}}
  4866. ###美术风格
  4867. 基础画风风格词:厚涂古风
  4868. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4869. ###场景列表
  4870. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4871. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4872. 无人物。}";
  4873. // 构建消息
  4874. $messages = [
  4875. [
  4876. 'role' => 'system',
  4877. 'content' => $systemPrompt
  4878. ],
  4879. [
  4880. 'role' => 'user',
  4881. 'content' => "以下是文档内容:
  4882. {$content}
  4883. 用户问题:
  4884. {$question}"
  4885. ]
  4886. ];
  4887. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4888. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4889. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4890. if ($model === 'deepseek-chat') {
  4891. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4892. $model = 'deepseek-v4-flash';
  4893. $thinkingMode = 'disabled';
  4894. } elseif ($model === 'deepseek-reasoner') {
  4895. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4896. $model = 'deepseek-v4-flash';
  4897. $thinkingMode = 'enabled';
  4898. }
  4899. $post_data = [
  4900. 'model' => $model,
  4901. 'messages' => $messages,
  4902. // 'max_tokens' => 8192,
  4903. 'temperature' => 0.7,
  4904. 'frequency_penalty' => 0,
  4905. 'presence_penalty' => 0,
  4906. 'response_format' => ['type' => 'text'],
  4907. 'thinking' => ['type'=>$thinkingMode],
  4908. 'stream' => true // 启用流式输出
  4909. ];
  4910. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4911. // 根据模型类型选择调用方法
  4912. $fullContent = '';
  4913. $fullReasoningContent = '';
  4914. $usage = [];
  4915. try {
  4916. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4917. // DeepSeek 官方模型使用 DeepSeek API
  4918. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4919. } else if (in_array($model, $this->gpt_text_models)) {
  4920. // GPT-5.4 模型使用 TokenRouter API
  4921. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4922. } else if (in_array($model, $this->gemini_text_models)) {
  4923. // Gemini 模型使用 Gemini API
  4924. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4925. } else {
  4926. // 其他模型使用火山引擎API
  4927. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4928. }
  4929. // 验证返回值类型
  4930. if (!is_iterable($streamGenerator)) {
  4931. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4932. dLog('deepseek')->error('addChat流式生成器无效', [
  4933. 'generator_type' => $errorType,
  4934. 'model' => $model,
  4935. 'anime_id' => $anime_id
  4936. ]);
  4937. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  4938. 'type' => $errorType,
  4939. 'model' => $model
  4940. ]);
  4941. yield [
  4942. 'type' => 'error',
  4943. 'script' => [],
  4944. 'episode' => [],
  4945. 'answer' => '',
  4946. 'reasoning' => '',
  4947. 'usage' => [],
  4948. 'error' => '接口返回数据异常,请重新请求'
  4949. ];
  4950. return;
  4951. }
  4952. // 处理流式输出
  4953. foreach ($streamGenerator as $chunk) {
  4954. if (isset($chunk['type'])) {
  4955. if ($chunk['type'] === 'done') {
  4956. // 最终结果
  4957. $fullContent = $chunk['full_content'];
  4958. $fullReasoningContent = $chunk['full_reasoning'];
  4959. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4960. } else {
  4961. // 逐块yield数据
  4962. yield $chunk;
  4963. }
  4964. }
  4965. }
  4966. } catch (\Exception $e) {
  4967. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  4968. 'model' => $model,
  4969. 'anime_id' => $anime_id,
  4970. 'trace' => $e->getTraceAsString()
  4971. ]);
  4972. logDB('deepseek', 'error', 'addChat流式处理失败', [
  4973. 'error' => $e->getMessage(),
  4974. 'model' => $model
  4975. ]);
  4976. yield [
  4977. 'type' => 'error',
  4978. 'script' => [],
  4979. 'episode' => [],
  4980. 'answer' => '',
  4981. 'reasoning' => '',
  4982. 'usage' => [],
  4983. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4984. ];
  4985. return;
  4986. }
  4987. dLog('deepseek')->info('完整内容: '.$fullContent);
  4988. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4989. // 处理完整内容并返回最终结果
  4990. $script_arr = [];
  4991. if ($fullContent) {
  4992. $script_arr = handleScriptContent($fullContent);
  4993. dLog('deepseek')->info('解析内容', $script_arr);
  4994. logDB('deepseek', 'info', '解析内容', $script_arr);
  4995. }
  4996. if (empty($script_arr['roles'])) {
  4997. // 未生成剧本相关内容,保存对话记录并返回提示
  4998. dLog('deepseek')->info('未生成剧本相关的内容');
  4999. try {
  5000. DB::beginTransaction();
  5001. $now = date('Y-m-d H:i:s');
  5002. // 保存对话记录
  5003. $records = [
  5004. [
  5005. 'uid' => $uid,
  5006. 'anime_id' => $anime_id,
  5007. 'sequence' => 0,
  5008. 'role' => 'user',
  5009. 'content' => $prompt,
  5010. 'created_at' => $now,
  5011. 'updated_at' => $now
  5012. ],
  5013. [
  5014. 'uid' => $uid,
  5015. 'anime_id' => $anime_id,
  5016. 'sequence' => 0,
  5017. 'role' => 'assistant',
  5018. // 'content' => $fullContent,
  5019. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5020. 'created_at' => $now,
  5021. 'updated_at' => $now
  5022. ]
  5023. ];
  5024. DB::table('mp_anime_records')->insert($records);
  5025. DB::commit();
  5026. } catch (\Exception $e) {
  5027. DB::rollBack();
  5028. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5029. }
  5030. yield [
  5031. 'type' => 'done',
  5032. 'script' => [],
  5033. 'episode' => [],
  5034. 'answer' => $fullContent,
  5035. 'reasoning' => $fullReasoningContent,
  5036. 'usage' => $usage,
  5037. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5038. ];
  5039. return;
  5040. }
  5041. // 如果需要生成原文内容,从script_arr中提取
  5042. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5043. $content = $script_arr['content'];
  5044. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5045. if (!$content) {
  5046. yield [
  5047. 'type' => 'done',
  5048. 'script' => [],
  5049. 'episode' => [],
  5050. 'answer' => $fullContent,
  5051. 'reasoning' => $fullReasoningContent,
  5052. 'usage' => $usage,
  5053. 'error' => '未生成剧本内容,请调整提示词再试'
  5054. ];
  5055. return;
  5056. }
  5057. }
  5058. // 替换美术风格
  5059. if ($mappedArtStyle !== '') {
  5060. $script_arr['art_style'] = $mappedArtStyle;
  5061. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5062. }
  5063. // 新建动漫
  5064. if ($user_anime_name == '新剧本策划') {
  5065. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5066. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5067. // if (!$anime_name) {
  5068. // // 未识别到剧本名,保存对话记录并返回提示
  5069. // dLog('deepseek')->info('未能识别到剧本名称');
  5070. // try {
  5071. // DB::beginTransaction();
  5072. // $now = date('Y-m-d H:i:s');
  5073. // // 保存对话记录
  5074. // $records = [
  5075. // [
  5076. // 'uid' => $uid,
  5077. // 'anime_id' => $anime_id,
  5078. // 'sequence' => 0,
  5079. // 'role' => 'user',
  5080. // 'content' => $prompt,
  5081. // 'created_at' => $now,
  5082. // 'updated_at' => $now
  5083. // ],
  5084. // [
  5085. // 'uid' => $uid,
  5086. // 'anime_id' => $anime_id,
  5087. // 'sequence' => 0,
  5088. // 'role' => 'assistant',
  5089. // 'content' => '未能生成剧本名称,请重试',
  5090. // 'created_at' => $now,
  5091. // 'updated_at' => $now
  5092. // ]
  5093. // ];
  5094. // DB::table('mp_anime_records')->insert($records);
  5095. // DB::commit();
  5096. // } catch (\Exception $e) {
  5097. // DB::rollBack();
  5098. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5099. // }
  5100. // yield [
  5101. // 'type' => 'done',
  5102. // 'script' => [],
  5103. // 'episode' => [],
  5104. // 'answer' => $fullContent,
  5105. // 'reasoning' => $fullReasoningContent,
  5106. // 'usage' => $usage,
  5107. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  5108. // ];
  5109. // return;
  5110. // }
  5111. // 确认对话名称唯一性
  5112. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5113. $anime_name = $anime_name . '_' . date('YmdHis');
  5114. }
  5115. }else {
  5116. $anime_name = $user_anime_name;
  5117. }
  5118. $table_data = [
  5119. 'user_id' => $uid,
  5120. 'anime_name' => $anime_name,
  5121. 'model' => $model,
  5122. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5123. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5124. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5125. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5126. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5127. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5128. 'art_style_type' => $input_art_style,
  5129. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5130. 'status' => '解析完成',
  5131. 'content' => $content,
  5132. 'is_multi' => $is_multi,
  5133. 'ace_mode' => $ace_mode,
  5134. 'generate_status' => '待执行',
  5135. 'updated_at' => date('Y-m-d H:i:s')
  5136. ];
  5137. if ($table_data['content']) {
  5138. $chapters = splitContent($table_data['content']);
  5139. $chapter_count = count($chapters);
  5140. if ($chapter_count > 0) {
  5141. $table_data['start_episode_sequence'] = 1;
  5142. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5143. }
  5144. }
  5145. // 如果有剧本ID则进行绑定
  5146. if ($script_id) {
  5147. $table_data['script_id'] = $script_id;
  5148. }
  5149. $single_episode = [];
  5150. try {
  5151. DB::beginTransaction();
  5152. $now = date('Y-m-d H:i:s');
  5153. // 更新动漫大纲
  5154. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5155. if (!$boolen) {
  5156. dLog('deepseek')->info('动漫保存失败', $table_data);
  5157. Utils::throwError('20003:动漫保存失败');
  5158. }
  5159. // 保存对话记录
  5160. $records = [
  5161. [
  5162. 'uid' => $uid,
  5163. 'anime_id' => $anime_id,
  5164. 'sequence' => 0,
  5165. 'role' => 'user',
  5166. 'content' => $prompt,
  5167. 'created_at' => date('Y-m-d H:i:s'),
  5168. 'updated_at' => date('Y-m-d H:i:s')
  5169. ],
  5170. [
  5171. 'uid' => $uid,
  5172. 'anime_id' => $anime_id,
  5173. 'sequence' => 0,
  5174. 'role' => 'assistant',
  5175. 'content' => $fullContent,
  5176. 'created_at' => date('Y-m-d H:i:s'),
  5177. 'updated_at' => date('Y-m-d H:i:s')
  5178. ]
  5179. ];
  5180. // 保存对话记录
  5181. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5182. if (!$boolen3) {
  5183. Utils::throwError('20003:对话记录保存失败');
  5184. }
  5185. if ($is_single) {
  5186. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5187. if (empty($episode_arr['acts'])) {
  5188. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5189. }
  5190. $saveResult = $this->saveEpisodeVersionData(
  5191. $anime_id,
  5192. 1,
  5193. $episode_arr,
  5194. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5195. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5196. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5197. null,
  5198. null,
  5199. false,
  5200. $content,
  5201. $now
  5202. );
  5203. $single_episode = $saveResult['episode'];
  5204. $episode_id = $saveResult['episode_id'];
  5205. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5206. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5207. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5208. 'props' => json_encode($saveResult['merged_props'], 256),
  5209. 'updated_at' => $now
  5210. ]);
  5211. if ($boolen5 === false) {
  5212. Utils::throwError('20003:单剧集主表资源同步失败');
  5213. }
  5214. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5215. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5216. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5217. $episode_record_content = '确认分镜大纲';
  5218. if ($content !== '') {
  5219. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5220. }
  5221. $episode_records = [
  5222. [
  5223. 'uid' => $uid,
  5224. 'anime_id' => $anime_id,
  5225. 'role' => 'user',
  5226. 'content' => $episode_record_content,
  5227. 'sequence' => 1,
  5228. 'episode_id' => $episode_id,
  5229. 'created_at' => $now,
  5230. 'updated_at' => $now
  5231. ],
  5232. [
  5233. 'uid' => $uid,
  5234. 'anime_id' => $anime_id,
  5235. 'role' => 'assistant',
  5236. 'content' => $fullContent,
  5237. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5238. 'sequence' => 1,
  5239. 'episode_id' => $episode_id,
  5240. 'created_at' => $now,
  5241. 'updated_at' => $now
  5242. ]
  5243. ];
  5244. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5245. if (!$boolen4) {
  5246. Utils::throwError('20003:单剧集分镜记录保存失败');
  5247. }
  5248. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  5249. if ($is_single && !empty($single_episode)) {
  5250. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5251. 'anime_id' => $anime_id,
  5252. 'episode_id' => $episode_id ?? 0,
  5253. 'model' => $model,
  5254. 'source' => 'addChat',
  5255. ]);
  5256. }
  5257. }
  5258. }catch (\Exception $e) {
  5259. DB::rollBack();
  5260. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5261. yield [
  5262. 'type' => 'done',
  5263. 'answer' => $fullContent,
  5264. 'reasoning' => $fullReasoningContent,
  5265. 'usage' => $usage,
  5266. 'error' => $e->getMessage(),
  5267. ];
  5268. return;
  5269. }
  5270. DB::commit();
  5271. dLog('deepseek')->info('保存完毕');
  5272. if ($is_single && !empty($single_episode)) {
  5273. // $this->batchSetGlobalRoleImg([
  5274. // 'anime_id' => $anime_id,
  5275. // ]);
  5276. // $this->batchSetGlobalSceneImg([
  5277. // 'anime_id' => $anime_id,
  5278. // ]);
  5279. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5280. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5281. }
  5282. $table_data['anime_id'] = $anime_id;
  5283. $table_data['roles'] = json_decode($table_data['roles'], true);
  5284. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5285. // $table_data['episodes'] = $script_arr['episodes'];
  5286. unset($table_data['created_at']);
  5287. unset($table_data['updated_at']);
  5288. unset($table_data['status']);
  5289. dLog('deepseek')->info('开始返回');
  5290. yield [
  5291. 'type' => 'done',
  5292. 'script' => $table_data,
  5293. 'episode' => $single_episode,
  5294. 'answer' => $fullContent,
  5295. 'reasoning' => $fullReasoningContent,
  5296. 'usage' => $usage
  5297. ];
  5298. }
  5299. public function reGenerateAnime($data) {
  5300. $uid = Site::getUid();
  5301. $file = getProp($data, 'file');
  5302. $content = getProp($data, 'content', '');
  5303. $bid = getProp($data, 'bid', 0);
  5304. $script_id = getProp($data, 'script_id', 0);
  5305. $anime_id = getProp($data, 'anime_id');
  5306. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5307. if (!$anime) {
  5308. Utils::throwError('20003:该对话不存在');
  5309. }
  5310. $user_anime_name = getProp($anime, 'anime_name');
  5311. $prompt = getProp($data, 'prompt');
  5312. // 处理文本模型
  5313. $model = getProp($data, 'model');
  5314. if (!$model) {
  5315. // 用户没有输入,从anime表获取
  5316. $model = getProp($anime, 'model');
  5317. if (!$model) {
  5318. // anime表也没有,使用默认值
  5319. $model = 'doubao-seed-2-0-mini-260215';
  5320. }
  5321. }
  5322. // 验证模型是否在可用模型表中
  5323. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5324. $model = 'doubao-seed-2-0-mini-260215';
  5325. }
  5326. $is_multi = getProp($anime, 'is_multi', 1);
  5327. $is_single = (int)$is_multi !== 1;
  5328. // 积分余额预检(仅单剧集模式收费)
  5329. if ($is_single) {
  5330. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5331. }
  5332. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  5333. if ($is_single) {
  5334. $episode_exists = DB::table('mp_anime_episodes')
  5335. ->where('anime_id', $anime_id)
  5336. ->where('sequence', 1)
  5337. ->exists();
  5338. if ($episode_exists) {
  5339. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  5340. }
  5341. }
  5342. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5343. if ($prompt) {
  5344. $question .= "本次修改要求如下:\n{$prompt}";
  5345. }
  5346. // 提取文件内容
  5347. if ($file) {
  5348. $content = $this->extractFileContent($file);
  5349. if (!$content) {
  5350. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5351. }
  5352. } elseif ($script_id) {
  5353. $content = $this->getContentByScriptId($script_id);
  5354. if (!$content) {
  5355. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5356. }
  5357. } elseif ($bid) {
  5358. $content = $this->getContentByBid($bid);
  5359. if (!$content) {
  5360. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5361. }
  5362. } elseif ($content) {
  5363. $content = filterContent($content);
  5364. }else {
  5365. $content = filterContent(getProp($anime, 'content'));
  5366. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5367. $need_generate_content = true;
  5368. }
  5369. }
  5370. // 判断是否需要生成原文内容
  5371. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5372. // 如果需要生成原文内容,添加额外的要求
  5373. $content_generation_requirement = $need_generate_content
  5374. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5375. : "";
  5376. // 美术风格
  5377. $input_art_style = getProp($anime, 'art_style');
  5378. if (!$input_art_style) {
  5379. $input_art_style = getProp($data, 'art_style');
  5380. }
  5381. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5382. // 美术风格
  5383. if (!$mappedArtStyle) {
  5384. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5385. }else {
  5386. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5387. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5388. }else {
  5389. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5390. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5391. }
  5392. }
  5393. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5394. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5395. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5396. 中年女:邻居阿姨
  5397. 老年男:幽默大爷
  5398. 老年女:婆婆
  5399. 萌娃:奶气萌娃";
  5400. $system_message = ['role'=>'system', 'content'=>$is_single
  5401. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5402. 强制要求:
  5403. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5404. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5405. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5406. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5407. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5408. 普通要求:
  5409. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5410. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5411. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5412. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5413. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5414. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5415. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5416. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5417. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5418. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5419. 3.$mappedArtStyle_prompt\n\n
  5420. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5421. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5422. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5423. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5424. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5425. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5426. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5427. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5428. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5429. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5430. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5431. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5432. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5433. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5434. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5435. 示例如下:\n
  5436. ###剧本名:西昆仑
  5437. ###故事梗概
  5438. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5439. ###剧本亮点
  5440. 亮点1:绝境奇药,生死一线
  5441. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5442. 亮点2:结拜兄妹,化解尴尬
  5443. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5444. 亮点3:纤发夺命,情愫暗涌
  5445. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5446. ###人物关系
  5447. 阿雪与梁萧之间存在兄妹之情。
  5448. ###核心矛盾
  5449. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5450. ###主体列表
  5451. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5452. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5453. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5454. 姿态:站立。}{{甜心小美}}
  5455. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5456. 全景,正面拍摄,青年女性,亚洲人。
  5457. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5458. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5459. 姿态:站立。}{{阳光青年}}
  5460. ###美术风格
  5461. 基础画风风格词:厚涂古风
  5462. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5463. ###场景列表
  5464. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5465. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5466. 无人物。}
  5467. ###分镜剧本
  5468. ##第1幕:徐家老旧厨房 白天 室内
  5469. 分镜1
  5470. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5471. 场景:徐家老旧厨房
  5472. 构图设计:全景,低角度仰视
  5473. 运镜调度:手持拍摄
  5474. 配音角色:旁白
  5475. 出镜角色:许芸-校服装、徐母
  5476. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5477. 画面类型:普通画面
  5478. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5479. 分镜2
  5480. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5481. 场景:徐家老旧厨房
  5482. 构图设计:近景,徐母面部特写
  5483. 运镜调度:固定镜头
  5484. 配音角色:徐母
  5485. 出镜角色:徐母
  5486. 台词内容:问我夜不归宿死哪儿去了。
  5487. 画面类型:对口型
  5488. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5489. ##第2幕:徐家简陋客厅 黄昏 室内
  5490. 分镜3
  5491. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5492. 场景:徐家简陋客厅
  5493. 构图设计:全景,景深虚化
  5494. 运镜调度:固定镜头
  5495. 配音角色:旁白
  5496. 出镜角色:无
  5497. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5498. 画面类型:普通画面
  5499. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5500. 分镜4
  5501. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5502. 场景:徐家简陋客厅
  5503. 构图设计:特写,火车票
  5504. 运镜调度:固定镜头
  5505. 配音角色:旁白
  5506. 出镜角色:无
  5507. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5508. 画面类型:普通画面
  5509. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5510. "
  5511. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5512. 强制要求:\n
  5513. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5514. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5515. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5516. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5517. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5518. 普通要求:\n
  5519. 1.剧本名(必须生成)必须与文档内容高度相关
  5520. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5521. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5522. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5523. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5524. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5525. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5526. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5527. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5528. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5529. 4.$mappedArtStyle_prompt\n\n
  5530. 示例如下:\n
  5531. ###剧本名:西昆仑
  5532. ###故事梗概
  5533. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5534. ###剧本亮点
  5535. 亮点1:绝境奇药,生死一线
  5536. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5537. 亮点2:结拜兄妹,化解尴尬
  5538. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5539. 亮点3:纤发夺命,情愫暗涌
  5540. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5541. ###人物关系
  5542. 阿雪与梁萧之间存在兄妹之情。
  5543. ###核心矛盾
  5544. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5545. ###主体列表
  5546. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5547. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5548. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5549. 姿态:站立。}{{甜心小美}}
  5550. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5551. 全景,正面拍摄,青年女性,亚洲人。
  5552. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5553. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5554. 姿态:站立。}{{阳光青年}}
  5555. ###美术风格
  5556. 基础画风风格词:厚涂古风
  5557. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5558. ###场景列表
  5559. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5560. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5561. 无人物。}"];
  5562. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  5563. $episode_count = $this->extractEpisodeNumber($prompt);
  5564. if ((int)getProp($anime, 'is_multi') !== 1) {
  5565. yield [
  5566. 'type' => 'done',
  5567. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  5568. 'reasoning' => '',
  5569. 'usage' => []
  5570. ];
  5571. return;
  5572. }
  5573. if ($episode_count) {
  5574. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  5575. $system_message = [
  5576. 'role' => 'system',
  5577. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5578. 强制要求:\n
  5579. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5580. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5581. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5582. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5583. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5584. 普通要求:\n
  5585. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5586. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5587. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5588. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5589. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5590. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5591. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5592. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5593. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5594. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  5595. 示例如下:\n
  5596. ###剧本名:西昆仑
  5597. ###故事梗概
  5598. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5599. ###剧本亮点
  5600. 亮点1:绝境奇药,生死一线
  5601. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5602. 亮点2:结拜兄妹,化解尴尬
  5603. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5604. 亮点3:纤发夺命,情愫暗涌
  5605. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5606. ###人物关系
  5607. 阿雪与梁萧之间存在兄妹之情。
  5608. ###核心矛盾
  5609. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5610. ###主体列表
  5611. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5612. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5613. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5614. 姿态:站立。}{{甜心小美}}
  5615. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5616. 全景,正面拍摄,青年女性,亚洲人。
  5617. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5618. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5619. 姿态:站立。}{{阳光青年}}
  5620. ###美术风格
  5621. 基础画风风格词:厚涂古风
  5622. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5623. ###场景列表
  5624. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5625. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5626. 无人物。}
  5627. ###分集详细内容
  5628. ##第1章 重生
  5629. 我重生了。
  5630. 源于一个男人偏执的暗恋。
  5631. ##第2章 相救
  5632. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  5633. 我眼睛扫向站在锅炉后的卞大伟。"
  5634. ];
  5635. // 构建消息
  5636. $messages = [
  5637. $system_message,
  5638. [
  5639. 'role' => 'user',
  5640. 'content' => "以下是文档内容:
  5641. {$content}
  5642. 用户问题:
  5643. {$question}"
  5644. ]
  5645. ];
  5646. }else {
  5647. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  5648. // 构建消息
  5649. $messages = [
  5650. $system_message,
  5651. [
  5652. 'role' => 'user',
  5653. 'content' => "以下是文档内容:
  5654. {$content}
  5655. 用户问题:
  5656. {$question}"
  5657. ]
  5658. ];
  5659. }else {
  5660. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  5661. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  5662. return (array)$value;
  5663. })->toArray();
  5664. array_unshift($messages, $system_message);
  5665. $messages[] = [
  5666. 'role' => 'user',
  5667. 'content' => $prompt
  5668. ];
  5669. }
  5670. }
  5671. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5672. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5673. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5674. if ($model === 'deepseek-chat') {
  5675. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5676. $model = 'deepseek-v4-flash';
  5677. $thinkingMode = 'disabled';
  5678. } elseif ($model === 'deepseek-reasoner') {
  5679. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5680. $model = 'deepseek-v4-flash';
  5681. $thinkingMode = 'enabled';
  5682. }
  5683. $post_data = [
  5684. 'model' => $model,
  5685. 'messages' => $messages,
  5686. // 'max_tokens' => 8192,
  5687. 'temperature' => 0.7,
  5688. 'frequency_penalty' => 0,
  5689. 'presence_penalty' => 0,
  5690. 'response_format' => ['type' => 'text'],
  5691. 'thinking' => ['type' => $thinkingMode],
  5692. 'stream' => true // 启用流式输出
  5693. ];
  5694. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5695. // 根据模型类型选择调用方法
  5696. $fullContent = '';
  5697. $fullReasoningContent = '';
  5698. $usage = [];
  5699. // dd($post_data);
  5700. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  5701. try {
  5702. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5703. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5704. } else if (in_array($model, $this->gpt_text_models)) {
  5705. // GPT-5.4 模型使用 TokenRouter API
  5706. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5707. } else if (in_array($model, $this->gemini_text_models)) {
  5708. // Gemini 模型使用 Gemini API
  5709. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  5710. } else {
  5711. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5712. }
  5713. // 验证返回值类型
  5714. if (!is_iterable($streamGenerator)) {
  5715. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5716. dLog('deepseek')->error('方法名流式生成器无效', [
  5717. 'generator_type' => $errorType,
  5718. 'model' => $model,
  5719. // 添加其他上下文信息
  5720. ]);
  5721. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  5722. 'type' => $errorType,
  5723. 'model' => $model
  5724. ]);
  5725. yield [
  5726. 'type' => 'error',
  5727. // 根据方法返回相应的空数据结构
  5728. 'answer' => '',
  5729. 'reasoning' => '',
  5730. 'usage' => [],
  5731. 'error' => '接口返回数据异常,请重新请求'
  5732. ];
  5733. return;
  5734. }
  5735. // 处理流式输出
  5736. foreach ($streamGenerator as $chunk) {
  5737. if (isset($chunk['type'])) {
  5738. if ($chunk['type'] === 'done') {
  5739. $fullContent = $chunk['full_content'];
  5740. $fullReasoningContent = $chunk['full_reasoning'];
  5741. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5742. } else {
  5743. yield $chunk;
  5744. }
  5745. }
  5746. }
  5747. } catch (\Exception $e) {
  5748. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  5749. 'model' => $model,
  5750. 'trace' => $e->getTraceAsString()
  5751. ]);
  5752. logDB('deepseek', 'error', '方法名流式处理失败', [
  5753. 'error' => $e->getMessage(),
  5754. 'model' => $model
  5755. ]);
  5756. yield [
  5757. 'type' => 'error',
  5758. // 根据方法返回相应的空数据结构
  5759. 'answer' => '',
  5760. 'reasoning' => '',
  5761. 'usage' => [],
  5762. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5763. ];
  5764. return;
  5765. }
  5766. dLog('deepseek')->info('完整内容: '.$fullContent);
  5767. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5768. // 处理完整内容并返回最终结果
  5769. $script_arr = [];
  5770. if ($fullContent) {
  5771. $script_arr = handleScriptContent($fullContent);
  5772. dLog('deepseek')->info('解析内容', $script_arr);
  5773. logDB('deepseek', 'info', '解析内容', $script_arr);
  5774. }
  5775. if (empty($script_arr['roles'])) {
  5776. // 未生成剧本相关内容,保存对话记录并返回提示
  5777. dLog('deepseek')->info('未生成剧本相关的内容');
  5778. try {
  5779. $now = date('Y-m-d H:i:s');
  5780. // 保存对话记录
  5781. $records = [
  5782. [
  5783. 'uid' => $uid,
  5784. 'anime_id' => $anime_id,
  5785. 'sequence' => 0,
  5786. 'role' => 'user',
  5787. 'content' => $prompt,
  5788. 'created_at' => $now,
  5789. 'updated_at' => $now
  5790. ],
  5791. [
  5792. 'uid' => $uid,
  5793. 'anime_id' => $anime_id,
  5794. 'sequence' => 0,
  5795. 'role' => 'assistant',
  5796. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  5797. 'created_at' => $now,
  5798. 'updated_at' => $now
  5799. ]
  5800. ];
  5801. DB::table('mp_anime_records')->insert($records);
  5802. } catch (\Exception $e) {
  5803. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5804. }
  5805. yield [
  5806. 'type' => 'done',
  5807. 'script' => [],
  5808. 'episode' => [],
  5809. 'answer' => $fullContent,
  5810. 'reasoning' => $fullReasoningContent,
  5811. 'usage' => $usage,
  5812. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5813. ];
  5814. return;
  5815. }
  5816. // 替换美术风格
  5817. if ($mappedArtStyle !== '') {
  5818. $script_arr['art_style'] = $mappedArtStyle;
  5819. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5820. }
  5821. if ($user_anime_name != '新剧本策划') {
  5822. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5823. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5824. // 确认对话名称唯一性
  5825. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5826. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  5827. }
  5828. }else {
  5829. $anime_name = $user_anime_name;
  5830. }
  5831. $table_data = [
  5832. 'user_id' => $uid,
  5833. 'model' => $model,
  5834. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5835. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5836. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5837. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5838. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5839. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5840. 'art_style_type' => $input_art_style,
  5841. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5842. 'status' => '解析完成',
  5843. 'generate_status' => '待执行',
  5844. 'updated_at' => date('Y-m-d H:i:s')
  5845. ];
  5846. if ($anime_name) $table_data['anime_name'] = $anime_name;
  5847. // 如果是修改集数,则将content内容更新(会改变原文)
  5848. if (isset($episode_count) && $episode_count > 0) {
  5849. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  5850. $table_data['start_episode_sequence'] = 1;
  5851. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  5852. }else {
  5853. // 如果需要生成原文内容,从script_arr中提取
  5854. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5855. $table_data['content'] = $script_arr['content'];
  5856. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  5857. if (!$table_data['content']) {
  5858. yield [
  5859. 'type' => 'done',
  5860. 'script' => [],
  5861. 'episode' => [],
  5862. 'answer' => $fullContent,
  5863. 'reasoning' => $fullReasoningContent,
  5864. 'usage' => $usage,
  5865. 'error' => '未生成剧本内容,请调整提示词再试'
  5866. ];
  5867. return;
  5868. }
  5869. }
  5870. if (isset($table_data['content']) && $table_data['content']) {
  5871. $chapters = splitContent($table_data['content']);
  5872. $chapter_count = count($chapters);
  5873. if ($chapter_count > 0) {
  5874. $table_data['start_episode_sequence'] = 1;
  5875. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5876. }
  5877. }
  5878. }
  5879. $single_episode = [];
  5880. try {
  5881. DB::beginTransaction();
  5882. $now = date('Y-m-d H:i:s');
  5883. // 更新动漫大纲
  5884. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5885. if (!$boolen) {
  5886. dLog('deepseek')->info('对话修改失败', $table_data);
  5887. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  5888. Utils::throwError('20003:对话修改失败');
  5889. }
  5890. // 保存对话记录
  5891. $records = [
  5892. [
  5893. 'uid' => $uid,
  5894. 'anime_id' => $anime_id,
  5895. 'sequence' => 0,
  5896. 'role' => 'user',
  5897. 'content' => $prompt,
  5898. 'created_at' => $now,
  5899. 'updated_at' => $now
  5900. ],
  5901. [
  5902. 'uid' => $uid,
  5903. 'anime_id' => $anime_id,
  5904. 'sequence' => 0,
  5905. 'role' => 'assistant',
  5906. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5907. 'content' => $fullContent,
  5908. 'created_at' => $now,
  5909. 'updated_at' => $now
  5910. ]
  5911. ];
  5912. // 保存对话记录
  5913. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5914. if (!$boolen3) {
  5915. Utils::throwError('20003:对话记录保存失败');
  5916. }
  5917. // 单剧集模式:生成并保存剧集信息
  5918. if ($is_single) {
  5919. $anime_name = getProp($anime, 'anime_name', '未命名');
  5920. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5921. if (empty($episode_arr['acts'])) {
  5922. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5923. }
  5924. $saveResult = $this->saveEpisodeVersionData(
  5925. $anime_id,
  5926. 1,
  5927. $episode_arr,
  5928. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5929. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5930. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5931. null,
  5932. null,
  5933. false,
  5934. $content,
  5935. $now
  5936. );
  5937. $single_episode = $saveResult['episode'];
  5938. $episode_id = $saveResult['episode_id'];
  5939. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5940. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5941. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5942. 'props' => json_encode($saveResult['merged_props'], 256),
  5943. 'updated_at' => $now
  5944. ]);
  5945. if ($boolen5 === false) {
  5946. Utils::throwError('20003:单剧集主表资源同步失败');
  5947. }
  5948. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5949. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5950. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5951. $episode_record_content = '确认分镜大纲';
  5952. if ($content !== '') {
  5953. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5954. }
  5955. $episode_records = [
  5956. [
  5957. 'uid' => $uid,
  5958. 'anime_id' => $anime_id,
  5959. 'role' => 'user',
  5960. 'content' => $episode_record_content,
  5961. 'sequence' => 1,
  5962. 'episode_id' => $episode_id,
  5963. 'created_at' => $now,
  5964. 'updated_at' => $now
  5965. ],
  5966. [
  5967. 'uid' => $uid,
  5968. 'anime_id' => $anime_id,
  5969. 'role' => 'assistant',
  5970. 'content' => $fullContent,
  5971. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5972. 'sequence' => 1,
  5973. 'episode_id' => $episode_id,
  5974. 'created_at' => $now,
  5975. 'updated_at' => $now
  5976. ]
  5977. ];
  5978. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5979. if (!$boolen4) {
  5980. Utils::throwError('20003:单剧集分镜记录保存失败');
  5981. }
  5982. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  5983. if ($is_single && !empty($single_episode)) {
  5984. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5985. 'anime_id' => $anime_id,
  5986. 'episode_id' => $episode_id ?? 0,
  5987. 'model' => $model,
  5988. 'source' => 'reGenerateAnime',
  5989. ]);
  5990. }
  5991. }
  5992. }catch (\Exception $e) {
  5993. DB::rollBack();
  5994. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  5995. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  5996. yield [
  5997. 'type' => 'done',
  5998. 'answer' => $fullContent,
  5999. 'reasoning' => $fullReasoningContent,
  6000. 'usage' => $usage,
  6001. 'error' => $e->getMessage(),
  6002. ];
  6003. return;
  6004. }
  6005. DB::commit();
  6006. dLog('deepseek')->info('保存完毕');
  6007. if ($is_single && !empty($single_episode)) {
  6008. // $this->batchSetGlobalRoleImg([
  6009. // 'anime_id' => $anime_id,
  6010. // ]);
  6011. // $this->batchSetGlobalSceneImg([
  6012. // 'anime_id' => $anime_id,
  6013. // ]);
  6014. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6015. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6016. }
  6017. $table_data['anime_id'] = $anime_id;
  6018. $table_data['roles'] = json_decode($table_data['roles'], true);
  6019. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6020. unset($table_data['updated_at']);
  6021. unset($table_data['status']);
  6022. yield [
  6023. 'type' => 'done',
  6024. 'script' => $table_data,
  6025. 'episode' => $single_episode,
  6026. 'answer' => $fullContent,
  6027. 'reasoning' => $fullReasoningContent,
  6028. 'usage' => $usage
  6029. ];
  6030. }
  6031. public function chat($data) {
  6032. $uid = Site::getUid();
  6033. // 积分余额预检(不足直接报错)
  6034. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  6035. $anime_id = getProp($data, 'anime_id');
  6036. $file = getProp($data, 'file');
  6037. $content = getProp($data, 'content', '');
  6038. $bid = getProp($data, 'bid', 0);
  6039. $script_id = getProp($data, 'script_id', 0);
  6040. $episode_number = getProp($data, 'episode_number', 1);
  6041. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6042. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6043. if (!$anime) Utils::throwError('20003:该对话不存在!');
  6044. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  6045. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  6046. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  6047. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  6048. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  6049. $roles = is_array($roles) ? $roles : [];
  6050. $scenes = is_array($scenes) ? $scenes : [];
  6051. // 获取最后一集序号
  6052. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  6053. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  6054. // 转换主体列表和场景列表的格式
  6055. // 获取参考主体或场景
  6056. if ((int)$episode_number === 1) {
  6057. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  6058. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  6059. }else {
  6060. $prev_episode_number = $episode_number - 1;
  6061. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  6062. }
  6063. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  6064. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  6065. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  6066. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  6067. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  6068. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  6069. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  6070. 中年女:邻居阿姨
  6071. 老年男:幽默大爷
  6072. 老年女:婆婆
  6073. 萌娃:奶气萌娃";
  6074. if ($roles_content) {
  6075. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  6076. 主体范围:\n {$roles_content}\n
  6077. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  6078. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6079. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6080. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6081. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6082. }else {
  6083. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6084. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6085. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6086. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6087. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6088. }
  6089. if ($scenes_content) {
  6090. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  6091. 场景范围:\n {$scenes_content}\n
  6092. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  6093. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6094. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6095. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  6096. }else {
  6097. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6098. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6099. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6100. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  6101. }
  6102. // 提取文件内容
  6103. if ($file) {
  6104. $uploaded_content = $this->extractFileContent($file);
  6105. if (!$uploaded_content) {
  6106. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6107. }
  6108. } elseif ($script_id) {
  6109. $uploaded_content = $this->getContentByScriptId($script_id);
  6110. if (!$uploaded_content) {
  6111. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6112. }
  6113. } elseif ($bid) {
  6114. $uploaded_content = $this->getContentByBid($bid);
  6115. if (!$uploaded_content) {
  6116. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6117. }
  6118. } elseif ($content) {
  6119. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  6120. }
  6121. // elseif ($prompt) {
  6122. // $uploaded_content = filterContent($prompt);
  6123. // }
  6124. else {
  6125. $uploaded_content = '';
  6126. }
  6127. $input_art_style = getProp($anime, 'art_style');
  6128. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6129. // 美术风格
  6130. if (!$mappedArtStyle) {
  6131. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6132. }else {
  6133. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6134. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6135. }else {
  6136. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6137. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6138. }
  6139. }
  6140. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6141. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6142. // 强制要求:
  6143. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6144. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6145. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6146. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  6147. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  6148. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  6149. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  6150. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  6151. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  6152. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  6153. // - 分镜要和场景列表、人物主体保持一致\n
  6154. // 普通要求:
  6155. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6156. // {$role_demo}
  6157. // {$scene_demo}
  6158. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6159. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6160. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6161. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  6162. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6163. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6164. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6165. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6166. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6167. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6168. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6169. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6170. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6171. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6172. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6173. // 5.$mappedArtStyle_prompt\n\n
  6174. // 示例格式:\n
  6175. // 第1集:隐形的守护者
  6176. // ###故事梗概
  6177. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6178. // ###美术风格
  6179. // 基础画风风格词:韩漫二次元
  6180. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6181. // ###主体列表
  6182. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6183. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6184. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6185. // ###场景列表
  6186. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6187. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6188. // 无人物。}
  6189. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6190. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6191. // 无人物。}
  6192. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6193. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6194. // 无人物。}
  6195. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6196. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6197. // 无人物。}
  6198. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6199. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6200. // 无人物。}
  6201. // ###分镜剧本
  6202. // ##第1幕:徐家老旧厨房 白天 室内
  6203. // 分镜1
  6204. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6205. // 场景:徐家老旧厨房
  6206. // 构图设计:全景,低角度仰视
  6207. // 运镜调度:手持拍摄
  6208. // 配音角色:旁白
  6209. // 出镜角色:许芸-校服装、徐母
  6210. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6211. // 画面类型:普通画面
  6212. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6213. // 分镜2
  6214. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6215. // 场景:徐家老旧厨房
  6216. // 构图设计:近景,徐母面部特写
  6217. // 运镜调度:固定镜头
  6218. // 配音角色:徐母
  6219. // 出镜角色:徐母
  6220. // 台词内容:问我夜不归宿死哪儿去了。
  6221. // 画面类型:对口型
  6222. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6223. // ##第2幕:徐家简陋客厅 黄昏 室内
  6224. // 分镜3
  6225. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6226. // 场景:徐家简陋客厅
  6227. // 构图设计:全景,景深虚化
  6228. // 运镜调度:固定镜头
  6229. // 配音角色:旁白
  6230. // 出镜角色:无
  6231. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6232. // 画面类型:普通画面
  6233. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6234. // 分镜4
  6235. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6236. // 场景:徐家简陋客厅
  6237. // 构图设计:特写,火车票
  6238. // 运镜调度:固定镜头
  6239. // 配音角色:旁白
  6240. // 出镜角色:无
  6241. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6242. // 画面类型:普通画面
  6243. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6244. // \n\n";
  6245. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  6246. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  6247. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  6248. 普通要求:
  6249. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6250. {$role_demo}
  6251. {$scene_demo}
  6252. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6253. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6254. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6255. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6256. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6257. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6258. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6259. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6260. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6261. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6262. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6263. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6264. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6265. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6266. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6267. 5.$mappedArtStyle_prompt
  6268. 6.《情绪-视听语言映射表》:
  6269. 6.1 场景空间与时间心理学 (Scene & Temporality)
  6270. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6271. -----|---------|------------|----------------
  6272. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  6273. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  6274. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  6275. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  6276. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  6277. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6278. -----|---------|------------|----------------
  6279. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  6280. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  6281. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  6282. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  6283. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  6284. --------|---------|--------------|-------------
  6285. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  6286. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  6287. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  6288. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  6289. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  6290. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  6291. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  6292. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  6293. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  6294. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  6295. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  6296. -----|---------|------------|------------
  6297. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  6298. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  6299. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  6300. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  6301. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  6302. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  6303. --------|---------|--------------|----------
  6304. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  6305. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  6306. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  6307. 6.6 声音设计与潜意识影响 (Soundscape)
  6308. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  6309. -----|---------|------------|------------------
  6310. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  6311. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  6312. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  6313. 理论基石:
  6314. - The Five C's of Cinematography by Joseph V. Mascelli
  6315. - Film Art: An Introduction by David Bordwell
  6316. - Sight, Sound, Motion by Herbert Zettl
  6317. - Notes on the Cinematograph by Robert Bresson
  6318. \n\n
  6319. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  6320. 示例格式:\n
  6321. 第1集:隐形的守护者
  6322. ###故事梗概
  6323. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6324. ###美术风格
  6325. 基础画风风格词:韩漫二次元
  6326. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6327. ###主体列表
  6328. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6329. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6330. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6331. ###场景列表
  6332. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6333. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6334. 无人物。}
  6335. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6336. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6337. 无人物。}
  6338. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6339. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6340. 无人物。}
  6341. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6342. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6343. 无人物。}
  6344. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6345. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6346. 无人物。}
  6347. ###分镜剧本
  6348. ##第1幕:徐家老旧厨房 白天 室内
  6349. 分镜1
  6350. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6351. 场景:徐家老旧厨房
  6352. 构图设计:全景,低角度仰视
  6353. 运镜调度:手持拍摄
  6354. 配音角色:旁白
  6355. 出镜角色:许芸-校服装、徐母
  6356. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6357. 画面类型:普通画面
  6358. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6359. 分镜2
  6360. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6361. 场景:徐家老旧厨房
  6362. 构图设计:近景,徐母面部特写
  6363. 运镜调度:固定镜头
  6364. 配音角色:徐母
  6365. 出镜角色:徐母
  6366. 台词内容:问我夜不归宿死哪儿去了。
  6367. 画面类型:对口型
  6368. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6369. ##第2幕:徐家简陋客厅 黄昏 室内
  6370. 分镜3
  6371. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6372. 场景:徐家简陋客厅
  6373. 构图设计:全景,景深虚化
  6374. 运镜调度:固定镜头
  6375. 配音角色:旁白
  6376. 出镜角色:无
  6377. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6378. 画面类型:普通画面
  6379. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6380. 分镜4
  6381. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6382. 场景:徐家简陋客厅
  6383. 构图设计:特写,火车票
  6384. 运镜调度:固定镜头
  6385. 配音角色:旁白
  6386. 出镜角色:无
  6387. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6388. 画面类型:普通画面
  6389. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6390. \n\n";
  6391. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6392. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  6393. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  6394. $prompt = $origin_prompt;
  6395. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  6396. // 获取章节内容
  6397. $full_content = getProp($anime, 'content');
  6398. if ($uploaded_content) {
  6399. $full_content = $uploaded_content;
  6400. }
  6401. // 根据章节内容拆分章节
  6402. $chapters = splitContent($full_content);
  6403. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  6404. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  6405. $messages = [];
  6406. if ($prompt == '确认分镜大纲') {
  6407. // 暂时保留
  6408. $content = $chapter_content;
  6409. if ($is_single) $content = $full_content; // 单剧集使用全文
  6410. if (!$content) {
  6411. Utils::throwError('20003:章节内容无法获取,请确认');
  6412. }
  6413. $question = $is_single
  6414. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  6415. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  6416. // 构建消息
  6417. $messages[] =
  6418. [
  6419. 'role' => 'user',
  6420. 'content' => $question
  6421. ];
  6422. }else if ($prompt == '继续策划下一集') {
  6423. if ($is_single) {
  6424. Utils::throwError('20003:单剧集不支持继续策划下一集');
  6425. }
  6426. $content = $chapter_content;
  6427. if (!$content) {
  6428. Utils::throwError('20003:章节内容无法获取,请确认');
  6429. }
  6430. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  6431. // 获取上一集最后记录
  6432. $prev_sequence = $episode_number - 1;
  6433. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  6434. // 构建消息
  6435. $messages[] =
  6436. [
  6437. 'role' => 'user',
  6438. 'content' => $question
  6439. ];
  6440. }else {
  6441. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  6442. if (!$content) {
  6443. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  6444. }
  6445. if (!$content) {
  6446. Utils::throwError('20003:章节内容无法获取,请确认');
  6447. }
  6448. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  6449. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  6450. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  6451. if ($origin_prompt) {
  6452. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  6453. }
  6454. $messages[] =
  6455. [
  6456. 'role' => 'user',
  6457. 'content' => $question
  6458. ];
  6459. }
  6460. // 处理文本模型
  6461. $model = getProp($data, 'model');
  6462. if (!$model) {
  6463. // 用户没有输入,从anime表获取
  6464. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6465. $model = getProp($anime, 'model');
  6466. if (!$model) {
  6467. // anime表也没有,使用默认值
  6468. $model = 'doubao-seed-2-0-mini-260215';
  6469. }
  6470. }
  6471. // 验证模型是否在可用模型表中
  6472. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6473. $model = 'doubao-seed-2-0-mini-260215';
  6474. }
  6475. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6476. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6477. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6478. if ($model === 'deepseek-chat') {
  6479. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6480. $model = 'deepseek-v4-flash';
  6481. $thinkingMode = 'disabled';
  6482. } elseif ($model === 'deepseek-reasoner') {
  6483. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6484. $model = 'deepseek-v4-flash';
  6485. $thinkingMode = 'enabled';
  6486. }
  6487. $post_data = [
  6488. 'model' => $model,
  6489. 'messages' => $messages,
  6490. // 'max_tokens' => 8192,
  6491. 'temperature' => 0.2,
  6492. 'frequency_penalty' => 0,
  6493. 'presence_penalty' => 0,
  6494. 'response_format' => ['type' => 'text'],
  6495. 'thinking' => ['type' => $thinkingMode],
  6496. 'stream' => true // 启用流式输出
  6497. ];
  6498. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6499. // 根据模型类型选择调用方法
  6500. $fullContent = '';
  6501. $fullReasoningContent = '';
  6502. $usage = [];
  6503. try {
  6504. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6505. // DeepSeek 官方模型使用 DeepSeek API
  6506. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6507. } else if (in_array($model, $this->gpt_text_models)) {
  6508. // GPT-5.4 模型使用 TokenRouter API
  6509. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6510. } else if (in_array($model, $this->gemini_text_models)) {
  6511. // Gemini 模型使用 Gemini API
  6512. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6513. } else {
  6514. // 其他模型使用火山引擎API
  6515. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6516. }
  6517. // 验证返回值类型
  6518. if (!is_iterable($streamGenerator)) {
  6519. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6520. dLog('deepseek')->error('chat流式生成器无效', [
  6521. 'generator_type' => $errorType,
  6522. 'model' => $model,
  6523. 'anime_id' => $anime_id,
  6524. 'episode_number' => $episode_number
  6525. ]);
  6526. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  6527. 'type' => $errorType,
  6528. 'model' => $model
  6529. ]);
  6530. yield [
  6531. 'type' => 'error',
  6532. 'episode' => [],
  6533. 'answer' => '',
  6534. 'reasoning' => '',
  6535. 'usage' => [],
  6536. 'error' => '接口返回数据异常,请重新请求'
  6537. ];
  6538. return;
  6539. }
  6540. // 处理流式输出
  6541. foreach ($streamGenerator as $chunk) {
  6542. if (isset($chunk['type'])) {
  6543. if ($chunk['type'] === 'done') {
  6544. // 最终结果
  6545. $fullContent = $chunk['full_content'];
  6546. $fullReasoningContent = $chunk['full_reasoning'];
  6547. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6548. } else {
  6549. // 逐块yield数据
  6550. yield $chunk;
  6551. }
  6552. }
  6553. }
  6554. } catch (\Exception $e) {
  6555. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  6556. 'model' => $model,
  6557. 'anime_id' => $anime_id,
  6558. 'episode_number' => $episode_number,
  6559. 'trace' => $e->getTraceAsString()
  6560. ]);
  6561. logDB('deepseek', 'error', 'chat流式处理失败', [
  6562. 'error' => $e->getMessage(),
  6563. 'model' => $model
  6564. ]);
  6565. yield [
  6566. 'type' => 'error',
  6567. 'episode' => [],
  6568. 'answer' => '',
  6569. 'reasoning' => '',
  6570. 'usage' => [],
  6571. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6572. ];
  6573. return;
  6574. }
  6575. dLog('deepseek')->info('完整内容: '.$fullContent);
  6576. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6577. // 处理完整内容并返回最终结果
  6578. $episode_arr = handleEpisodeContent($fullContent);
  6579. logDB('deepseek', 'info', '解析内容', $episode_arr);
  6580. if (empty($episode_arr['acts'])) {
  6581. // 未生成剧本相关内容,保存对话记录并返回提示
  6582. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  6583. try {
  6584. $now = date('Y-m-d H:i:s');
  6585. // 保存对话记录
  6586. $records = [
  6587. [
  6588. 'uid' => $uid,
  6589. 'anime_id' => $anime_id,
  6590. 'sequence' => $episode_number,
  6591. 'role' => 'user',
  6592. 'content' => $prompt,
  6593. 'created_at' => $now,
  6594. 'updated_at' => $now
  6595. ],
  6596. [
  6597. 'uid' => $uid,
  6598. 'anime_id' => $anime_id,
  6599. 'sequence' => $episode_number,
  6600. 'role' => 'assistant',
  6601. 'content' => $fullContent,
  6602. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6603. 'created_at' => $now,
  6604. 'updated_at' => $now
  6605. ]
  6606. ];
  6607. DB::table('mp_anime_records')->insert($records);
  6608. } catch (\Exception $e) {
  6609. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6610. }
  6611. yield [
  6612. 'type' => 'done',
  6613. 'episode' => [],
  6614. 'answer' => $fullContent,
  6615. 'reasoning' => $fullReasoningContent,
  6616. 'usage' => $usage,
  6617. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  6618. ];
  6619. return;
  6620. }
  6621. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  6622. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  6623. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  6624. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  6625. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  6626. $existing_props = is_array($existing_props) ? $existing_props : [];
  6627. $now = date('Y-m-d H:i:s');
  6628. try {
  6629. DB::beginTransaction();
  6630. $saveResult = $this->saveEpisodeVersionData(
  6631. $anime_id,
  6632. $episode_number,
  6633. $episode_arr,
  6634. $existing_roles,
  6635. $existing_scenes,
  6636. $existing_props,
  6637. $current_episode,
  6638. $base_episode,
  6639. $is_regenerate_version,
  6640. $content,
  6641. $now
  6642. );
  6643. $episode = $saveResult['episode'];
  6644. $episode_id = $saveResult['episode_id'];
  6645. $merged_roles = $saveResult['merged_roles'];
  6646. $merged_scenes = $saveResult['merged_scenes'];
  6647. $merged_props = $saveResult['merged_props'];
  6648. $record_content = $origin_prompt;
  6649. if ($uploaded_content !== '') {
  6650. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  6651. }
  6652. $records = [
  6653. [
  6654. 'uid' => $uid,
  6655. 'anime_id' => $anime_id,
  6656. 'role' => 'user',
  6657. 'content' => $record_content,
  6658. 'sequence' => $episode_number,
  6659. 'episode_id' => $episode_id,
  6660. 'created_at' => $now,
  6661. 'updated_at' => $now
  6662. ],
  6663. [
  6664. 'uid' => $uid,
  6665. 'anime_id' => $anime_id,
  6666. 'role' => 'assistant',
  6667. 'content' => $fullContent,
  6668. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6669. 'sequence' => $episode_number,
  6670. 'episode_id' => $episode_id,
  6671. 'created_at' => $now,
  6672. 'updated_at' => $now
  6673. ]
  6674. ];
  6675. $boolen4 = DB::table('mp_anime_records')->insert($records);
  6676. if (!$boolen4) {
  6677. Utils::throwError('20003:对话记录保存失败');
  6678. }
  6679. // 保存模型和内容到anime表
  6680. $update_anime_data = [
  6681. 'model' => $model,
  6682. 'updated_at' => $now
  6683. ];
  6684. if ($uploaded_content) {
  6685. $update_anime_data['content'] = $uploaded_content;
  6686. }
  6687. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  6688. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6689. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6690. 'anime_id' => $anime_id,
  6691. 'episode_number' => $episode_number,
  6692. 'model' => $model,
  6693. 'source' => 'chat',
  6694. ]);
  6695. }catch (\Exception $e) {
  6696. DB::rollBack();
  6697. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6698. yield [
  6699. 'type' => 'done',
  6700. 'answer' => $fullContent,
  6701. 'reasoning' => $fullReasoningContent,
  6702. 'usage' => $usage,
  6703. 'error' => $e->getMessage(),
  6704. ];
  6705. return;
  6706. }
  6707. DB::commit();
  6708. if ($is_global_generate_pics) {
  6709. // // 批量生成全局角色图片
  6710. // $this->batchSetGlobalRoleImg([
  6711. // 'anime_id' => $anime_id,
  6712. // ], true);
  6713. // // 批量生成全局场景图片
  6714. // $this->batchSetGlobalSceneImg([
  6715. // 'anime_id' => $anime_id,
  6716. // ], true);
  6717. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6718. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6719. }
  6720. $episode['episode_id'] = $episode_id;
  6721. $episode['roles'] = $merged_roles;
  6722. $episode['scenes'] = $merged_scenes;
  6723. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  6724. yield [
  6725. 'type' => 'done',
  6726. 'episode' => $episode,
  6727. 'answer' => $fullContent,
  6728. 'reasoning' => $fullReasoningContent,
  6729. 'usage' => $usage
  6730. ];
  6731. }
  6732. public function addChatForAce($data) {
  6733. $uid = Site::getUid();
  6734. $anime_id = getProp($data, 'anime_id');
  6735. if (!$anime_id) Utils::throwError('20003:请选择对话');
  6736. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  6737. if (!$anime) Utils::throwError('20003:对话不存在');
  6738. $file = getProp($data, 'file');
  6739. $content = getProp($data, 'content', '');
  6740. $bid = getProp($data, 'bid', 0);
  6741. $script_id = getProp($data, 'script_id', 0);
  6742. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  6743. $prompt = getProp($data, 'prompt');
  6744. $is_multi = getProp($anime, 'is_multi');
  6745. $is_single = (int)$is_multi !== 1;
  6746. // 积分余额预检(仅单剧集模式收费)
  6747. if ($is_single) {
  6748. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  6749. }
  6750. $extra_products = getProp($data, 'products', []);
  6751. if (!$extra_products) {
  6752. $extra_products = getProp($anime, 'extra_products');
  6753. if ($extra_products) {
  6754. $extra_products = json_decode($extra_products, true);
  6755. }else {
  6756. $extra_products = [];
  6757. }
  6758. }else {
  6759. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6760. }
  6761. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6762. $anime_script_id = getProp($anime, 'script_id');
  6763. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  6764. $cpid = Site::getCpid();
  6765. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6766. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6767. ->where('mapping.script_id', $anime_script_id)
  6768. ->where('product.cpid', $cpid)
  6769. ->where('product.is_deleted', 0);
  6770. $mappings = $script_products_mappings->select(
  6771. 'mapping.product_id',
  6772. 'mapping.episode_number',
  6773. 'product.product_name',
  6774. 'product.type',
  6775. 'product.product',
  6776. 'product.pic_prompt',
  6777. 'product.url',
  6778. 'product.pic_task_id',
  6779. 'product.pic_task_status',
  6780. 'product.three_view_image_url'
  6781. )
  6782. ->get();
  6783. // 按 product_id 分组,合并 episode_number
  6784. $productMap = [];
  6785. foreach ($mappings as $item) {
  6786. $product_id = $item->product_id;
  6787. $product_name = $item->product_name;
  6788. // 处理product_name两边的符号
  6789. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6790. if (!isset($productMap[$product_id])) {
  6791. $productMap[$product_id] = [
  6792. 'product_id' => $product_id,
  6793. 'product_name' => $product_name,
  6794. 'type' => (int)$item->type,
  6795. 'product' => (int)$item->product,
  6796. 'pic_prompt' => $item->pic_prompt,
  6797. 'url' => $item->url,
  6798. 'pic_task_id' => $item->pic_task_id,
  6799. 'pic_task_status' => $item->pic_task_status,
  6800. 'episode_numbers' => [],
  6801. ];
  6802. }
  6803. // 添加 episode_number(去重)
  6804. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6805. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6806. }
  6807. }
  6808. // 将查询到的剧本资产合并到extra_products中
  6809. // 先构建extra_products的索引(以product_id为key,用于去重)
  6810. $extraProductsMap = [];
  6811. foreach ($extra_products as $item) {
  6812. $key = getProp($item, 'product_id');
  6813. if ($key) {
  6814. $extraProductsMap[$key] = $item;
  6815. }
  6816. }
  6817. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6818. foreach ($productMap as $product) {
  6819. $product_id = $product['product_id'];
  6820. // 如果不存在则添加(不带episode_number信息)
  6821. if (!isset($extraProductsMap[$product_id])) {
  6822. $extraProductsMap[$product_id] = [
  6823. 'product_id' => $product['product_id'],
  6824. 'product_name' => $product['product_name'],
  6825. 'type' => $product['type'],
  6826. 'product' => $product['product'],
  6827. 'pic_prompt' => $product['pic_prompt'],
  6828. 'url' => $product['url'],
  6829. 'pic_task_id' => $product['pic_task_id'],
  6830. 'pic_task_status' => $product['pic_task_status'],
  6831. ];
  6832. }
  6833. }
  6834. // 重新赋值给extra_products
  6835. $extra_products = array_values($extraProductsMap);
  6836. }
  6837. $user_anime_name = getProp($anime, 'anime_name');
  6838. // 处理提示词
  6839. if ($prompt && $extra_products) {
  6840. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6841. foreach($extra_products as $item) {
  6842. $product_name = getProp($item, 'product_name');
  6843. if ($product_name) {
  6844. // 替换 {product_name} 为 product_name
  6845. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6846. }
  6847. }
  6848. }
  6849. // 处理文本模型
  6850. $model = getProp($data, 'model');
  6851. if (!$model) {
  6852. // 用户没有输入,从anime表获取
  6853. $model = getProp($anime, 'model');
  6854. if (!$model) {
  6855. // anime表也没有,使用默认值
  6856. $model = 'deepseek-v4-pro';
  6857. }
  6858. }
  6859. // 验证模型是否在可用模型表中
  6860. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6861. $model = 'deepseek-v4-pro';
  6862. }
  6863. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6864. if ($prompt) {
  6865. $question .= "本次修改要求如下:\n{$prompt}";
  6866. }
  6867. // if (!$file && !$content && !$bid) {
  6868. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  6869. // }
  6870. // 提取文件内容
  6871. if ($file) {
  6872. $content = $this->extractFileContent($file);
  6873. if (!$content) {
  6874. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6875. }
  6876. } elseif ($script_id) {
  6877. $content = $this->getContentByScriptId($script_id);
  6878. if (!$content) {
  6879. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6880. }
  6881. } elseif ($bid) {
  6882. $content = $this->getContentByBid($bid);
  6883. if (!$content) {
  6884. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6885. }
  6886. } elseif ($content) {
  6887. $content = filterContent($content);
  6888. } else {
  6889. $content = getProp($anime, 'content');
  6890. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6891. $need_generate_content = true;
  6892. }
  6893. }
  6894. // 美术风格
  6895. $input_art_style = getProp($data, 'art_style');
  6896. if (!$input_art_style) {
  6897. $mappedArtStyle = getProp($anime, 'art_style');
  6898. }else {
  6899. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6900. }
  6901. // 判断是否需要生成原文内容
  6902. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6903. // 如果需要生成原文内容,添加额外的要求
  6904. $content_generation_requirement = $need_generate_content
  6905. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6906. : "";
  6907. // 美术风格
  6908. if (!$mappedArtStyle) {
  6909. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6910. }else {
  6911. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6912. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6913. }else {
  6914. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6915. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6916. }
  6917. }
  6918. // 构建主体、场景和道具提示词
  6919. $extra_role_prompt = "\n";
  6920. $extra_scene_prompt = "\n";
  6921. $extra_prop_prompt = "\n";
  6922. $ref_products = []; // 参考资产
  6923. if ($extra_products) {
  6924. foreach($extra_products as $item) {
  6925. $product = getProp($item, 'product');
  6926. $product_name = getProp($item, 'product_name');
  6927. if ($product_name == '旁白') continue;
  6928. $ref_products[$product_name] = $item;
  6929. $pic_prompt = getProp($item, 'pic_prompt');
  6930. if ((int)$product === 1) {
  6931. // 拼接角色信息
  6932. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6933. } elseif ((int)$product === 2) {
  6934. // 拼接场景信息
  6935. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6936. } elseif ((int)$product === 3) {
  6937. // 拼接道具信息
  6938. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6939. }
  6940. }
  6941. // 优化提示词,融入剧本
  6942. if (!empty(trim($extra_role_prompt))) {
  6943. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6944. }
  6945. if (!empty(trim($extra_scene_prompt))) {
  6946. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6947. }
  6948. if (!empty(trim($extra_prop_prompt))) {
  6949. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6950. }
  6951. }
  6952. if ($anime_script_id && $is_single) {
  6953. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6954. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6955. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6956. }else {
  6957. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6958. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6959. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6960. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6961. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6962. {$extra_role_prompt}";
  6963. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6964. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6965. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6966. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6967. {$extra_scene_prompt}";
  6968. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6969. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6970. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6971. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6972. {$extra_prop_prompt}";
  6973. }
  6974. $systemPrompt = $is_single
  6975. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6976. 强制要求:
  6977. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6978. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6979. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6980. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6981. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6982. 普通要求:
  6983. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6984. $role_demo
  6985. $scene_demo
  6986. $prop_demo
  6987. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6988. 5.1片段分割逻辑(优先级从高到低):
  6989. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6990. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6991. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6992. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6993. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6994. - 片段数量格式为: 片段数量:8
  6995. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6996. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6997. 5.3分镜结构:每个分镜包含以下字段:
  6998. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6999. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7000. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7001. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7002. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7003. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7004. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7005. - 运镜:场景+画面描述+运镜
  7006. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7007. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7008. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7009. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7010. 6.{$mappedArtStyle_prompt}\n\n
  7011. 示例如下:\n
  7012. ###剧本名:西昆仑
  7013. ###故事梗概
  7014. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7015. ###剧本亮点
  7016. 亮点1:绝境奇药,生死一线
  7017. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7018. 亮点2:结拜兄妹,化解尴尬
  7019. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7020. 亮点3:纤发夺命,情愫暗涌
  7021. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7022. ###人物关系
  7023. 阿雪与梁萧之间存在兄妹之情。
  7024. ###核心矛盾
  7025. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7026. ###主体列表
  7027. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7028. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7029. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7030. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7031. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7032. 全景,正面拍摄,青年女性,亚洲人。
  7033. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7034. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7035. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7036. ###美术风格
  7037. 基础画风风格词:厚涂古风
  7038. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7039. ###场景列表
  7040. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7041. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7042. 无人物。}
  7043. ###分段剧本
  7044. 片段数量:8
  7045. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7046. ##片段1
  7047. 时长:12s
  7048. 分镜1
  7049. 出场角色:刀疤脸
  7050. 场景:边境小镇街道
  7051. 出场道具:酒杯-高脚杯
  7052. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7053. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7054. 配音台词:
  7055. 背景音效:
  7056. 分镜2
  7057. 出场角色:刀疤脸
  7058. 场景:悦来酒馆
  7059. 出场道具:酒杯-高脚杯
  7060. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7061. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7062. 配音台词:
  7063. 背景音效:
  7064. 分镜3
  7065. 出场角色:刀疤脸
  7066. 场景:悦来酒馆
  7067. 出场道具:酒杯-高脚杯
  7068. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7069. 运镜:从中景推向令牌特写。
  7070. 配音台词:
  7071. 背景音效:
  7072. 分镜4
  7073. 出场角色:刀疤脸
  7074. 场景:悦来酒馆
  7075. 出场道具:酒杯-高脚杯
  7076. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7077. 运镜:极速推向酒水溅起的瞬间。
  7078. 配音台词:
  7079. 背景音效:
  7080. 分镜5
  7081. 出场角色:刀疤脸
  7082. 场景:悦来酒馆
  7083. 出场道具:酒杯-高脚杯
  7084. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7085. 运镜:固定机位,利用倾斜构图制造压迫感。
  7086. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7087. 背景音效:
  7088. \n\n"
  7089. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7090. 强制要求:\n
  7091. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7092. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7093. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7094. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7095. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7096. 普通要求:\n
  7097. 1.剧本名(必须生成)必须与文档内容高度相关
  7098. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7099. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7100. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7101. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7102. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7103. {$extra_role_prompt}
  7104. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7105. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7106. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7107. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7108. {$extra_scene_prompt}
  7109. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7110. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7111. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7112. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7113. {$extra_prop_prompt}
  7114. 5.{$mappedArtStyle_prompt}\n\n
  7115. 示例如下:\n
  7116. ###剧本名:西昆仑
  7117. ###故事梗概
  7118. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7119. ###剧本亮点
  7120. 亮点1:绝境奇药,生死一线
  7121. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7122. 亮点2:结拜兄妹,化解尴尬
  7123. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7124. 亮点3:纤发夺命,情愫暗涌
  7125. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7126. ###人物关系
  7127. 阿雪与梁萧之间存在兄妹之情。
  7128. ###核心矛盾
  7129. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7130. ###主体列表
  7131. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7132. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7133. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7134. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7135. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7136. 全景,正面拍摄,青年女性,亚洲人。
  7137. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7138. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7139. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7140. ###美术风格
  7141. 基础画风风格词:厚涂古风
  7142. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7143. ###场景列表
  7144. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7145. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7146. 无人物。}
  7147. ###道具列表
  7148. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  7149. // 构建消息
  7150. $messages = [
  7151. [
  7152. 'role' => 'system',
  7153. 'content' => $systemPrompt
  7154. ],
  7155. [
  7156. 'role' => 'user',
  7157. 'content' => "以下是文档内容:
  7158. {$content}
  7159. 用户问题:
  7160. {$question}"
  7161. ]
  7162. ];
  7163. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7164. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7165. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7166. if ($model === 'deepseek-chat') {
  7167. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7168. $model = 'deepseek-v4-flash';
  7169. $thinkingMode = 'disabled';
  7170. } elseif ($model === 'deepseek-reasoner') {
  7171. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7172. $model = 'deepseek-v4-flash';
  7173. $thinkingMode = 'enabled';
  7174. }
  7175. $post_data = [
  7176. 'model' => $model,
  7177. 'messages' => $messages,
  7178. // 'max_tokens' => 8192,
  7179. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7180. 'frequency_penalty' => 0,
  7181. 'presence_penalty' => 0,
  7182. 'response_format' => ['type' => 'text'],
  7183. 'thinking' => ['type'=>$thinkingMode],
  7184. 'stream' => true // 启用流式输出
  7185. ];
  7186. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7187. // 根据模型类型选择调用方法
  7188. $fullContent = '';
  7189. $fullReasoningContent = '';
  7190. $usage = [];
  7191. try {
  7192. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7193. // DeepSeek 官方模型使用 DeepSeek API
  7194. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7195. } else if (in_array($model, $this->gpt_text_models)) {
  7196. // GPT-5.4 模型使用 TokenRouter API
  7197. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7198. } else if (in_array($model, $this->gemini_text_models)) {
  7199. // Gemini 模型使用 Gemini API
  7200. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  7201. } else {
  7202. // 其他模型使用火山引擎API
  7203. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7204. }
  7205. // 验证返回值类型
  7206. if (!is_iterable($streamGenerator)) {
  7207. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7208. dLog('deepseek')->error('addChat流式生成器无效', [
  7209. 'generator_type' => $errorType,
  7210. 'model' => $model,
  7211. 'anime_id' => $anime_id
  7212. ]);
  7213. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  7214. 'type' => $errorType,
  7215. 'model' => $model
  7216. ]);
  7217. yield [
  7218. 'type' => 'error',
  7219. 'script' => [],
  7220. 'episode' => [],
  7221. 'answer' => '',
  7222. 'reasoning' => '',
  7223. 'usage' => [],
  7224. 'error' => '接口返回数据异常,请重新请求'
  7225. ];
  7226. return;
  7227. }
  7228. // 处理流式输出
  7229. foreach ($streamGenerator as $chunk) {
  7230. if (isset($chunk['type'])) {
  7231. if ($chunk['type'] === 'done') {
  7232. // 最终结果
  7233. $fullContent = $chunk['full_content'];
  7234. $fullReasoningContent = $chunk['full_reasoning'];
  7235. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7236. } else {
  7237. // 逐块yield数据
  7238. yield $chunk;
  7239. }
  7240. }
  7241. }
  7242. } catch (\Exception $e) {
  7243. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  7244. 'model' => $model,
  7245. 'anime_id' => $anime_id,
  7246. 'trace' => $e->getTraceAsString()
  7247. ]);
  7248. logDB('deepseek', 'error', 'addChat流式处理失败', [
  7249. 'error' => $e->getMessage(),
  7250. 'model' => $model
  7251. ]);
  7252. yield [
  7253. 'type' => 'error',
  7254. 'script' => [],
  7255. 'episode' => [],
  7256. 'answer' => '',
  7257. 'reasoning' => '',
  7258. 'usage' => [],
  7259. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7260. ];
  7261. return;
  7262. }
  7263. dLog('deepseek')->info('完整内容: '.$fullContent);
  7264. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7265. // 处理完整内容并返回最终结果
  7266. $script_arr = [];
  7267. if ($fullContent) {
  7268. $script_arr = handleScriptContentForAce($fullContent);
  7269. dLog('deepseek')->info('解析内容', $script_arr);
  7270. logDB('deepseek', 'info', '解析内容', $script_arr);
  7271. }
  7272. if (empty($script_arr['roles'])) {
  7273. // 未生成剧本相关内容,保存对话记录并返回提示
  7274. dLog('deepseek')->info('未生成剧本相关的内容');
  7275. try {
  7276. DB::beginTransaction();
  7277. $now = date('Y-m-d H:i:s');
  7278. // 保存对话记录
  7279. $records = [
  7280. [
  7281. 'uid' => $uid,
  7282. 'anime_id' => $anime_id,
  7283. 'sequence' => 0,
  7284. 'role' => 'user',
  7285. 'content' => $prompt,
  7286. 'created_at' => $now,
  7287. 'updated_at' => $now
  7288. ],
  7289. [
  7290. 'uid' => $uid,
  7291. 'anime_id' => $anime_id,
  7292. 'sequence' => 0,
  7293. 'role' => 'assistant',
  7294. // 'content' => $fullContent,
  7295. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  7296. 'created_at' => $now,
  7297. 'updated_at' => $now
  7298. ]
  7299. ];
  7300. DB::table('mp_anime_records')->insert($records);
  7301. DB::commit();
  7302. } catch (\Exception $e) {
  7303. DB::rollBack();
  7304. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7305. }
  7306. yield [
  7307. 'type' => 'done',
  7308. 'script' => [],
  7309. 'episode' => [],
  7310. 'answer' => $fullContent,
  7311. 'reasoning' => $fullReasoningContent,
  7312. 'usage' => $usage,
  7313. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  7314. ];
  7315. return;
  7316. }
  7317. // 如果需要生成原文内容,从script_arr中提取
  7318. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  7319. $content = $script_arr['content'];
  7320. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  7321. if (!$content) {
  7322. yield [
  7323. 'type' => 'done',
  7324. 'script' => [],
  7325. 'episode' => [],
  7326. 'answer' => $fullContent,
  7327. 'reasoning' => $fullReasoningContent,
  7328. 'usage' => $usage,
  7329. 'error' => '未生成剧本内容,请调整提示词再试'
  7330. ];
  7331. return;
  7332. }
  7333. }
  7334. // 替换美术风格
  7335. if ($mappedArtStyle !== '') {
  7336. $script_arr['art_style'] = $mappedArtStyle;
  7337. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  7338. }
  7339. // 新建动漫
  7340. if ($user_anime_name == '新剧本策划') {
  7341. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  7342. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  7343. // if (!$anime_name) {
  7344. // // 未识别到剧本名,保存对话记录并返回提示
  7345. // dLog('deepseek')->info('未能识别到剧本名称');
  7346. // try {
  7347. // DB::beginTransaction();
  7348. // $now = date('Y-m-d H:i:s');
  7349. // // 保存对话记录
  7350. // $records = [
  7351. // [
  7352. // 'uid' => $uid,
  7353. // 'anime_id' => $anime_id,
  7354. // 'sequence' => 0,
  7355. // 'role' => 'user',
  7356. // 'content' => $prompt,
  7357. // 'created_at' => $now,
  7358. // 'updated_at' => $now
  7359. // ],
  7360. // [
  7361. // 'uid' => $uid,
  7362. // 'anime_id' => $anime_id,
  7363. // 'sequence' => 0,
  7364. // 'role' => 'assistant',
  7365. // 'content' => '未能生成剧本名称,请重试',
  7366. // 'created_at' => $now,
  7367. // 'updated_at' => $now
  7368. // ]
  7369. // ];
  7370. // DB::table('mp_anime_records')->insert($records);
  7371. // DB::commit();
  7372. // } catch (\Exception $e) {
  7373. // DB::rollBack();
  7374. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7375. // }
  7376. // yield [
  7377. // 'type' => 'done',
  7378. // 'script' => [],
  7379. // 'episode' => [],
  7380. // 'answer' => $fullContent,
  7381. // 'reasoning' => $fullReasoningContent,
  7382. // 'usage' => $usage,
  7383. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  7384. // ];
  7385. // return;
  7386. // }
  7387. // 确认对话名称唯一性
  7388. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  7389. $anime_name = $anime_name . '_' . date('YmdHis');
  7390. }
  7391. }else {
  7392. $anime_name = $user_anime_name;
  7393. }
  7394. $table_data = [
  7395. 'user_id' => $uid,
  7396. 'anime_name' => $anime_name,
  7397. 'model' => $model,
  7398. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  7399. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  7400. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  7401. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  7402. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  7403. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  7404. 'art_style_type' => $input_art_style,
  7405. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  7406. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  7407. 'status' => '解析完成',
  7408. 'content' => $content,
  7409. 'is_multi' => $is_multi,
  7410. 'ace_mode' => $ace_mode,
  7411. 'generate_status' => '待执行',
  7412. 'updated_at' => date('Y-m-d H:i:s')
  7413. ];
  7414. if ($table_data['content']) {
  7415. $chapters = splitContent($table_data['content']);
  7416. $chapter_count = count($chapters);
  7417. if ($chapter_count > 0) {
  7418. $table_data['start_episode_sequence'] = 1;
  7419. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  7420. }
  7421. }
  7422. if ($extra_products) {
  7423. $table_data['extra_products'] = json_encode($extra_products, 256);
  7424. }
  7425. // 如果有剧本ID则进行绑定
  7426. if ($script_id) {
  7427. $table_data['script_id'] = $script_id;
  7428. }
  7429. $single_episode = [];
  7430. try {
  7431. DB::beginTransaction();
  7432. $now = date('Y-m-d H:i:s');
  7433. // 更新动漫大纲
  7434. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7435. if (!$boolen) {
  7436. dLog('deepseek')->info('动漫保存失败', $table_data);
  7437. Utils::throwError('20003:动漫保存失败');
  7438. }
  7439. // 保存对话记录
  7440. $records = [
  7441. [
  7442. 'uid' => $uid,
  7443. 'anime_id' => $anime_id,
  7444. 'sequence' => 0,
  7445. 'role' => 'user',
  7446. 'content' => $prompt,
  7447. 'created_at' => date('Y-m-d H:i:s'),
  7448. 'updated_at' => date('Y-m-d H:i:s')
  7449. ],
  7450. [
  7451. 'uid' => $uid,
  7452. 'anime_id' => $anime_id,
  7453. 'sequence' => 0,
  7454. 'role' => 'assistant',
  7455. 'content' => $fullContent,
  7456. 'created_at' => date('Y-m-d H:i:s'),
  7457. 'updated_at' => date('Y-m-d H:i:s')
  7458. ]
  7459. ];
  7460. // 保存对话记录
  7461. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7462. if (!$boolen3) {
  7463. Utils::throwError('20003:对话记录保存失败');
  7464. }
  7465. if ($is_single) {
  7466. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7467. if (empty($episode_arr['acts'])) {
  7468. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7469. }
  7470. $saveResult = $this->saveEpisodeVersionData(
  7471. $anime_id,
  7472. 1,
  7473. $episode_arr,
  7474. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7475. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7476. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7477. null,
  7478. null,
  7479. false,
  7480. $content,
  7481. $now,
  7482. $ref_products
  7483. );
  7484. $single_episode = $saveResult['episode'];
  7485. $episode_id = $saveResult['episode_id'];
  7486. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7487. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7488. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7489. 'props' => json_encode($saveResult['merged_props'], 256),
  7490. 'updated_at' => $now
  7491. ]);
  7492. if ($boolen5 === false) {
  7493. Utils::throwError('20003:单剧集主表资源同步失败');
  7494. }
  7495. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7496. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7497. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7498. $episode_record_content = '确认分镜大纲';
  7499. if ($content !== '') {
  7500. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7501. }
  7502. $episode_records = [
  7503. [
  7504. 'uid' => $uid,
  7505. 'anime_id' => $anime_id,
  7506. 'role' => 'user',
  7507. 'content' => $episode_record_content,
  7508. 'sequence' => 1,
  7509. 'episode_id' => $episode_id,
  7510. 'created_at' => $now,
  7511. 'updated_at' => $now
  7512. ],
  7513. [
  7514. 'uid' => $uid,
  7515. 'anime_id' => $anime_id,
  7516. 'role' => 'assistant',
  7517. 'content' => $fullContent,
  7518. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7519. 'sequence' => 1,
  7520. 'episode_id' => $episode_id,
  7521. 'created_at' => $now,
  7522. 'updated_at' => $now
  7523. ]
  7524. ];
  7525. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7526. if (!$boolen4) {
  7527. Utils::throwError('20003:单剧集分镜记录保存失败');
  7528. }
  7529. }
  7530. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7531. if ($is_single && !empty($single_episode)) {
  7532. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7533. 'anime_id' => $anime_id,
  7534. 'episode_id' => $episode_id ?? 0,
  7535. 'model' => $model,
  7536. 'source' => 'addChatForAce',
  7537. ]);
  7538. }
  7539. }catch (\Exception $e) {
  7540. DB::rollBack();
  7541. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7542. yield [
  7543. 'type' => 'done',
  7544. 'answer' => $fullContent,
  7545. 'reasoning' => $fullReasoningContent,
  7546. 'usage' => $usage,
  7547. 'error' => $e->getMessage(),
  7548. ];
  7549. return;
  7550. }
  7551. DB::commit();
  7552. dLog('deepseek')->info('保存完毕');
  7553. if ($is_single && !empty($single_episode)) {
  7554. // $this->batchSetGlobalRoleImg([
  7555. // 'anime_id' => $anime_id,
  7556. // ]);
  7557. // $this->batchSetGlobalSceneImg([
  7558. // 'anime_id' => $anime_id,
  7559. // ]);
  7560. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7561. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7562. }
  7563. $table_data['anime_id'] = $anime_id;
  7564. $table_data['roles'] = json_decode($table_data['roles'], true);
  7565. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7566. // $table_data['episodes'] = $script_arr['episodes'];
  7567. unset($table_data['created_at']);
  7568. unset($table_data['updated_at']);
  7569. unset($table_data['status']);
  7570. dLog('deepseek')->info('开始返回');
  7571. yield [
  7572. 'type' => 'done',
  7573. 'script' => $table_data,
  7574. 'episode' => $single_episode,
  7575. 'answer' => $fullContent,
  7576. 'reasoning' => $fullReasoningContent,
  7577. 'usage' => $usage
  7578. ];
  7579. }
  7580. public function reGenerateAnimeForAce($data) {
  7581. $uid = Site::getUid();
  7582. $file = getProp($data, 'file');
  7583. $content = getProp($data, 'content', '');
  7584. $bid = getProp($data, 'bid', 0);
  7585. $script_id = getProp($data, 'script_id', 0);
  7586. $anime_id = getProp($data, 'anime_id');
  7587. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7588. if (!$anime) {
  7589. Utils::throwError('20003:该对话不存在');
  7590. }
  7591. $is_multi = getProp($anime, 'is_multi', 1);
  7592. $is_single = (int)$is_multi !== 1;
  7593. // 积分余额预检(仅单剧集模式收费)
  7594. if ($is_single) {
  7595. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  7596. }
  7597. $extra_products = getProp($data, 'products', []);
  7598. if (!$extra_products) {
  7599. $extra_products = getProp($anime, 'extra_products');
  7600. if ($extra_products) {
  7601. $extra_products = json_decode($extra_products, true);
  7602. }else {
  7603. $extra_products = [];
  7604. }
  7605. }else {
  7606. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7607. }
  7608. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7609. $anime_script_id = getProp($anime, 'script_id');
  7610. if ($anime_script_id && $is_single) {
  7611. $cpid = Site::getCpid();
  7612. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7613. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7614. ->where('mapping.script_id', $anime_script_id)
  7615. ->where('product.cpid', $cpid)
  7616. ->where('product.is_deleted', 0);
  7617. $mappings = $script_products_mappings->select(
  7618. 'mapping.product_id',
  7619. 'mapping.episode_number',
  7620. 'product.product_name',
  7621. 'product.type',
  7622. 'product.product',
  7623. 'product.pic_prompt',
  7624. 'product.url',
  7625. 'product.pic_task_id',
  7626. 'product.pic_task_status',
  7627. 'product.three_view_image_url'
  7628. )
  7629. ->get();
  7630. // 按 product_id 分组,合并 episode_number
  7631. $productMap = [];
  7632. foreach ($mappings as $item) {
  7633. $product_id = $item->product_id;
  7634. $product_name = $item->product_name;
  7635. // 处理product_name两边的符号
  7636. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7637. if (!isset($productMap[$product_id])) {
  7638. $productMap[$product_id] = [
  7639. 'product_id' => $product_id,
  7640. 'product_name' => $product_name,
  7641. 'type' => (int)$item->type,
  7642. 'product' => (int)$item->product,
  7643. 'pic_prompt' => $item->pic_prompt,
  7644. 'url' => $item->url,
  7645. 'pic_task_id' => $item->pic_task_id,
  7646. 'pic_task_status' => $item->pic_task_status,
  7647. 'episode_numbers' => [],
  7648. ];
  7649. }
  7650. // 添加 episode_number(去重)
  7651. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7652. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7653. }
  7654. }
  7655. // 将查询到的剧本资产合并到extra_products中
  7656. // 先构建extra_products的索引(以product_id为key,用于去重)
  7657. $extraProductsMap = [];
  7658. foreach ($extra_products as $item) {
  7659. $key = getProp($item, 'product_id');
  7660. if ($key) {
  7661. $extraProductsMap[$key] = $item;
  7662. }
  7663. }
  7664. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7665. foreach ($productMap as $product) {
  7666. $product_id = $product['product_id'];
  7667. // 如果不存在则添加(不带episode_number信息)
  7668. if (!isset($extraProductsMap[$product_id])) {
  7669. $extraProductsMap[$product_id] = [
  7670. 'product_id' => $product['product_id'],
  7671. 'product_name' => $product['product_name'],
  7672. 'type' => $product['type'],
  7673. 'product' => $product['product'],
  7674. 'pic_prompt' => $product['pic_prompt'],
  7675. 'url' => $product['url'],
  7676. 'pic_task_id' => $product['pic_task_id'],
  7677. 'pic_task_status' => $product['pic_task_status'],
  7678. ];
  7679. }
  7680. }
  7681. // 重新赋值给extra_products
  7682. $extra_products = array_values($extraProductsMap);
  7683. }
  7684. $user_anime_name = getProp($anime, 'anime_name');
  7685. $prompt = getProp($data, 'prompt');
  7686. // 处理提示词
  7687. if ($prompt && $extra_products) {
  7688. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7689. foreach($extra_products as $item) {
  7690. $product_name = getProp($item, 'product_name');
  7691. if ($product_name) {
  7692. // 替换 {product_name} 为 product_name
  7693. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7694. }
  7695. }
  7696. }
  7697. // 处理文本模型
  7698. $model = getProp($data, 'model');
  7699. if (!$model) {
  7700. // 用户没有输入,从anime表获取
  7701. $model = getProp($anime, 'model');
  7702. if (!$model) {
  7703. // anime表也没有,使用默认值
  7704. $model = 'deepseek-v4-pro';
  7705. }
  7706. }
  7707. // 验证模型是否在可用模型表中
  7708. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7709. $model = 'deepseek-v4-pro';
  7710. }
  7711. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  7712. if ($is_single) {
  7713. $episode_exists = DB::table('mp_anime_episodes')
  7714. ->where('anime_id', $anime_id)
  7715. ->where('sequence', 1)
  7716. ->exists();
  7717. if ($episode_exists) {
  7718. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  7719. }
  7720. }
  7721. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7722. if ($prompt) {
  7723. $question .= "本次修改要求如下:\n{$prompt}";
  7724. }
  7725. // 提取文件内容
  7726. if ($file) {
  7727. $content = $this->extractFileContent($file);
  7728. if (!$content) {
  7729. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7730. }
  7731. } elseif ($script_id) {
  7732. $content = $this->getContentByScriptId($script_id);
  7733. if (!$content) {
  7734. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7735. }
  7736. } elseif ($bid) {
  7737. $content = $this->getContentByBid($bid);
  7738. if (!$content) {
  7739. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7740. }
  7741. } elseif ($content) {
  7742. $content = filterContent($content);
  7743. }else {
  7744. $content = filterContent(getProp($anime, 'content'));
  7745. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7746. $need_generate_content = true;
  7747. }
  7748. }
  7749. // 判断是否需要生成原文内容
  7750. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7751. // 如果需要生成原文内容,添加额外的要求
  7752. $content_generation_requirement = $need_generate_content
  7753. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7754. : "";
  7755. // 美术风格
  7756. $input_art_style = getProp($data, 'art_style');
  7757. if (!$input_art_style) {
  7758. $mappedArtStyle = getProp($anime, 'art_style');
  7759. }else {
  7760. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7761. }
  7762. if (!$mappedArtStyle) {
  7763. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7764. }else {
  7765. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7766. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7767. }else {
  7768. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7769. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7770. }
  7771. }
  7772. // 构建主体、场景和道具提示词
  7773. $extra_role_prompt = "\n";
  7774. $extra_scene_prompt = "\n";
  7775. $extra_prop_prompt = "\n";
  7776. $ref_products = []; // 参考资产
  7777. if ($extra_products) {
  7778. foreach($extra_products as $item) {
  7779. $product = getProp($item, 'product');
  7780. $product_name = getProp($item, 'product_name');
  7781. if ($product_name == '旁白') continue;
  7782. $ref_products[$product_name] = $item;
  7783. $pic_prompt = getProp($item, 'pic_prompt');
  7784. if ((int)$product === 1) {
  7785. // 拼接角色信息
  7786. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7787. } elseif ((int)$product === 2) {
  7788. // 拼接场景信息
  7789. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7790. } elseif ((int)$product === 3) {
  7791. // 拼接道具信息
  7792. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7793. }
  7794. }
  7795. // 优化提示词,融入剧本
  7796. if (!empty(trim($extra_role_prompt))) {
  7797. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7798. }
  7799. if (!empty(trim($extra_scene_prompt))) {
  7800. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7801. }
  7802. if (!empty(trim($extra_prop_prompt))) {
  7803. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7804. }
  7805. }
  7806. if ($anime_script_id && $is_single) {
  7807. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7808. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7809. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7810. }else {
  7811. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7812. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7813. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7814. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7815. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7816. {$extra_role_prompt}";
  7817. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7818. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7819. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7820. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7821. {$extra_scene_prompt}";
  7822. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7823. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7824. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7825. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7826. {$extra_prop_prompt}";
  7827. }
  7828. $system_message = ['role'=>'system', 'content'=>$is_single
  7829. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7830. 强制要求:
  7831. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7832. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7833. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7834. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7835. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7836. 普通要求:
  7837. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7838. $role_demo
  7839. $scene_demo
  7840. $prop_demo
  7841. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7842. 5.1片段分割逻辑(优先级从高到低):
  7843. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7844. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7845. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7846. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7847. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7848. - 片段数量格式为: 片段数量:8
  7849. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7850. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7851. 5.3分镜结构:每个分镜包含以下字段:
  7852. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7853. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7854. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7855. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7856. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7857. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7858. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7859. - 运镜:场景+画面描述+运镜
  7860. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7861. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7862. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7863. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7864. 6.{$mappedArtStyle_prompt}\n\n
  7865. 示例如下:\n
  7866. ###剧本名:西昆仑
  7867. ###故事梗概
  7868. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7869. ###剧本亮点
  7870. 亮点1:绝境奇药,生死一线
  7871. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7872. 亮点2:结拜兄妹,化解尴尬
  7873. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7874. 亮点3:纤发夺命,情愫暗涌
  7875. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7876. ###人物关系
  7877. 阿雪与梁萧之间存在兄妹之情。
  7878. ###核心矛盾
  7879. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7880. ###主体列表
  7881. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7882. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7883. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7884. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7885. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7886. 全景,正面拍摄,青年女性,亚洲人。
  7887. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7888. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7889. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7890. ###美术风格
  7891. 基础画风风格词:厚涂古风
  7892. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7893. ###场景列表
  7894. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7895. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7896. 无人物。}
  7897. ###分段剧本
  7898. 片段数量:8
  7899. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7900. ##片段1
  7901. 时长:12s
  7902. 分镜1
  7903. 出场角色:刀疤脸
  7904. 场景:边境小镇街道
  7905. 出场道具:酒杯-高脚杯
  7906. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7907. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7908. 配音台词:
  7909. 背景音效:
  7910. 分镜2
  7911. 出场角色:刀疤脸
  7912. 场景:悦来酒馆
  7913. 出场道具:酒杯-高脚杯
  7914. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7915. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7916. 配音台词:
  7917. 背景音效:
  7918. 分镜3
  7919. 出场角色:刀疤脸
  7920. 场景:悦来酒馆
  7921. 出场道具:酒杯-高脚杯
  7922. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7923. 运镜:从中景推向令牌特写。
  7924. 配音台词:
  7925. 背景音效:
  7926. 分镜4
  7927. 出场角色:刀疤脸
  7928. 场景:悦来酒馆
  7929. 出场道具:酒杯-高脚杯
  7930. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7931. 运镜:极速推向酒水溅起的瞬间。
  7932. 配音台词:
  7933. 背景音效:
  7934. 分镜5
  7935. 出场角色:刀疤脸
  7936. 场景:悦来酒馆
  7937. 出场道具:酒杯-高脚杯
  7938. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7939. 运镜:固定机位,利用倾斜构图制造压迫感。
  7940. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7941. 背景音效:
  7942. \n\n"
  7943. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7944. 强制要求:\n
  7945. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7946. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7947. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7948. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7949. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7950. 普通要求:\n
  7951. 1.剧本名(必须生成)必须与文档内容高度相关
  7952. $role_demo
  7953. $scene_demo
  7954. $prop_demo
  7955. 5.{$mappedArtStyle_prompt}\n\n
  7956. 示例如下:\n
  7957. ###剧本名:西昆仑
  7958. ###故事梗概
  7959. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7960. ###剧本亮点
  7961. 亮点1:绝境奇药,生死一线
  7962. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7963. 亮点2:结拜兄妹,化解尴尬
  7964. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7965. 亮点3:纤发夺命,情愫暗涌
  7966. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7967. ###人物关系
  7968. 阿雪与梁萧之间存在兄妹之情。
  7969. ###核心矛盾
  7970. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7971. ###主体列表
  7972. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7973. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7974. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7975. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7976. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7977. 全景,正面拍摄,青年女性,亚洲人。
  7978. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7979. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7980. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7981. ###美术风格
  7982. 基础画风风格词:厚涂古风
  7983. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7984. ###场景列表
  7985. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7986. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7987. 无人物。}
  7988. ###道具列表
  7989. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  7990. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  7991. $episode_count = $this->extractEpisodeNumber($prompt);
  7992. if ((int)getProp($anime, 'is_multi') !== 1) {
  7993. yield [
  7994. 'type' => 'done',
  7995. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  7996. 'reasoning' => '',
  7997. 'usage' => []
  7998. ];
  7999. return;
  8000. }
  8001. if ($episode_count) {
  8002. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  8003. $system_message = [
  8004. 'role' => 'system',
  8005. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8006. 强制要求:\n
  8007. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8008. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8009. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8010. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8011. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8012. 普通要求:\n
  8013. 1.<故事梗概>控制在200-300字左右
  8014. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8015. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8016. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8017. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8018. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8019. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8020. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8021. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8022. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8023. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  8024. 示例如下:\n
  8025. ###剧本名:西昆仑
  8026. ###故事梗概
  8027. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8028. ###剧本亮点
  8029. 亮点1:绝境奇药,生死一线
  8030. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8031. 亮点2:结拜兄妹,化解尴尬
  8032. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8033. 亮点3:纤发夺命,情愫暗涌
  8034. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8035. ###人物关系
  8036. 阿雪与梁萧之间存在兄妹之情。
  8037. ###核心矛盾
  8038. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8039. ###主体列表
  8040. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8041. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8042. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8043. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8044. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8045. 全景,正面拍摄,青年女性,亚洲人。
  8046. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8047. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8048. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8049. ###美术风格
  8050. 基础画风风格词:厚涂古风
  8051. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8052. ###场景列表
  8053. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8054. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8055. 无人物。}
  8056. ###分集详细内容
  8057. ##第1章 重生
  8058. 我重生了。
  8059. 源于一个男人偏执的暗恋。
  8060. ##第2章 相救
  8061. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  8062. 我眼睛扫向站在锅炉后的卞大伟。"
  8063. ];
  8064. // 构建消息
  8065. $messages = [
  8066. $system_message,
  8067. [
  8068. 'role' => 'user',
  8069. 'content' => "以下是文档内容:
  8070. {$content}
  8071. 用户问题:
  8072. {$question}"
  8073. ]
  8074. ];
  8075. }else {
  8076. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  8077. // 构建消息
  8078. $messages = [
  8079. $system_message,
  8080. [
  8081. 'role' => 'user',
  8082. 'content' => "以下是文档内容:
  8083. {$content}
  8084. 用户问题:
  8085. {$question}"
  8086. ]
  8087. ];
  8088. }else {
  8089. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  8090. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  8091. return (array)$value;
  8092. })->toArray();
  8093. array_unshift($messages, $system_message);
  8094. $messages[] = [
  8095. 'role' => 'user',
  8096. 'content' => $prompt
  8097. ];
  8098. }
  8099. }
  8100. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8101. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  8102. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8103. if ($model === 'deepseek-chat') {
  8104. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8105. $model = 'deepseek-v4-flash';
  8106. $thinkingMode = 'disabled';
  8107. } elseif ($model === 'deepseek-reasoner') {
  8108. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8109. $model = 'deepseek-v4-flash';
  8110. $thinkingMode = 'enabled';
  8111. }
  8112. $post_data = [
  8113. 'model' => $model,
  8114. 'messages' => $messages,
  8115. // 'max_tokens' => 8192,
  8116. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8117. 'frequency_penalty' => 0,
  8118. 'presence_penalty' => 0,
  8119. 'response_format' => ['type' => 'text'],
  8120. 'thinking' => ['type' => $thinkingMode],
  8121. 'stream' => true // 启用流式输出
  8122. ];
  8123. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8124. // 根据模型类型选择调用方法
  8125. $fullContent = '';
  8126. $fullReasoningContent = '';
  8127. $usage = [];
  8128. // dd($post_data);
  8129. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  8130. try {
  8131. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8132. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8133. } else if (in_array($model, $this->gpt_text_models)) {
  8134. // GPT-5.4 模型使用 TokenRouter API
  8135. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8136. } else if (in_array($model, $this->gemini_text_models)) {
  8137. // Gemini 模型使用 Gemini API
  8138. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8139. } else {
  8140. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8141. }
  8142. // 验证返回值类型
  8143. if (!is_iterable($streamGenerator)) {
  8144. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8145. dLog('deepseek')->error('方法名流式生成器无效', [
  8146. 'generator_type' => $errorType,
  8147. 'model' => $model,
  8148. // 添加其他上下文信息
  8149. ]);
  8150. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  8151. 'type' => $errorType,
  8152. 'model' => $model
  8153. ]);
  8154. yield [
  8155. 'type' => 'error',
  8156. // 根据方法返回相应的空数据结构
  8157. 'answer' => '',
  8158. 'reasoning' => '',
  8159. 'usage' => [],
  8160. 'error' => '接口返回数据异常,请重新请求'
  8161. ];
  8162. return;
  8163. }
  8164. // 处理流式输出
  8165. foreach ($streamGenerator as $chunk) {
  8166. if (isset($chunk['type'])) {
  8167. if ($chunk['type'] === 'done') {
  8168. $fullContent = $chunk['full_content'];
  8169. $fullReasoningContent = $chunk['full_reasoning'];
  8170. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8171. } else {
  8172. yield $chunk;
  8173. }
  8174. }
  8175. }
  8176. } catch (\Exception $e) {
  8177. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  8178. 'model' => $model,
  8179. 'trace' => $e->getTraceAsString()
  8180. ]);
  8181. logDB('deepseek', 'error', '方法名流式处理失败', [
  8182. 'error' => $e->getMessage(),
  8183. 'model' => $model
  8184. ]);
  8185. yield [
  8186. 'type' => 'error',
  8187. // 根据方法返回相应的空数据结构
  8188. 'answer' => '',
  8189. 'reasoning' => '',
  8190. 'usage' => [],
  8191. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8192. ];
  8193. return;
  8194. }
  8195. dLog('deepseek')->info('完整内容: '.$fullContent);
  8196. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8197. // 处理完整内容并返回最终结果
  8198. $script_arr = [];
  8199. if ($fullContent) {
  8200. $script_arr = handleScriptContentForAce($fullContent);
  8201. dLog('deepseek')->info('解析内容', $script_arr);
  8202. logDB('deepseek', 'info', '解析内容', $script_arr);
  8203. }
  8204. if (empty($script_arr['roles'])) {
  8205. // 未生成剧本相关内容,保存对话记录并返回提示
  8206. dLog('deepseek')->info('未生成剧本相关的内容');
  8207. try {
  8208. $now = date('Y-m-d H:i:s');
  8209. // 保存对话记录
  8210. $records = [
  8211. [
  8212. 'uid' => $uid,
  8213. 'anime_id' => $anime_id,
  8214. 'sequence' => 0,
  8215. 'role' => 'user',
  8216. 'content' => $prompt,
  8217. 'created_at' => $now,
  8218. 'updated_at' => $now
  8219. ],
  8220. [
  8221. 'uid' => $uid,
  8222. 'anime_id' => $anime_id,
  8223. 'sequence' => 0,
  8224. 'role' => 'assistant',
  8225. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  8226. 'created_at' => $now,
  8227. 'updated_at' => $now
  8228. ]
  8229. ];
  8230. DB::table('mp_anime_records')->insert($records);
  8231. } catch (\Exception $e) {
  8232. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8233. }
  8234. yield [
  8235. 'type' => 'done',
  8236. 'script' => [],
  8237. 'episode' => [],
  8238. 'answer' => $fullContent,
  8239. 'reasoning' => $fullReasoningContent,
  8240. 'usage' => $usage,
  8241. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  8242. ];
  8243. return;
  8244. }
  8245. // 替换美术风格
  8246. if ($mappedArtStyle !== '') {
  8247. $script_arr['art_style'] = $mappedArtStyle;
  8248. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8249. }
  8250. if ($user_anime_name != '新剧本策划') {
  8251. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  8252. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  8253. // 确认对话名称唯一性
  8254. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  8255. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  8256. }
  8257. }else {
  8258. $anime_name = $user_anime_name;
  8259. }
  8260. $table_data = [
  8261. 'user_id' => $uid,
  8262. 'model' => $model,
  8263. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  8264. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  8265. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  8266. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  8267. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  8268. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  8269. 'art_style_type' => $input_art_style,
  8270. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  8271. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  8272. 'status' => '解析完成',
  8273. 'generate_status' => '待执行',
  8274. 'updated_at' => date('Y-m-d H:i:s')
  8275. ];
  8276. if ($anime_name) $table_data['anime_name'] = $anime_name;
  8277. // 如果是修改集数,则将content内容更新(会改变原文)
  8278. if (isset($episode_count) && $episode_count > 0) {
  8279. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  8280. $table_data['start_episode_sequence'] = 1;
  8281. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  8282. }else {
  8283. // 如果需要生成原文内容,从script_arr中提取
  8284. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  8285. $table_data['content'] = $script_arr['content'];
  8286. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  8287. if (!$table_data['content']) {
  8288. yield [
  8289. 'type' => 'done',
  8290. 'script' => [],
  8291. 'episode' => [],
  8292. 'answer' => $fullContent,
  8293. 'reasoning' => $fullReasoningContent,
  8294. 'usage' => $usage,
  8295. 'error' => '未生成剧本内容,请调整提示词再试'
  8296. ];
  8297. return;
  8298. }
  8299. }
  8300. if (isset($table_data['content']) && $table_data['content']) {
  8301. $chapters = splitContent($table_data['content']);
  8302. $chapter_count = count($chapters);
  8303. if ($chapter_count > 0) {
  8304. $table_data['start_episode_sequence'] = 1;
  8305. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  8306. }
  8307. }
  8308. }
  8309. if ($extra_products) {
  8310. $table_data['extra_products'] = json_encode($extra_products, 256);
  8311. }
  8312. $single_episode = [];
  8313. try {
  8314. DB::beginTransaction();
  8315. $now = date('Y-m-d H:i:s');
  8316. // 更新动漫大纲
  8317. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  8318. if (!$boolen) {
  8319. dLog('deepseek')->info('对话修改失败', $table_data);
  8320. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  8321. Utils::throwError('20003:对话修改失败');
  8322. }
  8323. // 保存对话记录
  8324. $records = [
  8325. [
  8326. 'uid' => $uid,
  8327. 'anime_id' => $anime_id,
  8328. 'sequence' => 0,
  8329. 'role' => 'user',
  8330. 'content' => $prompt,
  8331. 'created_at' => $now,
  8332. 'updated_at' => $now
  8333. ],
  8334. [
  8335. 'uid' => $uid,
  8336. 'anime_id' => $anime_id,
  8337. 'sequence' => 0,
  8338. 'role' => 'assistant',
  8339. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8340. 'content' => $fullContent,
  8341. 'created_at' => $now,
  8342. 'updated_at' => $now
  8343. ]
  8344. ];
  8345. // 保存对话记录
  8346. $boolen3 = DB::table('mp_anime_records')->insert($records);
  8347. if (!$boolen3) {
  8348. Utils::throwError('20003:对话记录保存失败');
  8349. }
  8350. // 单剧集模式:生成并保存剧集信息
  8351. if ($is_single) {
  8352. $anime_name = getProp($anime, 'anime_name', '未命名');
  8353. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8354. if (empty($episode_arr['acts'])) {
  8355. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  8356. }
  8357. $saveResult = $this->saveEpisodeVersionData(
  8358. $anime_id,
  8359. 1,
  8360. $episode_arr,
  8361. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8362. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8363. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  8364. null,
  8365. null,
  8366. false,
  8367. $content,
  8368. $now,
  8369. $ref_products
  8370. );
  8371. $single_episode = $saveResult['episode'];
  8372. $episode_id = $saveResult['episode_id'];
  8373. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  8374. 'roles' => json_encode($saveResult['merged_roles'], 256),
  8375. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  8376. 'props' => json_encode($saveResult['merged_props'], 256),
  8377. 'updated_at' => $now
  8378. ]);
  8379. if ($boolen5 === false) {
  8380. Utils::throwError('20003:单剧集主表资源同步失败');
  8381. }
  8382. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  8383. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  8384. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  8385. $episode_record_content = '确认分镜大纲';
  8386. if ($content !== '') {
  8387. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  8388. }
  8389. $episode_records = [
  8390. [
  8391. 'uid' => $uid,
  8392. 'anime_id' => $anime_id,
  8393. 'role' => 'user',
  8394. 'content' => $episode_record_content,
  8395. 'sequence' => 1,
  8396. 'episode_id' => $episode_id,
  8397. 'created_at' => $now,
  8398. 'updated_at' => $now
  8399. ],
  8400. [
  8401. 'uid' => $uid,
  8402. 'anime_id' => $anime_id,
  8403. 'role' => 'assistant',
  8404. 'content' => $fullContent,
  8405. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8406. 'sequence' => 1,
  8407. 'episode_id' => $episode_id,
  8408. 'created_at' => $now,
  8409. 'updated_at' => $now
  8410. ]
  8411. ];
  8412. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  8413. if (!$boolen4) {
  8414. Utils::throwError('20003:单剧集分镜记录保存失败');
  8415. }
  8416. }
  8417. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8418. if ($is_single && !empty($single_episode)) {
  8419. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8420. 'anime_id' => $anime_id,
  8421. 'episode_id' => $episode_id ?? 0,
  8422. 'model' => $model,
  8423. 'source' => 'reGenerateAnimeForAce',
  8424. ]);
  8425. }
  8426. }catch (\Exception $e) {
  8427. DB::rollBack();
  8428. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  8429. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  8430. yield [
  8431. 'type' => 'done',
  8432. 'answer' => $fullContent,
  8433. 'reasoning' => $fullReasoningContent,
  8434. 'usage' => $usage,
  8435. 'error' => $e->getMessage(),
  8436. ];
  8437. return;
  8438. }
  8439. DB::commit();
  8440. dLog('deepseek')->info('保存完毕');
  8441. if ($is_single && !empty($single_episode)) {
  8442. // $this->batchSetGlobalRoleImg([
  8443. // 'anime_id' => $anime_id,
  8444. // ]);
  8445. // $this->batchSetGlobalSceneImg([
  8446. // 'anime_id' => $anime_id,
  8447. // ]);
  8448. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8449. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8450. }
  8451. $table_data['anime_id'] = $anime_id;
  8452. $table_data['roles'] = json_decode($table_data['roles'], true);
  8453. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8454. $table_data['props'] = json_decode($table_data['props'], true);
  8455. unset($table_data['updated_at']);
  8456. unset($table_data['status']);
  8457. yield [
  8458. 'type' => 'done',
  8459. 'script' => $table_data,
  8460. 'episode' => $single_episode,
  8461. 'answer' => $fullContent,
  8462. 'reasoning' => $fullReasoningContent,
  8463. 'usage' => $usage
  8464. ];
  8465. }
  8466. public function chatForAce($data) {
  8467. $uid = Site::getUid();
  8468. // 积分余额预检(不足直接报错)
  8469. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  8470. $anime_id = getProp($data, 'anime_id');
  8471. $file = getProp($data, 'file');
  8472. $content = getProp($data, 'content', '');
  8473. $bid = getProp($data, 'bid', 0);
  8474. $script_id = getProp($data, 'script_id', 0);
  8475. $episode_number = getProp($data, 'episode_number', 1);
  8476. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8477. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8478. if (!$anime) Utils::throwError('20003:该对话不存在!');
  8479. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  8480. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  8481. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  8482. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  8483. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  8484. $roles = is_array($roles) ? $roles : [];
  8485. $scenes = is_array($scenes) ? $scenes : [];
  8486. $extra_products = getProp($data, 'products', []);
  8487. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  8488. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  8489. $anime_script_id = getProp($anime, 'script_id');
  8490. if ($anime_script_id) {
  8491. $cpid = Site::getCpid();
  8492. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  8493. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8494. ->where('mapping.script_id', $anime_script_id)
  8495. ->where('product.cpid', $cpid)
  8496. ->where('product.is_deleted', 0);
  8497. // 如果提供了 episode_number,则过滤指定集数
  8498. if ($episode_number !== null && $episode_number !== '') {
  8499. $script_products_mappings->where('mapping.episode_number', $episode_number);
  8500. }
  8501. $mappings = $script_products_mappings->select(
  8502. 'mapping.product_id',
  8503. 'mapping.episode_number',
  8504. 'product.product_name',
  8505. 'product.type',
  8506. 'product.product',
  8507. 'product.pic_prompt',
  8508. 'product.url',
  8509. 'product.pic_task_id',
  8510. 'product.pic_task_status',
  8511. 'product.three_view_image_url'
  8512. )
  8513. ->get();
  8514. // 按 product_id 分组,合并 episode_number
  8515. $productMap = [];
  8516. foreach ($mappings as $item) {
  8517. $product_id = $item->product_id;
  8518. $product_name = $item->product_name;
  8519. // 处理product_name两边的符号
  8520. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8521. if (!isset($productMap[$product_id])) {
  8522. $productMap[$product_id] = [
  8523. 'product_id' => $product_id,
  8524. 'product_name' => $product_name,
  8525. 'type' => (int)$item->type,
  8526. 'product' => (int)$item->product,
  8527. 'pic_prompt' => $item->pic_prompt,
  8528. 'url' => $item->url,
  8529. 'pic_task_id' => $item->pic_task_id,
  8530. 'pic_task_status' => $item->pic_task_status,
  8531. 'episode_numbers' => [],
  8532. ];
  8533. }
  8534. // 添加 episode_number(去重)
  8535. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8536. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8537. }
  8538. }
  8539. // 将查询到的剧本资产合并到extra_products中
  8540. // 先构建extra_products的索引(以product_id+episode_number为key)
  8541. $extraProductsMap = [];
  8542. foreach ($extra_products as $item) {
  8543. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  8544. $extraProductsMap[$key] = $item;
  8545. }
  8546. // 合并剧本资产(去重:product_id+episode_number)
  8547. foreach ($productMap as $product) {
  8548. foreach ($product['episode_numbers'] as $ep_num) {
  8549. $key = $product['product_id'] . '_' . $ep_num;
  8550. // 如果不存在则添加
  8551. if (!isset($extraProductsMap[$key])) {
  8552. $extraProductsMap[$key] = [
  8553. 'product_id' => $product['product_id'],
  8554. 'product_name' => $product['product_name'],
  8555. 'type' => $product['type'],
  8556. 'product' => $product['product'],
  8557. 'pic_prompt' => $product['pic_prompt'],
  8558. 'url' => $product['url'],
  8559. 'pic_task_id' => $product['pic_task_id'],
  8560. 'pic_task_status' => $product['pic_task_status'],
  8561. 'episode_number' => $ep_num,
  8562. ];
  8563. }
  8564. }
  8565. }
  8566. // 重新赋值给extra_products
  8567. $extra_products = array_values($extraProductsMap);
  8568. }
  8569. // 处理提示词
  8570. if ($prompt && $extra_products) {
  8571. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8572. foreach($extra_products as $item) {
  8573. $product_name = getProp($item, 'product_name');
  8574. if ($product_name) {
  8575. // 替换 {product_name} 为 product_name
  8576. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8577. }
  8578. }
  8579. }
  8580. // 获取最后一集序号
  8581. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  8582. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  8583. // 转换主体列表和场景列表的格式
  8584. // 获取参考主体或场景
  8585. if ((int)$episode_number === 1) {
  8586. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  8587. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  8588. }else {
  8589. $prev_episode_number = $episode_number - 1;
  8590. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  8591. }
  8592. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  8593. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  8594. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  8595. // 合并anime_products和extra_products(extra_products优先,去重)
  8596. $anime_products = getProp($anime, 'extra_products');
  8597. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  8598. $ref_products = [];
  8599. foreach($anime_products as $item) {
  8600. $product_name = getProp($item, 'product_name');
  8601. $ref_products[$product_name] = $item;
  8602. }
  8603. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  8604. $extra_roles = []; // 从extra_products中提取的角色
  8605. $extra_scenes = []; // 从extra_products中提取的场景
  8606. $extra_props = []; // 从extra_products中提取的道具
  8607. if ($extra_products && is_array($extra_products)) {
  8608. foreach($extra_products as $item) {
  8609. $product = (int)getProp($item, 'product');
  8610. $product_name = getProp($item, 'product_name');
  8611. if ($product_name == '旁白') continue;
  8612. $pic_prompt = getProp($item, 'pic_prompt');
  8613. $ref_products[$product_name] = $item;
  8614. if ($product === 1) {
  8615. // 角色
  8616. $extra_roles[$product_name] = [
  8617. 'role' => $product_name,
  8618. 'pic_prompt' => $pic_prompt,
  8619. 'url' => getProp($item, 'url', ''),
  8620. ];
  8621. } elseif ($product === 2) {
  8622. // 场景
  8623. $extra_scenes[$product_name] = [
  8624. 'scene' => $product_name,
  8625. 'pic_prompt' => $pic_prompt,
  8626. 'url' => getProp($item, 'url', ''),
  8627. ];
  8628. } elseif ($product === 3) {
  8629. // 道具
  8630. $extra_props[$product_name] = [
  8631. 'prop' => $product_name,
  8632. 'pic_prompt' => $pic_prompt,
  8633. 'url' => getProp($item, 'url', ''),
  8634. ];
  8635. }
  8636. }
  8637. }
  8638. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  8639. $merged_roles = [];
  8640. foreach($ref_roles as $role) {
  8641. $role_name = getProp($role, 'role');
  8642. if (!isset($extra_roles[$role_name])) {
  8643. $merged_roles[$role_name] = $role;
  8644. }
  8645. }
  8646. // 添加extra_roles
  8647. foreach($extra_roles as $role_name => $role) {
  8648. $merged_roles[$role_name] = $role;
  8649. }
  8650. $ref_roles = array_values($merged_roles);
  8651. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  8652. $merged_scenes = [];
  8653. foreach($ref_scenes as $scene) {
  8654. $scene_name = getProp($scene, 'scene');
  8655. if (!isset($extra_scenes[$scene_name])) {
  8656. $merged_scenes[$scene_name] = $scene;
  8657. }
  8658. }
  8659. // 添加extra_scenes
  8660. foreach($extra_scenes as $scene_name => $scene) {
  8661. $merged_scenes[$scene_name] = $scene;
  8662. }
  8663. $ref_scenes = array_values($merged_scenes);
  8664. // 合并ref_props和extra_props(extra_props优先,去重)
  8665. $merged_props = [];
  8666. foreach($ref_props as $prop) {
  8667. $prop_name = getProp($prop, 'prop');
  8668. if (!isset($extra_props[$prop_name])) {
  8669. $merged_props[$prop_name] = $prop;
  8670. }
  8671. }
  8672. // 添加extra_props
  8673. foreach($extra_props as $prop_name => $prop) {
  8674. $merged_props[$prop_name] = $prop;
  8675. }
  8676. $ref_props = array_values($merged_props);
  8677. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  8678. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  8679. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  8680. // 构建强制主体、场景和道具提示词
  8681. $forced_roles_prompt = "";
  8682. $forced_scenes_prompt = "";
  8683. $forced_props_prompt = "";
  8684. if (!empty($extra_roles)) {
  8685. $forced_roles_list = "";
  8686. foreach($extra_roles as $role_name => $role) {
  8687. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  8688. }
  8689. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  8690. }
  8691. if (!empty($extra_scenes)) {
  8692. $forced_scenes_list = "";
  8693. foreach($extra_scenes as $scene_name => $scene) {
  8694. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  8695. }
  8696. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  8697. }
  8698. if (!empty($extra_props)) {
  8699. $forced_props_list = "";
  8700. foreach($extra_props as $prop_name => $prop) {
  8701. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  8702. }
  8703. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  8704. }
  8705. if ($anime_script_id) {
  8706. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  8707. }else if ($roles_content) {
  8708. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  8709. 主体范围:\n {$roles_content}\n
  8710. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  8711. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8712. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8713. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8714. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8715. }else {
  8716. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8717. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8718. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8719. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8720. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8721. }
  8722. if ($anime_script_id) {
  8723. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  8724. }else if ($scenes_content) {
  8725. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8726. 场景范围:\n {$scenes_content}\n
  8727. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  8728. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  8729. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8730. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8731. }else {
  8732. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8733. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8734. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8735. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8736. }
  8737. if ($anime_script_id) {
  8738. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  8739. }else if ($props_content) {
  8740. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8741. 道具范围:\n {$props_content}\n
  8742. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  8743. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  8744. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8745. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8746. }else {
  8747. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8748. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  8749. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8750. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8751. }
  8752. // 提取文件内容
  8753. if ($file) {
  8754. $uploaded_content = $this->extractFileContent($file);
  8755. if (!$uploaded_content) {
  8756. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8757. }
  8758. } elseif ($script_id) {
  8759. $uploaded_content = $this->getContentByScriptId($script_id);
  8760. if (!$uploaded_content) {
  8761. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  8762. }
  8763. } elseif ($bid) {
  8764. $uploaded_content = $this->getContentByBid($bid);
  8765. if (!$uploaded_content) {
  8766. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  8767. }
  8768. } elseif ($content) {
  8769. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  8770. }
  8771. // elseif ($prompt) {
  8772. // $uploaded_content = filterContent($prompt);
  8773. // }
  8774. else {
  8775. $uploaded_content = '';
  8776. }
  8777. // 美术风格
  8778. $input_art_style = getProp($data, 'art_style');
  8779. if (!$input_art_style) {
  8780. $mappedArtStyle = getProp($anime, 'art_style');
  8781. }else {
  8782. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  8783. }
  8784. if (!$mappedArtStyle) {
  8785. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  8786. }else {
  8787. if (strstr($mappedArtStyle, '基础画风风格词')) {
  8788. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  8789. }else {
  8790. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  8791. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  8792. }
  8793. }
  8794. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8795. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8796. // 强制要求:
  8797. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8798. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8799. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8800. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  8801. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  8802. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  8803. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  8804. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  8805. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  8806. // 10.分镜要和场景列表、人物主体保持一致\n
  8807. // 普通要求:
  8808. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8809. // {$role_demo}
  8810. // {$scene_demo}
  8811. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8812. // 4.1片段分割逻辑(优先级从高到低):
  8813. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8814. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8815. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8816. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8817. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8818. // - 片段数量格式为: 片段数量:8
  8819. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8820. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8821. // 4.3分镜结构:每个分镜包含以下字段:
  8822. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  8823. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  8824. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8825. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  8826. // - 运镜:场景+画面描述+运镜
  8827. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  8828. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8829. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8830. // 5.$mappedArtStyle_prompt\n\n
  8831. // 示例格式:\n
  8832. // 第1集:隐形的守护者
  8833. // ###故事梗概
  8834. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8835. // ###美术风格
  8836. // 基础画风风格词:胡金铨武侠
  8837. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8838. // ###主体列表
  8839. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8840. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8841. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8842. // ###场景列表
  8843. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8844. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8845. // ###分段剧本
  8846. // 片段数量:8
  8847. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8848. // ##片段1
  8849. // 时长:12s
  8850. // 分镜1
  8851. // 场景:边境小镇街道
  8852. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8853. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8854. // 配音台词:
  8855. // 背景音效:
  8856. // 分镜2
  8857. // 场景:悦来酒馆
  8858. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8859. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8860. // 配音台词:
  8861. // 背景音效:
  8862. // 分镜3
  8863. // 场景:悦来酒馆
  8864. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8865. // 运镜:从中景推向令牌特写。
  8866. // 配音台词:
  8867. // 背景音效:
  8868. // 分镜4
  8869. // 场景:悦来酒馆
  8870. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8871. // 运镜:极速推向酒水溅起的瞬间。
  8872. // 配音台词:
  8873. // 背景音效:
  8874. // 分镜5
  8875. // 镜头描述
  8876. // 场景:悦来酒馆
  8877. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8878. // 运镜:固定机位,利用倾斜构图制造压迫感。
  8879. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8880. // 背景音效:
  8881. // \n\n";
  8882. /*
  8883. // ====== 旧版 $demo(缓存优化前版本,动态数据内嵌在规则中间) ======
  8884. // 如需换回:删除下方新版 $demo,并把本块恢复为活动代码(去掉首尾注释标记)
  8885. // ===================================================================
  8886. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  8887. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  8888. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  8889. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  8890. 强制要求:
  8891. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  8892. 普通要求:
  8893. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8894. {$role_demo}
  8895. {$scene_demo}
  8896. {$prop_demo}
  8897. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8898. 5.1片段分割逻辑(优先级从高到低):
  8899. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8900. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8901. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8902. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8903. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8904. - 片段数量格式为: 片段数量:8
  8905. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8906. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8907. 5.3分镜结构:每个分镜包含以下字段:
  8908. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8909. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8910. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8911. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8912. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8913. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8914. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8915. - 运镜:场景+画面描述+运镜
  8916. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8917. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8918. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8919. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8920. 6.《情绪-视听语言映射表》:
  8921. 6.1 场景空间与时间心理学 (Scene & Temporality)
  8922. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8923. -----|---------|------------|----------------
  8924. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  8925. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  8926. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  8927. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  8928. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  8929. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8930. -----|---------|------------|----------------
  8931. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  8932. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  8933. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  8934. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  8935. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  8936. --------|---------|--------------|-------------
  8937. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  8938. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  8939. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  8940. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  8941. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  8942. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  8943. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  8944. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  8945. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  8946. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  8947. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  8948. -----|---------|------------|------------
  8949. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  8950. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  8951. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  8952. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  8953. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  8954. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  8955. --------|---------|--------------|----------
  8956. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  8957. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  8958. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  8959. 6.6 声音设计与潜意识影响 (Soundscape)
  8960. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  8961. -----|---------|------------|------------------
  8962. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  8963. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  8964. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  8965. 理论基石:
  8966. - The Five C's of Cinematography by Joseph V. Mascelli
  8967. - Film Art: An Introduction by David Bordwell
  8968. - Sight, Sound, Motion by Herbert Zettl
  8969. - Notes on the Cinematograph by Robert Bresson
  8970. \n\n
  8971. 7.{$mappedArtStyle_prompt}
  8972. 示例格式:\n
  8973. 第1集:隐形的守护者
  8974. ###故事梗概
  8975. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8976. ###美术风格
  8977. 基础画风风格词:胡金铨武侠
  8978. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8979. ###主体列表
  8980. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8981. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8982. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8983. ###场景列表
  8984. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8985. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8986. ###道具列表
  8987. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  8988. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  8989. ###分段剧本
  8990. 片段数量:8
  8991. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8992. ##片段1
  8993. 时长:12s
  8994. 分镜1
  8995. 出场角色:刀疤脸
  8996. 场景:边境小镇街道
  8997. 出场道具:酒杯-高脚杯
  8998. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8999. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9000. 配音台词:
  9001. 背景音效:
  9002. 分镜2
  9003. 出场角色:刀疤脸
  9004. 场景:悦来酒馆
  9005. 出场道具:酒杯-高脚杯
  9006. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9007. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9008. 配音台词:
  9009. 背景音效:
  9010. 分镜3
  9011. 出场角色:刀疤脸
  9012. 场景:悦来酒馆
  9013. 出场道具:酒杯-高脚杯
  9014. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9015. 运镜:从中景推向令牌特写。
  9016. 配音台词:
  9017. 背景音效:
  9018. 分镜4
  9019. 出场角色:刀疤脸
  9020. 场景:悦来酒馆
  9021. 出场道具:酒杯-高脚杯
  9022. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9023. 运镜:极速推向酒水溅起的瞬间。
  9024. 配音台词:
  9025. 背景音效:
  9026. 分镜5
  9027. 出场角色:刀疤脸
  9028. 场景:悦来酒馆
  9029. 出场道具:酒杯-高脚杯
  9030. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9031. 运镜:固定机位,利用倾斜构图制造压迫感。
  9032. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9033. 背景音效:
  9034. \n\n";
  9035. */
  9036. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  9037. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  9038. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  9039. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  9040. 强制要求:
  9041. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  9042. 普通要求:
  9043. 1.剧集标题必须与文档内容高度相关,剧集序号见文末【本次剧集信息】。
  9044. 2.<主体列表>的详细规则和可选范围见文末【本次生成数据-主体列表】。
  9045. 3.<场景列表>的详细规则和可选范围见文末【本次生成数据-场景列表】。
  9046. 4.<道具列表>的详细规则和可选范围见文末【本次生成数据-道具列表】。
  9047. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9048. 5.1片段分割逻辑(优先级从高到低):
  9049. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9050. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9051. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9052. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9053. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9054. - 片段数量格式为: 片段数量:8
  9055. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9056. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9057. 5.3分镜结构:每个分镜包含以下字段:
  9058. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  9059. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  9060. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9061. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9062. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9063. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9064. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9065. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9066. - 运镜:场景+画面描述+运镜
  9067. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  9068. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  9069. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9070. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  9071. 6.《情绪-视听语言映射表》:
  9072. 6.1 场景空间与时间心理学 (Scene & Temporality)
  9073. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9074. -----|---------|------------|----------------
  9075. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  9076. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  9077. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  9078. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  9079. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  9080. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9081. -----|---------|------------|----------------
  9082. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  9083. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  9084. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  9085. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  9086. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  9087. --------|---------|--------------|-------------
  9088. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  9089. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  9090. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  9091. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  9092. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  9093. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  9094. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  9095. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  9096. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  9097. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  9098. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  9099. -----|---------|------------|------------
  9100. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  9101. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  9102. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  9103. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  9104. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  9105. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  9106. --------|---------|--------------|----------
  9107. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  9108. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  9109. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  9110. 6.6 声音设计与潜意识影响 (Soundscape)
  9111. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  9112. -----|---------|------------|------------------
  9113. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  9114. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  9115. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  9116. 理论基石:
  9117. - The Five C's of Cinematography by Joseph V. Mascelli
  9118. - Film Art: An Introduction by David Bordwell
  9119. - Sight, Sound, Motion by Herbert Zettl
  9120. - Notes on the Cinematograph by Robert Bresson
  9121. \n\n
  9122. 7.美术风格要求见文末【本次生成数据-美术风格】。
  9123. 示例格式:\n
  9124. 第1集:隐形的守护者
  9125. ###故事梗概
  9126. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9127. ###美术风格
  9128. 基础画风风格词:胡金铨武侠
  9129. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  9130. ###主体列表
  9131. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9132. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  9133. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  9134. ###场景列表
  9135. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  9136. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  9137. ###道具列表
  9138. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  9139. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  9140. ###分段剧本
  9141. 片段数量:8
  9142. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9143. ##片段1
  9144. 时长:12s
  9145. 分镜1
  9146. 出场角色:刀疤脸
  9147. 场景:边境小镇街道
  9148. 出场道具:酒杯-高脚杯
  9149. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9150. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9151. 配音台词:
  9152. 背景音效:
  9153. 分镜2
  9154. 出场角色:刀疤脸
  9155. 场景:悦来酒馆
  9156. 出场道具:酒杯-高脚杯
  9157. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9158. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9159. 配音台词:
  9160. 背景音效:
  9161. 分镜3
  9162. 出场角色:刀疤脸
  9163. 场景:悦来酒馆
  9164. 出场道具:酒杯-高脚杯
  9165. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9166. 运镜:从中景推向令牌特写。
  9167. 配音台词:
  9168. 背景音效:
  9169. 分镜4
  9170. 出场角色:刀疤脸
  9171. 场景:悦来酒馆
  9172. 出场道具:酒杯-高脚杯
  9173. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9174. 运镜:极速推向酒水溅起的瞬间。
  9175. 配音台词:
  9176. 背景音效:
  9177. 分镜5
  9178. 出场角色:刀疤脸
  9179. 场景:悦来酒馆
  9180. 出场道具:酒杯-高脚杯
  9181. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9182. 运镜:固定机位,利用倾斜构图制造压迫感。
  9183. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9184. 背景音效:
  9185. \n\n本次生成数据(以上规则的动态数据均在此处,优先级等同对应编号规则):
  9186. 【本次剧集信息】剧集序号是{$episode_number}。
  9187. 【本次生成数据-主体列表】{$role_demo}
  9188. 【本次生成数据-场景列表】{$scene_demo}
  9189. 【本次生成数据-道具列表】{$prop_demo}
  9190. 【本次生成数据-美术风格】{$mappedArtStyle_prompt}
  9191. \n\n";
  9192. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  9193. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  9194. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  9195. $prompt = $origin_prompt;
  9196. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  9197. // 获取章节内容
  9198. $full_content = getProp($anime, 'content');
  9199. if ($uploaded_content) {
  9200. $full_content = $uploaded_content;
  9201. }
  9202. // 根据章节内容拆分章节
  9203. $chapters = splitContent($full_content);
  9204. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  9205. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  9206. $messages = [];
  9207. if ($prompt == '确认分镜大纲') {
  9208. // 暂时保留
  9209. $content = $chapter_content;
  9210. if ($is_single) $content = $full_content; // 单剧集使用全文
  9211. if (!$content) {
  9212. Utils::throwError('20003:章节内容无法获取,请确认');
  9213. }
  9214. $question = $is_single
  9215. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  9216. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  9217. // 构建消息
  9218. $messages[] =
  9219. [
  9220. 'role' => 'user',
  9221. 'content' => $question
  9222. ];
  9223. }else if ($prompt == '继续策划下一集') {
  9224. if ($is_single) {
  9225. Utils::throwError('20003:单剧集不支持继续策划下一集');
  9226. }
  9227. $content = $chapter_content;
  9228. if (!$content) {
  9229. Utils::throwError('20003:章节内容无法获取,请确认');
  9230. }
  9231. // 获取上一集最后记录
  9232. $prev_sequence = $episode_number - 1;
  9233. $messages = array_merge(
  9234. [
  9235. [
  9236. 'role' => 'system',
  9237. 'content' => $demo
  9238. ]
  9239. ],
  9240. $this->getEpisodeChatContent($anime_id, $prev_sequence, $content)
  9241. );
  9242. // 构建消息
  9243. $messages[] =
  9244. [
  9245. 'role' => 'user',
  9246. 'content' => "请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)"
  9247. ];
  9248. /*
  9249. // 旧版逻辑
  9250. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  9251. // 构建消息
  9252. $messages[] =
  9253. [
  9254. 'role' => 'user',
  9255. 'content' => $question
  9256. ];
  9257. */
  9258. // dd($messages);
  9259. }else {
  9260. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  9261. if (!$content) {
  9262. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  9263. }
  9264. if (!$content) {
  9265. Utils::throwError('20003:章节内容无法获取,请确认');
  9266. }
  9267. $messages = array_merge(
  9268. [
  9269. [
  9270. 'role' => 'system',
  9271. 'content' => $demo
  9272. ]
  9273. ],
  9274. $this->getEpisodeChatMessages($anime_id, $episode_number)
  9275. );
  9276. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  9277. $question = "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  9278. if ($origin_prompt) {
  9279. $question .= "本次修改要求如下:\n{$origin_prompt}";
  9280. }
  9281. // 将本集原文加入消息,供模型逐字摘录原文台词(修复重新生成时配音台词全部为"无"的问题)
  9282. $messages[] = [
  9283. 'role' => 'user',
  9284. 'content' => "本集剧情内容:\n\n{$content}\n"
  9285. ];
  9286. $messages[] =
  9287. [
  9288. 'role' => 'user',
  9289. 'content' => $question
  9290. ];
  9291. }
  9292. // 处理文本模型
  9293. $model = getProp($data, 'model');
  9294. if (!$model) {
  9295. // 用户没有输入,从anime表获取
  9296. $model = getProp($anime, 'model');
  9297. if (!$model) {
  9298. // anime表也没有,使用默认值
  9299. $model = 'deepseek-v4-pro';
  9300. }
  9301. }
  9302. // 验证模型是否在可用模型表中
  9303. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9304. $model = 'deepseek-v4-pro';
  9305. }
  9306. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  9307. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  9308. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  9309. if ($model === 'deepseek-chat') {
  9310. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  9311. $model = 'deepseek-v4-flash';
  9312. $thinkingMode = 'disabled';
  9313. } elseif ($model === 'deepseek-reasoner') {
  9314. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  9315. $model = 'deepseek-v4-flash';
  9316. $thinkingMode = 'enabled';
  9317. }
  9318. $post_data = [
  9319. 'model' => $model,
  9320. 'messages' => $messages,
  9321. // 'max_tokens' => 8192,
  9322. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9323. 'frequency_penalty' => 0,
  9324. 'presence_penalty' => 0,
  9325. 'response_format' => ['type' => 'text'],
  9326. 'thinking' => ['type' => $thinkingMode],
  9327. 'stream' => true // 启用流式输出
  9328. ];
  9329. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9330. // 根据模型类型选择调用方法
  9331. $fullContent = '';
  9332. $fullReasoningContent = '';
  9333. $usage = [];
  9334. try {
  9335. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9336. // DeepSeek 官方模型使用 DeepSeek API
  9337. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9338. } else if (in_array($model, $this->gpt_text_models)) {
  9339. // GPT-5.4 模型使用 TokenRouter API
  9340. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9341. } else if (in_array($model, $this->gemini_text_models)) {
  9342. // Gemini 模型使用 Gemini API
  9343. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9344. } else {
  9345. // 其他模型使用火山引擎API
  9346. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9347. }
  9348. // 验证返回值类型
  9349. if (!is_iterable($streamGenerator)) {
  9350. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  9351. dLog('deepseek')->error('chat流式生成器无效', [
  9352. 'generator_type' => $errorType,
  9353. 'model' => $model,
  9354. 'anime_id' => $anime_id,
  9355. 'episode_number' => $episode_number
  9356. ]);
  9357. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  9358. 'type' => $errorType,
  9359. 'model' => $model
  9360. ]);
  9361. yield [
  9362. 'type' => 'error',
  9363. 'episode' => [],
  9364. 'answer' => '',
  9365. 'reasoning' => '',
  9366. 'usage' => [],
  9367. 'error' => '接口返回数据异常,请重新请求'
  9368. ];
  9369. return;
  9370. }
  9371. // 处理流式输出
  9372. foreach ($streamGenerator as $chunk) {
  9373. if (isset($chunk['type'])) {
  9374. if ($chunk['type'] === 'done') {
  9375. // 最终结果
  9376. $fullContent = $chunk['full_content'];
  9377. $fullReasoningContent = $chunk['full_reasoning'];
  9378. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9379. } else {
  9380. // 逐块yield数据
  9381. yield $chunk;
  9382. }
  9383. }
  9384. }
  9385. } catch (\Exception $e) {
  9386. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  9387. 'model' => $model,
  9388. 'anime_id' => $anime_id,
  9389. 'episode_number' => $episode_number,
  9390. 'trace' => $e->getTraceAsString()
  9391. ]);
  9392. logDB('deepseek', 'error', 'chat流式处理失败', [
  9393. 'error' => $e->getMessage(),
  9394. 'model' => $model
  9395. ]);
  9396. yield [
  9397. 'type' => 'error',
  9398. 'episode' => [],
  9399. 'answer' => '',
  9400. 'reasoning' => '',
  9401. 'usage' => [],
  9402. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  9403. ];
  9404. return;
  9405. }
  9406. // 兼容模型偶发将整段正文包裹成 JSON 字符串返回
  9407. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9408. dLog('deepseek')->info('完整内容: '.$fullContent);
  9409. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  9410. // 处理完整内容并返回最终结果
  9411. $episode_arr = handleEpisodeContentForAce($fullContent);
  9412. dLog('deepseek')->info('解析内容: ', $episode_arr);
  9413. logDB('deepseek', 'info', '解析内容', $episode_arr);
  9414. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  9415. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  9416. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  9417. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  9418. // }
  9419. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  9420. $max_retries = 3;
  9421. $retry_count = 0;
  9422. $validation_failed = false;
  9423. $validation_error_msg = '';
  9424. // 验证生成的内容
  9425. if ($anime_script_id) {
  9426. // 检查是否有acts数据
  9427. if (empty($episode_arr['acts'])) {
  9428. $validation_failed = true;
  9429. $validation_error_msg = '未生成分镜剧本相关的内容';
  9430. } else {
  9431. // 校验主体列表:不能为空主体(旁白不算)
  9432. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9433. // 过滤掉"旁白"角色
  9434. $generated_roles = array_filter($generated_roles, function($role) {
  9435. return $role !== '旁白';
  9436. });
  9437. if (empty($generated_roles)) {
  9438. $validation_failed = true;
  9439. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9440. }
  9441. // 仅当存在强制主体设定时校验主体列表
  9442. if (!$validation_failed && !empty($extra_roles)) {
  9443. $expected_roles = array_keys($extra_roles);
  9444. // 找出生成的主体中不在预期列表中的主体
  9445. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9446. if (!empty($invalid_roles)) {
  9447. $validation_failed = true;
  9448. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9449. }
  9450. }
  9451. // 仅当存在强制场景设定时校验场景列表
  9452. if (!$validation_failed && !empty($extra_scenes)) {
  9453. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  9454. $expected_scenes = array_keys($extra_scenes);
  9455. // 找出生成的场景中不在预期列表中的场景
  9456. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9457. if (!empty($invalid_scenes)) {
  9458. $validation_failed = true;
  9459. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9460. }
  9461. }
  9462. // 仅当存在强制道具设定时校验道具列表
  9463. if (!$validation_failed && !empty($extra_props)) {
  9464. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9465. $expected_props = array_keys($extra_props);
  9466. // 找出生成的道具中不在预期列表中的道具
  9467. $invalid_props = array_diff($generated_props, $expected_props);
  9468. if (!empty($invalid_props)) {
  9469. $validation_failed = true;
  9470. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9471. }
  9472. }
  9473. }
  9474. } else {
  9475. // 如果没有anime_script_id,只检查是否有acts数据
  9476. if (empty($episode_arr['acts'])) {
  9477. $validation_failed = true;
  9478. $validation_error_msg = '未生成分镜剧本相关的内容';
  9479. } else {
  9480. // 校验主体列表:不能为空主体(旁白不算)
  9481. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9482. // 过滤掉"旁白"角色
  9483. $generated_roles = array_filter($generated_roles, function($role) {
  9484. return $role !== '旁白';
  9485. });
  9486. if (empty($generated_roles)) {
  9487. $validation_failed = true;
  9488. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9489. }
  9490. }
  9491. }
  9492. // 重试逻辑
  9493. while ($validation_failed && $retry_count < $max_retries) {
  9494. $retry_count++;
  9495. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  9496. 'reason' => $validation_error_msg,
  9497. 'anime_id' => $anime_id,
  9498. 'episode_number' => $episode_number
  9499. ]);
  9500. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  9501. 'reason' => $validation_error_msg,
  9502. 'anime_id' => $anime_id
  9503. ]);
  9504. // 发送流式重试提示
  9505. yield [
  9506. 'type' => 'retry',
  9507. 'retry_count' => $retry_count,
  9508. 'reason' => $validation_error_msg
  9509. ];
  9510. // 构建重试提示词
  9511. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  9512. if ($anime_script_id) {
  9513. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  9514. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9515. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  9516. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  9517. } else {
  9518. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9519. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  9520. }
  9521. // 添加重试消息到messages
  9522. $messages[] = [
  9523. 'role' => 'assistant',
  9524. 'content' => $fullContent
  9525. ];
  9526. $messages[] = [
  9527. 'role' => 'user',
  9528. 'content' => $retry_prompt
  9529. ];
  9530. // 更新post_data的messages
  9531. $post_data['messages'] = $messages;
  9532. // 重新调用API
  9533. try {
  9534. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9535. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9536. } else if (in_array($model, $this->gpt_text_models)) {
  9537. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9538. } else if (in_array($model, $this->gemini_text_models)) {
  9539. // Gemini 模型使用 Gemini API
  9540. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9541. } else {
  9542. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9543. }
  9544. // 处理流式输出
  9545. $fullContent = '';
  9546. $fullReasoningContent = '';
  9547. foreach ($streamGenerator as $chunk) {
  9548. if (isset($chunk['type'])) {
  9549. if ($chunk['type'] === 'done') {
  9550. $fullContent = $chunk['full_content'];
  9551. $fullReasoningContent = $chunk['full_reasoning'];
  9552. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9553. } else {
  9554. yield $chunk;
  9555. }
  9556. }
  9557. }
  9558. // 重新解析内容
  9559. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9560. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  9561. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  9562. $episode_arr = handleEpisodeContentForAce($fullContent);
  9563. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  9564. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  9565. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  9566. // }
  9567. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  9568. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  9569. // 重新验证
  9570. $validation_failed = false;
  9571. $validation_error_msg = '';
  9572. if ($anime_script_id) {
  9573. if (empty($episode_arr['acts'])) {
  9574. $validation_failed = true;
  9575. $validation_error_msg = '未生成分镜剧本相关的内容';
  9576. } else {
  9577. // 校验主体列表:不能为空主体(旁白不算)
  9578. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9579. // 过滤掉"旁白"角色
  9580. $generated_roles = array_filter($generated_roles, function($role) {
  9581. return $role !== '旁白';
  9582. });
  9583. if (empty($generated_roles)) {
  9584. $validation_failed = true;
  9585. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9586. }
  9587. // 仅当存在强制主体设定时校验主体列表
  9588. if (!$validation_failed && !empty($extra_roles)) {
  9589. $expected_roles = array_keys($extra_roles);
  9590. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9591. if (!empty($invalid_roles)) {
  9592. $validation_failed = true;
  9593. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9594. }
  9595. }
  9596. // 仅当存在强制场景设定时校验场景列表
  9597. if (!$validation_failed && !empty($extra_scenes)) {
  9598. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  9599. $expected_scenes = array_keys($extra_scenes);
  9600. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9601. if (!empty($invalid_scenes)) {
  9602. $validation_failed = true;
  9603. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9604. }
  9605. }
  9606. // 仅当存在强制道具设定时校验道具列表
  9607. if (!$validation_failed && !empty($extra_props)) {
  9608. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9609. $expected_props = array_keys($extra_props);
  9610. $invalid_props = array_diff($generated_props, $expected_props);
  9611. if (!empty($invalid_props)) {
  9612. $validation_failed = true;
  9613. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9614. }
  9615. }
  9616. }
  9617. } else {
  9618. if (empty($episode_arr['acts'])) {
  9619. $validation_failed = true;
  9620. $validation_error_msg = '未生成分镜剧本相关的内容';
  9621. } else {
  9622. // 校验主体列表:不能为空主体(旁白不算)
  9623. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9624. // 过滤掉"旁白"角色
  9625. $generated_roles = array_filter($generated_roles, function($role) {
  9626. return $role !== '旁白';
  9627. });
  9628. if (empty($generated_roles)) {
  9629. $validation_failed = true;
  9630. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9631. }
  9632. }
  9633. }
  9634. } catch (\Exception $e) {
  9635. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  9636. 'trace' => $e->getTraceAsString()
  9637. ]);
  9638. break;
  9639. }
  9640. }
  9641. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  9642. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  9643. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  9644. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  9645. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  9646. if ($validation_failed && $retry_count >= $max_retries) {
  9647. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  9648. 'retry_count' => $retry_count,
  9649. 'last_error' => $validation_error_msg
  9650. ]);
  9651. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  9652. 'error' => $validation_error_msg,
  9653. 'anime_id' => $anime_id
  9654. ]);
  9655. $validation_failed = false;
  9656. $validation_error_msg = '';
  9657. }
  9658. // 如果重试后仍然失败
  9659. if ($validation_failed) {
  9660. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  9661. 'retry_count' => $retry_count,
  9662. 'last_error' => $validation_error_msg
  9663. ]);
  9664. try {
  9665. $now = date('Y-m-d H:i:s');
  9666. $records = [
  9667. [
  9668. 'uid' => $uid,
  9669. 'anime_id' => $anime_id,
  9670. 'sequence' => $episode_number,
  9671. 'role' => 'user',
  9672. 'content' => $prompt,
  9673. 'created_at' => $now,
  9674. 'updated_at' => $now
  9675. ],
  9676. [
  9677. 'uid' => $uid,
  9678. 'anime_id' => $anime_id,
  9679. 'sequence' => $episode_number,
  9680. 'role' => 'assistant',
  9681. 'content' => $fullContent,
  9682. 'created_at' => $now,
  9683. 'updated_at' => $now
  9684. ]
  9685. ];
  9686. DB::table('mp_anime_records')->insert($records);
  9687. } catch (\Exception $e) {
  9688. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9689. }
  9690. yield [
  9691. 'type' => 'done',
  9692. 'episode' => [],
  9693. 'answer' => $fullContent,
  9694. 'reasoning' => $fullReasoningContent,
  9695. 'usage' => $usage,
  9696. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  9697. ];
  9698. return;
  9699. }
  9700. // 验证成功,记录日志
  9701. if ($retry_count > 0) {
  9702. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  9703. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  9704. }
  9705. // 老逻辑
  9706. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  9707. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  9708. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  9709. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  9710. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  9711. $existing_props = is_array($existing_props) ? $existing_props : [];
  9712. $now = date('Y-m-d H:i:s');
  9713. try {
  9714. DB::beginTransaction();
  9715. $saveResult = $this->saveEpisodeVersionData(
  9716. $anime_id,
  9717. $episode_number,
  9718. $episode_arr,
  9719. $existing_roles,
  9720. $existing_scenes,
  9721. $existing_props,
  9722. $current_episode,
  9723. $base_episode,
  9724. $is_regenerate_version,
  9725. $content,
  9726. $now,
  9727. $ref_products
  9728. );
  9729. $episode = $saveResult['episode'];
  9730. $episode_id = $saveResult['episode_id'];
  9731. $merged_roles = $saveResult['merged_roles'];
  9732. $merged_scenes = $saveResult['merged_scenes'];
  9733. $merged_props = $saveResult['merged_props'];
  9734. $record_content = $origin_prompt;
  9735. if ($uploaded_content !== '') {
  9736. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  9737. }
  9738. $records = [
  9739. [
  9740. 'uid' => $uid,
  9741. 'anime_id' => $anime_id,
  9742. 'role' => 'user',
  9743. 'content' => $record_content,
  9744. 'sequence' => $episode_number,
  9745. 'episode_id' => $episode_id,
  9746. 'created_at' => $now,
  9747. 'updated_at' => $now
  9748. ],
  9749. [
  9750. 'uid' => $uid,
  9751. 'anime_id' => $anime_id,
  9752. 'role' => 'assistant',
  9753. 'content' => $fullContent,
  9754. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  9755. 'sequence' => $episode_number,
  9756. 'episode_id' => $episode_id,
  9757. 'created_at' => $now,
  9758. 'updated_at' => $now
  9759. ]
  9760. ];
  9761. $boolen4 = DB::table('mp_anime_records')->insert($records);
  9762. if (!$boolen4) {
  9763. Utils::throwError('20003:对话记录保存失败');
  9764. }
  9765. // 保存模型到anime表
  9766. $update_anime_data = [
  9767. 'model' => $model,
  9768. 'updated_at' => $now
  9769. ];
  9770. if ($uploaded_content) {
  9771. $update_anime_data['content'] = $uploaded_content;
  9772. }
  9773. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  9774. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  9775. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  9776. 'anime_id' => $anime_id,
  9777. 'episode_number' => $episode_number,
  9778. 'model' => $model,
  9779. 'source' => 'chatForAce',
  9780. ]);
  9781. }catch (\Exception $e) {
  9782. DB::rollBack();
  9783. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  9784. yield [
  9785. 'type' => 'done',
  9786. 'answer' => $fullContent,
  9787. 'reasoning' => $fullReasoningContent,
  9788. 'usage' => $usage,
  9789. 'error' => $e->getMessage(),
  9790. ];
  9791. return;
  9792. }
  9793. DB::commit();
  9794. if ($is_global_generate_pics) {
  9795. // // 批量生成全局角色图片
  9796. // $this->batchSetGlobalRoleImg([
  9797. // 'anime_id' => $anime_id,
  9798. // ], true);
  9799. // // 批量生成全局场景图片
  9800. // $this->batchSetGlobalSceneImg([
  9801. // 'anime_id' => $anime_id,
  9802. // ], true);
  9803. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  9804. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  9805. }
  9806. $episode['episode_id'] = $episode_id;
  9807. $episode['roles'] = $merged_roles;
  9808. $episode['scenes'] = $merged_scenes;
  9809. $episode['props'] = $merged_props;
  9810. $episode['end_episode_sequence'] = $end_episode_sequence;
  9811. // 获取mp_animes表中的视频参数
  9812. $episode['video_params'] = [
  9813. 'video_model' => getProp($anime, 'video_model'),
  9814. 'video_resolution' => getProp($anime, 'video_resolution'),
  9815. 'ratio' => getProp($anime, 'video_ratio'),
  9816. ];
  9817. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9818. yield [
  9819. 'type' => 'done',
  9820. 'episode' => $episode,
  9821. 'answer' => $fullContent,
  9822. 'reasoning' => $fullReasoningContent,
  9823. 'usage' => $usage
  9824. ];
  9825. }
  9826. /**
  9827. * chatForAce的非流式版本 - 用于定时任务
  9828. * 只获取最终 type=done 的数据,并验证必要字段
  9829. *
  9830. * @param array $data 请求数据
  9831. * @return array 生成结果
  9832. */
  9833. public function chatForAceNonStream($data) {
  9834. $finalResult = null;
  9835. // 调用流式方法,只保存 type=done 的数据
  9836. foreach ($this->chatForAce($data) as $chunk) {
  9837. // 只关注最终结果
  9838. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  9839. $finalResult = $chunk;
  9840. break; // 找到 done 就退出循环
  9841. }
  9842. }
  9843. // 验证最终结果
  9844. if (!$finalResult) {
  9845. return ['error' => '生成失败:未获取到最终结果'];
  9846. }
  9847. // 检查是否有错误
  9848. if (isset($finalResult['error']) && $finalResult['error']) {
  9849. return $finalResult;
  9850. }
  9851. // 验证必要字段
  9852. $episode = $finalResult['episode'] ?? [];
  9853. // 验证 roles(旁白不算主体,过滤后不能为空)
  9854. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  9855. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  9856. }
  9857. $nonNarratorRoles = array_filter(array_column($episode['roles'], 'role'), function($role) {
  9858. return $role !== '旁白';
  9859. });
  9860. if (empty($nonNarratorRoles)) {
  9861. return ['error' => '生成失败:主体列表(roles)为空或格式错误(旁白不算)'];
  9862. }
  9863. // 验证 scenes
  9864. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  9865. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  9866. }
  9867. // 验证 props(道具可以为空,但必须存在且为数组)
  9868. if (!isset($episode['props']) || !is_array($episode['props'])) {
  9869. $episode['props'] = [];
  9870. }
  9871. // 验证 acts(分镜剧本)
  9872. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  9873. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  9874. }
  9875. // 更新验证后的 episode 数据
  9876. $finalResult['episode'] = $episode;
  9877. // 记录验证成功日志
  9878. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  9879. 'roles_count' => count($episode['roles']),
  9880. 'scenes_count' => count($episode['scenes']),
  9881. 'props_count' => count($episode['props']),
  9882. 'acts_count' => count($episode['acts'])
  9883. ]);
  9884. return $finalResult;
  9885. }
  9886. /**
  9887. * 批量生成多个分集
  9888. *
  9889. * @param array $data 请求数据
  9890. * @return array 任务信息
  9891. */
  9892. public function batchGenerateEpisodes($data) {
  9893. $uid = Site::getUid();
  9894. $cpid = Site::getCpid();
  9895. $anime_id = getProp($data, 'anime_id');
  9896. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  9897. $start_episode_number = getProp($data, 'start_episode_number');
  9898. $end_episode_number = getProp($data, 'end_episode_number');
  9899. if (!$anime_id) {
  9900. Utils::throwError('20003:anime_id参数缺失');
  9901. }
  9902. if ($generate_episode_number < 1) {
  9903. Utils::throwError('20003:生成集数必须大于0');
  9904. }
  9905. // 获取动漫信息
  9906. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9907. if (!$anime) {
  9908. Utils::throwError('20003:该剧集不存在');
  9909. }
  9910. // 检查是否是全能模式
  9911. if ((int)getProp($anime, 'ace_mode') !== 1) {
  9912. Utils::throwError('20003:只有全能模式才支持批量生成');
  9913. }
  9914. // 检查是否是多剧集模式
  9915. if ((int)getProp($anime, 'is_multi') !== 1) {
  9916. Utils::throwError('20003:单剧集不支持批量生成');
  9917. }
  9918. // 指定起始/结束剧集序号时的校验
  9919. $hasSpecifiedRange = ($start_episode_number !== null && $start_episode_number !== '')
  9920. || ($end_episode_number !== null && $end_episode_number !== '');
  9921. if ($hasSpecifiedRange) {
  9922. if ($start_episode_number === null || $start_episode_number === ''
  9923. || $end_episode_number === null || $end_episode_number === '') {
  9924. Utils::throwError('20003:起始剧集序号和结束剧集序号必须同时提供');
  9925. }
  9926. $start_episode_number = (int)$start_episode_number;
  9927. $end_episode_number = (int)$end_episode_number;
  9928. if ($start_episode_number < 1 || $end_episode_number < $start_episode_number) {
  9929. Utils::throwError('20003:剧集序号范围错误,结束剧集序号不能小于起始剧集序号');
  9930. }
  9931. $startEpisodeNumber = $start_episode_number;
  9932. $endEpisodeNumber = $end_episode_number;
  9933. } else {
  9934. // 未指定范围时,以 generate_episode_number 判断要生成的集数,从当前已生成的最大集数的下一集开始
  9935. $currentMaxEpisode = DB::table('mp_anime_episodes')
  9936. ->where('anime_id', $anime_id)
  9937. ->where('is_default', 1)
  9938. ->max('episode_number');
  9939. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  9940. // 确定起始集数
  9941. $startEpisodeNumber = $currentMaxEpisode + 1;
  9942. // 计算结束集数
  9943. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  9944. }
  9945. // 本次实际生成的集数
  9946. $totalEpisodeCount = $endEpisodeNumber - $startEpisodeNumber + 1;
  9947. // 检查是否超过总集数限制
  9948. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  9949. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  9950. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  9951. }
  9952. // 创建任务前验重:批量任务表与剧集表中是否已存在范围内的剧集序号
  9953. $duplicatedBatchEpisodes = DB::table('mp_batch_episode_generation_details')
  9954. ->where('anime_id', $anime_id)
  9955. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  9956. ->pluck('episode_number')
  9957. ->unique()
  9958. ->sort()
  9959. ->values()
  9960. ->toArray();
  9961. $duplicatedAnimeEpisodes = DB::table('mp_anime_episodes')
  9962. ->where('anime_id', $anime_id)
  9963. ->where('is_default', 1)
  9964. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  9965. ->pluck('episode_number')
  9966. ->unique()
  9967. ->sort()
  9968. ->values()
  9969. ->toArray();
  9970. if (!empty($duplicatedBatchEpisodes) || !empty($duplicatedAnimeEpisodes)) {
  9971. $duplicateMessages = [];
  9972. if (!empty($duplicatedBatchEpisodes)) {
  9973. $duplicateMessages[] = '批量生成任务中已存在第' . implode('、', $duplicatedBatchEpisodes) . '集';
  9974. }
  9975. if (!empty($duplicatedAnimeEpisodes)) {
  9976. $duplicateMessages[] = '剧集中已存在第' . implode('、', $duplicatedAnimeEpisodes) . '集';
  9977. }
  9978. Utils::throwError('20003:' . implode(';', $duplicateMessages) . ',请勿重复创建');
  9979. }
  9980. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  9981. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  9982. ->where('anime_id', $anime_id)
  9983. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  9984. ->whereIn('status', ['pending', 'processing', 'completed'])
  9985. ->count();
  9986. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  9987. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  9988. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  9989. if ($needEpisodeCount > 0) {
  9990. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints() * $needEpisodeCount, $uid);
  9991. }
  9992. $now = date('Y-m-d H:i:s');
  9993. $createdTasks = [];
  9994. $skippedTasks = [];
  9995. // 为每一集创建详情记录
  9996. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  9997. // 检查是否已有该集的任务记录
  9998. $existingTask = DB::table('mp_batch_episode_generation_details')
  9999. ->where('anime_id', $anime_id)
  10000. ->where('episode_number', $episodeNumber)
  10001. ->first();
  10002. if ($existingTask) {
  10003. // 如果已存在且未完成,跳过
  10004. if (in_array($existingTask->status, ['pending', 'processing'])) {
  10005. $skippedTasks[] = $episodeNumber;
  10006. continue;
  10007. }
  10008. // 如果是失败状态,可以重新创建(删除旧记录)
  10009. if ($existingTask->status === 'failed') {
  10010. DB::table('mp_batch_episode_generation_details')
  10011. ->where('id', $existingTask->id)
  10012. ->delete();
  10013. }
  10014. // 如果是已完成状态,也跳过
  10015. if ($existingTask->status === 'completed') {
  10016. $skippedTasks[] = $episodeNumber;
  10017. continue;
  10018. }
  10019. }
  10020. // 准备任务数据
  10021. $taskData = [
  10022. 'anime_id' => $anime_id,
  10023. 'uid' => $uid,
  10024. 'cpid' => $cpid,
  10025. 'episode_number' => $episodeNumber,
  10026. 'status' => 'pending',
  10027. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  10028. 'retry_count' => 0,
  10029. 'created_at' => $now,
  10030. 'updated_at' => $now
  10031. ];
  10032. // 创建任务记录
  10033. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  10034. if ($taskId) {
  10035. $createdTasks[] = $episodeNumber;
  10036. }
  10037. }
  10038. if (empty($createdTasks)) {
  10039. if (!empty($skippedTasks)) {
  10040. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  10041. } else {
  10042. Utils::throwError('20003:创建批量生成任务失败');
  10043. }
  10044. }
  10045. // 创建/复用任务中心记录(按入参+type验重,避免重复任务)
  10046. $taskCenterId = $this->createBatchGenerateEpisodesTaskCenter(
  10047. $uid,
  10048. $cpid,
  10049. $anime_id,
  10050. $generate_episode_number,
  10051. $startEpisodeNumber,
  10052. $endEpisodeNumber
  10053. );
  10054. return [
  10055. 'anime_id' => $anime_id,
  10056. 'start_episode' => $startEpisodeNumber,
  10057. 'end_episode' => $endEpisodeNumber,
  10058. 'total_episodes' => $totalEpisodeCount,
  10059. 'created_episodes' => $createdTasks,
  10060. 'skipped_episodes' => $skippedTasks,
  10061. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$totalEpisodeCount}集。" .
  10062. "已创建: " . implode(',', $createdTasks) .
  10063. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : ""),
  10064. 'task_center_id' => $taskCenterId
  10065. ];
  10066. }
  10067. /**
  10068. * 根据入参创建或复用批量生成分集的任务中心记录
  10069. *
  10070. * 以入参(anime_id、generate_episode_number)计算 md5 存入 params_md5 字段用于验重:
  10071. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  10072. * 避免生成重复任务;唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复。
  10073. *
  10074. * @param int|string $uid
  10075. * @param int|string $cpid
  10076. * @param int|string $anime_id
  10077. * @param int $generate_episode_number
  10078. * @param int $startEpisodeNumber
  10079. * @param int $endEpisodeNumber
  10080. * @return int 任务中心ID
  10081. */
  10082. private function createBatchGenerateEpisodesTaskCenter($uid, $cpid, $anime_id, $generate_episode_number, $startEpisodeNumber, $endEpisodeNumber) {
  10083. $params = [
  10084. 'anime_id' => (int)$anime_id,
  10085. 'generate_episode_number' => (int)$generate_episode_number,
  10086. 'start_episode' => (int)$startEpisodeNumber,
  10087. 'end_episode' => (int)$endEpisodeNumber,
  10088. ];
  10089. // 验重键:入参 + 生成范围(anime_id + generate_episode_number + start/end)+ task_type
  10090. $paramsMd5 = md5(json_encode([
  10091. 'anime_id' => (int)$anime_id,
  10092. 'generate_episode_number' => (int)$generate_episode_number,
  10093. 'start_episode' => (int)$startEpisodeNumber,
  10094. 'end_episode' => (int)$endEpisodeNumber,
  10095. ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  10096. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  10097. $existing = DB::table('mp_task_center')
  10098. ->where('uid', (int)$uid)
  10099. ->where('cpid', (int)$cpid)
  10100. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10101. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  10102. ->where('params_md5', $paramsMd5)
  10103. ->orderBy('id', 'desc')
  10104. ->first();
  10105. if ($existing) {
  10106. dLog('deepseek')->info('复用批量生成分集任务中心记录,避免重复任务', [
  10107. 'anime_id' => $anime_id,
  10108. 'task_center_id' => $existing->id,
  10109. 'params_md5' => $paramsMd5,
  10110. ]);
  10111. return (int)$existing->id;
  10112. }
  10113. $now = date('Y-m-d H:i:s');
  10114. DB::table('mp_task_center')->insertOrIgnore([
  10115. 'uid' => (int)$uid,
  10116. 'cpid' => (int)$cpid,
  10117. 'task_type' => MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES,
  10118. 'title' => '批量生成分集',
  10119. 'ref_task_id' => 0,
  10120. 'status' => MpTaskCenter::STATUS_PROCESSING,
  10121. 'result' => null,
  10122. 'error_message' => null,
  10123. 'prompt' => null,
  10124. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  10125. 'params_md5' => $paramsMd5,
  10126. 'created_at' => $now,
  10127. 'updated_at' => $now,
  10128. ]);
  10129. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  10130. $taskId = (int)DB::table('mp_task_center')
  10131. ->where('uid', (int)$uid)
  10132. ->where('cpid', (int)$cpid)
  10133. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10134. ->where('params_md5', $paramsMd5)
  10135. ->orderBy('id', 'desc')
  10136. ->value('id');
  10137. dLog('deepseek')->info('创建批量生成分集任务中心记录', [
  10138. 'anime_id' => $anime_id,
  10139. 'task_center_id' => $taskId,
  10140. 'params_md5' => $paramsMd5,
  10141. ]);
  10142. return $taskId;
  10143. }
  10144. /**
  10145. * 批量生成分集全部结束后,更新任务中心记录的状态和结果
  10146. *
  10147. * 由批量生成 worker 子进程在退出前调用。分集详情任务的状态会在多处更新
  10148. * (completed/failed/pending/processing),这里只在所有详情任务均已结束时
  10149. * 统一汇总更新,避免在每个更新点重复处理。
  10150. *
  10151. * @param int|string $animeId
  10152. * @return int 更新的任务中心记录数
  10153. */
  10154. public function finishBatchGenerateEpisodesTaskCenters($animeId) {
  10155. $animeId = (int)$animeId;
  10156. $updated = 0;
  10157. // 该 anime 是否还有未结束的详情任务
  10158. $hasUnfinished = DB::table('mp_batch_episode_generation_details')
  10159. ->where('anime_id', $animeId)
  10160. ->whereIn('status', ['pending', 'processing'])
  10161. ->exists();
  10162. // 扫描该 anime 相关的未完成任务中心记录
  10163. $tasks = DB::table('mp_task_center')
  10164. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10165. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  10166. ->orderBy('id', 'desc')
  10167. ->limit(500)
  10168. ->get();
  10169. if ($hasUnfinished && !$tasks) {
  10170. return 0;
  10171. }
  10172. foreach ($tasks as $task) {
  10173. try {
  10174. $taskParams = json_decode((string)$task->params, true);
  10175. if (!is_array($taskParams) || (int)($taskParams['anime_id'] ?? 0) !== $animeId) {
  10176. continue;
  10177. }
  10178. $startEpisode = (int)($taskParams['start_episode'] ?? 0);
  10179. $endEpisode = (int)($taskParams['end_episode'] ?? 0);
  10180. if ($startEpisode < 1 || $endEpisode < $startEpisode) {
  10181. continue;
  10182. }
  10183. $details = DB::table('mp_batch_episode_generation_details')
  10184. ->where('anime_id', $animeId)
  10185. ->whereBetween('episode_number', [$startEpisode, $endEpisode])
  10186. ->get();
  10187. // 该批次范围内存在缺失记录,等待下一次检查
  10188. if ($details->isEmpty() || $details->count() < ($endEpisode - $startEpisode + 1)) {
  10189. continue;
  10190. }
  10191. $completedEpisodes = [];
  10192. $failedEpisodes = [];
  10193. $allFinished = true;
  10194. foreach ($details as $detail) {
  10195. if ($detail->status === 'completed') {
  10196. $completedEpisodes[] = $detail->episode_number;
  10197. } elseif ($detail->status === 'failed') {
  10198. $failedEpisodes[] = [
  10199. 'episode_number' => $detail->episode_number,
  10200. 'error_message' => $detail->error_message ?? '',
  10201. ];
  10202. } else {
  10203. // pending/processing(防御处理,正常不会走到)
  10204. $allFinished = false;
  10205. break;
  10206. }
  10207. }
  10208. if (!$allFinished) {
  10209. continue;
  10210. }
  10211. $result = json_encode([
  10212. 'anime_id' => $animeId,
  10213. 'start_episode' => $startEpisode,
  10214. 'end_episode' => $endEpisode,
  10215. 'total_episodes' => count($details),
  10216. 'completed_count' => count($completedEpisodes),
  10217. 'failed_count' => count($failedEpisodes),
  10218. 'completed_episodes' => $completedEpisodes,
  10219. 'failed_episodes' => $failedEpisodes,
  10220. ], JSON_UNESCAPED_UNICODE);
  10221. DB::table('mp_task_center')
  10222. ->where('id', $task->id)
  10223. ->update([
  10224. 'status' => !empty($failedEpisodes) ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  10225. 'result' => $result,
  10226. 'error_message' => !empty($failedEpisodes) ? ('有 ' . count($failedEpisodes) . ' 集生成失败') : null,
  10227. 'updated_at' => date('Y-m-d H:i:s'),
  10228. ]);
  10229. $updated++;
  10230. dLog('command')->info('批量生成分集任务已完成,更新任务中心', [
  10231. 'task_center_id' => $task->id,
  10232. 'anime_id' => $animeId,
  10233. 'start_episode' => $startEpisode,
  10234. 'end_episode' => $endEpisode,
  10235. ]);
  10236. } catch (\Exception $e) {
  10237. dLog('command')->error('更新批量生成分集任务中心异常', [
  10238. 'task_center_id' => $task->id,
  10239. 'anime_id' => $animeId,
  10240. 'error' => $e->getMessage(),
  10241. ]);
  10242. }
  10243. }
  10244. return $updated;
  10245. }
  10246. /**
  10247. * 获取批量生成任务状态
  10248. *
  10249. * @param array $data 请求数据
  10250. * @return array 任务状态信息
  10251. */
  10252. public function getBatchGenerationTaskStatus($data) {
  10253. $anime_id = getProp($data, 'anime_id');
  10254. if (!$anime_id) {
  10255. Utils::throwError('20003:anime_id参数缺失');
  10256. }
  10257. // 获取该anime的所有任务
  10258. $tasks = DB::table('mp_batch_episode_generation_details')
  10259. ->where('anime_id', $anime_id)
  10260. ->orderBy('episode_number')
  10261. ->get()
  10262. ->map(function($item) {
  10263. return [
  10264. 'id' => $item->id,
  10265. 'episode_number' => $item->episode_number,
  10266. 'status' => $item->status,
  10267. 'error_message' => $item->error_message,
  10268. 'retry_count' => $item->retry_count,
  10269. 'created_at' => $item->created_at,
  10270. 'updated_at' => $item->updated_at,
  10271. 'completed_at' => $item->completed_at
  10272. ];
  10273. })
  10274. ->toArray();
  10275. if (empty($tasks)) {
  10276. Utils::throwError('20003:该剧集没有批量生成任务');
  10277. }
  10278. // 统计各状态数量
  10279. $totalCount = count($tasks);
  10280. $pendingCount = 0;
  10281. $processingCount = 0;
  10282. $completedCount = 0;
  10283. $failedCount = 0;
  10284. $failed_episodes = [];
  10285. foreach ($tasks as $task) {
  10286. switch ($task['status']) {
  10287. case 'pending':
  10288. $pendingCount++;
  10289. break;
  10290. case 'processing':
  10291. $processingCount++;
  10292. break;
  10293. case 'completed':
  10294. $completedCount++;
  10295. break;
  10296. case 'failed':
  10297. $failedCount++;
  10298. // 组装失败分集对象(新对象):分集序号、错误原因
  10299. $failed_episodes[] = [
  10300. 'episode_number' => $task['episode_number'],
  10301. 'error_message' => $task['error_message'] ?? ''
  10302. ];
  10303. break;
  10304. }
  10305. }
  10306. // 计算进度百分比
  10307. $progress = 0;
  10308. if ($totalCount > 0) {
  10309. $progress = round(($completedCount / $totalCount) * 100, 2);
  10310. }
  10311. // 判断整体状态
  10312. $overallStatus = 'processing';
  10313. if ($completedCount === $totalCount) {
  10314. $overallStatus = 'completed';
  10315. } elseif ($pendingCount === $totalCount) {
  10316. $overallStatus = 'pending';
  10317. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  10318. $overallStatus = 'failed';
  10319. }
  10320. return [
  10321. 'anime_id' => $anime_id,
  10322. 'total_episodes' => $totalCount,
  10323. 'pending_count' => $pendingCount,
  10324. 'processing_count' => $processingCount,
  10325. 'completed_count' => $completedCount,
  10326. 'failed_count' => $failedCount,
  10327. 'progress' => $progress,
  10328. 'overall_status' => $overallStatus,
  10329. 'failed_episodes' => $failed_episodes,
  10330. 'tasks' => $tasks
  10331. ];
  10332. }
  10333. /**
  10334. * 将生成内容中不在强制列表中的资源合并进强制列表
  10335. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  10336. *
  10337. * @param array $generated 生成内容中的资源列表
  10338. * @param array $forced 强制资源列表(key为资源名称)
  10339. * @param string $type 资源类型:role、scene、prop
  10340. * @return array
  10341. */
  10342. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  10343. {
  10344. foreach ($generated as $item) {
  10345. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  10346. if ($name === null || $name === '') {
  10347. continue;
  10348. }
  10349. if ($name === '旁白') {
  10350. continue;
  10351. }
  10352. if (!isset($forced[$name])) {
  10353. $forced[$name] = $item;
  10354. }
  10355. }
  10356. return $forced;
  10357. }
  10358. /**
  10359. * 智能匹配并替换主体和场景名称
  10360. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  10361. *
  10362. * @param array $episode_arr 解析后的剧集数据
  10363. * @param array $extra_roles 强制主体设定(key为主体名称)
  10364. * @param array $extra_scenes 强制场景设定(key为场景名称)
  10365. * @return array 替换后的剧集数据
  10366. */
  10367. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  10368. $replaced_count = 0;
  10369. // 1. 处理主体列表
  10370. if (!empty($episode_arr['roles'])) {
  10371. foreach ($episode_arr['roles'] as &$role) {
  10372. $generated_role_name = $role['role'] ?? '';
  10373. // 跳过旁白
  10374. if ($generated_role_name === '旁白') {
  10375. continue;
  10376. }
  10377. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  10378. if (!isset($extra_roles[$generated_role_name])) {
  10379. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  10380. if ($matched_role) {
  10381. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  10382. $role['role'] = $matched_role;
  10383. $replaced_count++;
  10384. }
  10385. }
  10386. }
  10387. }
  10388. // 2. 处理场景列表
  10389. if (!empty($episode_arr['scenes'])) {
  10390. foreach ($episode_arr['scenes'] as &$scene) {
  10391. $generated_scene_name = $scene['scene'] ?? '';
  10392. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  10393. if (!isset($extra_scenes[$generated_scene_name])) {
  10394. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  10395. if ($matched_scene) {
  10396. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  10397. $scene['scene'] = $matched_scene;
  10398. $replaced_count++;
  10399. }
  10400. }
  10401. }
  10402. }
  10403. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  10404. if (!empty($episode_arr['acts'])) {
  10405. foreach ($episode_arr['acts'] as &$act) {
  10406. if (!empty($act['segments'])) {
  10407. foreach ($act['segments'] as &$segment) {
  10408. if (!empty($segment['segment_content'])) {
  10409. $original_content = $segment['segment_content'];
  10410. $replaced_content = $original_content;
  10411. // 替换场景名 - 在文本中查找并替换
  10412. foreach (array_keys($extra_scenes) as $full_scene_name) {
  10413. // 尝试找到可能的短名称
  10414. $potential_short_names = [];
  10415. // 提取场景名的主要部分(冒号之前)
  10416. if (mb_strpos($full_scene_name, ':') !== false) {
  10417. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  10418. $potential_short_names[] = $short_name;
  10419. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  10420. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  10421. $potential_short_names[] = $short_name;
  10422. }
  10423. // 替换场景字段中的短名称
  10424. foreach ($potential_short_names as $short_name) {
  10425. if ($short_name !== $full_scene_name) {
  10426. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  10427. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  10428. if ($new_content !== $replaced_content) {
  10429. $replaced_content = $new_content;
  10430. $replaced_count++;
  10431. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  10432. }
  10433. }
  10434. }
  10435. }
  10436. // 替换配音角色名(跳过旁白)
  10437. foreach (array_keys($extra_roles) as $full_role_name) {
  10438. if ($full_role_name === '旁白') {
  10439. continue;
  10440. }
  10441. // 尝试找到可能的短名称
  10442. $potential_short_names = [];
  10443. // 提取角色名的主要部分(短横线之前)
  10444. if (mb_strpos($full_role_name, '-') !== false) {
  10445. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  10446. $potential_short_names[] = $short_name;
  10447. }
  10448. // 替换配音台词中的短名称
  10449. foreach ($potential_short_names as $short_name) {
  10450. if ($short_name !== $full_role_name) {
  10451. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  10452. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  10453. if ($new_content !== $replaced_content) {
  10454. $replaced_content = $new_content;
  10455. $replaced_count++;
  10456. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  10457. }
  10458. }
  10459. }
  10460. }
  10461. // 如果有替换,更新segment_content
  10462. if ($replaced_content !== $original_content) {
  10463. $segment['segment_content'] = $replaced_content;
  10464. }
  10465. }
  10466. }
  10467. }
  10468. }
  10469. }
  10470. if ($replaced_count > 0) {
  10471. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  10472. 'replaced_count' => $replaced_count
  10473. ]);
  10474. }
  10475. return $episode_arr;
  10476. }
  10477. /**
  10478. * 查找匹配的名称
  10479. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  10480. *
  10481. * @param string $generated_name 生成的名称
  10482. * @param array $expected_names 预期的名称列表
  10483. * @return string|null 匹配到的名称,如果没有匹配则返回null
  10484. */
  10485. private function findMatchingName($generated_name, $expected_names) {
  10486. if (empty($generated_name)) {
  10487. return null;
  10488. }
  10489. // 尝试精确匹配
  10490. if (in_array($generated_name, $expected_names)) {
  10491. return $generated_name;
  10492. }
  10493. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  10494. foreach ($expected_names as $expected_name) {
  10495. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  10496. if (mb_strpos($expected_name, $generated_name) === 0) {
  10497. return $expected_name;
  10498. }
  10499. }
  10500. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  10501. // 这样可以处理一些变体,但优先级较低
  10502. foreach ($expected_names as $expected_name) {
  10503. if (mb_strpos($expected_name, $generated_name) !== false) {
  10504. return $expected_name;
  10505. }
  10506. }
  10507. return null;
  10508. }
  10509. /**
  10510. * 重新生成分段剧本
  10511. * @param array $data 包含以下字段:
  10512. * - prompt: string|null 用户修改要求(可选)
  10513. * - template_id: int|null 提示词模板ID(可选)
  10514. * - act_id: int|null 单个片段ID(与episode_id二选一)
  10515. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  10516. * @return array 返回生成结果
  10517. */
  10518. public function regenerateSegmentScript($data) {
  10519. $uid = Site::getUid();
  10520. $prompt = trim((string)getProp($data, 'prompt', ''));
  10521. $template_id = getProp($data, 'template_id', 0);
  10522. $act_id = getProp($data, 'act_id', 0);
  10523. $episode_id = getProp($data, 'episode_id', 0);
  10524. // 验证:prompt和template_id至少提供一个
  10525. if (empty($prompt) && empty($template_id)) {
  10526. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  10527. }
  10528. // 验证:act_id和episode_id二选一
  10529. if (empty($act_id) && empty($episode_id)) {
  10530. Utils::throwError('20003:请提供片段ID或剧集ID');
  10531. }
  10532. if (!empty($act_id) && !empty($episode_id)) {
  10533. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  10534. }
  10535. // 积分余额预检(仅剧集ID模式收费)
  10536. if (!empty($episode_id)) {
  10537. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  10538. }
  10539. // 如果提供了template_id,获取模板提示词
  10540. $template_prompt = '';
  10541. if ($template_id > 0) {
  10542. $template = DB::table('mp_prompt_templates')
  10543. ->where('id', $template_id)
  10544. ->where('is_deleted', 0)
  10545. ->first();
  10546. if (!$template) {
  10547. Utils::throwError('20003:提示词模板不存在或已删除');
  10548. }
  10549. $template_prompt = $template->template_prompt ?? '';
  10550. }
  10551. // 合并用户提示词和模板提示词
  10552. $final_prompt = '';
  10553. if (!empty($template_prompt)) {
  10554. $final_prompt = $template_prompt;
  10555. if (!empty($prompt)) {
  10556. $final_prompt .= "\n\n补充要求:" . $prompt;
  10557. }
  10558. } else {
  10559. $final_prompt = $prompt;
  10560. }
  10561. // 获取需要重新生成的内容参考
  10562. $reference_content = '';
  10563. $target_episode_id = 0;
  10564. $target_anime_id = 0;
  10565. $target_episode_number = 0;
  10566. if ($act_id > 0) {
  10567. // 单个片段模式:获取该片段的内容
  10568. $segment = DB::table('mp_episode_segments')
  10569. ->where('id', $act_id)
  10570. ->first();
  10571. if (!$segment) {
  10572. Utils::throwError('20003:片段不存在');
  10573. }
  10574. $target_episode_id = $segment->episode_id;
  10575. $target_anime_id = $segment->anime_id;
  10576. $target_episode_number = $segment->episode_number;
  10577. $reference_content = $segment->act_content ?? '';
  10578. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  10579. } else {
  10580. // 整个剧集模式:获取所有片段的内容
  10581. $segments = DB::table('mp_episode_segments')
  10582. ->where('episode_id', $episode_id)
  10583. ->orderBy('act_number')
  10584. ->get();
  10585. if ($segments->isEmpty()) {
  10586. Utils::throwError('20003:该剧集没有片段数据');
  10587. }
  10588. $target_episode_id = $episode_id;
  10589. $target_anime_id = $segments[0]->anime_id;
  10590. $target_episode_number = $segments[0]->episode_number;
  10591. // 拼接所有片段内容,保留格式用于AI理解
  10592. $act_contents = [];
  10593. foreach ($segments as $seg) {
  10594. $act_number = $seg->act_number;
  10595. $act_content = $seg->act_content ?? '';
  10596. if (!empty($act_content)) {
  10597. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  10598. }
  10599. }
  10600. $reference_content = implode("\n\n", $act_contents);
  10601. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  10602. if ($episode_content) {
  10603. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  10604. }else {
  10605. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  10606. }
  10607. }
  10608. if (empty($reference_content)) {
  10609. Utils::throwError('20003:没有可参考的片段内容');
  10610. }
  10611. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  10612. $episode = DB::table('mp_anime_episodes')
  10613. ->where('id', $target_episode_id)
  10614. ->first();
  10615. if (!$episode) {
  10616. Utils::throwError('20003:剧集不存在');
  10617. }
  10618. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  10619. $anime_script_id = getProp($anime, 'script_id');
  10620. $intro = $episode->intro ?? '';
  10621. $art_style = $episode->art_style ?? '';
  10622. $roles = json_decode($episode->roles ?? '[]', true);
  10623. $scenes = json_decode($episode->scenes ?? '[]', true);
  10624. $props = json_decode($episode->props ?? '[]', true);
  10625. // 构建提示词中的主体列表和场景列表参考
  10626. $roles_ref = '';
  10627. if (!empty($roles) && is_array($roles)) {
  10628. $roles_list = [];
  10629. foreach ($roles as $role) {
  10630. $role_name = getProp($role, 'role', '');
  10631. $role_desc = getProp($role, 'description', '');
  10632. $pic_prompt = getProp($role, 'pic_prompt', '');
  10633. $voice_prompt = getProp($role, 'voice_prompt', '');
  10634. if (!empty($role_name)) {
  10635. $role_line = $role_name;
  10636. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  10637. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  10638. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  10639. $roles_list[] = $role_line;
  10640. }
  10641. }
  10642. if (!empty($roles_list)) {
  10643. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  10644. }
  10645. }
  10646. $scenes_ref = '';
  10647. if (!empty($scenes) && is_array($scenes)) {
  10648. $scenes_list = [];
  10649. foreach ($scenes as $scene) {
  10650. $scene_name = getProp($scene, 'scene', '');
  10651. $scene_desc = getProp($scene, 'description', '');
  10652. $pic_prompt = getProp($scene, 'pic_prompt', '');
  10653. if (!empty($scene_name)) {
  10654. $scene_line = $scene_name;
  10655. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  10656. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  10657. $scenes_list[] = $scene_line;
  10658. }
  10659. }
  10660. if (!empty($scenes_list)) {
  10661. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  10662. }
  10663. }
  10664. $props_ref = '';
  10665. if (!empty($props) && is_array($props)) {
  10666. $props_list = [];
  10667. foreach ($props as $prop) {
  10668. $prop_name = getProp($prop, 'prop', '');
  10669. $prop_desc = getProp($prop, 'description', '');
  10670. $pic_prompt = getProp($prop, 'pic_prompt', '');
  10671. if (!empty($prop_name)) {
  10672. $prop_line = $prop_name;
  10673. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  10674. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  10675. $props_list[] = $prop_line;
  10676. }
  10677. }
  10678. if (!empty($props_list)) {
  10679. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  10680. }
  10681. }
  10682. // 构建美术风格参考
  10683. $art_style_ref = '';
  10684. if (!empty($art_style)) {
  10685. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  10686. }
  10687. // 构建内容简介参考
  10688. $intro_ref = '';
  10689. if (!empty($intro)) {
  10690. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  10691. }
  10692. // 构建完整的AI提示词
  10693. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  10694. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  10695. $user_prompt .= $intro_ref;
  10696. $user_prompt .= $art_style_ref;
  10697. $user_prompt .= $reference_content;
  10698. // $user_prompt .= $roles_ref;
  10699. // $user_prompt .= $scenes_ref;
  10700. $system_prompt = "\n\n【强制要求】\n";
  10701. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  10702. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  10703. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  10704. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  10705. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  10706. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  10707. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  10708. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  10709. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  10710. ###分段剧本
  10711. 片段数量:8
  10712. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10713. ##片段1
  10714. 时长:12s
  10715. 分镜1
  10716. 出场角色:刀疤脸
  10717. 场景:边境小镇街道
  10718. 出场道具:酒杯-高脚杯
  10719. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10720. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10721. 配音台词:
  10722. 背景音效:
  10723. 分镜2
  10724. 出场角色:刀疤脸
  10725. 场景:悦来酒馆
  10726. 出场道具:酒杯-高脚杯
  10727. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10728. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10729. 配音台词:
  10730. 背景音效:
  10731. 分镜3
  10732. 出场角色:刀疤脸
  10733. 场景:悦来酒馆
  10734. 出场道具:酒杯-高脚杯
  10735. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10736. 运镜:从中景推向令牌特写。
  10737. 配音台词:
  10738. 背景音效:
  10739. 分镜4
  10740. 出场角色:刀疤脸
  10741. 场景:悦来酒馆
  10742. 出场道具:酒杯-高脚杯
  10743. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10744. 运镜:极速推向酒水溅起的瞬间。
  10745. 配音台词:
  10746. 背景音效:
  10747. 分镜5
  10748. 出场角色:刀疤脸
  10749. 场景:悦来酒馆
  10750. 出场道具:酒杯-高脚杯
  10751. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10752. 运镜:固定机位,利用倾斜构图制造压迫感。
  10753. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10754. 背景音效:";
  10755. // 获取模型配置
  10756. $model = getProp($data, 'model');
  10757. if (!$model) {
  10758. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  10759. }
  10760. // 验证模型是否在可用模型表中
  10761. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10762. $model = 'deepseek-v4-pro';
  10763. }
  10764. // 模型兼容性处理
  10765. $thinkingMode = 'disabled';
  10766. $reasoningEffort = 'high';
  10767. if ($model === 'deepseek-chat') {
  10768. $model = 'deepseek-v4-flash';
  10769. $thinkingMode = 'disabled';
  10770. } elseif ($model === 'deepseek-reasoner') {
  10771. $model = 'deepseek-v4-flash';
  10772. $thinkingMode = 'enabled';
  10773. }
  10774. // 构建消息
  10775. $messages = [
  10776. [
  10777. 'role' => 'system',
  10778. 'content' => $system_prompt
  10779. ],
  10780. [
  10781. 'role' => 'user',
  10782. 'content' => $user_prompt
  10783. ]
  10784. ];
  10785. // dd($messages);
  10786. // 构建请求参数
  10787. $post_data = [
  10788. 'model' => $model,
  10789. 'messages' => $messages,
  10790. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  10791. 'frequency_penalty' => 0,
  10792. 'presence_penalty' => 0,
  10793. 'response_format' => ['type' => 'text'],
  10794. 'thinking' => ['type' => $thinkingMode],
  10795. 'stream' => false // 非流式输出
  10796. ];
  10797. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  10798. // 调用AI生成新的分段剧本
  10799. try {
  10800. $fullContent = '';
  10801. $usage = [];
  10802. // 根据模型类型选择调用方法
  10803. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10804. // DeepSeek 官方模型使用 DeepSeek API
  10805. $chatResult = $this->chatOnly($post_data);
  10806. } else if (in_array($model, $this->gpt_text_models)) {
  10807. // GPT 模型使用 TokenRouter API
  10808. $chatResult = $this->gpt54ChatOnly($post_data);
  10809. } else {
  10810. // 其他模型使用火山引擎API
  10811. $chatResult = $this->volcEngineChatCompletion($post_data);
  10812. }
  10813. if (is_array($chatResult)) {
  10814. $fullContent = $chatResult['fullContent'] ?? '';
  10815. $usage = $chatResult['usage'] ?? [];
  10816. }
  10817. $generated_content = $fullContent;
  10818. if (empty($generated_content)) {
  10819. Utils::throwError('20003:AI生成内容为空,请重试');
  10820. }
  10821. // 解析生成的内容 - 按片段分割
  10822. $parsed_segments = [];
  10823. // 先在开头添加换行符,确保第1片段也能被正确分割
  10824. $normalizedText = "\n" . $generated_content;
  10825. $parts = preg_split('/\n\s*##/', $normalizedText);
  10826. foreach ($parts as $part) {
  10827. $part = trim($part);
  10828. if (empty($part)) continue;
  10829. // 匹配"片段X"格式
  10830. if (!preg_match('/^片段\d+/', $part)) {
  10831. continue;
  10832. }
  10833. // 分离标题和内容
  10834. $lines = explode("\n", $part, 2);
  10835. $actTitle = trim($lines[0]);
  10836. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  10837. // 解析标题,提取序号
  10838. $actNumber = 0;
  10839. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  10840. $actNumber = intval($segmentTitleMatch[1]);
  10841. } else {
  10842. $actNumber = count($parsed_segments) + 1;
  10843. }
  10844. // 提取时长(仅保留数字)
  10845. $actDuration = 0;
  10846. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  10847. $actDurationStr = trim($actDurationMatch[1]);
  10848. // 提取数字部分(支持整数和小数)
  10849. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  10850. $actDuration = (float)$numMatch[1];
  10851. }
  10852. }
  10853. // 清理act_content:去除时长、旁白音色等非分镜内容行
  10854. // 只保留分镜内容,并确保分镜标记使用【】格式
  10855. $cleaned_content = '';
  10856. $content_lines = explode("\n", $actContent);
  10857. $is_capturing = false; // 标记是否开始捕获分镜内容
  10858. $count = 0;
  10859. foreach ($content_lines as $line) {
  10860. $trimmed_line = trim($line);
  10861. // 跳过时长和旁白音色行
  10862. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  10863. continue;
  10864. }
  10865. // 检测是否是分镜开始
  10866. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  10867. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  10868. $count++;
  10869. $is_capturing = true;
  10870. // 如果没有【】,则添加
  10871. if (!preg_match('/^【/u', $trimmed_line)) {
  10872. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  10873. }
  10874. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  10875. }
  10876. // 如果已经开始捕获,则添加该行
  10877. if ($is_capturing && !empty($trimmed_line)) {
  10878. $cleaned_content .= $trimmed_line."\n";
  10879. }
  10880. }
  10881. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  10882. $parsed_segments[] = [
  10883. 'act_number' => $actNumber,
  10884. 'act_title' => $actTitle,
  10885. 'act_duration' => $actDuration,
  10886. 'act_content' => $cleaned_content,
  10887. ];
  10888. }
  10889. if (empty($parsed_segments)) {
  10890. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  10891. }
  10892. // 收集所有资产名称(角色、场景、道具)
  10893. $product_names = [];
  10894. // 收集角色名称
  10895. if (!empty($roles) && is_array($roles)) {
  10896. foreach ($roles as $role) {
  10897. $role_name = getProp($role, 'role', '');
  10898. if (!empty($role_name)) {
  10899. $product_names[] = $role_name;
  10900. }
  10901. }
  10902. }
  10903. // 收集场景名称
  10904. if (!empty($scenes) && is_array($scenes)) {
  10905. foreach ($scenes as $scene) {
  10906. $scene_name = getProp($scene, 'scene', '');
  10907. if (!empty($scene_name)) {
  10908. $product_names[] = $scene_name;
  10909. }
  10910. }
  10911. }
  10912. // 收集道具名称
  10913. if (!empty($props) && is_array($props)) {
  10914. foreach ($props as $prop) {
  10915. $prop_name = getProp($prop, 'prop', '');
  10916. if (!empty($prop_name)) {
  10917. $product_names[] = $prop_name;
  10918. }
  10919. }
  10920. }
  10921. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  10922. $product_names = array_unique($product_names);
  10923. usort($product_names, function($a, $b) {
  10924. return mb_strlen($b) - mb_strlen($a);
  10925. });
  10926. // 处理每个片段的 act_show_content
  10927. foreach ($parsed_segments as &$segment) {
  10928. $act_content = getProp($segment, 'act_content', '');
  10929. if (empty($act_content)) {
  10930. $segment['act_show_content'] = '';
  10931. continue;
  10932. }
  10933. $processed_content = $act_content;
  10934. // 统一替换所有资产名称为 {资产名} 格式
  10935. // 使用占位符避免嵌套替换问题
  10936. $placeholder_map = [];
  10937. $placeholder_index = 0;
  10938. foreach ($product_names as $product_name) {
  10939. // 转义特殊字符
  10940. $escaped_product = preg_quote($product_name, '/');
  10941. // 检查是否匹配且未被 {} 包裹
  10942. $processed_content = preg_replace_callback(
  10943. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  10944. function($matches) use (&$placeholder_map, &$placeholder_index) {
  10945. // 使用唯一占位符
  10946. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  10947. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  10948. $placeholder_index++;
  10949. return $placeholder;
  10950. },
  10951. $processed_content
  10952. );
  10953. }
  10954. // 将所有占位符替换回实际内容
  10955. foreach ($placeholder_map as $placeholder => $replacement) {
  10956. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  10957. }
  10958. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  10959. $shot_counter = 0;
  10960. $processed_content = preg_replace_callback(
  10961. '/【(?:镜头|分镜)(\d+)】/u',
  10962. function($matches) use (&$shot_counter) {
  10963. $shot_counter++;
  10964. return '【镜头' . $shot_counter . '】';
  10965. },
  10966. $processed_content
  10967. );
  10968. $segment['act_show_content'] = $processed_content;
  10969. }
  10970. unset($segment); // 解除引用
  10971. // 保存到数据库
  10972. $now = date('Y-m-d H:i:s');
  10973. $saved_acts = []; // 用于记录保存后的片段信息
  10974. if ($act_id > 0) {
  10975. // 单个片段模式:更新单条记录
  10976. if (count($parsed_segments) > 0) {
  10977. $new_segment = $parsed_segments[0];
  10978. $update_data = [
  10979. 'act_content' => getProp($new_segment, 'act_content', ''),
  10980. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  10981. 'act_title' => getProp($new_segment, 'act_title', ''),
  10982. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  10983. 'updated_at' => $now,
  10984. ];
  10985. DB::table('mp_episode_segments')
  10986. ->where('id', $act_id)
  10987. ->update($update_data);
  10988. // 获取更新后的记录
  10989. $updated_act = DB::table('mp_episode_segments')
  10990. ->where('id', $act_id)
  10991. ->first();
  10992. if ($updated_act) {
  10993. $saved_acts[] = [
  10994. 'act_id' => $updated_act->id,
  10995. 'act_number' => $updated_act->act_number,
  10996. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  10997. 'act_content' => $updated_act->act_content,
  10998. 'act_show_content' => $updated_act->act_show_content,
  10999. 'video_url' => $updated_act->video_url ?? '',
  11000. 'video_duration' => $updated_act->video_duration ?? 0,
  11001. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  11002. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  11003. ];
  11004. }
  11005. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  11006. }
  11007. } else {
  11008. // 整个剧集模式:删除原有记录并批量保存新记录
  11009. DB::beginTransaction();
  11010. try {
  11011. // 删除原有的所有片段记录
  11012. DB::table('mp_episode_segments')
  11013. ->where('episode_id', $target_episode_id)
  11014. ->delete();
  11015. // 批量插入新的片段记录
  11016. $segments_to_insert = [];
  11017. foreach ($parsed_segments as $index => $segment) {
  11018. $act_number = $index + 1;
  11019. $segments_to_insert[] = [
  11020. 'anime_id' => $target_anime_id,
  11021. 'episode_id' => $target_episode_id,
  11022. 'episode_number' => $target_episode_number,
  11023. 'act_number' => $act_number,
  11024. 'act_title' => getProp($segment, 'act_title', ''),
  11025. 'act_duration' => getProp($segment, 'act_duration', 0),
  11026. 'act_content' => getProp($segment, 'act_content', ''),
  11027. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  11028. 'created_at' => $now,
  11029. 'updated_at' => $now,
  11030. ];
  11031. }
  11032. if (!empty($segments_to_insert)) {
  11033. DB::table('mp_episode_segments')->insert($segments_to_insert);
  11034. }
  11035. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  11036. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  11037. 'anime_id' => $target_anime_id,
  11038. 'episode_id' => $target_episode_id,
  11039. 'model' => $model,
  11040. 'source' => 'regenerateSegmentScript',
  11041. ]);
  11042. DB::commit();
  11043. // 查询保存后的所有片段记录
  11044. $saved_segments = DB::table('mp_episode_segments')
  11045. ->where('episode_id', $target_episode_id)
  11046. ->orderBy('act_number')
  11047. ->get();
  11048. foreach ($saved_segments as $saved_segment) {
  11049. $saved_acts[] = [
  11050. 'act_id' => $saved_segment->id,
  11051. 'act_number' => $saved_segment->act_number,
  11052. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  11053. 'act_content' => $saved_segment->act_content,
  11054. 'act_show_content' => $saved_segment->act_show_content,
  11055. 'video_url' => $saved_segment->video_url ?? '',
  11056. 'video_duration' => $saved_segment->video_duration ?? 0,
  11057. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  11058. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  11059. ];
  11060. }
  11061. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  11062. 'episode_id' => $target_episode_id,
  11063. 'segments_count' => count($segments_to_insert)
  11064. ]);
  11065. } catch (\Exception $e) {
  11066. DB::rollBack();
  11067. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  11068. Utils::throwError('20003:保存失败,请重试');
  11069. }
  11070. }
  11071. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  11072. return [
  11073. 'anime_id' => $target_anime_id,
  11074. 'episode_id' => $target_episode_id,
  11075. 'title' => getProp($episode, 'title', ''),
  11076. 'episode_number' => $target_episode_number,
  11077. 'is_generated' => getProp($episode, 'is_generated', 0),
  11078. 'acts' => $saved_acts,
  11079. ];
  11080. } catch (\Exception $e) {
  11081. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  11082. throw $e;
  11083. }
  11084. }
  11085. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  11086. {
  11087. $episode_arr = [
  11088. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  11089. 'intro' => getProp($script_arr, 'intro'),
  11090. 'art_style' => getProp($script_arr, 'art_style'),
  11091. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  11092. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  11093. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  11094. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  11095. ];
  11096. if (empty($episode_arr['acts'])) {
  11097. $fallback_episode_arr = handleEpisodeContent($fullContent);
  11098. if (!empty($fallback_episode_arr['acts'])) {
  11099. $episode_arr = array_merge($fallback_episode_arr, [
  11100. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  11101. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  11102. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  11103. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  11104. ]);
  11105. }
  11106. }
  11107. // if (!getProp($episode_arr, 'episode_title')) {
  11108. // $episode_title = '';
  11109. // $episodes = getProp($script_arr, 'episodes', []);
  11110. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  11111. // $episode_title = '第1集:' . $episodes[0]['title'];
  11112. // }
  11113. // if (!$episode_title) {
  11114. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  11115. // }
  11116. // $episode_arr['episode_title'] = $episode_title;
  11117. // }
  11118. return $episode_arr;
  11119. }
  11120. private function saveEpisodeVersionData(
  11121. int $anime_id,
  11122. int $episode_number,
  11123. array $episode_arr,
  11124. array $existing_roles,
  11125. array $existing_scenes,
  11126. array $existing_props,
  11127. $current_episode,
  11128. $base_episode,
  11129. bool $is_regenerate_version,
  11130. string $content,
  11131. string $now,
  11132. array $ref_products = []
  11133. ): array {
  11134. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  11135. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  11136. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  11137. // 过滤掉关键字段为空的条目
  11138. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  11139. return !empty($item['role'] ?? null);
  11140. }));
  11141. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  11142. return !empty($item['scene'] ?? null);
  11143. }));
  11144. $merged_props = array_values(array_filter($generated_props, function ($item) {
  11145. return !empty($item['prop'] ?? null);
  11146. }));
  11147. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  11148. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  11149. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  11150. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  11151. $ace_mode = getProp($anime, 'ace_mode');
  11152. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  11153. $global_roles = json_decode(getProp($anime, 'roles'), true);
  11154. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  11155. $global_roles = is_array($global_roles) ? $global_roles : [];
  11156. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  11157. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  11158. $art_style_type = getProp($anime, 'art_style_type');
  11159. // 检查并创建 roles 的图片生成任务
  11160. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  11161. // 检查并创建 scenes 的图片生成任务
  11162. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  11163. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  11164. if ($arr && is_array($arr)) {
  11165. $merged_roles = $arr['roles'];
  11166. $merged_scenes = $arr['scenes'];
  11167. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  11168. }
  11169. // 确保数据是数组类型
  11170. if (!is_array($merged_roles)) {
  11171. dLog('deepseek')->error('merged_roles不是数组类型', [
  11172. 'type' => gettype($merged_roles),
  11173. 'value' => $merged_roles
  11174. ]);
  11175. $merged_roles = [];
  11176. }
  11177. if (!is_array($merged_scenes)) {
  11178. dLog('deepseek')->error('merged_scenes不是数组类型', [
  11179. 'type' => gettype($merged_scenes),
  11180. 'value' => $merged_scenes
  11181. ]);
  11182. $merged_scenes = [];
  11183. }
  11184. if (!is_array($merged_props)) {
  11185. dLog('deepseek')->error('merged_props不是数组类型', [
  11186. 'type' => gettype($merged_props),
  11187. 'value' => $merged_props
  11188. ]);
  11189. $merged_props = [];
  11190. }
  11191. // 同步新出现的主体和场景到全局
  11192. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  11193. $role_arr = [];
  11194. foreach ($merged_roles as $item) {
  11195. $role_arr[$item['role']] = $item;
  11196. }
  11197. $version_count = DB::table('mp_anime_episodes')
  11198. ->where('anime_id', $anime_id)
  11199. ->where('episode_number', $episode_number)
  11200. ->count('id');
  11201. $episode = [
  11202. 'anime_id' => $anime_id,
  11203. 'episode_number' => $episode_number,
  11204. 'title' => getProp($episode_arr, 'episode_title'),
  11205. 'content' => $content,
  11206. 'intro' => getProp($episode_arr, 'intro'),
  11207. 'art_style' => getProp($episode_arr, 'art_style'),
  11208. 'roles' => json_encode($merged_roles, 256),
  11209. 'scenes' => json_encode($merged_scenes, 256),
  11210. 'props' => json_encode($merged_props, 256),
  11211. 'generate_status' => '待执行',
  11212. 'generate_at' => $now,
  11213. 'is_default' => 1,
  11214. 'updated_at' => $now,
  11215. ];
  11216. $del_flag = false;
  11217. if ($is_regenerate_version) {
  11218. DB::table('mp_anime_episodes')
  11219. ->where('anime_id', $anime_id)
  11220. ->where('episode_number', $episode_number)
  11221. ->update(['is_default' => 0, 'updated_at' => $now]);
  11222. $episode['sequence'] = $version_count + 1;
  11223. $episode['created_at'] = $now;
  11224. $episode['cpid'] = Site::getCpid();
  11225. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  11226. if (!$episode_id) {
  11227. Utils::throwError('20003:创建剧集版本失败');
  11228. }
  11229. } else {
  11230. $target_episode = $current_episode ?: $base_episode;
  11231. if ($target_episode) {
  11232. $episode_id = getProp($target_episode, 'id');
  11233. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  11234. DB::table('mp_anime_episodes')
  11235. ->where('anime_id', $anime_id)
  11236. ->where('episode_number', $episode_number)
  11237. ->where('id', '<>', $episode_id)
  11238. ->update(['is_default' => 0, 'updated_at' => $now]);
  11239. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  11240. if ($boolen === false) {
  11241. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  11242. Utils::throwError('20003:分集内容保存失败');
  11243. }
  11244. $del_flag = true;
  11245. } else {
  11246. DB::table('mp_anime_episodes')
  11247. ->where('anime_id', $anime_id)
  11248. ->where('episode_number', $episode_number)
  11249. ->update(['is_default' => 0, 'updated_at' => $now]);
  11250. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  11251. $episode['created_at'] = $now;
  11252. $episode['cpid'] = Site::getCpid();
  11253. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  11254. if (!$episode_id) {
  11255. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  11256. Utils::throwError('20003:分集内容保存失败');
  11257. }
  11258. }
  11259. }
  11260. $segments = [];
  11261. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  11262. // 如果是第2集及以后,获取上一集的主体音色数据
  11263. $previous_roles_voice = [];
  11264. if ($episode_number >= 2) {
  11265. $previous_episode = DB::table('mp_anime_episodes')
  11266. ->where('anime_id', $anime_id)
  11267. ->where('episode_number', $episode_number - 1)
  11268. ->where('is_default', 1)
  11269. ->first();
  11270. if ($previous_episode) {
  11271. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  11272. if (is_array($previous_roles)) {
  11273. foreach ($previous_roles as $prev_role) {
  11274. $role_name = getProp($prev_role, 'role');
  11275. if ($role_name) {
  11276. $previous_roles_voice[$role_name] = [
  11277. 'voice_name' => getProp($prev_role, 'voice_name'),
  11278. 'voice_type' => getProp($prev_role, 'voice_type'),
  11279. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  11280. ];
  11281. $voice_prompt = getProp($prev_role, 'voice_prompt');
  11282. if ($voice_prompt) {
  11283. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  11284. }
  11285. }
  11286. }
  11287. }
  11288. }
  11289. }
  11290. // 将继承的音色数据同步到当前集的主体列表
  11291. if (!empty($previous_roles_voice)) {
  11292. foreach ($merged_roles as &$role) {
  11293. $role_name = getProp($role, 'role');
  11294. if ($role_name && isset($previous_roles_voice[$role_name])) {
  11295. // 强制继承上一集的音色数据
  11296. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  11297. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  11298. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  11299. // 如果上一集有 voice_prompt 则继承,否则跳过
  11300. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  11301. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  11302. }
  11303. }
  11304. }
  11305. unset($role); // 解除引用
  11306. // 更新 role_arr 以便后续使用
  11307. $role_arr = [];
  11308. foreach ($merged_roles as $item) {
  11309. $role_arr[$item['role']] = $item;
  11310. }
  11311. }
  11312. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  11313. $emotion_list = array_flip($emotion_list);
  11314. foreach ($acts as $act) {
  11315. $act_segments = getProp($act, 'segments', []);
  11316. if (!is_array($act_segments)) {
  11317. continue;
  11318. }
  11319. if ((int)$ace_mode === 1) {
  11320. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  11321. $merged_parts = [];
  11322. foreach ($act_segments as $seg) {
  11323. $seg_num = getProp($seg, 'segment_number');
  11324. $seg_content = getProp($seg, 'segment_content');
  11325. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  11326. }
  11327. $act_content = implode("\n", $merged_parts);
  11328. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  11329. $segments[] = [
  11330. 'anime_id' => $anime_id,
  11331. 'episode_id' => $episode_id,
  11332. 'episode_number' => $episode_number,
  11333. 'act_number' => getProp($act, 'act_number'),
  11334. 'act_title' => getProp($act, 'act_title'),
  11335. 'act_duration' => getProp($act, 'act_duration'),
  11336. 'act_content' => $act_content,
  11337. 'created_at' => $now,
  11338. 'updated_at' => $now
  11339. ];
  11340. } else {
  11341. foreach ($act_segments as $segment) {
  11342. $voice_actor = getProp($segment, 'voice_actor');
  11343. // 优先从上一集继承音色数据
  11344. $timbre_info = [];
  11345. if (isset($previous_roles_voice[$voice_actor])) {
  11346. // 从上一集继承音色数据
  11347. $timbre_info = $previous_roles_voice[$voice_actor];
  11348. } elseif (isset($role_arr[$voice_actor])) {
  11349. // 使用当前集的主体音色数据
  11350. $timbre_info = $role_arr[$voice_actor];
  11351. }
  11352. $voice_type = getProp($timbre_info, 'voice_type');
  11353. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  11354. if ($timbre_emotion) {
  11355. $timbre_emotion = explode(',', $timbre_emotion);
  11356. } else {
  11357. $timbre_emotion = [];
  11358. }
  11359. $emotion = getProp($segment, 'emotion', '中性');
  11360. if (!in_array($emotion, $timbre_emotion)) {
  11361. $emotion = '中性';
  11362. }
  11363. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  11364. $segments[] = [
  11365. 'anime_id' => $anime_id,
  11366. 'episode_id' => $episode_id,
  11367. 'episode_number' => $episode_number,
  11368. 'act_number' => getProp($act, 'act_number'),
  11369. 'act_title' => getProp($act, 'act_title'),
  11370. 'act_duration' => getProp($act, 'act_duration'),
  11371. 'segment_id' => getProp($segment, 'segment_id'),
  11372. 'segment_number' => getProp($segment, 'segment_number'),
  11373. 'segment_content' => getProp($segment, 'segment_content'),
  11374. 'description' => getProp($segment, 'description'),
  11375. 'composition' => getProp($segment, 'composition'),
  11376. 'camera_movement' => getProp($segment, 'camera_movement'),
  11377. 'voice_actor' => $voice_actor,
  11378. 'dialogue' => getProp($segment, 'dialogue'),
  11379. 'frame_type' => getProp($segment, 'frame_type'),
  11380. 'scene' => getProp($segment, 'scene'),
  11381. 'characters' => getProp($segment, 'characters'),
  11382. 'tail_frame' => getProp($segment, 'tail_frame'),
  11383. 'voice_name' => getProp($timbre_info, 'voice_name'),
  11384. 'voice_type' => $voice_type,
  11385. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  11386. 'emotion' => $emotion,
  11387. 'emotion_type' => $emotion_type,
  11388. 'gender' => getProp($segment, 'gender', '0'),
  11389. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  11390. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  11391. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  11392. 'pitch' => getProp($segment, 'pitch', 0),
  11393. 'created_at' => $now,
  11394. 'updated_at' => $now
  11395. ];
  11396. }
  11397. }
  11398. }
  11399. if ($segments) {
  11400. if ($del_flag) {
  11401. DB::table('mp_episode_segments')
  11402. ->where('anime_id', $anime_id)
  11403. ->where('episode_id', $episode_id)
  11404. ->delete();
  11405. }
  11406. $boolen = DB::table('mp_episode_segments')->insert($segments);
  11407. if (!$boolen) {
  11408. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  11409. Utils::throwError('20003:分镜内容保存失败');
  11410. }
  11411. }
  11412. dLog('deepseek')->info('segments', $segments);
  11413. // ace_mode=1: acts 返回值按合并格式调整
  11414. if ((int)$ace_mode === 1) {
  11415. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  11416. $act_map = [];
  11417. foreach ($table_act_data as $item) {
  11418. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  11419. }
  11420. $restructured_acts = [];
  11421. foreach ($acts as $act) {
  11422. $act_segments = getProp($act, 'segments', []);
  11423. if (!is_array($act_segments)) {
  11424. continue;
  11425. }
  11426. $merged_parts = [];
  11427. foreach ($act_segments as $seg) {
  11428. $seg_num = getProp($seg, 'segment_number');
  11429. $seg_content = getProp($seg, 'segment_content');
  11430. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  11431. }
  11432. $act_content = implode("\n", $merged_parts);
  11433. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  11434. $restructured_acts[] = [
  11435. 'anime_id' => $anime_id,
  11436. 'episode_id' => $episode_id,
  11437. 'episode_number' => $episode_number,
  11438. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  11439. 'act_number' => getProp($act, 'act_number'),
  11440. 'act_title' => getProp($act, 'act_title'),
  11441. 'act_duration' => getProp($act, 'act_duration'),
  11442. 'act_content' => $act_content,
  11443. 'created_at' => $now,
  11444. 'updated_at' => $now,
  11445. ];
  11446. }
  11447. $acts = $restructured_acts;
  11448. }
  11449. $episode['episode_id'] = $episode_id;
  11450. $episode['roles'] = $merged_roles;
  11451. $episode['scenes'] = $merged_scenes;
  11452. $episode['props'] = $merged_props;
  11453. $episode['acts'] = $acts;
  11454. return [
  11455. 'episode' => $episode,
  11456. 'episode_id' => $episode_id,
  11457. 'merged_roles' => $merged_roles,
  11458. 'merged_scenes' => $merged_scenes,
  11459. 'merged_props' => $merged_props,
  11460. ];
  11461. }
  11462. private function buildEpisodeItemContent(array $items, string $nameKey): string
  11463. {
  11464. $content = '';
  11465. foreach ($items as $item) {
  11466. $name = trim((string)getProp($item, $nameKey));
  11467. if ($name === '' || $name === '旁白') {
  11468. continue;
  11469. }
  11470. $description = trim((string)getProp($item, 'description'));
  11471. $content .= $name . ': ' . $description;
  11472. if ($nameKey == 'role') {
  11473. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  11474. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11475. $voice_name = trim(getProp($item, 'voice_name'));
  11476. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  11477. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  11478. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  11479. }else {
  11480. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  11481. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11482. }
  11483. $content .= "\n";
  11484. }
  11485. return trim($content);
  11486. }
  11487. private function getEpisodeChatContent($animeId, $sequence, $content) {
  11488. if ((int)$sequence <= 0) {
  11489. return [];
  11490. }
  11491. $origin_content = '';
  11492. if ($content) {
  11493. $origin_content = '本集剧情内容:'.$content;
  11494. }else {
  11495. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  11496. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  11497. }
  11498. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  11499. // 获取分集信息
  11500. $episode = DB::table('mp_anime_episodes')
  11501. ->where('anime_id', $animeId)
  11502. ->where('episode_number', $sequence)
  11503. ->where('is_default', 1)
  11504. ->first();
  11505. if (!$episode) {
  11506. return [];
  11507. }
  11508. $episode_id = getProp($episode, 'id');
  11509. $episode_number = getProp($episode, 'episode_number');
  11510. $title = getProp($episode, 'title');
  11511. $intro = getProp($episode, 'intro');
  11512. $art_style = getProp($episode, 'art_style');
  11513. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  11514. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  11515. // 组装纯文本内容
  11516. $content = '';
  11517. // 添加分集标题和梗概
  11518. $content .= "###第{$episode_number}集:{$title}\n\n";
  11519. $content .= "###故事梗概\n";
  11520. $content .= trim($intro) . "\n\n";
  11521. // 添加美术风格
  11522. $content .= "###美术风格\n";
  11523. $content .= trim($art_style) . "\n\n";
  11524. // 添加主体列表
  11525. $content .= "###主体列表\n";
  11526. $pangbai_voice_prompt = "";
  11527. foreach ($roles as $role) {
  11528. $name = getProp($role, 'role');
  11529. $description = getProp($role, 'description');
  11530. $pic_prompt = getProp($role, 'pic_prompt');
  11531. $voice_prompt = getProp($role, 'voice_prompt');
  11532. $voice_name = getProp($role, 'voice_name');
  11533. $content .= "{$name}: {$description}";
  11534. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11535. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  11536. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  11537. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  11538. $content .= "\n";
  11539. }
  11540. $content .= "\n";
  11541. // 添加场景列表
  11542. $content .= "###场景列表\n";
  11543. foreach ($scenes as $scene) {
  11544. $name = getProp($scene, 'scene');
  11545. $description = getProp($scene, 'description');
  11546. $pic_prompt = getProp($scene, 'pic_prompt');
  11547. $content .= "{$name}: {$description}";
  11548. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11549. $content .= "\n";
  11550. }
  11551. $content .= "\n";
  11552. // 获取分镜信息
  11553. $segments = DB::table('mp_episode_segments')
  11554. ->where('anime_id', $animeId)
  11555. ->where('episode_id', $episode_id)
  11556. ->orderBy('segment_number')
  11557. ->get();
  11558. if ($segments && count($segments) > 0) {
  11559. if ((int)$ace_mode === 1) {
  11560. $content .= "###分段剧本\n";
  11561. // 获取片段数量
  11562. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  11563. $content .= "片段数量:{$act_count}\n";
  11564. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  11565. $content .= "\n";
  11566. }else {
  11567. $content .= "###分镜剧本\n";
  11568. }
  11569. // 按幕分组
  11570. $currentAct = null;
  11571. foreach ($segments as $segment) {
  11572. $act_number = getProp($segment, 'act_number');
  11573. $act_title = getProp($segment, 'act_title');
  11574. $act_duration = getProp($segment, 'act_duration');
  11575. $segment_number = getProp($segment, 'segment_number');
  11576. $segment_content = getProp($segment, 'segment_content');
  11577. $scene_description = getProp($segment, 'scene_description');
  11578. $scene_name = getProp($segment, 'scene_name');
  11579. $composition = getProp($segment, 'composition');
  11580. $camera_movement = getProp($segment, 'camera_movement');
  11581. $voice_type = getProp($segment, 'voice_type');
  11582. $characters = getProp($segment, 'characters');
  11583. $dialogue = getProp($segment, 'dialogue');
  11584. $frame_type = getProp($segment, 'frame_type');
  11585. $tail_frame_description = getProp($segment, 'tail_frame_description');
  11586. // 判断是否是全能模式
  11587. if ((int)$ace_mode === 1) { // 全能模式
  11588. // 如果是新的分段,添加分段标题
  11589. if ($act_number !== $currentAct) {
  11590. $currentAct = $act_number;
  11591. $content .= "##{$act_title}\n";
  11592. $content .= "时长:{$act_duration}s\n";
  11593. }
  11594. }else {
  11595. // 如果是新的幕,添加幕标题
  11596. if ($act_number !== $currentAct) {
  11597. $currentAct = $act_number;
  11598. $content .= "##第{$act_number}幕:{$scene_name}\n";
  11599. }
  11600. }
  11601. // 添加分镜信息
  11602. $content .= "分镜{$segment_number}\n";
  11603. $content .= "分镜内容:\n{$segment_content}\n";
  11604. // $content .= "画面描述:{$scene_description}\n";
  11605. // $content .= "场景:{$scene_name}\n";
  11606. // $content .= "构图设计:{$composition}\n";
  11607. // $content .= "运镜调度:{$camera_movement}\n";
  11608. // if (!empty($voice_type)) {
  11609. // $content .= "配音角色:{$voice_type}\n";
  11610. // }
  11611. // if (!empty($characters)) {
  11612. // $content .= "出镜角色:{$characters}\n";
  11613. // }
  11614. // if (!empty($dialogue)) {
  11615. // $content .= "台词内容:\"{$dialogue}\"\n";
  11616. // }
  11617. // $content .= "画面类型:{$frame_type}\n";
  11618. // $content .= "尾帧描述:{$tail_frame_description}\n";
  11619. $content .= "\n";
  11620. }
  11621. }
  11622. $content = trim($content);
  11623. if($content) $content = "上集剧本内容:\n{$content}";
  11624. return [
  11625. [
  11626. 'role' => 'user',
  11627. 'content' => $origin_content
  11628. ],
  11629. [
  11630. 'role' => 'assistant',
  11631. 'content' => $content
  11632. ]
  11633. ];
  11634. }
  11635. private function getEpisodeChatMessages($animeId, $sequence): array
  11636. {
  11637. if ((int)$sequence <= 0) {
  11638. return [];
  11639. }
  11640. return DB::table('mp_anime_records')
  11641. ->where('anime_id', $animeId)
  11642. ->where('sequence', $sequence)
  11643. ->where('episode_id', '>', 0)
  11644. ->select('role', 'content')
  11645. ->orderBy('created_at')
  11646. ->orderBy('id')
  11647. ->get()
  11648. ->map(function ($value) {
  11649. return (array)$value;
  11650. })
  11651. ->toArray();
  11652. }
  11653. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  11654. {
  11655. $existingMap = [];
  11656. foreach ($existingItems as $item) {
  11657. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  11658. if ($itemKey === '') {
  11659. continue;
  11660. }
  11661. $existingMap[$itemKey] = $item;
  11662. }
  11663. if (!$generatedItems) {
  11664. return array_values($existingItems);
  11665. }
  11666. $merged = [];
  11667. foreach ($generatedItems as $item) {
  11668. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  11669. if ($itemKey === '') {
  11670. continue;
  11671. }
  11672. if (isset($existingMap[$itemKey])) {
  11673. if (trim((string)getProp($item, 'description')) === '') {
  11674. $merged[] = $existingMap[$itemKey];
  11675. continue;
  11676. }
  11677. // 检查内容是否发生变化
  11678. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  11679. if (!$isChanged) {
  11680. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  11681. $mergedItem = [
  11682. $nameKey => trim((string)getProp($item, $nameKey)),
  11683. 'description' => trim((string)getProp($item, 'description')),
  11684. ];
  11685. // 如果有 pic_prompt,添加到合并项中
  11686. $picPrompt = getProp($item, 'pic_prompt');
  11687. if (!empty($picPrompt)) {
  11688. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  11689. }
  11690. // 继承现有项的 URL
  11691. $existingUrl = getProp($existingMap[$itemKey], 'url');
  11692. if (!empty($existingUrl)) {
  11693. $mergedItem['url'] = $existingUrl;
  11694. }
  11695. // 继承现有项的 task_id
  11696. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  11697. if (!empty($existingTaskId)) {
  11698. $mergedItem['task_id'] = $existingTaskId;
  11699. }
  11700. // 继承现有项的 task_status
  11701. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  11702. if (!empty($existingTaskStatus)) {
  11703. $mergedItem['task_status'] = $existingTaskStatus;
  11704. }
  11705. // 保留生成项的音色字段
  11706. $voiceName = getProp($item, 'voice_name');
  11707. if (!empty($voiceName)) {
  11708. $mergedItem['voice_name'] = $voiceName;
  11709. }
  11710. $voiceType = getProp($item, 'voice_type');
  11711. if (!empty($voiceType)) {
  11712. $mergedItem['voice_type'] = $voiceType;
  11713. }
  11714. $audioUrl = getProp($item, 'voice_audio_url');
  11715. if (!empty($audioUrl)) {
  11716. $mergedItem['voice_audio_url'] = $audioUrl;
  11717. }
  11718. $merged[] = $mergedItem;
  11719. } else {
  11720. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  11721. $mergedItem = [
  11722. $nameKey => trim((string)getProp($item, $nameKey)),
  11723. 'description' => trim((string)getProp($item, 'description')),
  11724. ];
  11725. // 如果有 pic_prompt,添加到合并项中
  11726. $picPrompt = getProp($item, 'pic_prompt');
  11727. if (!empty($picPrompt)) {
  11728. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  11729. }
  11730. // 保留生成项的音色字段
  11731. $voiceName = getProp($item, 'voice_name');
  11732. if (!empty($voiceName)) {
  11733. $mergedItem['voice_name'] = $voiceName;
  11734. }
  11735. $voiceType = getProp($item, 'voice_type');
  11736. if (!empty($voiceType)) {
  11737. $mergedItem['voice_type'] = $voiceType;
  11738. }
  11739. $audioUrl = getProp($item, 'voice_audio_url');
  11740. if (!empty($audioUrl)) {
  11741. $mergedItem['voice_audio_url'] = $audioUrl;
  11742. }
  11743. // 不继承 URL、task_id 和 task_status(重置状态)
  11744. $merged[] = $mergedItem;
  11745. }
  11746. } else {
  11747. // 新增项,保留生成项的所有字段
  11748. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  11749. }
  11750. }
  11751. return $merged ?: array_values($existingItems);
  11752. }
  11753. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  11754. {
  11755. $resetItem = [
  11756. $nameKey => trim((string)getProp($item, $nameKey)),
  11757. 'description' => trim((string)getProp($item, 'description')),
  11758. ];
  11759. // 保留指定的字段
  11760. foreach ($preserveFields as $field) {
  11761. $value = getProp($item, $field);
  11762. if (!empty($value)) {
  11763. $resetItem[$field] = $value;
  11764. }
  11765. }
  11766. return $resetItem;
  11767. }
  11768. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  11769. {
  11770. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  11771. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  11772. if ($existingKey !== $generatedKey) {
  11773. return true;
  11774. }
  11775. // 比较 description 是否变化
  11776. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  11777. return true;
  11778. }
  11779. // 比较 pic_prompt 是否变化
  11780. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  11781. }
  11782. private function normalizeEpisodeResourceKey($value): string
  11783. {
  11784. $value = trim((string)$value);
  11785. if ($value === '') {
  11786. return '';
  11787. }
  11788. return strtolower((string)preg_replace('/\s+/u', '', $value));
  11789. }
  11790. // 生成全局角色图片
  11791. private function batchSetGlobalRoleImg($data, $is_force=false) {
  11792. $anime_id = getProp($data, 'anime_id');
  11793. if (!$anime_id) Utils::throwError('1002:请选择对话');
  11794. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11795. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11796. $art_style = getProp($anime, 'art_style');
  11797. $update_flag = false;
  11798. foreach ($roles as &$role) {
  11799. $role_name = getProp($role, 'role');
  11800. if ($role_name == '旁白') continue;
  11801. // 优先使用 pic_prompt,如果没有则使用 description
  11802. $pic_prompt = getProp($role, 'pic_prompt');
  11803. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  11804. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  11805. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  11806. // 参考图地址
  11807. $ref_img_url = getProp($role, 'url');
  11808. if (!$is_force && $ref_img_url) continue;
  11809. $update_flag = true;
  11810. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  11811. try {
  11812. $params = [
  11813. 'prompt' => $description,
  11814. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  11815. 'ref_img_urls' => []
  11816. ];
  11817. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11818. $task_id = $task->id;
  11819. if (!$task_id) {
  11820. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  11821. }
  11822. $role['task_id'] = $task_id;
  11823. $role['task_status'] = 'processing';
  11824. } catch (\Exception $e) {
  11825. Utils::throwError("20003:" . $e->getMessage());
  11826. }
  11827. }
  11828. if (!$update_flag) return true;
  11829. // 保存角色信息
  11830. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  11831. 'roles' => json_encode($roles, 256),
  11832. 'generate_status' => '执行中',
  11833. 'generate_at' => date('Y-m-d H:i:s'),
  11834. 'updated_at' => date('Y-m-d H:i:s')
  11835. ]);
  11836. if (!$boolen) {
  11837. Utils::throwError('20003:保存角色信息失败');
  11838. }
  11839. return $boolen;
  11840. }
  11841. // 生成全局场景图片
  11842. private function batchSetGlobalSceneImg($data, $is_force=false) {
  11843. $anime_id = getProp($data, 'anime_id');
  11844. if (!$anime_id) Utils::throwError('1002:请选择对话');
  11845. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11846. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11847. $art_style = getProp($anime, 'art_style');
  11848. $update_flag = false;
  11849. foreach ($scenes as &$scene) {
  11850. $scene_name = getProp($scene, 'scene');
  11851. // 优先使用 pic_prompt,如果没有则使用 description
  11852. $pic_prompt = getProp($scene, 'pic_prompt');
  11853. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  11854. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  11855. // 参考图地址
  11856. $ref_img_url = getProp($scene, 'url');
  11857. if (!$is_force && $ref_img_url) continue;
  11858. $update_flag = true;
  11859. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  11860. try {
  11861. $params = [
  11862. 'prompt' => $description,
  11863. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  11864. 'ref_img_urls' => []
  11865. ];
  11866. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11867. $task_id = $task->id;
  11868. if (!$task_id) {
  11869. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  11870. }
  11871. $scene['task_id'] = $task_id;
  11872. $scene['task_status'] = 'processing';
  11873. } catch (\Exception $e) {
  11874. Utils::throwError("20003:" . $e->getMessage());
  11875. }
  11876. }
  11877. if (!$update_flag) return true;
  11878. // 保存角色信息
  11879. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  11880. 'scenes' => json_encode($scenes, 256),
  11881. 'generate_status' => '执行中',
  11882. 'generate_at' => date('Y-m-d H:i:s'),
  11883. 'updated_at' => date('Y-m-d H:i:s')
  11884. ]);
  11885. if (!$boolen) {
  11886. Utils::throwError('20003:保存角色信息失败');
  11887. }
  11888. return $boolen;
  11889. }
  11890. // 生成分镜主体、场景和道具图片
  11891. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  11892. $character_prefix = '';
  11893. $scene_prefix = '';
  11894. $prop_prefix = '';
  11895. if ($art_style_type) {
  11896. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  11897. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  11898. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  11899. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  11900. }
  11901. $update_flag = false;
  11902. // 获取上一集的roles、scenes和props数据
  11903. $prev_roles = [];
  11904. $prev_scenes = [];
  11905. $prev_props = [];
  11906. if ($episode_number > 1) {
  11907. $prev_episode = DB::table('mp_anime_episodes')
  11908. ->where('anime_id', $anime_id)
  11909. ->where('episode_number', $episode_number - 1)
  11910. ->where('is_default', 1)
  11911. ->first();
  11912. if ($prev_episode) {
  11913. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  11914. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  11915. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  11916. dLog('deepseek')->info("获取上一集数据成功", [
  11917. 'anime_id' => $anime_id,
  11918. 'prev_episode_number' => $episode_number - 1,
  11919. 'prev_roles_count' => count($prev_roles),
  11920. 'prev_scenes_count' => count($prev_scenes),
  11921. 'prev_props_count' => count($prev_props)
  11922. ]);
  11923. }
  11924. }
  11925. // 处理角色图片生成
  11926. foreach ($roles as &$role) {
  11927. $role_name = getProp($role, 'role');
  11928. if ($role_name == '旁白') continue;
  11929. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  11930. if (isset($ref_products[$role_name])) {
  11931. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  11932. if ($role['url']) continue;
  11933. }
  11934. $role_description = getProp($role, 'description');
  11935. $role_pic_prompt = getProp($role, 'pic_prompt');
  11936. $role_url = getProp($role, 'url');
  11937. // 检查是否可以从上一集继承
  11938. $inherited = false;
  11939. if (!$is_force && !empty($prev_roles)) {
  11940. foreach ($prev_roles as $prev_role) {
  11941. $prev_role_name = getProp($prev_role, 'role');
  11942. $prev_description = getProp($prev_role, 'description');
  11943. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  11944. $prev_url = getProp($prev_role, 'url');
  11945. $prev_task_id = getProp($prev_role, 'task_id');
  11946. $prev_task_status = getProp($prev_role, 'task_status');
  11947. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  11948. if ($role_name == $prev_role_name
  11949. && $role_description == $prev_description
  11950. && $role_pic_prompt == $prev_pic_prompt
  11951. && !empty($prev_url)) {
  11952. $role['task_id'] = $prev_task_id;
  11953. $role['task_status'] = $prev_task_status;
  11954. $role['url'] = $prev_url;
  11955. $inherited = true;
  11956. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  11957. 'anime_id' => $anime_id,
  11958. 'episode_number' => $episode_number,
  11959. 'task_id' => $prev_task_id,
  11960. 'url' => $prev_url
  11961. ]);
  11962. break;
  11963. }
  11964. }
  11965. }
  11966. // 如果已继承或已有url,跳过生成
  11967. if ($inherited || (!$is_force && $role_url)) {
  11968. continue;
  11969. }
  11970. // 优先使用 pic_prompt,如果没有则使用 description
  11971. $pic_prompt = getProp($role, 'pic_prompt');
  11972. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  11973. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11974. $update_flag = true;
  11975. // 调用AIImageGenerationService的生成图片任务接口
  11976. try {
  11977. $params = [
  11978. 'prompt' => $description,
  11979. 'ref_img_urls' => []
  11980. ];
  11981. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11982. $task_id = $task->id;
  11983. if (!$task_id) {
  11984. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  11985. continue; // 不中断,继续处理其他角色
  11986. }
  11987. $role['task_id'] = $task_id;
  11988. $role['task_status'] = 'processing';
  11989. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  11990. 'anime_id' => $anime_id,
  11991. 'episode_number' => $episode_number,
  11992. 'task_id' => $task_id
  11993. ]);
  11994. } catch (\Exception $e) {
  11995. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  11996. // 不抛出异常,继续处理其他角色
  11997. }
  11998. }
  11999. // 处理场景图片生成
  12000. foreach ($scenes as &$scene) {
  12001. $scene_name = getProp($scene, 'scene');
  12002. $scene_description = getProp($scene, 'description');
  12003. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  12004. $scene_url = getProp($scene, 'url');
  12005. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  12006. if (isset($ref_products[$scene_name])) {
  12007. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  12008. if ($scene['url']) continue;
  12009. }
  12010. // 检查是否可以从上一集继承
  12011. $inherited = false;
  12012. if (!$is_force && !empty($prev_scenes)) {
  12013. foreach ($prev_scenes as $prev_scene) {
  12014. $prev_scene_name = getProp($prev_scene, 'scene');
  12015. $prev_description = getProp($prev_scene, 'description');
  12016. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  12017. $prev_url = getProp($prev_scene, 'url');
  12018. $prev_task_id = getProp($prev_scene, 'task_id');
  12019. $prev_task_status = getProp($prev_scene, 'task_status');
  12020. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  12021. if ($scene_name == $prev_scene_name
  12022. && $scene_description == $prev_description
  12023. && $scene_pic_prompt == $prev_pic_prompt
  12024. && !empty($prev_url)) {
  12025. $scene['task_id'] = $prev_task_id;
  12026. $scene['task_status'] = $prev_task_status;
  12027. $scene['url'] = $prev_url;
  12028. $inherited = true;
  12029. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  12030. 'anime_id' => $anime_id,
  12031. 'episode_number' => $episode_number,
  12032. 'task_id' => $prev_task_id,
  12033. 'url' => $prev_url
  12034. ]);
  12035. break;
  12036. }
  12037. }
  12038. }
  12039. // 如果已继承或已有url,跳过生成
  12040. if ($inherited || (!$is_force && $scene_url)) {
  12041. continue;
  12042. }
  12043. // 优先使用 pic_prompt,如果没有则使用 description
  12044. $pic_prompt = getProp($scene, 'pic_prompt');
  12045. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  12046. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  12047. $update_flag = true;
  12048. // 调用AIImageGenerationService的生成图片任务接口
  12049. try {
  12050. $params = [
  12051. 'prompt' => $description,
  12052. 'ref_img_urls' => []
  12053. ];
  12054. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12055. $task_id = $task->id;
  12056. if (!$task_id) {
  12057. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  12058. continue; // 不中断,继续处理其他场景
  12059. }
  12060. $scene['task_id'] = $task_id;
  12061. $scene['task_status'] = 'processing';
  12062. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  12063. 'anime_id' => $anime_id,
  12064. 'episode_number' => $episode_number,
  12065. 'task_id' => $task_id
  12066. ]);
  12067. } catch (\Exception $e) {
  12068. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  12069. // 不抛出异常,继续处理其他场景
  12070. }
  12071. }
  12072. // 处理道具图片生成(逻辑与场景一致)
  12073. foreach ($props as &$prop) {
  12074. $prop_name = getProp($prop, 'prop');
  12075. $prop_description = getProp($prop, 'description');
  12076. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  12077. $prop_url = getProp($prop, 'url');
  12078. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  12079. if (isset($ref_products[$prop_name])) {
  12080. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  12081. if ($prop['url']) continue;
  12082. }
  12083. // 检查是否可以从上一集继承
  12084. $inherited = false;
  12085. if (!$is_force && !empty($prev_props)) {
  12086. foreach ($prev_props as $prev_prop) {
  12087. $prev_prop_name = getProp($prev_prop, 'prop');
  12088. $prev_description = getProp($prev_prop, 'description');
  12089. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  12090. $prev_url = getProp($prev_prop, 'url');
  12091. $prev_task_id = getProp($prev_prop, 'task_id');
  12092. $prev_task_status = getProp($prev_prop, 'task_status');
  12093. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  12094. if ($prop_name == $prev_prop_name
  12095. && $prop_description == $prev_description
  12096. && $prop_pic_prompt == $prev_pic_prompt
  12097. && !empty($prev_url)) {
  12098. $prop['task_id'] = $prev_task_id;
  12099. $prop['task_status'] = $prev_task_status;
  12100. $prop['url'] = $prev_url;
  12101. $inherited = true;
  12102. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  12103. 'anime_id' => $anime_id,
  12104. 'episode_number' => $episode_number,
  12105. 'task_id' => $prev_task_id,
  12106. 'url' => $prev_url
  12107. ]);
  12108. break;
  12109. }
  12110. }
  12111. }
  12112. // 如果已继承或已有url,跳过生成
  12113. if ($inherited || (!$is_force && $prop_url)) {
  12114. continue;
  12115. }
  12116. // 优先使用 pic_prompt,如果没有则使用 description
  12117. $pic_prompt = getProp($prop, 'pic_prompt');
  12118. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  12119. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  12120. $update_flag = true;
  12121. // 调用AIImageGenerationService的生成图片任务接口
  12122. try {
  12123. $params = [
  12124. 'prompt' => $description,
  12125. 'ref_img_urls' => []
  12126. ];
  12127. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12128. $task_id = $task->id;
  12129. if (!$task_id) {
  12130. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  12131. continue; // 不中断,继续处理其他道具
  12132. }
  12133. $prop['task_id'] = $task_id;
  12134. $prop['task_status'] = 'processing';
  12135. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  12136. 'anime_id' => $anime_id,
  12137. 'episode_number' => $episode_number,
  12138. 'task_id' => $task_id
  12139. ]);
  12140. } catch (\Exception $e) {
  12141. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  12142. // 不抛出异常,继续处理其他道具
  12143. }
  12144. }
  12145. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  12146. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  12147. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  12148. // // 保存剧集的角色和场景信息
  12149. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  12150. // 'roles' => json_encode($roles, 256),
  12151. // 'scenes' => json_encode($scenes, 256),
  12152. // 'generate_status' => '执行中',
  12153. // 'generate_at' => date('Y-m-d H:i:s'),
  12154. // 'updated_at' => date('Y-m-d H:i:s')
  12155. // ]);
  12156. // if (!$boolen) {
  12157. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  12158. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  12159. // }
  12160. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  12161. // 'episode_id' => $episode_id,
  12162. 'roles_count' => count($roles),
  12163. 'scenes_count' => count($scenes),
  12164. 'props_count' => count($props)
  12165. ]);
  12166. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  12167. }
  12168. /**
  12169. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  12170. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  12171. *
  12172. * @param int $anime_id 动漫对话ID
  12173. * @param array $episode_roles 剧集角色数据
  12174. * @param array $episode_scenes 剧集场景数据
  12175. * @param array $episode_props 剧集道具数据
  12176. * @return bool
  12177. */
  12178. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  12179. // 获取全局数据
  12180. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12181. if (!$anime) {
  12182. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  12183. return false;
  12184. }
  12185. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  12186. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  12187. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  12188. $roles_added = false;
  12189. $roles_updated = false;
  12190. $scenes_added = false;
  12191. $props_added = false;
  12192. // 处理角色同步
  12193. foreach ($episode_roles as $episode_role) {
  12194. $episode_role_name = getProp($episode_role, 'role');
  12195. $episode_description = getProp($episode_role, 'description');
  12196. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  12197. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  12198. // 跳过旁白
  12199. if ($episode_role_name == '旁白') {
  12200. continue;
  12201. }
  12202. // 检查全局中是否已存在相同的角色
  12203. $exists = false;
  12204. $global_role_index = -1;
  12205. foreach ($global_roles as $index => $global_role) {
  12206. $global_role_name = getProp($global_role, 'role');
  12207. $global_description = getProp($global_role, 'description');
  12208. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  12209. // 如果role、description、pic_prompt三项都一致,则认为已存在
  12210. if ($episode_role_name == $global_role_name
  12211. && $episode_description == $global_description
  12212. && $episode_pic_prompt == $global_pic_prompt) {
  12213. $exists = true;
  12214. $global_role_index = $index;
  12215. break;
  12216. }
  12217. }
  12218. // 如果不存在,则添加到全局
  12219. if (!$exists) {
  12220. $global_roles[] = $episode_role;
  12221. $roles_added = true;
  12222. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  12223. 'anime_id' => $anime_id,
  12224. 'role' => $episode_role_name
  12225. ]);
  12226. } else {
  12227. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  12228. if (!empty($episode_voice_prompt)) {
  12229. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  12230. // 如果全局没有voice_prompt或与剧集不一致,则更新
  12231. if ($global_voice_prompt !== $episode_voice_prompt) {
  12232. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  12233. $roles_updated = true;
  12234. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  12235. 'anime_id' => $anime_id,
  12236. 'role' => $episode_role_name,
  12237. 'voice_prompt' => $episode_voice_prompt
  12238. ]);
  12239. }
  12240. }
  12241. }
  12242. }
  12243. // 处理场景同步
  12244. foreach ($episode_scenes as $episode_scene) {
  12245. $episode_scene_name = getProp($episode_scene, 'scene');
  12246. $episode_description = getProp($episode_scene, 'description');
  12247. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  12248. // 检查全局中是否已存在相同的场景
  12249. $exists = false;
  12250. foreach ($global_scenes as $global_scene) {
  12251. $global_scene_name = getProp($global_scene, 'scene');
  12252. $global_description = getProp($global_scene, 'description');
  12253. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  12254. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  12255. if ($episode_scene_name == $global_scene_name
  12256. && $episode_description == $global_description
  12257. && $episode_pic_prompt == $global_pic_prompt) {
  12258. $exists = true;
  12259. break;
  12260. }
  12261. }
  12262. // 如果不存在,则添加到全局
  12263. if (!$exists) {
  12264. $global_scenes[] = $episode_scene;
  12265. $scenes_added = true;
  12266. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  12267. 'anime_id' => $anime_id,
  12268. 'scene' => $episode_scene_name
  12269. ]);
  12270. }
  12271. }
  12272. // 处理道具同步(逻辑与场景一致)
  12273. foreach ($episode_props as $episode_prop) {
  12274. $episode_prop_name = getProp($episode_prop, 'prop');
  12275. $episode_description = getProp($episode_prop, 'description');
  12276. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  12277. // 检查全局中是否已存在相同的道具
  12278. $exists = false;
  12279. foreach ($global_props as $global_prop) {
  12280. $global_prop_name = getProp($global_prop, 'prop');
  12281. $global_description = getProp($global_prop, 'description');
  12282. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  12283. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  12284. if ($episode_prop_name == $global_prop_name
  12285. && $episode_description == $global_description
  12286. && $episode_pic_prompt == $global_pic_prompt) {
  12287. $exists = true;
  12288. break;
  12289. }
  12290. }
  12291. // 如果不存在,则添加到全局
  12292. if (!$exists) {
  12293. $global_props[] = $episode_prop;
  12294. $props_added = true;
  12295. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  12296. 'anime_id' => $anime_id,
  12297. 'prop' => $episode_prop_name
  12298. ]);
  12299. }
  12300. }
  12301. // 如果有新增或更新,则更新全局数据
  12302. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  12303. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  12304. if ($roles_added || $roles_updated) {
  12305. $update_data['roles'] = json_encode($global_roles, 256);
  12306. }
  12307. if ($scenes_added) {
  12308. $update_data['scenes'] = json_encode($global_scenes, 256);
  12309. }
  12310. if ($props_added) {
  12311. $update_data['props'] = json_encode($global_props, 256);
  12312. }
  12313. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  12314. dLog('deepseek')->info('剧集数据同步到全局完成', [
  12315. 'anime_id' => $anime_id,
  12316. 'roles_added' => $roles_added,
  12317. 'roles_updated' => $roles_updated,
  12318. 'scenes_added' => $scenes_added,
  12319. 'props_added' => $props_added,
  12320. 'global_roles_count' => count($global_roles),
  12321. 'global_scenes_count' => count($global_scenes),
  12322. 'global_props_count' => count($global_props)
  12323. ]);
  12324. }
  12325. return true;
  12326. }
  12327. /**
  12328. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  12329. *
  12330. * @param int $anime_id 动漫对话ID
  12331. * @param int $episode_id 分集ID
  12332. * @return bool
  12333. */
  12334. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  12335. // 获取全局角色和场景数据
  12336. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12337. if (!$anime) {
  12338. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  12339. return false;
  12340. }
  12341. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  12342. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  12343. // 获取指定的分集
  12344. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  12345. if (!$episode) {
  12346. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  12347. return false;
  12348. }
  12349. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  12350. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  12351. $roles_updated = false;
  12352. $scenes_updated = false;
  12353. // 继承角色的task_id、task_status和url
  12354. foreach ($episode_roles as &$episode_role) {
  12355. $episode_role_name = getProp($episode_role, 'role');
  12356. $episode_description = getProp($episode_role, 'description');
  12357. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  12358. $episode_url = getProp($episode_role, 'url');
  12359. // 跳过旁白角色
  12360. if ($episode_role_name == '旁白') {
  12361. continue;
  12362. }
  12363. // 如果剧集中已有URL,跳过
  12364. if (!empty($episode_url)) {
  12365. continue;
  12366. }
  12367. // 遍历全局角色数据,查找匹配的角色
  12368. foreach ($global_roles as $global_role) {
  12369. $global_role_name = getProp($global_role, 'role');
  12370. $global_description = getProp($global_role, 'description');
  12371. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  12372. $global_url = getProp($global_role, 'url');
  12373. $global_task_id = getProp($global_role, 'task_id');
  12374. $global_task_status = getProp($global_role, 'task_status');
  12375. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  12376. if ($episode_role_name == $global_role_name
  12377. && $episode_description == $global_description
  12378. && $episode_pic_prompt == $global_pic_prompt) {
  12379. // 继承 task_id、task_status 和 url
  12380. if (!empty($global_task_id)) {
  12381. $episode_role['task_id'] = $global_task_id;
  12382. $episode_role['task_status'] = $global_task_status;
  12383. $roles_updated = true;
  12384. dLog('deepseek')->info('剧集角色继承全局task_id', [
  12385. 'episode_id' => $episode_id,
  12386. 'role' => $episode_role_name,
  12387. 'task_id' => $global_task_id,
  12388. 'task_status' => $global_task_status
  12389. ]);
  12390. }
  12391. if (!empty($global_url)) {
  12392. $episode_role['url'] = $global_url;
  12393. $roles_updated = true;
  12394. dLog('deepseek')->info('剧集角色继承全局url', [
  12395. 'episode_id' => $episode_id,
  12396. 'role' => $episode_role_name,
  12397. 'url' => $global_url
  12398. ]);
  12399. }
  12400. break;
  12401. }
  12402. }
  12403. }
  12404. // 继承场景的task_id、task_status和url
  12405. foreach ($episode_scenes as &$episode_scene) {
  12406. $episode_scene_name = getProp($episode_scene, 'scene');
  12407. $episode_description = getProp($episode_scene, 'description');
  12408. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  12409. $episode_url = getProp($episode_scene, 'url');
  12410. // 如果剧集中已有URL,跳过
  12411. if (!empty($episode_url)) {
  12412. continue;
  12413. }
  12414. // 遍历全局场景数据,查找匹配的场景
  12415. foreach ($global_scenes as $global_scene) {
  12416. $global_scene_name = getProp($global_scene, 'scene');
  12417. $global_description = getProp($global_scene, 'description');
  12418. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  12419. $global_url = getProp($global_scene, 'url');
  12420. $global_task_id = getProp($global_scene, 'task_id');
  12421. $global_task_status = getProp($global_scene, 'task_status');
  12422. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  12423. if ($episode_scene_name == $global_scene_name
  12424. && $episode_description == $global_description
  12425. && $episode_pic_prompt == $global_pic_prompt) {
  12426. // 继承 task_id、task_status 和 url
  12427. if (!empty($global_task_id)) {
  12428. $episode_scene['task_id'] = $global_task_id;
  12429. $episode_scene['task_status'] = $global_task_status;
  12430. $scenes_updated = true;
  12431. dLog('deepseek')->info('剧集场景继承全局task_id', [
  12432. 'episode_id' => $episode_id,
  12433. 'scene' => $episode_scene_name,
  12434. 'task_id' => $global_task_id,
  12435. 'task_status' => $global_task_status
  12436. ]);
  12437. }
  12438. if (!empty($global_url)) {
  12439. $episode_scene['url'] = $global_url;
  12440. $scenes_updated = true;
  12441. dLog('deepseek')->info('剧集场景继承全局url', [
  12442. 'episode_id' => $episode_id,
  12443. 'scene' => $episode_scene_name,
  12444. 'url' => $global_url
  12445. ]);
  12446. }
  12447. break;
  12448. }
  12449. }
  12450. }
  12451. // 如果有更新,则保存到数据库
  12452. if ($roles_updated || $scenes_updated) {
  12453. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  12454. if ($roles_updated) {
  12455. $update_data['roles'] = json_encode($episode_roles, 256);
  12456. }
  12457. if ($scenes_updated) {
  12458. $update_data['scenes'] = json_encode($episode_scenes, 256);
  12459. }
  12460. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  12461. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  12462. 'episode_id' => $episode_id,
  12463. 'roles_updated' => $roles_updated,
  12464. 'scenes_updated' => $scenes_updated
  12465. ]);
  12466. }
  12467. return true;
  12468. }
  12469. public function chatChangeImg($data) {
  12470. $segment = getProp($data, 'segment');
  12471. $segment_content = getProp($segment, 'segment_content');
  12472. $prompt = getProp($data, 'prompt');
  12473. $ref_img = getProp($data, 'ref_img');
  12474. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  12475. // 处理文本模型
  12476. $model = getProp($data, 'model');
  12477. if (!$model) {
  12478. // 用户没有输入,从anime表获取
  12479. $segment_id = getProp($segment, 'segment_id');
  12480. if ($segment_id) {
  12481. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  12482. if ($episode_id) {
  12483. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  12484. if ($anime_id) {
  12485. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  12486. }
  12487. }
  12488. }
  12489. if (!$model) {
  12490. // anime表也没有,使用默认值
  12491. $model = 'doubao-seed-2-0-mini-260215';
  12492. }
  12493. }
  12494. // 验证模型是否在可用模型表中
  12495. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  12496. $model = 'doubao-seed-2-0-mini-260215';
  12497. }
  12498. $messages[] =
  12499. [
  12500. 'role' => 'user',
  12501. 'content' => $question
  12502. ];
  12503. $post_data = [
  12504. 'model' => $model,
  12505. 'messages' => $messages,
  12506. // 'max_tokens' => 8192,
  12507. 'temperature' => 0.7,
  12508. 'frequency_penalty' => 0,
  12509. 'presence_penalty' => 0,
  12510. 'response_format' => ['type' => 'text'],
  12511. 'stream' => false // 是否启用流式输出
  12512. ];
  12513. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  12514. // DeepSeek 官方模型使用 DeepSeek API
  12515. $chatResult = $this->chatOnly($post_data);
  12516. } else if (in_array($model, $this->gpt_text_models)) {
  12517. // GPT-5.4 模型使用 TokenRouter API
  12518. $chatResult = $this->gpt54ChatOnly($post_data);
  12519. } else {
  12520. // 其他模型使用火山引擎API
  12521. $chatResult = $this->volcEngineChatCompletion($post_data);
  12522. }
  12523. if (is_array($chatResult)) {
  12524. extract($chatResult);
  12525. }else {
  12526. Utils::throwError('20003: 接口调用失败!');
  12527. }
  12528. // 仅记录 token 使用明细(不扣积分)
  12529. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  12530. 'model' => $model,
  12531. 'source' => 'chatChangeImg',
  12532. ], $model);
  12533. return [
  12534. 'type' => 'done',
  12535. // 'episode' => $episode,
  12536. 'answer' => $fullContent,
  12537. 'reasoning' => $fullReasoningContent,
  12538. 'usage' => $usage
  12539. ];
  12540. }
  12541. /**
  12542. * 仅调用 deepseek 对话接口(非流式)
  12543. *
  12544. * @param array $post_data
  12545. * @param int $timeout
  12546. * @return array
  12547. */
  12548. private function chatOnly($post_data, $timeout = 1800) {
  12549. $post_data['max_tokens'] = 300000;
  12550. $client = new Client(['timeout' => $timeout, 'verify' => false]);
  12551. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  12552. $response = $result->getBody()->getContents();
  12553. $response_arr = json_decode($response, true);
  12554. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  12555. $fullContent = '';
  12556. $fullReasoningContent = [];
  12557. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  12558. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  12559. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  12560. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  12561. }
  12562. return [
  12563. 'fullContent' => $fullContent,
  12564. 'fullReasoningContent' => $fullReasoningContent,
  12565. 'usage' => $usage
  12566. ];
  12567. }
  12568. /**
  12569. * 用 deepseek-v4-flash 非流式分析报错,返回不超过50字的用户友好提示
  12570. *
  12571. * @param string $errorMessage
  12572. * @return string|null
  12573. */
  12574. public function analyzeErrorMessage($errorMessage)
  12575. {
  12576. try {
  12577. $post_data = [
  12578. 'model' => 'deepseek-v4-flash',
  12579. 'messages' => [
  12580. [
  12581. 'role' => 'system',
  12582. 'content' => '你是视频生成任务的报错分析助手。请根据用户给出的原始报错,用一句中文提示告诉用户问题原因和下一步怎么做,不超过50个字,直接输出提示内容,不要解释、不要输出代码。',
  12583. ],
  12584. [
  12585. 'role' => 'user',
  12586. 'content' => (string)$errorMessage,
  12587. ],
  12588. ],
  12589. 'temperature' => 0.3,
  12590. 'frequency_penalty' => 0,
  12591. 'presence_penalty' => 0,
  12592. 'response_format' => ['type' => 'text'],
  12593. 'stream' => false,
  12594. ];
  12595. $result = $this->chatOnly($post_data, 8);
  12596. // 调用成功即记录 token 使用明细(不扣积分),保证错误分析这类隐性 AI 调用进入统计口径
  12597. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  12598. 'model' => 'deepseek-v4-flash',
  12599. 'source' => 'analyzeErrorMessage',
  12600. ], 'deepseek-v4-flash');
  12601. $content = trim((string)($result['fullContent'] ?? ''));
  12602. if ($content === '') {
  12603. return null;
  12604. }
  12605. return mb_substr($content, 0, 50);
  12606. } catch (\Exception $e) {
  12607. dLog('deepseek')->error('视频任务报错分析失败: ' . $e->getMessage(), [
  12608. 'error_message' => $errorMessage
  12609. ]);
  12610. return null;
  12611. }
  12612. }
  12613. // 仅调用 GPT-5.4 对话接口(非流式)
  12614. private function gpt54ChatOnly($post_data) {
  12615. $apiKey = env('GPT_54_API_KEY');
  12616. if (empty($apiKey)) {
  12617. Utils::throwError('20003:GPT-5.4 API Key未配置');
  12618. }
  12619. // 先探活,服务不可用时自动重试
  12620. $this->ensureGptServiceAvailable();
  12621. $client = new Client(['timeout' => 1800, 'verify' => false]);
  12622. $headers = [
  12623. 'Authorization' => 'Bearer ' . $apiKey,
  12624. 'Content-Type' => 'application/json'
  12625. ];
  12626. // 移除 thinking 参数,GPT-5.4 不支持
  12627. if (isset($post_data['thinking'])) {
  12628. unset($post_data['thinking']);
  12629. }
  12630. if (isset($post_data['reasoning_effort'])) {
  12631. unset($post_data['reasoning_effort']);
  12632. }
  12633. $post_data['max_completion_tokens'] = 100000;
  12634. // 确保 stream 为 false
  12635. $post_data['stream'] = false;
  12636. $maxRetries = $this->gptRetryTimes();
  12637. $interval = $this->gptRetryInterval();
  12638. $attempt = 0;
  12639. while (true) {
  12640. try {
  12641. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  12642. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  12643. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  12644. 'json' => $post_data,
  12645. 'headers' => $headers
  12646. ]);
  12647. $response = $result->getBody()->getContents();
  12648. $response_arr = json_decode($response, true);
  12649. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  12650. $fullContent = '';
  12651. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  12652. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  12653. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  12654. }
  12655. return [
  12656. 'fullContent' => $fullContent,
  12657. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  12658. 'usage' => $usage
  12659. ];
  12660. } catch (\Exception $e) {
  12661. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  12662. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  12663. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  12664. throw $e;
  12665. }
  12666. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  12667. 'retry' => $attempt + 1,
  12668. 'max_retries' => $maxRetries,
  12669. 'error' => $e->getMessage()
  12670. ]);
  12671. sleep($interval);
  12672. $attempt++;
  12673. }
  12674. }
  12675. }
  12676. private function splitContent($content) {
  12677. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  12678. $chapters = [];
  12679. // 匹配章节标题格式:
  12680. // 1. 标题可能独占一行,也可能在正文末尾或中间
  12681. // 2. 格式支持:
  12682. // - **第一集**
  12683. // - 第一集:
  12684. // - ###第1章 重生
  12685. // - ##第2章 相救
  12686. // - 第三章 共处一室
  12687. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  12688. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  12689. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  12690. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  12691. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  12692. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  12693. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  12694. // 先在每个标题前插入换行符(如果前面不是换行的话)
  12695. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  12696. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  12697. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  12698. // 用正则找出所有章节标题的位置
  12699. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  12700. $titleCount = count($matches[0]);
  12701. for ($i = 0; $i < $titleCount; $i++) {
  12702. // 获取当前章节标题
  12703. $titleLine = trim($matches[0][$i][0]);
  12704. // 去除标题开头的特殊符号
  12705. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/u', '', $titleLine);
  12706. // 去除标题结尾的冒号和特殊符号
  12707. $cleanTitle = preg_replace('/[#*·::\s]+$/u', '', $cleanTitle);
  12708. $cleanTitle = trim($cleanTitle);
  12709. // 获取当前标题的结束位置
  12710. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  12711. // 获取下一个章节标题的开始位置(如果存在)
  12712. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  12713. // 提取章节内容(从标题结束到下一个标题开始)
  12714. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  12715. // 清理内容:去除前后空白和分隔线
  12716. $chapterContent = trim($chapterContent);
  12717. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  12718. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  12719. if (!empty($cleanTitle) && !empty($chapterContent)) {
  12720. $chapters[] = [
  12721. 'title' => $cleanTitle,
  12722. 'content' => $chapterContent
  12723. ];
  12724. }
  12725. }
  12726. } else {
  12727. // 如果没有匹配到章节,返回整个内容
  12728. $chapters[] = [
  12729. 'title' => '',
  12730. 'content' => $content
  12731. ];
  12732. }
  12733. return $chapters;
  12734. }
  12735. public function getContentByBid($bid) {
  12736. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  12737. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  12738. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  12739. $content = '';
  12740. foreach ($chapters as $chapter) {
  12741. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  12742. }
  12743. return $content;
  12744. }
  12745. public function getContentByScriptId($script_id) {
  12746. $content = '';
  12747. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  12748. if ($contents) {
  12749. $content = implode(PHP_EOL, $contents);
  12750. }else {
  12751. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  12752. }
  12753. return $content;
  12754. }
  12755. /**
  12756. * 根据文件类型提取文本内容
  12757. *
  12758. * @param mixed $file 文件对象或文件路径
  12759. * @return string
  12760. */
  12761. public function extractFileContent($file) {
  12762. // 获取文件路径和扩展名
  12763. if (is_string($file)) {
  12764. $filePath = $file;
  12765. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  12766. } else {
  12767. // Laravel UploadedFile 对象
  12768. $filePath = $file->getRealPath();
  12769. $extension = strtolower($file->getClientOriginalExtension());
  12770. }
  12771. $content = '';
  12772. switch ($extension) {
  12773. case 'txt':
  12774. $content = $this->extractTxtContent($filePath);
  12775. break;
  12776. case 'pdf':
  12777. $content = $this->extractPdfContent($filePath);
  12778. break;
  12779. case 'doc':
  12780. case 'docx':
  12781. $content = $this->extractWordContent($filePath);
  12782. break;
  12783. // case 'jpg':
  12784. // case 'jpeg':
  12785. // case 'png':
  12786. // case 'gif':
  12787. // case 'bmp':
  12788. // case 'webp':
  12789. // $content = $this->extractImageContent($filePath);
  12790. // break;
  12791. default:
  12792. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  12793. }
  12794. // 移除非法 UTF-8 字节,避免后续 JSON 编码或正则解析异常
  12795. if (!mb_check_encoding($content, 'UTF-8')) {
  12796. $cleaned = @iconv('UTF-8', 'UTF-8//IGNORE', $content);
  12797. $content = $cleaned === false ? $content : $cleaned;
  12798. }
  12799. return $content;
  12800. }
  12801. /**
  12802. * 提取 TXT 文件内容
  12803. */
  12804. private function extractTxtContent($filePath) {
  12805. if (!file_exists($filePath)) {
  12806. Utils::throwError('20003:文件不存在');
  12807. }
  12808. $content = file_get_contents($filePath);
  12809. // 尝试检测并转换编码
  12810. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  12811. if ($encoding && $encoding !== 'UTF-8') {
  12812. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  12813. }
  12814. return trim($content);
  12815. }
  12816. /**
  12817. * 提取 PDF 文件内容
  12818. */
  12819. private function extractPdfContent($filePath) {
  12820. if (!file_exists($filePath)) {
  12821. Utils::throwError('20003:文件不存在');
  12822. }
  12823. try {
  12824. $parser = new PdfParser();
  12825. $pdf = $parser->parseFile($filePath);
  12826. $content = $pdf->getText();
  12827. return trim($content);
  12828. } catch (\Exception $e) {
  12829. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  12830. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  12831. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  12832. }
  12833. }
  12834. /**
  12835. * 提取 Word 文件内容(支持 doc 和 docx)
  12836. */
  12837. private function extractWordContent($filePath) {
  12838. if (!file_exists($filePath)) {
  12839. Utils::throwError('20003:文件不存在');
  12840. }
  12841. try {
  12842. $phpWord = WordIOFactory::load($filePath);
  12843. $content = '';
  12844. foreach ($phpWord->getSections() as $section) {
  12845. foreach ($section->getElements() as $element) {
  12846. $content .= $this->extractWordElementText($element);
  12847. }
  12848. }
  12849. return trim($content);
  12850. } catch (\Exception $e) {
  12851. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  12852. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  12853. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  12854. }
  12855. }
  12856. /**
  12857. * 递归提取 Word 元素中的文本
  12858. */
  12859. private function extractWordElementText($element) {
  12860. $text = '';
  12861. if (method_exists($element, 'getText')) {
  12862. $text .= $element->getText() . "\n";
  12863. } elseif (method_exists($element, 'getElements')) {
  12864. foreach ($element->getElements() as $childElement) {
  12865. $text .= $this->extractWordElementText($childElement);
  12866. }
  12867. }
  12868. return $text;
  12869. }
  12870. /**
  12871. * 提取图片内容(使用火山引擎 OCR)
  12872. */
  12873. private function extractImageContent($filePath) {
  12874. if (!file_exists($filePath)) {
  12875. Utils::throwError('20003:文件不存在');
  12876. }
  12877. try {
  12878. // 读取图片并转换为 base64
  12879. $imageData = file_get_contents($filePath);
  12880. $base64Image = base64_encode($imageData);
  12881. // 调用火山引擎 OCR 服务
  12882. $content = $this->callVolcEngineOCR($base64Image);
  12883. return trim($content);
  12884. } catch (\Exception $e) {
  12885. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  12886. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  12887. Utils::throwError('20003:图片识别失败');
  12888. }
  12889. }
  12890. /**
  12891. * 调用火山引擎 OCR 服务识别图片文字
  12892. *
  12893. * @param string $base64Image base64 编码的图片数据
  12894. * @return string 识别的文字内容
  12895. */
  12896. private function callVolcEngineOCR($base64Image) {
  12897. $method = 'POST';
  12898. $service = 'cv';
  12899. $host = 'visual.volcengineapi.com';
  12900. $region = env('VOLC_REGION', 'cn-north-1');
  12901. $access_key = env('VOLC_AK');
  12902. $secret_key = env('VOLC_SK');
  12903. $action = 'OCRNormal';
  12904. $version = '2020-08-26';
  12905. if (!$access_key || !$secret_key) {
  12906. Utils::throwError('20003:请配置火山引擎 AK/SK');
  12907. }
  12908. // 请求体
  12909. $body = json_encode([
  12910. 'image_base64' => $base64Image
  12911. ]);
  12912. // 生成签名
  12913. $headers = $this->getVolcEngineSignHeaders(
  12914. $method, $service, $host, $region,
  12915. "Action={$action}&Version={$version}",
  12916. $access_key, $secret_key, $body
  12917. );
  12918. $client = new Client(['timeout' => 1800, 'verify' => false]);
  12919. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  12920. 'headers' => $headers,
  12921. 'body' => $body
  12922. ]);
  12923. $response_arr = json_decode($response->getBody()->getContents(), true);
  12924. // 提取识别的文字
  12925. $textLines = [];
  12926. if (isset($response_arr['data']['line_texts'])) {
  12927. $textLines = $response_arr['data']['line_texts'];
  12928. } elseif (isset($response_arr['data']['ocr_infos'])) {
  12929. foreach ($response_arr['data']['ocr_infos'] as $info) {
  12930. if (isset($info['text'])) {
  12931. $textLines[] = $info['text'];
  12932. }
  12933. }
  12934. }
  12935. if (empty($textLines)) {
  12936. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  12937. return '';
  12938. }
  12939. return implode("\n", $textLines);
  12940. }
  12941. /**
  12942. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  12943. */
  12944. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  12945. $contentType = 'application/json';
  12946. $accept = 'application/json';
  12947. // 获取当前UTC时间
  12948. $t = new DateTime('now', new DateTimeZone('UTC'));
  12949. $xDate = $t->format('Ymd\THis\Z');
  12950. $dateStamp = $t->format('Ymd');
  12951. // 计算 body 的 sha256 哈希
  12952. $payloadHash = hash('sha256', $body);
  12953. // 1. 拼接规范请求串
  12954. $canonicalUri = '/';
  12955. $canonicalQueryString = $queryString;
  12956. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  12957. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  12958. $canonicalRequest = implode("\n", [
  12959. $method,
  12960. $canonicalUri,
  12961. $canonicalQueryString,
  12962. $canonicalHeaders,
  12963. $signedHeaders,
  12964. $payloadHash
  12965. ]);
  12966. // 2. 拼接待签名字符串
  12967. $algorithm = 'HMAC-SHA256';
  12968. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  12969. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  12970. $stringToSign = implode("\n", [
  12971. $algorithm,
  12972. $xDate,
  12973. $credentialScope,
  12974. $hashedCanonicalRequest
  12975. ]);
  12976. // 3. 计算签名
  12977. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  12978. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  12979. // 4. 添加签名到请求头
  12980. $authorizationHeader = sprintf(
  12981. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  12982. $algorithm,
  12983. $access_key,
  12984. $credentialScope,
  12985. $signedHeaders,
  12986. $signature
  12987. );
  12988. return [
  12989. 'Accept' => $accept,
  12990. 'Content-Type' => $contentType,
  12991. 'Host' => $host,
  12992. 'X-Date' => $xDate,
  12993. 'X-Content-Sha256'=> $payloadHash,
  12994. 'Authorization' => $authorizationHeader
  12995. ];
  12996. }
  12997. public function generateScriptWords($cid, $model = 'r1') {
  12998. ini_set('max_execution_time', 0);
  12999. if (!$cid) Utils::throwError('20003: 请选择章节!');
  13000. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  13001. // 模型兼容性处理和思考模式设置
  13002. $thinkingMode = 'disabled';
  13003. $reasoningEffort = 'high';
  13004. if ($model == 'r1') {
  13005. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  13006. $thinkingMode = 'enabled';
  13007. } else {
  13008. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  13009. $thinkingMode = 'disabled';
  13010. }
  13011. $messages = [
  13012. [
  13013. 'role' => 'system',
  13014. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  13015. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  13016. 2.非对话部分请全部用旁白角色代替
  13017. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  13018. ],
  13019. [
  13020. 'role' => 'user',
  13021. 'content' => $content
  13022. ]
  13023. ];
  13024. $post_data = [
  13025. 'model' => $model,
  13026. 'messages' => $messages,
  13027. // 'max_tokens' => 8192,
  13028. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  13029. 'frequency_penalty' => 0,
  13030. 'presence_penalty' => 0,
  13031. 'thinking' => ['type' => $thinkingMode],
  13032. 'response_format' => [
  13033. 'type' => 'text'
  13034. ],
  13035. 'stream' => false
  13036. ];
  13037. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  13038. // 根据模型类型选择调用方法
  13039. $fullContent = '';
  13040. $usage = [];
  13041. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  13042. // DeepSeek 官方模型使用 DeepSeek API
  13043. $chatResult = $this->chatOnly($post_data);
  13044. } else if (in_array($model, $this->gpt_text_models)) {
  13045. // GPT-5.4 模型使用 TokenRouter API
  13046. $chatResult = $this->gpt54ChatOnly($post_data);
  13047. } else {
  13048. // 其他模型使用火山引擎API
  13049. $chatResult = $this->volcEngineChatCompletion($post_data);
  13050. }
  13051. if (is_array($chatResult)) {
  13052. $fullContent = $chatResult['fullContent'];
  13053. $usage = $chatResult['usage'] ?? [];
  13054. }
  13055. // 仅记录 token 使用明细(不扣积分)
  13056. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  13057. 'model' => $model,
  13058. 'cid' => $cid,
  13059. 'source' => 'generateScriptWords',
  13060. ], $model);
  13061. return $fullContent;
  13062. }
  13063. /**
  13064. * 智能化解析集数信息
  13065. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  13066. *
  13067. * @param string $prompt 用户输入的提示词
  13068. * @return int|null 解析出的集数,如果没有找到则返回null
  13069. */
  13070. private function extractEpisodeNumber($prompt)
  13071. {
  13072. if (empty($prompt)) {
  13073. return null;
  13074. }
  13075. // 定义各种可能的表达模式
  13076. $patterns = [
  13077. // 基本模式:改成N集、调整成N集、修改成N集
  13078. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  13079. // 扩展模式:分成N集、拆分成N集、分割成N集
  13080. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  13081. // 数量模式:N集、共N集、总共N集
  13082. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  13083. // 制作模式:制作N集、生成N集、创建N集
  13084. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  13085. // 计划模式:计划N集、预计N集、打算N集
  13086. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  13087. // 需要模式:需要N集、要N集
  13088. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  13089. // 中文数字模式:改成三集、调整成五集等
  13090. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  13091. // 英文数字模式
  13092. '/(?: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',
  13093. ];
  13094. // 中文数字转阿拉伯数字的映射
  13095. $chineseNumbers = [
  13096. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  13097. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  13098. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  13099. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  13100. ];
  13101. // 逐个尝试匹配模式
  13102. foreach ($patterns as $pattern) {
  13103. if (preg_match($pattern, $prompt, $matches)) {
  13104. $number = trim($matches[1]);
  13105. // 如果是中文数字,转换为阿拉伯数字
  13106. if (isset($chineseNumbers[$number])) {
  13107. return $chineseNumbers[$number];
  13108. }
  13109. // 如果是阿拉伯数字,直接返回
  13110. if (is_numeric($number)) {
  13111. $episodeNum = intval($number);
  13112. // 合理性检查:集数应该在1-100之间
  13113. if ($episodeNum >= 1 && $episodeNum <= 100) {
  13114. return $episodeNum;
  13115. }
  13116. }
  13117. }
  13118. }
  13119. return null;
  13120. }
  13121. /**
  13122. * 调用火山引擎对话(Chat) API
  13123. *
  13124. * @param array $params 包含以下参数:
  13125. * - model: 模型ID(必填)
  13126. * - messages: 消息列表(必填)
  13127. * - stream: 是否流式输出(可选,默认false)
  13128. * - max_tokens: 最大输出token数(可选)
  13129. * - temperature: 采样温度(可选,默认1)
  13130. * - top_p: 核采样概率(可选,默认0.7)
  13131. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  13132. * - presence_penalty: 存在惩罚系数(可选,默认0)
  13133. * - stop: 停止词(可选)
  13134. * - tools: 工具列表(可选)
  13135. * @return array|Generator 非流式返回数组,流式返回生成器
  13136. */
  13137. public function volcEngineChatCompletion(array $params)
  13138. {
  13139. $apiKey = env('VOLC_AI_API_KEY');
  13140. if (empty($apiKey)) {
  13141. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  13142. }
  13143. // 构建请求参数
  13144. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  13145. $requestData = [
  13146. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  13147. 'messages' => $params['messages'] ?? [],
  13148. ];
  13149. if (!in_array($originalModel, $this->valid_text_models)) {
  13150. Utils::throwError('20003:该模型不支持!');
  13151. }
  13152. // 添加可选参数
  13153. if (isset($params['stream'])) {
  13154. $requestData['stream'] = $params['stream'];
  13155. }
  13156. if (isset($params['stream_options'])) {
  13157. $requestData['stream_options'] = $params['stream_options'];
  13158. }
  13159. if (isset($params['max_tokens'])) {
  13160. $requestData['max_tokens'] = $params['max_tokens'];
  13161. }else if (isset($params['max_completion_tokens'])) {
  13162. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  13163. }else {
  13164. $requestData['max_completion_tokens'] = 100000;
  13165. }
  13166. if (isset($params['temperature'])) {
  13167. $requestData['temperature'] = $params['temperature'];
  13168. }
  13169. if (isset($params['top_p'])) {
  13170. $requestData['top_p'] = $params['top_p'];
  13171. }
  13172. if (isset($params['frequency_penalty'])) {
  13173. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  13174. }
  13175. if (isset($params['presence_penalty'])) {
  13176. $requestData['presence_penalty'] = $params['presence_penalty'];
  13177. }
  13178. if (isset($params['stop'])) {
  13179. $requestData['stop'] = $params['stop'];
  13180. }
  13181. if (isset($params['tools'])) {
  13182. $requestData['tools'] = $params['tools'];
  13183. }
  13184. if (isset($params['tool_choice'])) {
  13185. $requestData['tool_choice'] = $params['tool_choice'];
  13186. }
  13187. if (isset($params['response_format'])) {
  13188. $requestData['response_format'] = $params['response_format'];
  13189. }
  13190. if (isset($params['thinking'])) {
  13191. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  13192. if (is_array($params['thinking'])) {
  13193. $requestData['thinking'] = $params['thinking'];
  13194. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  13195. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  13196. }
  13197. } else {
  13198. $requestData['thinking'] = ['type' => $params['thinking']];
  13199. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  13200. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  13201. }
  13202. }
  13203. } else {
  13204. $requestData['thinking'] = ['type' => 'disabled'];
  13205. }
  13206. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  13207. $client = new Client(['verify' => false, 'timeout' => 1800]);
  13208. try {
  13209. // 判断是否为流式输出
  13210. $isStream = isset($params['stream']) && $params['stream'] === true;
  13211. if ($isStream) {
  13212. // 流式输出
  13213. // 流式请求默认声明返回 usage(未显式传参时)
  13214. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  13215. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  13216. } else {
  13217. // 非流式输出
  13218. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  13219. 'headers' => [
  13220. 'Authorization' => 'Bearer ' . $apiKey,
  13221. 'Content-Type' => 'application/json',
  13222. ],
  13223. 'json' => $requestData
  13224. ]);
  13225. $responseData = json_decode($response->getBody(), true);
  13226. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  13227. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  13228. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  13229. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  13230. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  13231. }
  13232. return [
  13233. 'fullContent' => $fullContent,
  13234. 'fullReasoningContent' => $fullReasoningContent,
  13235. 'usage' => $usage
  13236. ];
  13237. }
  13238. } catch (\Exception $e) {
  13239. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  13240. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  13241. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  13242. }
  13243. }
  13244. /**
  13245. * 火山引擎对话API流式输出
  13246. *
  13247. * @param Client $client HTTP客户端
  13248. * @param string $apiKey API密钥
  13249. * @param array $requestData 请求数据
  13250. * @return Generator
  13251. */
  13252. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  13253. {
  13254. try {
  13255. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  13256. 'headers' => [
  13257. 'Authorization' => 'Bearer ' . $apiKey,
  13258. 'Content-Type' => 'application/json',
  13259. ],
  13260. 'json' => $requestData,
  13261. 'stream' => true
  13262. ]);
  13263. $body = $response->getBody();
  13264. $buffer = '';
  13265. $fullContent = '';
  13266. $fullReasoningContent = '';
  13267. $usage = [];
  13268. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  13269. // 逐行读取流式响应
  13270. while (!$body->eof()) {
  13271. $chunk = $body->read(1024);
  13272. $buffer .= $chunk;
  13273. // 按行分割
  13274. $lines = explode("\n", $buffer);
  13275. $buffer = array_pop($lines);
  13276. foreach ($lines as $line) {
  13277. $line = trim($line);
  13278. if (empty($line)) {
  13279. continue;
  13280. }
  13281. // 检查是否是SSE数据行
  13282. if (strpos($line, 'data: ') !== 0) {
  13283. continue;
  13284. }
  13285. $data = substr($line, 6);
  13286. if ($data === '[DONE]') {
  13287. dLog('deepseek')->info('收到结束标记');
  13288. break 2;
  13289. }
  13290. try {
  13291. $json = json_decode($data, true);
  13292. if (json_last_error() !== JSON_ERROR_NONE) {
  13293. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  13294. continue;
  13295. }
  13296. if (isset($json['choices'][0]['delta'])) {
  13297. $delta = $json['choices'][0]['delta'];
  13298. // 处理思维链内容
  13299. if (isset($delta['reasoning_content'])) {
  13300. $fullReasoningContent .= $delta['reasoning_content'];
  13301. yield [
  13302. 'type' => 'reasoning',
  13303. 'content' => $delta['reasoning_content'],
  13304. 'full_reasoning' => $fullReasoningContent
  13305. ];
  13306. }
  13307. // 处理回答内容
  13308. if (isset($delta['content'])) {
  13309. $fullContent .= $delta['content'];
  13310. yield [
  13311. 'type' => 'content',
  13312. 'content' => $delta['content'],
  13313. ];
  13314. }
  13315. }
  13316. // 获取使用统计信息
  13317. if (isset($json['usage'])) {
  13318. $usage = $json['usage'];
  13319. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  13320. }
  13321. } catch (\Exception $e) {
  13322. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  13323. continue;
  13324. }
  13325. }
  13326. }
  13327. dLog('deepseek')->info('流式读取完成', [
  13328. 'content_length' => strlen($fullContent),
  13329. 'reasoning_length' => strlen($fullReasoningContent)
  13330. ]);
  13331. yield [
  13332. 'type' => 'done',
  13333. 'full_content' => $fullContent,
  13334. 'full_reasoning' => $fullReasoningContent,
  13335. 'usage' => $usage
  13336. ];
  13337. } catch (\Exception $e) {
  13338. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  13339. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  13340. throw $e;
  13341. }
  13342. }
  13343. /**
  13344. * 检查并创建图片生成任务
  13345. *
  13346. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  13347. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  13348. * @param string $nameKey 资源名称字段('role' 或 'scene')
  13349. * @param string $art_style 美术风格
  13350. * @return array 更新后的资源列表
  13351. */
  13352. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  13353. {
  13354. // 确保参数为数组
  13355. $merged_items = is_array($merged_items) ? $merged_items : [];
  13356. $global_items = is_array($global_items) ? $global_items : [];
  13357. // 构建全局资源映射表,用于快速查找
  13358. $global_map = [];
  13359. foreach ($global_items as $item) {
  13360. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13361. if ($itemKey === '') {
  13362. continue;
  13363. }
  13364. $global_map[$itemKey] = $item;
  13365. }
  13366. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  13367. foreach ($merged_items as &$item) {
  13368. $item_name = getProp($item, $nameKey);
  13369. $item_description = getProp($item, 'description');
  13370. // $item_url = getProp($item, 'url');
  13371. // // 如果已有图片URL,跳过
  13372. // if (!empty($item_url)) {
  13373. // continue;
  13374. // }
  13375. // 如果是旁白角色,跳过
  13376. if ($nameKey === 'role' && $item_name === '旁白') {
  13377. continue;
  13378. }
  13379. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  13380. if ($itemKey === '') {
  13381. continue;
  13382. }
  13383. $need_create_task = false;
  13384. // 条件1:在全局资源中找不到匹配的名称
  13385. if (!isset($global_map[$itemKey])) {
  13386. $need_create_task = true;
  13387. } else {
  13388. // 条件2:名称匹配但描述或 pic_prompt 不一致
  13389. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  13390. $current_description = trim((string)$item_description);
  13391. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  13392. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  13393. // 如果 description 或 pic_prompt 有变化,需要重新生成
  13394. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  13395. $need_create_task = true;
  13396. }
  13397. }
  13398. // 如果需要创建任务,调用图片生成服务
  13399. if ($need_create_task) {
  13400. try {
  13401. // 优先使用 pic_prompt,如果没有则使用 description
  13402. $pic_prompt = getProp($item, 'pic_prompt');
  13403. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  13404. // 添加美术风格前缀
  13405. if ($art_style) {
  13406. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  13407. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  13408. $description = "{$prefix}:{$description}";
  13409. }
  13410. $params = [
  13411. 'prompt' => $description,
  13412. 'ref_img_urls' => []
  13413. ];
  13414. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13415. $task_id = $task->id;
  13416. if ($task_id) {
  13417. $item['task_id'] = $task_id;
  13418. $item['task_status'] = 'processing';
  13419. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  13420. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  13421. }
  13422. } catch (\Exception $e) {
  13423. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  13424. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  13425. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  13426. // 不抛出异常,继续处理其他资源
  13427. }
  13428. }
  13429. }
  13430. return $merged_items;
  13431. }
  13432. /**
  13433. * 同步新出现的主体和场景到全局
  13434. *
  13435. * @param int $anime_id 动漫ID
  13436. * @param array $merged_roles 合并后的角色列表
  13437. * @param array $merged_scenes 合并后的场景列表
  13438. * @param array $global_roles 全局角色列表
  13439. * @param array $global_scenes 全局场景列表
  13440. * @return void
  13441. */
  13442. private function syncNewResourcesToGlobal(
  13443. int $anime_id,
  13444. array $merged_roles,
  13445. array $merged_scenes,
  13446. array $global_roles,
  13447. array $global_scenes
  13448. ): void {
  13449. // 构建全局角色映射表
  13450. $global_role_map = [];
  13451. foreach ($global_roles as $role) {
  13452. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  13453. if ($roleKey !== '') {
  13454. $global_role_map[$roleKey] = $role;
  13455. }
  13456. }
  13457. // 构建全局场景映射表
  13458. $global_scene_map = [];
  13459. foreach ($global_scenes as $scene) {
  13460. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  13461. if ($sceneKey !== '') {
  13462. $global_scene_map[$sceneKey] = $scene;
  13463. }
  13464. }
  13465. $need_update = false;
  13466. $new_global_roles = $global_roles;
  13467. $new_global_scenes = $global_scenes;
  13468. // 检查并添加新角色到全局
  13469. foreach ($merged_roles as $role) {
  13470. $role_name = getProp($role, 'role');
  13471. // 跳过旁白
  13472. if ($role_name === '旁白') {
  13473. continue;
  13474. }
  13475. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  13476. if ($roleKey === '') {
  13477. continue;
  13478. }
  13479. // 如果全局中不存在该角色,添加到全局
  13480. if (!isset($global_role_map[$roleKey])) {
  13481. $new_global_roles[] = [
  13482. 'role' => $role_name,
  13483. 'description' => getProp($role, 'description', ''),
  13484. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  13485. 'voice_name' => getProp($role, 'voice_name', ''),
  13486. 'voice_type' => getProp($role, 'voice_type', ''),
  13487. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  13488. 'url' => getProp($role, 'url', ''),
  13489. 'task_id' => getProp($role, 'task_id', ''),
  13490. 'task_status' => getProp($role, 'task_status', ''),
  13491. ];
  13492. $global_role_map[$roleKey] = true; // 标记已添加
  13493. $need_update = true;
  13494. dLog('deepseek')->info("新角色同步到全局", [
  13495. 'anime_id' => $anime_id,
  13496. 'role' => $role_name,
  13497. 'task_id' => getProp($role, 'task_id', ''),
  13498. ]);
  13499. }
  13500. // else {
  13501. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  13502. // $global_role = $global_role_map[$roleKey];
  13503. // if (is_array($global_role)) {
  13504. // $updated = false;
  13505. // $update_fields = [];
  13506. // // 检查描述是否更新
  13507. // $current_description = trim((string)getProp($role, 'description'));
  13508. // $global_description = trim((string)getProp($global_role, 'description'));
  13509. // if ($current_description !== '' && $current_description !== $global_description) {
  13510. // $updated = true;
  13511. // $update_fields[] = 'description';
  13512. // }
  13513. // // 检查pic_prompt是否更新
  13514. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  13515. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  13516. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  13517. // $updated = true;
  13518. // $update_fields[] = 'pic_prompt';
  13519. // }
  13520. // // 检查图片任务信息是否更新
  13521. // $current_task_id = getProp($role, 'task_id');
  13522. // $global_task_id = getProp($global_role, 'task_id');
  13523. // if ($current_task_id && $current_task_id !== $global_task_id) {
  13524. // $updated = true;
  13525. // $update_fields[] = 'task_id';
  13526. // }
  13527. // // 如果有更新,同步到全局
  13528. // if ($updated) {
  13529. // foreach ($new_global_roles as &$global_role_item) {
  13530. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  13531. // if ($global_role_key === $roleKey) {
  13532. // if (in_array('description', $update_fields)) {
  13533. // $global_role_item['description'] = $current_description;
  13534. // }
  13535. // if (in_array('pic_prompt', $update_fields)) {
  13536. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  13537. // }
  13538. // if (in_array('task_id', $update_fields)) {
  13539. // $global_role_item['task_id'] = $current_task_id;
  13540. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  13541. // $global_role_item['url'] = getProp($role, 'url', '');
  13542. // }
  13543. // break;
  13544. // }
  13545. // }
  13546. // $need_update = true;
  13547. // dLog('deepseek')->info("角色信息更新到全局", [
  13548. // 'anime_id' => $anime_id,
  13549. // 'role' => $role_name,
  13550. // 'update_fields' => implode(',', $update_fields),
  13551. // ]);
  13552. // }
  13553. // }
  13554. // }
  13555. }
  13556. // 检查并添加新场景到全局
  13557. foreach ($merged_scenes as $scene) {
  13558. $scene_name = getProp($scene, 'scene');
  13559. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  13560. if ($sceneKey === '') {
  13561. continue;
  13562. }
  13563. // 如果全局中不存在该场景,添加到全局
  13564. if (!isset($global_scene_map[$sceneKey])) {
  13565. $new_global_scenes[] = [
  13566. 'scene' => $scene_name,
  13567. 'description' => getProp($scene, 'description', ''),
  13568. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  13569. 'url' => getProp($scene, 'url', ''),
  13570. 'task_id' => getProp($scene, 'task_id', ''),
  13571. 'task_status' => getProp($scene, 'task_status', ''),
  13572. ];
  13573. $global_scene_map[$sceneKey] = true; // 标记已添加
  13574. $need_update = true;
  13575. dLog('deepseek')->info("新场景同步到全局", [
  13576. 'anime_id' => $anime_id,
  13577. 'scene' => $scene_name,
  13578. 'task_id' => getProp($scene, 'task_id', ''),
  13579. ]);
  13580. }
  13581. // else {
  13582. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  13583. // $global_scene = $global_scene_map[$sceneKey];
  13584. // if (is_array($global_scene)) {
  13585. // $updated = false;
  13586. // $update_fields = [];
  13587. // // 检查描述是否更新
  13588. // $current_description = trim((string)getProp($scene, 'description'));
  13589. // $global_description = trim((string)getProp($global_scene, 'description'));
  13590. // if ($current_description !== '' && $current_description !== $global_description) {
  13591. // $updated = true;
  13592. // $update_fields[] = 'description';
  13593. // }
  13594. // // 检查pic_prompt是否更新
  13595. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  13596. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  13597. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  13598. // $updated = true;
  13599. // $update_fields[] = 'pic_prompt';
  13600. // }
  13601. // // 检查图片任务信息是否更新
  13602. // $current_task_id = getProp($scene, 'task_id');
  13603. // $global_task_id = getProp($global_scene, 'task_id');
  13604. // if ($current_task_id && $current_task_id !== $global_task_id) {
  13605. // $updated = true;
  13606. // $update_fields[] = 'task_id';
  13607. // }
  13608. // // 如果有更新,同步到全局
  13609. // if ($updated) {
  13610. // foreach ($new_global_scenes as &$global_scene_item) {
  13611. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  13612. // if ($global_scene_key === $sceneKey) {
  13613. // if (in_array('description', $update_fields)) {
  13614. // $global_scene_item['description'] = $current_description;
  13615. // }
  13616. // if (in_array('pic_prompt', $update_fields)) {
  13617. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  13618. // }
  13619. // if (in_array('task_id', $update_fields)) {
  13620. // $global_scene_item['task_id'] = $current_task_id;
  13621. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  13622. // $global_scene_item['url'] = getProp($scene, 'url', '');
  13623. // }
  13624. // break;
  13625. // }
  13626. // }
  13627. // $need_update = true;
  13628. // dLog('deepseek')->info("场景信息更新到全局", [
  13629. // 'anime_id' => $anime_id,
  13630. // 'scene' => $scene_name,
  13631. // 'update_fields' => implode(',', $update_fields),
  13632. // ]);
  13633. // }
  13634. // }
  13635. // }
  13636. }
  13637. // 如果有新增或更新,更新数据库
  13638. if ($need_update) {
  13639. $update_data = [
  13640. 'roles' => json_encode($new_global_roles, 256),
  13641. 'scenes' => json_encode($new_global_scenes, 256),
  13642. 'updated_at' => date('Y-m-d H:i:s'),
  13643. ];
  13644. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  13645. if ($result !== false) {
  13646. dLog('deepseek')->info("全局角色和场景更新成功", [
  13647. 'anime_id' => $anime_id,
  13648. 'roles_count' => count($new_global_roles),
  13649. 'scenes_count' => count($new_global_scenes),
  13650. ]);
  13651. } else {
  13652. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  13653. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  13654. }
  13655. }
  13656. }
  13657. }