DeepSeekService.php 961 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670
  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\ActShowContent;
  7. use App\Libs\JsonSafeRepair;
  8. use App\Libs\Utils;
  9. use GuzzleHttp\Client;
  10. use DateTime;
  11. use DateTimeZone;
  12. use App\Models\MpTaskCenter;
  13. use App\Models\MpUserPointsDetail;
  14. use App\Services\AIGeneration\AIImageGenerationService;
  15. use App\Services\PointsService;
  16. use Illuminate\Support\Facades\DB;
  17. use Illuminate\Support\Facades\Log;
  18. use Illuminate\Support\Facades\Redis;
  19. use OSS\Core\OssException;
  20. use OSS\OssClient;
  21. use Smalot\PdfParser\Parser as PdfParser;
  22. use TCPDF;
  23. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  24. use Predis\Command\Traits\Get\Get;
  25. class DeepSeekService
  26. {
  27. private $url;
  28. private $api_key;
  29. private $sys_message;
  30. private $headers;
  31. private $valid_text_models;
  32. private $gpt_text_models;
  33. private $gemini_text_models;
  34. private $baidu_glm_text_models;
  35. // GPT 上游错误详情缓存(按异常对象 id 缓存,避免流式响应体被重复读取后丢失)
  36. private $gpt_upstream_error_cache = [];
  37. protected $aiImageGenerationService;
  38. protected $pointsService;
  39. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  40. $this->aiImageGenerationService = $aiImageGenerationService;
  41. $this->pointsService = $pointsService;
  42. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  43. $this->api_key = env('DEEPSEEK_API_KEY');
  44. $this->headers = [
  45. 'Authorization' => 'Bearer '.$this->api_key,
  46. 'Content-Type' => 'application/json; charset=UTF-8'
  47. ];
  48. // 火山引擎模型列表
  49. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  50. // GPT文本模型列表
  51. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  52. // Gemini文本模型列表
  53. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  54. // 百度 AI 网关 GLM 文本模型列表
  55. $this->baidu_glm_text_models = BaseConst::BAIDU_GLM_TEXT_MODELS;
  56. $this->sys_message = [
  57. 'role' => 'system',
  58. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  59. 强制要求:\n
  60. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  61. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  62. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  63. 普通要求:\n
  64. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  65. 2.<分集剧本>的要求如下:
  66.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  67.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  68.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  69.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  70. \n\n
  71. 示例如下:\n
  72. ###剧本名:西昆仑
  73. ###故事梗概
  74. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  75. ###剧本亮点
  76. 亮点1:绝境奇药,生死一线
  77. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  78. 亮点2:结拜兄妹,化解尴尬
  79. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  80. 亮点3:纤发夺命,情愫暗涌
  81. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  82. ###人物关系
  83. 阿雪与梁萧之间存在兄妹之情。
  84. ###核心矛盾
  85. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  86. ###主体列表
  87. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  88. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  89. 阴阳球:天地异宝,能化生精气,救人于危难。
  90. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  91. ###美术风格
  92. 基础画风风格词:厚涂古风
  93. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  94. ###场景列表
  95. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  96. ###分集剧本
  97. ##分集01
  98. 第1集: 第一集的标题
  99. 场景描述:地点、时间、场景
  100. 运镜:固定近距离
  101. 出场角色:男主、女主
  102. 台词内容:
  103. 女主: 女主对话
  104. 男主:男主对话
  105. 女主: 女主对话
  106. 男主: 男主对话
  107. ##分集02
  108. 第2集: 第二集的标题
  109. 场景描述:地点、时间、场景
  110. 运镜:固定近距离
  111. 出场角色:男主、女主
  112. 台词内容:
  113. 女主: 女主对话
  114. 男主:男主对话
  115. 女主: 女主对话
  116. 男主: 男主对话"
  117. ];
  118. }
  119. /**
  120. * 通用文生文方法 - 支持多模型流式输出、图片输入;视频输入仅 Gemini 模型支持
  121. *
  122. * @param array $data 请求参数
  123. * @return \Generator 返回生成器,用于流式输出
  124. */
  125. public function generateText($data) {
  126. // 获取请求参数
  127. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  128. $messages = getProp($data, 'messages', []);
  129. $systemPrompt = getProp($data, 'system_prompt', '');
  130. $prompt = getProp($data, 'prompt', '');
  131. $images = getProp($data, 'images', []); // 支持多张图片
  132. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  133. $videos = getProp($data, 'videos', []); // Gemini 支持视频文件
  134. $videoUrls = getProp($data, 'video_urls', []); // Gemini 支持视频URL
  135. $isGeminiModel = in_array($model, $this->gemini_text_models);
  136. if ((!empty($videos) || !empty($videoUrls)) && !$isGeminiModel) {
  137. Utils::throwError('20003:仅Gemini模型支持视频输入');
  138. }
  139. // 计费预检:纯文生文按 normal 档(3);有参考图/视频输入按模型固定价格(图生文)
  140. $uid = Site::getUid();
  141. $chargeModality = '';
  142. $chargePoints = 0;
  143. $hasImageMedia = !empty($images) || !empty($imageUrls)
  144. || $this->messagesContainMedia($messages, ['image_url', 'image']);
  145. $hasVideoMedia = !empty($videos) || !empty($videoUrls)
  146. || $this->messagesContainMedia($messages, ['video_url', 'video']);
  147. if ($hasImageMedia || $hasVideoMedia) {
  148. $chargeModality = $hasVideoMedia ? 'video' : 'image';
  149. $chargePoints = $this->pointsService->getImageChatChargePoints($model);
  150. } else {
  151. $chargeModality = 'text';
  152. $chargePoints = $this->pointsService->getChatChargePoints('', 'normal');
  153. }
  154. if ($chargePoints > 0) {
  155. $this->pointsService->checkUserPointsEnough($chargePoints, $uid);
  156. }
  157. // 如果没有提供messages,则根据system_prompt、content和images构建
  158. if (empty($messages)) {
  159. $messages = [];
  160. // 添加系统提示词
  161. if (!empty($systemPrompt)) {
  162. $messages[] = [
  163. 'role' => 'system',
  164. 'content' => $systemPrompt
  165. ];
  166. }
  167. // 构建用户消息内容(支持文本+图片)
  168. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  169. $userMessage = [
  170. 'role' => 'user',
  171. 'content' => []
  172. ];
  173. // 添加文本内容
  174. if (!empty($prompt)) {
  175. $userMessage['content'][] = [
  176. 'type' => 'text',
  177. 'text' => $prompt
  178. ];
  179. }
  180. // 处理上传的图片文件
  181. if (!empty($images)) {
  182. if (!is_array($images)) {
  183. $images = [$images];
  184. }
  185. foreach ($images as $image) {
  186. $imageBase64 = $this->processImageToBase64($image);
  187. if ($imageBase64) {
  188. $userMessage['content'][] = [
  189. 'type' => 'image_url',
  190. 'image_url' => [
  191. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  192. ]
  193. ];
  194. }
  195. }
  196. }
  197. // 处理图片URL
  198. if (!empty($imageUrls)) {
  199. if (!is_array($imageUrls)) {
  200. $imageUrls = [$imageUrls];
  201. }
  202. foreach ($imageUrls as $url) {
  203. if (!empty($url)) {
  204. $userMessage['content'][] = [
  205. 'type' => 'image_url',
  206. 'image_url' => [
  207. 'url' => $url
  208. ]
  209. ];
  210. }
  211. }
  212. }
  213. // 处理上传的视频文件(仅 Gemini)
  214. if (!empty($videos) && $isGeminiModel) {
  215. if (!is_array($videos)) {
  216. $videos = [$videos];
  217. }
  218. foreach ($videos as $video) {
  219. $inlineData = $this->processMediaToInlineData($video);
  220. if ($inlineData) {
  221. $userMessage['content'][] = [
  222. 'type' => 'video',
  223. 'inline_data' => $inlineData
  224. ];
  225. }
  226. }
  227. }
  228. // 处理视频URL(仅 Gemini)
  229. if (!empty($videoUrls) && $isGeminiModel) {
  230. if (!is_array($videoUrls)) {
  231. $videoUrls = [$videoUrls];
  232. }
  233. foreach ($videoUrls as $url) {
  234. if (!empty($url)) {
  235. $userMessage['content'][] = [
  236. 'type' => 'video_url',
  237. 'video_url' => ['url' => $url]
  238. ];
  239. }
  240. }
  241. }
  242. // 如果只有文本内容,简化为字符串格式
  243. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  244. $userMessage['content'] = $userMessage['content'][0]['text'];
  245. }
  246. $messages[] = $userMessage;
  247. }
  248. }
  249. // 验证messages不为空
  250. if (empty($messages)) {
  251. Utils::throwError('20003:请提供有效的对话内容');
  252. }
  253. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  254. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  255. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  256. if ($model === 'deepseek-chat') {
  257. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  258. $model = 'deepseek-v4-flash';
  259. $thinkingMode = 'disabled';
  260. } elseif ($model === 'deepseek-reasoner') {
  261. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  262. $model = 'deepseek-v4-flash';
  263. $thinkingMode = 'enabled';
  264. }
  265. // 构建请求参数
  266. $post_data = [
  267. 'model' => $model,
  268. 'messages' => $messages,
  269. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  270. 'temperature' => getProp($data, 'temperature', 1),
  271. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  272. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  273. 'thinking' => ['type' => $thinkingMode],
  274. 'stream' => true // 启用流式输出
  275. ];
  276. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  277. // 添加可选参数
  278. if (isset($data['top_p'])) {
  279. $post_data['top_p'] = $data['top_p'];
  280. }
  281. if (isset($data['response_format'])) {
  282. $post_data['response_format'] = $data['response_format'];
  283. }
  284. // 根据模型类型选择流式实现
  285. $streamGenerator = $this->dispatchStreamByModel($post_data);
  286. if ($chargePoints > 0) {
  287. return $this->wrapGenerateTextCharge($streamGenerator, $uid, $model, $chargePoints, $chargeModality);
  288. }
  289. // 免费场景(0 积分):流式生成成功后仅记录 token 使用明细
  290. return $this->wrapGenerateTextTokenRecord($streamGenerator, $uid, $model);
  291. }
  292. /**
  293. * 流式生成成功后仅记录 token 明细(纯文本免费场景,不扣积分)
  294. *
  295. * @param \Generator $generator
  296. * @param int $uid
  297. * @param string $model
  298. * @return \Generator
  299. */
  300. private function wrapGenerateTextTokenRecord(\Generator $generator, int $uid, string $model, string $source = 'generateText'): \Generator
  301. {
  302. $recorded = false;
  303. foreach ($generator as $chunk) {
  304. if (!$recorded && isset($chunk['type']) && $chunk['type'] === 'done') {
  305. $this->recordTextTokenOnly($uid, $this->pointsService->getTokensFromUsage(getProp($chunk, 'usage', [])), [
  306. 'model' => $model,
  307. 'source' => $source,
  308. ], $model);
  309. $recorded = true;
  310. }
  311. yield $chunk;
  312. }
  313. }
  314. /**
  315. * 流式生成成功后再按档位/模型规则扣费(文生文 normal 档 / 图生文按模型固定价格)
  316. *
  317. * @param \Generator $generator
  318. * @param int $uid
  319. * @param string $model
  320. * @param int $points
  321. * @param string $modality
  322. * @return \Generator
  323. */
  324. private function wrapGenerateTextCharge(\Generator $generator, int $uid, string $model, int $points, string $modality): \Generator
  325. {
  326. $charged = false;
  327. foreach ($generator as $chunk) {
  328. if (!$charged && isset($chunk['type']) && $chunk['type'] === 'done') {
  329. $fullContent = (string)getProp($chunk, 'full_content', getProp($chunk, 'answer', ''));
  330. if ($fullContent !== '') {
  331. $this->chargeMultimodal($uid, $model, $points, $modality, getProp($chunk, 'usage', []));
  332. $charged = true;
  333. }
  334. }
  335. yield $chunk;
  336. }
  337. }
  338. /**
  339. * AI 对话(含图片/视频 -> 文本)成功后扣费并记录积分与 token 明细
  340. *
  341. * @param int $uid
  342. * @param string $model
  343. * @param int $points
  344. * @param string $modality
  345. * @param mixed $usage
  346. * @return void
  347. */
  348. private function chargeMultimodal(int $uid, string $model, int $points, string $modality, $usage): void
  349. {
  350. $result = $this->pointsService->recordChatCharge(
  351. $uid,
  352. $points,
  353. $this->pointsService->getTokensFromUsage($usage),
  354. [
  355. 'model' => $model,
  356. 'modality' => $modality,
  357. 'source' => 'generateText',
  358. ],
  359. '',
  360. $model
  361. );
  362. if (empty($result['charged'])) {
  363. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  364. }
  365. }
  366. /**
  367. * 检查 OpenAI 风格消息中是否包含指定媒体类型
  368. *
  369. * @param array $messages
  370. * @param array $mediaTypes
  371. * @return bool
  372. */
  373. private function messagesContainMedia(array $messages, array $mediaTypes): bool
  374. {
  375. foreach ($messages as $message) {
  376. $content = getProp($message, 'content', '');
  377. if (!is_array($content)) {
  378. continue;
  379. }
  380. foreach ($content as $part) {
  381. if (is_array($part) && in_array(getProp($part, 'type', ''), $mediaTypes, true)) {
  382. return true;
  383. }
  384. }
  385. }
  386. return false;
  387. }
  388. public function createGenerateText($data) {
  389. $file = getProp($data, 'file');
  390. $episode_num = getProp($data, 'episode_num');
  391. $uid = Site::getUid();
  392. $cpid = Site::getCpid();
  393. if (!$file) {
  394. Utils::throwError('20003:请上传文件');
  395. }
  396. // 提取文件内容
  397. $content = $this->extractFileContent($file);
  398. if (!$content) {
  399. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  400. }
  401. // 拆分章节并校验章节总数、标题连续性
  402. if ($episode_num) {
  403. $this->validateGenerateTextChapters($content, (int)$episode_num);
  404. }
  405. // 获取原始文件名(不含扩展名)作为script_name
  406. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  407. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  408. // 字节安全剥离,不依赖服务器locale设置
  409. $originalName = $file->getClientOriginalName();
  410. $extension = $file->getClientOriginalExtension();
  411. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  412. ? substr($originalName, 0, -strlen($extension) - 1)
  413. : $originalName;
  414. if ($script_name === '') {
  415. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  416. }
  417. // 如果同一用户的剧本名存在则提示
  418. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  419. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  420. }
  421. // 插入数据到mp_scripts表
  422. $script_id = DB::table('mp_scripts')->insertGetId([
  423. 'script_name' => $script_name,
  424. 'user_id' => $uid,
  425. 'cpid' => $cpid,
  426. 'content' => $content,
  427. 'created_at' => date('Y-m-d H:i:s'),
  428. 'updated_at' => date('Y-m-d H:i:s')
  429. ]);
  430. return [
  431. 'script_id' => $script_id,
  432. 'script_name' => $script_name
  433. ];
  434. }
  435. /**
  436. * AI对话调用成功后的积分扣费(返回结果前调用)
  437. *
  438. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  439. *
  440. * @param int $uid
  441. * @param int $tokens
  442. * @param array $chargeInfo
  443. * @return void
  444. */
  445. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo, string $chargeType = 'special'): void
  446. {
  447. // api_type 记录真实模型名(缺失时回退 deepseek 大类),保证明细与统计口径准确
  448. $model = (string)getProp($chargeInfo, 'model', '');
  449. $result = $this->pointsService->recordChatCharge(
  450. $uid,
  451. $this->pointsService->getChatChargePoints($model, $chargeType),
  452. $tokens,
  453. $chargeInfo,
  454. '',
  455. $model !== '' ? $model : 'deepseek'
  456. );
  457. if (empty($result['charged'])) {
  458. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  459. }
  460. }
  461. /**
  462. * 安全获取当前登录用户ID
  463. *
  464. * 命令行/队列等无用户上下文的场景返回 0,由记录方法自行跳过。
  465. *
  466. * @return int
  467. */
  468. private function getCurrentUid(): int
  469. {
  470. try {
  471. return (int)Site::getUid();
  472. } catch (\Throwable $e) {
  473. return 0;
  474. }
  475. }
  476. /**
  477. * 记录文生文 token 使用明细(仅记录,不扣积分)
  478. *
  479. * 用于不按积分计费的文生文接口;记录失败不影响主流程。
  480. *
  481. * @param int $uid 用户ID(0 时跳过)
  482. * @param int $tokens 消耗 token 数
  483. * @param array $chargeInfo 计费/来源信息(model、source 等)
  484. * @param string $apiType API 类型/模型标识
  485. * @return void
  486. */
  487. private function recordTextTokenOnly(int $uid, int $tokens, array $chargeInfo, string $apiType = ''): void
  488. {
  489. try {
  490. $this->pointsService->recordTokenOnlyDetail(
  491. $uid,
  492. $tokens,
  493. $chargeInfo,
  494. MpUserPointsDetail::TYPE_CHAT,
  495. $apiType,
  496. ''
  497. );
  498. } catch (\Throwable $e) {
  499. dLog('points')->warning('token明细记录异常(不影响主流程): ' . $e->getMessage(), [
  500. 'uid' => $uid,
  501. 'source' => $chargeInfo['source'] ?? '',
  502. ]);
  503. }
  504. }
  505. /**
  506. * 拆分剧本内容并校验章节总数与标题连续性
  507. *
  508. * @param string $content
  509. * @param int $episodeNum
  510. * @return void
  511. */
  512. private function validateGenerateTextChapters($content, $episodeNum)
  513. {
  514. $chapters = splitContent($content);
  515. if (count($chapters) !== $episodeNum) {
  516. Utils::throwError('20003:章节总数与集数不一致,请检查上传内容');
  517. }
  518. if (empty($chapters)) {
  519. return;
  520. }
  521. // 先尝试从标题正则中解析序号,确认是否从1开始连续递增
  522. $numbers = [];
  523. $unparsedIndex = null;
  524. foreach ($chapters as $index => $chapter) {
  525. $num = $this->parseChapterNumber($chapter['title']);
  526. if ($num === null) {
  527. $unparsedIndex = $index;
  528. break;
  529. }
  530. $numbers[] = $num;
  531. }
  532. if ($unparsedIndex === null) {
  533. $expected = 1;
  534. foreach ($numbers as $index => $num) {
  535. if ($num !== $expected) {
  536. $title = mb_substr(trim((string)$chapters[$index]['title']), 0, 40);
  537. Utils::throwError('20003:章节序号不连续:第' . ($index + 1) . '个章节“' . $title . '”序号为' . $num . ',预期为' . $expected);
  538. }
  539. $expected++;
  540. }
  541. return;
  542. }
  543. // 标题格式无法用正则确认时,交给模型分析
  544. $titles = array_column($chapters, 'title');
  545. $aiResult = $this->validateChapterSequenceByAI($titles);
  546. if ($aiResult['valid'] === false) {
  547. $badIndex = $aiResult['invalid_index'] ?: $unparsedIndex + 1;
  548. if (isset($chapters[$badIndex - 1])) {
  549. $title = mb_substr(trim((string)$chapters[$badIndex - 1]['title']), 0, 40);
  550. Utils::throwError('20003:章节序号不连续:第' . $badIndex . '个章节“' . $title . '”序号异常,请检查');
  551. }
  552. Utils::throwError('20003:章节序号不连续,请检查章节标题格式');
  553. }
  554. if ($aiResult['valid'] === null) {
  555. if (isset($chapters[$unparsedIndex])) {
  556. $title = mb_substr(trim((string)$chapters[$unparsedIndex]['title']), 0, 40);
  557. Utils::throwError('20003:无法确认第' . ($unparsedIndex + 1) . '个章节“' . $title . '”的章节序号,请检查标题格式');
  558. }
  559. Utils::throwError('20003:无法确认章节标题连续性,请检查章节标题格式');
  560. }
  561. }
  562. /**
  563. * 从章节标题中解析序号,支持阿拉伯数字和中文数字
  564. *
  565. * @param string $title
  566. * @return int|null
  567. */
  568. private function parseChapterNumber($title)
  569. {
  570. if (!preg_match('/第\s*([一二两三四五六七八九十百千万0-9]+)\s*[章节集幕场回话]/u', $title, $match)) {
  571. return null;
  572. }
  573. return $this->convertChineseNumber($match[1]);
  574. }
  575. /**
  576. * 中文数字转阿拉伯数字(支持到千)
  577. *
  578. * @param string $numStr
  579. * @return int
  580. */
  581. private function convertChineseNumber($numStr)
  582. {
  583. if (preg_match('/^\d+$/', $numStr)) {
  584. return (int)$numStr;
  585. }
  586. $map = [
  587. '零' => 0,
  588. '一' => 1,
  589. '二' => 2,
  590. '两' => 2,
  591. '三' => 3,
  592. '四' => 4,
  593. '五' => 5,
  594. '六' => 6,
  595. '七' => 7,
  596. '八' => 8,
  597. '九' => 9
  598. ];
  599. $total = 0;
  600. $section = 0;
  601. $length = mb_strlen($numStr);
  602. for ($i = 0; $i < $length; $i++) {
  603. $char = mb_substr($numStr, $i, 1);
  604. if (isset($map[$char])) {
  605. $section = $map[$char];
  606. } elseif ($char === '十') {
  607. $total += $section === 0 ? 10 : $section * 10;
  608. $section = 0;
  609. } elseif ($char === '百') {
  610. $total += $section === 0 ? 100 : $section * 100;
  611. $section = 0;
  612. } elseif ($char === '千') {
  613. $total += $section === 0 ? 1000 : $section * 1000;
  614. $section = 0;
  615. }
  616. }
  617. return $total + $section;
  618. }
  619. /**
  620. * 用 deepseek-v4-flash 非流式判断章节标题是否从1开始连续编号
  621. *
  622. * @param array $titles
  623. * @return array{valid: bool|null, invalid_index: int|null}
  624. */
  625. private function validateChapterSequenceByAI($titles)
  626. {
  627. $titleLines = [];
  628. foreach (array_slice($titles, 0, 200) as $index => $title) {
  629. $titleLines[] = ($index + 1) . '. ' . mb_substr(trim((string)$title), 0, 80);
  630. }
  631. $result = [
  632. 'valid' => null,
  633. 'invalid_index' => null
  634. ];
  635. $post_data = [
  636. 'model' => 'deepseek-v4-flash',
  637. 'messages' => [
  638. [
  639. 'role' => 'system',
  640. 'content' => '你是剧本章节校验助手。用户会给出章节标题列表,请判断这些标题中的编号是否从第1章/第1集开始连续递增,支持阿拉伯数字和中文数字。只输出 JSON,格式为 {"valid":true};若不连续则输出 {"valid":false,"invalid_index":N},其中 N 是第一个序号异常的章节序号(从1开始),不要输出其他内容。',
  641. ],
  642. [
  643. 'role' => 'user',
  644. 'content' => implode("\n", $titleLines),
  645. ],
  646. ],
  647. 'temperature' => 0,
  648. 'frequency_penalty' => 0,
  649. 'presence_penalty' => 0,
  650. 'stream' => false,
  651. ];
  652. try {
  653. $result = $this->chatOnly($post_data, 8);
  654. $content = trim((string)($result['fullContent'] ?? ''));
  655. if (preg_match('/"valid"\s*:\s*(true|false)/i', $content, $match)) {
  656. $result['valid'] = strtolower($match[1]) === 'true';
  657. }
  658. if (preg_match('/"invalid_index"\s*:\s*(\d+)/i', $content, $match)) {
  659. $result['invalid_index'] = (int)$match[1];
  660. }
  661. // 仅记录 token 使用明细(不扣积分):该校验为流程内的额外模型调用
  662. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  663. 'model' => 'deepseek-v4-flash',
  664. 'source' => 'validateChapterSequenceByAI',
  665. ], 'deepseek-v4-flash');
  666. } catch (\Exception $e) {
  667. dLog('deepseek')->error('章节连续性AI校验失败: ' . $e->getMessage());
  668. }
  669. return $result;
  670. }
  671. /**
  672. * 通用文生文(流式版本)- newGenerateText 的 stream=1 分支
  673. * 支持与 newGenerateText 相同的参数(模板/剧本/JSON输出/图片输入),
  674. * 输出格式与 generateText 一致:yield type=content / reasoning / done
  675. *
  676. * @param array $data 请求参数
  677. * @return \Generator
  678. */
  679. public function newGenerateTextStream($data, $existingTask = null) {
  680. $model = getProp($data, 'model', 'deepseek-v4-pro');
  681. $messages = getProp($data, 'messages', []);
  682. $systemPrompt = getProp($data, 'system_prompt', '');
  683. $prompt = getProp($data, 'prompt', '');
  684. $images = getProp($data, 'images', []);
  685. $imageUrls = getProp($data, 'image_urls', []);
  686. $responseFormat = getProp($data, 'response_format', 'text');
  687. $templateId = getProp($data, 'template_id', 0);
  688. $script_id = getProp($data, 'script_id', 0);
  689. $sequence = getProp($data, 'sequence', 0);
  690. $generateTaskId = 0;
  691. // 异步 worker 场景直接使用任务记录中的用户,避免命令行下无登录上下文
  692. $uid = $existingTask ? (int)$existingTask->uid : (int)Site::getUid();
  693. if ($script_id > 0 && !$existingTask) {
  694. $runningTask = DB::table('mp_script_generate_tasks')
  695. ->where('uid', $uid)
  696. ->where('script_id', $script_id)
  697. ->orderByDesc('id')
  698. ->first();
  699. if ($runningTask && in_array(getProp($runningTask, 'status'), ['pending', 'processing'])) {
  700. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  701. }
  702. }
  703. // 如果提供了script_id,从数据库获取剧本内容作为原文
  704. $originalContent = '';
  705. $hasValidScript = false;
  706. $rawPrompt = $prompt; // 保存用户原始输入,供模板一致性判断
  707. if ($script_id > 0) {
  708. $script = DB::table('mp_scripts')
  709. ->where('id', $script_id)
  710. ->where('is_deleted', 0)
  711. ->first();
  712. if (!$script) {
  713. Utils::throwError('20003:剧本不存在或已删除');
  714. }
  715. $originalContent = $script->content ?? '';
  716. if (empty($originalContent)) {
  717. Utils::throwError('20003:剧本内容为空');
  718. }
  719. $hasValidScript = true;
  720. if (!empty($prompt)) {
  721. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  722. } else {
  723. $prompt = "原文内容:\n" . $originalContent;
  724. }
  725. }
  726. // 如果提供了template_id,从数据库获取template_prompt
  727. if ($templateId > 0) {
  728. $template = DB::table('mp_prompt_templates')
  729. ->where('id', $templateId)
  730. ->where('is_deleted', 0)
  731. ->first();
  732. if (!$template) {
  733. Utils::throwError('20003:模板不存在或已删除');
  734. }
  735. $templatePrompt = $template->template_prompt ?? '';
  736. if (!empty($templatePrompt)) {
  737. // 模板提示词与用户输入基本一致时只保留一个,避免重复提示词
  738. // 剧本模式下当前 prompt 含原文内容需保留,其余情况以模板内容为准
  739. $trimmedRawPrompt = trim((string)$rawPrompt);
  740. if ($trimmedRawPrompt !== '' && mb_strtolower($trimmedRawPrompt) === mb_strtolower(trim($templatePrompt))) {
  741. if (!$hasValidScript) {
  742. $prompt = $templatePrompt;
  743. }
  744. } elseif (!empty($prompt)) {
  745. $prompt = $templatePrompt . "\n\n" . $prompt;
  746. } else {
  747. $prompt = $templatePrompt;
  748. }
  749. }
  750. }
  751. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  752. if (empty($messages)) {
  753. $messages = [];
  754. if (!empty($systemPrompt)) {
  755. $messages[] = [
  756. 'role' => 'system',
  757. 'content' => $systemPrompt
  758. ];
  759. }
  760. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  761. $userMessage = [
  762. 'role' => 'user',
  763. 'content' => []
  764. ];
  765. if (!empty($prompt)) {
  766. $userMessage['content'][] = [
  767. 'type' => 'text',
  768. 'text' => $prompt
  769. ];
  770. }
  771. if (!empty($images)) {
  772. if (!is_array($images)) {
  773. $images = [$images];
  774. }
  775. foreach ($images as $image) {
  776. $imageBase64 = $this->processImageToBase64($image);
  777. if ($imageBase64) {
  778. $userMessage['content'][] = [
  779. 'type' => 'image_url',
  780. 'image_url' => [
  781. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  782. ]
  783. ];
  784. }
  785. }
  786. }
  787. if (!empty($imageUrls)) {
  788. if (!is_array($imageUrls)) {
  789. $imageUrls = [$imageUrls];
  790. }
  791. foreach ($imageUrls as $url) {
  792. if (!empty($url)) {
  793. $userMessage['content'][] = [
  794. 'type' => 'image_url',
  795. 'image_url' => [
  796. 'url' => $url
  797. ]
  798. ];
  799. }
  800. }
  801. }
  802. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  803. $userMessage['content'] = $userMessage['content'][0]['text'];
  804. }
  805. $messages[] = $userMessage;
  806. }
  807. }
  808. if (empty($messages)) {
  809. Utils::throwError('20003:请提供有效的对话内容');
  810. }
  811. // 模型兼容性处理
  812. $thinkingMode = getProp($data, 'thinking', 'disabled');
  813. $reasoningEffort = getProp($data, 'reasoning_effort', 'high');
  814. if ($model === 'deepseek-chat') {
  815. $model = 'deepseek-v4-flash';
  816. $thinkingMode = 'disabled';
  817. } elseif ($model === 'deepseek-reasoner') {
  818. $model = 'deepseek-v4-flash';
  819. $thinkingMode = 'enabled';
  820. }
  821. // 构建请求参数(流式)
  822. $post_data = [
  823. 'model' => $model,
  824. 'messages' => $messages,
  825. 'temperature' => getProp($data, 'temperature', 1),
  826. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  827. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  828. 'thinking' => ['type' => $thinkingMode],
  829. 'stream' => true
  830. ];
  831. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  832. if (isset($data['top_p'])) {
  833. $post_data['top_p'] = $data['top_p'];
  834. }
  835. // response_format=json 时附加 JSON 说明与响应格式(与 newGenerateText 一致)
  836. if ($responseFormat === 'json') {
  837. $hasJsonKeyword = false;
  838. foreach ($post_data['messages'] as $message) {
  839. if (isset($message['content'])) {
  840. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  841. if (stripos($content, 'json') !== false) {
  842. $hasJsonKeyword = true;
  843. break;
  844. }
  845. }
  846. }
  847. if (!$hasJsonKeyword) {
  848. $lastMessageIndex = count($post_data['messages']) - 1;
  849. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  850. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  851. if (is_string($lastContent)) {
  852. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  853. } elseif (is_array($lastContent)) {
  854. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  855. if ($contentPart['type'] === 'text') {
  856. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  857. break;
  858. }
  859. }
  860. }
  861. }
  862. }
  863. $post_data['response_format'] = ['type' => 'json_object'];
  864. }
  865. // 如果提供了script_id,创建剧本资产生成任务
  866. if ($script_id > 0) {
  867. if ($existingTask) {
  868. // 异步 worker:接管已创建的 pending 任务,不再新建
  869. $generateTaskId = (int)$existingTask->id;
  870. } else {
  871. // 同步调用:保持原行为,创建 processing 任务
  872. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  873. 'uid' => $uid,
  874. 'script_id' => $script_id,
  875. 'sequence' => $sequence,
  876. 'status' => 'processing',
  877. 'prompt' => getProp($data, 'prompt', ''),
  878. 'started_at' => date('Y-m-d H:i:s'),
  879. 'created_at' => date('Y-m-d H:i:s'),
  880. 'updated_at' => date('Y-m-d H:i:s')
  881. ]);
  882. }
  883. }
  884. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  885. if ($hasValidScript) {
  886. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  887. }
  888. // 根据模型类型选择流式实现
  889. $streamGenerator = $this->dispatchStreamByModel($post_data);
  890. // 流式输出包装:done 时更新任务状态、扣费并保存对话记录
  891. return $this->wrapNewGenerateTextStream($streamGenerator, [
  892. 'uid' => $uid,
  893. 'model' => $model,
  894. 'generate_task_id' => $generateTaskId,
  895. 'has_valid_script' => $hasValidScript,
  896. 'script_id' => $script_id,
  897. 'sequence' => $sequence,
  898. 'original_prompt' => getProp($data, 'prompt', ''),
  899. 'response_format' => $responseFormat,
  900. ]);
  901. }
  902. /**
  903. * 流式生成收尾包装:done 时更新剧本资产生成任务、扣除积分并保存对话记录
  904. *
  905. * @param \Generator $generator
  906. * @param array $ctx
  907. * @return \Generator
  908. */
  909. private function wrapNewGenerateTextStream(\Generator $generator, array $ctx): \Generator
  910. {
  911. $fullContent = '';
  912. $usage = [];
  913. $finished = false;
  914. try {
  915. foreach ($generator as $chunk) {
  916. if (isset($chunk['type']) && $chunk['type'] === 'content') {
  917. $fullContent .= (string)getProp($chunk, 'content', '');
  918. }
  919. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  920. $fullContent = (string)getProp($chunk, 'full_content', $fullContent);
  921. $usage = getProp($chunk, 'usage', []);
  922. // 流式场景下部分模型/中转站不强制 JSON 输出,兜底提取标准 JSON
  923. if (($ctx['response_format'] ?? 'text') === 'json') {
  924. $fullContent = $this->extractJsonContent($fullContent);
  925. }
  926. $finished = true;
  927. // 保存对话记录并将 records 附加到 done 消息(无论 script_id 是否有值都返回 records 数组)
  928. $chunk['records'] = [];
  929. if (!empty($ctx['script_id'])) {
  930. try {
  931. $now = now();
  932. // 两条对话记录(user/assistant)在同一事务内写入,保证原子性
  933. $chunk['records'] = DB::transaction(function () use ($ctx, $fullContent, $now) {
  934. DB::table('mp_script_records')->insert([
  935. [
  936. 'uid' => $ctx['uid'],
  937. 'script_id' => $ctx['script_id'],
  938. 'sequence' => $ctx['sequence'],
  939. 'role' => 'user',
  940. 'content' => $ctx['original_prompt'],
  941. 'created_at' => $now,
  942. 'updated_at' => $now,
  943. ],
  944. [
  945. 'uid' => $ctx['uid'],
  946. 'script_id' => $ctx['script_id'],
  947. 'sequence' => $ctx['sequence'],
  948. 'role' => 'assistant',
  949. 'content' => $fullContent,
  950. 'created_at' => $now,
  951. 'updated_at' => $now,
  952. ],
  953. ]);
  954. return DB::table('mp_script_records')
  955. ->where('uid', $ctx['uid'])
  956. ->where('script_id', $ctx['script_id'])
  957. ->where('sequence', $ctx['sequence'])
  958. ->orderBy('id', 'desc')
  959. ->limit(2)
  960. ->get()
  961. ->map(function ($record) {
  962. return [
  963. 'rid' => $record->id,
  964. 'script_id' => $record->script_id,
  965. 'sequence' => $record->sequence,
  966. 'role' => $record->role,
  967. 'content' => $record->content,
  968. 'created_at' => $record->created_at,
  969. ];
  970. })
  971. ->reverse()
  972. ->values()
  973. ->toArray();
  974. });
  975. } catch (\Exception $e) {
  976. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  977. $chunk['records'] = [];
  978. }
  979. }
  980. }
  981. yield $chunk;
  982. }
  983. if ($finished) {
  984. // 任务状态与扣费在同一事务内:扣费失败则任务状态一并回滚,由外层 catch 置为 failed
  985. DB::transaction(function () use ($ctx, $fullContent, $usage) {
  986. if (!empty($ctx['generate_task_id'])) {
  987. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  988. 'status' => 'success',
  989. 'result' => $fullContent,
  990. 'completed_at' => date('Y-m-d H:i:s'),
  991. 'updated_at' => date('Y-m-d H:i:s'),
  992. ]);
  993. }
  994. if ($ctx['has_valid_script'] && $fullContent !== '') {
  995. $this->chargeChatSuccess($ctx['uid'], $this->pointsService->getTokensFromUsage($usage), [
  996. 'model' => $ctx['model'],
  997. 'script_id' => $ctx['script_id'],
  998. 'sequence' => $ctx['sequence'],
  999. 'source' => 'newGenerateText',
  1000. ]);
  1001. }
  1002. });
  1003. // JSON 输出结果的安全校验/修复与观察(事务外执行,不改变 result 与 SSE 推送内容)
  1004. if (!empty($ctx['generate_task_id'])) {
  1005. $this->guardScriptGenerateJsonResult(
  1006. (int)$ctx['generate_task_id'],
  1007. (int)($ctx['script_id'] ?? 0),
  1008. (int)($ctx['uid'] ?? 0),
  1009. (string)$fullContent,
  1010. (string)($ctx['response_format'] ?? '')
  1011. );
  1012. }
  1013. }
  1014. } catch (\Throwable $e) {
  1015. if (!empty($ctx['generate_task_id'])) {
  1016. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  1017. 'status' => 'failed',
  1018. 'error_message' => $e->getMessage(),
  1019. 'completed_at' => date('Y-m-d H:i:s'),
  1020. 'updated_at' => date('Y-m-d H:i:s'),
  1021. ]);
  1022. }
  1023. yield [
  1024. 'type' => 'error',
  1025. 'message' => $e->getMessage(),
  1026. ];
  1027. }
  1028. }
  1029. /**
  1030. * 从模型输出中提取标准 JSON(剥离 markdown 代码块及前后说明文字)
  1031. *
  1032. * @param string $content
  1033. * @return string
  1034. */
  1035. private function extractJsonContent(string $content): string
  1036. {
  1037. $content = trim($content);
  1038. if ($content === '') {
  1039. return $content;
  1040. }
  1041. // 剥离 ```json ... ``` 代码块
  1042. if (preg_match('/```(?:json)?\s*(.*?)```/s', $content, $m)) {
  1043. $content = trim($m[1]);
  1044. }
  1045. // 提取第一个 { 到最后一个 } 之间的内容(去除前后说明文字)
  1046. $first = strpos($content, '{');
  1047. $last = strrpos($content, '}');
  1048. if ($first !== false && $last !== false && $last > $first) {
  1049. $content = substr($content, $first, $last - $first + 1);
  1050. }
  1051. // 校验是否为合法 JSON,非法则原样返回(不强行截断)
  1052. json_decode($content, true);
  1053. if (json_last_error() !== JSON_ERROR_NONE) {
  1054. return trim($content);
  1055. }
  1056. return $content;
  1057. }
  1058. /**
  1059. * 剧本资产生成结果的 JSON 安全校验/修复与观察
  1060. *
  1061. * 规则:
  1062. * - result 永远保留模型原文,本方法不修改 result;
  1063. * - 仅当原文非法 JSON 且 JsonSafeRepair 安全修复成功时,才把修复后的标准
  1064. * JSON 写入 mp_script_generate_tasks.json_result;
  1065. * - 每次生成结果都写一条 system_logs(channel=script_generate_json),
  1066. * 用于观察非法 JSON 的发生率与修复率。
  1067. *
  1068. * @param int $taskId 剧本资产生成任务 ID
  1069. * @param int $scriptId 剧本 ID
  1070. * @param int $uid 用户 ID
  1071. * @param string $raw 已落库的 result 原文
  1072. * @param string $responseFormat 请求的 response_format
  1073. * @return void
  1074. */
  1075. private function guardScriptGenerateJsonResult(int $taskId, int $scriptId, int $uid, string $raw, string $responseFormat): void
  1076. {
  1077. if ($taskId <= 0 || $raw === '') {
  1078. return;
  1079. }
  1080. // 仅对"要求 JSON 输出"或"内容明显是 JSON"的结果做校验,避免误伤普通文本结果
  1081. $trimmed = ltrim($raw);
  1082. $looksLikeJson = $responseFormat === 'json'
  1083. || (isset($trimmed[0]) && ($trimmed[0] === '{' || $trimmed[0] === '['));
  1084. if (!$looksLikeJson) {
  1085. return;
  1086. }
  1087. $repair = JsonSafeRepair::repair($raw);
  1088. $common = [
  1089. 'task_id' => $taskId,
  1090. 'script_id' => $scriptId,
  1091. 'uid' => $uid,
  1092. 'raw_length' => strlen($raw),
  1093. ];
  1094. if ($repair['ok'] && $repair['json'] !== $raw) {
  1095. // 原文非法但安全修复成功:修复版另存 json_result,result 仍保留原文
  1096. DB::table('mp_script_generate_tasks')->where('id', $taskId)->update([
  1097. 'json_result' => $repair['json'],
  1098. 'updated_at' => date('Y-m-d H:i:s'),
  1099. ]);
  1100. logDB('script_generate_json', 'warning', '生成JSON修复成功', $common + [
  1101. 'json_state' => 'repaired',
  1102. 'json_length' => strlen((string)$repair['json']),
  1103. 'removed_count' => count($repair['removed_positions']),
  1104. 'removed_positions' => $repair['removed_positions'],
  1105. ]);
  1106. return;
  1107. }
  1108. if ($repair['ok']) {
  1109. // 原文本身就是合法 JSON
  1110. logDB('script_generate_json', 'info', '生成JSON校验通过', $common + [
  1111. 'json_state' => 'valid',
  1112. ]);
  1113. return;
  1114. }
  1115. // 非法 JSON 且不在安全修复范围内:保留原文,只记录观察日志
  1116. logDB('script_generate_json', 'error', '生成JSON修复失败', $common + [
  1117. 'json_state' => 'repair_failed',
  1118. 'reason' => $repair['reason'],
  1119. ]);
  1120. }
  1121. /**
  1122. * 创建剧本资产生成异步任务(stream=1 + script_id 走异步任务模式)
  1123. *
  1124. * @param array $data 原请求参数
  1125. * @return int 任务ID
  1126. */
  1127. public function createScriptGenerateAsyncTask(array $data): int
  1128. {
  1129. $script_id = (int)getProp($data, 'script_id', 0);
  1130. if ($script_id <= 0) {
  1131. Utils::throwError('20003:缺少剧本ID');
  1132. }
  1133. $uid = (int)Site::getUid();
  1134. // 与同步逻辑一致:同一剧本存在生成中任务时直接拒绝
  1135. $runningTask = DB::table('mp_script_generate_tasks')
  1136. ->where('uid', $uid)
  1137. ->where('script_id', $script_id)
  1138. ->orderByDesc('id')
  1139. ->first();
  1140. if ($runningTask && in_array(getProp($runningTask, 'status'), ['pending', 'processing'])) {
  1141. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  1142. }
  1143. // 前置校验剧本存在且内容非空,避免创建无效任务
  1144. $script = DB::table('mp_scripts')
  1145. ->where('id', $script_id)
  1146. ->where('is_deleted', 0)
  1147. ->first();
  1148. if (!$script) {
  1149. Utils::throwError('20003:剧本不存在或已删除');
  1150. }
  1151. if (empty($script->content)) {
  1152. Utils::throwError('20003:剧本内容为空');
  1153. }
  1154. // newGenerateText 请求不含上传文件对象,images/image_urls 以字符串形式传入,可直接序列化
  1155. $paramsJson = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  1156. if ($paramsJson === false) {
  1157. Utils::throwError('20003:请求参数序列化失败');
  1158. }
  1159. $now = date('Y-m-d H:i:s');
  1160. return (int)DB::table('mp_script_generate_tasks')->insertGetId([
  1161. 'uid' => $uid,
  1162. 'script_id' => $script_id,
  1163. 'sequence' => (int)getProp($data, 'sequence', 0),
  1164. 'status' => 'pending',
  1165. 'prompt' => (string)getProp($data, 'prompt', ''),
  1166. 'request_params' => $paramsJson,
  1167. 'started_at' => $now,
  1168. 'created_at' => $now,
  1169. 'updated_at' => $now,
  1170. ]);
  1171. }
  1172. /**
  1173. * 供 SSE 轮询:查询任务状态与增量 chunks
  1174. *
  1175. * @param int $taskId
  1176. * @param int $uid 当前登录用户,防越权
  1177. * @param int $afterSeq 已推送的最大 seq
  1178. * @return array{found:bool, task:?object, chunks:array, status:?string, error_message:?string}
  1179. */
  1180. public function pollScriptGenerateTask(int $taskId, int $uid, int $afterSeq = -1): array
  1181. {
  1182. $task = DB::table('mp_script_generate_tasks')
  1183. ->where('id', $taskId)
  1184. ->where('uid', $uid)
  1185. ->first();
  1186. if (!$task) {
  1187. return ['found' => false, 'task' => null, 'chunks' => [], 'status' => null, 'error_message' => null];
  1188. }
  1189. $rows = DB::table('mp_script_generate_task_chunks')
  1190. ->where('task_id', $taskId)
  1191. ->where('seq', '>', $afterSeq)
  1192. ->orderBy('seq')
  1193. ->get();
  1194. $chunks = [];
  1195. foreach ($rows as $row) {
  1196. $payload = json_decode((string)$row->payload, true);
  1197. if (is_array($payload)) {
  1198. $chunks[] = $payload;
  1199. }
  1200. }
  1201. return [
  1202. 'found' => true,
  1203. 'task' => $task,
  1204. 'chunks' => $chunks,
  1205. 'status' => (string)$task->status,
  1206. 'error_message' => (string)($task->error_message ?? ''),
  1207. ];
  1208. }
  1209. /**
  1210. * 异步 worker 执行入口:抢占 pending 任务并流式请求大模型
  1211. *
  1212. * 由 text:generate:run 命令调用;worker 内完成 chunks 落库,模型结束后
  1213. * 由流式包装(wrapNewGenerateTextStream)完成 records/扣费/任务状态/json 修复收尾。
  1214. *
  1215. * @param int $taskId
  1216. * @return array{ok:bool, task_id:int, status:?string, seq:int, error:?string}
  1217. */
  1218. public function runScriptGenerateTaskAsync(int $taskId): array
  1219. {
  1220. // 原子抢占:只允许 pending -> processing,避免重复执行
  1221. $claimed = DB::table('mp_script_generate_tasks')
  1222. ->where('id', $taskId)
  1223. ->where('status', 'pending')
  1224. ->update([
  1225. 'status' => 'processing',
  1226. 'started_at' => date('Y-m-d H:i:s'),
  1227. 'updated_at' => date('Y-m-d H:i:s'),
  1228. ]);
  1229. if (!$claimed) {
  1230. return ['ok' => false, 'task_id' => $taskId, 'status' => null, 'seq' => 0, 'error' => '任务已被处理或状态异常'];
  1231. }
  1232. $task = DB::table('mp_script_generate_tasks')->where('id', $taskId)->first();
  1233. if (!$task) {
  1234. return ['ok' => false, 'task_id' => $taskId, 'status' => null, 'seq' => 0, 'error' => '任务不存在'];
  1235. }
  1236. $params = json_decode((string)getProp($task, 'request_params', ''), true);
  1237. if (!is_array($params)) {
  1238. DB::table('mp_script_generate_tasks')->where('id', $taskId)->update([
  1239. 'status' => 'failed',
  1240. 'error_message' => '任务请求参数缺失',
  1241. 'completed_at' => date('Y-m-d H:i:s'),
  1242. 'updated_at' => date('Y-m-d H:i:s'),
  1243. ]);
  1244. return ['ok' => false, 'task_id' => $taskId, 'status' => 'failed', 'seq' => 0, 'error' => '任务请求参数缺失'];
  1245. }
  1246. // 兼容旧参数未带 stream 的情况
  1247. $params['stream'] = 1;
  1248. $seq = 0;
  1249. try {
  1250. $generator = $this->newGenerateTextStream($params, $task);
  1251. foreach ($generator as $chunk) {
  1252. DB::table('mp_script_generate_task_chunks')->insert([
  1253. 'task_id' => $taskId,
  1254. 'seq' => $seq,
  1255. 'chunk_type' => (string)getProp($chunk, 'type', 'content'),
  1256. 'payload' => json_encode($chunk, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE),
  1257. 'created_at' => date('Y-m-d H:i:s'),
  1258. ]);
  1259. $seq++;
  1260. }
  1261. $finalStatus = (string)DB::table('mp_script_generate_tasks')->where('id', $taskId)->value('status');
  1262. return ['ok' => $finalStatus === 'success', 'task_id' => $taskId, 'status' => $finalStatus, 'seq' => $seq, 'error' => null];
  1263. } catch (\Throwable $e) {
  1264. // 兜底:正常流程中 wrap 会自行把任务置为 failed,这里防止未知异常导致任务卡死
  1265. DB::table('mp_script_generate_tasks')->where('id', $taskId)->update([
  1266. 'status' => 'failed',
  1267. 'error_message' => $e->getMessage(),
  1268. 'completed_at' => date('Y-m-d H:i:s'),
  1269. 'updated_at' => date('Y-m-d H:i:s'),
  1270. ]);
  1271. return ['ok' => false, 'task_id' => $taskId, 'status' => 'failed', 'seq' => $seq, 'error' => $e->getMessage()];
  1272. }
  1273. }
  1274. /**
  1275. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  1276. *
  1277. * @param array $data 请求参数
  1278. * @return array 返回结果数组
  1279. */
  1280. public function newGenerateText($data) {
  1281. // stream=1 时改为流式请求大模型(输出格式参考 generateText:yield type=content/reasoning/done)
  1282. if ((int)getProp($data, 'stream', 0) === 1) {
  1283. return $this->newGenerateTextStream($data);
  1284. }
  1285. // 获取请求参数
  1286. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  1287. $messages = getProp($data, 'messages', []);
  1288. $systemPrompt = getProp($data, 'system_prompt', '');
  1289. $prompt = getProp($data, 'prompt', '');
  1290. $images = getProp($data, 'images', []); // 支持多张图片
  1291. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  1292. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  1293. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  1294. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  1295. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  1296. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  1297. $generateTaskId = 0;
  1298. $uid = Site::getUid();
  1299. if ($script_id > 0) {
  1300. $existingTask = DB::table('mp_script_generate_tasks')
  1301. ->where('uid', $uid)
  1302. ->where('script_id', $script_id)
  1303. ->orderByDesc('id')
  1304. ->first();
  1305. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  1306. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  1307. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  1308. }
  1309. }
  1310. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  1311. $originalContent = '';
  1312. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  1313. $rawPrompt = $prompt; // 保存用户原始输入,供模板一致性判断
  1314. if ($script_id > 0) {
  1315. $script = DB::table('mp_scripts')
  1316. ->where('id', $script_id)
  1317. ->where('is_deleted', 0)
  1318. ->first();
  1319. if (!$script) {
  1320. Utils::throwError('20003:剧本不存在或已删除');
  1321. }
  1322. $originalContent = $script->content ?? '';
  1323. if (empty($originalContent)) {
  1324. Utils::throwError('20003:剧本内容为空');
  1325. }
  1326. $hasValidScript = true;
  1327. // 将剧本内容添加到提示词前面
  1328. if (!empty($originalContent)) {
  1329. if (!empty($prompt)) {
  1330. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  1331. } else {
  1332. $prompt = "原文内容:\n" . $originalContent;
  1333. }
  1334. }
  1335. }
  1336. // 新增: 如果提供了template_id,从数据库获取template_prompt
  1337. if ($templateId > 0) {
  1338. $template = DB::table('mp_prompt_templates')
  1339. ->where('id', $templateId)
  1340. ->where('is_deleted', 0)
  1341. ->first();
  1342. if (!$template) {
  1343. Utils::throwError('20003:模板不存在或已删除');
  1344. }
  1345. $templatePrompt = $template->template_prompt ?? '';
  1346. // 将模板提示词和用户输入的prompt组合
  1347. // 模板为准,用户输入作为补充要求
  1348. // 模板提示词与用户输入基本一致时只保留一个,避免重复提示词
  1349. // 剧本模式下当前 prompt 含原文内容需保留,其余情况以模板内容为准
  1350. if (!empty($templatePrompt)) {
  1351. $trimmedRawPrompt = trim((string)$rawPrompt);
  1352. if ($trimmedRawPrompt !== '' && mb_strtolower($trimmedRawPrompt) === mb_strtolower(trim($templatePrompt))) {
  1353. if (!$hasValidScript) {
  1354. $prompt = $templatePrompt;
  1355. }
  1356. } elseif (!empty($prompt)) {
  1357. $prompt = $templatePrompt . "\n\n" . $prompt;
  1358. } else {
  1359. $prompt = $templatePrompt;
  1360. }
  1361. }
  1362. }
  1363. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  1364. if (empty($messages)) {
  1365. $messages = [];
  1366. // 添加系统提示词
  1367. if (!empty($systemPrompt)) {
  1368. $messages[] = [
  1369. 'role' => 'system',
  1370. 'content' => $systemPrompt
  1371. ];
  1372. }
  1373. // 构建用户消息内容(支持文本+图片)
  1374. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1375. $userMessage = [
  1376. 'role' => 'user',
  1377. 'content' => []
  1378. ];
  1379. // 添加文本内容
  1380. if (!empty($prompt)) {
  1381. $userMessage['content'][] = [
  1382. 'type' => 'text',
  1383. 'text' => $prompt
  1384. ];
  1385. }
  1386. // 处理上传的图片文件
  1387. if (!empty($images)) {
  1388. if (!is_array($images)) {
  1389. $images = [$images];
  1390. }
  1391. foreach ($images as $image) {
  1392. $imageBase64 = $this->processImageToBase64($image);
  1393. if ($imageBase64) {
  1394. $userMessage['content'][] = [
  1395. 'type' => 'image_url',
  1396. 'image_url' => [
  1397. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  1398. ]
  1399. ];
  1400. }
  1401. }
  1402. }
  1403. // 处理图片URL
  1404. if (!empty($imageUrls)) {
  1405. if (!is_array($imageUrls)) {
  1406. $imageUrls = [$imageUrls];
  1407. }
  1408. foreach ($imageUrls as $url) {
  1409. if (!empty($url)) {
  1410. $userMessage['content'][] = [
  1411. 'type' => 'image_url',
  1412. 'image_url' => [
  1413. 'url' => $url
  1414. ]
  1415. ];
  1416. }
  1417. }
  1418. }
  1419. // 如果只有文本内容,简化为字符串格式
  1420. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  1421. $userMessage['content'] = $userMessage['content'][0]['text'];
  1422. }
  1423. $messages[] = $userMessage;
  1424. }
  1425. }
  1426. // 验证messages不为空
  1427. if (empty($messages)) {
  1428. Utils::throwError('20003:请提供有效的对话内容');
  1429. }
  1430. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1431. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1432. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1433. if ($model === 'deepseek-chat') {
  1434. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1435. $model = 'deepseek-v4-flash';
  1436. $thinkingMode = 'disabled';
  1437. } elseif ($model === 'deepseek-reasoner') {
  1438. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1439. $model = 'deepseek-v4-flash';
  1440. $thinkingMode = 'enabled';
  1441. }
  1442. // 构建请求参数(非流式)
  1443. $post_data = [
  1444. 'model' => $model,
  1445. 'messages' => $messages,
  1446. 'temperature' => getProp($data, 'temperature', 1),
  1447. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  1448. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  1449. 'thinking' => ['type' => $thinkingMode],
  1450. 'stream' => false // 非流式输出
  1451. ];
  1452. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1453. // 添加可选参数
  1454. if (isset($data['top_p'])) {
  1455. $post_data['top_p'] = $data['top_p'];
  1456. }
  1457. // 新增: 根据response_format设置响应格式
  1458. if ($responseFormat === 'json') {
  1459. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  1460. $hasJsonKeyword = false;
  1461. foreach ($post_data['messages'] as $message) {
  1462. if (isset($message['content'])) {
  1463. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  1464. if (stripos($content, 'json') !== false) {
  1465. $hasJsonKeyword = true;
  1466. break;
  1467. }
  1468. }
  1469. }
  1470. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  1471. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  1472. if (!$hasJsonKeyword) {
  1473. $lastMessageIndex = count($post_data['messages']) - 1;
  1474. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  1475. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  1476. // 如果content是字符串,直接追加
  1477. if (is_string($lastContent)) {
  1478. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  1479. }
  1480. // 如果content是数组(包含文本和图片),在文本部分追加
  1481. else if (is_array($lastContent)) {
  1482. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  1483. if ($contentPart['type'] === 'text') {
  1484. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  1485. break;
  1486. }
  1487. }
  1488. }
  1489. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  1490. }
  1491. }
  1492. // 设置response_format参数(所有支持的模型)
  1493. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1494. // DeepSeek模型
  1495. $post_data['response_format'] = ['type' => 'json_object'];
  1496. } else if (in_array($model, $this->gpt_text_models)) {
  1497. // GPT模型
  1498. $post_data['response_format'] = ['type' => 'json_object'];
  1499. } else if (in_array($model, $this->valid_text_models)) {
  1500. // 火山引擎模型
  1501. $post_data['response_format'] = ['type' => 'json_object'];
  1502. }
  1503. }
  1504. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  1505. if ($script_id > 0) {
  1506. $uid = Site::getUid();
  1507. // 创建新的生成任务
  1508. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  1509. 'uid' => $uid,
  1510. 'script_id' => $script_id,
  1511. 'sequence' => $sequence,
  1512. 'status' => 'processing',
  1513. 'prompt' => getProp($data, 'prompt', ''),
  1514. 'started_at' => date('Y-m-d H:i:s'),
  1515. 'created_at' => date('Y-m-d H:i:s'),
  1516. 'updated_at' => date('Y-m-d H:i:s')
  1517. ]);
  1518. }
  1519. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  1520. if ($hasValidScript) {
  1521. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  1522. }
  1523. // 统一分模型调用非流式实现
  1524. try {
  1525. $aiResult = null;
  1526. $result = $this->dispatchChatOnlyByModel($post_data);
  1527. dLog('deepseek')->info('newGenerateText模型调用完成', ['requested_model' => $model]);
  1528. $aiResult = [
  1529. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  1530. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  1531. 'usage' => $result['usage'] ?? [],
  1532. 'model' => $model,
  1533. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  1534. ];
  1535. } catch (\Exception $e) {
  1536. // 生成失败,更新任务状态
  1537. if ($generateTaskId) {
  1538. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1539. 'status' => 'failed',
  1540. 'error_message' => $e->getMessage(),
  1541. 'completed_at' => date('Y-m-d H:i:s'),
  1542. 'updated_at' => date('Y-m-d H:i:s')
  1543. ]);
  1544. }
  1545. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  1546. }
  1547. // 生成成功,更新任务状态
  1548. if ($generateTaskId && $aiResult) {
  1549. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1550. 'status' => 'success',
  1551. 'result' => getProp($aiResult, 'content', ''),
  1552. 'completed_at' => date('Y-m-d H:i:s'),
  1553. 'updated_at' => date('Y-m-d H:i:s')
  1554. ]);
  1555. $aiResult['generate_task_id'] = $generateTaskId;
  1556. // JSON 输出结果的安全校验/修复与观察(不改变 result)
  1557. $this->guardScriptGenerateJsonResult(
  1558. (int)$generateTaskId,
  1559. (int)$script_id,
  1560. (int)$uid,
  1561. (string)getProp($aiResult, 'content', ''),
  1562. (string)$responseFormat
  1563. );
  1564. }
  1565. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  1566. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  1567. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  1568. 'model' => $model,
  1569. 'script_id' => $script_id,
  1570. 'sequence' => $sequence,
  1571. 'source' => 'newGenerateText',
  1572. ]);
  1573. }
  1574. // 新增: 如果提供了script_id,保存对话记录
  1575. if ($script_id > 0 && $aiResult) {
  1576. try {
  1577. $uid = Site::getUid();
  1578. $now = now();
  1579. // 获取用户原始的prompt(不包含剧本内容)
  1580. $originalPrompt = getProp($data, 'prompt', '');
  1581. $recordsToInsert = [
  1582. [
  1583. 'uid' => $uid,
  1584. 'script_id' => $script_id,
  1585. 'sequence' => $sequence,
  1586. 'role' => 'user',
  1587. 'content' => $originalPrompt,
  1588. 'created_at' => $now,
  1589. 'updated_at' => $now,
  1590. ],
  1591. [
  1592. 'uid' => $uid,
  1593. 'script_id' => $script_id,
  1594. 'sequence' => $sequence,
  1595. 'role' => 'assistant',
  1596. 'content' => $aiResult['content'],
  1597. 'created_at' => $now,
  1598. 'updated_at' => $now,
  1599. ]
  1600. ];
  1601. DB::table('mp_script_records')->insert($recordsToInsert);
  1602. // 获取刚插入的记录ID(假设按插入顺序返回)
  1603. $insertedRecords = DB::table('mp_script_records')
  1604. ->where('uid', $uid)
  1605. ->where('script_id', $script_id)
  1606. ->where('sequence', $sequence)
  1607. ->orderBy('id', 'desc')
  1608. ->limit(2)
  1609. ->get()
  1610. ->map(function ($record) {
  1611. return [
  1612. 'rid' => $record->id,
  1613. 'script_id' => $record->script_id,
  1614. 'sequence' => $record->sequence,
  1615. 'role' => $record->role,
  1616. 'content' => $record->content,
  1617. 'created_at' => $record->created_at,
  1618. ];
  1619. })
  1620. ->reverse()
  1621. ->values()
  1622. ->toArray();
  1623. // 将记录信息添加到返回结果中
  1624. $aiResult['records'] = $insertedRecords;
  1625. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  1626. } catch (\Exception $e) {
  1627. // 记录错误但不影响主流程
  1628. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  1629. }
  1630. }
  1631. // 未提供 script_id 或保存失败时,也返回 records 数组(保持返回结构一致)
  1632. if (!isset($aiResult['records'])) {
  1633. $aiResult['records'] = [];
  1634. }
  1635. return $aiResult;
  1636. }
  1637. /**
  1638. * 通用 Gemini 文生文方法(支持流式和非流式)
  1639. *
  1640. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  1641. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  1642. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  1643. * system_prompt 系统提示词(可选)
  1644. * prompt 用户提示词(可选)
  1645. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  1646. * image_urls 图片/视频URL列表(可选,同上)
  1647. * temperature 温度(可选,默认 1)
  1648. * top_p 核采样(可选)
  1649. * max_tokens 最大输出 token(可选,默认 8192)
  1650. * response_format text/json(可选)
  1651. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  1652. * thinking_budget 思考预算(可选,默认 20)
  1653. * stream 是否流式(可选,默认 false)
  1654. *
  1655. * @param array $data 请求参数
  1656. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  1657. */
  1658. public function geminiGenerateText($data) {
  1659. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  1660. $isStream = (bool)getProp($data, 'stream', false);
  1661. if (!in_array($model, $this->gemini_text_models)) {
  1662. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  1663. }
  1664. $requestData = $this->buildGeminiRequestBody($data, $model);
  1665. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  1666. if ($isStream) {
  1667. // 流式返回生成器,成功后记录 token 使用明细(不扣积分)
  1668. return $this->wrapGenerateTextTokenRecord(
  1669. $this->geminiStreamResponse($requestData, $model),
  1670. $this->getCurrentUid(),
  1671. $model,
  1672. 'geminiGenerateText'
  1673. );
  1674. }
  1675. // 非流式:成功后记录 token 使用明细(不扣积分)
  1676. $result = $this->geminiChatOnly($requestData, $model);
  1677. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  1678. 'model' => $model,
  1679. 'source' => 'geminiGenerateText',
  1680. ], $model);
  1681. return $result;
  1682. }
  1683. /**
  1684. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  1685. */
  1686. private function geminiMediaMaxBytes() {
  1687. return 14 * 1024 * 1024;
  1688. }
  1689. /**
  1690. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  1691. */
  1692. private function buildGeminiRequestBody($data, $model) {
  1693. $messages = getProp($data, 'messages', []);
  1694. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  1695. if (empty($messages)) {
  1696. $systemPrompt = getProp($data, 'system_prompt', '');
  1697. $prompt = getProp($data, 'prompt', '');
  1698. $images = getProp($data, 'images', []);
  1699. $imageUrls = getProp($data, 'image_urls', []);
  1700. $messages = [];
  1701. if (!empty($systemPrompt)) {
  1702. $messages[] = [
  1703. 'role' => 'system',
  1704. 'content' => $systemPrompt
  1705. ];
  1706. }
  1707. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1708. $userMessage = ['role' => 'user', 'content' => []];
  1709. if (!empty($prompt)) {
  1710. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  1711. }
  1712. if (!empty($images)) {
  1713. if (!is_array($images)) {
  1714. $images = [$images];
  1715. }
  1716. foreach ($images as $image) {
  1717. $inlineData = $this->processMediaToInlineData($image);
  1718. if ($inlineData) {
  1719. $userMessage['content'][] = [
  1720. 'type' => 'image',
  1721. 'inline_data' => $inlineData
  1722. ];
  1723. }
  1724. }
  1725. }
  1726. if (!empty($imageUrls)) {
  1727. if (!is_array($imageUrls)) {
  1728. $imageUrls = [$imageUrls];
  1729. }
  1730. foreach ($imageUrls as $url) {
  1731. if (!empty($url)) {
  1732. $inlineData = $this->processMediaToInlineData($url);
  1733. if ($inlineData) {
  1734. $userMessage['content'][] = [
  1735. 'type' => 'image',
  1736. 'inline_data' => $inlineData
  1737. ];
  1738. }
  1739. }
  1740. }
  1741. }
  1742. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  1743. $userMessage['content'] = $userMessage['content'][0]['text'];
  1744. }
  1745. $messages[] = $userMessage;
  1746. }
  1747. }
  1748. if (empty($messages)) {
  1749. Utils::throwError('20003:请提供有效的对话内容');
  1750. }
  1751. // 转换为 Gemini contents 格式
  1752. $systemInstruction = '';
  1753. $contents = [];
  1754. foreach ($messages as $message) {
  1755. $role = getProp($message, 'role', 'user');
  1756. $content = getProp($message, 'content', '');
  1757. if ($role === 'system') {
  1758. if (is_array($content)) {
  1759. $systemInstruction = $this->extractGeminiTextFromParts($content);
  1760. } else {
  1761. $systemInstruction = (string)$content;
  1762. }
  1763. continue;
  1764. }
  1765. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  1766. $parts = [];
  1767. if (is_array($content)) {
  1768. foreach ($content as $part) {
  1769. $partType = getProp($part, 'type', 'text');
  1770. if ($partType === 'text') {
  1771. $text = (string)getProp($part, 'text', '');
  1772. if ($text !== '') {
  1773. $parts[] = ['text' => $text];
  1774. }
  1775. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  1776. if (in_array($partType, ['image_url', 'video_url'])) {
  1777. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  1778. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  1779. } elseif (isset($part['inline_data'])) {
  1780. // 已处理过的 inline_data 直接使用
  1781. $parts[] = ['inline_data' => $part['inline_data']];
  1782. continue;
  1783. } else {
  1784. $url = '';
  1785. }
  1786. $inlineData = $this->processMediaToInlineData($url);
  1787. if ($inlineData) {
  1788. $parts[] = ['inline_data' => $inlineData];
  1789. }
  1790. }
  1791. }
  1792. } else {
  1793. $text = (string)$content;
  1794. if ($text !== '') {
  1795. $parts[] = ['text' => $text];
  1796. }
  1797. }
  1798. if (!empty($parts)) {
  1799. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  1800. }
  1801. }
  1802. if (empty($contents)) {
  1803. Utils::throwError('20003:请提供有效的对话内容');
  1804. }
  1805. // 构建生成配置
  1806. $generationConfig = [];
  1807. if (getProp($data, 'temperature', null) !== null) {
  1808. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  1809. }
  1810. if (getProp($data, 'top_p', null) !== null) {
  1811. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  1812. }
  1813. if (getProp($data, 'frequency_penalty', null) !== null) {
  1814. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  1815. }
  1816. if (getProp($data, 'presence_penalty', null) !== null) {
  1817. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  1818. }
  1819. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  1820. if ($maxOutputTokens <= 0) {
  1821. $maxOutputTokens = 8192;
  1822. }
  1823. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  1824. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  1825. $maxOutputTokens = 32768;
  1826. }
  1827. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  1828. // response_format 映射:text -> text/plain,json -> application/json
  1829. $responseFormat = getProp($data, 'response_format', 'text');
  1830. if (is_array($responseFormat)) {
  1831. $responseFormat = getProp($responseFormat, 'type', 'text');
  1832. }
  1833. if (in_array($responseFormat, ['json', 'json_object'])) {
  1834. $generationConfig['responseMimeType'] = 'application/json';
  1835. } else {
  1836. $generationConfig['responseMimeType'] = 'text/plain';
  1837. }
  1838. $requestData = [
  1839. 'contents' => $contents,
  1840. 'generationConfig' => $generationConfig,
  1841. ];
  1842. if ($systemInstruction !== '') {
  1843. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  1844. }
  1845. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  1846. $thinkingMode = getProp($data, 'thinking', null);
  1847. if (is_array($thinkingMode)) {
  1848. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  1849. }
  1850. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  1851. if ($thinkingMode === null) {
  1852. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  1853. }
  1854. if ($thinkingMode === 'enabled') {
  1855. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  1856. if ($thinkingBudget <= 0) {
  1857. $thinkingBudget = 20;
  1858. }
  1859. $requestData['generationConfig']['thinkingConfig'] = [
  1860. 'thinkingBudget' => $thinkingBudget
  1861. ];
  1862. } elseif ($defaultThinking) {
  1863. // 该模型仅支持思考模式,传 0 会返回 400
  1864. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  1865. } else {
  1866. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  1867. }
  1868. return $requestData;
  1869. }
  1870. /**
  1871. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  1872. *
  1873. * 模型名 -> env 变量名映射:
  1874. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  1875. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  1876. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  1877. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  1878. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  1879. */
  1880. private function getGeminiApiKey($model) {
  1881. $map = [
  1882. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  1883. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  1884. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  1885. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  1886. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  1887. ];
  1888. if (isset($map[$model])) {
  1889. $key = env($map[$model]);
  1890. if (!empty($key)) {
  1891. return $key;
  1892. }
  1893. }
  1894. return env('GEMINI_API_KEY', '');
  1895. }
  1896. /**
  1897. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  1898. */
  1899. private function geminiChatOnly($requestData, $model) {
  1900. $apiKey = $this->getGeminiApiKey($model);
  1901. if (empty($apiKey)) {
  1902. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1903. }
  1904. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1905. if (isset($requestData['messages'])) {
  1906. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1907. }
  1908. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1909. . '/models/' . $model . ':generateContent';
  1910. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1911. $headers = [
  1912. 'Authorization' => 'Bearer ' . $apiKey,
  1913. 'Content-Type' => 'application/json'
  1914. ];
  1915. $maxRetries = $this->gptRetryTimes();
  1916. $interval = $this->gptRetryInterval();
  1917. $attempt = 0;
  1918. while (true) {
  1919. try {
  1920. $response = $client->post($url, [
  1921. 'json' => $requestData,
  1922. 'headers' => $headers
  1923. ]);
  1924. $responseArr = json_decode($response->getBody()->getContents(), true);
  1925. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  1926. $fullContent = $this->extractGeminiContent($responseArr);
  1927. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  1928. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  1929. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  1930. ? $responseArr['candidates'][0]['finishReason']
  1931. : '';
  1932. return [
  1933. 'fullContent' => $fullContent,
  1934. 'fullReasoningContent' => $fullReasoningContent,
  1935. 'usage' => $usage,
  1936. 'finish_reason' => $finishReason
  1937. ];
  1938. } catch (\Exception $e) {
  1939. $retryable = true;
  1940. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1941. $status = $e->getResponse()->getStatusCode();
  1942. $retryable = $status >= 500 || $status == 429;
  1943. }
  1944. if (!$retryable || $attempt >= $maxRetries) {
  1945. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  1946. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  1947. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  1948. }
  1949. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  1950. 'retry' => $attempt + 1,
  1951. 'max_retries' => $maxRetries,
  1952. 'error' => $e->getMessage()
  1953. ]);
  1954. sleep($interval);
  1955. $attempt++;
  1956. }
  1957. }
  1958. }
  1959. /**
  1960. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  1961. */
  1962. private function geminiStreamResponse($requestData, $model) {
  1963. $apiKey = $this->getGeminiApiKey($model);
  1964. if (empty($apiKey)) {
  1965. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1966. }
  1967. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1968. if (isset($requestData['messages'])) {
  1969. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1970. }
  1971. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1972. . '/models/' . $model . ':generateContent?alt=sse';
  1973. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1974. $headers = [
  1975. 'Authorization' => 'Bearer ' . $apiKey,
  1976. 'Content-Type' => 'application/json'
  1977. ];
  1978. try {
  1979. $response = $client->post($url, [
  1980. 'json' => $requestData,
  1981. 'headers' => $headers,
  1982. 'stream' => true
  1983. ]);
  1984. $body = $response->getBody();
  1985. $fullContent = '';
  1986. $fullReasoningContent = '';
  1987. $usage = [];
  1988. $buffer = '';
  1989. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1990. while (!$body->eof()) {
  1991. $chunk = $body->read(1024);
  1992. $buffer .= $chunk;
  1993. $lines = explode("\n", $buffer);
  1994. $buffer = array_pop($lines);
  1995. foreach ($lines as $line) {
  1996. $line = trim($line);
  1997. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1998. continue;
  1999. }
  2000. $data = substr($line, 6);
  2001. if ($data === '[DONE]') {
  2002. break 2;
  2003. }
  2004. try {
  2005. $json = json_decode($data, true);
  2006. if (json_last_error() !== JSON_ERROR_NONE) {
  2007. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2008. continue;
  2009. }
  2010. // 思考内容(thoughts)
  2011. $thoughts = $this->extractGeminiThoughts($json);
  2012. if ($thoughts !== '') {
  2013. $fullReasoningContent .= $thoughts;
  2014. yield [
  2015. 'type' => 'reasoning',
  2016. 'content' => $thoughts,
  2017. 'full_reasoning' => $fullReasoningContent
  2018. ];
  2019. }
  2020. // 回答内容
  2021. $partText = $this->extractGeminiContent($json);
  2022. if ($partText !== '') {
  2023. $fullContent .= $partText;
  2024. yield [
  2025. 'type' => 'content',
  2026. 'content' => $partText,
  2027. ];
  2028. }
  2029. // 使用统计
  2030. if (isset($json['usageMetadata'])) {
  2031. $usage = $json['usageMetadata'];
  2032. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  2033. }
  2034. } catch (\Exception $e) {
  2035. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2036. continue;
  2037. }
  2038. }
  2039. }
  2040. dLog('deepseek')->info('Gemini流式读取完成', [
  2041. 'content_length' => strlen($fullContent),
  2042. 'reasoning_length' => strlen($fullReasoningContent)
  2043. ]);
  2044. yield [
  2045. 'type' => 'done',
  2046. 'full_content' => $fullContent,
  2047. 'full_reasoning' => $fullReasoningContent,
  2048. 'usage' => $usage
  2049. ];
  2050. } catch (\Exception $e) {
  2051. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  2052. yield [
  2053. 'type' => 'error',
  2054. 'msg' => $e->getMessage(),
  2055. 'code' => $e->getCode()
  2056. ];
  2057. }
  2058. }
  2059. /**
  2060. * 从 Gemini 响应中提取回答文本
  2061. */
  2062. private function extractGeminiContent($responseArr) {
  2063. $text = '';
  2064. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  2065. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  2066. if (isset($part['text'])) {
  2067. $text .= $part['text'];
  2068. }
  2069. }
  2070. }
  2071. return $text;
  2072. }
  2073. /**
  2074. * 从 Gemini 响应中提取思考内容
  2075. */
  2076. private function extractGeminiReasoningContent($responseArr) {
  2077. $reasoning = '';
  2078. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  2079. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  2080. if (isset($thought['text'])) {
  2081. $reasoning .= $thought['text'];
  2082. }
  2083. }
  2084. }
  2085. return $reasoning;
  2086. }
  2087. /**
  2088. * 从 Gemini 流式响应中提取本次增量思考内容
  2089. */
  2090. private function extractGeminiThoughts($responseArr) {
  2091. $thoughts = '';
  2092. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  2093. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  2094. if (isset($thought['text'])) {
  2095. $thoughts .= $thought['text'];
  2096. }
  2097. }
  2098. }
  2099. return $thoughts;
  2100. }
  2101. /**
  2102. * 提取消息数组中的纯文本
  2103. */
  2104. private function extractGeminiTextFromParts($parts) {
  2105. $text = '';
  2106. if (is_array($parts)) {
  2107. foreach ($parts as $part) {
  2108. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  2109. $text .= (string)getProp($part, 'text', '');
  2110. }
  2111. }
  2112. }
  2113. return $text;
  2114. }
  2115. /**
  2116. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  2117. *
  2118. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  2119. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  2120. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  2121. *
  2122. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  2123. * @return array|null ['mime_type' => string, 'data' => string]
  2124. */
  2125. private function processMediaToInlineData($media) {
  2126. if (empty($media)) {
  2127. return null;
  2128. }
  2129. $localPath = null;
  2130. $isTempFile = false;
  2131. try {
  2132. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  2133. if (is_string($media) && strpos($media, 'data:') === 0) {
  2134. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  2135. return [
  2136. 'mime_type' => $matches[1],
  2137. 'data' => $matches[2]
  2138. ];
  2139. }
  2140. return null;
  2141. }
  2142. // 2. 获取本地文件路径
  2143. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  2144. $localPath = $this->downloadMediaToTemp($media);
  2145. $isTempFile = true;
  2146. } elseif (is_string($media)) {
  2147. $localPath = $media;
  2148. } else {
  2149. // Laravel UploadedFile 对象
  2150. $localPath = $media->getRealPath();
  2151. }
  2152. if (!$localPath || !file_exists($localPath)) {
  2153. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  2154. return null;
  2155. }
  2156. $fileSize = filesize($localPath);
  2157. $maxBytes = $this->geminiMediaMaxBytes();
  2158. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  2159. $mimeType = $this->detectMediaMime($localPath);
  2160. $isVideo = strpos($mimeType, 'video/') === 0;
  2161. $needCompress = $fileSize > $maxBytes;
  2162. $duration = 0;
  2163. if ($isVideo) {
  2164. $duration = $this->getMediaDuration($localPath);
  2165. if ($duration > 300) {
  2166. $needCompress = true;
  2167. }
  2168. }
  2169. $finalPath = $localPath;
  2170. $compressedPath = null;
  2171. if ($needCompress && $this->ffmpegAvailable()) {
  2172. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  2173. if ($compressed && file_exists($compressed)) {
  2174. $compressedPath = $compressed;
  2175. if (filesize($compressed) < $fileSize || $isVideo) {
  2176. $finalPath = $compressed;
  2177. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  2178. } else {
  2179. @unlink($compressed);
  2180. $compressedPath = null;
  2181. }
  2182. }
  2183. }
  2184. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  2185. $finalSize = filesize($finalPath);
  2186. if ($finalSize > $maxBytes) {
  2187. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  2188. 'path' => $localPath,
  2189. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  2190. 'limit_mb' => 14
  2191. ]);
  2192. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  2193. }
  2194. // 兜底校验:视频时长超过5分钟且未能压缩成功
  2195. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  2196. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  2197. }
  2198. $data = base64_encode(file_get_contents($finalPath));
  2199. return [
  2200. 'mime_type' => $mimeType,
  2201. 'data' => $data
  2202. ];
  2203. } catch (\App\Exceptions\ApiException $e) {
  2204. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  2205. throw $e;
  2206. } catch (\Exception $e) {
  2207. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  2208. return null;
  2209. } finally {
  2210. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  2211. @unlink($compressedPath);
  2212. }
  2213. if ($isTempFile && $localPath && file_exists($localPath)) {
  2214. @unlink($localPath);
  2215. }
  2216. }
  2217. }
  2218. /**
  2219. * 下载远程多媒体到临时目录
  2220. *
  2221. * @return string|null 本地临时文件路径
  2222. */
  2223. private function downloadMediaToTemp($url) {
  2224. try {
  2225. $tempDir = storage_path('app/temp/gemini');
  2226. if (!is_dir($tempDir)) {
  2227. mkdir($tempDir, 0775, true);
  2228. }
  2229. $extension = 'tmp';
  2230. $pathInfo = parse_url($url, PHP_URL_PATH);
  2231. if ($pathInfo) {
  2232. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  2233. if ($ext && strlen($ext) <= 10) {
  2234. $extension = strtolower($ext);
  2235. }
  2236. }
  2237. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  2238. $client = new Client(['timeout' => 300, 'verify' => false]);
  2239. $response = $client->get($url, ['sink' => $tmpFile]);
  2240. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  2241. @unlink($tmpFile);
  2242. return null;
  2243. }
  2244. return $tmpFile;
  2245. } catch (\Exception $e) {
  2246. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  2247. return null;
  2248. }
  2249. }
  2250. /**
  2251. * 检测多媒体文件 MIME 类型
  2252. */
  2253. private function detectMediaMime($filePath) {
  2254. $imageInfo = @getimagesize($filePath);
  2255. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  2256. return $imageInfo['mime'];
  2257. }
  2258. // 视频按扩展名粗略判断
  2259. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  2260. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  2261. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  2262. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  2263. if (isset($videoExts[$ext])) {
  2264. return $videoExts[$ext];
  2265. }
  2266. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  2267. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  2268. if (isset($imageExts[$ext])) {
  2269. return $imageExts[$ext];
  2270. }
  2271. return 'application/octet-stream';
  2272. }
  2273. /**
  2274. * 获取多媒体时长(秒),非视频或失败返回 0
  2275. */
  2276. private function getMediaDuration($filePath) {
  2277. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  2278. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  2279. $output = trim((string)shell_exec($cmd));
  2280. $duration = (float)$output;
  2281. return $duration > 0 ? $duration : 0;
  2282. }
  2283. /**
  2284. * 检查 ffmpeg 是否可用
  2285. */
  2286. private function ffmpegAvailable() {
  2287. static $available = null;
  2288. if ($available !== null) {
  2289. return $available;
  2290. }
  2291. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2292. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  2293. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  2294. $available = false;
  2295. return $available;
  2296. }
  2297. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  2298. $output = shell_exec($cmd);
  2299. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  2300. return $available;
  2301. }
  2302. /**
  2303. * 使用 ffmpeg 压缩多媒体文件
  2304. *
  2305. * @param string $inputFile 输入文件路径
  2306. * @param bool $isVideo 是否为视频
  2307. * @param float $duration 视频时长(秒),非视频传 0
  2308. * @return string|null 压缩后的文件路径,失败返回 null
  2309. */
  2310. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  2311. try {
  2312. $tempDir = storage_path('app/temp/gemini');
  2313. if (!is_dir($tempDir)) {
  2314. mkdir($tempDir, 0775, true);
  2315. }
  2316. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2317. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  2318. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  2319. if ($isVideo) {
  2320. // 视频:时长超过5分钟则加速压缩到5分钟以内
  2321. $speedFactor = 1.0;
  2322. if ($duration > 300) {
  2323. $speedFactor = $duration / 300;
  2324. }
  2325. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  2326. $finalDuration = $duration / max(1.0, $speedFactor);
  2327. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  2328. $targetBitrate = max(300, min(6000, $targetBitrate));
  2329. $filters = [];
  2330. $filters[] = 'scale=min(1280,iw):-2';
  2331. $filters[] = 'fps=24';
  2332. if ($speedFactor > 1.0) {
  2333. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  2334. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  2335. $fullCount = (int)ceil($speedFactor / 2.0);
  2336. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2337. if ($lastTempo < 0.5) {
  2338. $fullCount++;
  2339. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2340. }
  2341. for ($i = 0; $i < $fullCount; $i++) {
  2342. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  2343. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  2344. }
  2345. }
  2346. $filterStr = implode(',', $filters);
  2347. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  2348. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  2349. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  2350. } else {
  2351. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  2352. $imageInfo = @getimagesize($inputFile);
  2353. $scaleW = 2048;
  2354. $scaleH = 2048;
  2355. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  2356. if ($imageInfo[0] >= $imageInfo[1]) {
  2357. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  2358. $scaleW = 2048;
  2359. } else {
  2360. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  2361. $scaleH = 2048;
  2362. }
  2363. }
  2364. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  2365. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  2366. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  2367. }
  2368. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  2369. $output = shell_exec($cmd);
  2370. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  2371. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  2372. 'input' => $inputFile,
  2373. 'output' => $output
  2374. ]);
  2375. @unlink($outputFile);
  2376. return null;
  2377. }
  2378. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  2379. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  2380. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  2381. ]);
  2382. return $outputFile;
  2383. } catch (\Exception $e) {
  2384. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  2385. return null;
  2386. }
  2387. }
  2388. /**
  2389. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  2390. *
  2391. * @param array $data
  2392. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  2393. */
  2394. public function getScriptGenerateTasks($data) {
  2395. $uid = Site::getUid();
  2396. return DB::table('mp_script_generate_tasks as t')
  2397. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  2398. ->where('t.uid', $uid)
  2399. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  2400. ->orderByDesc('t.id')
  2401. ->paginate(15);
  2402. }
  2403. public function saveScriptChatHistory($data) {
  2404. $uid = Site::getUid();
  2405. $rid = getProp($data, 'rid');
  2406. $script_id = getProp($data, 'script_id');
  2407. $sequence = getProp($data, 'sequence', 0);
  2408. $content = getProp($data, 'content');
  2409. if (!$rid) {
  2410. Utils::throwError('20003:请选择对话记录ID');
  2411. }
  2412. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  2413. if (!$record) {
  2414. Utils::throwError('20003:对话记录不存在');
  2415. }
  2416. if (!$script_id) {
  2417. Utils::throwError('20003:请选择剧本');
  2418. }
  2419. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  2420. if (!$script) {
  2421. Utils::throwError('20003:剧本不存在');
  2422. }
  2423. // 批量插入数据
  2424. return DB::table('mp_script_records')->where('id', $rid)->update([
  2425. 'content' => $content,
  2426. 'updated_at' => date('Y-m-d H:i:s')
  2427. ]);
  2428. }
  2429. /**
  2430. * 获取剧本的历史对话记录
  2431. *
  2432. * @param array $data 请求参数
  2433. * @return array 返回历史记录数组
  2434. */
  2435. public function getScriptChatHistory($data) {
  2436. $uid = Site::getUid();
  2437. $script_id = getProp($data, 'script_id');
  2438. $rid = getProp($data, 'rid');
  2439. $sequence = getProp($data, 'sequence', null);
  2440. if (!$script_id) {
  2441. Utils::throwError('20003:请提供剧本ID');
  2442. }
  2443. // 验证剧本是否存在
  2444. $script = DB::table('mp_scripts')
  2445. ->where('id', $script_id)
  2446. ->where('is_deleted', 0)
  2447. ->first();
  2448. if (!$script) {
  2449. Utils::throwError('20003:剧本不存在');
  2450. }
  2451. // 构建查询
  2452. $query = DB::table('mp_script_records')
  2453. ->where('script_id', $script_id);
  2454. // ->where('uid', $uid);
  2455. // 如果提供了 sequence,则过滤指定剧集
  2456. if ($sequence !== null) {
  2457. $query->where('sequence', $sequence);
  2458. }
  2459. // 记录ID筛选
  2460. if ($rid) {
  2461. $query->where('id', $rid);
  2462. }
  2463. // 查询记录并按 id 正序排序
  2464. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  2465. ->orderBy('created_at', 'asc')
  2466. ->orderBy('id', 'asc')
  2467. ->get()
  2468. ->map(function ($record) {
  2469. return [
  2470. 'rid' => $record->id,
  2471. 'script_id' => $record->script_id,
  2472. 'sequence' => $record->sequence,
  2473. 'role' => $record->role,
  2474. 'content' => $record->content,
  2475. 'products' => $record->products ? json_decode($record->products) : [],
  2476. 'created_at' => $record->created_at,
  2477. ];
  2478. })
  2479. ->toArray();
  2480. return $records;
  2481. }
  2482. /**
  2483. * 处理图片转换为base64
  2484. *
  2485. * @param mixed $image 图片文件对象或文件路径
  2486. * @return string|null base64编码的图片数据
  2487. */
  2488. private function processImageToBase64($image) {
  2489. try {
  2490. // 获取文件路径
  2491. if (is_string($image)) {
  2492. $filePath = $image;
  2493. } else {
  2494. // Laravel UploadedFile 对象
  2495. $filePath = $image->getRealPath();
  2496. }
  2497. if (!file_exists($filePath)) {
  2498. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  2499. return null;
  2500. }
  2501. // 验证是否为图片文件
  2502. $imageInfo = @getimagesize($filePath);
  2503. if ($imageInfo === false) {
  2504. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  2505. return null;
  2506. }
  2507. // 读取图片并转换为base64
  2508. $imageData = file_get_contents($filePath);
  2509. $base64Image = base64_encode($imageData);
  2510. dLog('deepseek')->info('图片转换成功', [
  2511. 'size' => strlen($imageData),
  2512. 'type' => $imageInfo['mime']
  2513. ]);
  2514. return $base64Image;
  2515. } catch (\Exception $e) {
  2516. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  2517. return null;
  2518. }
  2519. }
  2520. private function getArtStylePromptMappings($art_style='')
  2521. {
  2522. // 优先从画风表读取(入库后以表数据为准,保持原返回结构:['画风名' => ['aliases' => [...], 'prompt' => "..."]]
  2523. $dbRows = DB::table('mp_art_styles')
  2524. ->where('is_deleted', 0)
  2525. ->orderBy('id')
  2526. ->get(['art_style', 'aliases', 'prompt']);
  2527. if ($dbRows->isNotEmpty()) {
  2528. $arr = [];
  2529. foreach ($dbRows as $row) {
  2530. $arr[$row->art_style] = [
  2531. 'aliases' => is_string($row->aliases) ? json_decode($row->aliases, true) : [],
  2532. 'prompt' => (string)$row->prompt,
  2533. ];
  2534. }
  2535. if ($art_style) {
  2536. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2537. }
  2538. return $arr;
  2539. }
  2540. $arr = [
  2541. '唯美真人风格' => [
  2542. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2543. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  2544. ],
  2545. '真人古风风格' => [
  2546. 'aliases' => ['真人古风风格', '真人古风'],
  2547. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  2548. ],
  2549. '日系动漫风格' => [
  2550. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2551. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  2552. ],
  2553. '国漫风格' => [
  2554. 'aliases' => ['国漫风格', '国漫'],
  2555. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  2556. ],
  2557. 'Q版卡通风格' => [
  2558. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2559. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  2560. ],
  2561. '简约扁平风格' => [
  2562. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2563. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  2564. ],
  2565. '武侠风格' => [
  2566. 'aliases' => ['武侠风格', '武侠'],
  2567. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  2568. ],
  2569. '古风仙侠风格' => [
  2570. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2571. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  2572. ],
  2573. '新中式水墨风格' => [
  2574. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2575. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  2576. ],
  2577. '写实插画风格' => [
  2578. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2579. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  2580. ],
  2581. '3D卡通风格' => [
  2582. 'aliases' => ['3D卡通风格', '3D卡通'],
  2583. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  2584. ],
  2585. '条漫风格' => [
  2586. 'aliases' => ['条漫风格', '条漫'],
  2587. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  2588. ],
  2589. '赛博朋克风格' => [
  2590. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2591. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  2592. ],
  2593. '暗黑悬疑风格' => [
  2594. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2595. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  2596. ],
  2597. '治愈清新风格' => [
  2598. 'aliases' => ['治愈清新风格', '治愈清新'],
  2599. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  2600. ],
  2601. '3D真人风格' => [
  2602. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  2603. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  2604. ],
  2605. ];
  2606. if($art_style) {
  2607. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2608. }
  2609. return $arr;
  2610. $arr = [
  2611. '唯美真人风格' => [
  2612. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2613. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  2614. 2. 色彩色调
  2615. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  2616. 3. 画质精度
  2617. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  2618. 4. 画面观感
  2619. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  2620. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  2621. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  2622. ],
  2623. '真人古风风格' => [
  2624. 'aliases' => ['真人古风风格', '真人古风'],
  2625. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  2626. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  2627. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  2628. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  2629. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  2630. ],
  2631. '日系动漫风格' => [
  2632. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2633. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  2634. 正向提示词(中文)
  2635. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  2636. 必须遵守规则
  2637. • 全程保持日系动漫风格,不混入其他画风
  2638. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  2639. • 画面适配所选画面比例,构图居中,主体突出
  2640. • 线条干净、色彩统一,不杂乱、不突兀
  2641. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  2642. ],
  2643. '国漫风格' => [
  2644. 'aliases' => ['国漫风格', '国漫'],
  2645. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  2646. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  2647. 必须遵守规则
  2648. • 严格保持国漫画风,不串风格、不混画风
  2649. • 角色形象统一,不随意改变五官、身材、服饰
  2650. • 画面构图稳定,适合漫剧叙事展示
  2651. • 色调统一,不出现脏色、杂色
  2652. 禁止/避免词汇
  2653. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  2654. ],
  2655. 'Q版卡通风格' => [
  2656. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2657. 'prompt' => "风格说明
  2658. 头大身小,造型可爱圆润,简约干净
  2659. 正向提示词(中文)
  2660. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  2661. 必须遵守规则
  2662. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  2663. • 角色造型统一,表情可爱,不诡异
  2664. • 画面简洁清爽,无多余复杂元素
  2665. • 色彩明亮柔和,不刺眼
  2666. 禁止/避免词汇
  2667. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  2668. ],
  2669. '简约扁平风格' => [
  2670. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2671. 'prompt' => "风格说明
  2672. 色块简洁、无复杂渐变,现代极简风
  2673. 正向提示词(中文)
  2674. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  2675. 必须遵守规则
  2676. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  2677. • 构图简洁,主体突出,无多余装饰
  2678. • 色彩统一、干净,不杂乱
  2679. 禁止/避免词汇
  2680. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  2681. ],
  2682. '武侠风格' => [
  2683. 'aliases' => ['武侠风格', '武侠'],
  2684. 'prompt' => "风格说明
  2685. 江湖气息,线条硬朗,动作感强
  2686. 正向提示词(中文)
  2687. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  2688. 必须遵守规则
  2689. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  2690. • 角色形象、服饰、身材比例统一
  2691. • 画面动作自然,不扭曲、不畸形
  2692. 禁止/避免词汇
  2693. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  2694. ],
  2695. '古风仙侠风格' => [
  2696. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2697. 'prompt' => "风格说明
  2698. 飘逸汉服、云雾仙气、唯美空灵
  2699. 正向提示词(中文)
  2700. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  2701. 必须遵守规则
  2702. • 保持古风仙侠统一画风,不混入现代、科幻元素
  2703. • 角色服饰、发型、形象前后一致
  2704. • 场景仙气飘逸,色调清雅统一
  2705. • 画面唯美柔和,不阴暗、不诡异
  2706. 禁止/避免词汇
  2707. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  2708. ],
  2709. '新中式水墨风格' => [
  2710. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2711. 'prompt' => "风格说明
  2712. 淡墨渲染,毛笔笔触,留白意境
  2713. 正向提示词(中文)
  2714. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  2715. 必须遵守规则
  2716. • 严格保持水墨质感,不混入厚涂、写实、卡通
  2717. • 色调淡雅统一,不浓艳杂乱
  2718. • 画面干净有意境,不堆砌元素
  2719. 禁止/避免词汇
  2720. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  2721. ],
  2722. '写实插画风格' => [
  2723. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2724. 'prompt' => "风格说明
  2725. 接近真人比例,光影真实,质感细腻
  2726. 正向提示词(中文)
  2727. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  2728. 必须遵守规则
  2729. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  2730. • 角色五官、身材、服饰高度统一
  2731. • 画面清晰、光影自然、不扭曲
  2732. 禁止/避免词汇
  2733. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  2734. ],
  2735. '3D卡通风格' => [
  2736. 'aliases' => ['3D卡通风格', '3D卡通'],
  2737. 'prompt' => "风格说明
  2738. 3D建模质感,柔和渲染,圆润可爱
  2739. 正向提示词(中文)
  2740. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  2741. 必须遵守规则
  2742. • 保持3D卡通统一质感,不出现2D杂乱线条
  2743. • 角色模型、比例、形象前后一致
  2744. • 画面干净,不模糊、不穿模
  2745. 禁止/避免词汇
  2746. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  2747. ],
  2748. '条漫风格' => [
  2749. 'aliases' => ['条漫风格', '条漫'],
  2750. 'prompt' => "风格说明
  2751. 纵向分镜,上下滑动阅读,轻量化
  2752. 正向提示词(中文)
  2753. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  2754. 必须遵守规则
  2755. • 保持条漫纵向阅读逻辑,构图简洁
  2756. • 画风统一,不混写实、3D、水墨
  2757. • 画面干净,不杂乱
  2758. 禁止/避免词汇
  2759. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  2760. ],
  2761. '赛博朋克风格' => [
  2762. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2763. 'prompt' => "风格说明
  2764. 霓虹灯光、未来都市、暗色调、科技机械
  2765. 正向提示词(中文)
  2766. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  2767. 必须遵守规则
  2768. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  2769. • 色调以暗调+霓虹为主,色彩统一
  2770. • 画面科技感强,不杂乱
  2771. 禁止/避免词汇
  2772. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  2773. ],
  2774. '暗黑悬疑风格' => [
  2775. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2776. 'prompt' => "风格说明
  2777. 低饱和、冷色调、阴影重、神秘压抑
  2778. 正向提示词(中文)
  2779. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  2780. 必须遵守规则
  2781. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  2782. • 画面氛围压抑神秘,但不低俗、不血腥
  2783. • 角色形象统一,不崩坏
  2784. 禁止/避免词汇
  2785. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  2786. ],
  2787. '治愈清新风格' => [
  2788. 'aliases' => ['治愈清新风格', '治愈清新'],
  2789. 'prompt' => "风格说明
  2790. 马卡龙色系、柔光、温暖干净
  2791. 正向提示词(中文)
  2792. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  2793. 必须遵守规则
  2794. • 保持治愈清新统一色调,不阴暗、不诡异
  2795. • 画面柔和干净,无杂乱元素
  2796. • 角色形象柔和可爱,不狰狞
  2797. 禁止/避免词汇
  2798. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  2799. ],
  2800. ];
  2801. return $arr;
  2802. }
  2803. public function getArtStylePromptByInput($inputArtStyle): string
  2804. {
  2805. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  2806. if ($normalizedInput === '') {
  2807. return '';
  2808. }
  2809. // 按归一化画风名匹配(去除中英文空格等差异),表数据与内置映射通用
  2810. $mappings = $this->getArtStylePromptMappings();
  2811. if (!is_array($mappings)) {
  2812. return '';
  2813. }
  2814. foreach ($mappings as $artStyleName => $mapping) {
  2815. if ($this->normalizeArtStyleInput($artStyleName) === $normalizedInput) {
  2816. return (string)getProp($mapping, 'prompt', '');
  2817. }
  2818. }
  2819. return '';
  2820. }
  2821. public function getArtStyleShortPromptByInput($inputArtStyle) {
  2822. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  2823. if ($normalizedInput === '') {
  2824. return [];
  2825. }
  2826. // 优先从画风表读取(按归一化画风名匹配,停用画风保持可用);
  2827. // character_prefix/scene_prefix 缺失时用通用 prompt 兜底,均缺失则返回空数组
  2828. $row = null;
  2829. $dbRows = DB::table('mp_art_styles')
  2830. ->where('is_deleted', 0)
  2831. ->get(['art_style', 'character_prefix', 'scene_prefix', 'prompt']);
  2832. foreach ($dbRows as $dbRow) {
  2833. if ($this->normalizeArtStyleInput($dbRow->art_style) === $normalizedInput) {
  2834. $row = $dbRow;
  2835. break;
  2836. }
  2837. }
  2838. if ($row) {
  2839. $prompt = (string)$row->prompt;
  2840. $result = [
  2841. 'character_prefix' => (string)$row->character_prefix !== '' ? (string)$row->character_prefix : $prompt,
  2842. 'scene_prefix' => (string)$row->scene_prefix !== '' ? (string)$row->scene_prefix : $prompt,
  2843. ];
  2844. // 前缀与通用提示词均不存在时返回空数组
  2845. if ($result['character_prefix'] === '' && $result['scene_prefix'] === '') {
  2846. return [];
  2847. }
  2848. return $result;
  2849. }
  2850. $stylePrefixes = [
  2851. '唯美真人风格' => [
  2852. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  2853. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强',
  2854. 'prompt' => '唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质'
  2855. ],
  2856. '真人古风风格' => [
  2857. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  2858. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清',
  2859. 'prompt' => '真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清'
  2860. ],
  2861. '日系动漫风格' => [
  2862. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  2863. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强',
  2864. 'prompt' => '日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影'
  2865. ],
  2866. '国漫风格' => [
  2867. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  2868. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染',
  2869. 'prompt' => '国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节'
  2870. ],
  2871. 'Q版卡通风格' => [
  2872. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  2873. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感',
  2874. 'prompt' => 'Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画'
  2875. ],
  2876. '简约扁平风格' => [
  2877. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  2878. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽',
  2879. 'prompt' => '简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽'
  2880. ],
  2881. '武侠风格' => [
  2882. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  2883. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学',
  2884. 'prompt' => '武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制'
  2885. ],
  2886. '古风仙侠风格' => [
  2887. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  2888. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学',
  2889. 'prompt' => '古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面'
  2890. ],
  2891. '新中式水墨风格' => [
  2892. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  2893. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景',
  2894. 'prompt' => '新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感'
  2895. ],
  2896. '写实插画风格' => [
  2897. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  2898. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图',
  2899. 'prompt' => '写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染'
  2900. ],
  2901. '3D卡通风格' => [
  2902. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  2903. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染',
  2904. 'prompt' => '3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富'
  2905. ],
  2906. '条漫风格' => [
  2907. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  2908. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感',
  2909. 'prompt' => '条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制'
  2910. ],
  2911. '赛博朋克风格' => [
  2912. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  2913. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影',
  2914. 'prompt' => '赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染'
  2915. ],
  2916. '暗黑悬疑风格' => [
  2917. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  2918. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图',
  2919. 'prompt' => '暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现'
  2920. ],
  2921. '治愈清新风格' => [
  2922. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  2923. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强',
  2924. 'prompt' => '治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足'
  2925. ]
  2926. ];
  2927. // 内置映射同样按归一化画风名匹配
  2928. foreach ($stylePrefixes as $artStyleName => $item) {
  2929. if ($this->normalizeArtStyleInput($artStyleName) !== $normalizedInput) {
  2930. continue;
  2931. }
  2932. $prompt = (string)($item['prompt'] ?? '');
  2933. // 前缀缺失时用通用 prompt 兜底
  2934. $result = [
  2935. 'character_prefix' => !empty($item['character_prefix']) ? $item['character_prefix'] : $prompt,
  2936. 'scene_prefix' => !empty($item['scene_prefix']) ? $item['scene_prefix'] : $prompt,
  2937. ];
  2938. // 与表分支一致:前缀与通用提示词均不存在时返回空数组
  2939. if ($result['character_prefix'] === '' && $result['scene_prefix'] === '') {
  2940. return [];
  2941. }
  2942. return $result;
  2943. }
  2944. return [];
  2945. }
  2946. private function normalizeArtStyleInput($value): string
  2947. {
  2948. $value = trim((string)$value);
  2949. if ($value === '') {
  2950. return '';
  2951. }
  2952. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  2953. return mb_strtolower($value, 'UTF-8');
  2954. }
  2955. private function replaceArtStyleSection(string $content, string $artStyle): string
  2956. {
  2957. if ($content === '' || $artStyle === '') {
  2958. return $content;
  2959. }
  2960. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  2961. if (!preg_match($pattern, $content)) {
  2962. return $content;
  2963. }
  2964. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  2965. }
  2966. /**
  2967. * 解开模型偶发返回的 JSON 包装内容
  2968. *
  2969. * @param mixed $content 模型返回的原始内容
  2970. * @return mixed 解开后的内容(若无法解开则原样返回)
  2971. */
  2972. private function unwrapJsonWrappedContent($content) {
  2973. $trimmed = ltrim((string)$content);
  2974. if ($trimmed === '' || ($trimmed[0] !== '{' && $trimmed[0] !== '[')) {
  2975. return $content;
  2976. }
  2977. $decoded = json_decode($trimmed, true);
  2978. if (!is_array($decoded)) {
  2979. return $content;
  2980. }
  2981. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2982. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2983. return $decoded[$key];
  2984. }
  2985. }
  2986. return $content;
  2987. }
  2988. /**
  2989. * 流式文生文统一分发:根据模型路由到对应提供商的流式实现
  2990. *
  2991. * @param array $post_data 请求参数(含 model / messages / stream 等)
  2992. * @return \Generator
  2993. */
  2994. public function dispatchStreamByModel($post_data) {
  2995. // 强制按流式模式分发
  2996. $post_data['stream'] = true;
  2997. $model = (string)getProp($post_data, 'model', '');
  2998. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2999. // DeepSeek 官方模型
  3000. return $this->deepSeekStreamResponse($post_data);
  3001. } else if (in_array($model, $this->gpt_text_models)) {
  3002. // GPT 模型
  3003. return $this->gpt54StreamResponse($post_data);
  3004. } else if (in_array($model, $this->gemini_text_models)) {
  3005. // Gemini 模型
  3006. return $this->geminiStreamResponse($post_data, $model);
  3007. } else if (in_array($model, $this->baidu_glm_text_models)) {
  3008. // 百度 AI 网关 GLM 模型
  3009. return $this->baiduGLMStreamResponse($post_data);
  3010. } else if (in_array($model, $this->valid_text_models)) {
  3011. // 火山引擎等其他模型
  3012. return $this->volcEngineChatCompletion($post_data);
  3013. }
  3014. Utils::throwError('20003:不支持的模型: ' . $model);
  3015. }
  3016. /**
  3017. * 非流式文生文统一分发:根据模型路由到对应提供商的非流式实现
  3018. *
  3019. * @param array $post_data 请求参数(含 model / messages / stream 等)
  3020. * @return array
  3021. */
  3022. public function dispatchChatOnlyByModel($post_data) {
  3023. // 强制按非流式模式分发
  3024. $post_data['stream'] = false;
  3025. $model = (string)getProp($post_data, 'model', '');
  3026. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3027. // DeepSeek 官方模型
  3028. return $this->chatOnly($post_data);
  3029. } else if (in_array($model, $this->gpt_text_models)) {
  3030. // GPT 模型
  3031. return $this->gpt54ChatOnly($post_data);
  3032. } else if (in_array($model, $this->gemini_text_models)) {
  3033. // Gemini 模型
  3034. return $this->geminiChatOnly($post_data, $model);
  3035. } else if (in_array($model, $this->baidu_glm_text_models)) {
  3036. // 百度 AI 网关 GLM 模型
  3037. return $this->baiduGLMChatOnly($post_data);
  3038. } else if (in_array($model, $this->valid_text_models)) {
  3039. // 火山引擎等其他模型
  3040. return $this->volcEngineChatCompletion($post_data);
  3041. }
  3042. Utils::throwError('20003:不支持的模型: ' . $model);
  3043. }
  3044. /**
  3045. * 百度 AI 网关 GLM 流式实现(OpenAI Chat Completions 协议)
  3046. *
  3047. * @param array $post_data 请求参数(前端模型名 baidu-glm-5.2 / baidu-glm-5.3)
  3048. * @return \Generator
  3049. */
  3050. private function baiduGLMStreamResponse($post_data) {
  3051. $payload = $this->buildBaiduGLMPayload($post_data, true);
  3052. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3053. try {
  3054. $response = $client->post('https://ai-gateway.baidubce.com/v1/chat/completions', [
  3055. 'json' => $payload,
  3056. 'headers' => $this->baiduGLMHeaders(),
  3057. 'stream' => true,
  3058. ]);
  3059. } catch (\Exception $e) {
  3060. $errorDetail = $this->extractBaiduGLMErrorDetail($e);
  3061. dLog('deepseek')->error('百度GLM流式请求建立失败: ' . $e->getMessage(), [
  3062. 'payload' => $payload,
  3063. 'detail' => $errorDetail,
  3064. ]);
  3065. Utils::throwError('20003:百度GLM流式请求失败: ' . $errorDetail);
  3066. }
  3067. $body = $response->getBody();
  3068. $buffer = '';
  3069. $fullContent = '';
  3070. $fullReasoning = '';
  3071. $usage = [];
  3072. dLog('deepseek')->info('开始读取百度GLM流式响应');
  3073. try {
  3074. while (!$body->eof()) {
  3075. $chunk = $body->read(1024);
  3076. $buffer .= $chunk;
  3077. $lines = explode("\n", $buffer);
  3078. $buffer = array_pop($lines);
  3079. foreach ($lines as $line) {
  3080. $line = trim($line);
  3081. if (empty($line)) {
  3082. continue;
  3083. }
  3084. if (strpos($line, 'data: ') !== 0) {
  3085. dLog('deepseek')->warning('百度GLM非SSE数据行', ['line' => $line]);
  3086. continue;
  3087. }
  3088. $data = substr($line, 6);
  3089. if ($data === '[DONE]') {
  3090. dLog('deepseek')->info('百度GLM收到结束标记');
  3091. break 2;
  3092. }
  3093. try {
  3094. $json = json_decode($data, true);
  3095. if (json_last_error() !== JSON_ERROR_NONE) {
  3096. dLog('deepseek')->warning('百度GLM JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3097. continue;
  3098. }
  3099. if (isset($json['choices'][0]['delta'])) {
  3100. $delta = $json['choices'][0]['delta'];
  3101. // 思考链内容(兼容 reasoning_content / reasoning 两种字段)
  3102. $reasoningDelta = '';
  3103. if (isset($delta['reasoning_content']) && is_string($delta['reasoning_content'])) {
  3104. $reasoningDelta = $delta['reasoning_content'];
  3105. } elseif (isset($delta['reasoning']) && is_string($delta['reasoning'])) {
  3106. $reasoningDelta = $delta['reasoning'];
  3107. }
  3108. if ($reasoningDelta !== '') {
  3109. $fullReasoning .= $reasoningDelta;
  3110. yield [
  3111. 'type' => 'reasoning',
  3112. 'content' => $reasoningDelta,
  3113. 'full_reasoning' => $fullReasoning,
  3114. ];
  3115. }
  3116. // 正文内容
  3117. if (isset($delta['content']) && is_string($delta['content'])) {
  3118. $fullContent .= $delta['content'];
  3119. yield [
  3120. 'type' => 'content',
  3121. 'content' => $delta['content'],
  3122. ];
  3123. }
  3124. }
  3125. if (isset($json['usage'])) {
  3126. $usage = $json['usage'];
  3127. }
  3128. } catch (\Exception $e) {
  3129. dLog('deepseek')->error('百度GLM解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3130. continue;
  3131. }
  3132. }
  3133. }
  3134. } catch (\Exception $e) {
  3135. dLog('deepseek')->error('百度GLM流式读取中断: ' . $e->getMessage());
  3136. throw $e;
  3137. }
  3138. dLog('deepseek')->info('百度GLM流式读取完成', [
  3139. 'content_length' => strlen($fullContent),
  3140. 'reasoning_length' => strlen($fullReasoning),
  3141. ]);
  3142. yield [
  3143. 'type' => 'done',
  3144. 'full_content' => $fullContent,
  3145. 'full_reasoning' => $fullReasoning,
  3146. 'usage' => $usage,
  3147. ];
  3148. }
  3149. /**
  3150. * 百度 AI 网关 GLM 非流式实现(OpenAI Chat Completions 协议)
  3151. *
  3152. * @param array $post_data 请求参数(前端模型名 baidu-glm-5.2 / baidu-glm-5.3)
  3153. * @return array
  3154. */
  3155. private function baiduGLMChatOnly($post_data) {
  3156. $payload = $this->buildBaiduGLMPayload($post_data, false);
  3157. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3158. try {
  3159. $result = $client->post('https://ai-gateway.baidubce.com/v1/chat/completions', [
  3160. 'json' => $payload,
  3161. 'headers' => $this->baiduGLMHeaders(),
  3162. ]);
  3163. $response_arr = json_decode($result->getBody()->getContents(), true);
  3164. dLog('deepseek')->info('百度GLM非流式请求完成', ['response' => $response_arr]);
  3165. $fullContent = '';
  3166. $fullReasoningContent = '';
  3167. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  3168. if (isset($response_arr['choices'][0]['message'])) {
  3169. $message = $response_arr['choices'][0]['message'];
  3170. if (isset($message['content']) && is_string($message['content'])) {
  3171. $fullContent = $message['content'];
  3172. }
  3173. if (isset($message['reasoning_content']) && is_string($message['reasoning_content'])) {
  3174. $fullReasoningContent = $message['reasoning_content'];
  3175. } elseif (isset($message['reasoning']) && is_string($message['reasoning'])) {
  3176. $fullReasoningContent = $message['reasoning'];
  3177. }
  3178. }
  3179. return [
  3180. 'fullContent' => $fullContent,
  3181. 'fullReasoningContent' => $fullReasoningContent,
  3182. 'usage' => $usage,
  3183. ];
  3184. } catch (\Exception $e) {
  3185. $errorDetail = $this->extractBaiduGLMErrorDetail($e);
  3186. dLog('deepseek')->error('百度GLM非流式请求失败: ' . $e->getMessage(), [
  3187. 'payload' => $payload,
  3188. 'detail' => $errorDetail,
  3189. ]);
  3190. Utils::throwError('20003:百度GLM请求失败: ' . $errorDetail);
  3191. }
  3192. }
  3193. /**
  3194. * 组装百度 AI 网关 GLM 请求参数
  3195. *
  3196. * @param array $data 请求参数
  3197. * @param bool $stream 是否流式
  3198. * @return array
  3199. */
  3200. private function buildBaiduGLMPayload(array $data, bool $stream): array
  3201. {
  3202. if (empty(env('BAIDU_GLM_AK'))) {
  3203. Utils::throwError('20003:百度GLM API Key未配置,请检查环境变量BAIDU_GLM_AK');
  3204. }
  3205. $frontModel = (string)getProp($data, 'model', '');
  3206. $externalModel = isset(BaseConst::BAIDU_GLM_MODEL_MAP[$frontModel])
  3207. ? BaseConst::BAIDU_GLM_MODEL_MAP[$frontModel]
  3208. : '';
  3209. if ($externalModel === '') {
  3210. Utils::throwError('20003:不支持的百度GLM模型: ' . $frontModel);
  3211. }
  3212. $messages = getProp($data, 'messages', []);
  3213. if (empty($messages)) {
  3214. Utils::throwError('20003:请提供有效的对话内容');
  3215. }
  3216. // OpenAI Chat Completions 标准参数白名单。
  3217. // 注意:thinking 不在白名单中,由下方按模型单独控制
  3218. // (glm-5.2 支持关闭思考,glm-5.3 强制思考、不接受 thinking 参数)。
  3219. $allowedKeys = [
  3220. 'temperature',
  3221. 'top_p',
  3222. 'max_tokens',
  3223. 'max_completion_tokens',
  3224. 'reasoning_effort',
  3225. 'frequency_penalty',
  3226. 'presence_penalty',
  3227. 'stop',
  3228. 'response_format',
  3229. 'stream_options',
  3230. 'tools',
  3231. 'tool_choice',
  3232. 'user',
  3233. 'seed',
  3234. ];
  3235. $payload = [
  3236. 'model' => $externalModel,
  3237. 'messages' => $messages,
  3238. 'stream' => $stream,
  3239. ];
  3240. foreach ($allowedKeys as $key) {
  3241. if (array_key_exists($key, $data) && $data[$key] !== null && $data[$key] !== '') {
  3242. $payload[$key] = $data[$key];
  3243. }
  3244. }
  3245. // ================= 思考模式策略(仅百度 GLM)=================
  3246. // 规则:调用方传了的参数以其为准,未传则按模型默认策略补齐。
  3247. // glm-5.2:支持关闭思考,默认关闭(thinking.disabled),可显著缩短响应时间
  3248. // glm-5.3:强制思考,网关不接受 thinking 参数(传 disabled 会返回 400),
  3249. // 因此统一不下发 thinking,只下发 reasoning_effort,默认 low
  3250. $validEfforts = ['low', 'high', 'max'];
  3251. // 调用方传入的 thinking(兼容 'enabled' 字符串与 ['type' => 'enabled'] 数组两种写法)
  3252. $inputThinking = null;
  3253. if (array_key_exists('thinking', $data)) {
  3254. $rawThinking = $data['thinking'];
  3255. if (is_array($rawThinking)) {
  3256. $rawThinking = getProp($rawThinking, 'type', null);
  3257. }
  3258. if (in_array($rawThinking, ['enabled', 'disabled'], true)) {
  3259. $inputThinking = $rawThinking;
  3260. }
  3261. }
  3262. // 调用方传入的思考强度;百度网关只接受 low / high / max,其它取值(如 none)视为未传
  3263. $inputEffort = null;
  3264. if (isset($payload['reasoning_effort']) && in_array($payload['reasoning_effort'], $validEfforts, true)) {
  3265. $inputEffort = $payload['reasoning_effort'];
  3266. }
  3267. unset($payload['reasoning_effort']);
  3268. if ($externalModel === 'glm-5.3') {
  3269. // glm-5.3 始终思考:即使传入 disabled(或未传)也强制走 reasoning_effort
  3270. $payload['reasoning_effort'] = $inputEffort ?: 'high';
  3271. } else {
  3272. // glm-5.2 支持关闭思考:未显式开启思考时默认关闭
  3273. $thinkingType = ($inputThinking === 'enabled') ? 'enabled' : 'disabled';
  3274. $payload['thinking'] = ['type' => $thinkingType];
  3275. if ($thinkingType === 'enabled') {
  3276. $payload['reasoning_effort'] = $inputEffort ?: 'high';
  3277. }
  3278. }
  3279. if ($stream && !isset($payload['stream_options'])) {
  3280. $payload['stream_options'] = ['include_usage' => true];
  3281. }
  3282. if (!isset($payload['max_tokens']) && !isset($payload['max_completion_tokens'])) {
  3283. // GLM-5.x 输出上限较高,给长文生成留足空间
  3284. $payload['max_tokens'] = 100000;
  3285. }
  3286. return $payload;
  3287. }
  3288. /**
  3289. * 百度 AI 网关 GLM 鉴权请求头
  3290. *
  3291. * @return array
  3292. */
  3293. private function baiduGLMHeaders(): array
  3294. {
  3295. return [
  3296. 'Authorization' => 'Bearer ' . env('BAIDU_GLM_AK'),
  3297. 'Content-Type' => 'application/json; charset=UTF-8',
  3298. 'Accept' => 'text/event-stream',
  3299. ];
  3300. }
  3301. /**
  3302. * 从 Guzzle 异常响应体中提取百度 AI 网关返回的错误信息
  3303. *
  3304. * @param \Exception $e
  3305. * @return string
  3306. */
  3307. private function extractBaiduGLMErrorDetail(\Exception $e): string
  3308. {
  3309. $detail = $e->getMessage();
  3310. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  3311. try {
  3312. $responseBody = (string)$e->getResponse()->getBody();
  3313. $decoded = json_decode($responseBody, true);
  3314. if (is_array($decoded)) {
  3315. if (isset($decoded['error']['message']) && $decoded['error']['message'] !== '') {
  3316. $detail = $decoded['error']['message'];
  3317. } elseif (isset($decoded['message']) && $decoded['message'] !== '') {
  3318. $detail = $decoded['message'];
  3319. } elseif (isset($decoded['error']) && is_string($decoded['error'])) {
  3320. $detail = $decoded['error'];
  3321. }
  3322. } elseif ($responseBody !== '') {
  3323. $detail = $responseBody;
  3324. }
  3325. } catch (\Throwable $parseError) {
  3326. // 保留原始异常信息
  3327. }
  3328. }
  3329. return mb_substr($detail, 0, 500);
  3330. }
  3331. private function deepSeekStreamResponse($post_data) {
  3332. // 设置最大输出tokens
  3333. $post_data['max_tokens'] = 300000;
  3334. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  3335. $post_data['stream_options'] = ['include_usage' => true];
  3336. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3337. $response = $client->post($this->url, [
  3338. 'json' => $post_data,
  3339. 'headers' => $this->headers,
  3340. 'stream' => true // 启用流式响应
  3341. ]);
  3342. $body = $response->getBody();
  3343. $fullContent = '';
  3344. $fullReasoningContent = '';
  3345. $usage = [];
  3346. $buffer = '';
  3347. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  3348. // 逐行读取流式响应
  3349. while (!$body->eof()) {
  3350. $chunk = $body->read(1024); // 每次读取 1KB
  3351. $buffer .= $chunk;
  3352. // 按行分割
  3353. $lines = explode("\n", $buffer);
  3354. // 保留最后一个不完整的行
  3355. $buffer = array_pop($lines);
  3356. foreach ($lines as $line) {
  3357. $line = trim($line);
  3358. // 跳过空行
  3359. if (empty($line)) {
  3360. continue;
  3361. }
  3362. // 检查是否是 SSE 数据行
  3363. if (strpos($line, 'data: ') !== 0) {
  3364. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  3365. continue;
  3366. }
  3367. $data = substr($line, 6); // 移除 "data: " 前缀
  3368. if ($data === '[DONE]') {
  3369. dLog('deepseek')->info('收到结束标记');
  3370. break 2; // 跳出两层循环
  3371. }
  3372. try {
  3373. $json = json_decode($data, true);
  3374. if (json_last_error() !== JSON_ERROR_NONE) {
  3375. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3376. continue;
  3377. }
  3378. if (isset($json['choices'][0]['delta'])) {
  3379. $delta = $json['choices'][0]['delta'];
  3380. // 处理思维链内容(仅 deepseek-reasoner 模型)
  3381. if (isset($delta['reasoning_content'])) {
  3382. $fullReasoningContent .= $delta['reasoning_content'];
  3383. yield [
  3384. 'type' => 'reasoning',
  3385. 'content' => $delta['reasoning_content'],
  3386. 'full_reasoning' => $fullReasoningContent
  3387. ];
  3388. }
  3389. // 处理最终回答内容
  3390. if (isset($delta['content'])) {
  3391. $fullContent .= $delta['content'];
  3392. yield [
  3393. 'type' => 'content',
  3394. 'content' => $delta['content'],
  3395. ];
  3396. }
  3397. }
  3398. // 获取使用统计信息
  3399. if (isset($json['usage'])) {
  3400. $usage = $json['usage'];
  3401. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  3402. }
  3403. } catch (\Exception $e) {
  3404. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3405. continue;
  3406. }
  3407. }
  3408. }
  3409. dLog('deepseek')->info('流式读取完成', [
  3410. 'content_length' => strlen($fullContent),
  3411. 'reasoning_length' => strlen($fullReasoningContent)
  3412. ]);
  3413. yield [
  3414. 'type' => 'done',
  3415. 'full_content' => $fullContent,
  3416. 'full_reasoning' => $fullReasoningContent,
  3417. 'usage' => $usage
  3418. ];
  3419. }
  3420. /**
  3421. * GPT 重试次数(env 可配置,默认 5 次)
  3422. */
  3423. private function gptRetryTimes()
  3424. {
  3425. return (int)env('GPT_RETRY_TIMES', 5);
  3426. }
  3427. /**
  3428. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  3429. */
  3430. private function gptRetryInterval()
  3431. {
  3432. return (int)env('GPT_RETRY_INTERVAL', 10);
  3433. }
  3434. /**
  3435. * 判断 GPT 请求异常是否可重试
  3436. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  3437. */
  3438. private function isGptRetryableException(\Exception $e)
  3439. {
  3440. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  3441. return false;
  3442. }
  3443. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  3444. $status = $e->getResponse()->getStatusCode();
  3445. return $status >= 500 || $status == 429;
  3446. }
  3447. return true;
  3448. }
  3449. /**
  3450. * 解析 GPT 上游错误详情:状态码、错误码(如 content_filter)、错误信息与响应体
  3451. * 流式响应的 body 不可 seek,Guzzle 自带的 body summary 取不到内容,这里手动读取并截断
  3452. */
  3453. private function resolveGptUpstreamError(\Exception $e)
  3454. {
  3455. // 同一个异常对象可能被内层与外层 catch 多次解析,而流式响应体只能读取一次,这里缓存解析结果
  3456. // 同时持有异常对象引用:spl_object_id 在对象回收后会被复用,仅凭 id 取值可能串到其他异常的数据
  3457. $cacheKey = spl_object_id($e);
  3458. if (isset($this->gpt_upstream_error_cache[$cacheKey]) && $this->gpt_upstream_error_cache[$cacheKey]['exception'] === $e) {
  3459. return $this->gpt_upstream_error_cache[$cacheKey]['detail'];
  3460. }
  3461. $detail = [
  3462. 'status' => 0,
  3463. 'code' => '',
  3464. 'message' => '',
  3465. 'body' => '',
  3466. ];
  3467. if (!($e instanceof \GuzzleHttp\Exception\BadResponseException) || !$e->getResponse()) {
  3468. $this->gpt_upstream_error_cache[$cacheKey] = ['exception' => $e, 'detail' => $detail];
  3469. return $detail;
  3470. }
  3471. $response = $e->getResponse();
  3472. $detail['status'] = (int)$response->getStatusCode();
  3473. try {
  3474. $body = $response->getBody();
  3475. if ($body->isSeekable()) {
  3476. $body->rewind();
  3477. }
  3478. $content = $body->isReadable() ? (string)$body : '';
  3479. } catch (\Throwable $t) {
  3480. $content = '';
  3481. }
  3482. if ($content === '') {
  3483. $this->gpt_upstream_error_cache[$cacheKey] = ['exception' => $e, 'detail' => $detail];
  3484. return $detail;
  3485. }
  3486. $detail['body'] = mb_substr($content, 0, 4000);
  3487. $decoded = json_decode($content, true);
  3488. $decoded_error = is_array($decoded) ? getProp($decoded, 'error') : null;
  3489. if (is_array($decoded_error)) {
  3490. $detail['code'] = (string)getProp($decoded_error, 'code', '');
  3491. // 上游 message 可能超长,截断后再用于模型翻译与展示,避免把整段报错送进模型
  3492. $detail['message'] = mb_substr((string)getProp($decoded_error, 'message', ''), 0, 1000);
  3493. }
  3494. $this->gpt_upstream_error_cache[$cacheKey] = ['exception' => $e, 'detail' => $detail];
  3495. return $detail;
  3496. }
  3497. /**
  3498. * 将上游错误转换为展示给前端的提示:内容安全策略拦截等给出可操作的说明
  3499. */
  3500. private function buildChatErrorForUser(\Exception $e, $upstreamError = null)
  3501. {
  3502. if (!is_array($upstreamError)) {
  3503. $upstreamError = $this->resolveGptUpstreamError($e);
  3504. }
  3505. $code = (string)getProp($upstreamError, 'code', '');
  3506. $message = (string)getProp($upstreamError, 'message', '');
  3507. $status = (int)getProp($upstreamError, 'status', 0);
  3508. if ($code === 'content_filter') {
  3509. return '本集内容被上游模型的内容安全策略拦截,请调整剧本中过于血腥、暴力等敏感描述后重试,或改用其他模型';
  3510. }
  3511. // 其他上游报错复用全局错误映射(已知签名本地命中;未命中时由模型翻译并缓存)
  3512. if ($message !== '') {
  3513. $mapped = mapErrorMessage($message);
  3514. if ($mapped !== '' && $mapped !== '未知异常,请重试') {
  3515. return $mapped;
  3516. }
  3517. // 映射不可用时保留上游原文,便于排查
  3518. return '上游模型返回错误(' . $status . '):' . mb_substr($message, 0, 300);
  3519. }
  3520. // 拿不到上游报文时,仅传输层异常(连接失败、超时等)交给全局映射兜底
  3521. if ($e instanceof \GuzzleHttp\Exception\GuzzleException) {
  3522. return mapErrorMessage($e->getMessage());
  3523. }
  3524. // 业务异常(如参数校验)保持原有文案,避免被模型翻译后丢失关键信息
  3525. return '处理请求时发生异常: ' . $e->getMessage();
  3526. }
  3527. /**
  3528. * GPT 中转站探活:GET /v1/models,5 秒短超时
  3529. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  3530. */
  3531. private function checkGptServiceAvailable($apiKey = null)
  3532. {
  3533. if ($apiKey === null) {
  3534. $apiKey = env('GPT_54_API_KEY');
  3535. }
  3536. if (empty($apiKey)) {
  3537. return false;
  3538. }
  3539. try {
  3540. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  3541. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  3542. 'headers' => [
  3543. 'Authorization' => 'Bearer ' . $apiKey,
  3544. 'Content-Type' => 'application/json'
  3545. ]
  3546. ]);
  3547. $status = $response->getStatusCode();
  3548. return $status < 500 && $status != 429;
  3549. } catch (\Exception $e) {
  3550. return false;
  3551. }
  3552. }
  3553. /**
  3554. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  3555. * 全部失败抛出友好错误
  3556. */
  3557. private function ensureGptServiceAvailable($apiKey = null)
  3558. {
  3559. $maxRetries = $this->gptRetryTimes();
  3560. $interval = $this->gptRetryInterval();
  3561. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  3562. if ($this->checkGptServiceAvailable($apiKey)) {
  3563. return;
  3564. }
  3565. if ($attempt < $maxRetries) {
  3566. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  3567. 'retry' => $attempt + 1,
  3568. 'max_retries' => $maxRetries
  3569. ]);
  3570. sleep($interval);
  3571. }
  3572. }
  3573. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  3574. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  3575. 'max_retries' => $maxRetries,
  3576. 'interval' => $interval
  3577. ]);
  3578. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  3579. }
  3580. /**
  3581. * GPT 流式输出处理方法
  3582. *
  3583. * @param array $post_data GPT API请求参数
  3584. * @return \Generator 返回生成器,用于流式输出
  3585. */
  3586. private function gpt54StreamResponse($post_data) {
  3587. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  3588. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  3589. // gpt-5.4 中转已下线,强制映射到 gpt-5.6-sol
  3590. if ($modelName === 'gpt-5.4') {
  3591. $modelName = 'gpt-5.6-terra';
  3592. $post_data['model'] = $modelName;
  3593. }
  3594. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  3595. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  3596. $usedLunaFallback = false;
  3597. // 流式请求长时间无任何返回(TTFB)超过该秒数时切换备用 Key(env 可配置,默认 600 秒)
  3598. $ttfbTimeoutSeconds = (int)env('GPT_SWITCH_LUNA_AFTER_SECONDS', 600);
  3599. if (empty($apiKey)) {
  3600. Utils::throwError('20003:GPT API Key未配置');
  3601. }
  3602. // 先探活,服务不可用时自动重试
  3603. $this->ensureGptServiceAvailable($apiKey);
  3604. $client = new Client(['timeout' => 1800, 'verify' => false, 'read_timeout' => $ttfbTimeoutSeconds]);
  3605. // 移除 thinking 参数,GPT-5.4 不支持
  3606. if (isset($post_data['thinking'])) {
  3607. unset($post_data['thinking']);
  3608. }
  3609. if (isset($post_data['reasoning_effort'])) {
  3610. unset($post_data['reasoning_effort']);
  3611. }
  3612. // GPT-5.x(推理型上游)只接受默认 temperature(1),传入其他值会返回 400:
  3613. // Unsupported value: 'temperature' does not support 1.35 with this model.
  3614. // Only the default (1) value is supported.
  3615. unset($post_data['temperature']);
  3616. // 流式场景下保留 response_format(json 输出时强制模型输出完整 JSON,与非流式 gpt54ChatOnly 对齐)
  3617. // 中转站对 response_format 的兼容性由请求方控制:仅在需要 json 输出时传入
  3618. $post_data['max_completion_tokens'] = 100000;
  3619. // GPT-5.x 上游仅支持 max_completion_tokens,同时携带 max_tokens 会返回 400:
  3620. // Unsupported parameter: 'max_tokens' is not supported with this model.
  3621. // 这里显式移除,防止调用方在 post_data 中残留 max_tokens。
  3622. unset($post_data['max_tokens']);
  3623. // GPT-5.x(推理型上游)不接受 frequency_penalty / presence_penalty:
  3624. // Unsupported parameter: 'frequency_penalty' is not supported with this model.
  3625. // 调用方默认传 0,移除后采样行为不变,显式清理避免 400。
  3626. unset($post_data['frequency_penalty'], $post_data['presence_penalty']);
  3627. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  3628. $post_data['stream_options'] = ['include_usage' => true];
  3629. $maxRetries = $this->gptRetryTimes();
  3630. $interval = $this->gptRetryInterval();
  3631. $attempt = 0;
  3632. while (true) {
  3633. $fullContent = '';
  3634. $usage = [];
  3635. $buffer = '';
  3636. // JSON 输出场景:不启用"整段正文包成 JSON 字符串"的暂缓缓存,流式过程中直接输出供前端展示
  3637. $isJsonRequest = isset($post_data['response_format'])
  3638. && is_array($post_data['response_format'])
  3639. && ($post_data['response_format']['type'] ?? '') === 'json_object';
  3640. $suspectJsonWrap = false;
  3641. $pendingContent = '';
  3642. $requestStartedAt = microtime(true);
  3643. $headers = [
  3644. 'Authorization' => 'Bearer ' . $apiKey,
  3645. 'Content-Type' => 'application/json',
  3646. 'Accept' => 'text/event-stream'
  3647. ];
  3648. try {
  3649. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  3650. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  3651. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  3652. 'json' => $post_data,
  3653. 'headers' => $headers,
  3654. 'stream' => true // 启用流式响应
  3655. ]);
  3656. $body = $response->getBody();
  3657. dLog('deepseek')->info('开始读取 GPT 流式响应');
  3658. // 逐行读取流式响应
  3659. while (!$body->eof()) {
  3660. // 长时间没有任何内容返回时,切换备用 Key 重试
  3661. if ($fullContent === '' && empty($usage) && (microtime(true) - $requestStartedAt) > $ttfbTimeoutSeconds) {
  3662. throw new \RuntimeException('GPT 流式响应长时间无返回,等待切换备用 Key');
  3663. }
  3664. $chunk = $body->read(1024); // 每次读取 1KB
  3665. $buffer .= $chunk;
  3666. // 按行分割
  3667. $lines = explode("\n", $buffer);
  3668. // 保留最后一个不完整的行
  3669. $buffer = array_pop($lines);
  3670. foreach ($lines as $line) {
  3671. $line = trim($line);
  3672. // 跳过空行
  3673. if (empty($line)) {
  3674. continue;
  3675. }
  3676. // 检查是否是 SSE 数据行
  3677. if (strpos($line, 'data: ') !== 0) {
  3678. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  3679. continue;
  3680. }
  3681. $data = substr($line, 6); // 移除 "data: " 前缀
  3682. if ($data === '[DONE]') {
  3683. dLog('deepseek')->info('收到结束标记');
  3684. break 2; // 跳出 foreach 和流读取循环
  3685. }
  3686. try {
  3687. $json = json_decode($data, true);
  3688. if (json_last_error() !== JSON_ERROR_NONE) {
  3689. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3690. continue;
  3691. }
  3692. if (isset($json['choices'][0]['delta'])) {
  3693. $delta = $json['choices'][0]['delta'];
  3694. // 处理回答内容
  3695. if (isset($delta['content'])) {
  3696. $fullContent .= $delta['content'];
  3697. $trimmed = ltrim($fullContent);
  3698. if (!$suspectJsonWrap && !$isJsonRequest && $trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
  3699. // 可能模型把整段正文包成了 JSON 字符串,先暂缓输出
  3700. $suspectJsonWrap = true;
  3701. }
  3702. if (!$suspectJsonWrap) {
  3703. // 中转可能一次返回大段内容,按小块输出保持流式节奏
  3704. $chunkSize = 256;
  3705. $chunkLength = mb_strlen($delta['content']);
  3706. for ($offset = 0; $offset < $chunkLength; $offset += $chunkSize) {
  3707. yield [
  3708. 'type' => 'content',
  3709. 'content' => mb_substr($delta['content'], $offset, $chunkSize),
  3710. ];
  3711. }
  3712. } else {
  3713. $pendingContent .= $delta['content'];
  3714. }
  3715. }
  3716. }
  3717. // 获取使用统计信息
  3718. if (isset($json['usage'])) {
  3719. $usage = $json['usage'];
  3720. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  3721. }
  3722. } catch (\Exception $e) {
  3723. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3724. continue;
  3725. }
  3726. }
  3727. }
  3728. dLog('deepseek')->info('流式读取完成', [
  3729. 'content_length' => strlen($fullContent)
  3730. ]);
  3731. // 兼容模型偶发把整段正文包裹成 JSON 字符串返回
  3732. if ($suspectJsonWrap) {
  3733. $decoded = json_decode(trim($fullContent), true);
  3734. $unwrapped = null;
  3735. if (is_array($decoded)) {
  3736. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  3737. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  3738. $unwrapped = $decoded[$key];
  3739. break;
  3740. }
  3741. }
  3742. }
  3743. if ($unwrapped !== null) {
  3744. $fullContent = $unwrapped;
  3745. $chunkSize = 256;
  3746. $contentLength = mb_strlen($fullContent);
  3747. for ($offset = 0; $offset < $contentLength; $offset += $chunkSize) {
  3748. yield [
  3749. 'type' => 'content',
  3750. 'content' => mb_substr($fullContent, $offset, $chunkSize),
  3751. ];
  3752. }
  3753. } elseif ($pendingContent !== '') {
  3754. // 误判:补发暂缓内容,避免内容丢失
  3755. yield [
  3756. 'type' => 'content',
  3757. 'content' => $pendingContent,
  3758. ];
  3759. }
  3760. }
  3761. yield [
  3762. 'type' => 'done',
  3763. 'full_content' => $fullContent,
  3764. 'full_reasoning' => '',
  3765. 'usage' => $usage
  3766. ];
  3767. return;
  3768. } catch (\Exception $e) {
  3769. // 提前解析上游错误详情(流式响应体只能读取一次,后续日志与前端提示共用)
  3770. $upstream_error = $this->resolveGptUpstreamError($e);
  3771. // 报错或长时间无返回时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  3772. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  3773. $usedLunaFallback = true;
  3774. $apiKey = $lunaApiKey;
  3775. dLog('deepseek')->warning('GPT 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  3776. continue;
  3777. }
  3778. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  3779. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  3780. // 记录上游返回的错误详情(流式响应 Guzzle 不会自动附带 body,需手动读取)
  3781. $error_context = ['error' => $e->getMessage()];
  3782. if ($upstream_error['status'] || $upstream_error['body'] !== '') {
  3783. $error_context['upstream_status'] = $upstream_error['status'];
  3784. $error_context['upstream_code'] = $upstream_error['code'];
  3785. $error_context['upstream_body'] = $upstream_error['body'];
  3786. }
  3787. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage(), $error_context);
  3788. logDB('deepseek', 'error', 'GPT 流式请求失败', $error_context);
  3789. throw $e;
  3790. }
  3791. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  3792. 'retry' => $attempt + 1,
  3793. 'max_retries' => $maxRetries,
  3794. 'error' => $e->getMessage()
  3795. ]);
  3796. sleep($interval);
  3797. $attempt++;
  3798. }
  3799. }
  3800. }
  3801. // 与推理模型对话
  3802. public function chatWithReasoner($data) {
  3803. // 文生文计费预检(normal 档)
  3804. $uid = Site::getUid();
  3805. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'normal'), $uid);
  3806. $content = getProp($data, 'content');
  3807. $model = getProp($data, 'model', 'r1');
  3808. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3809. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3810. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3811. if ($model == 'r1') {
  3812. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  3813. $thinkingMode = 'disabled';
  3814. } else {
  3815. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  3816. $thinkingMode = 'disabled';
  3817. }
  3818. // 获取可选情感(根据音色可支持情感选)
  3819. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  3820. $emotion_list = [];
  3821. foreach ($timbre_emotion as $emotion) {
  3822. $tmp = explode(',', $emotion);
  3823. $emotion_list = array_merge($emotion_list, $tmp);
  3824. }
  3825. $emotion_list = array_unique($emotion_list);
  3826. $emotion_str = implode('、', $emotion_list);
  3827. // // 获取可选情感
  3828. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  3829. // $emotion_str = implode('、', $emotion_list);
  3830. // 是否启用情感
  3831. $enable_emotion = getProp($data, 'enable_emotion', 0);
  3832. if ($enable_emotion) {
  3833. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  3834. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3835. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  3836. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  3837. }else {
  3838. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  3839. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3840. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  3841. }
  3842. $messages = [
  3843. [
  3844. 'role' => 'system',
  3845. 'content' => $sys_content
  3846. ],
  3847. [
  3848. 'role' => 'user',
  3849. 'content' => $content
  3850. ]
  3851. ];
  3852. $post_data = [
  3853. 'model' => $model,
  3854. 'messages' => $messages,
  3855. // 'max_tokens' => 8192,
  3856. 'temperature' => 1,
  3857. 'frequency_penalty' => 0,
  3858. 'presence_penalty' => 0,
  3859. 'thinking' => ['type' => $thinkingMode],
  3860. 'response_format' => [
  3861. 'type' => 'text'
  3862. ],
  3863. 'stream' => false
  3864. ];
  3865. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3866. // 根据模型类型选择调用方法
  3867. $fullContent = '';
  3868. $usage = [];
  3869. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  3870. if (is_array($chatResult)) {
  3871. $fullContent = $chatResult['fullContent'];
  3872. $usage = $chatResult['usage'];
  3873. }
  3874. // 处理获取到的剧本数据
  3875. $script_content = handleScriptWords($fullContent, $enable_emotion);
  3876. $result = [
  3877. 'origin_content' => $fullContent,
  3878. 'roles' => getProp($script_content, 'roles'),
  3879. 'words' => getProp($script_content, 'words'),
  3880. ];
  3881. // 文生文成功计费(normal 档):同时记录积分与 token 明细
  3882. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  3883. 'model' => $model,
  3884. 'source' => 'chatWithReasoner',
  3885. ], 'normal');
  3886. return $result;
  3887. }
  3888. public function resetParagraphAudio($data) {
  3889. $bid = getProp($data, 'bid');
  3890. $cid = getProp($data, 'cid');
  3891. $version_id = getProp($data, 'version_id');
  3892. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  3893. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  3894. 'generate_status' => '待制作',
  3895. 'updated_at' => date('Y-m-d H:i:s')
  3896. ]);
  3897. }
  3898. public function saveParagraphAudio($data) {
  3899. $bid = getProp($data, 'bid');
  3900. $cid = getProp($data, 'cid');
  3901. $version_id = getProp($data, 'version_id');
  3902. $sequence = getProp($data, 'sequence');
  3903. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  3904. // 获取所有情感
  3905. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3906. $emotion_list = array_flip($emotion_list);
  3907. // 获取音色支持情感
  3908. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  3909. $timbre_emotion = explode(',', $timbre_emotion);
  3910. $emotion = getProp($data, 'emotion');
  3911. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  3912. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3913. $list = [
  3914. 'bid' => $bid,
  3915. 'cid' => $cid,
  3916. 'version_id' => $version_id,
  3917. 'sequence' => $sequence,
  3918. 'role' => getProp($data, 'role'),
  3919. 'gender' => getProp($data, 'gender'),
  3920. 'text' => trim(getProp($data, 'text')),
  3921. 'emotion' => $emotion,
  3922. 'emotion_type' => $emotion_type,
  3923. 'voice_type' => getProp($data, 'voice_type'),
  3924. 'voice_name' => getProp($data, 'voice_name'),
  3925. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  3926. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  3927. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  3928. 'pitch' => getProp($data, 'pitch', 0),
  3929. // 'paragraph_audio_url' => '',
  3930. 'generate_status' => '制作中',
  3931. 'error_msg' => '',
  3932. 'updated_at' => date('Y-m-d H:i:s')
  3933. ];
  3934. $continue = false;
  3935. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  3936. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  3937. $list['generate_status'] = '制作成功';
  3938. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  3939. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  3940. $continue = true;
  3941. }
  3942. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  3943. if ($id) {
  3944. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  3945. }else {
  3946. $list['created_at'] = date('Y-m-d H:i:s');
  3947. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  3948. $boolen = $id ? true : false;
  3949. }
  3950. // 如果更新成功则加入查询队列
  3951. if ($boolen) {
  3952. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  3953. Redis::sadd($redis_key, $id);
  3954. }
  3955. if ($boolen && !$continue) {
  3956. $boolen = false;
  3957. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3958. // 根据ID通过API通知合成音频
  3959. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  3960. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  3961. $response = $result->getBody()->getContents();
  3962. $response_arr = json_decode($response, true);
  3963. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3964. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3965. Log::info('通知火山生成段落音频失败: '.$error_msg);
  3966. Utils::throwError('20003:通知火山生成段落音频失败');
  3967. }
  3968. $boolen = true;
  3969. }
  3970. return $boolen;
  3971. }
  3972. public function insertAudioEffect($data) {
  3973. $audio_id = getProp($data, 'audio_id');
  3974. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3975. $bid = getProp($chapter_audio, 'bid');
  3976. $version_id = getProp($chapter_audio, 'version_id');
  3977. $cid = getProp($chapter_audio, 'cid');
  3978. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3979. $audio_effect_json = getProp($data, 'audio_effect_json');
  3980. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  3981. try {
  3982. DB::beginTransaction();
  3983. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3984. if (!$count) {
  3985. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3986. }else {
  3987. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3988. }
  3989. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3990. 'audio_effect_status' => '添加中',
  3991. 'audio_effect_json' => $audio_effect_json,
  3992. 'updated_at' => date('Y-m-d H:i:s')
  3993. ]);
  3994. if (!$boolen1) {
  3995. DB::rollBack();
  3996. Utils::throwError('20003:更新生成数据失败');
  3997. }
  3998. $id = DB::table('mp_audio_tasks')->insertGetId([
  3999. 'audio_id' => $audio_id,
  4000. 'generate_status' => '执行中',
  4001. 'generate_json' => json_encode([], 256),
  4002. 'bid' => $bid,
  4003. 'book_name' => getProp($chapter_audio, 'book_name'),
  4004. 'version_id' => $version_id,
  4005. 'version_name' => getProp($chapter_audio, 'version_name'),
  4006. 'cid' => $cid,
  4007. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  4008. 'task_name' => $task_name,
  4009. 'created_at' => date('Y-m-d H:i:s'),
  4010. 'updated_at' => date('Y-m-d H:i:s')
  4011. ]);
  4012. if (!$id) {
  4013. DB::rollBack();
  4014. Utils::throwError('20003:创建任务失败');
  4015. }
  4016. }catch (\Exception $e) {
  4017. DB::rollBack();
  4018. Utils::throwError('20003:'.$e->getMessage());
  4019. }
  4020. DB::commit();
  4021. $client = new Client(['timeout' => 1800, 'verify' => false]);
  4022. // 根据ID通过API通知合成音频
  4023. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  4024. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  4025. $response = $result->getBody()->getContents();
  4026. $response_arr = json_decode($response, true);
  4027. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4028. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4029. Log::info('通知火山插入音效失败: '.$error_msg);
  4030. Utils::throwError('20003:通知火山插入音效失败');
  4031. }
  4032. return true;
  4033. }
  4034. public function insertBgm($data) {
  4035. $audio_id = getProp($data, 'audio_id');
  4036. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  4037. $bid = getProp($chapter_audio, 'bid');
  4038. $version_id = getProp($chapter_audio, 'version_id');
  4039. $cid = getProp($chapter_audio, 'cid');
  4040. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  4041. $bgm_json = getProp($data, 'bgm_json');
  4042. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  4043. if (!$bgm_json) {
  4044. $bgm_json = getProp($data, 'audio_effect_json');
  4045. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  4046. }
  4047. try {
  4048. DB::beginTransaction();
  4049. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  4050. if (!$count) {
  4051. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  4052. }else {
  4053. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  4054. }
  4055. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  4056. 'bgm_status' => '添加中',
  4057. 'bgm_json' => $bgm_json,
  4058. 'updated_at' => date('Y-m-d H:i:s')
  4059. ]);
  4060. if (!$boolen1) {
  4061. DB::rollBack();
  4062. Utils::throwError('20003:更新生成数据失败');
  4063. }
  4064. $id = DB::table('mp_audio_tasks')->insertGetId([
  4065. 'audio_id' => $audio_id,
  4066. 'generate_status' => '执行中',
  4067. 'generate_json' => json_encode([], 256),
  4068. 'bid' => $bid,
  4069. 'book_name' => getProp($chapter_audio, 'book_name'),
  4070. 'version_id' => $version_id,
  4071. 'version_name' => getProp($chapter_audio, 'version_name'),
  4072. 'cid' => $cid,
  4073. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  4074. 'task_name' => $task_name,
  4075. 'created_at' => date('Y-m-d H:i:s'),
  4076. 'updated_at' => date('Y-m-d H:i:s')
  4077. ]);
  4078. if (!$id) {
  4079. DB::rollBack();
  4080. Utils::throwError('20003:创建任务失败');
  4081. }
  4082. }catch (\Exception $e) {
  4083. DB::rollBack();
  4084. Utils::throwError('20003:'.$e->getMessage());
  4085. }
  4086. DB::commit();
  4087. $client = new Client(['timeout' => 1800, 'verify' => false]);
  4088. // 根据ID通过API通知合成音频
  4089. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  4090. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  4091. $response = $result->getBody()->getContents();
  4092. $response_arr = json_decode($response, true);
  4093. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4094. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4095. Log::info('通知火山插入bgm失败: '.$error_msg);
  4096. Utils::throwError('20003:通知火山插入bgm失败');
  4097. }
  4098. return true;
  4099. }
  4100. public function getParagraphAudios($data) {
  4101. $bid = getProp($data, 'bid');
  4102. $cid = getProp($data, 'cid');
  4103. $version_id = getProp($data, 'version_id');
  4104. $sequence = getProp($data, 'sequence');
  4105. // 获取已生成的音频
  4106. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  4107. if ($sequence) $query->where('sequence', $sequence);
  4108. $paragraph_audios = $query->orderBy('sequence')->get();
  4109. $result = [];
  4110. foreach($paragraph_audios as $item) {
  4111. $result[] = [
  4112. 'sequence' => getProp($item, 'sequence'),
  4113. 'role' => getProp($item, 'role'),
  4114. 'gender' => getProp($item, 'gender'),
  4115. 'text' => trim(getProp($item, 'text')),
  4116. 'emotion' => getProp($item, 'emotion'),
  4117. 'emotion_type' => getProp($item, 'emotion_type'),
  4118. 'voice_type' => getProp($item, 'voice_type'),
  4119. 'voice_name' => getProp($item, 'voice_name'),
  4120. 'speed_ratio' => getProp($item, 'speed_ratio'),
  4121. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  4122. 'emotion_scale' => getProp($item, 'emotion_scale'),
  4123. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  4124. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  4125. ];
  4126. }
  4127. return $result;
  4128. }
  4129. // 新增合成任务
  4130. public function addGenerateTask($data) {
  4131. $bid = getProp($data, 'bid');
  4132. $cid = getProp($data, 'cid');
  4133. $version_id = getProp($data, 'version_id');
  4134. $generate_json = getProp($data, 'generate_json');
  4135. // 获取已生成的音频
  4136. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  4137. $paragraph_list = [];
  4138. foreach($paragraph_audios as $item) {
  4139. $paragraph_list[getProp($item, 'sequence')] = [
  4140. 'role' => getProp($item, 'role'),
  4141. 'gender' => getProp($item, 'gender'),
  4142. 'text' => trim(getProp($item, 'text')),
  4143. 'emotion' => getProp($item, 'emotion'),
  4144. 'emotion_type' => getProp($item, 'emotion_type'),
  4145. 'voice_type' => getProp($item, 'voice_type'),
  4146. 'voice_name' => getProp($item, 'voice_name'),
  4147. 'speed_ratio' => getProp($item, 'speed_ratio'),
  4148. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  4149. 'emotion_scale' => getProp($item, 'emotion_scale'),
  4150. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  4151. ];
  4152. }
  4153. // 更新角色-音色信息
  4154. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  4155. $existed_role_info = json_decode($existed_role_info, true);
  4156. if (!$existed_role_info) $existed_role_info = [];
  4157. // 获取情感信息
  4158. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  4159. $emotion_list = array_flip($emotion_list);
  4160. // 获取音色对应情感组
  4161. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  4162. $timbre_emotion_list = [];
  4163. foreach($timbre_emotions as $item) {
  4164. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  4165. }
  4166. // 构造生成音频的json
  4167. $words = json_decode($generate_json, true);
  4168. // 最终合成前的参数组
  4169. $mp_chapter_paragraph_audios = [];
  4170. $sequence = 1;
  4171. $complete_paragraph_sequences = [];
  4172. foreach($words as &$word) {
  4173. 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:参数格式有误');
  4174. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  4175. $role = getProp($word, 'role');
  4176. $word['gender'] = (int)$word['gender'];
  4177. // 判断音色对应情感是否支持,不支持则调整为中性
  4178. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  4179. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  4180. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  4181. if (isset($emotion_list[getProp($word, 'emotion')])) {
  4182. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  4183. }else {
  4184. $word['emotion'] = '中性';
  4185. $word['emotion_type'] = 'neutral';
  4186. }
  4187. $existed_role_info[$role] = [
  4188. 'timbre_type' => $word['voice_type'],
  4189. 'timbre_name' => $word['voice_name'],
  4190. 'emotion' => $word['emotion'],
  4191. 'emotion_type' => $word['emotion_type'],
  4192. 'speed_ratio' => $word['speed_ratio'],
  4193. 'loudness_ratio'=> $word['loudness_ratio'],
  4194. 'emotion_scale' => $word['emotion_scale'],
  4195. 'pitch' => $word['pitch']
  4196. ];
  4197. $word['paragraph_audio_url'] = '';
  4198. // 判断生成参数是否相同,相同则直接使用已生成的音频
  4199. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  4200. // 如果音频存在并且参数都未改变则使用已生成的音频
  4201. if (getProp($paragraph, 'paragraph_audio_url')) {
  4202. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  4203. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  4204. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  4205. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  4206. // {
  4207. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  4208. // }
  4209. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  4210. }
  4211. $tmp = $word;
  4212. // 组装章节分句音频数据
  4213. // $tmp['sequence'] = getProp($word, 'sequence');
  4214. // $tmp['text'] = getProp($word, 'text');
  4215. // $tmp['emotion'] = getProp($word, 'emotion');
  4216. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  4217. // $tmp['voice_name'] = getProp($word, 'voice_name');
  4218. // $tmp['voice_type'] = getProp($word, 'voice_type');
  4219. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  4220. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  4221. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  4222. $tmp['bid'] = $bid;
  4223. $tmp['version_id'] = $version_id;
  4224. $tmp['cid'] = $cid;
  4225. $tmp['sequence'] = $sequence;
  4226. $tmp['created_at'] = date('Y-m-d H:i:s');
  4227. $tmp['updated_at'] = date('Y-m-d H:i:s');
  4228. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  4229. $mp_chapter_paragraph_audios[] = $tmp;
  4230. $complete_paragraph_sequences[] = $sequence;
  4231. $sequence++;
  4232. }
  4233. $generate_json = json_encode($words, 256);
  4234. // 判断是否有未生成字幕的段落
  4235. $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();
  4236. if ($no_subtitle_sequences) {
  4237. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  4238. }
  4239. try {
  4240. DB::beginTransaction();
  4241. $role_info = json_encode($existed_role_info, 256);
  4242. $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')]);
  4243. if (!$boolen) {
  4244. DB::rollBack();
  4245. Utils::throwError('20003:更新角色信息失败');
  4246. }
  4247. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  4248. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  4249. if (!$count) {
  4250. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  4251. }else {
  4252. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  4253. }
  4254. $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')]);
  4255. if (!$boolen1) {
  4256. DB::rollBack();
  4257. Utils::throwError('20003:更新生成数据失败');
  4258. }
  4259. $id = DB::table('mp_audio_tasks')->insertGetId([
  4260. 'audio_id' => getProp($chapter_audio, 'id'),
  4261. 'generate_status' => '执行中',
  4262. 'generate_json' => $generate_json,
  4263. 'bid' => $bid,
  4264. 'book_name' => getProp($chapter_audio, 'book_name'),
  4265. 'version_id' => $version_id,
  4266. 'version_name' => getProp($chapter_audio, 'version_name'),
  4267. 'cid' => $cid,
  4268. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  4269. 'task_name' => $task_name,
  4270. 'created_at' => date('Y-m-d H:i:s'),
  4271. 'updated_at' => date('Y-m-d H:i:s')
  4272. ]);
  4273. if (!$id) {
  4274. DB::rollBack();
  4275. Utils::throwError('20003:创建任务失败');
  4276. }
  4277. // 删除不在段落序号范围内的其他数据
  4278. if ($complete_paragraph_sequences) {
  4279. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  4280. }
  4281. // // 删除章节分句音频数据并重新插入
  4282. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  4283. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  4284. // if (!$boolen3) {
  4285. // DB::rollBack();
  4286. // Utils::throwError('20003:更新章节分句音频失败');
  4287. // }
  4288. } catch (\Exception $e) {
  4289. DB::rollBack();
  4290. Utils::throwError('20003:'.$e->getMessage());
  4291. }
  4292. DB::commit();
  4293. // 通知火山生成音频
  4294. $client = new Client(['timeout' => 1800, 'verify' => false]);
  4295. // 根据ID通过API通知合成音频
  4296. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  4297. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  4298. $response = $result->getBody()->getContents();
  4299. $response_arr = json_decode($response, true);
  4300. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4301. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4302. Log::info('通知火山生成音频失败: '.$error_msg);
  4303. Utils::throwError('20003:通知火山生成音频失败');
  4304. }
  4305. return true;
  4306. }
  4307. public function timbreList($data) {
  4308. $gender = getProp($data, 'gender');
  4309. $timbre_name = getProp($data, 'voice_name');
  4310. $category_id = getProp($data, 'category_id');
  4311. $age_stage = getProp($data, 'age_stage');
  4312. $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');
  4313. if ($gender) {
  4314. $query->where('gender', $gender);
  4315. }
  4316. if ($timbre_name) {
  4317. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  4318. }
  4319. if ($category_id) {
  4320. $query->where(function ($query) use ($category_id) {
  4321. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  4322. });
  4323. }
  4324. if ($age_stage) {
  4325. $query->where('age_stage', $age_stage);
  4326. }
  4327. $list = $query->get()->map(function ($value) {
  4328. $value = (array)$value;
  4329. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  4330. return $value;
  4331. })->toArray();
  4332. return $list;
  4333. }
  4334. // 生成火山临时token
  4335. public function setStsToken() {
  4336. // ************* 配置参数 *************
  4337. $method = 'GET';
  4338. $service = 'sts';
  4339. $host = 'open.volcengineapi.com';
  4340. $region = env('VOLC_REGION');
  4341. $endpoint = 'https://open.volcengineapi.com';
  4342. // $endpoint = 'https://tos-cn-beijing.volces.com';
  4343. $access_key = env('VOLC_AK');
  4344. $secret_key = env('VOLC_SK');
  4345. // 获取缓存中的token,如果没有则请求接口
  4346. $token = Redis::get('volc_sts_token');
  4347. if (!$token) {
  4348. // 查询参数
  4349. $query_parameters = [
  4350. 'Action' => 'AssumeRole',
  4351. 'RoleSessionName' => 'user@zw',
  4352. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  4353. 'Version' => '2018-01-01'
  4354. ];
  4355. // 生成URL编码的查询字符串
  4356. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  4357. // 获取签名头信息
  4358. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  4359. // 构建完整URL
  4360. $request_url = $endpoint . '?' . $request_parameters;
  4361. $client = new Client(['verify' => false]);
  4362. $response = $client->get($request_url, ['headers' => $headers]);
  4363. $response_arr = json_decode($response->getBody()->getContents(), true);
  4364. $result = [
  4365. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  4366. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  4367. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  4368. 'Region' => env('VOLC_REGION'),
  4369. 'Endpoint' => env('VOLC_END_POINT'),
  4370. 'Bucket' => env('VOLC_BUCKET'),
  4371. ];
  4372. // 缓存token
  4373. Redis::setex('volc_sts_token', 3000, json_encode($result));
  4374. return $result;
  4375. } else {
  4376. return json_decode($token, true);
  4377. }
  4378. // $response = $response['Response'];
  4379. // $access_key = $response['Credentials']['AccessKeyId'];
  4380. // $secret_key = $response['Credentials']['AccessKeySecret'];
  4381. // $security_token = $response['Credentials']['SecurityToken'];
  4382. // $expiration = $response['Credentials']['Expiration'];
  4383. // dd($response_arr);
  4384. }
  4385. public function emotionGroups($data) {
  4386. $id = getProp($data, 'group_id');
  4387. $group_name = getProp($data, 'group_name');
  4388. $voice_type = getProp($data, 'voice_type');
  4389. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  4390. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  4391. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  4392. if ($group_name) {
  4393. $query->where('group_name', 'like', "%{$group_name}%");
  4394. }
  4395. if ($id) {
  4396. $query->where('id', $id);
  4397. }
  4398. if ($voice_type) {
  4399. $query->where('voice_type', $voice_type);
  4400. }
  4401. return $query->orderBy('id')->get()->map(function ($value) {
  4402. return (array)$value;
  4403. })->toArray();
  4404. }
  4405. private function sign($key, $msg) {
  4406. return hash_hmac('sha256', $msg, $key, true);
  4407. }
  4408. // 生成签名密钥
  4409. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  4410. $kDate = $this->sign($key, $dateStamp);
  4411. $kRegion = $this->sign($kDate, $regionName);
  4412. $kService = $this->sign($kRegion, $serviceName);
  4413. $kSigning = $this->sign($kService, 'request');
  4414. return $kSigning;
  4415. }
  4416. // 获取签名头信息
  4417. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  4418. $contenttype = 'application/x-www-form-urlencoded';
  4419. $accept = 'application/json';
  4420. // 获取当前UTC时间
  4421. $t = new DateTime('now', new DateTimeZone('UTC'));
  4422. $xdate = $t->format('Ymd\THis\Z');
  4423. $datestamp = $t->format('Ymd');
  4424. // 1. 拼接规范请求串
  4425. $canonical_uri = '/';
  4426. $canonical_querystring = $request_parameters;
  4427. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  4428. $signed_headers = 'content-type;host;x-date';
  4429. // 空请求体的SHA256哈希
  4430. $payload_hash = hash('sha256', '');
  4431. $canonical_request = implode("\n", [
  4432. $method,
  4433. $canonical_uri,
  4434. $canonical_querystring,
  4435. $canonical_headers,
  4436. $signed_headers,
  4437. $payload_hash
  4438. ]);
  4439. // 2. 拼接待签名字符串
  4440. $algorithm = 'HMAC-SHA256';
  4441. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  4442. $hashed_canonical_request = hash('sha256', $canonical_request);
  4443. $string_to_sign = implode("\n", [
  4444. $algorithm,
  4445. $xdate,
  4446. $credential_scope,
  4447. $hashed_canonical_request
  4448. ]);
  4449. // 3. 计算签名
  4450. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  4451. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  4452. // 4. 添加签名到请求头
  4453. $authorization_header = sprintf(
  4454. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  4455. $algorithm,
  4456. $access_key,
  4457. $credential_scope,
  4458. $signed_headers,
  4459. $signature
  4460. );
  4461. return [
  4462. 'Accept' => $accept,
  4463. 'Content-Type' => $contenttype,
  4464. 'X-Date' => $xdate,
  4465. 'Authorization' => $authorization_header
  4466. ];
  4467. }
  4468. // 文字合成语音(火山引擎)
  4469. public function tts($data) {
  4470. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  4471. $headers = [
  4472. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  4473. 'Content-Type' => 'application/json; charset=UTF-8'
  4474. ];
  4475. $post_data = [
  4476. 'app' => [
  4477. 'appid' => env('VOLC_APPID'),
  4478. 'token' => env('VOLC_TOKEN'),
  4479. 'cluster' => 'volcano_tts'
  4480. ],
  4481. 'user' => [
  4482. 'uid' => 'mp_audio'
  4483. ],
  4484. // 'audio' => [
  4485. // 'voice_type' =>
  4486. // ],
  4487. ];
  4488. }
  4489. public function scriptList($data) {
  4490. $uid = Site::getUid();
  4491. $script_id = getProp($data, 'script_id');
  4492. $script_name = getProp($data, 'script_name');
  4493. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  4494. if ($script_id) {
  4495. $query->where('id', $script_id);
  4496. }
  4497. if ($script_name) {
  4498. $query->where('script_name', 'like', "%{$script_name}%");
  4499. }
  4500. return $query->orderBy('created_at', 'desc')->paginate(12);
  4501. }
  4502. public function scripts($data) {
  4503. $uid = Site::getUid();
  4504. $script_id = getProp($data, 'script_id');
  4505. $script_name = getProp($data, 'script_name');
  4506. $is_products = getProp($data, 'is_products');
  4507. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  4508. if ($script_id) {
  4509. $query->where('id', $script_id);
  4510. }
  4511. if ($is_products !== '') {
  4512. $query->where('is_products', $is_products);
  4513. }
  4514. if ($script_name) {
  4515. $query->where('script_name', 'like', "%{$script_name}%");
  4516. }
  4517. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  4518. return (array)$value;
  4519. })->toArray();
  4520. }
  4521. public function scriptInfo($data) {
  4522. $uid = Site::getUid();
  4523. $script_id = getProp($data, 'script_id');
  4524. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  4525. // ->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();
  4526. ->selectRaw('id as script_id, script_name')->first();
  4527. if (!$script) Utils::throwError('20003:该剧本不存在!');
  4528. $script = (array)$script;
  4529. // 获取分集组信息
  4530. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  4531. ->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')
  4532. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  4533. $value = (array)$value;
  4534. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  4535. return (array)$value;
  4536. })->toArray();
  4537. $script['group'] = $groups;
  4538. return $script;
  4539. }
  4540. public function createScript($data) {
  4541. $script_name = getProp($data, 'script_name');
  4542. $uid = Site::getUid(); // 获取当前用户ID
  4543. $cpid = Site::getCpid(); // 获取当前公司组ID
  4544. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  4545. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  4546. $script_name .= '_'.date('YmdHis');
  4547. }
  4548. return DB::table('mp_scripts')->insertGetId([
  4549. 'script_name' => $script_name,
  4550. 'user_id' => $uid,
  4551. 'cpid' => $cpid,
  4552. 'created_at' => date('Y-m-d H:i:s'),
  4553. 'updated_at' => date('Y-m-d H:i:s')
  4554. ]);
  4555. }
  4556. public function editScript($data) {
  4557. $script_id = getProp($data, 'script_id');
  4558. $script_name = getProp($data, 'script_name');
  4559. $uid = Site::getUid(); // 获取当前用户ID
  4560. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  4561. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  4562. if ($id && (int)$id !== (int)$script_id) {
  4563. $script_name .= '_'.date('YmdHis');
  4564. }
  4565. return DB::table('mp_scripts')->where('id', $script_id)->update([
  4566. 'script_name' => $script_name,
  4567. 'updated_at' => date('Y-m-d H:i:s')
  4568. ]);
  4569. }
  4570. public function delScript($data) {
  4571. $script_id = getProp($data, 'script_id');
  4572. $uid = Site::getUid(); // 获取当前用户ID
  4573. if (!$script_id) Utils::throwError('20003:请选择剧本');
  4574. return DB::table('mp_scripts')->where('id', $script_id)->update([
  4575. 'is_deleted' => 1,
  4576. 'updated_at' => date('Y-m-d H:i:s')
  4577. ]);
  4578. }
  4579. public function createEpisode($data) {
  4580. $script_id = getProp($data, 'script_id');
  4581. $group_name = getProp($data, 'group_name');
  4582. $remark = getProp($data, 'remark');
  4583. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  4584. $uid = Site::getUid(); // 获取当前用户ID
  4585. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  4586. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  4587. $group_name .= '_'.date('YmdHis');
  4588. }
  4589. return DB::table('mp_script_episode_group')->insertGetId([
  4590. 'script_id' => $script_id,
  4591. 'group_name' => $group_name,
  4592. 'user_id' => $uid,
  4593. 'remark' => $remark,
  4594. 'created_at' => date('Y-m-d H:i:s'),
  4595. 'updated_at' => date('Y-m-d H:i:s')
  4596. ]);
  4597. }
  4598. public function editEpisode($data) {
  4599. $group_id = getProp($data, 'group_id');
  4600. $start_episode_number = getProp($data, 'start_episode_number');
  4601. $end_episode_number = getProp($data, 'end_episode_number');
  4602. $group_name = getProp($data, 'group_name');
  4603. $uid = Site::getUid(); // 获取当前用户ID
  4604. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  4605. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  4606. if ($id && (int)$id !== (int)$group_id) {
  4607. $group_name .= '_'.date('YmdHis');
  4608. }
  4609. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4610. 'group_name' => $group_name,
  4611. 'start_episode_number' => $start_episode_number,
  4612. 'end_episode_number' => $end_episode_number,
  4613. 'updated_at' => date('Y-m-d H:i:s')
  4614. ]);
  4615. }
  4616. public function delEpisode($data) {
  4617. $group_id = getProp($data, 'group_id');
  4618. $uid = Site::getUid(); // 获取当前用户ID
  4619. if (!$group_id) Utils::throwError('20003:请选择分集');
  4620. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4621. 'is_deleted' => 1,
  4622. 'updated_at' => date('Y-m-d H:i:s')
  4623. ]);
  4624. }
  4625. /**
  4626. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4627. *
  4628. * @param array $data 包含以下参数:
  4629. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4630. * - question: 用户问题(可选)
  4631. * - model: 使用的模型(r1 或 v3,默认 v3)
  4632. * @return \Generator 返回生成器,用于流式输出
  4633. */
  4634. public function generateEpisodes($data) {
  4635. // 文生文计费预检(special 档,每次调用扣 10)
  4636. $uid = Site::getUid();
  4637. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  4638. $script_id = getProp($data, 'script_id');
  4639. $group_id = getProp($data, 'group_id');
  4640. // $file = getProp($data, 'file');
  4641. $file = '';
  4642. $content = getProp($data, 'content', '');
  4643. // $bid = getProp($data, 'bid', 0);
  4644. $bid = 0;
  4645. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4646. if (!$group) {
  4647. Utils::throwError('20003:剧本分集不存在');
  4648. }
  4649. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  4650. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  4651. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  4652. $prompt = getProp($data, 'prompt');
  4653. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  4654. $model = getProp($data, 'model');
  4655. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4656. Utils::throwError('20003:该模型不存在!');
  4657. }
  4658. // 检查是否存在重叠的剧集序号范围
  4659. $exists_groups = DB::table('mp_script_episode_group')
  4660. ->where('script_id', $script_id)
  4661. ->where('id', '<>', $group_id) // 排除当前组
  4662. ->where('is_deleted', 0)
  4663. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4664. // 检查新范围是否与现有范围重叠
  4665. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4666. // 新范围的开始在现有范围内
  4667. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4668. ->where('end_episode_number', '>=', $start_episode_sequence);
  4669. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4670. // 新范围的结束在现有范围内
  4671. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4672. ->where('end_episode_number', '>=', $end_episode_sequence);
  4673. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4674. // 新范围完全包含现有范围
  4675. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4676. ->where('end_episode_number', '<=', $end_episode_sequence);
  4677. });
  4678. })
  4679. ->select('start_episode_number', 'end_episode_number')
  4680. ->get();
  4681. if ($exists_groups->isNotEmpty()) {
  4682. $conflict_ranges = [];
  4683. foreach ($exists_groups as $group) {
  4684. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4685. }
  4686. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4687. }
  4688. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4689. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4690. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4691. if ($model === 'deepseek-chat') {
  4692. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4693. $model = 'deepseek-v4-flash';
  4694. $thinkingMode = 'disabled';
  4695. } elseif ($model === 'deepseek-reasoner') {
  4696. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4697. $model = 'deepseek-v4-flash';
  4698. $thinkingMode = 'enabled';
  4699. }
  4700. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4701. if (!$script) {
  4702. Utils::throwError('20003:剧本不存在');
  4703. }
  4704. $content = getProp($group, 'content');
  4705. if (!$file && !$content && !$bid) {
  4706. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4707. }
  4708. // 提取文件内容
  4709. if ($file) {
  4710. $content = $this->extractFileContent($file);
  4711. if (!$content) {
  4712. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4713. }
  4714. } elseif ($bid) {
  4715. $content = $this->getContentByBid($bid);
  4716. if (!$content) {
  4717. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4718. }
  4719. } elseif ($content) {
  4720. $content = filterContent($content);
  4721. } elseif ($prompt) {
  4722. $content = filterContent($prompt);
  4723. } else {
  4724. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4725. }
  4726. // 构建消息
  4727. $messages = [
  4728. $this->sys_message,
  4729. [
  4730. 'role' => 'user',
  4731. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4732. ]
  4733. ];
  4734. $post_data = [
  4735. 'model' => $model,
  4736. 'messages' => $messages,
  4737. // 'max_tokens' => 8192,
  4738. 'temperature' => 0.7,
  4739. 'frequency_penalty' => 0,
  4740. 'presence_penalty' => 0,
  4741. 'thinking' => ['type' => $thinkingMode],
  4742. 'response_format' => ['type' => 'text'],
  4743. 'stream' => true
  4744. ];
  4745. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4746. // 根据模型类型选择调用方法
  4747. $fullContent = '';
  4748. $fullReasoningContent = '';
  4749. $usage = [];
  4750. $streamGenerator = $this->dispatchStreamByModel($post_data);
  4751. // 处理流式输出
  4752. foreach ($streamGenerator as $chunk) {
  4753. if (isset($chunk['type'])) {
  4754. if ($chunk['type'] === 'done') {
  4755. // 最终结果
  4756. $fullContent = $chunk['full_content'];
  4757. $fullReasoningContent = $chunk['full_reasoning'];
  4758. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4759. } else {
  4760. // 逐块yield数据
  4761. yield $chunk;
  4762. }
  4763. }
  4764. }
  4765. dLog('deepseek')->info('完整内容: '.$fullContent);
  4766. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4767. // 处理完整内容并返回最终结果
  4768. $script_arr = [];
  4769. if ($fullContent) {
  4770. $script_arr = extractScriptContent($fullContent);
  4771. }
  4772. logDB('deepseek', 'info', '解析内容', $script_arr);
  4773. if (!$script_arr['episodes']) {
  4774. Utils::throwError('20003:未生成剧本相关信息');
  4775. // yield [
  4776. // 'type' => 'done',
  4777. // 'script' => $script_arr,
  4778. // 'msg' => '未生成剧本相关信息',
  4779. // 'answer' => $fullContent,
  4780. // 'reasoning' => $fullReasoningContent,
  4781. // 'usage' => $usage
  4782. // ];
  4783. // return ;
  4784. }
  4785. try {
  4786. DB::beginTransaction();
  4787. // // 返回前保存剧本内容
  4788. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4789. // 'content' => $content,
  4790. // 'updated_at' => date('Y-m-d H:i:s')
  4791. // ]);
  4792. // if (!$boolen) {
  4793. // Utils::throwError('20003:保存剧本内容失败');
  4794. // }
  4795. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4796. // 'start_episode_number' => $start_episode_sequence,
  4797. // 'end_episode_number' => $end_episode_sequence,
  4798. // 'updated_at' => date('Y-m-d H:i:s')
  4799. // ]);
  4800. // if (!$boolen1) {
  4801. // Utils::throwError('20003:保存分集失败');
  4802. // }
  4803. $episode_content = '';
  4804. $episodes = [];
  4805. foreach ($script_arr['episodes'] as $item) {
  4806. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  4807. // $episodes[] = [
  4808. // 'script_id' => $script_id,
  4809. // 'episode_number' => $item['episode_number'],
  4810. // 'episode_name' => $item['episode_name'],
  4811. // 'episode_content' => $item['episode_content'],
  4812. // 'created_at' => date('Y-m-d H:i:s'),
  4813. // 'updated_at' => date('Y-m-d H:i:s'),
  4814. // ];
  4815. }
  4816. if ($episode_content) {
  4817. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4818. 'episode_content' => $episode_content,
  4819. 'updated_at' => date('Y-m-d H:i:s')
  4820. ]);
  4821. if (!$boolen2) {
  4822. Utils::throwError('20003:保存分集内容失败');
  4823. }
  4824. }else {
  4825. Utils::throwError('20003:分集剧本解析失败');
  4826. }
  4827. // 文生文成功计费(special 档):与落库同事务
  4828. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  4829. 'model' => $model,
  4830. 'script_id' => $script_id,
  4831. 'group_id' => $group_id,
  4832. 'source' => 'generateEpisodes',
  4833. ]);
  4834. }catch (\Exception $e) {
  4835. DB::rollBack();
  4836. Utils::throwError('20003:'.$e->getMessage());
  4837. }
  4838. DB::commit();
  4839. yield [
  4840. 'type' => 'done',
  4841. 'script' => $script_arr,
  4842. 'episode_content' => $episode_content,
  4843. 'answer' => $fullContent,
  4844. 'reasoning' => $fullReasoningContent,
  4845. 'usage' => $usage
  4846. ];
  4847. }
  4848. public function chatWithFileStream($data) {
  4849. // 剧本解析资产表计费预检(special 档)
  4850. $uid = Site::getUid();
  4851. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  4852. $script_id = getProp($data, 'script_id');
  4853. $group_id = getProp($data, 'group_id');
  4854. $file = getProp($data, 'file');
  4855. $content = getProp($data, 'content', '');
  4856. $bid = getProp($data, 'bid', 0);
  4857. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4858. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4859. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  4860. $prompt = getProp($data, 'prompt');
  4861. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4862. if (!empty($prompt)) {
  4863. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4864. }
  4865. $question = getProp($data, 'question', $baseQuestion);
  4866. $model = getProp($data, 'model');
  4867. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4868. Utils::throwError('20003:该模型不存在!');
  4869. }
  4870. // 检查是否存在重叠的剧集序号范围
  4871. $exists_groups = DB::table('mp_script_episode_group')
  4872. ->where('script_id', $script_id)
  4873. ->where('id', '<>', $group_id)
  4874. ->where('is_deleted', 0)
  4875. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4876. // 检查新范围是否与现有范围重叠
  4877. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4878. // 新范围的开始在现有范围内
  4879. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4880. ->where('end_episode_number', '>=', $start_episode_sequence);
  4881. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4882. // 新范围的结束在现有范围内
  4883. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4884. ->where('end_episode_number', '>=', $end_episode_sequence);
  4885. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4886. // 新范围完全包含现有范围
  4887. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4888. ->where('end_episode_number', '<=', $end_episode_sequence);
  4889. });
  4890. })
  4891. ->select('start_episode_number', 'end_episode_number')
  4892. ->get();
  4893. if ($exists_groups->isNotEmpty()) {
  4894. $conflict_ranges = [];
  4895. foreach ($exists_groups as $group) {
  4896. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4897. }
  4898. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4899. }
  4900. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4901. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4902. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4903. if ($model === 'deepseek-chat') {
  4904. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4905. $model = 'deepseek-v4-flash';
  4906. $thinkingMode = 'disabled';
  4907. } elseif ($model === 'deepseek-reasoner') {
  4908. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4909. $model = 'deepseek-v4-flash';
  4910. $thinkingMode = 'enabled';
  4911. }
  4912. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4913. if (!$script) {
  4914. Utils::throwError('20003:剧本不存在');
  4915. }
  4916. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4917. if (!$group) {
  4918. Utils::throwError('20003:剧本分集不存在');
  4919. }
  4920. if (!$file && !$content && !$bid) {
  4921. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4922. }
  4923. // 提取文件内容
  4924. if ($file) {
  4925. $content = $this->extractFileContent($file);
  4926. if (!$content) {
  4927. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4928. }
  4929. } elseif ($bid) {
  4930. $content = $this->getContentByBid($bid);
  4931. if (!$content) {
  4932. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4933. }
  4934. } elseif ($content) {
  4935. $content = filterContent($content);
  4936. } elseif ($prompt) {
  4937. $content = filterContent($prompt);
  4938. } else {
  4939. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4940. }
  4941. // 构建消息
  4942. $messages = [
  4943. [
  4944. 'role' => 'system',
  4945. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4946. 强制要求:\n
  4947. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4948. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4949. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  4950. 普通要求:\n
  4951. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  4952. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  4953. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  4954. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  4955. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  4956. 示例如下:\n
  4957. ###剧本名:西昆仑
  4958. ###故事梗概
  4959. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4960. ###剧本亮点
  4961. 亮点1:绝境奇药,生死一线
  4962. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4963. 亮点2:结拜兄妹,化解尴尬
  4964. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4965. 亮点3:纤发夺命,情愫暗涌
  4966. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4967. ###人物关系
  4968. 阿雪与梁萧之间存在兄妹之情。
  4969. ###核心矛盾
  4970. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4971. ###主体列表
  4972. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  4973. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  4974. 阴阳球:天地异宝,能化生精气,救人于危难。
  4975. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  4976. ###美术风格
  4977. 基础画风风格词:厚涂古风
  4978. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4979. ###场景列表
  4980. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  4981. [
  4982. 'role' => 'user',
  4983. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4984. ]
  4985. ];
  4986. $post_data = [
  4987. 'model' => $model,
  4988. 'messages' => $messages,
  4989. // 'max_tokens' => 8192,
  4990. 'temperature' => 0.7,
  4991. 'frequency_penalty' => 0,
  4992. 'presence_penalty' => 0,
  4993. 'thinking' => ['type' => $thinkingMode],
  4994. 'response_format' => ['type' => 'text'],
  4995. 'stream' => true
  4996. ];
  4997. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4998. // 根据模型类型选择调用方法
  4999. $fullContent = '';
  5000. $fullReasoningContent = '';
  5001. $usage = [];
  5002. $streamGenerator = $this->dispatchStreamByModel($post_data);
  5003. // 处理流式输出
  5004. foreach ($streamGenerator as $chunk) {
  5005. if (isset($chunk['type'])) {
  5006. if ($chunk['type'] === 'done') {
  5007. // 最终结果
  5008. $fullContent = $chunk['full_content'];
  5009. $fullReasoningContent = $chunk['full_reasoning'];
  5010. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5011. } else {
  5012. // 逐块yield数据
  5013. yield $chunk;
  5014. }
  5015. }
  5016. }
  5017. dLog('deepseek')->info('完整内容: '.$fullContent);
  5018. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  5019. // 处理完整内容并返回最终结果
  5020. $script_arr = [];
  5021. if ($fullContent) {
  5022. $script_arr = extractScriptContent($fullContent);
  5023. }
  5024. logDB('deepseek', 'info', '解析内容', $script_arr);
  5025. if (!$script_arr['roles']) {
  5026. Utils::throwError('20003:未生成剧本相关信息');
  5027. // yield [
  5028. // 'type' => 'done',
  5029. // 'script' => $script_arr,
  5030. // 'msg' => '未生成剧本相关信息',
  5031. // 'answer' => $fullContent,
  5032. // 'reasoning' => $fullReasoningContent,
  5033. // 'usage' => $usage
  5034. // ];
  5035. }
  5036. try {
  5037. DB::beginTransaction();
  5038. // // 返回前保存剧本内容
  5039. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  5040. // 'content' => $content,
  5041. // 'status' => '解析完成',
  5042. // 'updated_at' => date('Y-m-d H:i:s')
  5043. // ]);
  5044. // if (!$boolen) {
  5045. // Utils::throwError('20003:保存剧本内容失败');
  5046. // }
  5047. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  5048. 'start_episode_number' => $start_episode_sequence,
  5049. 'end_episode_number' => $end_episode_sequence,
  5050. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5051. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5052. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5053. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5054. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5055. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5056. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5057. 'status' => '解析完成',
  5058. 'content' => $content,
  5059. 'updated_at' => date('Y-m-d H:i:s')
  5060. ]);
  5061. if (!$boolen1) {
  5062. Utils::throwError('20003:保存分集失败');
  5063. }
  5064. // 剧本解析资产表成功计费(special 档):与落库同事务
  5065. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5066. 'model' => $model,
  5067. 'script_id' => $script_id,
  5068. 'group_id' => $group_id,
  5069. 'source' => 'chatWithFileStream',
  5070. ], 'special');
  5071. // $episodes = [];
  5072. // foreach ($script_arr['episodes'] as $item) {
  5073. // $episodes[] = [
  5074. // 'script_id' => $script_id,
  5075. // 'episode_number' => $item['episode_number'],
  5076. // 'episode_name' => $item['episode_name'],
  5077. // 'episode_content' => $item['episode_content'],
  5078. // 'created_at' => date('Y-m-d H:i:s'),
  5079. // 'updated_at' => date('Y-m-d H:i:s'),
  5080. // ];
  5081. // }
  5082. // if ($episodes) {
  5083. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  5084. // if (!$boolen2) {
  5085. // Utils::throwError('20003:保存分集内容失败');
  5086. // }
  5087. // }else {
  5088. // Utils::throwError('20003:分集剧本解析失败');
  5089. // }
  5090. }catch (\Exception $e) {
  5091. DB::rollBack();
  5092. Utils::throwError('20003:'.$e->getMessage());
  5093. }
  5094. DB::commit();
  5095. yield [
  5096. 'type' => 'done',
  5097. 'script' => $script_arr,
  5098. 'answer' => $fullContent,
  5099. 'reasoning' => $fullReasoningContent,
  5100. 'usage' => $usage
  5101. ];
  5102. }
  5103. /**
  5104. * 上传文件识别文字内容并与 DeepSeek 进行对话
  5105. *
  5106. * @param array $data 包含以下参数:
  5107. * - file: 上传的文件(UploadedFile 对象)或文件路径
  5108. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  5109. * - model: 使用的模型(r1 或 v3,默认 v3)
  5110. * @return array
  5111. */
  5112. public function chatWithFile($data) {
  5113. // 剧本解析资产表计费预检(special 档)
  5114. $uid = Site::getUid();
  5115. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  5116. $script_id = getProp($data, 'script_id');
  5117. $file = getProp($data, 'file');
  5118. $content = getProp($data, 'content', '');
  5119. $bid = getProp($data, 'bid', 0);
  5120. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  5121. $total_episode_num = getProp($data, 'total_episode_num', 30);
  5122. $prompt = getProp($data, 'prompt');
  5123. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  5124. if (!empty($prompt)) {
  5125. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  5126. }
  5127. $question = getProp($data, 'question', $baseQuestion);
  5128. // 处理文本模型
  5129. $model = getProp($data, 'model');
  5130. if (!$model) {
  5131. // 用户没有输入,使用默认值
  5132. $model = 'doubao-seed-2-0-mini-260215';
  5133. }
  5134. // 验证模型是否在可用模型表中
  5135. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5136. $model = 'doubao-seed-2-0-mini-260215';
  5137. }
  5138. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5139. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5140. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5141. if ($model === 'deepseek-chat') {
  5142. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5143. $model = 'deepseek-v4-flash';
  5144. $thinkingMode = 'disabled';
  5145. } elseif ($model === 'deepseek-reasoner') {
  5146. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5147. $model = 'deepseek-v4-flash';
  5148. $thinkingMode = 'enabled';
  5149. }
  5150. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  5151. if (!$script) {
  5152. Utils::throwError('20003:剧本不存在');
  5153. }
  5154. if (!$file && !$content && !$bid) {
  5155. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5156. }
  5157. // 提取文件内容
  5158. if ($file) {
  5159. $content = $this->extractFileContent($file);
  5160. if (!$content) {
  5161. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5162. }
  5163. } elseif ($bid) {
  5164. $content = $this->getContentByBid($bid);
  5165. if (!$content) {
  5166. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5167. }
  5168. } elseif ($content) {
  5169. $content = filterContent($content);
  5170. } elseif ($prompt) {
  5171. $content = filterContent($prompt);
  5172. } else {
  5173. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5174. }
  5175. // 构建消息
  5176. $messages = [
  5177. $this->sys_message,
  5178. [
  5179. 'role' => 'user',
  5180. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  5181. ]
  5182. ];
  5183. $post_data = [
  5184. 'model' => $model,
  5185. 'messages' => $messages,
  5186. // 'max_tokens' => 8192,
  5187. 'temperature' => 0.7,
  5188. 'frequency_penalty' => 0,
  5189. 'presence_penalty' => 0,
  5190. 'thinking' => ['type' => $thinkingMode],
  5191. 'response_format' => ['type' => 'text'],
  5192. 'stream' => false
  5193. ];
  5194. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5195. // 根据模型类型选择调用方法
  5196. $fullContent = '';
  5197. $usage = [];
  5198. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  5199. if (is_array($chatResult)) {
  5200. $fullContent = $chatResult['fullContent'];
  5201. $usage = $chatResult['usage'];
  5202. }
  5203. $script_arr = [];
  5204. // 处理结果
  5205. if ($fullContent) {
  5206. $script_arr = extractScriptContent($fullContent);
  5207. }
  5208. // 返回前保存剧本内容
  5209. DB::table('mp_scripts')->where('id', $script_id)->update([
  5210. 'content' => $content,
  5211. 'updated_at' => date('Y-m-d H:i:s')
  5212. ]);
  5213. // 剧本解析资产表成功计费(special 档):同时记录积分与 token 明细
  5214. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5215. 'model' => $model,
  5216. 'script_id' => $script_id,
  5217. 'source' => 'chatWithFile',
  5218. ], 'special');
  5219. return [
  5220. 'script' => $script_arr,
  5221. 'answer' => $fullContent,
  5222. 'usage' => $usage
  5223. ];
  5224. }
  5225. public function getEpisodeContent($data) {
  5226. $group_id = getProp($data, 'group_id');
  5227. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  5228. }
  5229. public function saveEpisodeContent($data) {
  5230. $script_id = getProp($data, 'script_id');
  5231. $group_id = getProp($data, 'group_id');
  5232. $start_episode_sequence = getProp($data, 'start_episode_number');
  5233. $end_episode_sequence = getProp($data, 'end_episode_number');
  5234. // 检查是否存在重叠的剧集序号范围
  5235. $exists_groups = DB::table('mp_script_episode_group')
  5236. ->where('script_id', $script_id)
  5237. ->where('id', '<>', $group_id) // 排除当前组
  5238. ->where('is_deleted', 0)
  5239. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  5240. // 检查新范围是否与现有范围重叠
  5241. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5242. // 新范围的开始在现有范围内
  5243. $q->where('start_episode_number', '<=', $start_episode_sequence)
  5244. ->where('end_episode_number', '>=', $start_episode_sequence);
  5245. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5246. // 新范围的结束在现有范围内
  5247. $q->where('start_episode_number', '<=', $end_episode_sequence)
  5248. ->where('end_episode_number', '>=', $end_episode_sequence);
  5249. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5250. // 新范围完全包含现有范围
  5251. $q->where('start_episode_number', '>=', $start_episode_sequence)
  5252. ->where('end_episode_number', '<=', $end_episode_sequence);
  5253. });
  5254. })
  5255. ->select('start_episode_number', 'end_episode_number')
  5256. ->get();
  5257. if ($exists_groups->isNotEmpty()) {
  5258. $conflict_ranges = [];
  5259. foreach ($exists_groups as $group) {
  5260. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  5261. }
  5262. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  5263. }
  5264. $episode_content = getProp($data, 'episode_content');
  5265. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  5266. 'content' => $episode_content,
  5267. 'start_episode_number' => $start_episode_sequence,
  5268. 'end_episode_number' => $end_episode_sequence,
  5269. 'updated_at' => date('Y-m-d H:i:s')
  5270. ]);
  5271. $script_arr =getProp($data, 'script', []);
  5272. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  5273. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  5274. $script_id = getProp($data, 'script_id');
  5275. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  5276. try {
  5277. DB::beginTransaction();
  5278. $update_data = [
  5279. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5280. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5281. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5282. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5283. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5284. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5285. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5286. 'status' => 3,
  5287. 'start_episode_sequence' => $start_episode_sequence,
  5288. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  5289. 'episode_num' => count($script_arr['episodes']),
  5290. 'updated_at' => date('Y-m-d H:i:s')
  5291. ];
  5292. // 保存剧本内容
  5293. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  5294. if (!$boolen) {
  5295. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  5296. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  5297. Utils::throwError('20003:剧本内容保存失败');
  5298. }
  5299. // 保存分集内容
  5300. // 删除历史分集内容
  5301. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  5302. $episodes = [];
  5303. $sequence = 1;
  5304. foreach ($script_arr['episodes'] as $episode) {
  5305. $segment_number = 1;
  5306. foreach($episode['segments'] as $segment) {
  5307. $episodes[] = [
  5308. 'script_id' => $script_id,
  5309. 'episode_number' => $episode['episode_number'],
  5310. 'title' => $episode['title'],
  5311. // 'content' => $episode['content'],
  5312. 'content' => '',
  5313. 'segment_number' => $segment_number,
  5314. 'segment_content' => $segment['segment_content'],
  5315. 'sequence' => $sequence,
  5316. 'created_at' => date('Y-m-d H:i:s'),
  5317. 'updated_at' => date('Y-m-d H:i:s')
  5318. ];
  5319. $sequence++;
  5320. $segment_number++;
  5321. }
  5322. }
  5323. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  5324. if (!$boolen2) {
  5325. dLog('deepseek')->info('分集内容保存失败', $episodes);
  5326. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  5327. Utils::throwError('20003:分集内容保存失败');
  5328. }
  5329. } catch (\Exception $e) {
  5330. DB::rollBack();
  5331. Utils::throwError('20003:'.$e->getMessage());
  5332. }
  5333. DB::commit();
  5334. return true;
  5335. }
  5336. public function getBookContent($data) {
  5337. $bid = getProp($data, 'bid');
  5338. $start_sequence = getProp($data, 'start_sequence');
  5339. $end_sequence = getProp($data, 'end_sequence');
  5340. $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])
  5341. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  5342. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  5343. return $return_content;
  5344. }
  5345. public function exportScript($data) {
  5346. $filename = getProp($data, 'filename');
  5347. $script_id = getProp($data, 'script_id');
  5348. $group_id = getProp($data, 'group_id');
  5349. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  5350. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  5351. if (!$script) Utils::throwError('20003:该剧本不存在!');
  5352. $script = (array)$script;
  5353. // 获取分集组信息
  5354. if ($group_id) {
  5355. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  5356. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  5357. ->get()->map(function($value) {
  5358. return (array)$value;
  5359. })->toArray();
  5360. }else {
  5361. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  5362. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  5363. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  5364. return (array)$value;
  5365. })->toArray();
  5366. }
  5367. if (!$groups) Utils::throwError('20003:分集不存在');
  5368. $script['group'] = $groups;
  5369. $export_type = getProp($data, 'export_type', 'txt');
  5370. // 生成文件名
  5371. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  5372. // 根据导出类型生成不同格式的文件
  5373. switch ($export_type) {
  5374. case 'txt':
  5375. return $this->exportScriptAsTxt($script, $filename);
  5376. case 'pdf':
  5377. return $this->exportScriptAsPdf($script, $filename);
  5378. default:
  5379. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  5380. }
  5381. }
  5382. /**
  5383. * 导出剧本为TXT格式
  5384. */
  5385. private function exportScriptAsTxt($script, $filename) {
  5386. // 构建TXT内容
  5387. $content = $this->buildScriptContent($script);
  5388. // 设置响应头,直接下载
  5389. header('Content-Type: text/plain; charset=utf-8');
  5390. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  5391. header('Content-Length: ' . strlen($content));
  5392. // 输出内容并结束
  5393. echo $content;
  5394. exit();
  5395. }
  5396. /**
  5397. * 导出剧本为PDF格式
  5398. */
  5399. private function exportScriptAsPdf($script, $filename) {
  5400. // 使用HTML转PDF的方式来更好地支持中文
  5401. $htmlContent = $this->buildScriptHtmlForPdf($script);
  5402. // 创建PDF实例
  5403. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  5404. // 设置文档信息
  5405. $pdf->SetCreator('剧本导出系统');
  5406. $pdf->SetAuthor('系统');
  5407. $pdf->SetTitle($script['script_name']);
  5408. $pdf->SetSubject('剧本导出');
  5409. // 设置边距
  5410. $pdf->SetMargins(15, 15, 15);
  5411. $pdf->SetAutoPageBreak(TRUE, 15);
  5412. // 添加页面
  5413. $pdf->AddPage();
  5414. // 注册并使用 simsun.ttf 字体
  5415. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  5416. // 使用HTML内容生成PDF
  5417. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  5418. // 直接输出PDF文件供下载
  5419. header('Content-Type: application/pdf');
  5420. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  5421. // 直接输出PDF内容
  5422. $pdf->Output($filename . '.pdf', 'D');
  5423. exit();
  5424. }
  5425. /**
  5426. * 构建用于PDF的HTML内容
  5427. */
  5428. private function buildScriptHtmlForPdf($script) {
  5429. $html = '<style>
  5430. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  5431. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  5432. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  5433. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  5434. .info { margin-bottom: 8px; }
  5435. .group { margin-bottom: 30px; page-break-inside: avoid; }
  5436. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  5437. .segment { margin-bottom: 10px; margin-left: 20px; }
  5438. .episode-content { white-space: pre-wrap; }
  5439. </style>';
  5440. // 标题
  5441. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  5442. // 处理分组数据
  5443. if (!empty($script['group']) && is_array($script['group'])) {
  5444. $groups = (array)$script['group'];
  5445. foreach ($groups as $group) {
  5446. $html .= '<div class="group">';
  5447. // 分组标题
  5448. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  5449. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  5450. // 故事梗概
  5451. if (!empty($group['intro'])) {
  5452. $html .= '<h3>故事梗概</h3>';
  5453. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  5454. }
  5455. // 剧本亮点
  5456. if (!empty($group['highlights'])) {
  5457. $html .= '<h3>剧本亮点</h3>';
  5458. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  5459. }
  5460. // 人物关系
  5461. if (!empty($group['role_relationship'])) {
  5462. $html .= '<h3>人物关系</h3>';
  5463. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  5464. }
  5465. // 核心矛盾
  5466. if (!empty($group['core_contradiction'])) {
  5467. $html .= '<h3>核心矛盾</h3>';
  5468. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  5469. }
  5470. // 主体列表
  5471. if (!empty($group['roles']) && is_array($group['roles'])) {
  5472. $html .= '<h3>主体列表</h3>';
  5473. $html .= '<ul>';
  5474. foreach ($group['roles'] as $role) {
  5475. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  5476. }
  5477. $html .= '</ul>';
  5478. }
  5479. // 美术风格
  5480. if (!empty($group['art_style'])) {
  5481. $html .= '<h3>美术风格</h3>';
  5482. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  5483. }
  5484. // 场景列表
  5485. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  5486. $html .= '<h3>场景列表</h3>';
  5487. $html .= '<ul>';
  5488. foreach ($group['scenes'] as $scene) {
  5489. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  5490. }
  5491. $html .= '</ul>';
  5492. }
  5493. // 分集剧本
  5494. if (!empty($group['episode_content'])) {
  5495. $html .= '<h3>分集剧本</h3>';
  5496. // 去除零宽字符和其他不可见字符
  5497. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  5498. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  5499. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  5500. }
  5501. $html .= '</div>';
  5502. }
  5503. }
  5504. return $html;
  5505. }
  5506. /**
  5507. * 构建PDF内容
  5508. */
  5509. private function buildPdfContent($pdf, $script) {
  5510. // 标题
  5511. $pdf->SetFont('dejavusans', 'B', 18);
  5512. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  5513. $pdf->Ln(5);
  5514. // 基本信息
  5515. $pdf->SetFont('dejavusans', '', 12);
  5516. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  5517. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  5518. $pdf->Ln(5);
  5519. // 剧本简介
  5520. if (!empty($script['intro'])) {
  5521. $pdf->SetFont('dejavusans', 'B', 14);
  5522. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  5523. $pdf->SetFont('dejavusans', '', 12);
  5524. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  5525. $pdf->Ln(3);
  5526. }
  5527. // 亮点
  5528. if (!empty($script['highlights'])) {
  5529. $pdf->SetFont('dejavusans', 'B', 14);
  5530. $pdf->Cell(0, 10, '亮点', 0, 1);
  5531. $pdf->SetFont('dejavusans', '', 12);
  5532. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  5533. $pdf->Ln(3);
  5534. }
  5535. // 核心矛盾
  5536. if (!empty($script['core_contradiction'])) {
  5537. $pdf->SetFont('dejavusans', 'B', 14);
  5538. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  5539. $pdf->SetFont('dejavusans', '', 12);
  5540. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  5541. $pdf->Ln(3);
  5542. }
  5543. // 艺术风格
  5544. if (!empty($script['art_style'])) {
  5545. $pdf->SetFont('dejavusans', 'B', 14);
  5546. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  5547. $pdf->SetFont('dejavusans', '', 12);
  5548. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  5549. $pdf->Ln(3);
  5550. }
  5551. // 备注
  5552. if (!empty($script['remark'])) {
  5553. $pdf->SetFont('dejavusans', 'B', 14);
  5554. $pdf->Cell(0, 10, '备注', 0, 1);
  5555. $pdf->SetFont('dejavusans', '', 12);
  5556. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  5557. $pdf->Ln(3);
  5558. }
  5559. // 角色列表
  5560. if (!empty($script['roles']) && is_array($script['roles'])) {
  5561. $pdf->SetFont('dejavusans', 'B', 14);
  5562. $pdf->Cell(0, 10, '角色列表', 0, 1);
  5563. $pdf->SetFont('dejavusans', '', 12);
  5564. foreach ($script['roles'] as $index => $role) {
  5565. if (is_array($role) || is_object($role)) {
  5566. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  5567. } else {
  5568. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  5569. }
  5570. }
  5571. $pdf->Ln(3);
  5572. }
  5573. // 角色关系
  5574. if (!empty($script['role_relationship'])) {
  5575. $pdf->SetFont('dejavusans', 'B', 14);
  5576. $pdf->Cell(0, 10, '角色关系', 0, 1);
  5577. $pdf->SetFont('dejavusans', '', 12);
  5578. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  5579. $pdf->Ln(3);
  5580. }
  5581. // 场景列表
  5582. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  5583. $pdf->SetFont('dejavusans', 'B', 14);
  5584. $pdf->Cell(0, 10, '场景列表', 0, 1);
  5585. $pdf->SetFont('dejavusans', '', 12);
  5586. foreach ($script['scenes'] as $index => $scene) {
  5587. if (is_array($scene) || is_object($scene)) {
  5588. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  5589. } else {
  5590. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  5591. }
  5592. }
  5593. $pdf->Ln(5);
  5594. }
  5595. // 分集内容
  5596. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  5597. $pdf->SetFont('dejavusans', 'B', 16);
  5598. $pdf->Cell(0, 12, '分集内容', 0, 1);
  5599. $pdf->Ln(3);
  5600. foreach ($script['episodes'] as $episode) {
  5601. // 检查是否需要新页面
  5602. if ($pdf->GetY() > 250) {
  5603. $pdf->AddPage();
  5604. }
  5605. $pdf->SetFont('dejavusans', 'B', 14);
  5606. $episodeTitle = '第' . $episode['episode_number'] . '集';
  5607. if (!empty($episode['title'])) {
  5608. $episodeTitle .= ':' . $episode['title'];
  5609. }
  5610. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  5611. // 处理分段内容
  5612. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  5613. $pdf->SetFont('dejavusans', '', 12);
  5614. foreach ($episode['segments'] as $segment) {
  5615. if (!empty($segment['segment_content'])) {
  5616. // 如果有分段编号,显示分段标题
  5617. if (!empty($segment['segment_number'])) {
  5618. $pdf->SetFont('dejavusans', 'B', 12);
  5619. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  5620. $pdf->SetFont('dejavusans', '', 12);
  5621. }
  5622. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  5623. $pdf->Ln(2);
  5624. }
  5625. }
  5626. }
  5627. $pdf->Ln(5);
  5628. }
  5629. }
  5630. }
  5631. /**
  5632. * 构建剧本文本内容
  5633. */
  5634. private function buildScriptContent($script) {
  5635. $content = '';
  5636. $groups = $script['group'];
  5637. $groups = (array)$groups;
  5638. foreach ($groups as $group) {
  5639. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  5640. // 剧本基本信息
  5641. if (!empty($group['intro'])) {
  5642. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  5643. }
  5644. if (!empty($group['highlights'])) {
  5645. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  5646. }
  5647. if (!empty($group['role_relationship'])) {
  5648. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  5649. }
  5650. if (!empty($group['core_contradiction'])) {
  5651. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  5652. }
  5653. if (!empty($group['roles']) && is_array($group['roles'])) {
  5654. $content .= "###主体列表\n";
  5655. foreach ($group['roles'] as $role) {
  5656. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  5657. }
  5658. $content .= "\n\n";
  5659. }
  5660. if (!empty($group['art_style'])) {
  5661. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  5662. }
  5663. // 场景信息
  5664. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  5665. $content .= "###场景列表\n";
  5666. foreach ($group['scenes'] as $scene) {
  5667. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  5668. }
  5669. $content .= "\n\n";
  5670. }
  5671. // 分集内容
  5672. if (!empty($group['episode_content'])) {
  5673. $content .= "###分集剧本\n";
  5674. $content .= $group['episode_content'];
  5675. // foreach ($script['episodes'] as $episode) {
  5676. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  5677. // // if (!empty($episode['episode_name'])) {
  5678. // // $content .= ":" . $episode['episode_name'];
  5679. // // }
  5680. // // $content .= "\n";
  5681. // $content .= $episode['episode_content'] . "\n\n";
  5682. // }
  5683. }
  5684. }
  5685. return $content;
  5686. }
  5687. /**
  5688. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  5689. *
  5690. * @param array $data 包含以下参数:
  5691. * - file: 上传的文件(UploadedFile 对象)或文件路径
  5692. * - question: 用户问题(可选)
  5693. * - model: 使用的模型(r1 或 v3,默认 v3)
  5694. * @return \Generator 返回生成器,用于流式输出
  5695. */
  5696. public function addChat($data) {
  5697. $uid = Site::getUid();
  5698. $anime_id = getProp($data, 'anime_id');
  5699. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5700. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5701. if (!$anime) Utils::throwError('20003:对话不存在');
  5702. $file = getProp($data, 'file');
  5703. $content = getProp($data, 'content', '');
  5704. $bid = getProp($data, 'bid', 0);
  5705. $script_id = getProp($data, 'script_id', 0);
  5706. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5707. $prompt = getProp($data, 'prompt');
  5708. $user_anime_name = getProp($anime, 'anime_name');
  5709. // 处理文本模型
  5710. $model = getProp($data, 'model');
  5711. if (!$model) {
  5712. // 用户没有输入,从anime表获取
  5713. $model = getProp($anime, 'model');
  5714. if (!$model) {
  5715. // anime表也没有,使用默认值
  5716. $model = 'doubao-seed-2-0-mini-260215';
  5717. }
  5718. }
  5719. // 验证模型是否在可用模型表中
  5720. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5721. $model = 'doubao-seed-2-0-mini-260215';
  5722. }
  5723. $is_multi = getProp($anime, 'is_multi');
  5724. $is_single = (int)$is_multi !== 1;
  5725. // 积分余额预检(仅单剧集模式收费)
  5726. if ($is_single) {
  5727. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5728. }
  5729. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5730. if ($prompt) {
  5731. $question .= "本次修改要求如下:\n{$prompt}";
  5732. }
  5733. // if (!$file && !$content && !$bid) {
  5734. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5735. // }
  5736. // 提取文件内容
  5737. if ($file) {
  5738. $content = $this->extractFileContent($file);
  5739. if (!$content) {
  5740. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5741. }
  5742. } elseif ($script_id) {
  5743. $content = $this->getContentByScriptId($script_id);
  5744. if (!$content) {
  5745. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5746. }
  5747. } elseif ($bid) {
  5748. $content = $this->getContentByBid($bid);
  5749. if (!$content) {
  5750. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5751. }
  5752. } elseif ($content) {
  5753. $content = filterContent($content);
  5754. } else {
  5755. $content = getProp($anime, 'content');
  5756. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5757. $need_generate_content = true;
  5758. }
  5759. }
  5760. // 美术风格
  5761. $input_art_style = getProp($data, 'art_style');
  5762. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5763. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5764. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5765. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5766. 中年女:邻居阿姨
  5767. 老年男:幽默大爷
  5768. 老年女:婆婆
  5769. 萌娃:奶气萌娃";
  5770. // 判断是否需要生成原文内容
  5771. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5772. // 如果需要生成原文内容,添加额外的要求
  5773. $content_generation_requirement = $need_generate_content
  5774. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5775. : "";
  5776. // 美术风格
  5777. if (!$mappedArtStyle) {
  5778. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5779. }else {
  5780. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5781. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5782. }else {
  5783. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5784. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5785. }
  5786. }
  5787. $systemPrompt = $is_single
  5788. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5789. 强制要求:
  5790. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5791. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5792. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5793. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5794. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5795. 普通要求:
  5796. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5797. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5798. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  5799. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5800. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5801. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5802. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5803. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5804. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5805. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5806. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5807. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5808. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5809. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5810. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5811. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5812. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5813. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5814. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5815. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5816. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5817. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5818. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5819. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5820. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5821. 5.{$mappedArtStyle_prompt}\n\n
  5822. 示例如下:\n
  5823. ###剧本名:西昆仑
  5824. ###故事梗概
  5825. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5826. ###剧本亮点
  5827. 亮点1:绝境奇药,生死一线
  5828. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5829. 亮点2:结拜兄妹,化解尴尬
  5830. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5831. 亮点3:纤发夺命,情愫暗涌
  5832. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5833. ###人物关系
  5834. 阿雪与梁萧之间存在兄妹之情。
  5835. ###核心矛盾
  5836. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5837. ###主体列表
  5838. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5839. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5840. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5841. 姿态:站立。}{{甜心小美}}
  5842. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5843. 全景,正面拍摄,青年女性,亚洲人。
  5844. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5845. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5846. 姿态:站立。}{{阳光青年}}
  5847. ###美术风格
  5848. 基础画风风格词:厚涂古风
  5849. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5850. ###场景列表
  5851. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5852. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5853. 无人物。}
  5854. ###分镜剧本
  5855. ##第1幕:徐家老旧厨房 白天 室内
  5856. 分镜1
  5857. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5858. 场景:徐家老旧厨房
  5859. 构图设计:全景,低角度仰视
  5860. 运镜调度:手持拍摄
  5861. 配音角色:旁白
  5862. 出镜角色:许芸-校服装、徐母
  5863. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5864. 画面类型:普通画面
  5865. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5866. 分镜2
  5867. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5868. 场景:徐家老旧厨房
  5869. 构图设计:近景,徐母面部特写
  5870. 运镜调度:固定镜头
  5871. 配音角色:徐母
  5872. 出镜角色:徐母
  5873. 台词内容:问我夜不归宿死哪儿去了。
  5874. 画面类型:对口型
  5875. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5876. ##第2幕:徐家简陋客厅 黄昏 室内
  5877. 分镜3
  5878. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5879. 场景:徐家简陋客厅
  5880. 构图设计:全景,景深虚化
  5881. 运镜调度:固定镜头
  5882. 配音角色:旁白
  5883. 出镜角色:无
  5884. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5885. 画面类型:普通画面
  5886. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5887. 分镜4
  5888. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5889. 场景:徐家简陋客厅
  5890. 构图设计:特写,火车票
  5891. 运镜调度:固定镜头
  5892. 配音角色:旁白
  5893. 出镜角色:无
  5894. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5895. 画面类型:普通画面
  5896. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5897. "
  5898. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5899. 强制要求:\n
  5900. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5901. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5902. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5903. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5904. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5905. 普通要求:\n
  5906. 1.剧本名(必须生成)必须与文档内容高度相关
  5907. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5908. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5909. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5910. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5911. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5912. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5913. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5914. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5915. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5916. 4.{$mappedArtStyle_prompt}\n\n
  5917. 示例如下:\n
  5918. ###剧本名:西昆仑
  5919. ###故事梗概
  5920. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5921. ###剧本亮点
  5922. 亮点1:绝境奇药,生死一线
  5923. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5924. 亮点2:结拜兄妹,化解尴尬
  5925. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5926. 亮点3:纤发夺命,情愫暗涌
  5927. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5928. ###人物关系
  5929. 阿雪与梁萧之间存在兄妹之情。
  5930. ###核心矛盾
  5931. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5932. ###主体列表
  5933. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5934. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5935. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5936. 姿态:站立。}{{甜心小美}}
  5937. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5938. 全景,正面拍摄,青年女性,亚洲人。
  5939. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5940. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5941. 姿态:站立。}{{阳光青年}}
  5942. ###美术风格
  5943. 基础画风风格词:厚涂古风
  5944. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5945. ###场景列表
  5946. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5947. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5948. 无人物。}";
  5949. // 构建消息
  5950. $messages = [
  5951. [
  5952. 'role' => 'system',
  5953. 'content' => $systemPrompt
  5954. ],
  5955. [
  5956. 'role' => 'user',
  5957. 'content' => "以下是文档内容:
  5958. {$content}
  5959. 用户问题:
  5960. {$question}"
  5961. ]
  5962. ];
  5963. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5964. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5965. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5966. if ($model === 'deepseek-chat') {
  5967. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5968. $model = 'deepseek-v4-flash';
  5969. $thinkingMode = 'disabled';
  5970. } elseif ($model === 'deepseek-reasoner') {
  5971. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5972. $model = 'deepseek-v4-flash';
  5973. $thinkingMode = 'enabled';
  5974. }
  5975. $post_data = [
  5976. 'model' => $model,
  5977. 'messages' => $messages,
  5978. // 'max_tokens' => 8192,
  5979. 'temperature' => 0.7,
  5980. 'frequency_penalty' => 0,
  5981. 'presence_penalty' => 0,
  5982. 'response_format' => ['type' => 'text'],
  5983. 'thinking' => ['type'=>$thinkingMode],
  5984. 'stream' => true // 启用流式输出
  5985. ];
  5986. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5987. // 根据模型类型选择调用方法
  5988. $fullContent = '';
  5989. $fullReasoningContent = '';
  5990. $usage = [];
  5991. try {
  5992. $streamGenerator = $this->dispatchStreamByModel($post_data);
  5993. // 验证返回值类型
  5994. if (!is_iterable($streamGenerator)) {
  5995. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5996. dLog('deepseek')->error('addChat流式生成器无效', [
  5997. 'generator_type' => $errorType,
  5998. 'model' => $model,
  5999. 'anime_id' => $anime_id
  6000. ]);
  6001. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  6002. 'type' => $errorType,
  6003. 'model' => $model
  6004. ]);
  6005. yield [
  6006. 'type' => 'error',
  6007. 'script' => [],
  6008. 'episode' => [],
  6009. 'answer' => '',
  6010. 'reasoning' => '',
  6011. 'usage' => [],
  6012. 'error' => '接口返回数据异常,请重新请求'
  6013. ];
  6014. return;
  6015. }
  6016. // 处理流式输出
  6017. foreach ($streamGenerator as $chunk) {
  6018. if (isset($chunk['type'])) {
  6019. if ($chunk['type'] === 'done') {
  6020. // 最终结果
  6021. $fullContent = $chunk['full_content'];
  6022. $fullReasoningContent = $chunk['full_reasoning'];
  6023. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6024. } else {
  6025. // 逐块yield数据
  6026. yield $chunk;
  6027. }
  6028. }
  6029. }
  6030. } catch (\Exception $e) {
  6031. // 解析上游错误详情(如 content_filter),便于日志定位与前端提示
  6032. $upstream_error = $this->resolveGptUpstreamError($e);
  6033. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  6034. 'model' => $model,
  6035. 'anime_id' => $anime_id,
  6036. 'upstream_status' => $upstream_error['status'],
  6037. 'upstream_code' => $upstream_error['code'],
  6038. 'upstream_body' => $upstream_error['body'],
  6039. 'trace' => $e->getTraceAsString()
  6040. ]);
  6041. logDB('deepseek', 'error', 'addChat流式处理失败', [
  6042. 'error' => $e->getMessage(),
  6043. 'model' => $model,
  6044. 'upstream_status' => $upstream_error['status'],
  6045. 'upstream_code' => $upstream_error['code'],
  6046. 'upstream_body' => $upstream_error['body']
  6047. ]);
  6048. yield [
  6049. 'type' => 'error',
  6050. 'script' => [],
  6051. 'episode' => [],
  6052. 'answer' => '',
  6053. 'reasoning' => '',
  6054. 'usage' => [],
  6055. 'error' => $this->buildChatErrorForUser($e, $upstream_error)
  6056. ];
  6057. return;
  6058. }
  6059. dLog('deepseek')->info('完整内容: '.$fullContent);
  6060. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6061. // 处理完整内容并返回最终结果
  6062. $script_arr = [];
  6063. if ($fullContent) {
  6064. $script_arr = handleScriptContent($fullContent);
  6065. dLog('deepseek')->info('解析内容', $script_arr);
  6066. logDB('deepseek', 'info', '解析内容', $script_arr);
  6067. }
  6068. if (empty($script_arr['roles'])) {
  6069. // 未生成剧本相关内容,保存对话记录并返回提示
  6070. dLog('deepseek')->info('未生成剧本相关的内容');
  6071. try {
  6072. DB::beginTransaction();
  6073. $now = date('Y-m-d H:i:s');
  6074. // 保存对话记录
  6075. $records = [
  6076. [
  6077. 'uid' => $uid,
  6078. 'anime_id' => $anime_id,
  6079. 'sequence' => 0,
  6080. 'role' => 'user',
  6081. 'content' => $prompt,
  6082. 'created_at' => $now,
  6083. 'updated_at' => $now
  6084. ],
  6085. [
  6086. 'uid' => $uid,
  6087. 'anime_id' => $anime_id,
  6088. 'sequence' => 0,
  6089. 'role' => 'assistant',
  6090. // 'content' => $fullContent,
  6091. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  6092. 'created_at' => $now,
  6093. 'updated_at' => $now
  6094. ]
  6095. ];
  6096. DB::table('mp_anime_records')->insert($records);
  6097. DB::commit();
  6098. } catch (\Exception $e) {
  6099. DB::rollBack();
  6100. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6101. }
  6102. yield [
  6103. 'type' => 'done',
  6104. 'script' => [],
  6105. 'episode' => [],
  6106. 'answer' => $fullContent,
  6107. 'reasoning' => $fullReasoningContent,
  6108. 'usage' => $usage,
  6109. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6110. ];
  6111. return;
  6112. }
  6113. // 如果需要生成原文内容,从script_arr中提取
  6114. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6115. $content = $script_arr['content'];
  6116. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  6117. if (!$content) {
  6118. yield [
  6119. 'type' => 'done',
  6120. 'script' => [],
  6121. 'episode' => [],
  6122. 'answer' => $fullContent,
  6123. 'reasoning' => $fullReasoningContent,
  6124. 'usage' => $usage,
  6125. 'error' => '未生成剧本内容,请调整提示词再试'
  6126. ];
  6127. return;
  6128. }
  6129. }
  6130. // 替换美术风格
  6131. if ($mappedArtStyle !== '') {
  6132. $script_arr['art_style'] = $mappedArtStyle;
  6133. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6134. }
  6135. // 新建动漫
  6136. if ($user_anime_name == '新剧本策划') {
  6137. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6138. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6139. // if (!$anime_name) {
  6140. // // 未识别到剧本名,保存对话记录并返回提示
  6141. // dLog('deepseek')->info('未能识别到剧本名称');
  6142. // try {
  6143. // DB::beginTransaction();
  6144. // $now = date('Y-m-d H:i:s');
  6145. // // 保存对话记录
  6146. // $records = [
  6147. // [
  6148. // 'uid' => $uid,
  6149. // 'anime_id' => $anime_id,
  6150. // 'sequence' => 0,
  6151. // 'role' => 'user',
  6152. // 'content' => $prompt,
  6153. // 'created_at' => $now,
  6154. // 'updated_at' => $now
  6155. // ],
  6156. // [
  6157. // 'uid' => $uid,
  6158. // 'anime_id' => $anime_id,
  6159. // 'sequence' => 0,
  6160. // 'role' => 'assistant',
  6161. // 'content' => '未能生成剧本名称,请重试',
  6162. // 'created_at' => $now,
  6163. // 'updated_at' => $now
  6164. // ]
  6165. // ];
  6166. // DB::table('mp_anime_records')->insert($records);
  6167. // DB::commit();
  6168. // } catch (\Exception $e) {
  6169. // DB::rollBack();
  6170. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6171. // }
  6172. // yield [
  6173. // 'type' => 'done',
  6174. // 'script' => [],
  6175. // 'episode' => [],
  6176. // 'answer' => $fullContent,
  6177. // 'reasoning' => $fullReasoningContent,
  6178. // 'usage' => $usage,
  6179. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  6180. // ];
  6181. // return;
  6182. // }
  6183. // 确认对话名称唯一性
  6184. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6185. $anime_name = $anime_name . '_' . date('YmdHis');
  6186. }
  6187. }else {
  6188. $anime_name = $user_anime_name;
  6189. }
  6190. $table_data = [
  6191. 'user_id' => $uid,
  6192. 'anime_name' => $anime_name,
  6193. 'model' => $model,
  6194. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6195. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6196. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6197. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6198. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6199. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6200. 'art_style_type' => $input_art_style,
  6201. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6202. 'status' => '解析完成',
  6203. 'content' => $content,
  6204. 'is_multi' => $is_multi,
  6205. 'ace_mode' => $ace_mode,
  6206. 'generate_status' => '待执行',
  6207. 'updated_at' => date('Y-m-d H:i:s')
  6208. ];
  6209. if ($table_data['content']) {
  6210. $chapters = splitContent($table_data['content']);
  6211. $chapter_count = count($chapters);
  6212. if ($chapter_count > 0) {
  6213. $table_data['start_episode_sequence'] = 1;
  6214. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6215. }
  6216. }
  6217. // 如果有剧本ID则进行绑定
  6218. if ($script_id) {
  6219. $table_data['script_id'] = $script_id;
  6220. }
  6221. $single_episode = [];
  6222. try {
  6223. DB::beginTransaction();
  6224. $now = date('Y-m-d H:i:s');
  6225. // 更新动漫大纲
  6226. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6227. if (!$boolen) {
  6228. dLog('deepseek')->info('动漫保存失败', $table_data);
  6229. Utils::throwError('20003:动漫保存失败');
  6230. }
  6231. // 保存对话记录
  6232. $records = [
  6233. [
  6234. 'uid' => $uid,
  6235. 'anime_id' => $anime_id,
  6236. 'sequence' => 0,
  6237. 'role' => 'user',
  6238. 'content' => $prompt,
  6239. 'created_at' => date('Y-m-d H:i:s'),
  6240. 'updated_at' => date('Y-m-d H:i:s')
  6241. ],
  6242. [
  6243. 'uid' => $uid,
  6244. 'anime_id' => $anime_id,
  6245. 'sequence' => 0,
  6246. 'role' => 'assistant',
  6247. 'content' => $fullContent,
  6248. 'created_at' => date('Y-m-d H:i:s'),
  6249. 'updated_at' => date('Y-m-d H:i:s')
  6250. ]
  6251. ];
  6252. // 保存对话记录
  6253. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6254. if (!$boolen3) {
  6255. Utils::throwError('20003:对话记录保存失败');
  6256. }
  6257. if ($is_single) {
  6258. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6259. if (empty($episode_arr['acts'])) {
  6260. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6261. }
  6262. $saveResult = $this->saveEpisodeVersionData(
  6263. $anime_id,
  6264. 1,
  6265. $episode_arr,
  6266. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6267. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6268. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6269. null,
  6270. null,
  6271. false,
  6272. $content,
  6273. $now
  6274. );
  6275. $single_episode = $saveResult['episode'];
  6276. $episode_id = $saveResult['episode_id'];
  6277. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6278. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6279. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6280. 'props' => json_encode($saveResult['merged_props'], 256),
  6281. 'updated_at' => $now
  6282. ]);
  6283. if ($boolen5 === false) {
  6284. Utils::throwError('20003:单剧集主表资源同步失败');
  6285. }
  6286. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6287. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6288. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6289. $episode_record_content = '确认分镜大纲';
  6290. if ($content !== '') {
  6291. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6292. }
  6293. $episode_records = [
  6294. [
  6295. 'uid' => $uid,
  6296. 'anime_id' => $anime_id,
  6297. 'role' => 'user',
  6298. 'content' => $episode_record_content,
  6299. 'sequence' => 1,
  6300. 'episode_id' => $episode_id,
  6301. 'created_at' => $now,
  6302. 'updated_at' => $now
  6303. ],
  6304. [
  6305. 'uid' => $uid,
  6306. 'anime_id' => $anime_id,
  6307. 'role' => 'assistant',
  6308. 'content' => $fullContent,
  6309. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6310. 'sequence' => 1,
  6311. 'episode_id' => $episode_id,
  6312. 'created_at' => $now,
  6313. 'updated_at' => $now
  6314. ]
  6315. ];
  6316. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6317. if (!$boolen4) {
  6318. Utils::throwError('20003:单剧集分镜记录保存失败');
  6319. }
  6320. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6321. if ($is_single && !empty($single_episode)) {
  6322. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6323. 'anime_id' => $anime_id,
  6324. 'episode_id' => $episode_id ?? 0,
  6325. 'model' => $model,
  6326. 'source' => 'addChat',
  6327. ]);
  6328. }
  6329. }
  6330. }catch (\Exception $e) {
  6331. DB::rollBack();
  6332. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6333. yield [
  6334. 'type' => 'done',
  6335. 'answer' => $fullContent,
  6336. 'reasoning' => $fullReasoningContent,
  6337. 'usage' => $usage,
  6338. 'error' => $e->getMessage(),
  6339. ];
  6340. return;
  6341. }
  6342. DB::commit();
  6343. dLog('deepseek')->info('保存完毕');
  6344. if ($is_single && !empty($single_episode)) {
  6345. // $this->batchSetGlobalRoleImg([
  6346. // 'anime_id' => $anime_id,
  6347. // ]);
  6348. // $this->batchSetGlobalSceneImg([
  6349. // 'anime_id' => $anime_id,
  6350. // ]);
  6351. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6352. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6353. }
  6354. $table_data['anime_id'] = $anime_id;
  6355. $table_data['roles'] = json_decode($table_data['roles'], true);
  6356. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6357. // $table_data['episodes'] = $script_arr['episodes'];
  6358. unset($table_data['created_at']);
  6359. unset($table_data['updated_at']);
  6360. unset($table_data['status']);
  6361. dLog('deepseek')->info('开始返回');
  6362. yield [
  6363. 'type' => 'done',
  6364. 'script' => $table_data,
  6365. 'episode' => $single_episode,
  6366. 'answer' => $fullContent,
  6367. 'reasoning' => $fullReasoningContent,
  6368. 'usage' => $usage
  6369. ];
  6370. }
  6371. public function reGenerateAnime($data) {
  6372. $uid = Site::getUid();
  6373. $file = getProp($data, 'file');
  6374. $content = getProp($data, 'content', '');
  6375. $bid = getProp($data, 'bid', 0);
  6376. $script_id = getProp($data, 'script_id', 0);
  6377. $anime_id = getProp($data, 'anime_id');
  6378. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6379. if (!$anime) {
  6380. Utils::throwError('20003:该对话不存在');
  6381. }
  6382. $user_anime_name = getProp($anime, 'anime_name');
  6383. $prompt = getProp($data, 'prompt');
  6384. // 处理文本模型
  6385. $model = getProp($data, 'model');
  6386. if (!$model) {
  6387. // 用户没有输入,从anime表获取
  6388. $model = getProp($anime, 'model');
  6389. if (!$model) {
  6390. // anime表也没有,使用默认值
  6391. $model = 'doubao-seed-2-0-mini-260215';
  6392. }
  6393. }
  6394. // 验证模型是否在可用模型表中
  6395. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6396. $model = 'doubao-seed-2-0-mini-260215';
  6397. }
  6398. $is_multi = getProp($anime, 'is_multi', 1);
  6399. $is_single = (int)$is_multi !== 1;
  6400. // 积分余额预检(仅单剧集模式收费)
  6401. if ($is_single) {
  6402. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  6403. }
  6404. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  6405. if ($is_single) {
  6406. $episode_exists = DB::table('mp_anime_episodes')
  6407. ->where('anime_id', $anime_id)
  6408. ->where('sequence', 1)
  6409. ->exists();
  6410. if ($episode_exists) {
  6411. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  6412. }
  6413. }
  6414. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  6415. if ($prompt) {
  6416. $question .= "本次修改要求如下:\n{$prompt}";
  6417. }
  6418. // 提取文件内容
  6419. if ($file) {
  6420. $content = $this->extractFileContent($file);
  6421. if (!$content) {
  6422. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6423. }
  6424. } elseif ($script_id) {
  6425. $content = $this->getContentByScriptId($script_id);
  6426. if (!$content) {
  6427. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6428. }
  6429. } elseif ($bid) {
  6430. $content = $this->getContentByBid($bid);
  6431. if (!$content) {
  6432. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6433. }
  6434. } elseif ($content) {
  6435. $content = filterContent($content);
  6436. }else {
  6437. $content = filterContent(getProp($anime, 'content'));
  6438. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6439. $need_generate_content = true;
  6440. }
  6441. }
  6442. // 判断是否需要生成原文内容
  6443. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6444. // 如果需要生成原文内容,添加额外的要求
  6445. $content_generation_requirement = $need_generate_content
  6446. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6447. : "";
  6448. // 美术风格
  6449. $input_art_style = getProp($anime, 'art_style');
  6450. if (!$input_art_style) {
  6451. $input_art_style = getProp($data, 'art_style');
  6452. }
  6453. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6454. // 美术风格
  6455. if (!$mappedArtStyle) {
  6456. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6457. }else {
  6458. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6459. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6460. }else {
  6461. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6462. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6463. }
  6464. }
  6465. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  6466. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  6467. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  6468. 中年女:邻居阿姨
  6469. 老年男:幽默大爷
  6470. 老年女:婆婆
  6471. 萌娃:奶气萌娃";
  6472. $system_message = ['role'=>'system', 'content'=>$is_single
  6473. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6474. 强制要求:
  6475. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6476. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6477. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6478. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6479. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6480. 普通要求:
  6481. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6482. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6483. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6484. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6485. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6486. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6487. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6488. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6489. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6490. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6491. 3.$mappedArtStyle_prompt\n\n
  6492. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6493. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6494. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6495. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  6496. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  6497. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6498. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6499. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6500. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6501. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6502. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6503. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6504. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6505. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6506. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  6507. 示例如下:\n
  6508. ###剧本名:西昆仑
  6509. ###故事梗概
  6510. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6511. ###剧本亮点
  6512. 亮点1:绝境奇药,生死一线
  6513. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6514. 亮点2:结拜兄妹,化解尴尬
  6515. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6516. 亮点3:纤发夺命,情愫暗涌
  6517. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6518. ###人物关系
  6519. 阿雪与梁萧之间存在兄妹之情。
  6520. ###核心矛盾
  6521. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6522. ###主体列表
  6523. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6524. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6525. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6526. 姿态:站立。}{{甜心小美}}
  6527. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6528. 全景,正面拍摄,青年女性,亚洲人。
  6529. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6530. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6531. 姿态:站立。}{{阳光青年}}
  6532. ###美术风格
  6533. 基础画风风格词:厚涂古风
  6534. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6535. ###场景列表
  6536. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6537. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6538. 无人物。}
  6539. ###分镜剧本
  6540. ##第1幕:徐家老旧厨房 白天 室内
  6541. 分镜1
  6542. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6543. 场景:徐家老旧厨房
  6544. 构图设计:全景,低角度仰视
  6545. 运镜调度:手持拍摄
  6546. 配音角色:旁白
  6547. 出镜角色:许芸-校服装、徐母
  6548. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6549. 画面类型:普通画面
  6550. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6551. 分镜2
  6552. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6553. 场景:徐家老旧厨房
  6554. 构图设计:近景,徐母面部特写
  6555. 运镜调度:固定镜头
  6556. 配音角色:徐母
  6557. 出镜角色:徐母
  6558. 台词内容:问我夜不归宿死哪儿去了。
  6559. 画面类型:对口型
  6560. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6561. ##第2幕:徐家简陋客厅 黄昏 室内
  6562. 分镜3
  6563. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6564. 场景:徐家简陋客厅
  6565. 构图设计:全景,景深虚化
  6566. 运镜调度:固定镜头
  6567. 配音角色:旁白
  6568. 出镜角色:无
  6569. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6570. 画面类型:普通画面
  6571. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6572. 分镜4
  6573. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6574. 场景:徐家简陋客厅
  6575. 构图设计:特写,火车票
  6576. 运镜调度:固定镜头
  6577. 配音角色:旁白
  6578. 出镜角色:无
  6579. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6580. 画面类型:普通画面
  6581. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  6582. "
  6583. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6584. 强制要求:\n
  6585. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6586. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6587. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6588. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6589. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6590. 普通要求:\n
  6591. 1.剧本名(必须生成)必须与文档内容高度相关
  6592. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6593. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6594. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6595. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6596. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6597. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6598. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6599. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6600. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6601. 4.$mappedArtStyle_prompt\n\n
  6602. 示例如下:\n
  6603. ###剧本名:西昆仑
  6604. ###故事梗概
  6605. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6606. ###剧本亮点
  6607. 亮点1:绝境奇药,生死一线
  6608. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6609. 亮点2:结拜兄妹,化解尴尬
  6610. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6611. 亮点3:纤发夺命,情愫暗涌
  6612. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6613. ###人物关系
  6614. 阿雪与梁萧之间存在兄妹之情。
  6615. ###核心矛盾
  6616. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6617. ###主体列表
  6618. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6619. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6620. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6621. 姿态:站立。}{{甜心小美}}
  6622. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6623. 全景,正面拍摄,青年女性,亚洲人。
  6624. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6625. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6626. 姿态:站立。}{{阳光青年}}
  6627. ###美术风格
  6628. 基础画风风格词:厚涂古风
  6629. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6630. ###场景列表
  6631. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6632. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6633. 无人物。}"];
  6634. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6635. $episode_count = $this->extractEpisodeNumber($prompt);
  6636. if ((int)getProp($anime, 'is_multi') !== 1) {
  6637. yield [
  6638. 'type' => 'done',
  6639. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6640. 'reasoning' => '',
  6641. 'usage' => []
  6642. ];
  6643. return;
  6644. }
  6645. if ($episode_count) {
  6646. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6647. $system_message = [
  6648. 'role' => 'system',
  6649. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6650. 强制要求:\n
  6651. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6652. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6653. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6654. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6655. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6656. 普通要求:\n
  6657. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6658. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6659. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6660. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6661. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6662. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6663. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6664. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6665. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6666. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6667. 示例如下:\n
  6668. ###剧本名:西昆仑
  6669. ###故事梗概
  6670. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6671. ###剧本亮点
  6672. 亮点1:绝境奇药,生死一线
  6673. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6674. 亮点2:结拜兄妹,化解尴尬
  6675. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6676. 亮点3:纤发夺命,情愫暗涌
  6677. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6678. ###人物关系
  6679. 阿雪与梁萧之间存在兄妹之情。
  6680. ###核心矛盾
  6681. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6682. ###主体列表
  6683. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6684. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6685. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6686. 姿态:站立。}{{甜心小美}}
  6687. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6688. 全景,正面拍摄,青年女性,亚洲人。
  6689. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6690. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6691. 姿态:站立。}{{阳光青年}}
  6692. ###美术风格
  6693. 基础画风风格词:厚涂古风
  6694. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6695. ###场景列表
  6696. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6697. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6698. 无人物。}
  6699. ###分集详细内容
  6700. ##第1章 重生
  6701. 我重生了。
  6702. 源于一个男人偏执的暗恋。
  6703. ##第2章 相救
  6704. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6705. 我眼睛扫向站在锅炉后的卞大伟。"
  6706. ];
  6707. // 构建消息
  6708. $messages = [
  6709. $system_message,
  6710. [
  6711. 'role' => 'user',
  6712. 'content' => "以下是文档内容:
  6713. {$content}
  6714. 用户问题:
  6715. {$question}"
  6716. ]
  6717. ];
  6718. }else {
  6719. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6720. // 构建消息
  6721. $messages = [
  6722. $system_message,
  6723. [
  6724. 'role' => 'user',
  6725. 'content' => "以下是文档内容:
  6726. {$content}
  6727. 用户问题:
  6728. {$question}"
  6729. ]
  6730. ];
  6731. }else {
  6732. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6733. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6734. return (array)$value;
  6735. })->toArray();
  6736. array_unshift($messages, $system_message);
  6737. $messages[] = [
  6738. 'role' => 'user',
  6739. 'content' => $prompt
  6740. ];
  6741. }
  6742. }
  6743. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6744. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6745. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6746. if ($model === 'deepseek-chat') {
  6747. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6748. $model = 'deepseek-v4-flash';
  6749. $thinkingMode = 'disabled';
  6750. } elseif ($model === 'deepseek-reasoner') {
  6751. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6752. $model = 'deepseek-v4-flash';
  6753. $thinkingMode = 'enabled';
  6754. }
  6755. $post_data = [
  6756. 'model' => $model,
  6757. 'messages' => $messages,
  6758. // 'max_tokens' => 8192,
  6759. 'temperature' => 0.7,
  6760. 'frequency_penalty' => 0,
  6761. 'presence_penalty' => 0,
  6762. 'response_format' => ['type' => 'text'],
  6763. 'thinking' => ['type' => $thinkingMode],
  6764. 'stream' => true // 启用流式输出
  6765. ];
  6766. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6767. // 根据模型类型选择调用方法
  6768. $fullContent = '';
  6769. $fullReasoningContent = '';
  6770. $usage = [];
  6771. // dd($post_data);
  6772. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6773. try {
  6774. $streamGenerator = $this->dispatchStreamByModel($post_data);
  6775. // 验证返回值类型
  6776. if (!is_iterable($streamGenerator)) {
  6777. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6778. dLog('deepseek')->error('方法名流式生成器无效', [
  6779. 'generator_type' => $errorType,
  6780. 'model' => $model,
  6781. // 添加其他上下文信息
  6782. ]);
  6783. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6784. 'type' => $errorType,
  6785. 'model' => $model
  6786. ]);
  6787. yield [
  6788. 'type' => 'error',
  6789. // 根据方法返回相应的空数据结构
  6790. 'answer' => '',
  6791. 'reasoning' => '',
  6792. 'usage' => [],
  6793. 'error' => '接口返回数据异常,请重新请求'
  6794. ];
  6795. return;
  6796. }
  6797. // 处理流式输出
  6798. foreach ($streamGenerator as $chunk) {
  6799. if (isset($chunk['type'])) {
  6800. if ($chunk['type'] === 'done') {
  6801. $fullContent = $chunk['full_content'];
  6802. $fullReasoningContent = $chunk['full_reasoning'];
  6803. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6804. } else {
  6805. yield $chunk;
  6806. }
  6807. }
  6808. }
  6809. } catch (\Exception $e) {
  6810. // 解析上游错误详情(如 content_filter),便于日志定位与前端提示
  6811. $upstream_error = $this->resolveGptUpstreamError($e);
  6812. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6813. 'model' => $model,
  6814. 'upstream_status' => $upstream_error['status'],
  6815. 'upstream_code' => $upstream_error['code'],
  6816. 'upstream_body' => $upstream_error['body'],
  6817. 'trace' => $e->getTraceAsString()
  6818. ]);
  6819. logDB('deepseek', 'error', '方法名流式处理失败', [
  6820. 'error' => $e->getMessage(),
  6821. 'model' => $model,
  6822. 'upstream_status' => $upstream_error['status'],
  6823. 'upstream_code' => $upstream_error['code'],
  6824. 'upstream_body' => $upstream_error['body']
  6825. ]);
  6826. yield [
  6827. 'type' => 'error',
  6828. // 根据方法返回相应的空数据结构
  6829. 'answer' => '',
  6830. 'reasoning' => '',
  6831. 'usage' => [],
  6832. 'error' => $this->buildChatErrorForUser($e, $upstream_error)
  6833. ];
  6834. return;
  6835. }
  6836. dLog('deepseek')->info('完整内容: '.$fullContent);
  6837. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6838. // 处理完整内容并返回最终结果
  6839. $script_arr = [];
  6840. if ($fullContent) {
  6841. $script_arr = handleScriptContent($fullContent);
  6842. dLog('deepseek')->info('解析内容', $script_arr);
  6843. logDB('deepseek', 'info', '解析内容', $script_arr);
  6844. }
  6845. if (empty($script_arr['roles'])) {
  6846. // 未生成剧本相关内容,保存对话记录并返回提示
  6847. dLog('deepseek')->info('未生成剧本相关的内容');
  6848. try {
  6849. $now = date('Y-m-d H:i:s');
  6850. // 保存对话记录
  6851. $records = [
  6852. [
  6853. 'uid' => $uid,
  6854. 'anime_id' => $anime_id,
  6855. 'sequence' => 0,
  6856. 'role' => 'user',
  6857. 'content' => $prompt,
  6858. 'created_at' => $now,
  6859. 'updated_at' => $now
  6860. ],
  6861. [
  6862. 'uid' => $uid,
  6863. 'anime_id' => $anime_id,
  6864. 'sequence' => 0,
  6865. 'role' => 'assistant',
  6866. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6867. 'created_at' => $now,
  6868. 'updated_at' => $now
  6869. ]
  6870. ];
  6871. DB::table('mp_anime_records')->insert($records);
  6872. } catch (\Exception $e) {
  6873. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6874. }
  6875. yield [
  6876. 'type' => 'done',
  6877. 'script' => [],
  6878. 'episode' => [],
  6879. 'answer' => $fullContent,
  6880. 'reasoning' => $fullReasoningContent,
  6881. 'usage' => $usage,
  6882. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6883. ];
  6884. return;
  6885. }
  6886. // 替换美术风格
  6887. if ($mappedArtStyle !== '') {
  6888. $script_arr['art_style'] = $mappedArtStyle;
  6889. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6890. }
  6891. if ($user_anime_name != '新剧本策划') {
  6892. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6893. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6894. // 确认对话名称唯一性
  6895. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6896. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6897. }
  6898. }else {
  6899. $anime_name = $user_anime_name;
  6900. }
  6901. $table_data = [
  6902. 'user_id' => $uid,
  6903. 'model' => $model,
  6904. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6905. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6906. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6907. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6908. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6909. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6910. 'art_style_type' => $input_art_style,
  6911. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6912. 'status' => '解析完成',
  6913. 'generate_status' => '待执行',
  6914. 'updated_at' => date('Y-m-d H:i:s')
  6915. ];
  6916. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6917. // 如果是修改集数,则将content内容更新(会改变原文)
  6918. if (isset($episode_count) && $episode_count > 0) {
  6919. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6920. $table_data['start_episode_sequence'] = 1;
  6921. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6922. }else {
  6923. // 如果需要生成原文内容,从script_arr中提取
  6924. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6925. $table_data['content'] = $script_arr['content'];
  6926. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6927. if (!$table_data['content']) {
  6928. yield [
  6929. 'type' => 'done',
  6930. 'script' => [],
  6931. 'episode' => [],
  6932. 'answer' => $fullContent,
  6933. 'reasoning' => $fullReasoningContent,
  6934. 'usage' => $usage,
  6935. 'error' => '未生成剧本内容,请调整提示词再试'
  6936. ];
  6937. return;
  6938. }
  6939. }
  6940. if (isset($table_data['content']) && $table_data['content']) {
  6941. $chapters = splitContent($table_data['content']);
  6942. $chapter_count = count($chapters);
  6943. if ($chapter_count > 0) {
  6944. $table_data['start_episode_sequence'] = 1;
  6945. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6946. }
  6947. }
  6948. }
  6949. $single_episode = [];
  6950. try {
  6951. DB::beginTransaction();
  6952. $now = date('Y-m-d H:i:s');
  6953. // 更新动漫大纲
  6954. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6955. if (!$boolen) {
  6956. dLog('deepseek')->info('对话修改失败', $table_data);
  6957. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6958. Utils::throwError('20003:对话修改失败');
  6959. }
  6960. // 保存对话记录
  6961. $records = [
  6962. [
  6963. 'uid' => $uid,
  6964. 'anime_id' => $anime_id,
  6965. 'sequence' => 0,
  6966. 'role' => 'user',
  6967. 'content' => $prompt,
  6968. 'created_at' => $now,
  6969. 'updated_at' => $now
  6970. ],
  6971. [
  6972. 'uid' => $uid,
  6973. 'anime_id' => $anime_id,
  6974. 'sequence' => 0,
  6975. 'role' => 'assistant',
  6976. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6977. 'content' => $fullContent,
  6978. 'created_at' => $now,
  6979. 'updated_at' => $now
  6980. ]
  6981. ];
  6982. // 保存对话记录
  6983. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6984. if (!$boolen3) {
  6985. Utils::throwError('20003:对话记录保存失败');
  6986. }
  6987. // 单剧集模式:生成并保存剧集信息
  6988. if ($is_single) {
  6989. $anime_name = getProp($anime, 'anime_name', '未命名');
  6990. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6991. if (empty($episode_arr['acts'])) {
  6992. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6993. }
  6994. $saveResult = $this->saveEpisodeVersionData(
  6995. $anime_id,
  6996. 1,
  6997. $episode_arr,
  6998. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6999. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7000. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7001. null,
  7002. null,
  7003. false,
  7004. $content,
  7005. $now
  7006. );
  7007. $single_episode = $saveResult['episode'];
  7008. $episode_id = $saveResult['episode_id'];
  7009. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7010. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7011. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7012. 'props' => json_encode($saveResult['merged_props'], 256),
  7013. 'updated_at' => $now
  7014. ]);
  7015. if ($boolen5 === false) {
  7016. Utils::throwError('20003:单剧集主表资源同步失败');
  7017. }
  7018. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7019. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7020. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7021. $episode_record_content = '确认分镜大纲';
  7022. if ($content !== '') {
  7023. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7024. }
  7025. $episode_records = [
  7026. [
  7027. 'uid' => $uid,
  7028. 'anime_id' => $anime_id,
  7029. 'role' => 'user',
  7030. 'content' => $episode_record_content,
  7031. 'sequence' => 1,
  7032. 'episode_id' => $episode_id,
  7033. 'created_at' => $now,
  7034. 'updated_at' => $now
  7035. ],
  7036. [
  7037. 'uid' => $uid,
  7038. 'anime_id' => $anime_id,
  7039. 'role' => 'assistant',
  7040. 'content' => $fullContent,
  7041. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7042. 'sequence' => 1,
  7043. 'episode_id' => $episode_id,
  7044. 'created_at' => $now,
  7045. 'updated_at' => $now
  7046. ]
  7047. ];
  7048. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7049. if (!$boolen4) {
  7050. Utils::throwError('20003:单剧集分镜记录保存失败');
  7051. }
  7052. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7053. if ($is_single && !empty($single_episode)) {
  7054. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7055. 'anime_id' => $anime_id,
  7056. 'episode_id' => $episode_id ?? 0,
  7057. 'model' => $model,
  7058. 'source' => 'reGenerateAnime',
  7059. ]);
  7060. }
  7061. }
  7062. }catch (\Exception $e) {
  7063. DB::rollBack();
  7064. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  7065. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  7066. yield [
  7067. 'type' => 'done',
  7068. 'answer' => $fullContent,
  7069. 'reasoning' => $fullReasoningContent,
  7070. 'usage' => $usage,
  7071. 'error' => $e->getMessage(),
  7072. ];
  7073. return;
  7074. }
  7075. DB::commit();
  7076. dLog('deepseek')->info('保存完毕');
  7077. if ($is_single && !empty($single_episode)) {
  7078. // $this->batchSetGlobalRoleImg([
  7079. // 'anime_id' => $anime_id,
  7080. // ]);
  7081. // $this->batchSetGlobalSceneImg([
  7082. // 'anime_id' => $anime_id,
  7083. // ]);
  7084. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7085. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7086. }
  7087. $table_data['anime_id'] = $anime_id;
  7088. $table_data['roles'] = json_decode($table_data['roles'], true);
  7089. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7090. unset($table_data['updated_at']);
  7091. unset($table_data['status']);
  7092. yield [
  7093. 'type' => 'done',
  7094. 'script' => $table_data,
  7095. 'episode' => $single_episode,
  7096. 'answer' => $fullContent,
  7097. 'reasoning' => $fullReasoningContent,
  7098. 'usage' => $usage
  7099. ];
  7100. }
  7101. public function chat($data) {
  7102. $uid = Site::getUid();
  7103. // 积分余额预检(不足直接报错)
  7104. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  7105. $anime_id = getProp($data, 'anime_id');
  7106. $file = getProp($data, 'file');
  7107. $content = getProp($data, 'content', '');
  7108. $bid = getProp($data, 'bid', 0);
  7109. $script_id = getProp($data, 'script_id', 0);
  7110. $episode_number = getProp($data, 'episode_number', 1);
  7111. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7112. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7113. if (!$anime) Utils::throwError('20003:该对话不存在!');
  7114. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  7115. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  7116. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  7117. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  7118. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  7119. $roles = is_array($roles) ? $roles : [];
  7120. $scenes = is_array($scenes) ? $scenes : [];
  7121. // 获取最后一集序号
  7122. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  7123. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  7124. // 转换主体列表和场景列表的格式
  7125. // 获取参考主体或场景
  7126. if ((int)$episode_number === 1) {
  7127. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  7128. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  7129. }else {
  7130. $prev_episode_number = $episode_number - 1;
  7131. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  7132. }
  7133. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  7134. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  7135. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  7136. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  7137. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  7138. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  7139. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  7140. 中年女:邻居阿姨
  7141. 老年男:幽默大爷
  7142. 老年女:婆婆
  7143. 萌娃:奶气萌娃";
  7144. if ($roles_content) {
  7145. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  7146. 主体范围:\n {$roles_content}\n
  7147. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  7148. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  7149. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7150. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7151. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  7152. }else {
  7153. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7154. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  7155. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7156. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7157. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  7158. }
  7159. if ($scenes_content) {
  7160. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7161. 场景范围:\n {$scenes_content}\n
  7162. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  7163. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7164. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7165. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  7166. }else {
  7167. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7168. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7169. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7170. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  7171. }
  7172. // 提取文件内容
  7173. if ($file) {
  7174. $uploaded_content = $this->extractFileContent($file);
  7175. if (!$uploaded_content) {
  7176. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7177. }
  7178. } elseif ($script_id) {
  7179. $uploaded_content = $this->getContentByScriptId($script_id);
  7180. if (!$uploaded_content) {
  7181. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7182. }
  7183. } elseif ($bid) {
  7184. $uploaded_content = $this->getContentByBid($bid);
  7185. if (!$uploaded_content) {
  7186. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7187. }
  7188. } elseif ($content) {
  7189. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  7190. }
  7191. // elseif ($prompt) {
  7192. // $uploaded_content = filterContent($prompt);
  7193. // }
  7194. else {
  7195. $uploaded_content = '';
  7196. }
  7197. $input_art_style = getProp($anime, 'art_style');
  7198. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7199. // 美术风格
  7200. if (!$mappedArtStyle) {
  7201. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7202. }else {
  7203. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7204. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7205. }else {
  7206. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7207. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7208. }
  7209. }
  7210. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7211. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7212. // 强制要求:
  7213. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7214. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7215. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7216. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  7217. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  7218. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  7219. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  7220. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  7221. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  7222. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  7223. // - 分镜要和场景列表、人物主体保持一致\n
  7224. // 普通要求:
  7225. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7226. // {$role_demo}
  7227. // {$scene_demo}
  7228. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  7229. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  7230. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  7231. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  7232. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  7233. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  7234. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  7235. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  7236. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  7237. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  7238. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  7239. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  7240. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  7241. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  7242. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  7243. // 5.$mappedArtStyle_prompt\n\n
  7244. // 示例格式:\n
  7245. // 第1集:隐形的守护者
  7246. // ###故事梗概
  7247. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7248. // ###美术风格
  7249. // 基础画风风格词:韩漫二次元
  7250. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  7251. // ###主体列表
  7252. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  7253. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  7254. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  7255. // ###场景列表
  7256. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  7257. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7258. // 无人物。}
  7259. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  7260. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  7261. // 无人物。}
  7262. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  7263. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  7264. // 无人物。}
  7265. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  7266. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  7267. // 无人物。}
  7268. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  7269. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  7270. // 无人物。}
  7271. // ###分镜剧本
  7272. // ##第1幕:徐家老旧厨房 白天 室内
  7273. // 分镜1
  7274. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  7275. // 场景:徐家老旧厨房
  7276. // 构图设计:全景,低角度仰视
  7277. // 运镜调度:手持拍摄
  7278. // 配音角色:旁白
  7279. // 出镜角色:许芸-校服装、徐母
  7280. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  7281. // 画面类型:普通画面
  7282. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  7283. // 分镜2
  7284. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  7285. // 场景:徐家老旧厨房
  7286. // 构图设计:近景,徐母面部特写
  7287. // 运镜调度:固定镜头
  7288. // 配音角色:徐母
  7289. // 出镜角色:徐母
  7290. // 台词内容:问我夜不归宿死哪儿去了。
  7291. // 画面类型:对口型
  7292. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  7293. // ##第2幕:徐家简陋客厅 黄昏 室内
  7294. // 分镜3
  7295. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  7296. // 场景:徐家简陋客厅
  7297. // 构图设计:全景,景深虚化
  7298. // 运镜调度:固定镜头
  7299. // 配音角色:旁白
  7300. // 出镜角色:无
  7301. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  7302. // 画面类型:普通画面
  7303. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  7304. // 分镜4
  7305. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  7306. // 场景:徐家简陋客厅
  7307. // 构图设计:特写,火车票
  7308. // 运镜调度:固定镜头
  7309. // 配音角色:旁白
  7310. // 出镜角色:无
  7311. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  7312. // 画面类型:普通画面
  7313. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  7314. // \n\n";
  7315. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7316. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7317. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  7318. 普通要求:
  7319. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7320. {$role_demo}
  7321. {$scene_demo}
  7322. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  7323. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  7324. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  7325. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7326. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  7327. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  7328. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  7329. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  7330. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  7331. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  7332. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  7333. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  7334. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  7335. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  7336. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  7337. 5.$mappedArtStyle_prompt
  7338. 6.《情绪-视听语言映射表》:
  7339. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7340. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7341. -----|---------|------------|----------------
  7342. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7343. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7344. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7345. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7346. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7347. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7348. -----|---------|------------|----------------
  7349. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7350. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7351. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7352. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7353. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7354. --------|---------|--------------|-------------
  7355. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7356. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7357. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7358. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7359. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7360. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7361. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7362. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7363. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7364. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7365. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7366. -----|---------|------------|------------
  7367. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7368. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7369. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7370. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7371. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7372. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7373. --------|---------|--------------|----------
  7374. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7375. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7376. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7377. 6.6 声音设计与潜意识影响 (Soundscape)
  7378. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7379. -----|---------|------------|------------------
  7380. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7381. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7382. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7383. 理论基石:
  7384. - The Five C's of Cinematography by Joseph V. Mascelli
  7385. - Film Art: An Introduction by David Bordwell
  7386. - Sight, Sound, Motion by Herbert Zettl
  7387. - Notes on the Cinematograph by Robert Bresson
  7388. \n\n
  7389. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  7390. 示例格式:\n
  7391. 第1集:隐形的守护者
  7392. ###故事梗概
  7393. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7394. ###美术风格
  7395. 基础画风风格词:韩漫二次元
  7396. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  7397. ###主体列表
  7398. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  7399. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  7400. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  7401. ###场景列表
  7402. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  7403. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7404. 无人物。}
  7405. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  7406. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  7407. 无人物。}
  7408. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  7409. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  7410. 无人物。}
  7411. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  7412. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  7413. 无人物。}
  7414. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  7415. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  7416. 无人物。}
  7417. ###分镜剧本
  7418. ##第1幕:徐家老旧厨房 白天 室内
  7419. 分镜1
  7420. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  7421. 场景:徐家老旧厨房
  7422. 构图设计:全景,低角度仰视
  7423. 运镜调度:手持拍摄
  7424. 配音角色:旁白
  7425. 出镜角色:许芸-校服装、徐母
  7426. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  7427. 画面类型:普通画面
  7428. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  7429. 分镜2
  7430. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  7431. 场景:徐家老旧厨房
  7432. 构图设计:近景,徐母面部特写
  7433. 运镜调度:固定镜头
  7434. 配音角色:徐母
  7435. 出镜角色:徐母
  7436. 台词内容:问我夜不归宿死哪儿去了。
  7437. 画面类型:对口型
  7438. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  7439. ##第2幕:徐家简陋客厅 黄昏 室内
  7440. 分镜3
  7441. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  7442. 场景:徐家简陋客厅
  7443. 构图设计:全景,景深虚化
  7444. 运镜调度:固定镜头
  7445. 配音角色:旁白
  7446. 出镜角色:无
  7447. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  7448. 画面类型:普通画面
  7449. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  7450. 分镜4
  7451. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  7452. 场景:徐家简陋客厅
  7453. 构图设计:特写,火车票
  7454. 运镜调度:固定镜头
  7455. 配音角色:旁白
  7456. 出镜角色:无
  7457. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  7458. 画面类型:普通画面
  7459. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  7460. \n\n";
  7461. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7462. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  7463. $is_regenerate_version = true;
  7464. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7465. $prompt = $origin_prompt;
  7466. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7467. // 获取章节内容
  7468. $full_content = getProp($anime, 'content');
  7469. if ($uploaded_content) {
  7470. $full_content = $uploaded_content;
  7471. }
  7472. // 根据章节内容拆分章节
  7473. $chapters = splitContent($full_content);
  7474. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7475. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7476. $messages = [];
  7477. if ($prompt == '确认分镜大纲') {
  7478. // 暂时保留
  7479. $content = $chapter_content;
  7480. if ($is_single) $content = $full_content; // 单剧集使用全文
  7481. if (!$content) {
  7482. Utils::throwError('20003:章节内容无法获取,请确认');
  7483. }
  7484. $question = $is_single
  7485. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7486. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7487. // 构建消息
  7488. $messages[] =
  7489. [
  7490. 'role' => 'user',
  7491. 'content' => $question
  7492. ];
  7493. }else if ($prompt == '继续策划下一集') {
  7494. if ($is_single) {
  7495. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7496. }
  7497. $content = $chapter_content;
  7498. if (!$content) {
  7499. Utils::throwError('20003:章节内容无法获取,请确认');
  7500. }
  7501. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7502. // 获取上一集最后记录
  7503. $prev_sequence = $episode_number - 1;
  7504. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7505. // 构建消息
  7506. $messages[] =
  7507. [
  7508. 'role' => 'user',
  7509. 'content' => $question
  7510. ];
  7511. }else {
  7512. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7513. if (!$content) {
  7514. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7515. }
  7516. if (!$content) {
  7517. Utils::throwError('20003:章节内容无法获取,请确认');
  7518. }
  7519. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7520. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7521. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7522. if ($origin_prompt) {
  7523. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  7524. }
  7525. $messages[] =
  7526. [
  7527. 'role' => 'user',
  7528. 'content' => $question
  7529. ];
  7530. }
  7531. // 处理文本模型
  7532. $model = getProp($data, 'model');
  7533. if (!$model) {
  7534. // 用户没有输入,从anime表获取
  7535. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7536. $model = getProp($anime, 'model');
  7537. if (!$model) {
  7538. // anime表也没有,使用默认值
  7539. $model = 'doubao-seed-2-0-mini-260215';
  7540. }
  7541. }
  7542. // 验证模型是否在可用模型表中
  7543. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7544. $model = 'doubao-seed-2-0-mini-260215';
  7545. }
  7546. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7547. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7548. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7549. if ($model === 'deepseek-chat') {
  7550. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7551. $model = 'deepseek-v4-flash';
  7552. $thinkingMode = 'disabled';
  7553. } elseif ($model === 'deepseek-reasoner') {
  7554. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7555. $model = 'deepseek-v4-flash';
  7556. $thinkingMode = 'enabled';
  7557. }
  7558. $post_data = [
  7559. 'model' => $model,
  7560. 'messages' => $messages,
  7561. // 'max_tokens' => 8192,
  7562. 'temperature' => 0.2,
  7563. 'frequency_penalty' => 0,
  7564. 'presence_penalty' => 0,
  7565. 'response_format' => ['type' => 'text'],
  7566. 'thinking' => ['type' => $thinkingMode],
  7567. 'stream' => true // 启用流式输出
  7568. ];
  7569. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7570. // 根据模型类型选择调用方法
  7571. $fullContent = '';
  7572. $fullReasoningContent = '';
  7573. $usage = [];
  7574. try {
  7575. $streamGenerator = $this->dispatchStreamByModel($post_data);
  7576. // 验证返回值类型
  7577. if (!is_iterable($streamGenerator)) {
  7578. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7579. dLog('deepseek')->error('chat流式生成器无效', [
  7580. 'generator_type' => $errorType,
  7581. 'model' => $model,
  7582. 'anime_id' => $anime_id,
  7583. 'episode_number' => $episode_number
  7584. ]);
  7585. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7586. 'type' => $errorType,
  7587. 'model' => $model
  7588. ]);
  7589. yield [
  7590. 'type' => 'error',
  7591. 'episode' => [],
  7592. 'answer' => '',
  7593. 'reasoning' => '',
  7594. 'usage' => [],
  7595. 'error' => '接口返回数据异常,请重新请求'
  7596. ];
  7597. return;
  7598. }
  7599. // 处理流式输出
  7600. foreach ($streamGenerator as $chunk) {
  7601. if (isset($chunk['type'])) {
  7602. if ($chunk['type'] === 'done') {
  7603. // 最终结果
  7604. $fullContent = $chunk['full_content'];
  7605. $fullReasoningContent = $chunk['full_reasoning'];
  7606. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7607. } else {
  7608. // 逐块yield数据
  7609. yield $chunk;
  7610. }
  7611. }
  7612. }
  7613. } catch (\Exception $e) {
  7614. // 解析上游错误详情(如 content_filter),便于日志定位与前端提示
  7615. $upstream_error = $this->resolveGptUpstreamError($e);
  7616. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7617. 'model' => $model,
  7618. 'anime_id' => $anime_id,
  7619. 'episode_number' => $episode_number,
  7620. 'upstream_status' => $upstream_error['status'],
  7621. 'upstream_code' => $upstream_error['code'],
  7622. 'upstream_body' => $upstream_error['body'],
  7623. 'trace' => $e->getTraceAsString()
  7624. ]);
  7625. logDB('deepseek', 'error', 'chat流式处理失败', [
  7626. 'error' => $e->getMessage(),
  7627. 'model' => $model,
  7628. 'upstream_status' => $upstream_error['status'],
  7629. 'upstream_code' => $upstream_error['code'],
  7630. 'upstream_body' => $upstream_error['body']
  7631. ]);
  7632. yield [
  7633. 'type' => 'error',
  7634. 'episode' => [],
  7635. 'answer' => '',
  7636. 'reasoning' => '',
  7637. 'usage' => [],
  7638. 'error' => $this->buildChatErrorForUser($e, $upstream_error)
  7639. ];
  7640. return;
  7641. }
  7642. dLog('deepseek')->info('完整内容: '.$fullContent);
  7643. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7644. // 处理完整内容并返回最终结果
  7645. $episode_arr = handleEpisodeContent($fullContent);
  7646. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7647. if (empty($episode_arr['acts'])) {
  7648. // 未生成剧本相关内容,保存对话记录并返回提示
  7649. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  7650. try {
  7651. $now = date('Y-m-d H:i:s');
  7652. // 保存对话记录
  7653. $records = [
  7654. [
  7655. 'uid' => $uid,
  7656. 'anime_id' => $anime_id,
  7657. 'sequence' => $episode_number,
  7658. 'role' => 'user',
  7659. 'content' => $prompt,
  7660. 'created_at' => $now,
  7661. 'updated_at' => $now
  7662. ],
  7663. [
  7664. 'uid' => $uid,
  7665. 'anime_id' => $anime_id,
  7666. 'sequence' => $episode_number,
  7667. 'role' => 'assistant',
  7668. 'content' => $fullContent,
  7669. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7670. 'created_at' => $now,
  7671. 'updated_at' => $now
  7672. ]
  7673. ];
  7674. DB::table('mp_anime_records')->insert($records);
  7675. } catch (\Exception $e) {
  7676. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7677. }
  7678. yield [
  7679. 'type' => 'done',
  7680. 'episode' => [],
  7681. 'answer' => $fullContent,
  7682. 'reasoning' => $fullReasoningContent,
  7683. 'usage' => $usage,
  7684. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  7685. ];
  7686. return;
  7687. }
  7688. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  7689. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  7690. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  7691. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  7692. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  7693. $existing_props = is_array($existing_props) ? $existing_props : [];
  7694. $now = date('Y-m-d H:i:s');
  7695. try {
  7696. DB::beginTransaction();
  7697. $saveResult = $this->saveEpisodeVersionData(
  7698. $anime_id,
  7699. $episode_number,
  7700. $episode_arr,
  7701. $existing_roles,
  7702. $existing_scenes,
  7703. $existing_props,
  7704. $current_episode,
  7705. $base_episode,
  7706. $is_regenerate_version,
  7707. $content,
  7708. $now
  7709. );
  7710. $episode = $saveResult['episode'];
  7711. $episode_id = $saveResult['episode_id'];
  7712. $merged_roles = $saveResult['merged_roles'];
  7713. $merged_scenes = $saveResult['merged_scenes'];
  7714. $merged_props = $saveResult['merged_props'];
  7715. $record_content = $origin_prompt;
  7716. if ($uploaded_content !== '') {
  7717. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  7718. }
  7719. $records = [
  7720. [
  7721. 'uid' => $uid,
  7722. 'anime_id' => $anime_id,
  7723. 'role' => 'user',
  7724. 'content' => $record_content,
  7725. 'sequence' => $episode_number,
  7726. 'episode_id' => $episode_id,
  7727. 'created_at' => $now,
  7728. 'updated_at' => $now
  7729. ],
  7730. [
  7731. 'uid' => $uid,
  7732. 'anime_id' => $anime_id,
  7733. 'role' => 'assistant',
  7734. 'content' => $fullContent,
  7735. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7736. 'sequence' => $episode_number,
  7737. 'episode_id' => $episode_id,
  7738. 'created_at' => $now,
  7739. 'updated_at' => $now
  7740. ]
  7741. ];
  7742. $boolen4 = DB::table('mp_anime_records')->insert($records);
  7743. if (!$boolen4) {
  7744. Utils::throwError('20003:对话记录保存失败');
  7745. }
  7746. // 保存模型和内容到anime表
  7747. $update_anime_data = [
  7748. 'model' => $model,
  7749. 'updated_at' => $now
  7750. ];
  7751. if ($uploaded_content) {
  7752. $update_anime_data['content'] = $uploaded_content;
  7753. }
  7754. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  7755. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7756. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7757. 'anime_id' => $anime_id,
  7758. 'episode_number' => $episode_number,
  7759. 'model' => $model,
  7760. 'source' => 'chat',
  7761. ]);
  7762. }catch (\Exception $e) {
  7763. DB::rollBack();
  7764. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7765. yield [
  7766. 'type' => 'done',
  7767. 'answer' => $fullContent,
  7768. 'reasoning' => $fullReasoningContent,
  7769. 'usage' => $usage,
  7770. 'error' => $e->getMessage(),
  7771. ];
  7772. return;
  7773. }
  7774. DB::commit();
  7775. if ($is_global_generate_pics) {
  7776. // // 批量生成全局角色图片
  7777. // $this->batchSetGlobalRoleImg([
  7778. // 'anime_id' => $anime_id,
  7779. // ], true);
  7780. // // 批量生成全局场景图片
  7781. // $this->batchSetGlobalSceneImg([
  7782. // 'anime_id' => $anime_id,
  7783. // ], true);
  7784. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7785. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7786. }
  7787. $episode['episode_id'] = $episode_id;
  7788. $episode['roles'] = $merged_roles;
  7789. $episode['scenes'] = $merged_scenes;
  7790. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  7791. yield [
  7792. 'type' => 'done',
  7793. 'episode' => $episode,
  7794. 'answer' => $fullContent,
  7795. 'reasoning' => $fullReasoningContent,
  7796. 'usage' => $usage
  7797. ];
  7798. }
  7799. public function addChatForAce($data) {
  7800. $uid = Site::getUid();
  7801. $anime_id = getProp($data, 'anime_id');
  7802. if (!$anime_id) Utils::throwError('20003:请选择对话');
  7803. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  7804. if (!$anime) Utils::throwError('20003:对话不存在');
  7805. $file = getProp($data, 'file');
  7806. $content = getProp($data, 'content', '');
  7807. $bid = getProp($data, 'bid', 0);
  7808. $script_id = getProp($data, 'script_id', 0);
  7809. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  7810. $prompt = getProp($data, 'prompt');
  7811. $is_multi = getProp($anime, 'is_multi');
  7812. $is_single = (int)$is_multi !== 1;
  7813. // 积分余额预检(仅单剧集模式收费)
  7814. if ($is_single) {
  7815. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  7816. }
  7817. $extra_products = getProp($data, 'products', []);
  7818. if (!$extra_products) {
  7819. $extra_products = getProp($anime, 'extra_products');
  7820. if ($extra_products) {
  7821. $extra_products = json_decode($extra_products, true);
  7822. }else {
  7823. $extra_products = [];
  7824. }
  7825. }else {
  7826. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7827. }
  7828. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7829. $anime_script_id = getProp($anime, 'script_id');
  7830. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  7831. $cpid = Site::getCpid();
  7832. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7833. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7834. ->where('mapping.script_id', $anime_script_id)
  7835. ->where('product.cpid', $cpid)
  7836. ->where('product.is_deleted', 0);
  7837. $mappings = $script_products_mappings->select(
  7838. 'mapping.product_id',
  7839. 'mapping.episode_number',
  7840. 'product.product_name',
  7841. 'product.type',
  7842. 'product.product',
  7843. 'product.pic_prompt',
  7844. 'product.url',
  7845. 'product.pic_task_id',
  7846. 'product.pic_task_status',
  7847. 'product.three_view_image_url'
  7848. )
  7849. ->get();
  7850. // 按 product_id 分组,合并 episode_number
  7851. $productMap = [];
  7852. foreach ($mappings as $item) {
  7853. $product_id = $item->product_id;
  7854. $product_name = $item->product_name;
  7855. // 处理product_name两边的符号
  7856. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7857. if (!isset($productMap[$product_id])) {
  7858. $productMap[$product_id] = [
  7859. 'product_id' => $product_id,
  7860. 'product_name' => $product_name,
  7861. 'type' => (int)$item->type,
  7862. 'product' => (int)$item->product,
  7863. 'pic_prompt' => $item->pic_prompt,
  7864. 'url' => $item->url,
  7865. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7866. 'pic_task_id' => $item->pic_task_id,
  7867. 'pic_task_status' => $item->pic_task_status,
  7868. 'episode_numbers' => [],
  7869. ];
  7870. }
  7871. // 添加 episode_number(去重)
  7872. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7873. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7874. }
  7875. }
  7876. // 将查询到的剧本资产合并到extra_products中
  7877. // 先构建extra_products的索引(以product_id为key,用于去重)
  7878. $extraProductsMap = [];
  7879. foreach ($extra_products as $item) {
  7880. $key = getProp($item, 'product_id');
  7881. if ($key) {
  7882. $extraProductsMap[$key] = $item;
  7883. }
  7884. }
  7885. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7886. foreach ($productMap as $product) {
  7887. $product_id = $product['product_id'];
  7888. // 如果不存在则添加(不带episode_number信息)
  7889. if (!isset($extraProductsMap[$product_id])) {
  7890. $extraProductsMap[$product_id] = [
  7891. 'product_id' => $product['product_id'],
  7892. 'product_name' => $product['product_name'],
  7893. 'type' => $product['type'],
  7894. 'product' => $product['product'],
  7895. 'pic_prompt' => $product['pic_prompt'],
  7896. 'url' => $product['url'],
  7897. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  7898. 'pic_task_id' => $product['pic_task_id'],
  7899. 'pic_task_status' => $product['pic_task_status'],
  7900. ];
  7901. }
  7902. }
  7903. // 重新赋值给extra_products
  7904. $extra_products = array_values($extraProductsMap);
  7905. }
  7906. $user_anime_name = getProp($anime, 'anime_name');
  7907. // 处理提示词
  7908. if ($prompt && $extra_products) {
  7909. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7910. foreach($extra_products as $item) {
  7911. $product_name = getProp($item, 'product_name');
  7912. if ($product_name) {
  7913. // 替换 {product_name} 为 product_name
  7914. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7915. }
  7916. }
  7917. }
  7918. // 处理文本模型
  7919. $model = getProp($data, 'model');
  7920. if (!$model) {
  7921. // 用户没有输入,从anime表获取
  7922. $model = getProp($anime, 'model');
  7923. if (!$model) {
  7924. // anime表也没有,使用默认值
  7925. $model = 'deepseek-v4-pro';
  7926. }
  7927. }
  7928. // 验证模型是否在可用模型表中
  7929. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7930. $model = 'deepseek-v4-pro';
  7931. }
  7932. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7933. if ($prompt) {
  7934. $question .= "本次修改要求如下:\n{$prompt}";
  7935. }
  7936. // if (!$file && !$content && !$bid) {
  7937. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  7938. // }
  7939. // 提取文件内容
  7940. if ($file) {
  7941. $content = $this->extractFileContent($file);
  7942. if (!$content) {
  7943. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7944. }
  7945. } elseif ($script_id) {
  7946. $content = $this->getContentByScriptId($script_id);
  7947. if (!$content) {
  7948. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7949. }
  7950. } elseif ($bid) {
  7951. $content = $this->getContentByBid($bid);
  7952. if (!$content) {
  7953. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7954. }
  7955. } elseif ($content) {
  7956. $content = filterContent($content);
  7957. } else {
  7958. $content = getProp($anime, 'content');
  7959. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7960. $need_generate_content = true;
  7961. }
  7962. }
  7963. // 美术风格
  7964. $input_art_style = getProp($data, 'art_style');
  7965. if (!$input_art_style) {
  7966. $mappedArtStyle = getProp($anime, 'art_style');
  7967. }else {
  7968. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7969. }
  7970. // 判断是否需要生成原文内容
  7971. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7972. // 如果需要生成原文内容,添加额外的要求
  7973. $content_generation_requirement = $need_generate_content
  7974. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7975. : "";
  7976. // 美术风格
  7977. if (!$mappedArtStyle) {
  7978. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7979. }else {
  7980. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7981. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7982. }else {
  7983. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7984. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7985. }
  7986. }
  7987. // 构建主体、场景和道具提示词
  7988. $extra_role_prompt = "\n";
  7989. $extra_scene_prompt = "\n";
  7990. $extra_prop_prompt = "\n";
  7991. $extra_roles = [];
  7992. $extra_scenes = [];
  7993. $extra_props = [];
  7994. $ref_products = []; // 参考资产
  7995. if ($extra_products) {
  7996. foreach($extra_products as $item) {
  7997. $product = getProp($item, 'product');
  7998. $product_name = getProp($item, 'product_name');
  7999. if ($product_name == '旁白') continue;
  8000. $ref_products[$product_name] = $item;
  8001. $pic_prompt = getProp($item, 'pic_prompt');
  8002. if ((int)$product === 1) {
  8003. // 拼接角色信息
  8004. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8005. $extra_roles[$product_name] = [
  8006. 'role' => $product_name,
  8007. 'pic_prompt' => $pic_prompt,
  8008. 'url' => getProp($item, 'url', ''),
  8009. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  8010. ];
  8011. } elseif ((int)$product === 2) {
  8012. // 拼接场景信息
  8013. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8014. $extra_scenes[$product_name] = [
  8015. 'scene' => $product_name,
  8016. 'pic_prompt' => $pic_prompt,
  8017. 'url' => getProp($item, 'url', ''),
  8018. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  8019. ];
  8020. } elseif ((int)$product === 3) {
  8021. // 拼接道具信息
  8022. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  8023. $extra_props[$product_name] = [
  8024. 'prop' => $product_name,
  8025. 'pic_prompt' => $pic_prompt,
  8026. 'url' => getProp($item, 'url', ''),
  8027. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  8028. ];
  8029. }
  8030. }
  8031. // 优化提示词,融入剧本
  8032. if (!empty(trim($extra_role_prompt))) {
  8033. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  8034. }
  8035. if (!empty(trim($extra_scene_prompt))) {
  8036. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  8037. }
  8038. if (!empty(trim($extra_prop_prompt))) {
  8039. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  8040. }
  8041. }
  8042. if ($anime_script_id && $is_single) {
  8043. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  8044. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  8045. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  8046. }else {
  8047. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8048. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8049. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8050. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8051. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8052. {$extra_role_prompt}";
  8053. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8054. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  8055. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8056. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8057. {$extra_scene_prompt}";
  8058. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8059. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  8060. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8061. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  8062. {$extra_prop_prompt}";
  8063. }
  8064. $systemPrompt = $is_single
  8065. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  8066. 强制要求:
  8067. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8068. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8069. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8070. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8071. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8072. 普通要求:
  8073. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  8074. $role_demo
  8075. $scene_demo
  8076. $prop_demo
  8077. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8078. 5.1片段分割逻辑(优先级从高到低):
  8079. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8080. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8081. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8082. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8083. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8084. - 片段数量格式为: 片段数量:8
  8085. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8086. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8087. 5.3分镜结构:每个分镜包含以下字段:
  8088. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  8089. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8090. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8091. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8092. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8093. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8094. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8095. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8096. - 运镜:场景+画面描述+运镜
  8097. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8098. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8099. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8100. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  8101. 6.《情绪-视听语言映射表》:
  8102. 6.1 场景空间与时间心理学 (Scene & Temporality)
  8103. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8104. -----|---------|------------|----------------
  8105. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  8106. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  8107. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  8108. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  8109. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  8110. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8111. -----|---------|------------|----------------
  8112. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  8113. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  8114. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  8115. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  8116. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  8117. --------|---------|--------------|-------------
  8118. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  8119. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  8120. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  8121. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  8122. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  8123. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  8124. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  8125. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  8126. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  8127. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  8128. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  8129. -----|---------|------------|------------
  8130. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  8131. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  8132. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  8133. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  8134. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  8135. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  8136. --------|---------|--------------|----------
  8137. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  8138. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  8139. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  8140. 6.6 声音设计与潜意识影响 (Soundscape)
  8141. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  8142. -----|---------|------------|------------------
  8143. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  8144. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  8145. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  8146. 理论基石:
  8147. - The Five C's of Cinematography by Joseph V. Mascelli
  8148. - Film Art: An Introduction by David Bordwell
  8149. - Sight, Sound, Motion by Herbert Zettl
  8150. - Notes on the Cinematograph by Robert Bresson
  8151. \n\n
  8152. 7.{$mappedArtStyle_prompt}\n\n
  8153. 示例如下:\n
  8154. ###剧本名:西昆仑
  8155. ###故事梗概
  8156. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8157. ###剧本亮点
  8158. 亮点1:绝境奇药,生死一线
  8159. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8160. 亮点2:结拜兄妹,化解尴尬
  8161. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8162. 亮点3:纤发夺命,情愫暗涌
  8163. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8164. ###人物关系
  8165. 阿雪与梁萧之间存在兄妹之情。
  8166. ###核心矛盾
  8167. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8168. ###主体列表
  8169. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8170. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8171. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8172. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8173. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8174. 全景,正面拍摄,青年女性,亚洲人。
  8175. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8176. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8177. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8178. ###美术风格
  8179. 基础画风风格词:厚涂古风
  8180. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8181. ###场景列表
  8182. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8183. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8184. 无人物。}
  8185. ###分段剧本
  8186. 片段数量:8
  8187. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8188. ##片段1
  8189. 时长:12s
  8190. 分镜1
  8191. 出场角色:刀疤脸
  8192. 场景:边境小镇街道
  8193. 出场道具:酒杯-高脚杯
  8194. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8195. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8196. 配音台词:
  8197. 背景音效:
  8198. 分镜2
  8199. 出场角色:刀疤脸
  8200. 场景:悦来酒馆
  8201. 出场道具:酒杯-高脚杯
  8202. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8203. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8204. 配音台词:
  8205. 背景音效:
  8206. 分镜3
  8207. 出场角色:刀疤脸
  8208. 场景:悦来酒馆
  8209. 出场道具:酒杯-高脚杯
  8210. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8211. 运镜:从中景推向令牌特写。
  8212. 配音台词:
  8213. 背景音效:
  8214. 分镜4
  8215. 出场角色:刀疤脸
  8216. 场景:悦来酒馆
  8217. 出场道具:酒杯-高脚杯
  8218. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8219. 运镜:极速推向酒水溅起的瞬间。
  8220. 配音台词:
  8221. 背景音效:
  8222. 分镜5
  8223. 出场角色:刀疤脸
  8224. 场景:悦来酒馆
  8225. 出场道具:酒杯-高脚杯
  8226. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8227. 运镜:固定机位,利用倾斜构图制造压迫感。
  8228. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8229. 背景音效:
  8230. \n\n"
  8231. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8232. 强制要求:\n
  8233. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8234. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8235. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8236. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8237. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8238. 普通要求:\n
  8239. 1.剧本名(必须生成)必须与文档内容高度相关
  8240. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8241. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8242. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8243. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8244. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8245. {$extra_role_prompt}
  8246. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8247. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  8248. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8249. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8250. {$extra_scene_prompt}
  8251. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8252. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  8253. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8254. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  8255. {$extra_prop_prompt}
  8256. 5.{$mappedArtStyle_prompt}\n\n
  8257. 示例如下:\n
  8258. ###剧本名:西昆仑
  8259. ###故事梗概
  8260. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8261. ###剧本亮点
  8262. 亮点1:绝境奇药,生死一线
  8263. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8264. 亮点2:结拜兄妹,化解尴尬
  8265. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8266. 亮点3:纤发夺命,情愫暗涌
  8267. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8268. ###人物关系
  8269. 阿雪与梁萧之间存在兄妹之情。
  8270. ###核心矛盾
  8271. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8272. ###主体列表
  8273. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8274. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8275. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8276. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8277. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8278. 全景,正面拍摄,青年女性,亚洲人。
  8279. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8280. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8281. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8282. ###美术风格
  8283. 基础画风风格词:厚涂古风
  8284. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8285. ###场景列表
  8286. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8287. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8288. 无人物。}
  8289. ###道具列表
  8290. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  8291. // 构建消息
  8292. $messages = [
  8293. [
  8294. 'role' => 'system',
  8295. 'content' => $systemPrompt
  8296. ],
  8297. [
  8298. 'role' => 'user',
  8299. 'content' => "以下是文档内容:
  8300. {$content}
  8301. 用户问题:
  8302. {$question}"
  8303. ]
  8304. ];
  8305. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8306. $thinkingMode = getProp($data, 'thinking', 'enabled'); // 默认思考模式
  8307. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8308. if ($model === 'deepseek-chat') {
  8309. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8310. $model = 'deepseek-v4-flash';
  8311. $thinkingMode = 'disabled';
  8312. } elseif ($model === 'deepseek-reasoner') {
  8313. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8314. $model = 'deepseek-v4-flash';
  8315. $thinkingMode = 'enabled';
  8316. }
  8317. $post_data = [
  8318. 'model' => $model,
  8319. 'messages' => $messages,
  8320. // 'max_tokens' => 8192,
  8321. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8322. 'frequency_penalty' => 0,
  8323. 'presence_penalty' => 0,
  8324. 'response_format' => ['type' => 'text'],
  8325. 'thinking' => ['type'=>$thinkingMode],
  8326. 'stream' => true // 启用流式输出
  8327. ];
  8328. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8329. // 根据模型类型选择调用方法
  8330. $fullContent = '';
  8331. $fullReasoningContent = '';
  8332. $usage = [];
  8333. try {
  8334. $streamGenerator = $this->dispatchStreamByModel($post_data);
  8335. // 验证返回值类型
  8336. if (!is_iterable($streamGenerator)) {
  8337. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8338. dLog('deepseek')->error('addChat流式生成器无效', [
  8339. 'generator_type' => $errorType,
  8340. 'model' => $model,
  8341. 'anime_id' => $anime_id
  8342. ]);
  8343. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  8344. 'type' => $errorType,
  8345. 'model' => $model
  8346. ]);
  8347. yield [
  8348. 'type' => 'error',
  8349. 'script' => [],
  8350. 'episode' => [],
  8351. 'answer' => '',
  8352. 'reasoning' => '',
  8353. 'usage' => [],
  8354. 'error' => '接口返回数据异常,请重新请求'
  8355. ];
  8356. return;
  8357. }
  8358. // 处理流式输出
  8359. foreach ($streamGenerator as $chunk) {
  8360. if (isset($chunk['type'])) {
  8361. if ($chunk['type'] === 'done') {
  8362. // 最终结果
  8363. $fullContent = $chunk['full_content'];
  8364. $fullReasoningContent = $chunk['full_reasoning'];
  8365. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8366. } else {
  8367. // 逐块yield数据
  8368. yield $chunk;
  8369. }
  8370. }
  8371. }
  8372. } catch (\Exception $e) {
  8373. // 解析上游错误详情(如 content_filter),便于日志定位与前端提示
  8374. $upstream_error = $this->resolveGptUpstreamError($e);
  8375. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  8376. 'model' => $model,
  8377. 'anime_id' => $anime_id,
  8378. 'upstream_status' => $upstream_error['status'],
  8379. 'upstream_code' => $upstream_error['code'],
  8380. 'upstream_body' => $upstream_error['body'],
  8381. 'trace' => $e->getTraceAsString()
  8382. ]);
  8383. logDB('deepseek', 'error', 'addChat流式处理失败', [
  8384. 'error' => $e->getMessage(),
  8385. 'model' => $model,
  8386. 'upstream_status' => $upstream_error['status'],
  8387. 'upstream_code' => $upstream_error['code'],
  8388. 'upstream_body' => $upstream_error['body']
  8389. ]);
  8390. yield [
  8391. 'type' => 'error',
  8392. 'script' => [],
  8393. 'episode' => [],
  8394. 'answer' => '',
  8395. 'reasoning' => '',
  8396. 'usage' => [],
  8397. 'error' => $this->buildChatErrorForUser($e, $upstream_error)
  8398. ];
  8399. return;
  8400. }
  8401. dLog('deepseek')->info('完整内容: '.$fullContent);
  8402. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8403. // 处理完整内容并返回最终结果
  8404. $script_arr = [];
  8405. if ($fullContent) {
  8406. $script_arr = handleScriptContentForAce($fullContent);
  8407. dLog('deepseek')->info('解析内容', $script_arr);
  8408. logDB('deepseek', 'info', '解析内容', $script_arr);
  8409. }
  8410. if (empty($script_arr['roles'])) {
  8411. // 未生成剧本相关内容,保存对话记录并返回提示
  8412. dLog('deepseek')->info('未生成剧本相关的内容');
  8413. try {
  8414. DB::beginTransaction();
  8415. $now = date('Y-m-d H:i:s');
  8416. // 保存对话记录
  8417. $records = [
  8418. [
  8419. 'uid' => $uid,
  8420. 'anime_id' => $anime_id,
  8421. 'sequence' => 0,
  8422. 'role' => 'user',
  8423. 'content' => $prompt,
  8424. 'created_at' => $now,
  8425. 'updated_at' => $now
  8426. ],
  8427. [
  8428. 'uid' => $uid,
  8429. 'anime_id' => $anime_id,
  8430. 'sequence' => 0,
  8431. 'role' => 'assistant',
  8432. // 'content' => $fullContent,
  8433. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  8434. 'created_at' => $now,
  8435. 'updated_at' => $now
  8436. ]
  8437. ];
  8438. DB::table('mp_anime_records')->insert($records);
  8439. DB::commit();
  8440. } catch (\Exception $e) {
  8441. DB::rollBack();
  8442. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8443. }
  8444. yield [
  8445. 'type' => 'done',
  8446. 'script' => [],
  8447. 'episode' => [],
  8448. 'answer' => $fullContent,
  8449. 'reasoning' => $fullReasoningContent,
  8450. 'usage' => $usage,
  8451. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  8452. ];
  8453. return;
  8454. }
  8455. // 如果需要生成原文内容,从script_arr中提取
  8456. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  8457. $content = $script_arr['content'];
  8458. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  8459. if (!$content) {
  8460. yield [
  8461. 'type' => 'done',
  8462. 'script' => [],
  8463. 'episode' => [],
  8464. 'answer' => $fullContent,
  8465. 'reasoning' => $fullReasoningContent,
  8466. 'usage' => $usage,
  8467. 'error' => '未生成剧本内容,请调整提示词再试'
  8468. ];
  8469. return;
  8470. }
  8471. }
  8472. // 替换美术风格
  8473. if ($mappedArtStyle !== '') {
  8474. $script_arr['art_style'] = $mappedArtStyle;
  8475. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8476. }
  8477. // 新建动漫
  8478. if ($user_anime_name == '新剧本策划') {
  8479. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  8480. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  8481. // if (!$anime_name) {
  8482. // // 未识别到剧本名,保存对话记录并返回提示
  8483. // dLog('deepseek')->info('未能识别到剧本名称');
  8484. // try {
  8485. // DB::beginTransaction();
  8486. // $now = date('Y-m-d H:i:s');
  8487. // // 保存对话记录
  8488. // $records = [
  8489. // [
  8490. // 'uid' => $uid,
  8491. // 'anime_id' => $anime_id,
  8492. // 'sequence' => 0,
  8493. // 'role' => 'user',
  8494. // 'content' => $prompt,
  8495. // 'created_at' => $now,
  8496. // 'updated_at' => $now
  8497. // ],
  8498. // [
  8499. // 'uid' => $uid,
  8500. // 'anime_id' => $anime_id,
  8501. // 'sequence' => 0,
  8502. // 'role' => 'assistant',
  8503. // 'content' => '未能生成剧本名称,请重试',
  8504. // 'created_at' => $now,
  8505. // 'updated_at' => $now
  8506. // ]
  8507. // ];
  8508. // DB::table('mp_anime_records')->insert($records);
  8509. // DB::commit();
  8510. // } catch (\Exception $e) {
  8511. // DB::rollBack();
  8512. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8513. // }
  8514. // yield [
  8515. // 'type' => 'done',
  8516. // 'script' => [],
  8517. // 'episode' => [],
  8518. // 'answer' => $fullContent,
  8519. // 'reasoning' => $fullReasoningContent,
  8520. // 'usage' => $usage,
  8521. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  8522. // ];
  8523. // return;
  8524. // }
  8525. // 确认对话名称唯一性
  8526. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  8527. $anime_name = $anime_name . '_' . date('YmdHis');
  8528. }
  8529. }else {
  8530. $anime_name = $user_anime_name;
  8531. }
  8532. // 单剧集模式:按 chatForAce 逻辑校验并重试生成剧集与分段剧本
  8533. if ($is_single) {
  8534. $max_retries = 3;
  8535. $retry_count = 0;
  8536. $validation_failed = false;
  8537. $validation_error_msg = '';
  8538. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8539. // 首次校验
  8540. if ($anime_script_id) {
  8541. if (empty($episode_arr['acts'])) {
  8542. $validation_failed = true;
  8543. $validation_error_msg = '未生成分镜剧本相关的内容';
  8544. } else {
  8545. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8546. $generated_roles = array_filter($generated_roles, function($role) {
  8547. return $role !== '旁白';
  8548. });
  8549. if (empty($generated_roles)) {
  8550. $validation_failed = true;
  8551. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8552. }
  8553. if (!$validation_failed && !empty($extra_roles)) {
  8554. $expected_roles = array_keys($extra_roles);
  8555. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8556. if (!empty($invalid_roles)) {
  8557. $validation_failed = true;
  8558. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8559. }
  8560. }
  8561. if (!$validation_failed && !empty($extra_scenes)) {
  8562. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  8563. $expected_scenes = array_keys($extra_scenes);
  8564. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8565. if (!empty($invalid_scenes)) {
  8566. $validation_failed = true;
  8567. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8568. }
  8569. }
  8570. if (!$validation_failed && !empty($extra_props)) {
  8571. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8572. $expected_props = array_keys($extra_props);
  8573. $invalid_props = array_diff($generated_props, $expected_props);
  8574. if (!empty($invalid_props)) {
  8575. $validation_failed = true;
  8576. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8577. }
  8578. }
  8579. }
  8580. } else {
  8581. if (empty($episode_arr['acts'])) {
  8582. $validation_failed = true;
  8583. $validation_error_msg = '未生成分镜剧本相关的内容';
  8584. } else {
  8585. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8586. $generated_roles = array_filter($generated_roles, function($role) {
  8587. return $role !== '旁白';
  8588. });
  8589. if (empty($generated_roles)) {
  8590. $validation_failed = true;
  8591. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8592. }
  8593. }
  8594. }
  8595. // 重试循环
  8596. while ($validation_failed && $retry_count < $max_retries) {
  8597. $retry_count++;
  8598. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  8599. 'reason' => $validation_error_msg,
  8600. 'anime_id' => $anime_id,
  8601. 'episode_number' => 1
  8602. ]);
  8603. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  8604. 'reason' => $validation_error_msg,
  8605. 'anime_id' => $anime_id
  8606. ]);
  8607. yield [
  8608. 'type' => 'retry',
  8609. 'retry_count' => $retry_count,
  8610. 'reason' => $validation_error_msg
  8611. ];
  8612. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  8613. if ($anime_script_id) {
  8614. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  8615. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  8616. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  8617. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  8618. } else {
  8619. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  8620. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  8621. }
  8622. $messages[] = [
  8623. 'role' => 'assistant',
  8624. 'content' => $fullContent
  8625. ];
  8626. $messages[] = [
  8627. 'role' => 'user',
  8628. 'content' => $retry_prompt
  8629. ];
  8630. $post_data['messages'] = $messages;
  8631. try {
  8632. $streamGenerator = $this->dispatchStreamByModel($post_data);
  8633. $fullContent = '';
  8634. $fullReasoningContent = '';
  8635. foreach ($streamGenerator as $chunk) {
  8636. if (isset($chunk['type'])) {
  8637. if ($chunk['type'] === 'done') {
  8638. $fullContent = $chunk['full_content'];
  8639. $fullReasoningContent = $chunk['full_reasoning'];
  8640. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8641. } else {
  8642. yield $chunk;
  8643. }
  8644. }
  8645. }
  8646. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  8647. // 重试接口未返回有效内容时直接失败,避免空内容被兼容放行后保存
  8648. if ($fullContent === '') {
  8649. dLog('deepseek')->error("第{$retry_count}次重试接口未返回有效内容");
  8650. yield [
  8651. 'type' => 'done',
  8652. 'script' => [],
  8653. 'episode' => [],
  8654. 'answer' => '',
  8655. 'reasoning' => $fullReasoningContent,
  8656. 'usage' => $usage,
  8657. 'error' => '生成接口未返回有效内容,请稍后重试'
  8658. ];
  8659. return;
  8660. }
  8661. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  8662. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  8663. $script_arr = handleScriptContentForAce($fullContent);
  8664. if ($mappedArtStyle !== '') {
  8665. $script_arr['art_style'] = $mappedArtStyle;
  8666. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8667. }
  8668. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8669. $validation_failed = false;
  8670. $validation_error_msg = '';
  8671. if ($anime_script_id) {
  8672. if (empty($episode_arr['acts'])) {
  8673. $validation_failed = true;
  8674. $validation_error_msg = '未生成分镜剧本相关的内容';
  8675. } else {
  8676. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8677. $generated_roles = array_filter($generated_roles, function($role) {
  8678. return $role !== '旁白';
  8679. });
  8680. if (empty($generated_roles)) {
  8681. $validation_failed = true;
  8682. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8683. }
  8684. if (!$validation_failed && !empty($extra_roles)) {
  8685. $expected_roles = array_keys($extra_roles);
  8686. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8687. if (!empty($invalid_roles)) {
  8688. $validation_failed = true;
  8689. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8690. }
  8691. }
  8692. if (!$validation_failed && !empty($extra_scenes)) {
  8693. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  8694. $expected_scenes = array_keys($extra_scenes);
  8695. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8696. if (!empty($invalid_scenes)) {
  8697. $validation_failed = true;
  8698. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8699. }
  8700. }
  8701. if (!$validation_failed && !empty($extra_props)) {
  8702. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8703. $expected_props = array_keys($extra_props);
  8704. $invalid_props = array_diff($generated_props, $expected_props);
  8705. if (!empty($invalid_props)) {
  8706. $validation_failed = true;
  8707. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8708. }
  8709. }
  8710. }
  8711. } else {
  8712. if (empty($episode_arr['acts'])) {
  8713. $validation_failed = true;
  8714. $validation_error_msg = '未生成分镜剧本相关的内容';
  8715. } else {
  8716. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8717. $generated_roles = array_filter($generated_roles, function($role) {
  8718. return $role !== '旁白';
  8719. });
  8720. if (empty($generated_roles)) {
  8721. $validation_failed = true;
  8722. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8723. }
  8724. }
  8725. }
  8726. } catch (\Exception $e) {
  8727. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  8728. 'trace' => $e->getTraceAsString()
  8729. ]);
  8730. break;
  8731. }
  8732. }
  8733. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存
  8734. if ($validation_failed && $retry_count >= $max_retries) {
  8735. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  8736. 'retry_count' => $retry_count,
  8737. 'last_error' => $validation_error_msg
  8738. ]);
  8739. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  8740. 'error' => $validation_error_msg,
  8741. 'anime_id' => $anime_id
  8742. ]);
  8743. $validation_failed = false;
  8744. $validation_error_msg = '';
  8745. }
  8746. // 如果重试后仍然失败
  8747. if ($validation_failed) {
  8748. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  8749. 'retry_count' => $retry_count,
  8750. 'last_error' => $validation_error_msg
  8751. ]);
  8752. try {
  8753. $now = date('Y-m-d H:i:s');
  8754. $records = [
  8755. [
  8756. 'uid' => $uid,
  8757. 'anime_id' => $anime_id,
  8758. 'sequence' => 1,
  8759. 'role' => 'user',
  8760. 'content' => $prompt,
  8761. 'created_at' => $now,
  8762. 'updated_at' => $now
  8763. ],
  8764. [
  8765. 'uid' => $uid,
  8766. 'anime_id' => $anime_id,
  8767. 'sequence' => 1,
  8768. 'role' => 'assistant',
  8769. 'content' => $fullContent,
  8770. 'created_at' => $now,
  8771. 'updated_at' => $now
  8772. ]
  8773. ];
  8774. DB::table('mp_anime_records')->insert($records);
  8775. } catch (\Exception $e) {
  8776. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8777. }
  8778. yield [
  8779. 'type' => 'done',
  8780. 'script' => [],
  8781. 'episode' => [],
  8782. 'answer' => $fullContent,
  8783. 'reasoning' => $fullReasoningContent,
  8784. 'usage' => $usage,
  8785. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  8786. ];
  8787. return;
  8788. }
  8789. // 验证成功,记录日志
  8790. if ($retry_count > 0) {
  8791. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  8792. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  8793. }
  8794. }
  8795. $table_data = [
  8796. 'user_id' => $uid,
  8797. 'anime_name' => $anime_name,
  8798. 'model' => $model,
  8799. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  8800. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  8801. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  8802. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  8803. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  8804. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  8805. 'art_style_type' => $input_art_style,
  8806. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  8807. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  8808. 'status' => '解析完成',
  8809. 'content' => $content,
  8810. 'is_multi' => $is_multi,
  8811. 'ace_mode' => $ace_mode,
  8812. 'generate_status' => '待执行',
  8813. 'updated_at' => date('Y-m-d H:i:s')
  8814. ];
  8815. if ($table_data['content']) {
  8816. $chapters = splitContent($table_data['content']);
  8817. $chapter_count = count($chapters);
  8818. if ($chapter_count > 0) {
  8819. $table_data['start_episode_sequence'] = 1;
  8820. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  8821. }
  8822. }
  8823. if ($extra_products) {
  8824. $table_data['extra_products'] = json_encode($extra_products, 256);
  8825. }
  8826. // 如果有剧本ID则进行绑定
  8827. if ($script_id) {
  8828. $table_data['script_id'] = $script_id;
  8829. }
  8830. $single_episode = [];
  8831. try {
  8832. DB::beginTransaction();
  8833. $now = date('Y-m-d H:i:s');
  8834. // 更新动漫大纲
  8835. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  8836. if (!$boolen) {
  8837. dLog('deepseek')->info('动漫保存失败', $table_data);
  8838. Utils::throwError('20003:动漫保存失败');
  8839. }
  8840. // 保存对话记录
  8841. $records = [
  8842. [
  8843. 'uid' => $uid,
  8844. 'anime_id' => $anime_id,
  8845. 'sequence' => 0,
  8846. 'role' => 'user',
  8847. 'content' => $prompt,
  8848. 'created_at' => date('Y-m-d H:i:s'),
  8849. 'updated_at' => date('Y-m-d H:i:s')
  8850. ],
  8851. [
  8852. 'uid' => $uid,
  8853. 'anime_id' => $anime_id,
  8854. 'sequence' => 0,
  8855. 'role' => 'assistant',
  8856. 'content' => $fullContent,
  8857. 'created_at' => date('Y-m-d H:i:s'),
  8858. 'updated_at' => date('Y-m-d H:i:s')
  8859. ]
  8860. ];
  8861. // 保存对话记录
  8862. $boolen3 = DB::table('mp_anime_records')->insert($records);
  8863. if (!$boolen3) {
  8864. Utils::throwError('20003:对话记录保存失败');
  8865. }
  8866. if ($is_single) {
  8867. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8868. if (empty($episode_arr['acts'])) {
  8869. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  8870. }
  8871. $saveResult = $this->saveEpisodeVersionData(
  8872. $anime_id,
  8873. 1,
  8874. $episode_arr,
  8875. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8876. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8877. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  8878. null,
  8879. null,
  8880. false,
  8881. $content,
  8882. $now,
  8883. $ref_products
  8884. );
  8885. $single_episode = $saveResult['episode'];
  8886. $episode_id = $saveResult['episode_id'];
  8887. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  8888. 'roles' => json_encode($saveResult['merged_roles'], 256),
  8889. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  8890. 'props' => json_encode($saveResult['merged_props'], 256),
  8891. 'updated_at' => $now
  8892. ]);
  8893. if ($boolen5 === false) {
  8894. Utils::throwError('20003:单剧集主表资源同步失败');
  8895. }
  8896. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  8897. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  8898. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  8899. $episode_record_content = '确认分镜大纲';
  8900. if ($content !== '') {
  8901. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  8902. }
  8903. $episode_records = [
  8904. [
  8905. 'uid' => $uid,
  8906. 'anime_id' => $anime_id,
  8907. 'role' => 'user',
  8908. 'content' => $episode_record_content,
  8909. 'sequence' => 1,
  8910. 'episode_id' => $episode_id,
  8911. 'created_at' => $now,
  8912. 'updated_at' => $now
  8913. ],
  8914. [
  8915. 'uid' => $uid,
  8916. 'anime_id' => $anime_id,
  8917. 'role' => 'assistant',
  8918. 'content' => $fullContent,
  8919. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8920. 'sequence' => 1,
  8921. 'episode_id' => $episode_id,
  8922. 'created_at' => $now,
  8923. 'updated_at' => $now
  8924. ]
  8925. ];
  8926. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  8927. if (!$boolen4) {
  8928. Utils::throwError('20003:单剧集分镜记录保存失败');
  8929. }
  8930. }
  8931. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8932. if ($is_single && !empty($single_episode)) {
  8933. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8934. 'anime_id' => $anime_id,
  8935. 'episode_id' => $episode_id ?? 0,
  8936. 'model' => $model,
  8937. 'source' => 'addChatForAce',
  8938. ]);
  8939. }
  8940. }catch (\Exception $e) {
  8941. DB::rollBack();
  8942. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  8943. yield [
  8944. 'type' => 'done',
  8945. 'answer' => $fullContent,
  8946. 'reasoning' => $fullReasoningContent,
  8947. 'usage' => $usage,
  8948. 'error' => $e->getMessage(),
  8949. ];
  8950. return;
  8951. }
  8952. DB::commit();
  8953. dLog('deepseek')->info('保存完毕');
  8954. if ($is_single && !empty($single_episode)) {
  8955. // $this->batchSetGlobalRoleImg([
  8956. // 'anime_id' => $anime_id,
  8957. // ]);
  8958. // $this->batchSetGlobalSceneImg([
  8959. // 'anime_id' => $anime_id,
  8960. // ]);
  8961. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8962. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8963. }
  8964. $table_data['anime_id'] = $anime_id;
  8965. $table_data['roles'] = json_decode($table_data['roles'], true);
  8966. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8967. // $table_data['episodes'] = $script_arr['episodes'];
  8968. unset($table_data['created_at']);
  8969. unset($table_data['updated_at']);
  8970. unset($table_data['status']);
  8971. dLog('deepseek')->info('开始返回');
  8972. yield [
  8973. 'type' => 'done',
  8974. 'script' => $table_data,
  8975. 'episode' => $single_episode,
  8976. 'answer' => $fullContent,
  8977. 'reasoning' => $fullReasoningContent,
  8978. 'usage' => $usage
  8979. ];
  8980. }
  8981. public function reGenerateAnimeForAce($data) {
  8982. $uid = Site::getUid();
  8983. $file = getProp($data, 'file');
  8984. $content = getProp($data, 'content', '');
  8985. $bid = getProp($data, 'bid', 0);
  8986. $script_id = getProp($data, 'script_id', 0);
  8987. $anime_id = getProp($data, 'anime_id');
  8988. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8989. if (!$anime) {
  8990. Utils::throwError('20003:该对话不存在');
  8991. }
  8992. $is_multi = getProp($anime, 'is_multi', 1);
  8993. $is_single = (int)$is_multi !== 1;
  8994. // 积分余额预检(仅单剧集模式收费)
  8995. if ($is_single) {
  8996. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  8997. }
  8998. $extra_products = getProp($data, 'products', []);
  8999. if (!$extra_products) {
  9000. $extra_products = getProp($anime, 'extra_products');
  9001. if ($extra_products) {
  9002. $extra_products = json_decode($extra_products, true);
  9003. }else {
  9004. $extra_products = [];
  9005. }
  9006. }else {
  9007. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  9008. }
  9009. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  9010. $anime_script_id = getProp($anime, 'script_id');
  9011. if ($anime_script_id && $is_single) {
  9012. $cpid = Site::getCpid();
  9013. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  9014. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  9015. ->where('mapping.script_id', $anime_script_id)
  9016. ->where('product.cpid', $cpid)
  9017. ->where('product.is_deleted', 0);
  9018. $mappings = $script_products_mappings->select(
  9019. 'mapping.product_id',
  9020. 'mapping.episode_number',
  9021. 'product.product_name',
  9022. 'product.type',
  9023. 'product.product',
  9024. 'product.pic_prompt',
  9025. 'product.url',
  9026. 'product.pic_task_id',
  9027. 'product.pic_task_status',
  9028. 'product.three_view_image_url'
  9029. )
  9030. ->get();
  9031. // 按 product_id 分组,合并 episode_number
  9032. $productMap = [];
  9033. foreach ($mappings as $item) {
  9034. $product_id = $item->product_id;
  9035. $product_name = $item->product_name;
  9036. // 处理product_name两边的符号
  9037. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  9038. if (!isset($productMap[$product_id])) {
  9039. $productMap[$product_id] = [
  9040. 'product_id' => $product_id,
  9041. 'product_name' => $product_name,
  9042. 'type' => (int)$item->type,
  9043. 'product' => (int)$item->product,
  9044. 'pic_prompt' => $item->pic_prompt,
  9045. 'url' => $item->url,
  9046. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9047. 'pic_task_id' => $item->pic_task_id,
  9048. 'pic_task_status' => $item->pic_task_status,
  9049. 'episode_numbers' => [],
  9050. ];
  9051. }
  9052. // 添加 episode_number(去重)
  9053. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  9054. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  9055. }
  9056. }
  9057. // 将查询到的剧本资产合并到extra_products中
  9058. // 先构建extra_products的索引(以product_id为key,用于去重)
  9059. $extraProductsMap = [];
  9060. foreach ($extra_products as $item) {
  9061. $key = getProp($item, 'product_id');
  9062. if ($key) {
  9063. $extraProductsMap[$key] = $item;
  9064. }
  9065. }
  9066. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  9067. foreach ($productMap as $product) {
  9068. $product_id = $product['product_id'];
  9069. // 如果不存在则添加(不带episode_number信息)
  9070. if (!isset($extraProductsMap[$product_id])) {
  9071. $extraProductsMap[$product_id] = [
  9072. 'product_id' => $product['product_id'],
  9073. 'product_name' => $product['product_name'],
  9074. 'type' => $product['type'],
  9075. 'product' => $product['product'],
  9076. 'pic_prompt' => $product['pic_prompt'],
  9077. 'url' => $product['url'],
  9078. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  9079. 'pic_task_id' => $product['pic_task_id'],
  9080. 'pic_task_status' => $product['pic_task_status'],
  9081. ];
  9082. }
  9083. }
  9084. // 重新赋值给extra_products
  9085. $extra_products = array_values($extraProductsMap);
  9086. }
  9087. $user_anime_name = getProp($anime, 'anime_name');
  9088. $prompt = getProp($data, 'prompt');
  9089. // 处理提示词
  9090. if ($prompt && $extra_products) {
  9091. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  9092. foreach($extra_products as $item) {
  9093. $product_name = getProp($item, 'product_name');
  9094. if ($product_name) {
  9095. // 替换 {product_name} 为 product_name
  9096. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  9097. }
  9098. }
  9099. }
  9100. // 处理文本模型
  9101. $model = getProp($data, 'model');
  9102. if (!$model) {
  9103. // 用户没有输入,从anime表获取
  9104. $model = getProp($anime, 'model');
  9105. if (!$model) {
  9106. // anime表也没有,使用默认值
  9107. $model = 'deepseek-v4-pro';
  9108. }
  9109. }
  9110. // 验证模型是否在可用模型表中
  9111. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9112. $model = 'deepseek-v4-pro';
  9113. }
  9114. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  9115. if ($is_single) {
  9116. $episode_exists = DB::table('mp_anime_episodes')
  9117. ->where('anime_id', $anime_id)
  9118. ->where('sequence', 1)
  9119. ->exists();
  9120. if ($episode_exists) {
  9121. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  9122. }
  9123. }
  9124. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  9125. if ($prompt) {
  9126. $question .= "本次修改要求如下:\n{$prompt}";
  9127. }
  9128. // 提取文件内容
  9129. if ($file) {
  9130. $content = $this->extractFileContent($file);
  9131. if (!$content) {
  9132. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  9133. }
  9134. } elseif ($script_id) {
  9135. $content = $this->getContentByScriptId($script_id);
  9136. if (!$content) {
  9137. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  9138. }
  9139. } elseif ($bid) {
  9140. $content = $this->getContentByBid($bid);
  9141. if (!$content) {
  9142. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  9143. }
  9144. } elseif ($content) {
  9145. $content = filterContent($content);
  9146. }else {
  9147. $content = filterContent(getProp($anime, 'content'));
  9148. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  9149. $need_generate_content = true;
  9150. }
  9151. }
  9152. // 判断是否需要生成原文内容
  9153. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  9154. // 如果需要生成原文内容,添加额外的要求
  9155. $content_generation_requirement = $need_generate_content
  9156. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  9157. : "";
  9158. // 美术风格
  9159. $input_art_style = getProp($data, 'art_style');
  9160. if (!$input_art_style) {
  9161. $mappedArtStyle = getProp($anime, 'art_style');
  9162. }else {
  9163. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  9164. }
  9165. if (!$mappedArtStyle) {
  9166. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  9167. }else {
  9168. if (strstr($mappedArtStyle, '基础画风风格词')) {
  9169. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  9170. }else {
  9171. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  9172. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  9173. }
  9174. }
  9175. // 构建主体、场景和道具提示词
  9176. $extra_role_prompt = "\n";
  9177. $extra_scene_prompt = "\n";
  9178. $extra_prop_prompt = "\n";
  9179. $extra_roles = [];
  9180. $extra_scenes = [];
  9181. $extra_props = [];
  9182. $ref_products = []; // 参考资产
  9183. if ($extra_products) {
  9184. foreach($extra_products as $item) {
  9185. $product = getProp($item, 'product');
  9186. $product_name = getProp($item, 'product_name');
  9187. if ($product_name == '旁白') continue;
  9188. $ref_products[$product_name] = $item;
  9189. $pic_prompt = getProp($item, 'pic_prompt');
  9190. if ((int)$product === 1) {
  9191. // 拼接角色信息
  9192. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9193. $extra_roles[$product_name] = [
  9194. 'role' => $product_name,
  9195. 'pic_prompt' => $pic_prompt,
  9196. 'url' => getProp($item, 'url', ''),
  9197. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9198. ];
  9199. } elseif ((int)$product === 2) {
  9200. // 拼接场景信息
  9201. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9202. $extra_scenes[$product_name] = [
  9203. 'scene' => $product_name,
  9204. 'pic_prompt' => $pic_prompt,
  9205. 'url' => getProp($item, 'url', ''),
  9206. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9207. ];
  9208. } elseif ((int)$product === 3) {
  9209. // 拼接道具信息
  9210. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9211. $extra_props[$product_name] = [
  9212. 'prop' => $product_name,
  9213. 'pic_prompt' => $pic_prompt,
  9214. 'url' => getProp($item, 'url', ''),
  9215. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9216. ];
  9217. }
  9218. }
  9219. // 优化提示词,融入剧本
  9220. if (!empty(trim($extra_role_prompt))) {
  9221. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  9222. }
  9223. if (!empty(trim($extra_scene_prompt))) {
  9224. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  9225. }
  9226. if (!empty(trim($extra_prop_prompt))) {
  9227. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  9228. }
  9229. }
  9230. if ($anime_script_id && $is_single) {
  9231. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  9232. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  9233. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  9234. }else {
  9235. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  9236. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9237. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  9238. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9239. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9240. {$extra_role_prompt}";
  9241. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9242. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  9243. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9244. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  9245. {$extra_scene_prompt}";
  9246. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9247. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  9248. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  9249. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  9250. {$extra_prop_prompt}";
  9251. }
  9252. $system_message = ['role'=>'system', 'content'=>$is_single
  9253. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  9254. 强制要求:
  9255. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9256. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9257. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9258. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9259. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9260. 普通要求:
  9261. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  9262. $role_demo
  9263. $scene_demo
  9264. $prop_demo
  9265. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9266. 5.1片段分割逻辑(优先级从高到低):
  9267. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9268. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9269. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9270. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9271. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9272. - 片段数量格式为: 片段数量:8
  9273. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9274. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9275. 5.3分镜结构:每个分镜包含以下字段:
  9276. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  9277. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  9278. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9279. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9280. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9281. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9282. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9283. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9284. - 运镜:场景+画面描述+运镜
  9285. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  9286. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  9287. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9288. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  9289. 6.《情绪-视听语言映射表》:
  9290. 6.1 场景空间与时间心理学 (Scene & Temporality)
  9291. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9292. -----|---------|------------|----------------
  9293. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  9294. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  9295. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  9296. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  9297. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  9298. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9299. -----|---------|------------|----------------
  9300. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  9301. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  9302. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  9303. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  9304. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  9305. --------|---------|--------------|-------------
  9306. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  9307. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  9308. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  9309. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  9310. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  9311. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  9312. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  9313. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  9314. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  9315. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  9316. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  9317. -----|---------|------------|------------
  9318. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  9319. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  9320. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  9321. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  9322. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  9323. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  9324. --------|---------|--------------|----------
  9325. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  9326. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  9327. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  9328. 6.6 声音设计与潜意识影响 (Soundscape)
  9329. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  9330. -----|---------|------------|------------------
  9331. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  9332. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  9333. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  9334. 理论基石:
  9335. - The Five C's of Cinematography by Joseph V. Mascelli
  9336. - Film Art: An Introduction by David Bordwell
  9337. - Sight, Sound, Motion by Herbert Zettl
  9338. - Notes on the Cinematograph by Robert Bresson
  9339. \n\n
  9340. 7.{$mappedArtStyle_prompt}\n\n
  9341. 示例如下:\n
  9342. ###剧本名:西昆仑
  9343. ###故事梗概
  9344. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9345. ###剧本亮点
  9346. 亮点1:绝境奇药,生死一线
  9347. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9348. 亮点2:结拜兄妹,化解尴尬
  9349. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9350. 亮点3:纤发夺命,情愫暗涌
  9351. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9352. ###人物关系
  9353. 阿雪与梁萧之间存在兄妹之情。
  9354. ###核心矛盾
  9355. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9356. ###主体列表
  9357. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9358. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9359. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9360. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9361. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9362. 全景,正面拍摄,青年女性,亚洲人。
  9363. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9364. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9365. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9366. ###美术风格
  9367. 基础画风风格词:厚涂古风
  9368. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9369. ###场景列表
  9370. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9371. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9372. 无人物。}
  9373. ###分段剧本
  9374. 片段数量:8
  9375. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9376. ##片段1
  9377. 时长:12s
  9378. 分镜1
  9379. 出场角色:刀疤脸
  9380. 场景:边境小镇街道
  9381. 出场道具:酒杯-高脚杯
  9382. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9383. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9384. 配音台词:
  9385. 背景音效:
  9386. 分镜2
  9387. 出场角色:刀疤脸
  9388. 场景:悦来酒馆
  9389. 出场道具:酒杯-高脚杯
  9390. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9391. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9392. 配音台词:
  9393. 背景音效:
  9394. 分镜3
  9395. 出场角色:刀疤脸
  9396. 场景:悦来酒馆
  9397. 出场道具:酒杯-高脚杯
  9398. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9399. 运镜:从中景推向令牌特写。
  9400. 配音台词:
  9401. 背景音效:
  9402. 分镜4
  9403. 出场角色:刀疤脸
  9404. 场景:悦来酒馆
  9405. 出场道具:酒杯-高脚杯
  9406. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9407. 运镜:极速推向酒水溅起的瞬间。
  9408. 配音台词:
  9409. 背景音效:
  9410. 分镜5
  9411. 出场角色:刀疤脸
  9412. 场景:悦来酒馆
  9413. 出场道具:酒杯-高脚杯
  9414. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9415. 运镜:固定机位,利用倾斜构图制造压迫感。
  9416. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9417. 背景音效:
  9418. \n\n"
  9419. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  9420. 强制要求:\n
  9421. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9422. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9423. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9424. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9425. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9426. 普通要求:\n
  9427. 1.剧本名(必须生成)必须与文档内容高度相关
  9428. $role_demo
  9429. $scene_demo
  9430. $prop_demo
  9431. 5.{$mappedArtStyle_prompt}\n\n
  9432. 示例如下:\n
  9433. ###剧本名:西昆仑
  9434. ###故事梗概
  9435. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9436. ###剧本亮点
  9437. 亮点1:绝境奇药,生死一线
  9438. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9439. 亮点2:结拜兄妹,化解尴尬
  9440. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9441. 亮点3:纤发夺命,情愫暗涌
  9442. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9443. ###人物关系
  9444. 阿雪与梁萧之间存在兄妹之情。
  9445. ###核心矛盾
  9446. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9447. ###主体列表
  9448. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9449. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9450. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9451. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9452. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9453. 全景,正面拍摄,青年女性,亚洲人。
  9454. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9455. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9456. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9457. ###美术风格
  9458. 基础画风风格词:厚涂古风
  9459. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9460. ###场景列表
  9461. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9462. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9463. 无人物。}
  9464. ###道具列表
  9465. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  9466. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  9467. $episode_count = $this->extractEpisodeNumber($prompt);
  9468. if ((int)getProp($anime, 'is_multi') !== 1) {
  9469. yield [
  9470. 'type' => 'done',
  9471. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  9472. 'reasoning' => '',
  9473. 'usage' => []
  9474. ];
  9475. return;
  9476. }
  9477. if ($episode_count) {
  9478. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  9479. $system_message = [
  9480. 'role' => 'system',
  9481. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  9482. 强制要求:\n
  9483. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9484. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9485. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9486. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9487. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9488. 普通要求:\n
  9489. 1.<故事梗概>控制在200-300字左右
  9490. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  9491. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9492. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  9493. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9494. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9495. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9496. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  9497. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9498. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  9499. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  9500. 示例如下:\n
  9501. ###剧本名:西昆仑
  9502. ###故事梗概
  9503. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9504. ###剧本亮点
  9505. 亮点1:绝境奇药,生死一线
  9506. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9507. 亮点2:结拜兄妹,化解尴尬
  9508. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9509. 亮点3:纤发夺命,情愫暗涌
  9510. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9511. ###人物关系
  9512. 阿雪与梁萧之间存在兄妹之情。
  9513. ###核心矛盾
  9514. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9515. ###主体列表
  9516. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9517. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9518. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9519. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9520. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9521. 全景,正面拍摄,青年女性,亚洲人。
  9522. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9523. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9524. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9525. ###美术风格
  9526. 基础画风风格词:厚涂古风
  9527. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9528. ###场景列表
  9529. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9530. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9531. 无人物。}
  9532. ###分集详细内容
  9533. ##第1章 重生
  9534. 我重生了。
  9535. 源于一个男人偏执的暗恋。
  9536. ##第2章 相救
  9537. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  9538. 我眼睛扫向站在锅炉后的卞大伟。"
  9539. ];
  9540. // 构建消息
  9541. $messages = [
  9542. $system_message,
  9543. [
  9544. 'role' => 'user',
  9545. 'content' => "以下是文档内容:
  9546. {$content}
  9547. 用户问题:
  9548. {$question}"
  9549. ]
  9550. ];
  9551. }else {
  9552. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  9553. // 构建消息
  9554. $messages = [
  9555. $system_message,
  9556. [
  9557. 'role' => 'user',
  9558. 'content' => "以下是文档内容:
  9559. {$content}
  9560. 用户问题:
  9561. {$question}"
  9562. ]
  9563. ];
  9564. }else {
  9565. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  9566. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  9567. return (array)$value;
  9568. })->toArray();
  9569. array_unshift($messages, $system_message);
  9570. $messages[] = [
  9571. 'role' => 'user',
  9572. 'content' => $prompt
  9573. ];
  9574. }
  9575. }
  9576. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  9577. $thinkingMode = getProp($data, 'thinking', 'enabled'); // 默认非思考模式
  9578. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  9579. if ($model === 'deepseek-chat') {
  9580. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  9581. $model = 'deepseek-v4-flash';
  9582. $thinkingMode = 'disabled';
  9583. } elseif ($model === 'deepseek-reasoner') {
  9584. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  9585. $model = 'deepseek-v4-flash';
  9586. $thinkingMode = 'enabled';
  9587. }
  9588. $post_data = [
  9589. 'model' => $model,
  9590. 'messages' => $messages,
  9591. // 'max_tokens' => 8192,
  9592. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9593. 'frequency_penalty' => 0,
  9594. 'presence_penalty' => 0,
  9595. 'response_format' => ['type' => 'text'],
  9596. 'thinking' => ['type' => $thinkingMode],
  9597. 'stream' => true // 启用流式输出
  9598. ];
  9599. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9600. // 根据模型类型选择调用方法
  9601. $fullContent = '';
  9602. $fullReasoningContent = '';
  9603. $usage = [];
  9604. // dd($post_data);
  9605. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  9606. try {
  9607. $streamGenerator = $this->dispatchStreamByModel($post_data);
  9608. // 验证返回值类型
  9609. if (!is_iterable($streamGenerator)) {
  9610. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  9611. dLog('deepseek')->error('方法名流式生成器无效', [
  9612. 'generator_type' => $errorType,
  9613. 'model' => $model,
  9614. // 添加其他上下文信息
  9615. ]);
  9616. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  9617. 'type' => $errorType,
  9618. 'model' => $model
  9619. ]);
  9620. yield [
  9621. 'type' => 'error',
  9622. // 根据方法返回相应的空数据结构
  9623. 'answer' => '',
  9624. 'reasoning' => '',
  9625. 'usage' => [],
  9626. 'error' => '接口返回数据异常,请重新请求'
  9627. ];
  9628. return;
  9629. }
  9630. // 处理流式输出
  9631. foreach ($streamGenerator as $chunk) {
  9632. if (isset($chunk['type'])) {
  9633. if ($chunk['type'] === 'done') {
  9634. $fullContent = $chunk['full_content'];
  9635. $fullReasoningContent = $chunk['full_reasoning'];
  9636. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9637. } else {
  9638. yield $chunk;
  9639. }
  9640. }
  9641. }
  9642. } catch (\Exception $e) {
  9643. // 解析上游错误详情(如 content_filter),便于日志定位与前端提示
  9644. $upstream_error = $this->resolveGptUpstreamError($e);
  9645. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  9646. 'model' => $model,
  9647. 'upstream_status' => $upstream_error['status'],
  9648. 'upstream_code' => $upstream_error['code'],
  9649. 'upstream_body' => $upstream_error['body'],
  9650. 'trace' => $e->getTraceAsString()
  9651. ]);
  9652. logDB('deepseek', 'error', '方法名流式处理失败', [
  9653. 'error' => $e->getMessage(),
  9654. 'model' => $model,
  9655. 'upstream_status' => $upstream_error['status'],
  9656. 'upstream_code' => $upstream_error['code'],
  9657. 'upstream_body' => $upstream_error['body']
  9658. ]);
  9659. yield [
  9660. 'type' => 'error',
  9661. // 根据方法返回相应的空数据结构
  9662. 'answer' => '',
  9663. 'reasoning' => '',
  9664. 'usage' => [],
  9665. 'error' => $this->buildChatErrorForUser($e, $upstream_error)
  9666. ];
  9667. return;
  9668. }
  9669. dLog('deepseek')->info('完整内容: '.$fullContent);
  9670. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  9671. // 处理完整内容并返回最终结果
  9672. $script_arr = [];
  9673. if ($fullContent) {
  9674. $script_arr = handleScriptContentForAce($fullContent);
  9675. dLog('deepseek')->info('解析内容', $script_arr);
  9676. logDB('deepseek', 'info', '解析内容', $script_arr);
  9677. }
  9678. if (empty($script_arr['roles'])) {
  9679. // 未生成剧本相关内容,保存对话记录并返回提示
  9680. dLog('deepseek')->info('未生成剧本相关的内容');
  9681. try {
  9682. $now = date('Y-m-d H:i:s');
  9683. // 保存对话记录
  9684. $records = [
  9685. [
  9686. 'uid' => $uid,
  9687. 'anime_id' => $anime_id,
  9688. 'sequence' => 0,
  9689. 'role' => 'user',
  9690. 'content' => $prompt,
  9691. 'created_at' => $now,
  9692. 'updated_at' => $now
  9693. ],
  9694. [
  9695. 'uid' => $uid,
  9696. 'anime_id' => $anime_id,
  9697. 'sequence' => 0,
  9698. 'role' => 'assistant',
  9699. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  9700. 'created_at' => $now,
  9701. 'updated_at' => $now
  9702. ]
  9703. ];
  9704. DB::table('mp_anime_records')->insert($records);
  9705. } catch (\Exception $e) {
  9706. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9707. }
  9708. yield [
  9709. 'type' => 'done',
  9710. 'script' => [],
  9711. 'episode' => [],
  9712. 'answer' => $fullContent,
  9713. 'reasoning' => $fullReasoningContent,
  9714. 'usage' => $usage,
  9715. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  9716. ];
  9717. return;
  9718. }
  9719. // 替换美术风格
  9720. if ($mappedArtStyle !== '') {
  9721. $script_arr['art_style'] = $mappedArtStyle;
  9722. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  9723. }
  9724. if ($user_anime_name != '新剧本策划') {
  9725. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  9726. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  9727. // 确认对话名称唯一性
  9728. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  9729. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  9730. }
  9731. }else {
  9732. $anime_name = $user_anime_name;
  9733. }
  9734. // 单剧集模式:按 chatForAce 逻辑校验并重试生成剧集与分段剧本
  9735. if ($is_single) {
  9736. $max_retries = 3;
  9737. $retry_count = 0;
  9738. $validation_failed = false;
  9739. $validation_error_msg = '';
  9740. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9741. // 首次校验
  9742. if ($anime_script_id) {
  9743. if (empty($episode_arr['acts'])) {
  9744. $validation_failed = true;
  9745. $validation_error_msg = '未生成分镜剧本相关的内容';
  9746. } else {
  9747. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9748. $generated_roles = array_filter($generated_roles, function($role) {
  9749. return $role !== '旁白';
  9750. });
  9751. if (empty($generated_roles)) {
  9752. $validation_failed = true;
  9753. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9754. }
  9755. if (!$validation_failed && !empty($extra_roles)) {
  9756. $expected_roles = array_keys($extra_roles);
  9757. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9758. if (!empty($invalid_roles)) {
  9759. $validation_failed = true;
  9760. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9761. }
  9762. }
  9763. if (!$validation_failed && !empty($extra_scenes)) {
  9764. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  9765. $expected_scenes = array_keys($extra_scenes);
  9766. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9767. if (!empty($invalid_scenes)) {
  9768. $validation_failed = true;
  9769. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9770. }
  9771. }
  9772. if (!$validation_failed && !empty($extra_props)) {
  9773. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9774. $expected_props = array_keys($extra_props);
  9775. $invalid_props = array_diff($generated_props, $expected_props);
  9776. if (!empty($invalid_props)) {
  9777. $validation_failed = true;
  9778. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9779. }
  9780. }
  9781. }
  9782. } else {
  9783. if (empty($episode_arr['acts'])) {
  9784. $validation_failed = true;
  9785. $validation_error_msg = '未生成分镜剧本相关的内容';
  9786. } else {
  9787. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9788. $generated_roles = array_filter($generated_roles, function($role) {
  9789. return $role !== '旁白';
  9790. });
  9791. if (empty($generated_roles)) {
  9792. $validation_failed = true;
  9793. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9794. }
  9795. }
  9796. }
  9797. // 重试循环
  9798. while ($validation_failed && $retry_count < $max_retries) {
  9799. $retry_count++;
  9800. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  9801. 'reason' => $validation_error_msg,
  9802. 'anime_id' => $anime_id,
  9803. 'episode_number' => 1
  9804. ]);
  9805. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  9806. 'reason' => $validation_error_msg,
  9807. 'anime_id' => $anime_id
  9808. ]);
  9809. yield [
  9810. 'type' => 'retry',
  9811. 'retry_count' => $retry_count,
  9812. 'reason' => $validation_error_msg
  9813. ];
  9814. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  9815. if ($anime_script_id) {
  9816. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  9817. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9818. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  9819. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  9820. } else {
  9821. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9822. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  9823. }
  9824. $messages[] = [
  9825. 'role' => 'assistant',
  9826. 'content' => $fullContent
  9827. ];
  9828. $messages[] = [
  9829. 'role' => 'user',
  9830. 'content' => $retry_prompt
  9831. ];
  9832. $post_data['messages'] = $messages;
  9833. try {
  9834. $streamGenerator = $this->dispatchStreamByModel($post_data);
  9835. $fullContent = '';
  9836. $fullReasoningContent = '';
  9837. foreach ($streamGenerator as $chunk) {
  9838. if (isset($chunk['type'])) {
  9839. if ($chunk['type'] === 'done') {
  9840. $fullContent = $chunk['full_content'];
  9841. $fullReasoningContent = $chunk['full_reasoning'];
  9842. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9843. } else {
  9844. yield $chunk;
  9845. }
  9846. }
  9847. }
  9848. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9849. // 重试接口未返回有效内容时直接失败,避免空内容被兼容放行后保存
  9850. if ($fullContent === '') {
  9851. dLog('deepseek')->error("第{$retry_count}次重试接口未返回有效内容");
  9852. yield [
  9853. 'type' => 'done',
  9854. 'script' => [],
  9855. 'episode' => [],
  9856. 'answer' => '',
  9857. 'reasoning' => $fullReasoningContent,
  9858. 'usage' => $usage,
  9859. 'error' => '生成接口未返回有效内容,请稍后重试'
  9860. ];
  9861. return;
  9862. }
  9863. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  9864. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  9865. $script_arr = handleScriptContentForAce($fullContent);
  9866. if ($mappedArtStyle !== '') {
  9867. $script_arr['art_style'] = $mappedArtStyle;
  9868. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  9869. }
  9870. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9871. $validation_failed = false;
  9872. $validation_error_msg = '';
  9873. if ($anime_script_id) {
  9874. if (empty($episode_arr['acts'])) {
  9875. $validation_failed = true;
  9876. $validation_error_msg = '未生成分镜剧本相关的内容';
  9877. } else {
  9878. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9879. $generated_roles = array_filter($generated_roles, function($role) {
  9880. return $role !== '旁白';
  9881. });
  9882. if (empty($generated_roles)) {
  9883. $validation_failed = true;
  9884. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9885. }
  9886. if (!$validation_failed && !empty($extra_roles)) {
  9887. $expected_roles = array_keys($extra_roles);
  9888. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9889. if (!empty($invalid_roles)) {
  9890. $validation_failed = true;
  9891. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9892. }
  9893. }
  9894. if (!$validation_failed && !empty($extra_scenes)) {
  9895. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  9896. $expected_scenes = array_keys($extra_scenes);
  9897. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9898. if (!empty($invalid_scenes)) {
  9899. $validation_failed = true;
  9900. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9901. }
  9902. }
  9903. if (!$validation_failed && !empty($extra_props)) {
  9904. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9905. $expected_props = array_keys($extra_props);
  9906. $invalid_props = array_diff($generated_props, $expected_props);
  9907. if (!empty($invalid_props)) {
  9908. $validation_failed = true;
  9909. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9910. }
  9911. }
  9912. }
  9913. } else {
  9914. if (empty($episode_arr['acts'])) {
  9915. $validation_failed = true;
  9916. $validation_error_msg = '未生成分镜剧本相关的内容';
  9917. } else {
  9918. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9919. $generated_roles = array_filter($generated_roles, function($role) {
  9920. return $role !== '旁白';
  9921. });
  9922. if (empty($generated_roles)) {
  9923. $validation_failed = true;
  9924. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9925. }
  9926. }
  9927. }
  9928. } catch (\Exception $e) {
  9929. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  9930. 'trace' => $e->getTraceAsString()
  9931. ]);
  9932. break;
  9933. }
  9934. }
  9935. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存
  9936. if ($validation_failed && $retry_count >= $max_retries) {
  9937. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  9938. 'retry_count' => $retry_count,
  9939. 'last_error' => $validation_error_msg
  9940. ]);
  9941. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  9942. 'error' => $validation_error_msg,
  9943. 'anime_id' => $anime_id
  9944. ]);
  9945. $validation_failed = false;
  9946. $validation_error_msg = '';
  9947. }
  9948. // 如果重试后仍然失败
  9949. if ($validation_failed) {
  9950. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  9951. 'retry_count' => $retry_count,
  9952. 'last_error' => $validation_error_msg
  9953. ]);
  9954. try {
  9955. $now = date('Y-m-d H:i:s');
  9956. $records = [
  9957. [
  9958. 'uid' => $uid,
  9959. 'anime_id' => $anime_id,
  9960. 'sequence' => 1,
  9961. 'role' => 'user',
  9962. 'content' => $prompt,
  9963. 'created_at' => $now,
  9964. 'updated_at' => $now
  9965. ],
  9966. [
  9967. 'uid' => $uid,
  9968. 'anime_id' => $anime_id,
  9969. 'sequence' => 1,
  9970. 'role' => 'assistant',
  9971. 'content' => $fullContent,
  9972. 'created_at' => $now,
  9973. 'updated_at' => $now
  9974. ]
  9975. ];
  9976. DB::table('mp_anime_records')->insert($records);
  9977. } catch (\Exception $e) {
  9978. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9979. }
  9980. yield [
  9981. 'type' => 'done',
  9982. 'script' => [],
  9983. 'episode' => [],
  9984. 'answer' => $fullContent,
  9985. 'reasoning' => $fullReasoningContent,
  9986. 'usage' => $usage,
  9987. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  9988. ];
  9989. return;
  9990. }
  9991. // 验证成功,记录日志
  9992. if ($retry_count > 0) {
  9993. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  9994. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  9995. }
  9996. }
  9997. $table_data = [
  9998. 'user_id' => $uid,
  9999. 'model' => $model,
  10000. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  10001. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  10002. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  10003. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  10004. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  10005. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  10006. 'art_style_type' => $input_art_style,
  10007. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  10008. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  10009. 'status' => '解析完成',
  10010. 'generate_status' => '待执行',
  10011. 'updated_at' => date('Y-m-d H:i:s')
  10012. ];
  10013. if ($anime_name) $table_data['anime_name'] = $anime_name;
  10014. // 如果是修改集数,则将content内容更新(会改变原文)
  10015. if (isset($episode_count) && $episode_count > 0) {
  10016. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  10017. $table_data['start_episode_sequence'] = 1;
  10018. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  10019. }else {
  10020. // 如果需要生成原文内容,从script_arr中提取
  10021. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  10022. $table_data['content'] = $script_arr['content'];
  10023. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  10024. if (!$table_data['content']) {
  10025. yield [
  10026. 'type' => 'done',
  10027. 'script' => [],
  10028. 'episode' => [],
  10029. 'answer' => $fullContent,
  10030. 'reasoning' => $fullReasoningContent,
  10031. 'usage' => $usage,
  10032. 'error' => '未生成剧本内容,请调整提示词再试'
  10033. ];
  10034. return;
  10035. }
  10036. }
  10037. if (isset($table_data['content']) && $table_data['content']) {
  10038. $chapters = splitContent($table_data['content']);
  10039. $chapter_count = count($chapters);
  10040. if ($chapter_count > 0) {
  10041. $table_data['start_episode_sequence'] = 1;
  10042. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  10043. }
  10044. }
  10045. }
  10046. if ($extra_products) {
  10047. $table_data['extra_products'] = json_encode($extra_products, 256);
  10048. }
  10049. $single_episode = [];
  10050. try {
  10051. DB::beginTransaction();
  10052. $now = date('Y-m-d H:i:s');
  10053. // 更新动漫大纲
  10054. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  10055. if (!$boolen) {
  10056. dLog('deepseek')->info('对话修改失败', $table_data);
  10057. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  10058. Utils::throwError('20003:对话修改失败');
  10059. }
  10060. // 保存对话记录
  10061. $records = [
  10062. [
  10063. 'uid' => $uid,
  10064. 'anime_id' => $anime_id,
  10065. 'sequence' => 0,
  10066. 'role' => 'user',
  10067. 'content' => $prompt,
  10068. 'created_at' => $now,
  10069. 'updated_at' => $now
  10070. ],
  10071. [
  10072. 'uid' => $uid,
  10073. 'anime_id' => $anime_id,
  10074. 'sequence' => 0,
  10075. 'role' => 'assistant',
  10076. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  10077. 'content' => $fullContent,
  10078. 'created_at' => $now,
  10079. 'updated_at' => $now
  10080. ]
  10081. ];
  10082. // 保存对话记录
  10083. $boolen3 = DB::table('mp_anime_records')->insert($records);
  10084. if (!$boolen3) {
  10085. Utils::throwError('20003:对话记录保存失败');
  10086. }
  10087. // 单剧集模式:生成并保存剧集信息
  10088. if ($is_single) {
  10089. $anime_name = getProp($anime, 'anime_name', '未命名');
  10090. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  10091. if (empty($episode_arr['acts'])) {
  10092. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  10093. }
  10094. $saveResult = $this->saveEpisodeVersionData(
  10095. $anime_id,
  10096. 1,
  10097. $episode_arr,
  10098. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  10099. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  10100. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  10101. null,
  10102. null,
  10103. false,
  10104. $content,
  10105. $now,
  10106. $ref_products
  10107. );
  10108. $single_episode = $saveResult['episode'];
  10109. $episode_id = $saveResult['episode_id'];
  10110. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  10111. 'roles' => json_encode($saveResult['merged_roles'], 256),
  10112. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  10113. 'props' => json_encode($saveResult['merged_props'], 256),
  10114. 'updated_at' => $now
  10115. ]);
  10116. if ($boolen5 === false) {
  10117. Utils::throwError('20003:单剧集主表资源同步失败');
  10118. }
  10119. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  10120. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  10121. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  10122. $episode_record_content = '确认分镜大纲';
  10123. if ($content !== '') {
  10124. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  10125. }
  10126. $episode_records = [
  10127. [
  10128. 'uid' => $uid,
  10129. 'anime_id' => $anime_id,
  10130. 'role' => 'user',
  10131. 'content' => $episode_record_content,
  10132. 'sequence' => 1,
  10133. 'episode_id' => $episode_id,
  10134. 'created_at' => $now,
  10135. 'updated_at' => $now
  10136. ],
  10137. [
  10138. 'uid' => $uid,
  10139. 'anime_id' => $anime_id,
  10140. 'role' => 'assistant',
  10141. 'content' => $fullContent,
  10142. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  10143. 'sequence' => 1,
  10144. 'episode_id' => $episode_id,
  10145. 'created_at' => $now,
  10146. 'updated_at' => $now
  10147. ]
  10148. ];
  10149. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  10150. if (!$boolen4) {
  10151. Utils::throwError('20003:单剧集分镜记录保存失败');
  10152. }
  10153. }
  10154. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  10155. if ($is_single && !empty($single_episode)) {
  10156. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  10157. 'anime_id' => $anime_id,
  10158. 'episode_id' => $episode_id ?? 0,
  10159. 'model' => $model,
  10160. 'source' => 'reGenerateAnimeForAce',
  10161. ]);
  10162. }
  10163. }catch (\Exception $e) {
  10164. DB::rollBack();
  10165. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  10166. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  10167. yield [
  10168. 'type' => 'done',
  10169. 'answer' => $fullContent,
  10170. 'reasoning' => $fullReasoningContent,
  10171. 'usage' => $usage,
  10172. 'error' => $e->getMessage(),
  10173. ];
  10174. return;
  10175. }
  10176. DB::commit();
  10177. dLog('deepseek')->info('保存完毕');
  10178. if ($is_single && !empty($single_episode)) {
  10179. // $this->batchSetGlobalRoleImg([
  10180. // 'anime_id' => $anime_id,
  10181. // ]);
  10182. // $this->batchSetGlobalSceneImg([
  10183. // 'anime_id' => $anime_id,
  10184. // ]);
  10185. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  10186. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  10187. }
  10188. $table_data['anime_id'] = $anime_id;
  10189. $table_data['roles'] = json_decode($table_data['roles'], true);
  10190. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  10191. $table_data['props'] = json_decode($table_data['props'], true);
  10192. unset($table_data['updated_at']);
  10193. unset($table_data['status']);
  10194. yield [
  10195. 'type' => 'done',
  10196. 'script' => $table_data,
  10197. 'episode' => $single_episode,
  10198. 'answer' => $fullContent,
  10199. 'reasoning' => $fullReasoningContent,
  10200. 'usage' => $usage
  10201. ];
  10202. }
  10203. public function chatForAce($data) {
  10204. $uid = Site::getUid();
  10205. // 积分余额预检(不足直接报错)
  10206. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  10207. $anime_id = getProp($data, 'anime_id');
  10208. $file = getProp($data, 'file');
  10209. $content = getProp($data, 'content', '');
  10210. $bid = getProp($data, 'bid', 0);
  10211. $script_id = getProp($data, 'script_id', 0);
  10212. $episode_number = getProp($data, 'episode_number', 1);
  10213. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10214. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10215. if (!$anime) Utils::throwError('20003:该对话不存在!');
  10216. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  10217. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  10218. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  10219. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  10220. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  10221. $roles = is_array($roles) ? $roles : [];
  10222. $scenes = is_array($scenes) ? $scenes : [];
  10223. $extra_products = getProp($data, 'products', []);
  10224. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  10225. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  10226. $anime_script_id = getProp($anime, 'script_id');
  10227. if ($anime_script_id) {
  10228. $cpid = Site::getCpid();
  10229. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  10230. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  10231. ->where('mapping.script_id', $anime_script_id)
  10232. ->where('product.cpid', $cpid)
  10233. ->where('product.is_deleted', 0);
  10234. // 如果提供了 episode_number,则过滤指定集数
  10235. if ($episode_number !== null && $episode_number !== '') {
  10236. $script_products_mappings->where('mapping.episode_number', $episode_number);
  10237. }
  10238. $mappings = $script_products_mappings->select(
  10239. 'mapping.product_id',
  10240. 'mapping.episode_number',
  10241. 'product.product_name',
  10242. 'product.type',
  10243. 'product.product',
  10244. 'product.pic_prompt',
  10245. 'product.url',
  10246. 'product.pic_task_id',
  10247. 'product.pic_task_status',
  10248. 'product.three_view_image_url'
  10249. )
  10250. ->get();
  10251. // 按 product_id 分组,合并 episode_number
  10252. $productMap = [];
  10253. foreach ($mappings as $item) {
  10254. $product_id = $item->product_id;
  10255. $product_name = $item->product_name;
  10256. // 处理product_name两边的符号
  10257. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  10258. if (!isset($productMap[$product_id])) {
  10259. $productMap[$product_id] = [
  10260. 'product_id' => $product_id,
  10261. 'product_name' => $product_name,
  10262. 'type' => (int)$item->type,
  10263. 'product' => (int)$item->product,
  10264. 'pic_prompt' => $item->pic_prompt,
  10265. 'url' => $item->url,
  10266. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  10267. 'pic_task_id' => $item->pic_task_id,
  10268. 'pic_task_status' => $item->pic_task_status,
  10269. 'episode_numbers' => [],
  10270. ];
  10271. }
  10272. // 添加 episode_number(去重)
  10273. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  10274. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  10275. }
  10276. }
  10277. // 将查询到的剧本资产合并到extra_products中
  10278. // 先构建extra_products的索引(以product_id+episode_number为key)
  10279. $extraProductsMap = [];
  10280. foreach ($extra_products as $item) {
  10281. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  10282. $extraProductsMap[$key] = $item;
  10283. }
  10284. // 合并剧本资产(去重:product_id+episode_number)
  10285. foreach ($productMap as $product) {
  10286. foreach ($product['episode_numbers'] as $ep_num) {
  10287. $key = $product['product_id'] . '_' . $ep_num;
  10288. // 如果不存在则添加
  10289. if (!isset($extraProductsMap[$key])) {
  10290. $extraProductsMap[$key] = [
  10291. 'product_id' => $product['product_id'],
  10292. 'product_name' => $product['product_name'],
  10293. 'type' => $product['type'],
  10294. 'product' => $product['product'],
  10295. 'pic_prompt' => $product['pic_prompt'],
  10296. 'url' => $product['url'],
  10297. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  10298. 'pic_task_id' => $product['pic_task_id'],
  10299. 'pic_task_status' => $product['pic_task_status'],
  10300. 'episode_number' => $ep_num,
  10301. ];
  10302. }
  10303. }
  10304. }
  10305. // 重新赋值给extra_products
  10306. $extra_products = array_values($extraProductsMap);
  10307. }
  10308. // 处理提示词
  10309. if ($prompt && $extra_products) {
  10310. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  10311. foreach($extra_products as $item) {
  10312. $product_name = getProp($item, 'product_name');
  10313. if ($product_name) {
  10314. // 替换 {product_name} 为 product_name
  10315. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  10316. }
  10317. }
  10318. }
  10319. // 获取最后一集序号
  10320. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  10321. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  10322. // 转换主体列表和场景列表的格式
  10323. // 获取参考主体或场景
  10324. if ((int)$episode_number === 1) {
  10325. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  10326. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  10327. }else {
  10328. $prev_episode_number = $episode_number - 1;
  10329. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  10330. }
  10331. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  10332. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  10333. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  10334. // 合并anime_products和extra_products(extra_products优先,去重)
  10335. $anime_products = getProp($anime, 'extra_products');
  10336. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  10337. $ref_products = [];
  10338. foreach($anime_products as $item) {
  10339. $product_name = getProp($item, 'product_name');
  10340. $ref_products[$product_name] = $item;
  10341. }
  10342. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  10343. $extra_roles = []; // 从extra_products中提取的角色
  10344. $extra_scenes = []; // 从extra_products中提取的场景
  10345. $extra_props = []; // 从extra_products中提取的道具
  10346. if ($extra_products && is_array($extra_products)) {
  10347. foreach($extra_products as $item) {
  10348. $product = (int)getProp($item, 'product');
  10349. $product_name = getProp($item, 'product_name');
  10350. if ($product_name == '旁白') continue;
  10351. $pic_prompt = getProp($item, 'pic_prompt');
  10352. $ref_products[$product_name] = $item;
  10353. if ($product === 1) {
  10354. // 角色
  10355. $extra_roles[$product_name] = [
  10356. 'role' => $product_name,
  10357. 'pic_prompt' => $pic_prompt,
  10358. 'url' => getProp($item, 'url', ''),
  10359. ];
  10360. } elseif ($product === 2) {
  10361. // 场景
  10362. $extra_scenes[$product_name] = [
  10363. 'scene' => $product_name,
  10364. 'pic_prompt' => $pic_prompt,
  10365. 'url' => getProp($item, 'url', ''),
  10366. ];
  10367. } elseif ($product === 3) {
  10368. // 道具
  10369. $extra_props[$product_name] = [
  10370. 'prop' => $product_name,
  10371. 'pic_prompt' => $pic_prompt,
  10372. 'url' => getProp($item, 'url', ''),
  10373. ];
  10374. }
  10375. }
  10376. }
  10377. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  10378. $merged_roles = [];
  10379. foreach($ref_roles as $role) {
  10380. $role_name = getProp($role, 'role');
  10381. if (!isset($extra_roles[$role_name])) {
  10382. $merged_roles[$role_name] = $role;
  10383. }
  10384. }
  10385. // 添加extra_roles
  10386. foreach($extra_roles as $role_name => $role) {
  10387. $merged_roles[$role_name] = $role;
  10388. }
  10389. $ref_roles = array_values($merged_roles);
  10390. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  10391. $merged_scenes = [];
  10392. foreach($ref_scenes as $scene) {
  10393. $scene_name = getProp($scene, 'scene');
  10394. if (!isset($extra_scenes[$scene_name])) {
  10395. $merged_scenes[$scene_name] = $scene;
  10396. }
  10397. }
  10398. // 添加extra_scenes
  10399. foreach($extra_scenes as $scene_name => $scene) {
  10400. $merged_scenes[$scene_name] = $scene;
  10401. }
  10402. $ref_scenes = array_values($merged_scenes);
  10403. // 合并ref_props和extra_props(extra_props优先,去重)
  10404. $merged_props = [];
  10405. foreach($ref_props as $prop) {
  10406. $prop_name = getProp($prop, 'prop');
  10407. if (!isset($extra_props[$prop_name])) {
  10408. $merged_props[$prop_name] = $prop;
  10409. }
  10410. }
  10411. // 添加extra_props
  10412. foreach($extra_props as $prop_name => $prop) {
  10413. $merged_props[$prop_name] = $prop;
  10414. }
  10415. $ref_props = array_values($merged_props);
  10416. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  10417. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  10418. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  10419. // 构建强制主体、场景和道具提示词
  10420. $forced_roles_prompt = "";
  10421. $forced_scenes_prompt = "";
  10422. $forced_props_prompt = "";
  10423. if (!empty($extra_roles)) {
  10424. $forced_roles_list = "";
  10425. foreach($extra_roles as $role_name => $role) {
  10426. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  10427. }
  10428. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  10429. }
  10430. if (!empty($extra_scenes)) {
  10431. $forced_scenes_list = "";
  10432. foreach($extra_scenes as $scene_name => $scene) {
  10433. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  10434. }
  10435. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  10436. }
  10437. if (!empty($extra_props)) {
  10438. $forced_props_list = "";
  10439. foreach($extra_props as $prop_name => $prop) {
  10440. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  10441. }
  10442. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  10443. }
  10444. if ($anime_script_id) {
  10445. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  10446. }else if ($roles_content) {
  10447. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  10448. 主体范围:\n {$roles_content}\n
  10449. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  10450. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  10451. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  10452. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  10453. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  10454. }else {
  10455. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  10456. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  10457. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  10458. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  10459. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  10460. }
  10461. if ($anime_script_id) {
  10462. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  10463. }else if ($scenes_content) {
  10464. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  10465. 场景范围:\n {$scenes_content}\n
  10466. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  10467. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  10468. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  10469. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  10470. }else {
  10471. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  10472. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  10473. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  10474. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  10475. }
  10476. if ($anime_script_id) {
  10477. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  10478. }else if ($props_content) {
  10479. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  10480. 道具范围:\n {$props_content}\n
  10481. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  10482. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  10483. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  10484. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  10485. }else {
  10486. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  10487. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  10488. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  10489. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  10490. }
  10491. // 提取文件内容
  10492. if ($file) {
  10493. $uploaded_content = $this->extractFileContent($file);
  10494. if (!$uploaded_content) {
  10495. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  10496. }
  10497. } elseif ($script_id) {
  10498. $uploaded_content = $this->getContentByScriptId($script_id);
  10499. if (!$uploaded_content) {
  10500. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  10501. }
  10502. } elseif ($bid) {
  10503. $uploaded_content = $this->getContentByBid($bid);
  10504. if (!$uploaded_content) {
  10505. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  10506. }
  10507. } elseif ($content) {
  10508. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  10509. }
  10510. // elseif ($prompt) {
  10511. // $uploaded_content = filterContent($prompt);
  10512. // }
  10513. else {
  10514. $uploaded_content = '';
  10515. }
  10516. // 美术风格
  10517. $input_art_style = getProp($data, 'art_style');
  10518. if (!$input_art_style) {
  10519. $mappedArtStyle = getProp($anime, 'art_style');
  10520. }else {
  10521. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  10522. }
  10523. if (!$mappedArtStyle) {
  10524. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  10525. }else {
  10526. if (strstr($mappedArtStyle, '基础画风风格词')) {
  10527. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  10528. }else {
  10529. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  10530. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  10531. }
  10532. }
  10533. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10534. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  10535. // 强制要求:
  10536. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  10537. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  10538. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  10539. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  10540. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  10541. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  10542. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  10543. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  10544. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  10545. // 10.分镜要和场景列表、人物主体保持一致\n
  10546. // 普通要求:
  10547. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  10548. // {$role_demo}
  10549. // {$scene_demo}
  10550. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10551. // 4.1片段分割逻辑(优先级从高到低):
  10552. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10553. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10554. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10555. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10556. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10557. // - 片段数量格式为: 片段数量:8
  10558. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10559. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10560. // 4.3分镜结构:每个分镜包含以下字段:
  10561. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  10562. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  10563. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10564. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  10565. // - 运镜:场景+画面描述+运镜
  10566. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  10567. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10568. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10569. // 5.$mappedArtStyle_prompt\n\n
  10570. // 示例格式:\n
  10571. // 第1集:隐形的守护者
  10572. // ###故事梗概
  10573. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10574. // ###美术风格
  10575. // 基础画风风格词:胡金铨武侠
  10576. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10577. // ###主体列表
  10578. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10579. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10580. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10581. // ###场景列表
  10582. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10583. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10584. // ###分段剧本
  10585. // 片段数量:8
  10586. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10587. // ##片段1
  10588. // 时长:12s
  10589. // 分镜1
  10590. // 场景:边境小镇街道
  10591. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10592. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10593. // 配音台词:
  10594. // 背景音效:
  10595. // 分镜2
  10596. // 场景:悦来酒馆
  10597. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10598. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10599. // 配音台词:
  10600. // 背景音效:
  10601. // 分镜3
  10602. // 场景:悦来酒馆
  10603. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10604. // 运镜:从中景推向令牌特写。
  10605. // 配音台词:
  10606. // 背景音效:
  10607. // 分镜4
  10608. // 场景:悦来酒馆
  10609. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10610. // 运镜:极速推向酒水溅起的瞬间。
  10611. // 配音台词:
  10612. // 背景音效:
  10613. // 分镜5
  10614. // 镜头描述
  10615. // 场景:悦来酒馆
  10616. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10617. // 运镜:固定机位,利用倾斜构图制造压迫感。
  10618. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10619. // 背景音效:
  10620. // \n\n";
  10621. /*
  10622. // ====== 旧版 $demo(缓存优化前版本,动态数据内嵌在规则中间) ======
  10623. // 如需换回:删除下方新版 $demo,并把本块恢复为活动代码(去掉首尾注释标记)
  10624. // ===================================================================
  10625. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  10626. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  10627. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  10628. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  10629. 强制要求:
  10630. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  10631. 普通要求:
  10632. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  10633. {$role_demo}
  10634. {$scene_demo}
  10635. {$prop_demo}
  10636. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10637. 5.1片段分割逻辑(优先级从高到低):
  10638. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10639. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10640. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10641. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10642. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10643. - 片段数量格式为: 片段数量:8
  10644. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10645. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10646. 5.3分镜结构:每个分镜包含以下字段:
  10647. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  10648. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10649. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10650. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10651. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10652. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10653. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10654. - 运镜:场景+画面描述+运镜
  10655. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  10656. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  10657. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10658. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10659. 6.《情绪-视听语言映射表》:
  10660. 6.1 场景空间与时间心理学 (Scene & Temporality)
  10661. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10662. -----|---------|------------|----------------
  10663. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  10664. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  10665. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  10666. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  10667. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  10668. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10669. -----|---------|------------|----------------
  10670. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  10671. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  10672. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  10673. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  10674. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  10675. --------|---------|--------------|-------------
  10676. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  10677. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  10678. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  10679. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  10680. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  10681. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  10682. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  10683. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  10684. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  10685. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  10686. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  10687. -----|---------|------------|------------
  10688. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  10689. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  10690. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  10691. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  10692. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  10693. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  10694. --------|---------|--------------|----------
  10695. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  10696. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  10697. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  10698. 6.6 声音设计与潜意识影响 (Soundscape)
  10699. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  10700. -----|---------|------------|------------------
  10701. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  10702. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  10703. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  10704. 理论基石:
  10705. - The Five C's of Cinematography by Joseph V. Mascelli
  10706. - Film Art: An Introduction by David Bordwell
  10707. - Sight, Sound, Motion by Herbert Zettl
  10708. - Notes on the Cinematograph by Robert Bresson
  10709. \n\n
  10710. 7.{$mappedArtStyle_prompt}
  10711. 示例格式:\n
  10712. 第1集:隐形的守护者
  10713. ###故事梗概
  10714. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10715. ###美术风格
  10716. 基础画风风格词:胡金铨武侠
  10717. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10718. ###主体列表
  10719. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10720. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10721. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10722. ###场景列表
  10723. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10724. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10725. ###道具列表
  10726. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  10727. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  10728. ###分段剧本
  10729. 片段数量:8
  10730. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10731. ##片段1
  10732. 时长:12s
  10733. 分镜1
  10734. 出场角色:刀疤脸
  10735. 场景:边境小镇街道
  10736. 出场道具:酒杯-高脚杯
  10737. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10738. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10739. 配音台词:
  10740. 背景音效:
  10741. 分镜2
  10742. 出场角色:刀疤脸
  10743. 场景:悦来酒馆
  10744. 出场道具:酒杯-高脚杯
  10745. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10746. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10747. 配音台词:
  10748. 背景音效:
  10749. 分镜3
  10750. 出场角色:刀疤脸
  10751. 场景:悦来酒馆
  10752. 出场道具:酒杯-高脚杯
  10753. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10754. 运镜:从中景推向令牌特写。
  10755. 配音台词:
  10756. 背景音效:
  10757. 分镜4
  10758. 出场角色:刀疤脸
  10759. 场景:悦来酒馆
  10760. 出场道具:酒杯-高脚杯
  10761. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10762. 运镜:极速推向酒水溅起的瞬间。
  10763. 配音台词:
  10764. 背景音效:
  10765. 分镜5
  10766. 出场角色:刀疤脸
  10767. 场景:悦来酒馆
  10768. 出场道具:酒杯-高脚杯
  10769. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10770. 运镜:固定机位,利用倾斜构图制造压迫感。
  10771. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10772. 背景音效:
  10773. \n\n";
  10774. */
  10775. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  10776. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  10777. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  10778. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  10779. 强制要求:
  10780. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  10781. 普通要求:
  10782. 1.剧集标题必须与文档内容高度相关,剧集序号见文末【本次剧集信息】。
  10783. 2.<主体列表>的详细规则和可选范围见文末【本次生成数据-主体列表】。
  10784. 3.<场景列表>的详细规则和可选范围见文末【本次生成数据-场景列表】。
  10785. 4.<道具列表>的详细规则和可选范围见文末【本次生成数据-道具列表】。
  10786. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10787. 5.1片段分割逻辑(优先级从高到低):
  10788. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10789. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10790. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10791. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10792. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10793. - 片段数量格式为: 片段数量:8
  10794. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10795. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10796. 5.3分镜结构:每个分镜包含以下字段:
  10797. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  10798. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  10799. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10800. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10801. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10802. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10803. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10804. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10805. - 运镜:场景+画面描述+运镜
  10806. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  10807. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  10808. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10809. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10810. 6.《情绪-视听语言映射表》:
  10811. 6.1 场景空间与时间心理学 (Scene & Temporality)
  10812. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10813. -----|---------|------------|----------------
  10814. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  10815. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  10816. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  10817. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  10818. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  10819. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10820. -----|---------|------------|----------------
  10821. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  10822. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  10823. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  10824. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  10825. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  10826. --------|---------|--------------|-------------
  10827. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  10828. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  10829. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  10830. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  10831. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  10832. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  10833. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  10834. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  10835. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  10836. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  10837. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  10838. -----|---------|------------|------------
  10839. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  10840. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  10841. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  10842. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  10843. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  10844. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  10845. --------|---------|--------------|----------
  10846. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  10847. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  10848. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  10849. 6.6 声音设计与潜意识影响 (Soundscape)
  10850. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  10851. -----|---------|------------|------------------
  10852. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  10853. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  10854. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  10855. 理论基石:
  10856. - The Five C's of Cinematography by Joseph V. Mascelli
  10857. - Film Art: An Introduction by David Bordwell
  10858. - Sight, Sound, Motion by Herbert Zettl
  10859. - Notes on the Cinematograph by Robert Bresson
  10860. \n\n
  10861. 7.美术风格要求见文末【本次生成数据-美术风格】。
  10862. 示例格式:\n
  10863. 第1集:隐形的守护者
  10864. ###故事梗概
  10865. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10866. ###美术风格
  10867. 基础画风风格词:胡金铨武侠
  10868. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10869. ###主体列表
  10870. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10871. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10872. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10873. ###场景列表
  10874. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10875. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10876. ###道具列表
  10877. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  10878. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  10879. ###分段剧本
  10880. 片段数量:8
  10881. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10882. ##片段1
  10883. 时长:12s
  10884. 分镜1
  10885. 出场角色:刀疤脸
  10886. 场景:边境小镇街道
  10887. 出场道具:酒杯-高脚杯
  10888. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10889. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10890. 配音台词:
  10891. 背景音效:
  10892. 分镜2
  10893. 出场角色:刀疤脸
  10894. 场景:悦来酒馆
  10895. 出场道具:酒杯-高脚杯
  10896. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10897. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10898. 配音台词:
  10899. 背景音效:
  10900. 分镜3
  10901. 出场角色:刀疤脸
  10902. 场景:悦来酒馆
  10903. 出场道具:酒杯-高脚杯
  10904. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10905. 运镜:从中景推向令牌特写。
  10906. 配音台词:
  10907. 背景音效:
  10908. 分镜4
  10909. 出场角色:刀疤脸
  10910. 场景:悦来酒馆
  10911. 出场道具:酒杯-高脚杯
  10912. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10913. 运镜:极速推向酒水溅起的瞬间。
  10914. 配音台词:
  10915. 背景音效:
  10916. 分镜5
  10917. 出场角色:刀疤脸
  10918. 场景:悦来酒馆
  10919. 出场道具:酒杯-高脚杯
  10920. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10921. 运镜:固定机位,利用倾斜构图制造压迫感。
  10922. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10923. 背景音效:
  10924. \n\n本次生成数据(以上规则的动态数据均在此处,优先级等同对应编号规则):
  10925. 【本次剧集信息】剧集序号是{$episode_number}。
  10926. 【本次生成数据-主体列表】{$role_demo}
  10927. 【本次生成数据-场景列表】{$scene_demo}
  10928. 【本次生成数据-道具列表】{$prop_demo}
  10929. 【本次生成数据-美术风格】{$mappedArtStyle_prompt}
  10930. \n\n";
  10931. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10932. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  10933. // $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  10934. $is_regenerate_version = true;
  10935. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  10936. $prompt = $origin_prompt;
  10937. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  10938. // 获取章节内容
  10939. $full_content = getProp($anime, 'content');
  10940. if ($uploaded_content) {
  10941. $full_content = $uploaded_content;
  10942. }
  10943. // 根据章节内容拆分章节
  10944. $chapters = splitContent($full_content);
  10945. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  10946. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  10947. $messages = [];
  10948. if ($prompt == '确认分镜大纲') {
  10949. // 暂时保留
  10950. $content = $chapter_content;
  10951. if ($is_single) $content = $full_content; // 单剧集使用全文
  10952. if (!$content) {
  10953. Utils::throwError('20003:章节内容无法获取,请确认');
  10954. }
  10955. $question = $is_single
  10956. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  10957. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  10958. // 构建消息
  10959. $messages[] =
  10960. [
  10961. 'role' => 'user',
  10962. 'content' => $question
  10963. ];
  10964. }else if ($prompt == '继续策划下一集') {
  10965. if ($is_single) {
  10966. Utils::throwError('20003:单剧集不支持继续策划下一集');
  10967. }
  10968. $content = $chapter_content;
  10969. if (!$content) {
  10970. Utils::throwError('20003:章节内容无法获取,请确认');
  10971. }
  10972. // 获取上一集最后记录
  10973. $prev_sequence = $episode_number - 1;
  10974. $messages = array_merge(
  10975. [
  10976. [
  10977. 'role' => 'system',
  10978. 'content' => $demo
  10979. ]
  10980. ],
  10981. $this->getEpisodeChatContent($anime_id, $prev_sequence, $content)
  10982. );
  10983. // 构建消息
  10984. $messages[] =
  10985. [
  10986. 'role' => 'user',
  10987. 'content' => "请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)"
  10988. ];
  10989. /*
  10990. // 旧版逻辑
  10991. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  10992. // 构建消息
  10993. $messages[] =
  10994. [
  10995. 'role' => 'user',
  10996. 'content' => $question
  10997. ];
  10998. */
  10999. // dd($messages);
  11000. }else {
  11001. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  11002. if (!$content) {
  11003. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  11004. }
  11005. if (!$content) {
  11006. Utils::throwError('20003:章节内容无法获取,请确认');
  11007. }
  11008. $messages = array_merge(
  11009. [
  11010. [
  11011. 'role' => 'system',
  11012. 'content' => $demo
  11013. ]
  11014. ],
  11015. $this->getEpisodeChatMessages($anime_id, $episode_number)
  11016. );
  11017. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  11018. $question = "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  11019. if ($origin_prompt) {
  11020. $question .= "本次修改要求如下:\n{$origin_prompt}";
  11021. }
  11022. // 将本集原文加入消息,供模型逐字摘录原文台词(修复重新生成时配音台词全部为"无"的问题)
  11023. $messages[] = [
  11024. 'role' => 'user',
  11025. 'content' => "本集剧情内容:\n\n{$content}\n"
  11026. ];
  11027. $messages[] =
  11028. [
  11029. 'role' => 'user',
  11030. 'content' => $question
  11031. ];
  11032. }
  11033. // 处理文本模型
  11034. $model = getProp($data, 'model');
  11035. if (!$model) {
  11036. // 用户没有输入,从anime表获取
  11037. $model = getProp($anime, 'model');
  11038. if (!$model) {
  11039. // anime表也没有,使用默认值
  11040. $model = 'deepseek-v4-pro';
  11041. }
  11042. }
  11043. // 验证模型是否在可用模型表中
  11044. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  11045. $model = 'deepseek-v4-pro';
  11046. }
  11047. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  11048. $thinkingMode = getProp($data, 'thinking', 'enabled'); // 默认非思考模式
  11049. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  11050. if ($model === 'deepseek-chat') {
  11051. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  11052. $model = 'deepseek-v4-flash';
  11053. $thinkingMode = 'disabled';
  11054. } elseif ($model === 'deepseek-reasoner') {
  11055. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  11056. $model = 'deepseek-v4-flash';
  11057. $thinkingMode = 'enabled';
  11058. }
  11059. $post_data = [
  11060. 'model' => $model,
  11061. 'messages' => $messages,
  11062. // 'max_tokens' => 8192,
  11063. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  11064. 'frequency_penalty' => 0,
  11065. 'presence_penalty' => 0,
  11066. 'response_format' => ['type' => 'text'],
  11067. 'thinking' => ['type' => $thinkingMode],
  11068. 'stream' => true // 启用流式输出
  11069. ];
  11070. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  11071. // 根据模型类型选择调用方法
  11072. $fullContent = '';
  11073. $fullReasoningContent = '';
  11074. $usage = [];
  11075. try {
  11076. $streamGenerator = $this->dispatchStreamByModel($post_data);
  11077. // 验证返回值类型
  11078. if (!is_iterable($streamGenerator)) {
  11079. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  11080. dLog('deepseek')->error('chat流式生成器无效', [
  11081. 'generator_type' => $errorType,
  11082. 'model' => $model,
  11083. 'anime_id' => $anime_id,
  11084. 'episode_number' => $episode_number
  11085. ]);
  11086. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  11087. 'type' => $errorType,
  11088. 'model' => $model
  11089. ]);
  11090. yield [
  11091. 'type' => 'error',
  11092. 'episode' => [],
  11093. 'answer' => '',
  11094. 'reasoning' => '',
  11095. 'usage' => [],
  11096. 'error' => '接口返回数据异常,请重新请求'
  11097. ];
  11098. return;
  11099. }
  11100. // 处理流式输出
  11101. foreach ($streamGenerator as $chunk) {
  11102. if (isset($chunk['type'])) {
  11103. if ($chunk['type'] === 'done') {
  11104. // 最终结果
  11105. $fullContent = $chunk['full_content'];
  11106. $fullReasoningContent = $chunk['full_reasoning'];
  11107. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  11108. } else {
  11109. // 逐块yield数据
  11110. yield $chunk;
  11111. }
  11112. }
  11113. }
  11114. } catch (\Exception $e) {
  11115. // 解析上游错误详情(如 content_filter),便于日志定位与前端提示
  11116. $upstream_error = $this->resolveGptUpstreamError($e);
  11117. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  11118. 'model' => $model,
  11119. 'anime_id' => $anime_id,
  11120. 'episode_number' => $episode_number,
  11121. 'upstream_status' => $upstream_error['status'],
  11122. 'upstream_code' => $upstream_error['code'],
  11123. 'upstream_body' => $upstream_error['body'],
  11124. 'trace' => $e->getTraceAsString()
  11125. ]);
  11126. logDB('deepseek', 'error', 'chat流式处理失败', [
  11127. 'error' => $e->getMessage(),
  11128. 'model' => $model,
  11129. 'upstream_status' => $upstream_error['status'],
  11130. 'upstream_code' => $upstream_error['code'],
  11131. 'upstream_body' => $upstream_error['body']
  11132. ]);
  11133. yield [
  11134. 'type' => 'error',
  11135. 'episode' => [],
  11136. 'answer' => '',
  11137. 'reasoning' => '',
  11138. 'usage' => [],
  11139. 'error' => $this->buildChatErrorForUser($e, $upstream_error)
  11140. ];
  11141. return;
  11142. }
  11143. // 兼容模型偶发将整段正文包裹成 JSON 字符串返回
  11144. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  11145. dLog('deepseek')->info('完整内容: '.$fullContent);
  11146. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  11147. // 处理完整内容并返回最终结果
  11148. $episode_arr = handleEpisodeContentForAce($fullContent);
  11149. dLog('deepseek')->info('解析内容: ', $episode_arr);
  11150. logDB('deepseek', 'info', '解析内容', $episode_arr);
  11151. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  11152. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  11153. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  11154. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  11155. // }
  11156. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  11157. $max_retries = 3;
  11158. $retry_count = 0;
  11159. $validation_failed = false;
  11160. $validation_error_msg = '';
  11161. // 验证生成的内容
  11162. if ($anime_script_id) {
  11163. // 检查是否有acts数据
  11164. if (empty($episode_arr['acts'])) {
  11165. $validation_failed = true;
  11166. $validation_error_msg = '未生成分镜剧本相关的内容';
  11167. } else {
  11168. // 校验主体列表:不能为空主体(旁白不算)
  11169. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11170. // 过滤掉"旁白"角色
  11171. $generated_roles = array_filter($generated_roles, function($role) {
  11172. return $role !== '旁白';
  11173. });
  11174. if (empty($generated_roles)) {
  11175. $validation_failed = true;
  11176. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11177. }
  11178. // 仅当存在强制主体设定时校验主体列表
  11179. if (!$validation_failed && !empty($extra_roles)) {
  11180. $expected_roles = array_keys($extra_roles);
  11181. // 找出生成的主体中不在预期列表中的主体
  11182. $invalid_roles = array_diff($generated_roles, $expected_roles);
  11183. if (!empty($invalid_roles)) {
  11184. $validation_failed = true;
  11185. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  11186. }
  11187. }
  11188. // 仅当存在强制场景设定时校验场景列表
  11189. if (!$validation_failed && !empty($extra_scenes)) {
  11190. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  11191. $expected_scenes = array_keys($extra_scenes);
  11192. // 找出生成的场景中不在预期列表中的场景
  11193. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  11194. if (!empty($invalid_scenes)) {
  11195. $validation_failed = true;
  11196. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  11197. }
  11198. }
  11199. // 仅当存在强制道具设定时校验道具列表
  11200. if (!$validation_failed && !empty($extra_props)) {
  11201. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  11202. $expected_props = array_keys($extra_props);
  11203. // 找出生成的道具中不在预期列表中的道具
  11204. $invalid_props = array_diff($generated_props, $expected_props);
  11205. if (!empty($invalid_props)) {
  11206. $validation_failed = true;
  11207. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  11208. }
  11209. }
  11210. }
  11211. } else {
  11212. // 如果没有anime_script_id,只检查是否有acts数据
  11213. if (empty($episode_arr['acts'])) {
  11214. $validation_failed = true;
  11215. $validation_error_msg = '未生成分镜剧本相关的内容';
  11216. } else {
  11217. // 校验主体列表:不能为空主体(旁白不算)
  11218. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11219. // 过滤掉"旁白"角色
  11220. $generated_roles = array_filter($generated_roles, function($role) {
  11221. return $role !== '旁白';
  11222. });
  11223. if (empty($generated_roles)) {
  11224. $validation_failed = true;
  11225. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11226. }
  11227. }
  11228. }
  11229. // 重试逻辑
  11230. while ($validation_failed && $retry_count < $max_retries) {
  11231. $retry_count++;
  11232. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  11233. 'reason' => $validation_error_msg,
  11234. 'anime_id' => $anime_id,
  11235. 'episode_number' => $episode_number
  11236. ]);
  11237. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  11238. 'reason' => $validation_error_msg,
  11239. 'anime_id' => $anime_id
  11240. ]);
  11241. // 发送流式重试提示
  11242. yield [
  11243. 'type' => 'retry',
  11244. 'retry_count' => $retry_count,
  11245. 'reason' => $validation_error_msg
  11246. ];
  11247. // 构建重试提示词
  11248. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  11249. if ($anime_script_id) {
  11250. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  11251. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  11252. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  11253. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  11254. } else {
  11255. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  11256. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  11257. }
  11258. // 添加重试消息到messages
  11259. $messages[] = [
  11260. 'role' => 'assistant',
  11261. 'content' => $fullContent
  11262. ];
  11263. $messages[] = [
  11264. 'role' => 'user',
  11265. 'content' => $retry_prompt
  11266. ];
  11267. // 更新post_data的messages
  11268. $post_data['messages'] = $messages;
  11269. // 重新调用API
  11270. try {
  11271. $streamGenerator = $this->dispatchStreamByModel($post_data);
  11272. // 处理流式输出
  11273. $fullContent = '';
  11274. $fullReasoningContent = '';
  11275. foreach ($streamGenerator as $chunk) {
  11276. if (isset($chunk['type'])) {
  11277. if ($chunk['type'] === 'done') {
  11278. $fullContent = $chunk['full_content'];
  11279. $fullReasoningContent = $chunk['full_reasoning'];
  11280. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  11281. } else {
  11282. yield $chunk;
  11283. }
  11284. }
  11285. }
  11286. // 重新解析内容
  11287. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  11288. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  11289. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  11290. $episode_arr = handleEpisodeContentForAce($fullContent);
  11291. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  11292. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  11293. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  11294. // }
  11295. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  11296. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  11297. // 重新验证
  11298. $validation_failed = false;
  11299. $validation_error_msg = '';
  11300. if ($anime_script_id) {
  11301. if (empty($episode_arr['acts'])) {
  11302. $validation_failed = true;
  11303. $validation_error_msg = '未生成分镜剧本相关的内容';
  11304. } else {
  11305. // 校验主体列表:不能为空主体(旁白不算)
  11306. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11307. // 过滤掉"旁白"角色
  11308. $generated_roles = array_filter($generated_roles, function($role) {
  11309. return $role !== '旁白';
  11310. });
  11311. if (empty($generated_roles)) {
  11312. $validation_failed = true;
  11313. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11314. }
  11315. // 仅当存在强制主体设定时校验主体列表
  11316. if (!$validation_failed && !empty($extra_roles)) {
  11317. $expected_roles = array_keys($extra_roles);
  11318. $invalid_roles = array_diff($generated_roles, $expected_roles);
  11319. if (!empty($invalid_roles)) {
  11320. $validation_failed = true;
  11321. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  11322. }
  11323. }
  11324. // 仅当存在强制场景设定时校验场景列表
  11325. if (!$validation_failed && !empty($extra_scenes)) {
  11326. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  11327. $expected_scenes = array_keys($extra_scenes);
  11328. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  11329. if (!empty($invalid_scenes)) {
  11330. $validation_failed = true;
  11331. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  11332. }
  11333. }
  11334. // 仅当存在强制道具设定时校验道具列表
  11335. if (!$validation_failed && !empty($extra_props)) {
  11336. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  11337. $expected_props = array_keys($extra_props);
  11338. $invalid_props = array_diff($generated_props, $expected_props);
  11339. if (!empty($invalid_props)) {
  11340. $validation_failed = true;
  11341. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  11342. }
  11343. }
  11344. }
  11345. } else {
  11346. if (empty($episode_arr['acts'])) {
  11347. $validation_failed = true;
  11348. $validation_error_msg = '未生成分镜剧本相关的内容';
  11349. } else {
  11350. // 校验主体列表:不能为空主体(旁白不算)
  11351. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11352. // 过滤掉"旁白"角色
  11353. $generated_roles = array_filter($generated_roles, function($role) {
  11354. return $role !== '旁白';
  11355. });
  11356. if (empty($generated_roles)) {
  11357. $validation_failed = true;
  11358. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11359. }
  11360. }
  11361. }
  11362. } catch (\Exception $e) {
  11363. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  11364. 'trace' => $e->getTraceAsString()
  11365. ]);
  11366. break;
  11367. }
  11368. }
  11369. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  11370. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  11371. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  11372. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  11373. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  11374. if ($validation_failed && $retry_count >= $max_retries) {
  11375. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  11376. 'retry_count' => $retry_count,
  11377. 'last_error' => $validation_error_msg
  11378. ]);
  11379. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  11380. 'error' => $validation_error_msg,
  11381. 'anime_id' => $anime_id
  11382. ]);
  11383. $validation_failed = false;
  11384. $validation_error_msg = '';
  11385. }
  11386. // 如果重试后仍然失败
  11387. if ($validation_failed) {
  11388. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  11389. 'retry_count' => $retry_count,
  11390. 'last_error' => $validation_error_msg
  11391. ]);
  11392. try {
  11393. $now = date('Y-m-d H:i:s');
  11394. $records = [
  11395. [
  11396. 'uid' => $uid,
  11397. 'anime_id' => $anime_id,
  11398. 'sequence' => $episode_number,
  11399. 'role' => 'user',
  11400. 'content' => $prompt,
  11401. 'created_at' => $now,
  11402. 'updated_at' => $now
  11403. ],
  11404. [
  11405. 'uid' => $uid,
  11406. 'anime_id' => $anime_id,
  11407. 'sequence' => $episode_number,
  11408. 'role' => 'assistant',
  11409. 'content' => $fullContent,
  11410. 'created_at' => $now,
  11411. 'updated_at' => $now
  11412. ]
  11413. ];
  11414. DB::table('mp_anime_records')->insert($records);
  11415. } catch (\Exception $e) {
  11416. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  11417. }
  11418. yield [
  11419. 'type' => 'done',
  11420. 'episode' => [],
  11421. 'answer' => $fullContent,
  11422. 'reasoning' => $fullReasoningContent,
  11423. 'usage' => $usage,
  11424. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  11425. ];
  11426. return;
  11427. }
  11428. // 验证成功,记录日志
  11429. if ($retry_count > 0) {
  11430. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  11431. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  11432. }
  11433. // 老逻辑
  11434. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  11435. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  11436. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  11437. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  11438. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  11439. $existing_props = is_array($existing_props) ? $existing_props : [];
  11440. $now = date('Y-m-d H:i:s');
  11441. try {
  11442. DB::beginTransaction();
  11443. $saveResult = $this->saveEpisodeVersionData(
  11444. $anime_id,
  11445. $episode_number,
  11446. $episode_arr,
  11447. $existing_roles,
  11448. $existing_scenes,
  11449. $existing_props,
  11450. $current_episode,
  11451. $base_episode,
  11452. $is_regenerate_version,
  11453. $content,
  11454. $now,
  11455. $ref_products
  11456. );
  11457. $episode = $saveResult['episode'];
  11458. $episode_id = $saveResult['episode_id'];
  11459. $merged_roles = $saveResult['merged_roles'];
  11460. $merged_scenes = $saveResult['merged_scenes'];
  11461. $merged_props = $saveResult['merged_props'];
  11462. $record_content = $origin_prompt;
  11463. if ($uploaded_content !== '') {
  11464. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  11465. }
  11466. $records = [
  11467. [
  11468. 'uid' => $uid,
  11469. 'anime_id' => $anime_id,
  11470. 'role' => 'user',
  11471. 'content' => $record_content,
  11472. 'sequence' => $episode_number,
  11473. 'episode_id' => $episode_id,
  11474. 'created_at' => $now,
  11475. 'updated_at' => $now
  11476. ],
  11477. [
  11478. 'uid' => $uid,
  11479. 'anime_id' => $anime_id,
  11480. 'role' => 'assistant',
  11481. 'content' => $fullContent,
  11482. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  11483. 'sequence' => $episode_number,
  11484. 'episode_id' => $episode_id,
  11485. 'created_at' => $now,
  11486. 'updated_at' => $now
  11487. ]
  11488. ];
  11489. $boolen4 = DB::table('mp_anime_records')->insert($records);
  11490. if (!$boolen4) {
  11491. Utils::throwError('20003:对话记录保存失败');
  11492. }
  11493. // 保存模型到anime表
  11494. $update_anime_data = [
  11495. 'model' => $model,
  11496. 'updated_at' => $now
  11497. ];
  11498. if ($uploaded_content) {
  11499. $update_anime_data['content'] = $uploaded_content;
  11500. }
  11501. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  11502. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  11503. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  11504. 'anime_id' => $anime_id,
  11505. 'episode_number' => $episode_number,
  11506. 'model' => $model,
  11507. 'source' => 'chatForAce',
  11508. ]);
  11509. }catch (\Exception $e) {
  11510. DB::rollBack();
  11511. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  11512. yield [
  11513. 'type' => 'done',
  11514. 'answer' => $fullContent,
  11515. 'reasoning' => $fullReasoningContent,
  11516. 'usage' => $usage,
  11517. 'error' => $e->getMessage(),
  11518. ];
  11519. return;
  11520. }
  11521. DB::commit();
  11522. if ($is_global_generate_pics) {
  11523. // // 批量生成全局角色图片
  11524. // $this->batchSetGlobalRoleImg([
  11525. // 'anime_id' => $anime_id,
  11526. // ], true);
  11527. // // 批量生成全局场景图片
  11528. // $this->batchSetGlobalSceneImg([
  11529. // 'anime_id' => $anime_id,
  11530. // ], true);
  11531. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  11532. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  11533. }
  11534. $episode['episode_id'] = $episode_id;
  11535. $episode['roles'] = $merged_roles;
  11536. $episode['scenes'] = $merged_scenes;
  11537. $episode['props'] = $merged_props;
  11538. $episode['end_episode_sequence'] = $end_episode_sequence;
  11539. // 获取mp_animes表中的视频参数
  11540. $episode['video_params'] = [
  11541. 'video_model' => getProp($anime, 'video_model'),
  11542. 'video_resolution' => getProp($anime, 'video_resolution'),
  11543. 'ratio' => getProp($anime, 'video_ratio'),
  11544. ];
  11545. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  11546. yield [
  11547. 'type' => 'done',
  11548. 'episode' => $episode,
  11549. 'answer' => $fullContent,
  11550. 'reasoning' => $fullReasoningContent,
  11551. 'usage' => $usage
  11552. ];
  11553. }
  11554. /**
  11555. * chatForAce的非流式版本 - 用于定时任务
  11556. * 只获取最终 type=done 的数据,并验证必要字段
  11557. *
  11558. * @param array $data 请求数据
  11559. * @return array 生成结果
  11560. */
  11561. public function chatForAceNonStream($data) {
  11562. $finalResult = null;
  11563. // 调用流式方法,只保存 type=done 的数据
  11564. foreach ($this->chatForAce($data) as $chunk) {
  11565. // 只关注最终结果
  11566. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  11567. $finalResult = $chunk;
  11568. break; // 找到 done 就退出循环
  11569. }
  11570. // 出错时直接带上原因返回(如上游内容安全策略拦截),避免被吞成"未获取到最终结果"
  11571. if (isset($chunk['type']) && $chunk['type'] === 'error' && !empty($chunk['error'])) {
  11572. return ['error' => $chunk['error']];
  11573. }
  11574. }
  11575. // 验证最终结果
  11576. if (!$finalResult) {
  11577. return ['error' => '生成失败:未获取到最终结果'];
  11578. }
  11579. // 检查是否有错误
  11580. if (isset($finalResult['error']) && $finalResult['error']) {
  11581. return $finalResult;
  11582. }
  11583. // 验证必要字段
  11584. $episode = $finalResult['episode'] ?? [];
  11585. // 验证 roles(旁白不算主体,过滤后不能为空)
  11586. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  11587. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  11588. }
  11589. $nonNarratorRoles = array_filter(array_column($episode['roles'], 'role'), function($role) {
  11590. return $role !== '旁白';
  11591. });
  11592. if (empty($nonNarratorRoles)) {
  11593. return ['error' => '生成失败:主体列表(roles)为空或格式错误(旁白不算)'];
  11594. }
  11595. // 验证 scenes
  11596. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  11597. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  11598. }
  11599. // 验证 props(道具可以为空,但必须存在且为数组)
  11600. if (!isset($episode['props']) || !is_array($episode['props'])) {
  11601. $episode['props'] = [];
  11602. }
  11603. // 验证 acts(分镜剧本)
  11604. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  11605. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  11606. }
  11607. // 更新验证后的 episode 数据
  11608. $finalResult['episode'] = $episode;
  11609. // 记录验证成功日志
  11610. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  11611. 'roles_count' => count($episode['roles']),
  11612. 'scenes_count' => count($episode['scenes']),
  11613. 'props_count' => count($episode['props']),
  11614. 'acts_count' => count($episode['acts'])
  11615. ]);
  11616. return $finalResult;
  11617. }
  11618. /**
  11619. * 批量生成多个分集
  11620. *
  11621. * @param array $data 请求数据
  11622. * @return array 任务信息
  11623. */
  11624. public function batchGenerateEpisodes($data) {
  11625. $uid = Site::getUid();
  11626. $cpid = Site::getCpid();
  11627. $anime_id = getProp($data, 'anime_id');
  11628. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  11629. $start_episode_number = getProp($data, 'start_episode_number');
  11630. $end_episode_number = getProp($data, 'end_episode_number');
  11631. if (!$anime_id) {
  11632. Utils::throwError('20003:anime_id参数缺失');
  11633. }
  11634. if ($generate_episode_number < 1) {
  11635. Utils::throwError('20003:生成集数必须大于0');
  11636. }
  11637. // 获取动漫信息
  11638. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  11639. if (!$anime) {
  11640. Utils::throwError('20003:该剧集不存在');
  11641. }
  11642. // 检查是否是全能模式
  11643. if ((int)getProp($anime, 'ace_mode') !== 1) {
  11644. Utils::throwError('20003:只有全能模式才支持批量生成');
  11645. }
  11646. // 检查是否是多剧集模式
  11647. if ((int)getProp($anime, 'is_multi') !== 1) {
  11648. Utils::throwError('20003:单剧集不支持批量生成');
  11649. }
  11650. // 指定起始/结束剧集序号时的校验
  11651. $hasSpecifiedRange = ($start_episode_number !== null && $start_episode_number !== '')
  11652. || ($end_episode_number !== null && $end_episode_number !== '');
  11653. if ($hasSpecifiedRange) {
  11654. if ($start_episode_number === null || $start_episode_number === ''
  11655. || $end_episode_number === null || $end_episode_number === '') {
  11656. Utils::throwError('20003:起始剧集序号和结束剧集序号必须同时提供');
  11657. }
  11658. $start_episode_number = (int)$start_episode_number;
  11659. $end_episode_number = (int)$end_episode_number;
  11660. if ($start_episode_number < 1 || $end_episode_number < $start_episode_number) {
  11661. Utils::throwError('20003:剧集序号范围错误,结束剧集序号不能小于起始剧集序号');
  11662. }
  11663. // 起始序号必须是已有剧集(is_default=1)的下一个序号,不允许跨序号创建
  11664. $currentMaxEpisode = DB::table('mp_anime_episodes')
  11665. ->where('anime_id', $anime_id)
  11666. ->where('is_default', 1)
  11667. ->max('episode_number');
  11668. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  11669. $nextEpisodeNumber = $currentMaxEpisode + 1;
  11670. if ($start_episode_number !== $nextEpisodeNumber) {
  11671. Utils::throwError('20003:起始剧集序号必须是已有剧集的下一个序号(第' . $nextEpisodeNumber . '集),不允许跨序号创建');
  11672. }
  11673. $startEpisodeNumber = $start_episode_number;
  11674. $endEpisodeNumber = $end_episode_number;
  11675. } else {
  11676. // 未指定范围时,以 generate_episode_number 判断要生成的集数,从当前已生成的最大集数的下一集开始
  11677. $currentMaxEpisode = DB::table('mp_anime_episodes')
  11678. ->where('anime_id', $anime_id)
  11679. ->where('is_default', 1)
  11680. ->max('episode_number');
  11681. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  11682. // 确定起始集数
  11683. $startEpisodeNumber = $currentMaxEpisode + 1;
  11684. // 计算结束集数
  11685. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  11686. }
  11687. // 本次实际生成的集数
  11688. $totalEpisodeCount = $endEpisodeNumber - $startEpisodeNumber + 1;
  11689. // 检查是否超过总集数限制
  11690. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  11691. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  11692. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  11693. }
  11694. // 创建任务前验重:批量任务表与剧集表中是否已存在范围内的剧集序号
  11695. $duplicatedBatchEpisodes = DB::table('mp_batch_episode_generation_details')
  11696. ->where('anime_id', $anime_id)
  11697. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11698. ->pluck('episode_number')
  11699. ->unique()
  11700. ->sort()
  11701. ->values()
  11702. ->toArray();
  11703. $duplicatedAnimeEpisodes = DB::table('mp_anime_episodes')
  11704. ->where('anime_id', $anime_id)
  11705. ->where('is_default', 1)
  11706. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11707. ->pluck('episode_number')
  11708. ->unique()
  11709. ->sort()
  11710. ->values()
  11711. ->toArray();
  11712. if (!empty($duplicatedBatchEpisodes) || !empty($duplicatedAnimeEpisodes)) {
  11713. $duplicateMessages = [];
  11714. if (!empty($duplicatedBatchEpisodes)) {
  11715. $duplicateMessages[] = '批量生成任务中已存在第' . implode('、', $duplicatedBatchEpisodes) . '集';
  11716. }
  11717. if (!empty($duplicatedAnimeEpisodes)) {
  11718. $duplicateMessages[] = '剧集中已存在第' . implode('、', $duplicatedAnimeEpisodes) . '集';
  11719. }
  11720. Utils::throwError('20003:' . implode(';', $duplicateMessages) . ',请勿重复创建');
  11721. }
  11722. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  11723. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  11724. ->where('anime_id', $anime_id)
  11725. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11726. ->whereIn('status', ['pending', 'processing', 'completed'])
  11727. ->count();
  11728. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  11729. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  11730. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  11731. if ($needEpisodeCount > 0) {
  11732. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints() * $needEpisodeCount, $uid);
  11733. }
  11734. $now = date('Y-m-d H:i:s');
  11735. $createdTasks = [];
  11736. $skippedTasks = [];
  11737. // 为每一集创建详情记录
  11738. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  11739. // 检查是否已有该集的任务记录
  11740. $existingTask = DB::table('mp_batch_episode_generation_details')
  11741. ->where('anime_id', $anime_id)
  11742. ->where('episode_number', $episodeNumber)
  11743. ->first();
  11744. if ($existingTask) {
  11745. // 如果已存在且未完成,跳过
  11746. if (in_array($existingTask->status, ['pending', 'processing'])) {
  11747. $skippedTasks[] = $episodeNumber;
  11748. continue;
  11749. }
  11750. // 如果是失败状态,可以重新创建(删除旧记录)
  11751. if ($existingTask->status === 'failed') {
  11752. DB::table('mp_batch_episode_generation_details')
  11753. ->where('id', $existingTask->id)
  11754. ->delete();
  11755. }
  11756. // 如果是已完成状态,也跳过
  11757. if ($existingTask->status === 'completed') {
  11758. $skippedTasks[] = $episodeNumber;
  11759. continue;
  11760. }
  11761. }
  11762. // 准备任务数据
  11763. $taskData = [
  11764. 'anime_id' => $anime_id,
  11765. 'uid' => $uid,
  11766. 'cpid' => $cpid,
  11767. 'episode_number' => $episodeNumber,
  11768. 'status' => 'pending',
  11769. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  11770. 'retry_count' => 0,
  11771. 'created_at' => $now,
  11772. 'updated_at' => $now
  11773. ];
  11774. // 创建任务记录
  11775. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  11776. if ($taskId) {
  11777. $createdTasks[] = $episodeNumber;
  11778. }
  11779. }
  11780. if (empty($createdTasks)) {
  11781. if (!empty($skippedTasks)) {
  11782. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  11783. } else {
  11784. Utils::throwError('20003:创建批量生成任务失败');
  11785. }
  11786. }
  11787. // 创建/复用任务中心记录(按入参+type验重,避免重复任务)
  11788. $taskCenterId = $this->createBatchGenerateEpisodesTaskCenter(
  11789. $uid,
  11790. $cpid,
  11791. $anime_id,
  11792. $generate_episode_number,
  11793. $startEpisodeNumber,
  11794. $endEpisodeNumber
  11795. );
  11796. return [
  11797. 'anime_id' => $anime_id,
  11798. 'start_episode' => $startEpisodeNumber,
  11799. 'end_episode' => $endEpisodeNumber,
  11800. 'total_episodes' => $totalEpisodeCount,
  11801. 'created_episodes' => $createdTasks,
  11802. 'skipped_episodes' => $skippedTasks,
  11803. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$totalEpisodeCount}集。" .
  11804. "已创建: " . implode(',', $createdTasks) .
  11805. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : ""),
  11806. 'task_center_id' => $taskCenterId
  11807. ];
  11808. }
  11809. /**
  11810. * 根据入参创建或复用批量生成分集的任务中心记录
  11811. *
  11812. * 以入参(anime_id、generate_episode_number)计算 md5 存入 params_md5 字段用于验重:
  11813. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  11814. * 避免生成重复任务;唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复。
  11815. *
  11816. * @param int|string $uid
  11817. * @param int|string $cpid
  11818. * @param int|string $anime_id
  11819. * @param int $generate_episode_number
  11820. * @param int $startEpisodeNumber
  11821. * @param int $endEpisodeNumber
  11822. * @return int 任务中心ID
  11823. */
  11824. private function createBatchGenerateEpisodesTaskCenter($uid, $cpid, $anime_id, $generate_episode_number, $startEpisodeNumber, $endEpisodeNumber) {
  11825. $params = [
  11826. 'anime_id' => (int)$anime_id,
  11827. 'generate_episode_number' => (int)$generate_episode_number,
  11828. 'start_episode' => (int)$startEpisodeNumber,
  11829. 'end_episode' => (int)$endEpisodeNumber,
  11830. ];
  11831. // 验重键:入参 + 生成范围(anime_id + generate_episode_number + start/end)+ task_type
  11832. $paramsMd5 = md5(json_encode([
  11833. 'anime_id' => (int)$anime_id,
  11834. 'generate_episode_number' => (int)$generate_episode_number,
  11835. 'start_episode' => (int)$startEpisodeNumber,
  11836. 'end_episode' => (int)$endEpisodeNumber,
  11837. ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  11838. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  11839. $existing = DB::table('mp_task_center')
  11840. ->where('uid', (int)$uid)
  11841. ->where('cpid', (int)$cpid)
  11842. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11843. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  11844. ->where('params_md5', $paramsMd5)
  11845. ->orderBy('id', 'desc')
  11846. ->first();
  11847. if ($existing) {
  11848. dLog('deepseek')->info('复用批量生成分集任务中心记录,避免重复任务', [
  11849. 'anime_id' => $anime_id,
  11850. 'task_center_id' => $existing->id,
  11851. 'params_md5' => $paramsMd5,
  11852. ]);
  11853. return (int)$existing->id;
  11854. }
  11855. $now = date('Y-m-d H:i:s');
  11856. DB::table('mp_task_center')->insertOrIgnore([
  11857. 'uid' => (int)$uid,
  11858. 'cpid' => (int)$cpid,
  11859. 'task_type' => MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES,
  11860. 'title' => '批量生成分集',
  11861. 'ref_task_id' => 0,
  11862. 'status' => MpTaskCenter::STATUS_PROCESSING,
  11863. 'result' => null,
  11864. 'error_message' => null,
  11865. 'prompt' => null,
  11866. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  11867. 'params_md5' => $paramsMd5,
  11868. 'created_at' => $now,
  11869. 'updated_at' => $now,
  11870. ]);
  11871. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  11872. $taskId = (int)DB::table('mp_task_center')
  11873. ->where('uid', (int)$uid)
  11874. ->where('cpid', (int)$cpid)
  11875. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11876. ->where('params_md5', $paramsMd5)
  11877. ->orderBy('id', 'desc')
  11878. ->value('id');
  11879. dLog('deepseek')->info('创建批量生成分集任务中心记录', [
  11880. 'anime_id' => $anime_id,
  11881. 'task_center_id' => $taskId,
  11882. 'params_md5' => $paramsMd5,
  11883. ]);
  11884. return $taskId;
  11885. }
  11886. /**
  11887. * 批量生成分集全部结束后,更新任务中心记录的状态和结果
  11888. *
  11889. * 由批量生成 worker 子进程在退出前调用。分集详情任务的状态会在多处更新
  11890. * (completed/failed/pending/processing),这里只在所有详情任务均已结束时
  11891. * 统一汇总更新,避免在每个更新点重复处理。
  11892. *
  11893. * @param int|string $animeId
  11894. * @return int 更新的任务中心记录数
  11895. */
  11896. public function finishBatchGenerateEpisodesTaskCenters($animeId) {
  11897. $animeId = (int)$animeId;
  11898. $updated = 0;
  11899. // 该 anime 是否还有未结束的详情任务
  11900. $hasUnfinished = DB::table('mp_batch_episode_generation_details')
  11901. ->where('anime_id', $animeId)
  11902. ->whereIn('status', ['pending', 'processing'])
  11903. ->exists();
  11904. // 扫描该 anime 相关的未完成任务中心记录
  11905. $tasks = DB::table('mp_task_center')
  11906. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11907. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  11908. ->orderBy('id', 'desc')
  11909. ->limit(500)
  11910. ->get();
  11911. if ($hasUnfinished && !$tasks) {
  11912. return 0;
  11913. }
  11914. foreach ($tasks as $task) {
  11915. try {
  11916. $taskParams = json_decode((string)$task->params, true);
  11917. if (!is_array($taskParams) || (int)($taskParams['anime_id'] ?? 0) !== $animeId) {
  11918. continue;
  11919. }
  11920. $startEpisode = (int)($taskParams['start_episode'] ?? 0);
  11921. $endEpisode = (int)($taskParams['end_episode'] ?? 0);
  11922. if ($startEpisode < 1 || $endEpisode < $startEpisode) {
  11923. continue;
  11924. }
  11925. $details = DB::table('mp_batch_episode_generation_details')
  11926. ->where('anime_id', $animeId)
  11927. ->whereBetween('episode_number', [$startEpisode, $endEpisode])
  11928. ->get();
  11929. // 该批次范围内存在缺失记录,等待下一次检查
  11930. if ($details->isEmpty() || $details->count() < ($endEpisode - $startEpisode + 1)) {
  11931. continue;
  11932. }
  11933. $completedEpisodes = [];
  11934. $failedEpisodes = [];
  11935. $allFinished = true;
  11936. foreach ($details as $detail) {
  11937. if ($detail->status === 'completed') {
  11938. $completedEpisodes[] = $detail->episode_number;
  11939. } elseif ($detail->status === 'failed') {
  11940. $failedEpisodes[] = [
  11941. 'episode_number' => $detail->episode_number,
  11942. 'error_message' => $detail->error_message ?? '',
  11943. ];
  11944. } else {
  11945. // pending/processing(防御处理,正常不会走到)
  11946. $allFinished = false;
  11947. break;
  11948. }
  11949. }
  11950. if (!$allFinished) {
  11951. continue;
  11952. }
  11953. $result = json_encode([
  11954. 'anime_id' => $animeId,
  11955. 'start_episode' => $startEpisode,
  11956. 'end_episode' => $endEpisode,
  11957. 'total_episodes' => count($details),
  11958. 'completed_count' => count($completedEpisodes),
  11959. 'failed_count' => count($failedEpisodes),
  11960. 'completed_episodes' => $completedEpisodes,
  11961. 'failed_episodes' => $failedEpisodes,
  11962. ], JSON_UNESCAPED_UNICODE);
  11963. DB::table('mp_task_center')
  11964. ->where('id', $task->id)
  11965. ->update([
  11966. 'status' => !empty($failedEpisodes) ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  11967. 'result' => $result,
  11968. 'error_message' => !empty($failedEpisodes) ? ('有 ' . count($failedEpisodes) . ' 集生成失败') : null,
  11969. 'updated_at' => date('Y-m-d H:i:s'),
  11970. ]);
  11971. $updated++;
  11972. dLog('command')->info('批量生成分集任务已完成,更新任务中心', [
  11973. 'task_center_id' => $task->id,
  11974. 'anime_id' => $animeId,
  11975. 'start_episode' => $startEpisode,
  11976. 'end_episode' => $endEpisode,
  11977. ]);
  11978. } catch (\Exception $e) {
  11979. dLog('command')->error('更新批量生成分集任务中心异常', [
  11980. 'task_center_id' => $task->id,
  11981. 'anime_id' => $animeId,
  11982. 'error' => $e->getMessage(),
  11983. ]);
  11984. }
  11985. }
  11986. return $updated;
  11987. }
  11988. /**
  11989. * 获取批量生成任务状态
  11990. *
  11991. * @param array $data 请求数据
  11992. * @return array 任务状态信息
  11993. */
  11994. public function getBatchGenerationTaskStatus($data) {
  11995. $anime_id = getProp($data, 'anime_id');
  11996. if (!$anime_id) {
  11997. Utils::throwError('20003:anime_id参数缺失');
  11998. }
  11999. // 获取该anime的所有任务
  12000. $tasks = DB::table('mp_batch_episode_generation_details')
  12001. ->where('anime_id', $anime_id)
  12002. ->orderBy('episode_number')
  12003. ->get()
  12004. ->map(function($item) {
  12005. return [
  12006. 'id' => $item->id,
  12007. 'episode_number' => $item->episode_number,
  12008. 'status' => $item->status,
  12009. 'error_message' => $item->error_message,
  12010. 'retry_count' => $item->retry_count,
  12011. 'created_at' => $item->created_at,
  12012. 'updated_at' => $item->updated_at,
  12013. 'completed_at' => $item->completed_at
  12014. ];
  12015. })
  12016. ->toArray();
  12017. if (empty($tasks)) {
  12018. Utils::throwError('20003:该剧集没有批量生成任务');
  12019. }
  12020. // 统计各状态数量
  12021. $totalCount = count($tasks);
  12022. $pendingCount = 0;
  12023. $processingCount = 0;
  12024. $completedCount = 0;
  12025. $failedCount = 0;
  12026. $failed_episodes = [];
  12027. foreach ($tasks as $task) {
  12028. switch ($task['status']) {
  12029. case 'pending':
  12030. $pendingCount++;
  12031. break;
  12032. case 'processing':
  12033. $processingCount++;
  12034. break;
  12035. case 'completed':
  12036. $completedCount++;
  12037. break;
  12038. case 'failed':
  12039. $failedCount++;
  12040. // 组装失败分集对象(新对象):分集序号、错误原因
  12041. $failed_episodes[] = [
  12042. 'episode_number' => $task['episode_number'],
  12043. 'error_message' => $task['error_message'] ?? ''
  12044. ];
  12045. break;
  12046. }
  12047. }
  12048. // 计算进度百分比
  12049. $progress = 0;
  12050. if ($totalCount > 0) {
  12051. $progress = round(($completedCount / $totalCount) * 100, 2);
  12052. }
  12053. // 判断整体状态
  12054. $overallStatus = 'processing';
  12055. if ($completedCount === $totalCount) {
  12056. $overallStatus = 'completed';
  12057. } elseif ($pendingCount === $totalCount) {
  12058. $overallStatus = 'pending';
  12059. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  12060. $overallStatus = 'failed';
  12061. }
  12062. return [
  12063. 'anime_id' => $anime_id,
  12064. 'total_episodes' => $totalCount,
  12065. 'pending_count' => $pendingCount,
  12066. 'processing_count' => $processingCount,
  12067. 'completed_count' => $completedCount,
  12068. 'failed_count' => $failedCount,
  12069. 'progress' => $progress,
  12070. 'overall_status' => $overallStatus,
  12071. 'failed_episodes' => $failed_episodes,
  12072. 'tasks' => $tasks
  12073. ];
  12074. }
  12075. /**
  12076. * 将生成内容中不在强制列表中的资源合并进强制列表
  12077. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  12078. *
  12079. * @param array $generated 生成内容中的资源列表
  12080. * @param array $forced 强制资源列表(key为资源名称)
  12081. * @param string $type 资源类型:role、scene、prop
  12082. * @return array
  12083. */
  12084. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  12085. {
  12086. foreach ($generated as $item) {
  12087. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  12088. if ($name === null || $name === '') {
  12089. continue;
  12090. }
  12091. if ($name === '旁白') {
  12092. continue;
  12093. }
  12094. if (!isset($forced[$name])) {
  12095. $forced[$name] = $item;
  12096. }
  12097. }
  12098. return $forced;
  12099. }
  12100. /**
  12101. * 智能匹配并替换主体和场景名称
  12102. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  12103. *
  12104. * @param array $episode_arr 解析后的剧集数据
  12105. * @param array $extra_roles 强制主体设定(key为主体名称)
  12106. * @param array $extra_scenes 强制场景设定(key为场景名称)
  12107. * @return array 替换后的剧集数据
  12108. */
  12109. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  12110. $replaced_count = 0;
  12111. // 1. 处理主体列表
  12112. if (!empty($episode_arr['roles'])) {
  12113. foreach ($episode_arr['roles'] as &$role) {
  12114. $generated_role_name = $role['role'] ?? '';
  12115. // 跳过旁白
  12116. if ($generated_role_name === '旁白') {
  12117. continue;
  12118. }
  12119. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  12120. if (!isset($extra_roles[$generated_role_name])) {
  12121. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  12122. if ($matched_role) {
  12123. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  12124. $role['role'] = $matched_role;
  12125. $replaced_count++;
  12126. }
  12127. }
  12128. }
  12129. }
  12130. // 2. 处理场景列表
  12131. if (!empty($episode_arr['scenes'])) {
  12132. foreach ($episode_arr['scenes'] as &$scene) {
  12133. $generated_scene_name = $scene['scene'] ?? '';
  12134. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  12135. if (!isset($extra_scenes[$generated_scene_name])) {
  12136. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  12137. if ($matched_scene) {
  12138. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  12139. $scene['scene'] = $matched_scene;
  12140. $replaced_count++;
  12141. }
  12142. }
  12143. }
  12144. }
  12145. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  12146. if (!empty($episode_arr['acts'])) {
  12147. foreach ($episode_arr['acts'] as &$act) {
  12148. if (!empty($act['segments'])) {
  12149. foreach ($act['segments'] as &$segment) {
  12150. if (!empty($segment['segment_content'])) {
  12151. $original_content = $segment['segment_content'];
  12152. $replaced_content = $original_content;
  12153. // 替换场景名 - 在文本中查找并替换
  12154. foreach (array_keys($extra_scenes) as $full_scene_name) {
  12155. // 尝试找到可能的短名称
  12156. $potential_short_names = [];
  12157. // 提取场景名的主要部分(冒号之前)
  12158. if (mb_strpos($full_scene_name, ':') !== false) {
  12159. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  12160. $potential_short_names[] = $short_name;
  12161. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  12162. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  12163. $potential_short_names[] = $short_name;
  12164. }
  12165. // 替换场景字段中的短名称
  12166. foreach ($potential_short_names as $short_name) {
  12167. if ($short_name !== $full_scene_name) {
  12168. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  12169. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  12170. if ($new_content !== $replaced_content) {
  12171. $replaced_content = $new_content;
  12172. $replaced_count++;
  12173. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  12174. }
  12175. }
  12176. }
  12177. }
  12178. // 替换配音角色名(跳过旁白)
  12179. foreach (array_keys($extra_roles) as $full_role_name) {
  12180. if ($full_role_name === '旁白') {
  12181. continue;
  12182. }
  12183. // 尝试找到可能的短名称
  12184. $potential_short_names = [];
  12185. // 提取角色名的主要部分(短横线之前)
  12186. if (mb_strpos($full_role_name, '-') !== false) {
  12187. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  12188. $potential_short_names[] = $short_name;
  12189. }
  12190. // 替换配音台词中的短名称
  12191. foreach ($potential_short_names as $short_name) {
  12192. if ($short_name !== $full_role_name) {
  12193. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  12194. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  12195. if ($new_content !== $replaced_content) {
  12196. $replaced_content = $new_content;
  12197. $replaced_count++;
  12198. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  12199. }
  12200. }
  12201. }
  12202. }
  12203. // 如果有替换,更新segment_content
  12204. if ($replaced_content !== $original_content) {
  12205. $segment['segment_content'] = $replaced_content;
  12206. }
  12207. }
  12208. }
  12209. }
  12210. }
  12211. }
  12212. if ($replaced_count > 0) {
  12213. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  12214. 'replaced_count' => $replaced_count
  12215. ]);
  12216. }
  12217. return $episode_arr;
  12218. }
  12219. /**
  12220. * 查找匹配的名称
  12221. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  12222. *
  12223. * @param string $generated_name 生成的名称
  12224. * @param array $expected_names 预期的名称列表
  12225. * @return string|null 匹配到的名称,如果没有匹配则返回null
  12226. */
  12227. private function findMatchingName($generated_name, $expected_names) {
  12228. if (empty($generated_name)) {
  12229. return null;
  12230. }
  12231. // 尝试精确匹配
  12232. if (in_array($generated_name, $expected_names)) {
  12233. return $generated_name;
  12234. }
  12235. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  12236. foreach ($expected_names as $expected_name) {
  12237. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  12238. if (mb_strpos($expected_name, $generated_name) === 0) {
  12239. return $expected_name;
  12240. }
  12241. }
  12242. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  12243. // 这样可以处理一些变体,但优先级较低
  12244. foreach ($expected_names as $expected_name) {
  12245. if (mb_strpos($expected_name, $generated_name) !== false) {
  12246. return $expected_name;
  12247. }
  12248. }
  12249. return null;
  12250. }
  12251. /**
  12252. * 重新生成分段剧本
  12253. * @param array $data 包含以下字段:
  12254. * - prompt: string|null 用户修改要求(可选)
  12255. * - template_id: int|null 提示词模板ID(可选)
  12256. * - act_id: int|null 单个片段ID(与episode_id二选一)
  12257. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  12258. * @return array 返回生成结果
  12259. */
  12260. public function regenerateSegmentScript($data) {
  12261. $uid = Site::getUid();
  12262. $prompt = trim((string)getProp($data, 'prompt', ''));
  12263. $template_id = getProp($data, 'template_id', 0);
  12264. $act_id = getProp($data, 'act_id', 0);
  12265. $episode_id = getProp($data, 'episode_id', 0);
  12266. $check_mode = (int)getProp($data, 'check_mode', 0); // 1=预览确认模式(仅 act_id 模式生效,不落库,返回 editAct 入参)
  12267. // 单片段模式:act_id 可以是数据库真实ID(数字)或预览生成的虚拟ID(字符串),非空即单片段模式
  12268. $isActIdMode = !empty($act_id);
  12269. // 验证:prompt和template_id至少提供一个
  12270. if (empty($prompt) && empty($template_id)) {
  12271. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  12272. }
  12273. // 验证:act_id和episode_id二选一
  12274. if (empty($act_id) && empty($episode_id)) {
  12275. Utils::throwError('20003:请提供片段ID或剧集ID');
  12276. }
  12277. if (!empty($act_id) && !empty($episode_id)) {
  12278. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  12279. }
  12280. // 积分余额预检:act_id 单片段模式按 normal 档,episode_id 剧集模式按 special 档
  12281. $chargeType = $isActIdMode ? 'normal' : 'special';
  12282. if ($isActIdMode) {
  12283. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', $chargeType), $uid);
  12284. } else {
  12285. $is_generated = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('is_generated');
  12286. if ($is_generated) Utils::throwError('20003:该分集已不支持重新生成片段,请创建副本后重试!');
  12287. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', $chargeType), $uid);
  12288. }
  12289. // 如果提供了template_id,获取模板提示词
  12290. $template_prompt = '';
  12291. if ($template_id > 0) {
  12292. $template = DB::table('mp_prompt_templates')
  12293. ->where('id', $template_id)
  12294. ->where('is_deleted', 0)
  12295. ->first();
  12296. if (!$template) {
  12297. Utils::throwError('20003:提示词模板不存在或已删除');
  12298. }
  12299. $template_prompt = $template->template_prompt ?? '';
  12300. }
  12301. // 合并用户提示词和模板提示词(模板提示词与用户输入基本一致时只保留一个,避免重复提示词)
  12302. $final_prompt = '';
  12303. if (!empty($template_prompt)) {
  12304. $trimmedPrompt = trim((string)$prompt);
  12305. if ($trimmedPrompt !== '' && mb_strtolower($trimmedPrompt) === mb_strtolower(trim($template_prompt))) {
  12306. $final_prompt = $template_prompt;
  12307. } elseif (!empty($prompt)) {
  12308. $final_prompt = $template_prompt . "\n\n补充要求:" . $prompt;
  12309. } else {
  12310. $final_prompt = $template_prompt;
  12311. }
  12312. } else {
  12313. $final_prompt = $prompt;
  12314. }
  12315. // 获取需要重新生成的内容参考
  12316. $reference_content = '';
  12317. $target_episode_id = 0;
  12318. $target_anime_id = 0;
  12319. $target_episode_number = 0;
  12320. if ($isActIdMode) {
  12321. // 单个片段模式:获取该片段的内容
  12322. $segment = DB::table('mp_episode_segments')
  12323. ->where('id', $act_id)
  12324. ->first();
  12325. // 数据库不存在时,尝试从预览虚拟 act_id 保存的 redis 数据中恢复
  12326. if (!$segment) {
  12327. $previewData = Redis::get($this->buildActPreviewKey($act_id));
  12328. if ($previewData) {
  12329. $previewData = json_decode($previewData, true);
  12330. $segment = (object)[
  12331. 'anime_id' => getProp($previewData, 'anime_id'),
  12332. 'episode_id' => getProp($previewData, 'episode_id'),
  12333. 'episode_number' => getProp($previewData, 'episode_number'),
  12334. 'act_number' => getProp($previewData, 'act_number'),
  12335. 'act_duration' => getProp($previewData, 'act_duration'),
  12336. 'act_content' => getProp($previewData, 'act_content'),
  12337. ];
  12338. }
  12339. }
  12340. if (!$segment) {
  12341. Utils::throwError('20003:片段不存在');
  12342. }
  12343. $target_episode_id = $segment->episode_id;
  12344. $target_anime_id = $segment->anime_id;
  12345. $target_episode_number = $segment->episode_number;
  12346. $reference_content = $segment->act_content ?? '';
  12347. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  12348. } else {
  12349. // 整个剧集模式:获取所有片段的内容
  12350. $segments = DB::table('mp_episode_segments')
  12351. ->where('episode_id', $episode_id)
  12352. ->orderBy('act_number')
  12353. ->get();
  12354. if ($segments->isEmpty()) {
  12355. Utils::throwError('20003:该剧集没有片段数据');
  12356. }
  12357. $target_episode_id = $episode_id;
  12358. $target_anime_id = $segments[0]->anime_id;
  12359. $target_episode_number = $segments[0]->episode_number;
  12360. // 拼接所有片段内容,保留格式用于AI理解
  12361. $act_contents = [];
  12362. foreach ($segments as $seg) {
  12363. $act_number = $seg->act_number;
  12364. $act_content = $seg->act_content ?? '';
  12365. if (!empty($act_content)) {
  12366. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  12367. }
  12368. }
  12369. $reference_content = implode("\n\n", $act_contents);
  12370. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  12371. if ($episode_content) {
  12372. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【原分段剧本内容】\n{$reference_content}";
  12373. //$reference_content = "\n\n【本集原始内容】\n{$episode_content}";
  12374. }else {
  12375. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  12376. }
  12377. }
  12378. if (empty($reference_content)) {
  12379. Utils::throwError('20003:没有可参考的片段内容');
  12380. }
  12381. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  12382. $episode = DB::table('mp_anime_episodes')
  12383. ->where('id', $target_episode_id)
  12384. ->first();
  12385. if (!$episode) {
  12386. Utils::throwError('20003:剧集不存在');
  12387. }
  12388. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  12389. $anime_script_id = getProp($anime, 'script_id');
  12390. $intro = $episode->intro ?? '';
  12391. $art_style = $episode->art_style ?? '';
  12392. $roles = json_decode($episode->roles ?? '[]', true);
  12393. $scenes = json_decode($episode->scenes ?? '[]', true);
  12394. $props = json_decode($episode->props ?? '[]', true);
  12395. // 构建提示词中的主体列表和场景列表参考
  12396. $roles_ref = '';
  12397. if (!empty($roles) && is_array($roles)) {
  12398. $roles_list = [];
  12399. foreach ($roles as $role) {
  12400. $role_name = getProp($role, 'role', '');
  12401. $role_desc = getProp($role, 'description', '');
  12402. $pic_prompt = getProp($role, 'pic_prompt', '');
  12403. $voice_prompt = getProp($role, 'voice_prompt', '');
  12404. if (!empty($role_name)) {
  12405. $role_line = $role_name;
  12406. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  12407. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  12408. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  12409. $roles_list[] = $role_line;
  12410. }
  12411. }
  12412. if (!empty($roles_list)) {
  12413. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  12414. }
  12415. }
  12416. $scenes_ref = '';
  12417. if (!empty($scenes) && is_array($scenes)) {
  12418. $scenes_list = [];
  12419. foreach ($scenes as $scene) {
  12420. $scene_name = getProp($scene, 'scene', '');
  12421. $scene_desc = getProp($scene, 'description', '');
  12422. $pic_prompt = getProp($scene, 'pic_prompt', '');
  12423. if (!empty($scene_name)) {
  12424. $scene_line = $scene_name;
  12425. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  12426. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  12427. $scenes_list[] = $scene_line;
  12428. }
  12429. }
  12430. if (!empty($scenes_list)) {
  12431. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  12432. }
  12433. }
  12434. $props_ref = '';
  12435. if (!empty($props) && is_array($props)) {
  12436. $props_list = [];
  12437. foreach ($props as $prop) {
  12438. $prop_name = getProp($prop, 'prop', '');
  12439. $prop_desc = getProp($prop, 'description', '');
  12440. $pic_prompt = getProp($prop, 'pic_prompt', '');
  12441. if (!empty($prop_name)) {
  12442. $prop_line = $prop_name;
  12443. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  12444. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  12445. $props_list[] = $prop_line;
  12446. }
  12447. }
  12448. if (!empty($props_list)) {
  12449. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  12450. }
  12451. }
  12452. // 构建美术风格参考
  12453. $art_style_ref = '';
  12454. if (!empty($art_style)) {
  12455. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  12456. }
  12457. // 构建内容简介参考
  12458. $intro_ref = '';
  12459. if (!empty($intro)) {
  12460. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  12461. }
  12462. // 构建完整的AI提示词
  12463. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  12464. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  12465. $user_prompt .= $intro_ref;
  12466. $user_prompt .= $art_style_ref;
  12467. $user_prompt .= $reference_content;
  12468. $user_prompt .= "\n\n【生成要求】\n- 请以【原分段剧本内容】为蓝本,保留剧情脉络、角色、场景与分段结构,但必须围绕【用户要求】对相关片段进行实质性修改;若【用户要求】未指定具体修改点,也需对画面、运镜、台词等描述进行改写,禁止整段原样复制。\n";
  12469. // $user_prompt .= $roles_ref;
  12470. // $user_prompt .= $scenes_ref;
  12471. // 输出格式铁律(用户消息侧再次强制,避免模型自由发挥)
  12472. $user_prompt .= "\n\n【输出格式铁律-必须严格遵守】\n";
  12473. if ($isActIdMode) {
  12474. $user_prompt .= "- 请直接以“##片段1”开头,紧跟“时长:X s”行,然后输出本片段的完整分镜内容(分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效),分镜从1开始连续编号。\n";
  12475. $user_prompt .= "- 只允许根据【原分段剧本内容】生成一个片段(即“##片段1”),禁止生成多个片段。\n";
  12476. } else {
  12477. $user_prompt .= "- 请以“###分段剧本”开头,依次输出“片段数量:N”、“旁白音色:...”,然后按“##片段N”逐段输出,每段必须紧跟“时长:X s”行,再输出该片段的完整分镜内容(分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效),分镜从1开始连续编号。\n";
  12478. }
  12479. $user_prompt .= "- 缺少“##片段N”标题或“时长:”行即为格式错误;输出前必须检查格式,不得输出其他任何内容。\n";
  12480. $user_prompt .= "- 片段时长必须在4秒到15秒之间(4s≤时长≤15s),超过15秒必须拆分为多个片段,不得输出低于4秒或超过15秒的片段。\n";
  12481. // 整集模式:强制生成与原来一致的片段数量
  12482. if ($episode_id > 0 && isset($segments)) {
  12483. $originSegmentCount = count($segments);
  12484. $user_prompt .= "- 本集原有{$originSegmentCount}个片段,必须严格生成{$originSegmentCount}个片段(##片段1 到 ##片段{$originSegmentCount}),不得多不得少。\n";
  12485. }
  12486. $system_prompt = "\n\n【输出格式铁律-最高优先级】\n";
  12487. if ($isActIdMode) {
  12488. $system_prompt .= "- 直接以“##片段1”开头,紧跟“时长:X s”行,然后输出本片段分镜内容\n";
  12489. $system_prompt .= "- 只允许根据【原分段剧本内容】生成一个片段(即“##片段1”),禁止生成多个片段。\n";
  12490. } else {
  12491. $system_prompt .= "- 以“###分段剧本”开头,输出“片段数量:N”、“旁白音色:...”\n";
  12492. $system_prompt .= "- 然后按“##片段N”逐段输出,每段紧跟“时长:X s”行\n";
  12493. }
  12494. $system_prompt .= "- 每个片段必须严格以“##片段N”开头(N从1开始连续),并且必须包含“时长:X s”行,缺少即为格式错误\n";
  12495. $system_prompt .= "- 片段时长必须在4~15秒之间(4s≤时长≤15s),超过15秒必须拆分为多个片段,禁止输出低于4秒或超过15秒的片段\n";
  12496. $system_prompt .= "- 输出前检查:若缺少##片段N标题或时长行,视为输出无效,必须修正后输出\n\n";
  12497. $system_prompt .= "【强制要求】\n";
  12498. // $system_prompt .= "- 请严格参考【本集原始内容】或【原分段剧本内容】进行本次生成,注意新生成的分段剧本内容一定不要跟【原分段剧本内容】一致,要进行一定程度调整\n";
  12499. $system_prompt .= "- 【重要】必须参考【本集原始内容】与【原分段剧本内容】中的剧情脉络、角色、场景、道具和分段结构,但严禁原样复制或几乎照抄原文;必须围绕【用户要求】对相关内容进行实质性修改,若生成结果与【原分段剧本内容】完全一致或未体现用户要求,视为生成失败\n";
  12500. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:\n";
  12501. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)\n";
  12502. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  12503. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  12504. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  12505. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  12506. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  12507. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  12508. $system_prompt .= "- 【重要】每个片段必须以“##片段N”开头(N为序号),并且必须包含“时长:X s”行,缺少片段标题或时长视为格式错误\n";
  12509. // 按模式构造强制输出格式:只传 act_id(单片段)时不需要 ###分段剧本/片段数量/旁白音色;传 episode_id(整集)时需要完整格式
  12510. $segmentHeader = '';
  12511. if ($episode_id > 0) {
  12512. $segmentHeader = "###分段剧本\n片段数量:8\n旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。\n\n";
  12513. }
  12514. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:\n" . $segmentHeader . "##片段1\n时长:12s\n分镜1\n出场角色:刀疤脸\n场景:边境小镇街道\n出场道具:酒杯-高脚杯\n画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。\n运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。\n配音台词:\n背景音效:\n\n分镜2\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。\n运镜:缓慢横移,掠过阴影中瑟缩的食客。\n配音台词:\n背景音效:\n\n分镜3\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。\n运镜:从中景推向令牌特写。\n配音台词:\n背景音效:\n\n分镜4\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。\n运镜:极速推向酒水溅起的瞬间。\n配音台词:\n背景音效:\n\n分镜5\n出场角色:刀疤脸\n场景:悦来酒馆\n出场道具:酒杯-高脚杯\n画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。\n运镜:固定机位,利用倾斜构图制造压迫感。\n配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?\n背景音效:";
  12515. // 获取模型配置
  12516. $model = getProp($data, 'model');
  12517. if (!$model) {
  12518. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  12519. }
  12520. // 验证模型是否在可用模型表中
  12521. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  12522. $model = 'deepseek-v4-pro';
  12523. }
  12524. // 模型兼容性处理
  12525. $thinkingMode = 'disabled';
  12526. $reasoningEffort = 'high';
  12527. if ($model === 'deepseek-chat') {
  12528. $model = 'deepseek-v4-flash';
  12529. $thinkingMode = 'disabled';
  12530. } elseif ($model === 'deepseek-reasoner') {
  12531. $model = 'deepseek-v4-flash';
  12532. $thinkingMode = 'enabled';
  12533. }
  12534. // 构建消息
  12535. $messages = [
  12536. [
  12537. 'role' => 'system',
  12538. 'content' => $system_prompt
  12539. ],
  12540. [
  12541. 'role' => 'user',
  12542. 'content' => $user_prompt
  12543. ]
  12544. ];
  12545. // dd($messages);
  12546. // 构建请求参数
  12547. $post_data = [
  12548. 'model' => $model,
  12549. 'messages' => $messages,
  12550. 'temperature' => 1.4,
  12551. 'frequency_penalty' => 0.3,
  12552. 'presence_penalty' => 0,
  12553. 'response_format' => ['type' => 'text'],
  12554. 'thinking' => ['type' => $thinkingMode],
  12555. 'stream' => false // 非流式输出
  12556. ];
  12557. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  12558. // 调用AI生成新的分段剧本
  12559. try {
  12560. $fullContent = '';
  12561. $usage = [];
  12562. // 根据模型类型选择调用方法
  12563. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  12564. if (is_array($chatResult)) {
  12565. $fullContent = $chatResult['fullContent'] ?? '';
  12566. $usage = $chatResult['usage'] ?? [];
  12567. }
  12568. $generated_content = $fullContent;
  12569. // 归一化"场景:"标签换行格式:场景:\n场景名\n => 场景:场景名\n,保证场景字段为一行
  12570. $generated_content = preg_replace('/场景[::]\s*\n\s*([^\n]+)/u', '场景:$1', $generated_content);
  12571. if (empty($generated_content)) {
  12572. Utils::throwError('20003:AI生成内容为空,请重试');
  12573. }
  12574. dLog('deepseek')->info('regenerateSegmentScript AI生成内容', [
  12575. 'act_id' => $act_id,
  12576. 'episode_id' => $episode_id,
  12577. 'content_length' => mb_strlen($generated_content),
  12578. 'content_head' => mb_substr($generated_content, 0, 500),
  12579. 'content_tail' => mb_substr($generated_content, -200),
  12580. ]);
  12581. // 解析生成的内容 - 按片段分割
  12582. $parsed_segments = [];
  12583. // 先在开头添加换行符,确保第1片段也能被正确分割
  12584. $normalizedText = "\n" . $generated_content;
  12585. $parts = preg_split('/\n\s*##/', $normalizedText);
  12586. foreach ($parts as $part) {
  12587. $part = trim($part);
  12588. if (empty($part)) continue;
  12589. // 匹配"片段X"格式
  12590. if (!preg_match('/^片段\d+/', $part)) {
  12591. continue;
  12592. }
  12593. // 分离标题和内容
  12594. $lines = explode("\n", $part, 2);
  12595. $actTitle = trim($lines[0]);
  12596. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  12597. // 解析标题,提取序号
  12598. $actNumber = 0;
  12599. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  12600. $actNumber = intval($segmentTitleMatch[1]);
  12601. } else {
  12602. $actNumber = count($parsed_segments) + 1;
  12603. }
  12604. // 提取时长(仅保留数字)
  12605. $actDuration = 0;
  12606. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  12607. $actDurationStr = trim($actDurationMatch[1]);
  12608. // 提取数字部分(支持整数和小数)
  12609. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  12610. $actDuration = (float)$numMatch[1];
  12611. }
  12612. }
  12613. // 时长范围约束:4~15秒,超限兜底修正(0=未知按最低4秒)
  12614. if ($actDuration > 15) {
  12615. $actDuration = 15;
  12616. }
  12617. if ($actDuration < 4) {
  12618. $actDuration = 4;
  12619. }
  12620. // 清理act_content:去除时长、旁白音色等非分镜内容行,只保留分镜内容
  12621. $cleaned_content = $this->cleanSegmentContent($actContent);
  12622. $parsed_segments[] = [
  12623. 'act_number' => $actNumber,
  12624. 'act_title' => $actTitle,
  12625. 'act_duration' => $actDuration,
  12626. 'act_content' => $cleaned_content,
  12627. ];
  12628. }
  12629. // 兜底:模型未输出 ##片段N 标题时(如直接输出分镜正文),将整个生成内容作为单个片段解析(act_id 单片段场景)
  12630. if (empty($parsed_segments)) {
  12631. $fallbackContent = $this->cleanSegmentContent($generated_content);
  12632. if ($fallbackContent !== '') {
  12633. $fallbackDuration = 0;
  12634. if (preg_match('/时长[::]\s*([^\n]+)/u', $generated_content, $durationMatch)) {
  12635. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $durationMatch[1], $numMatch)) {
  12636. $fallbackDuration = (float)$numMatch[1];
  12637. }
  12638. }
  12639. // 内容未带时长时,单片段模式沿用原片段的时长
  12640. if ($fallbackDuration <= 0 && $isActIdMode && !empty($segment->act_duration)) {
  12641. $fallbackDuration = (float)$segment->act_duration;
  12642. }
  12643. // 时长范围约束:4~15秒,超限兜底修正(0=未知按最低4秒)
  12644. if ($fallbackDuration > 15) {
  12645. $fallbackDuration = 15;
  12646. }
  12647. if ($fallbackDuration < 4) {
  12648. $fallbackDuration = 4;
  12649. }
  12650. $parsed_segments[] = [
  12651. 'act_number' => 1,
  12652. 'act_title' => '片段1',
  12653. 'act_duration' => $fallbackDuration,
  12654. 'act_content' => $fallbackContent,
  12655. ];
  12656. }
  12657. }
  12658. // act_id 单片段模式:只允许一个片段,多余片段丢弃,仅保留第一个
  12659. if ($isActIdMode && count($parsed_segments) > 1) {
  12660. dLog('deepseek')->info('regenerateSegmentScript act_id 模式仅保留第一个片段', [
  12661. 'act_id' => $act_id,
  12662. 'original_count' => count($parsed_segments),
  12663. ]);
  12664. $parsed_segments = array_slice($parsed_segments, 0, 1);
  12665. }
  12666. dLog('deepseek')->info('regenerateSegmentScript 解析结果', [
  12667. 'act_id' => $act_id,
  12668. 'episode_id' => $episode_id,
  12669. 'segment_count' => count($parsed_segments),
  12670. 'segments' => array_map(function ($seg) {
  12671. return [
  12672. 'act_number' => $seg['act_number'],
  12673. 'act_duration' => $seg['act_duration'],
  12674. 'content_length' => mb_strlen($seg['act_content']),
  12675. ];
  12676. }, $parsed_segments),
  12677. ]);
  12678. if (empty($parsed_segments)) {
  12679. dLog('deepseek')->error('regenerateSegmentScript 无法解析生成的分段剧本', [
  12680. 'act_id' => $act_id,
  12681. 'episode_id' => $episode_id,
  12682. 'content_length' => mb_strlen($generated_content),
  12683. 'content_head' => mb_substr($generated_content, 0, 1000),
  12684. 'content_tail' => mb_substr($generated_content, -300),
  12685. ]);
  12686. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  12687. }
  12688. // 收集所有资产名称(角色、场景、道具)
  12689. $product_names = [];
  12690. // 收集角色名称
  12691. if (!empty($roles) && is_array($roles)) {
  12692. foreach ($roles as $role) {
  12693. $role_name = getProp($role, 'role', '');
  12694. if (!empty($role_name)) {
  12695. $product_names[] = $role_name;
  12696. }
  12697. }
  12698. }
  12699. // 收集场景名称
  12700. if (!empty($scenes) && is_array($scenes)) {
  12701. foreach ($scenes as $scene) {
  12702. $scene_name = getProp($scene, 'scene', '');
  12703. if (!empty($scene_name)) {
  12704. $product_names[] = $scene_name;
  12705. }
  12706. }
  12707. }
  12708. // 收集道具名称
  12709. if (!empty($props) && is_array($props)) {
  12710. foreach ($props as $prop) {
  12711. $prop_name = getProp($prop, 'prop', '');
  12712. if (!empty($prop_name)) {
  12713. $product_names[] = $prop_name;
  12714. }
  12715. }
  12716. }
  12717. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  12718. $product_names = array_unique($product_names);
  12719. usort($product_names, function($a, $b) {
  12720. return mb_strlen($b) - mb_strlen($a);
  12721. });
  12722. // 处理每个片段的 act_show_content
  12723. foreach ($parsed_segments as &$segment) {
  12724. $act_content = getProp($segment, 'act_content', '');
  12725. if (empty($act_content)) {
  12726. $segment['act_show_content'] = '';
  12727. continue;
  12728. }
  12729. $processed_content = $act_content;
  12730. // 统一替换所有资产名称为 {资产名} 格式
  12731. // 使用占位符避免嵌套替换问题
  12732. $placeholder_map = [];
  12733. $placeholder_index = 0;
  12734. foreach ($product_names as $product_name) {
  12735. // 转义特殊字符
  12736. $escaped_product = preg_quote($product_name, '/');
  12737. // 检查是否匹配且未被 {} 包裹
  12738. $processed_content = preg_replace_callback(
  12739. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  12740. function($matches) use (&$placeholder_map, &$placeholder_index) {
  12741. // 使用唯一占位符
  12742. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  12743. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  12744. $placeholder_index++;
  12745. return $placeholder;
  12746. },
  12747. $processed_content
  12748. );
  12749. }
  12750. // 将所有占位符替换回实际内容
  12751. foreach ($placeholder_map as $placeholder => $replacement) {
  12752. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  12753. }
  12754. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  12755. $shot_counter = 0;
  12756. $processed_content = preg_replace_callback(
  12757. // 兼容“【镜头 1】”“【分镜 1】”等分镜/镜头与数字间带空格的情况
  12758. '/【(?:镜头|分镜)\s*(\d+)】/u',
  12759. function($matches) use (&$shot_counter) {
  12760. $shot_counter++;
  12761. return '【镜头' . $shot_counter . '】';
  12762. },
  12763. $processed_content
  12764. );
  12765. // 按动漫画风给 act_show_content 的「画面:[…]」插入画风提示词
  12766. // 总开关 config('anime.act_show_art_style_enabled') 默认关闭,只处理 act_show_content
  12767. $processed_content = ActShowContent::insertArtStylePrompt($processed_content, $target_anime_id);
  12768. $segment['act_show_content'] = $processed_content;
  12769. }
  12770. unset($segment); // 解除引用
  12771. // 保存到数据库
  12772. $now = date('Y-m-d H:i:s');
  12773. $saved_acts = []; // 用于记录保存后的片段信息
  12774. if ($isActIdMode) {
  12775. // 单个片段模式:更新单条记录
  12776. if (count($parsed_segments) > 0) {
  12777. $new_segment = $parsed_segments[0];
  12778. // 预览确认模式(check_mode=1):不落库,组装 editAct 入参返回,由前端确认后调用 editAct 更新
  12779. if ($check_mode === 1) {
  12780. // 单片段预览生成即按 normal 档扣费
  12781. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12782. 'anime_id' => $target_anime_id,
  12783. 'episode_id' => $target_episode_id,
  12784. 'model' => $model,
  12785. 'source' => 'regenerateSegmentScript',
  12786. ], 'normal');
  12787. return [
  12788. 'check_mode' => 1,
  12789. 'act_id' => $act_id,
  12790. 'act_title' => getProp($new_segment, 'act_title', ''),
  12791. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  12792. 'act_content' => getProp($new_segment, 'act_show_content', ''),
  12793. ];
  12794. }
  12795. // 虚拟 act_id 仅用于预览/参考,不允许直接保存到数据库
  12796. if (!is_numeric($act_id)) {
  12797. Utils::throwError('20003:该片段不可直接保存');
  12798. }
  12799. $update_data = [
  12800. 'act_content' => getProp($new_segment, 'act_content', ''),
  12801. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  12802. 'act_title' => getProp($new_segment, 'act_title', ''),
  12803. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  12804. 'updated_at' => $now,
  12805. ];
  12806. DB::table('mp_episode_segments')
  12807. ->where('id', $act_id)
  12808. ->update($update_data);
  12809. // 获取更新后的记录
  12810. $updated_act = DB::table('mp_episode_segments')
  12811. ->where('id', $act_id)
  12812. ->first();
  12813. if ($updated_act) {
  12814. $saved_acts[] = [
  12815. 'act_id' => $updated_act->id,
  12816. 'act_number' => $updated_act->act_number,
  12817. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  12818. 'act_content' => $updated_act->act_content,
  12819. 'act_show_content' => $updated_act->act_show_content,
  12820. 'video_url' => $updated_act->video_url ?? '',
  12821. 'video_duration' => $updated_act->video_duration ?? 0,
  12822. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  12823. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  12824. ];
  12825. }
  12826. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  12827. // 单片段模式成功扣费(normal 档)
  12828. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12829. 'anime_id' => $target_anime_id,
  12830. 'episode_id' => $target_episode_id,
  12831. 'model' => $model,
  12832. 'source' => 'regenerateSegmentScript',
  12833. ], 'normal');
  12834. }
  12835. } else {
  12836. // 预览确认模式(check_mode=1):不落库,返回展示参数供前端确认后调用 saveEpisodeActs 保存
  12837. if ($check_mode === 1) {
  12838. // 剧集模式预览生成即扣除积分并记录 token 明细(special 档)
  12839. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12840. 'anime_id' => $target_anime_id,
  12841. 'episode_id' => $target_episode_id,
  12842. 'model' => $model,
  12843. 'source' => 'regenerateSegmentScript',
  12844. ], 'special');
  12845. // 为每个片段生成虚拟 act_id 并写入 redis(1天有效),供后续按虚拟 act_id 恢复片段数据
  12846. $previewActs = [];
  12847. foreach ($parsed_segments as $seg) {
  12848. $virtualActId = 'preview_' . time() . '_' . uniqid();
  12849. Redis::setex($this->buildActPreviewKey($virtualActId), 86400, json_encode([
  12850. 'anime_id' => $target_anime_id,
  12851. 'episode_id' => $target_episode_id,
  12852. 'episode_number' => $target_episode_number,
  12853. 'act_number' => $seg['act_number'],
  12854. 'act_title' => $seg['act_title'],
  12855. 'act_duration' => $seg['act_duration'],
  12856. 'act_content' => $seg['act_content'],
  12857. 'act_show_content'=> $seg['act_show_content'],
  12858. ], JSON_UNESCAPED_UNICODE));
  12859. $previewActs[] = [
  12860. 'act_id' => $virtualActId,
  12861. 'act_number' => $seg['act_number'],
  12862. 'act_title' => $seg['act_title'],
  12863. 'act_duration' => $seg['act_duration'],
  12864. 'act_content' => $seg['act_content'],
  12865. 'act_show_content' => $seg['act_show_content'],
  12866. 'video_url' => '',
  12867. 'video_duration' => 0,
  12868. 'video_time_point_start' => 0,
  12869. 'video_time_point_end' => 0,
  12870. 'last_frame_url' => '',
  12871. 'current_type' => 0,
  12872. ];
  12873. }
  12874. return [
  12875. 'check_mode' => 1,
  12876. 'anime_id' => $target_anime_id,
  12877. 'episode_id' => $target_episode_id,
  12878. 'title' => getProp($episode, 'title', ''),
  12879. 'episode_number' => $target_episode_number,
  12880. 'is_generated' => getProp($episode, 'is_generated', 0),
  12881. 'acts' => $previewActs,
  12882. ];
  12883. }
  12884. // 整个剧集模式:删除原有记录并批量保存新记录
  12885. DB::beginTransaction();
  12886. try {
  12887. // 删除原有的所有片段记录
  12888. DB::table('mp_episode_segments')
  12889. ->where('episode_id', $target_episode_id)
  12890. ->delete();
  12891. // 批量插入新的片段记录
  12892. $segments_to_insert = [];
  12893. foreach ($parsed_segments as $index => $segment) {
  12894. $act_number = $index + 1;
  12895. $segments_to_insert[] = [
  12896. 'anime_id' => $target_anime_id,
  12897. 'episode_id' => $target_episode_id,
  12898. 'episode_number' => $target_episode_number,
  12899. 'act_number' => $act_number,
  12900. 'act_title' => getProp($segment, 'act_title', ''),
  12901. 'act_duration' => getProp($segment, 'act_duration', 0),
  12902. 'act_content' => getProp($segment, 'act_content', ''),
  12903. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  12904. 'created_at' => $now,
  12905. 'updated_at' => $now,
  12906. ];
  12907. }
  12908. if (!empty($segments_to_insert)) {
  12909. DB::table('mp_episode_segments')->insert($segments_to_insert);
  12910. }
  12911. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(special 档,与保存同事务)
  12912. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12913. 'anime_id' => $target_anime_id,
  12914. 'episode_id' => $target_episode_id,
  12915. 'model' => $model,
  12916. 'source' => 'regenerateSegmentScript',
  12917. ], 'special');
  12918. DB::commit();
  12919. // 查询保存后的所有片段记录
  12920. $saved_segments = DB::table('mp_episode_segments')
  12921. ->where('episode_id', $target_episode_id)
  12922. ->orderBy('act_number')
  12923. ->get();
  12924. foreach ($saved_segments as $saved_segment) {
  12925. $saved_acts[] = [
  12926. 'act_id' => $saved_segment->id,
  12927. 'act_number' => $saved_segment->act_number,
  12928. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  12929. 'act_content' => $saved_segment->act_content,
  12930. 'act_show_content' => $saved_segment->act_show_content,
  12931. 'video_url' => $saved_segment->video_url ?? '',
  12932. 'video_duration' => $saved_segment->video_duration ?? 0,
  12933. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  12934. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  12935. ];
  12936. }
  12937. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  12938. 'episode_id' => $target_episode_id,
  12939. 'segments_count' => count($segments_to_insert)
  12940. ]);
  12941. } catch (\Exception $e) {
  12942. DB::rollBack();
  12943. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  12944. Utils::throwError('20003:保存失败,请重试');
  12945. }
  12946. }
  12947. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  12948. return [
  12949. 'anime_id' => $target_anime_id,
  12950. 'episode_id' => $target_episode_id,
  12951. 'title' => getProp($episode, 'title', ''),
  12952. 'episode_number' => $target_episode_number,
  12953. 'is_generated' => getProp($episode, 'is_generated', 0),
  12954. 'acts' => $saved_acts,
  12955. ];
  12956. } catch (\Exception $e) {
  12957. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  12958. throw $e;
  12959. }
  12960. }
  12961. /**
  12962. * 保存剧集片段(预览确认模式使用):删除旧数据并批量保存新数据到 mp_episode_segments
  12963. *
  12964. * 逻辑与 regenerateSegmentScript 的 episode_id + check_mode=0 保存保持一致。
  12965. *
  12966. * @param array $data 请求参数:episode_id 必填,acts 必填(预览返回的片段数组)
  12967. * @return array
  12968. */
  12969. public function saveEpisodeActs($data) {
  12970. $uid = Site::getUid();
  12971. $episode_id = (int)getProp($data, 'episode_id', 0);
  12972. $acts = getProp($data, 'acts', []);
  12973. if (!$episode_id) {
  12974. Utils::throwError('20003:请提供剧集ID');
  12975. }
  12976. if (!is_array($acts) || empty($acts)) {
  12977. Utils::throwError('20003:请提供片段数据');
  12978. }
  12979. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  12980. if (!$episode) {
  12981. Utils::throwError('20003:剧集不存在');
  12982. }
  12983. // 用户校验:只能调整自己的剧集
  12984. $anime = DB::table('mp_animes')->where('id', $episode->anime_id)->first();
  12985. if (!$anime || (int)$anime->user_id !== (int)$uid) {
  12986. Utils::throwError('20003:没有权限操作该剧集');
  12987. }
  12988. $anime_id = (int)$episode->anime_id;
  12989. $episode_number = (int)$episode->episode_number;
  12990. $now = date('Y-m-d H:i:s');
  12991. try {
  12992. DB::beginTransaction();
  12993. // 删除原有的所有片段记录
  12994. DB::table('mp_episode_segments')
  12995. ->where('episode_id', $episode_id)
  12996. ->delete();
  12997. // 批量插入新的片段记录
  12998. $segments_to_insert = [];
  12999. $index = 0;
  13000. foreach ($acts as $act) {
  13001. if (!is_array($act)) {
  13002. continue;
  13003. }
  13004. $index++;
  13005. $segments_to_insert[] = [
  13006. 'anime_id' => $anime_id,
  13007. 'episode_id' => $episode_id,
  13008. 'episode_number' => $episode_number,
  13009. 'act_number' => (int)getProp($act, 'act_number', $index),
  13010. 'act_title' => (string)getProp($act, 'act_title', ''),
  13011. 'act_duration' => (float)getProp($act, 'act_duration', 0),
  13012. 'act_content' => (string)getProp($act, 'act_content', ''),
  13013. // 'act_show_content' => (string)getProp($act, 'act_show_content', ''),
  13014. 'created_at' => $now,
  13015. 'updated_at' => $now,
  13016. ];
  13017. }
  13018. if (empty($segments_to_insert)) {
  13019. DB::rollBack();
  13020. Utils::throwError('20003:没有有效的片段数据');
  13021. }
  13022. DB::table('mp_episode_segments')->insert($segments_to_insert);
  13023. DB::commit();
  13024. } catch (\Exception $e) {
  13025. DB::rollBack();
  13026. dLog('deepseek')->error('保存剧集片段失败: ' . $e->getMessage(), [
  13027. 'episode_id' => $episode_id,
  13028. ]);
  13029. Utils::throwError('20003:保存失败,请重试');
  13030. }
  13031. // 查询保存后的所有片段记录(数组化,与 episodeInfoForAce 处理一致)
  13032. $saved_segments = DB::table('mp_episode_segments')
  13033. ->where('episode_id', $episode_id)
  13034. ->orderBy('act_number')
  13035. ->get()
  13036. ->map(function ($value) {
  13037. return (array)$value;
  13038. })
  13039. ->toArray();
  13040. // 构造与 episodeInfoForAce 一致的 acts 与 total_duration
  13041. $acts = [];
  13042. $totalDuration = 0;
  13043. foreach ($saved_segments as $segment) {
  13044. $videoDuration = getProp($segment, 'video_duration');
  13045. $actDuration = getProp($segment, 'act_duration');
  13046. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  13047. $totalDuration += floatval($videoDuration);
  13048. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  13049. $totalDuration += floatval($actDuration);
  13050. } else {
  13051. $totalDuration += 5;
  13052. }
  13053. $acts[] = [
  13054. 'act_id' => getProp($segment, 'id'),
  13055. 'act_number' => getProp($segment, 'act_number'),
  13056. 'act_title' => getProp($segment, 'act_title'),
  13057. 'act_duration' => getProp($segment, 'act_duration'),
  13058. 'act_content' => getProp($segment, 'act_content'),
  13059. 'video_url' => getProp($segment, 'video_url'),
  13060. 'video_duration' => getProp($segment, 'video_duration', 0),
  13061. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  13062. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  13063. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  13064. 'current_type' => getProp($segment, 'current_type'),
  13065. ];
  13066. }
  13067. // 顶层与 episodeInfoForAce 一致
  13068. $result = [
  13069. 'episode_id' => $episode_id,
  13070. 'anime_id' => $anime_id,
  13071. 'episode_number' => $episode_number,
  13072. 'title' => getProp($episode, 'title'),
  13073. 'intro' => getProp($episode, 'intro'),
  13074. 'art_style' => getProp($episode, 'art_style'),
  13075. 'roles' => json_decode(getProp($episode, 'roles', '[]'), true),
  13076. 'scenes' => json_decode(getProp($episode, 'scenes', '[]'), true),
  13077. 'props' => getProp($episode, 'props') ? json_decode(getProp($episode, 'props'), true) : [],
  13078. 'is_generated' => getProp($episode, 'is_generated'),
  13079. 'acts' => array_values($acts),
  13080. 'total_duration' => intval(round($totalDuration)),
  13081. ];
  13082. // video_params(从 mp_animes 取,与 episodeInfoForAce 一致)
  13083. $animeRow = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  13084. $result['video_params'] = [
  13085. 'video_model' => getProp($animeRow, 'video_model'),
  13086. 'video_resolution' => getProp($animeRow, 'video_resolution'),
  13087. 'ratio' => getProp($animeRow, 'video_ratio'),
  13088. ];
  13089. return $result;
  13090. }
  13091. /**
  13092. * 预览虚拟 act_id 在 redis 中的键
  13093. *
  13094. * @param mixed $actId
  13095. * @return string
  13096. */
  13097. private function buildActPreviewKey($actId): string
  13098. {
  13099. return 'anime_act_preview:' . $actId;
  13100. }
  13101. /**
  13102. * 清理分镜内容:去除时长、旁白音色等非分镜行,只保留完整分镜内容(分镜标记统一为【分镜N】/【镜头N】)
  13103. *
  13104. * @param string $actContent
  13105. * @return string
  13106. */
  13107. private function cleanSegmentContent(string $actContent): string
  13108. {
  13109. $cleaned_content = '';
  13110. $content_lines = explode("\n", $actContent);
  13111. $is_capturing = false; // 标记是否开始捕获分镜内容
  13112. $count = 0;
  13113. foreach ($content_lines as $line) {
  13114. $trimmed_line = trim($line);
  13115. // 跳过时长、旁白音色等非分镜行
  13116. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  13117. continue;
  13118. }
  13119. // 检测分镜开始(支持【分镜X】【镜头X】、分镜X、镜头X,以及分镜/镜头与数字间带空格的情况)
  13120. if (preg_match('/^(?:【)?(分镜|镜头)\s*(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  13121. $count++;
  13122. $is_capturing = true;
  13123. // 统一归一化为【分镜N】/【镜头N】(兼容“镜头 1”“【镜头 1】”等写法)
  13124. $trimmed_line = preg_replace('/^(?:【)?(分镜|镜头)\s*(\d+)(?:】)?/u', '【$1$2】', $trimmed_line);
  13125. if ($count > 1) {
  13126. $trimmed_line = "\n" . $trimmed_line;
  13127. }
  13128. }
  13129. if ($is_capturing && !empty($trimmed_line)) {
  13130. $cleaned_content .= $trimmed_line . "\n";
  13131. }
  13132. }
  13133. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  13134. return $cleaned_content;
  13135. }
  13136. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  13137. {
  13138. $episode_arr = [
  13139. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  13140. 'intro' => getProp($script_arr, 'intro'),
  13141. 'art_style' => getProp($script_arr, 'art_style'),
  13142. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  13143. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  13144. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  13145. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  13146. ];
  13147. if (empty($episode_arr['acts'])) {
  13148. $fallback_episode_arr = handleEpisodeContent($fullContent);
  13149. if (!empty($fallback_episode_arr['acts'])) {
  13150. $episode_arr = array_merge($fallback_episode_arr, [
  13151. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  13152. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  13153. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  13154. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  13155. ]);
  13156. }
  13157. }
  13158. // if (!getProp($episode_arr, 'episode_title')) {
  13159. // $episode_title = '';
  13160. // $episodes = getProp($script_arr, 'episodes', []);
  13161. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  13162. // $episode_title = '第1集:' . $episodes[0]['title'];
  13163. // }
  13164. // if (!$episode_title) {
  13165. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  13166. // }
  13167. // $episode_arr['episode_title'] = $episode_title;
  13168. // }
  13169. return $episode_arr;
  13170. }
  13171. private function saveEpisodeVersionData(
  13172. int $anime_id,
  13173. int $episode_number,
  13174. array $episode_arr,
  13175. array $existing_roles,
  13176. array $existing_scenes,
  13177. array $existing_props,
  13178. $current_episode,
  13179. $base_episode,
  13180. bool $is_regenerate_version,
  13181. string $content,
  13182. string $now,
  13183. array $ref_products = []
  13184. ): array {
  13185. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  13186. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  13187. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  13188. // 过滤掉关键字段为空的条目
  13189. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  13190. return !empty($item['role'] ?? null);
  13191. }));
  13192. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  13193. return !empty($item['scene'] ?? null);
  13194. }));
  13195. $merged_props = array_values(array_filter($generated_props, function ($item) {
  13196. return !empty($item['prop'] ?? null);
  13197. }));
  13198. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  13199. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  13200. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  13201. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  13202. $ace_mode = getProp($anime, 'ace_mode');
  13203. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  13204. $global_roles = json_decode(getProp($anime, 'roles'), true);
  13205. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  13206. $global_roles = is_array($global_roles) ? $global_roles : [];
  13207. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  13208. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  13209. $art_style_type = getProp($anime, 'art_style_type');
  13210. // 检查并创建 roles 的图片生成任务
  13211. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  13212. // 检查并创建 scenes 的图片生成任务
  13213. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  13214. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  13215. if ($arr && is_array($arr)) {
  13216. $merged_roles = $arr['roles'];
  13217. $merged_scenes = $arr['scenes'];
  13218. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  13219. }
  13220. // 确保数据是数组类型
  13221. if (!is_array($merged_roles)) {
  13222. dLog('deepseek')->error('merged_roles不是数组类型', [
  13223. 'type' => gettype($merged_roles),
  13224. 'value' => $merged_roles
  13225. ]);
  13226. $merged_roles = [];
  13227. }
  13228. if (!is_array($merged_scenes)) {
  13229. dLog('deepseek')->error('merged_scenes不是数组类型', [
  13230. 'type' => gettype($merged_scenes),
  13231. 'value' => $merged_scenes
  13232. ]);
  13233. $merged_scenes = [];
  13234. }
  13235. if (!is_array($merged_props)) {
  13236. dLog('deepseek')->error('merged_props不是数组类型', [
  13237. 'type' => gettype($merged_props),
  13238. 'value' => $merged_props
  13239. ]);
  13240. $merged_props = [];
  13241. }
  13242. // 同步新出现的主体和场景到全局
  13243. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  13244. $role_arr = [];
  13245. foreach ($merged_roles as $item) {
  13246. $role_arr[$item['role']] = $item;
  13247. }
  13248. $version_count = DB::table('mp_anime_episodes')
  13249. ->where('anime_id', $anime_id)
  13250. ->where('episode_number', $episode_number)
  13251. ->count('id');
  13252. $episode = [
  13253. 'anime_id' => $anime_id,
  13254. 'episode_number' => $episode_number,
  13255. 'title' => getProp($episode_arr, 'episode_title'),
  13256. 'content' => $content,
  13257. 'intro' => getProp($episode_arr, 'intro'),
  13258. 'art_style' => getProp($episode_arr, 'art_style'),
  13259. 'roles' => json_encode($merged_roles, 256),
  13260. 'scenes' => json_encode($merged_scenes, 256),
  13261. 'props' => json_encode($merged_props, 256),
  13262. 'generate_status' => '待执行',
  13263. 'generate_at' => $now,
  13264. 'is_default' => 1,
  13265. 'updated_at' => $now,
  13266. ];
  13267. $del_flag = false;
  13268. if ($is_regenerate_version) {
  13269. DB::table('mp_anime_episodes')
  13270. ->where('anime_id', $anime_id)
  13271. ->where('episode_number', $episode_number)
  13272. ->update(['is_default' => 0, 'updated_at' => $now]);
  13273. $episode['sequence'] = $version_count + 1;
  13274. $episode['created_at'] = $now;
  13275. $episode['cpid'] = Site::getCpid();
  13276. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  13277. if (!$episode_id) {
  13278. Utils::throwError('20003:创建剧集版本失败');
  13279. }
  13280. } else {
  13281. $target_episode = $current_episode ?: $base_episode;
  13282. if ($target_episode) {
  13283. $episode_id = getProp($target_episode, 'id');
  13284. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  13285. DB::table('mp_anime_episodes')
  13286. ->where('anime_id', $anime_id)
  13287. ->where('episode_number', $episode_number)
  13288. ->where('id', '<>', $episode_id)
  13289. ->update(['is_default' => 0, 'updated_at' => $now]);
  13290. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  13291. if ($boolen === false) {
  13292. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  13293. Utils::throwError('20003:分集内容保存失败');
  13294. }
  13295. $del_flag = true;
  13296. } else {
  13297. DB::table('mp_anime_episodes')
  13298. ->where('anime_id', $anime_id)
  13299. ->where('episode_number', $episode_number)
  13300. ->update(['is_default' => 0, 'updated_at' => $now]);
  13301. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  13302. $episode['created_at'] = $now;
  13303. $episode['cpid'] = Site::getCpid();
  13304. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  13305. if (!$episode_id) {
  13306. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  13307. Utils::throwError('20003:分集内容保存失败');
  13308. }
  13309. }
  13310. }
  13311. $segments = [];
  13312. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  13313. // 如果是第2集及以后,获取上一集的主体音色数据
  13314. $previous_roles_voice = [];
  13315. if ($episode_number >= 2) {
  13316. $previous_episode = DB::table('mp_anime_episodes')
  13317. ->where('anime_id', $anime_id)
  13318. ->where('episode_number', $episode_number - 1)
  13319. ->where('is_default', 1)
  13320. ->first();
  13321. if ($previous_episode) {
  13322. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  13323. if (is_array($previous_roles)) {
  13324. foreach ($previous_roles as $prev_role) {
  13325. $role_name = getProp($prev_role, 'role');
  13326. if ($role_name) {
  13327. $previous_roles_voice[$role_name] = [
  13328. 'voice_name' => getProp($prev_role, 'voice_name'),
  13329. 'voice_type' => getProp($prev_role, 'voice_type'),
  13330. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  13331. ];
  13332. $voice_prompt = getProp($prev_role, 'voice_prompt');
  13333. if ($voice_prompt) {
  13334. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  13335. }
  13336. }
  13337. }
  13338. }
  13339. }
  13340. }
  13341. // 将继承的音色数据同步到当前集的主体列表
  13342. if (!empty($previous_roles_voice)) {
  13343. foreach ($merged_roles as &$role) {
  13344. $role_name = getProp($role, 'role');
  13345. if ($role_name && isset($previous_roles_voice[$role_name])) {
  13346. // 强制继承上一集的音色数据
  13347. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  13348. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  13349. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  13350. // 如果上一集有 voice_prompt 则继承,否则跳过
  13351. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  13352. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  13353. }
  13354. }
  13355. }
  13356. unset($role); // 解除引用
  13357. // 更新 role_arr 以便后续使用
  13358. $role_arr = [];
  13359. foreach ($merged_roles as $item) {
  13360. $role_arr[$item['role']] = $item;
  13361. }
  13362. }
  13363. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  13364. $emotion_list = array_flip($emotion_list);
  13365. foreach ($acts as $act) {
  13366. $act_segments = getProp($act, 'segments', []);
  13367. if (!is_array($act_segments)) {
  13368. continue;
  13369. }
  13370. if ((int)$ace_mode === 1) {
  13371. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  13372. $merged_parts = [];
  13373. foreach ($act_segments as $seg) {
  13374. $seg_num = getProp($seg, 'segment_number');
  13375. $seg_content = getProp($seg, 'segment_content');
  13376. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  13377. }
  13378. $act_content = implode("\n", $merged_parts);
  13379. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  13380. $segments[] = [
  13381. 'anime_id' => $anime_id,
  13382. 'episode_id' => $episode_id,
  13383. 'episode_number' => $episode_number,
  13384. 'act_number' => getProp($act, 'act_number'),
  13385. 'act_title' => getProp($act, 'act_title'),
  13386. 'act_duration' => getProp($act, 'act_duration'),
  13387. 'act_content' => $act_content,
  13388. 'created_at' => $now,
  13389. 'updated_at' => $now
  13390. ];
  13391. } else {
  13392. foreach ($act_segments as $segment) {
  13393. $voice_actor = getProp($segment, 'voice_actor');
  13394. // 优先从上一集继承音色数据
  13395. $timbre_info = [];
  13396. if (isset($previous_roles_voice[$voice_actor])) {
  13397. // 从上一集继承音色数据
  13398. $timbre_info = $previous_roles_voice[$voice_actor];
  13399. } elseif (isset($role_arr[$voice_actor])) {
  13400. // 使用当前集的主体音色数据
  13401. $timbre_info = $role_arr[$voice_actor];
  13402. }
  13403. $voice_type = getProp($timbre_info, 'voice_type');
  13404. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  13405. if ($timbre_emotion) {
  13406. $timbre_emotion = explode(',', $timbre_emotion);
  13407. } else {
  13408. $timbre_emotion = [];
  13409. }
  13410. $emotion = getProp($segment, 'emotion', '中性');
  13411. if (!in_array($emotion, $timbre_emotion)) {
  13412. $emotion = '中性';
  13413. }
  13414. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  13415. $segments[] = [
  13416. 'anime_id' => $anime_id,
  13417. 'episode_id' => $episode_id,
  13418. 'episode_number' => $episode_number,
  13419. 'act_number' => getProp($act, 'act_number'),
  13420. 'act_title' => getProp($act, 'act_title'),
  13421. 'act_duration' => getProp($act, 'act_duration'),
  13422. 'segment_id' => getProp($segment, 'segment_id'),
  13423. 'segment_number' => getProp($segment, 'segment_number'),
  13424. 'segment_content' => getProp($segment, 'segment_content'),
  13425. 'description' => getProp($segment, 'description'),
  13426. 'composition' => getProp($segment, 'composition'),
  13427. 'camera_movement' => getProp($segment, 'camera_movement'),
  13428. 'voice_actor' => $voice_actor,
  13429. 'dialogue' => getProp($segment, 'dialogue'),
  13430. 'frame_type' => getProp($segment, 'frame_type'),
  13431. 'scene' => getProp($segment, 'scene'),
  13432. 'characters' => getProp($segment, 'characters'),
  13433. 'tail_frame' => getProp($segment, 'tail_frame'),
  13434. 'voice_name' => getProp($timbre_info, 'voice_name'),
  13435. 'voice_type' => $voice_type,
  13436. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  13437. 'emotion' => $emotion,
  13438. 'emotion_type' => $emotion_type,
  13439. 'gender' => getProp($segment, 'gender', '0'),
  13440. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  13441. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  13442. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  13443. 'pitch' => getProp($segment, 'pitch', 0),
  13444. 'created_at' => $now,
  13445. 'updated_at' => $now
  13446. ];
  13447. }
  13448. }
  13449. }
  13450. if ($segments) {
  13451. if ($del_flag) {
  13452. DB::table('mp_episode_segments')
  13453. ->where('anime_id', $anime_id)
  13454. ->where('episode_id', $episode_id)
  13455. ->delete();
  13456. }
  13457. $boolen = DB::table('mp_episode_segments')->insert($segments);
  13458. if (!$boolen) {
  13459. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  13460. Utils::throwError('20003:分镜内容保存失败');
  13461. }
  13462. }
  13463. dLog('deepseek')->info('segments', $segments);
  13464. // ace_mode=1: acts 返回值按合并格式调整
  13465. if ((int)$ace_mode === 1) {
  13466. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  13467. $act_map = [];
  13468. foreach ($table_act_data as $item) {
  13469. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  13470. }
  13471. $restructured_acts = [];
  13472. foreach ($acts as $act) {
  13473. $act_segments = getProp($act, 'segments', []);
  13474. if (!is_array($act_segments)) {
  13475. continue;
  13476. }
  13477. $merged_parts = [];
  13478. foreach ($act_segments as $seg) {
  13479. $seg_num = getProp($seg, 'segment_number');
  13480. $seg_content = getProp($seg, 'segment_content');
  13481. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  13482. }
  13483. $act_content = implode("\n", $merged_parts);
  13484. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  13485. $restructured_acts[] = [
  13486. 'anime_id' => $anime_id,
  13487. 'episode_id' => $episode_id,
  13488. 'episode_number' => $episode_number,
  13489. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  13490. 'act_number' => getProp($act, 'act_number'),
  13491. 'act_title' => getProp($act, 'act_title'),
  13492. 'act_duration' => getProp($act, 'act_duration'),
  13493. 'act_content' => $act_content,
  13494. 'created_at' => $now,
  13495. 'updated_at' => $now,
  13496. ];
  13497. }
  13498. $acts = $restructured_acts;
  13499. }
  13500. $episode['episode_id'] = $episode_id;
  13501. $episode['roles'] = $merged_roles;
  13502. $episode['scenes'] = $merged_scenes;
  13503. $episode['props'] = $merged_props;
  13504. $episode['acts'] = $acts;
  13505. return [
  13506. 'episode' => $episode,
  13507. 'episode_id' => $episode_id,
  13508. 'merged_roles' => $merged_roles,
  13509. 'merged_scenes' => $merged_scenes,
  13510. 'merged_props' => $merged_props,
  13511. ];
  13512. }
  13513. private function buildEpisodeItemContent(array $items, string $nameKey): string
  13514. {
  13515. $content = '';
  13516. foreach ($items as $item) {
  13517. $name = trim((string)getProp($item, $nameKey));
  13518. if ($name === '' || $name === '旁白') {
  13519. continue;
  13520. }
  13521. $description = trim((string)getProp($item, 'description'));
  13522. $content .= $name . ': ' . $description;
  13523. if ($nameKey == 'role') {
  13524. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  13525. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13526. $voice_name = trim(getProp($item, 'voice_name'));
  13527. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  13528. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  13529. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  13530. }else {
  13531. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  13532. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13533. }
  13534. $content .= "\n";
  13535. }
  13536. return trim($content);
  13537. }
  13538. private function getEpisodeChatContent($animeId, $sequence, $content) {
  13539. if ((int)$sequence <= 0) {
  13540. return [];
  13541. }
  13542. $origin_content = '';
  13543. if ($content) {
  13544. $origin_content = '本集剧情内容:'.$content;
  13545. }else {
  13546. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  13547. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  13548. }
  13549. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  13550. // 获取分集信息
  13551. $episode = DB::table('mp_anime_episodes')
  13552. ->where('anime_id', $animeId)
  13553. ->where('episode_number', $sequence)
  13554. ->where('is_default', 1)
  13555. ->first();
  13556. if (!$episode) {
  13557. return [];
  13558. }
  13559. $episode_id = getProp($episode, 'id');
  13560. $episode_number = getProp($episode, 'episode_number');
  13561. $title = getProp($episode, 'title');
  13562. $intro = getProp($episode, 'intro');
  13563. $art_style = getProp($episode, 'art_style');
  13564. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  13565. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  13566. // 组装纯文本内容
  13567. $content = '';
  13568. // 添加分集标题和梗概
  13569. $content .= "###第{$episode_number}集:{$title}\n\n";
  13570. $content .= "###故事梗概\n";
  13571. $content .= trim($intro) . "\n\n";
  13572. // 添加美术风格
  13573. $content .= "###美术风格\n";
  13574. $content .= trim($art_style) . "\n\n";
  13575. // 添加主体列表
  13576. $content .= "###主体列表\n";
  13577. $pangbai_voice_prompt = "";
  13578. foreach ($roles as $role) {
  13579. $name = getProp($role, 'role');
  13580. $description = getProp($role, 'description');
  13581. $pic_prompt = getProp($role, 'pic_prompt');
  13582. $voice_prompt = getProp($role, 'voice_prompt');
  13583. $voice_name = getProp($role, 'voice_name');
  13584. $content .= "{$name}: {$description}";
  13585. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13586. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  13587. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  13588. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  13589. $content .= "\n";
  13590. }
  13591. $content .= "\n";
  13592. // 添加场景列表
  13593. $content .= "###场景列表\n";
  13594. foreach ($scenes as $scene) {
  13595. $name = getProp($scene, 'scene');
  13596. $description = getProp($scene, 'description');
  13597. $pic_prompt = getProp($scene, 'pic_prompt');
  13598. $content .= "{$name}: {$description}";
  13599. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13600. $content .= "\n";
  13601. }
  13602. $content .= "\n";
  13603. // 获取分镜信息
  13604. $segments = DB::table('mp_episode_segments')
  13605. ->where('anime_id', $animeId)
  13606. ->where('episode_id', $episode_id)
  13607. ->orderBy('segment_number')
  13608. ->get();
  13609. if ($segments && count($segments) > 0) {
  13610. if ((int)$ace_mode === 1) {
  13611. $content .= "###分段剧本\n";
  13612. // 获取片段数量
  13613. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  13614. $content .= "片段数量:{$act_count}\n";
  13615. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  13616. $content .= "\n";
  13617. }else {
  13618. $content .= "###分镜剧本\n";
  13619. }
  13620. // 按幕分组
  13621. $currentAct = null;
  13622. foreach ($segments as $segment) {
  13623. $act_number = getProp($segment, 'act_number');
  13624. $act_title = getProp($segment, 'act_title');
  13625. $act_duration = getProp($segment, 'act_duration');
  13626. $segment_number = getProp($segment, 'segment_number');
  13627. $segment_content = getProp($segment, 'segment_content');
  13628. $scene_description = getProp($segment, 'scene_description');
  13629. $scene_name = getProp($segment, 'scene_name');
  13630. $composition = getProp($segment, 'composition');
  13631. $camera_movement = getProp($segment, 'camera_movement');
  13632. $voice_type = getProp($segment, 'voice_type');
  13633. $characters = getProp($segment, 'characters');
  13634. $dialogue = getProp($segment, 'dialogue');
  13635. $frame_type = getProp($segment, 'frame_type');
  13636. $tail_frame_description = getProp($segment, 'tail_frame_description');
  13637. // 判断是否是全能模式
  13638. if ((int)$ace_mode === 1) { // 全能模式
  13639. // 如果是新的分段,添加分段标题
  13640. if ($act_number !== $currentAct) {
  13641. $currentAct = $act_number;
  13642. $content .= "##{$act_title}\n";
  13643. $content .= "时长:{$act_duration}s\n";
  13644. }
  13645. }else {
  13646. // 如果是新的幕,添加幕标题
  13647. if ($act_number !== $currentAct) {
  13648. $currentAct = $act_number;
  13649. $content .= "##第{$act_number}幕:{$scene_name}\n";
  13650. }
  13651. }
  13652. // 添加分镜信息
  13653. $content .= "分镜{$segment_number}\n";
  13654. $content .= "分镜内容:\n{$segment_content}\n";
  13655. // $content .= "画面描述:{$scene_description}\n";
  13656. // $content .= "场景:{$scene_name}\n";
  13657. // $content .= "构图设计:{$composition}\n";
  13658. // $content .= "运镜调度:{$camera_movement}\n";
  13659. // if (!empty($voice_type)) {
  13660. // $content .= "配音角色:{$voice_type}\n";
  13661. // }
  13662. // if (!empty($characters)) {
  13663. // $content .= "出镜角色:{$characters}\n";
  13664. // }
  13665. // if (!empty($dialogue)) {
  13666. // $content .= "台词内容:\"{$dialogue}\"\n";
  13667. // }
  13668. // $content .= "画面类型:{$frame_type}\n";
  13669. // $content .= "尾帧描述:{$tail_frame_description}\n";
  13670. $content .= "\n";
  13671. }
  13672. }
  13673. $content = trim($content);
  13674. if($content) $content = "上集剧本内容:\n{$content}";
  13675. return [
  13676. [
  13677. 'role' => 'user',
  13678. 'content' => $origin_content
  13679. ],
  13680. [
  13681. 'role' => 'assistant',
  13682. 'content' => $content
  13683. ]
  13684. ];
  13685. }
  13686. private function getEpisodeChatMessages($animeId, $sequence): array
  13687. {
  13688. if ((int)$sequence <= 0) {
  13689. return [];
  13690. }
  13691. return DB::table('mp_anime_records')
  13692. ->where('anime_id', $animeId)
  13693. ->where('sequence', $sequence)
  13694. ->where('episode_id', '>', 0)
  13695. ->select('role', 'content')
  13696. ->orderBy('created_at')
  13697. ->orderBy('id')
  13698. ->get()
  13699. ->map(function ($value) {
  13700. return (array)$value;
  13701. })
  13702. ->toArray();
  13703. }
  13704. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  13705. {
  13706. $existingMap = [];
  13707. foreach ($existingItems as $item) {
  13708. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13709. if ($itemKey === '') {
  13710. continue;
  13711. }
  13712. $existingMap[$itemKey] = $item;
  13713. }
  13714. if (!$generatedItems) {
  13715. return array_values($existingItems);
  13716. }
  13717. $merged = [];
  13718. foreach ($generatedItems as $item) {
  13719. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13720. if ($itemKey === '') {
  13721. continue;
  13722. }
  13723. if (isset($existingMap[$itemKey])) {
  13724. if (trim((string)getProp($item, 'description')) === '') {
  13725. $merged[] = $existingMap[$itemKey];
  13726. continue;
  13727. }
  13728. // 检查内容是否发生变化
  13729. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  13730. if (!$isChanged) {
  13731. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  13732. $mergedItem = [
  13733. $nameKey => trim((string)getProp($item, $nameKey)),
  13734. 'description' => trim((string)getProp($item, 'description')),
  13735. ];
  13736. // 如果有 pic_prompt,添加到合并项中
  13737. $picPrompt = getProp($item, 'pic_prompt');
  13738. if (!empty($picPrompt)) {
  13739. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  13740. }
  13741. // 继承现有项的 URL
  13742. $existingUrl = getProp($existingMap[$itemKey], 'url');
  13743. if (!empty($existingUrl)) {
  13744. $mergedItem['url'] = $existingUrl;
  13745. }
  13746. // 继承现有项的 task_id
  13747. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  13748. if (!empty($existingTaskId)) {
  13749. $mergedItem['task_id'] = $existingTaskId;
  13750. }
  13751. // 继承现有项的 task_status
  13752. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  13753. if (!empty($existingTaskStatus)) {
  13754. $mergedItem['task_status'] = $existingTaskStatus;
  13755. }
  13756. // 保留生成项的音色字段
  13757. $voiceName = getProp($item, 'voice_name');
  13758. if (!empty($voiceName)) {
  13759. $mergedItem['voice_name'] = $voiceName;
  13760. }
  13761. $voiceType = getProp($item, 'voice_type');
  13762. if (!empty($voiceType)) {
  13763. $mergedItem['voice_type'] = $voiceType;
  13764. }
  13765. $audioUrl = getProp($item, 'voice_audio_url');
  13766. if (!empty($audioUrl)) {
  13767. $mergedItem['voice_audio_url'] = $audioUrl;
  13768. }
  13769. $merged[] = $mergedItem;
  13770. } else {
  13771. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  13772. $mergedItem = [
  13773. $nameKey => trim((string)getProp($item, $nameKey)),
  13774. 'description' => trim((string)getProp($item, 'description')),
  13775. ];
  13776. // 如果有 pic_prompt,添加到合并项中
  13777. $picPrompt = getProp($item, 'pic_prompt');
  13778. if (!empty($picPrompt)) {
  13779. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  13780. }
  13781. // 保留生成项的音色字段
  13782. $voiceName = getProp($item, 'voice_name');
  13783. if (!empty($voiceName)) {
  13784. $mergedItem['voice_name'] = $voiceName;
  13785. }
  13786. $voiceType = getProp($item, 'voice_type');
  13787. if (!empty($voiceType)) {
  13788. $mergedItem['voice_type'] = $voiceType;
  13789. }
  13790. $audioUrl = getProp($item, 'voice_audio_url');
  13791. if (!empty($audioUrl)) {
  13792. $mergedItem['voice_audio_url'] = $audioUrl;
  13793. }
  13794. // 不继承 URL、task_id 和 task_status(重置状态)
  13795. $merged[] = $mergedItem;
  13796. }
  13797. } else {
  13798. // 新增项,保留生成项的所有字段
  13799. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  13800. }
  13801. }
  13802. return $merged ?: array_values($existingItems);
  13803. }
  13804. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  13805. {
  13806. $resetItem = [
  13807. $nameKey => trim((string)getProp($item, $nameKey)),
  13808. 'description' => trim((string)getProp($item, 'description')),
  13809. ];
  13810. // 保留指定的字段
  13811. foreach ($preserveFields as $field) {
  13812. $value = getProp($item, $field);
  13813. if (!empty($value)) {
  13814. $resetItem[$field] = $value;
  13815. }
  13816. }
  13817. return $resetItem;
  13818. }
  13819. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  13820. {
  13821. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  13822. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  13823. if ($existingKey !== $generatedKey) {
  13824. return true;
  13825. }
  13826. // 比较 description 是否变化
  13827. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  13828. return true;
  13829. }
  13830. // 比较 pic_prompt 是否变化
  13831. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  13832. }
  13833. private function normalizeEpisodeResourceKey($value): string
  13834. {
  13835. $value = trim((string)$value);
  13836. if ($value === '') {
  13837. return '';
  13838. }
  13839. return strtolower((string)preg_replace('/\s+/u', '', $value));
  13840. }
  13841. // 生成全局角色图片
  13842. private function batchSetGlobalRoleImg($data, $is_force=false) {
  13843. $anime_id = getProp($data, 'anime_id');
  13844. if (!$anime_id) Utils::throwError('1002:请选择对话');
  13845. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  13846. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  13847. $art_style = getProp($anime, 'art_style');
  13848. $update_flag = false;
  13849. foreach ($roles as &$role) {
  13850. $role_name = getProp($role, 'role');
  13851. if ($role_name == '旁白') continue;
  13852. // 优先使用 pic_prompt,如果没有则使用 description
  13853. $pic_prompt = getProp($role, 'pic_prompt');
  13854. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  13855. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  13856. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  13857. // 参考图地址
  13858. $ref_img_url = getProp($role, 'url');
  13859. if (!$is_force && $ref_img_url) continue;
  13860. $update_flag = true;
  13861. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  13862. try {
  13863. $params = [
  13864. 'prompt' => $description,
  13865. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  13866. 'ref_img_urls' => [],
  13867. // 计费锚点(动漫/剧本),用于积分明细归属统计
  13868. 'anime_id' => $anime_id,
  13869. ];
  13870. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13871. $task_id = $task->id;
  13872. if (!$task_id) {
  13873. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  13874. }
  13875. $role['task_id'] = $task_id;
  13876. $role['task_status'] = 'processing';
  13877. } catch (\Exception $e) {
  13878. Utils::throwError("20003:" . $e->getMessage());
  13879. }
  13880. }
  13881. if (!$update_flag) return true;
  13882. // 保存角色信息
  13883. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  13884. 'roles' => json_encode($roles, 256),
  13885. 'generate_status' => '执行中',
  13886. 'generate_at' => date('Y-m-d H:i:s'),
  13887. 'updated_at' => date('Y-m-d H:i:s')
  13888. ]);
  13889. if (!$boolen) {
  13890. Utils::throwError('20003:保存角色信息失败');
  13891. }
  13892. return $boolen;
  13893. }
  13894. // 生成全局场景图片
  13895. private function batchSetGlobalSceneImg($data, $is_force=false) {
  13896. $anime_id = getProp($data, 'anime_id');
  13897. if (!$anime_id) Utils::throwError('1002:请选择对话');
  13898. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  13899. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  13900. $art_style = getProp($anime, 'art_style');
  13901. $update_flag = false;
  13902. foreach ($scenes as &$scene) {
  13903. $scene_name = getProp($scene, 'scene');
  13904. // 优先使用 pic_prompt,如果没有则使用 description
  13905. $pic_prompt = getProp($scene, 'pic_prompt');
  13906. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  13907. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  13908. // 参考图地址
  13909. $ref_img_url = getProp($scene, 'url');
  13910. if (!$is_force && $ref_img_url) continue;
  13911. $update_flag = true;
  13912. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  13913. try {
  13914. $params = [
  13915. 'prompt' => $description,
  13916. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  13917. 'ref_img_urls' => [],
  13918. // 计费锚点(动漫/剧本),用于积分明细归属统计
  13919. 'anime_id' => $anime_id,
  13920. ];
  13921. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13922. $task_id = $task->id;
  13923. if (!$task_id) {
  13924. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  13925. }
  13926. $scene['task_id'] = $task_id;
  13927. $scene['task_status'] = 'processing';
  13928. } catch (\Exception $e) {
  13929. Utils::throwError("20003:" . $e->getMessage());
  13930. }
  13931. }
  13932. if (!$update_flag) return true;
  13933. // 保存角色信息
  13934. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  13935. 'scenes' => json_encode($scenes, 256),
  13936. 'generate_status' => '执行中',
  13937. 'generate_at' => date('Y-m-d H:i:s'),
  13938. 'updated_at' => date('Y-m-d H:i:s')
  13939. ]);
  13940. if (!$boolen) {
  13941. Utils::throwError('20003:保存角色信息失败');
  13942. }
  13943. return $boolen;
  13944. }
  13945. // 生成分镜主体、场景和道具图片
  13946. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  13947. $character_prefix = '';
  13948. $scene_prefix = '';
  13949. $prop_prefix = '';
  13950. if ($art_style_type) {
  13951. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  13952. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  13953. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  13954. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  13955. }
  13956. $update_flag = false;
  13957. // 获取上一集的roles、scenes和props数据
  13958. $prev_roles = [];
  13959. $prev_scenes = [];
  13960. $prev_props = [];
  13961. if ($episode_number > 1) {
  13962. $prev_episode = DB::table('mp_anime_episodes')
  13963. ->where('anime_id', $anime_id)
  13964. ->where('episode_number', $episode_number - 1)
  13965. ->where('is_default', 1)
  13966. ->first();
  13967. if ($prev_episode) {
  13968. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  13969. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  13970. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  13971. dLog('deepseek')->info("获取上一集数据成功", [
  13972. 'anime_id' => $anime_id,
  13973. 'prev_episode_number' => $episode_number - 1,
  13974. 'prev_roles_count' => count($prev_roles),
  13975. 'prev_scenes_count' => count($prev_scenes),
  13976. 'prev_props_count' => count($prev_props)
  13977. ]);
  13978. }
  13979. }
  13980. // 处理角色图片生成
  13981. foreach ($roles as &$role) {
  13982. $role_name = getProp($role, 'role');
  13983. if ($role_name == '旁白') continue;
  13984. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  13985. if (isset($ref_products[$role_name])) {
  13986. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  13987. $role['three_view_image_url'] = isset($ref_products[$role_name]['three_view_image_url']) ? $ref_products[$role_name]['three_view_image_url'] : '';
  13988. if ($role['url']) continue;
  13989. }
  13990. $role_description = getProp($role, 'description');
  13991. $role_pic_prompt = getProp($role, 'pic_prompt');
  13992. $role_url = getProp($role, 'url');
  13993. // 检查是否可以从上一集继承
  13994. $inherited = false;
  13995. if (!$is_force && !empty($prev_roles)) {
  13996. foreach ($prev_roles as $prev_role) {
  13997. $prev_role_name = getProp($prev_role, 'role');
  13998. $prev_description = getProp($prev_role, 'description');
  13999. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  14000. $prev_url = getProp($prev_role, 'url');
  14001. $prev_task_id = getProp($prev_role, 'task_id');
  14002. $prev_task_status = getProp($prev_role, 'task_status');
  14003. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  14004. if ($role_name == $prev_role_name
  14005. && $role_description == $prev_description
  14006. && $role_pic_prompt == $prev_pic_prompt
  14007. && !empty($prev_url)) {
  14008. $role['task_id'] = $prev_task_id;
  14009. $role['task_status'] = $prev_task_status;
  14010. $role['url'] = $prev_url;
  14011. $inherited = true;
  14012. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  14013. 'anime_id' => $anime_id,
  14014. 'episode_number' => $episode_number,
  14015. 'task_id' => $prev_task_id,
  14016. 'url' => $prev_url
  14017. ]);
  14018. break;
  14019. }
  14020. }
  14021. }
  14022. // 如果已继承或已有url,跳过生成
  14023. if ($inherited || (!$is_force && $role_url)) {
  14024. continue;
  14025. }
  14026. // 优先使用 pic_prompt,如果没有则使用 description
  14027. $pic_prompt = getProp($role, 'pic_prompt');
  14028. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  14029. $description = buildStylePromptPrefix($character_prefix) . "主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  14030. $update_flag = true;
  14031. // 调用AIImageGenerationService的生成图片任务接口
  14032. try {
  14033. $params = [
  14034. 'prompt' => $description,
  14035. 'ref_img_urls' => [],
  14036. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  14037. 'anime_id' => $anime_id,
  14038. 'episode_number' => $episode_number,
  14039. ];
  14040. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  14041. $task_id = $task->id;
  14042. if (!$task_id) {
  14043. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  14044. continue; // 不中断,继续处理其他角色
  14045. }
  14046. $role['task_id'] = $task_id;
  14047. $role['task_status'] = 'processing';
  14048. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  14049. 'anime_id' => $anime_id,
  14050. 'episode_number' => $episode_number,
  14051. 'task_id' => $task_id
  14052. ]);
  14053. } catch (\Exception $e) {
  14054. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  14055. // 不抛出异常,继续处理其他角色
  14056. }
  14057. }
  14058. // 处理场景图片生成
  14059. foreach ($scenes as &$scene) {
  14060. $scene_name = getProp($scene, 'scene');
  14061. $scene_description = getProp($scene, 'description');
  14062. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  14063. $scene_url = getProp($scene, 'url');
  14064. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  14065. if (isset($ref_products[$scene_name])) {
  14066. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  14067. $scene['three_view_image_url'] = isset($ref_products[$scene_name]['three_view_image_url']) ? $ref_products[$scene_name]['three_view_image_url'] : '';
  14068. if ($scene['url']) continue;
  14069. }
  14070. // 检查是否可以从上一集继承
  14071. $inherited = false;
  14072. if (!$is_force && !empty($prev_scenes)) {
  14073. foreach ($prev_scenes as $prev_scene) {
  14074. $prev_scene_name = getProp($prev_scene, 'scene');
  14075. $prev_description = getProp($prev_scene, 'description');
  14076. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  14077. $prev_url = getProp($prev_scene, 'url');
  14078. $prev_task_id = getProp($prev_scene, 'task_id');
  14079. $prev_task_status = getProp($prev_scene, 'task_status');
  14080. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  14081. if ($scene_name == $prev_scene_name
  14082. && $scene_description == $prev_description
  14083. && $scene_pic_prompt == $prev_pic_prompt
  14084. && !empty($prev_url)) {
  14085. $scene['task_id'] = $prev_task_id;
  14086. $scene['task_status'] = $prev_task_status;
  14087. $scene['url'] = $prev_url;
  14088. $inherited = true;
  14089. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  14090. 'anime_id' => $anime_id,
  14091. 'episode_number' => $episode_number,
  14092. 'task_id' => $prev_task_id,
  14093. 'url' => $prev_url
  14094. ]);
  14095. break;
  14096. }
  14097. }
  14098. }
  14099. // 如果已继承或已有url,跳过生成
  14100. if ($inherited || (!$is_force && $scene_url)) {
  14101. continue;
  14102. }
  14103. // 优先使用 pic_prompt,如果没有则使用 description
  14104. $pic_prompt = getProp($scene, 'pic_prompt');
  14105. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  14106. $description = buildStylePromptPrefix($scene_prefix) . "场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  14107. $update_flag = true;
  14108. // 调用AIImageGenerationService的生成图片任务接口
  14109. try {
  14110. $params = [
  14111. 'prompt' => $description,
  14112. 'ref_img_urls' => [],
  14113. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  14114. 'anime_id' => $anime_id,
  14115. 'episode_number' => $episode_number,
  14116. ];
  14117. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  14118. $task_id = $task->id;
  14119. if (!$task_id) {
  14120. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  14121. continue; // 不中断,继续处理其他场景
  14122. }
  14123. $scene['task_id'] = $task_id;
  14124. $scene['task_status'] = 'processing';
  14125. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  14126. 'anime_id' => $anime_id,
  14127. 'episode_number' => $episode_number,
  14128. 'task_id' => $task_id
  14129. ]);
  14130. } catch (\Exception $e) {
  14131. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  14132. // 不抛出异常,继续处理其他场景
  14133. }
  14134. }
  14135. // 处理道具图片生成(逻辑与场景一致)
  14136. foreach ($props as &$prop) {
  14137. $prop_name = getProp($prop, 'prop');
  14138. $prop_description = getProp($prop, 'description');
  14139. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  14140. $prop_url = getProp($prop, 'url');
  14141. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  14142. if (isset($ref_products[$prop_name])) {
  14143. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  14144. $prop['three_view_image_url'] = isset($ref_products[$prop_name]['three_view_image_url']) ? $ref_products[$prop_name]['three_view_image_url'] : '';
  14145. if ($prop['url']) continue;
  14146. }
  14147. // 检查是否可以从上一集继承
  14148. $inherited = false;
  14149. if (!$is_force && !empty($prev_props)) {
  14150. foreach ($prev_props as $prev_prop) {
  14151. $prev_prop_name = getProp($prev_prop, 'prop');
  14152. $prev_description = getProp($prev_prop, 'description');
  14153. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  14154. $prev_url = getProp($prev_prop, 'url');
  14155. $prev_task_id = getProp($prev_prop, 'task_id');
  14156. $prev_task_status = getProp($prev_prop, 'task_status');
  14157. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  14158. if ($prop_name == $prev_prop_name
  14159. && $prop_description == $prev_description
  14160. && $prop_pic_prompt == $prev_pic_prompt
  14161. && !empty($prev_url)) {
  14162. $prop['task_id'] = $prev_task_id;
  14163. $prop['task_status'] = $prev_task_status;
  14164. $prop['url'] = $prev_url;
  14165. $inherited = true;
  14166. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  14167. 'anime_id' => $anime_id,
  14168. 'episode_number' => $episode_number,
  14169. 'task_id' => $prev_task_id,
  14170. 'url' => $prev_url
  14171. ]);
  14172. break;
  14173. }
  14174. }
  14175. }
  14176. // 如果已继承或已有url,跳过生成
  14177. if ($inherited || (!$is_force && $prop_url)) {
  14178. continue;
  14179. }
  14180. // 优先使用 pic_prompt,如果没有则使用 description
  14181. $pic_prompt = getProp($prop, 'pic_prompt');
  14182. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  14183. $description = buildStylePromptPrefix($prop_prefix) . "道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  14184. $update_flag = true;
  14185. // 调用AIImageGenerationService的生成图片任务接口
  14186. try {
  14187. $params = [
  14188. 'prompt' => $description,
  14189. 'ref_img_urls' => [],
  14190. // 计费锚点(动漫/剧集/剧本),用于积分明细归属统计
  14191. 'anime_id' => $anime_id,
  14192. 'episode_number' => $episode_number,
  14193. ];
  14194. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  14195. $task_id = $task->id;
  14196. if (!$task_id) {
  14197. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  14198. continue; // 不中断,继续处理其他道具
  14199. }
  14200. $prop['task_id'] = $task_id;
  14201. $prop['task_status'] = 'processing';
  14202. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  14203. 'anime_id' => $anime_id,
  14204. 'episode_number' => $episode_number,
  14205. 'task_id' => $task_id
  14206. ]);
  14207. } catch (\Exception $e) {
  14208. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  14209. // 不抛出异常,继续处理其他道具
  14210. }
  14211. }
  14212. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  14213. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  14214. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  14215. // // 保存剧集的角色和场景信息
  14216. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  14217. // 'roles' => json_encode($roles, 256),
  14218. // 'scenes' => json_encode($scenes, 256),
  14219. // 'generate_status' => '执行中',
  14220. // 'generate_at' => date('Y-m-d H:i:s'),
  14221. // 'updated_at' => date('Y-m-d H:i:s')
  14222. // ]);
  14223. // if (!$boolen) {
  14224. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  14225. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  14226. // }
  14227. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  14228. // 'episode_id' => $episode_id,
  14229. 'roles_count' => count($roles),
  14230. 'scenes_count' => count($scenes),
  14231. 'props_count' => count($props)
  14232. ]);
  14233. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  14234. }
  14235. /**
  14236. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  14237. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  14238. *
  14239. * @param int $anime_id 动漫对话ID
  14240. * @param array $episode_roles 剧集角色数据
  14241. * @param array $episode_scenes 剧集场景数据
  14242. * @param array $episode_props 剧集道具数据
  14243. * @return bool
  14244. */
  14245. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  14246. // 获取全局数据
  14247. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  14248. if (!$anime) {
  14249. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  14250. return false;
  14251. }
  14252. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  14253. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  14254. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  14255. $roles_added = false;
  14256. $roles_updated = false;
  14257. $scenes_added = false;
  14258. $props_added = false;
  14259. // 处理角色同步
  14260. foreach ($episode_roles as $episode_role) {
  14261. $episode_role_name = getProp($episode_role, 'role');
  14262. $episode_description = getProp($episode_role, 'description');
  14263. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  14264. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  14265. // 跳过旁白
  14266. if ($episode_role_name == '旁白') {
  14267. continue;
  14268. }
  14269. // 检查全局中是否已存在相同的角色
  14270. $exists = false;
  14271. $global_role_index = -1;
  14272. foreach ($global_roles as $index => $global_role) {
  14273. $global_role_name = getProp($global_role, 'role');
  14274. $global_description = getProp($global_role, 'description');
  14275. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  14276. // 如果role、description、pic_prompt三项都一致,则认为已存在
  14277. if ($episode_role_name == $global_role_name
  14278. && $episode_description == $global_description
  14279. && $episode_pic_prompt == $global_pic_prompt) {
  14280. $exists = true;
  14281. $global_role_index = $index;
  14282. break;
  14283. }
  14284. }
  14285. // 如果不存在,则添加到全局
  14286. if (!$exists) {
  14287. $global_roles[] = $episode_role;
  14288. $roles_added = true;
  14289. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  14290. 'anime_id' => $anime_id,
  14291. 'role' => $episode_role_name
  14292. ]);
  14293. } else {
  14294. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  14295. if (!empty($episode_voice_prompt)) {
  14296. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  14297. // 如果全局没有voice_prompt或与剧集不一致,则更新
  14298. if ($global_voice_prompt !== $episode_voice_prompt) {
  14299. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  14300. $roles_updated = true;
  14301. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  14302. 'anime_id' => $anime_id,
  14303. 'role' => $episode_role_name,
  14304. 'voice_prompt' => $episode_voice_prompt
  14305. ]);
  14306. }
  14307. }
  14308. }
  14309. }
  14310. // 处理场景同步
  14311. foreach ($episode_scenes as $episode_scene) {
  14312. $episode_scene_name = getProp($episode_scene, 'scene');
  14313. $episode_description = getProp($episode_scene, 'description');
  14314. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  14315. // 检查全局中是否已存在相同的场景
  14316. $exists = false;
  14317. foreach ($global_scenes as $global_scene) {
  14318. $global_scene_name = getProp($global_scene, 'scene');
  14319. $global_description = getProp($global_scene, 'description');
  14320. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  14321. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  14322. if ($episode_scene_name == $global_scene_name
  14323. && $episode_description == $global_description
  14324. && $episode_pic_prompt == $global_pic_prompt) {
  14325. $exists = true;
  14326. break;
  14327. }
  14328. }
  14329. // 如果不存在,则添加到全局
  14330. if (!$exists) {
  14331. $global_scenes[] = $episode_scene;
  14332. $scenes_added = true;
  14333. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  14334. 'anime_id' => $anime_id,
  14335. 'scene' => $episode_scene_name
  14336. ]);
  14337. }
  14338. }
  14339. // 处理道具同步(逻辑与场景一致)
  14340. foreach ($episode_props as $episode_prop) {
  14341. $episode_prop_name = getProp($episode_prop, 'prop');
  14342. $episode_description = getProp($episode_prop, 'description');
  14343. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  14344. // 检查全局中是否已存在相同的道具
  14345. $exists = false;
  14346. foreach ($global_props as $global_prop) {
  14347. $global_prop_name = getProp($global_prop, 'prop');
  14348. $global_description = getProp($global_prop, 'description');
  14349. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  14350. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  14351. if ($episode_prop_name == $global_prop_name
  14352. && $episode_description == $global_description
  14353. && $episode_pic_prompt == $global_pic_prompt) {
  14354. $exists = true;
  14355. break;
  14356. }
  14357. }
  14358. // 如果不存在,则添加到全局
  14359. if (!$exists) {
  14360. $global_props[] = $episode_prop;
  14361. $props_added = true;
  14362. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  14363. 'anime_id' => $anime_id,
  14364. 'prop' => $episode_prop_name
  14365. ]);
  14366. }
  14367. }
  14368. // 如果有新增或更新,则更新全局数据
  14369. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  14370. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  14371. if ($roles_added || $roles_updated) {
  14372. $update_data['roles'] = json_encode($global_roles, 256);
  14373. }
  14374. if ($scenes_added) {
  14375. $update_data['scenes'] = json_encode($global_scenes, 256);
  14376. }
  14377. if ($props_added) {
  14378. $update_data['props'] = json_encode($global_props, 256);
  14379. }
  14380. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  14381. dLog('deepseek')->info('剧集数据同步到全局完成', [
  14382. 'anime_id' => $anime_id,
  14383. 'roles_added' => $roles_added,
  14384. 'roles_updated' => $roles_updated,
  14385. 'scenes_added' => $scenes_added,
  14386. 'props_added' => $props_added,
  14387. 'global_roles_count' => count($global_roles),
  14388. 'global_scenes_count' => count($global_scenes),
  14389. 'global_props_count' => count($global_props)
  14390. ]);
  14391. }
  14392. return true;
  14393. }
  14394. /**
  14395. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  14396. *
  14397. * @param int $anime_id 动漫对话ID
  14398. * @param int $episode_id 分集ID
  14399. * @return bool
  14400. */
  14401. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  14402. // 获取全局角色和场景数据
  14403. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  14404. if (!$anime) {
  14405. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  14406. return false;
  14407. }
  14408. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  14409. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  14410. // 获取指定的分集
  14411. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  14412. if (!$episode) {
  14413. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  14414. return false;
  14415. }
  14416. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  14417. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  14418. $roles_updated = false;
  14419. $scenes_updated = false;
  14420. // 继承角色的task_id、task_status和url
  14421. foreach ($episode_roles as &$episode_role) {
  14422. $episode_role_name = getProp($episode_role, 'role');
  14423. $episode_description = getProp($episode_role, 'description');
  14424. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  14425. $episode_url = getProp($episode_role, 'url');
  14426. // 跳过旁白角色
  14427. if ($episode_role_name == '旁白') {
  14428. continue;
  14429. }
  14430. // 如果剧集中已有URL,跳过
  14431. if (!empty($episode_url)) {
  14432. continue;
  14433. }
  14434. // 遍历全局角色数据,查找匹配的角色
  14435. foreach ($global_roles as $global_role) {
  14436. $global_role_name = getProp($global_role, 'role');
  14437. $global_description = getProp($global_role, 'description');
  14438. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  14439. $global_url = getProp($global_role, 'url');
  14440. $global_task_id = getProp($global_role, 'task_id');
  14441. $global_task_status = getProp($global_role, 'task_status');
  14442. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  14443. if ($episode_role_name == $global_role_name
  14444. && $episode_description == $global_description
  14445. && $episode_pic_prompt == $global_pic_prompt) {
  14446. // 继承 task_id、task_status 和 url
  14447. if (!empty($global_task_id)) {
  14448. $episode_role['task_id'] = $global_task_id;
  14449. $episode_role['task_status'] = $global_task_status;
  14450. $roles_updated = true;
  14451. dLog('deepseek')->info('剧集角色继承全局task_id', [
  14452. 'episode_id' => $episode_id,
  14453. 'role' => $episode_role_name,
  14454. 'task_id' => $global_task_id,
  14455. 'task_status' => $global_task_status
  14456. ]);
  14457. }
  14458. if (!empty($global_url)) {
  14459. $episode_role['url'] = $global_url;
  14460. $roles_updated = true;
  14461. dLog('deepseek')->info('剧集角色继承全局url', [
  14462. 'episode_id' => $episode_id,
  14463. 'role' => $episode_role_name,
  14464. 'url' => $global_url
  14465. ]);
  14466. }
  14467. break;
  14468. }
  14469. }
  14470. }
  14471. // 继承场景的task_id、task_status和url
  14472. foreach ($episode_scenes as &$episode_scene) {
  14473. $episode_scene_name = getProp($episode_scene, 'scene');
  14474. $episode_description = getProp($episode_scene, 'description');
  14475. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  14476. $episode_url = getProp($episode_scene, 'url');
  14477. // 如果剧集中已有URL,跳过
  14478. if (!empty($episode_url)) {
  14479. continue;
  14480. }
  14481. // 遍历全局场景数据,查找匹配的场景
  14482. foreach ($global_scenes as $global_scene) {
  14483. $global_scene_name = getProp($global_scene, 'scene');
  14484. $global_description = getProp($global_scene, 'description');
  14485. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  14486. $global_url = getProp($global_scene, 'url');
  14487. $global_task_id = getProp($global_scene, 'task_id');
  14488. $global_task_status = getProp($global_scene, 'task_status');
  14489. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  14490. if ($episode_scene_name == $global_scene_name
  14491. && $episode_description == $global_description
  14492. && $episode_pic_prompt == $global_pic_prompt) {
  14493. // 继承 task_id、task_status 和 url
  14494. if (!empty($global_task_id)) {
  14495. $episode_scene['task_id'] = $global_task_id;
  14496. $episode_scene['task_status'] = $global_task_status;
  14497. $scenes_updated = true;
  14498. dLog('deepseek')->info('剧集场景继承全局task_id', [
  14499. 'episode_id' => $episode_id,
  14500. 'scene' => $episode_scene_name,
  14501. 'task_id' => $global_task_id,
  14502. 'task_status' => $global_task_status
  14503. ]);
  14504. }
  14505. if (!empty($global_url)) {
  14506. $episode_scene['url'] = $global_url;
  14507. $scenes_updated = true;
  14508. dLog('deepseek')->info('剧集场景继承全局url', [
  14509. 'episode_id' => $episode_id,
  14510. 'scene' => $episode_scene_name,
  14511. 'url' => $global_url
  14512. ]);
  14513. }
  14514. break;
  14515. }
  14516. }
  14517. }
  14518. // 如果有更新,则保存到数据库
  14519. if ($roles_updated || $scenes_updated) {
  14520. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  14521. if ($roles_updated) {
  14522. $update_data['roles'] = json_encode($episode_roles, 256);
  14523. }
  14524. if ($scenes_updated) {
  14525. $update_data['scenes'] = json_encode($episode_scenes, 256);
  14526. }
  14527. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  14528. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  14529. 'episode_id' => $episode_id,
  14530. 'roles_updated' => $roles_updated,
  14531. 'scenes_updated' => $scenes_updated
  14532. ]);
  14533. }
  14534. return true;
  14535. }
  14536. public function chatChangeImg($data) {
  14537. // 文生文计费预检(normal 档)
  14538. $uid = Site::getUid();
  14539. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'normal'), $uid);
  14540. $segment = getProp($data, 'segment');
  14541. $segment_content = getProp($segment, 'segment_content');
  14542. $prompt = getProp($data, 'prompt');
  14543. $ref_img = getProp($data, 'ref_img');
  14544. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  14545. // 处理文本模型
  14546. $model = getProp($data, 'model');
  14547. if (!$model) {
  14548. // 用户没有输入,从anime表获取
  14549. $segment_id = getProp($segment, 'segment_id');
  14550. if ($segment_id) {
  14551. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  14552. if ($episode_id) {
  14553. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  14554. if ($anime_id) {
  14555. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  14556. }
  14557. }
  14558. }
  14559. if (!$model) {
  14560. // anime表也没有,使用默认值
  14561. $model = 'doubao-seed-2-0-mini-260215';
  14562. }
  14563. }
  14564. // 验证模型是否在可用模型表中
  14565. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  14566. $model = 'doubao-seed-2-0-mini-260215';
  14567. }
  14568. $messages[] =
  14569. [
  14570. 'role' => 'user',
  14571. 'content' => $question
  14572. ];
  14573. $post_data = [
  14574. 'model' => $model,
  14575. 'messages' => $messages,
  14576. // 'max_tokens' => 8192,
  14577. 'temperature' => 0.7,
  14578. 'frequency_penalty' => 0,
  14579. 'presence_penalty' => 0,
  14580. 'response_format' => ['type' => 'text'],
  14581. 'stream' => false // 是否启用流式输出
  14582. ];
  14583. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  14584. if (is_array($chatResult)) {
  14585. extract($chatResult);
  14586. }else {
  14587. Utils::throwError('20003: 接口调用失败!');
  14588. }
  14589. // 文生文成功计费(normal 档):同时记录积分与 token 明细
  14590. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  14591. 'model' => $model,
  14592. 'source' => 'chatChangeImg',
  14593. ], 'normal');
  14594. return [
  14595. 'type' => 'done',
  14596. // 'episode' => $episode,
  14597. 'answer' => $fullContent,
  14598. 'reasoning' => $fullReasoningContent,
  14599. 'usage' => $usage
  14600. ];
  14601. }
  14602. /**
  14603. * 仅调用 deepseek 对话接口(非流式)
  14604. *
  14605. * @param array $post_data
  14606. * @param int $timeout
  14607. * @return array
  14608. */
  14609. private function chatOnly($post_data, $timeout = 1800) {
  14610. $post_data['max_tokens'] = 300000;
  14611. $client = new Client(['timeout' => $timeout, 'verify' => false]);
  14612. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  14613. $response = $result->getBody()->getContents();
  14614. $response_arr = json_decode($response, true);
  14615. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  14616. $fullContent = '';
  14617. $fullReasoningContent = [];
  14618. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  14619. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  14620. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  14621. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  14622. }
  14623. return [
  14624. 'fullContent' => $fullContent,
  14625. 'fullReasoningContent' => $fullReasoningContent,
  14626. 'usage' => $usage
  14627. ];
  14628. }
  14629. /**
  14630. * 用 deepseek-v4-flash 非流式分析报错,返回不超过50字的用户友好提示
  14631. *
  14632. * @param string $errorMessage
  14633. * @return string|null
  14634. */
  14635. public function analyzeErrorMessage($errorMessage)
  14636. {
  14637. try {
  14638. $post_data = [
  14639. 'model' => 'deepseek-v4-flash',
  14640. 'messages' => [
  14641. [
  14642. 'role' => 'system',
  14643. 'content' => '你是视频生成任务的报错分析助手。请根据用户给出的原始报错,用一句中文提示告诉用户问题原因和下一步怎么做,不超过50个字,直接输出提示内容,不要解释、不要输出代码。',
  14644. ],
  14645. [
  14646. 'role' => 'user',
  14647. 'content' => (string)$errorMessage,
  14648. ],
  14649. ],
  14650. 'temperature' => 0.3,
  14651. 'frequency_penalty' => 0,
  14652. 'presence_penalty' => 0,
  14653. 'response_format' => ['type' => 'text'],
  14654. 'stream' => false,
  14655. ];
  14656. $result = $this->chatOnly($post_data, 8);
  14657. // 调用成功即记录 token 使用明细(不扣积分),保证错误分析这类隐性 AI 调用进入统计口径
  14658. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  14659. 'model' => 'deepseek-v4-flash',
  14660. 'source' => 'analyzeErrorMessage',
  14661. ], 'deepseek-v4-flash');
  14662. $content = trim((string)($result['fullContent'] ?? ''));
  14663. if ($content === '') {
  14664. return null;
  14665. }
  14666. return mb_substr($content, 0, 50);
  14667. } catch (\Exception $e) {
  14668. dLog('deepseek')->error('视频任务报错分析失败: ' . $e->getMessage(), [
  14669. 'error_message' => $errorMessage
  14670. ]);
  14671. return null;
  14672. }
  14673. }
  14674. // 仅调用 GPT-5.4 对话接口(非流式)
  14675. private function gpt54ChatOnly($post_data) {
  14676. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  14677. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  14678. // gpt-5.4 中转已下线,强制映射到 gpt-5.6-sol
  14679. if ($modelName === 'gpt-5.4') {
  14680. $modelName = 'gpt-5.6-terra';
  14681. $post_data['model'] = $modelName;
  14682. }
  14683. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  14684. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  14685. $usedLunaFallback = false;
  14686. if (empty($apiKey)) {
  14687. Utils::throwError('20003:GPT-5.4 API Key未配置');
  14688. }
  14689. // 先探活,服务不可用时自动重试
  14690. $this->ensureGptServiceAvailable($apiKey);
  14691. $client = new Client(['timeout' => 1800, 'verify' => false]);
  14692. // 移除 thinking 参数,GPT-5.4 不支持
  14693. if (isset($post_data['thinking'])) {
  14694. unset($post_data['thinking']);
  14695. }
  14696. if (isset($post_data['reasoning_effort'])) {
  14697. unset($post_data['reasoning_effort']);
  14698. }
  14699. // GPT-5.x(推理型上游)只接受默认 temperature(1),传入其他值会返回 400:
  14700. // Unsupported value: 'temperature' does not support 1.35 with this model.
  14701. // Only the default (1) value is supported.
  14702. unset($post_data['temperature']);
  14703. $post_data['max_completion_tokens'] = 100000;
  14704. // GPT-5.x 上游不支持 max_tokens,与 gpt54StreamResponse 保持一致,显式移除避免 400。
  14705. unset($post_data['max_tokens']);
  14706. // GPT-5.x 上游不接受 frequency_penalty / presence_penalty,移除默认值 0 不影响行为。
  14707. unset($post_data['frequency_penalty'], $post_data['presence_penalty']);
  14708. // 确保 stream 为 false
  14709. $post_data['stream'] = false;
  14710. $maxRetries = $this->gptRetryTimes();
  14711. $interval = $this->gptRetryInterval();
  14712. $attempt = 0;
  14713. while (true) {
  14714. try {
  14715. $headers = [
  14716. 'Authorization' => 'Bearer ' . $apiKey,
  14717. 'Content-Type' => 'application/json'
  14718. ];
  14719. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  14720. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  14721. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  14722. 'json' => $post_data,
  14723. 'headers' => $headers
  14724. ]);
  14725. $response = $result->getBody()->getContents();
  14726. $response_arr = json_decode($response, true);
  14727. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  14728. $fullContent = '';
  14729. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  14730. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  14731. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  14732. }
  14733. return [
  14734. 'fullContent' => $fullContent,
  14735. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  14736. 'usage' => $usage
  14737. ];
  14738. } catch (\Exception $e) {
  14739. // 提前解析上游错误详情,便于日志中记录真实原因(如 content_filter)
  14740. $upstream_error = $this->resolveGptUpstreamError($e);
  14741. // 报错或超时时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  14742. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  14743. $usedLunaFallback = true;
  14744. $apiKey = $lunaApiKey;
  14745. dLog('deepseek')->warning('GPT-5.4 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  14746. continue;
  14747. }
  14748. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  14749. $error_context = ['error' => $e->getMessage()];
  14750. if ($upstream_error['status'] || $upstream_error['body'] !== '') {
  14751. $error_context['upstream_status'] = $upstream_error['status'];
  14752. $error_context['upstream_code'] = $upstream_error['code'];
  14753. $error_context['upstream_body'] = $upstream_error['body'];
  14754. }
  14755. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage(), $error_context);
  14756. logDB('deepseek', 'error', 'GPT-5.4 请求失败', $error_context);
  14757. throw $e;
  14758. }
  14759. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  14760. 'retry' => $attempt + 1,
  14761. 'max_retries' => $maxRetries,
  14762. 'error' => $e->getMessage()
  14763. ]);
  14764. sleep($interval);
  14765. $attempt++;
  14766. }
  14767. }
  14768. }
  14769. public function getContentByBid($bid) {
  14770. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  14771. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  14772. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  14773. $content = '';
  14774. foreach ($chapters as $chapter) {
  14775. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  14776. }
  14777. return $content;
  14778. }
  14779. public function getContentByScriptId($script_id) {
  14780. $content = '';
  14781. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  14782. if ($contents) {
  14783. $content = implode(PHP_EOL, $contents);
  14784. }else {
  14785. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  14786. }
  14787. return $content;
  14788. }
  14789. /**
  14790. * 根据文件类型提取文本内容
  14791. *
  14792. * @param mixed $file 文件对象或文件路径
  14793. * @return string
  14794. */
  14795. public function extractFileContent($file) {
  14796. // 获取文件路径和扩展名
  14797. if (is_string($file)) {
  14798. $filePath = $file;
  14799. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  14800. } else {
  14801. // Laravel UploadedFile 对象
  14802. $filePath = $file->getRealPath();
  14803. $extension = strtolower($file->getClientOriginalExtension());
  14804. }
  14805. $content = '';
  14806. switch ($extension) {
  14807. case 'txt':
  14808. $content = $this->extractTxtContent($filePath);
  14809. break;
  14810. case 'pdf':
  14811. $content = $this->extractPdfContent($filePath);
  14812. break;
  14813. case 'doc':
  14814. case 'docx':
  14815. $content = $this->extractWordContent($filePath);
  14816. break;
  14817. // case 'jpg':
  14818. // case 'jpeg':
  14819. // case 'png':
  14820. // case 'gif':
  14821. // case 'bmp':
  14822. // case 'webp':
  14823. // $content = $this->extractImageContent($filePath);
  14824. // break;
  14825. default:
  14826. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  14827. }
  14828. // 移除非法 UTF-8 字节,避免后续 JSON 编码或正则解析异常
  14829. if (!mb_check_encoding($content, 'UTF-8')) {
  14830. $cleaned = @iconv('UTF-8', 'UTF-8//IGNORE', $content);
  14831. $content = $cleaned === false ? $content : $cleaned;
  14832. }
  14833. return $content;
  14834. }
  14835. /**
  14836. * 提取 TXT 文件内容
  14837. */
  14838. private function extractTxtContent($filePath) {
  14839. if (!file_exists($filePath)) {
  14840. Utils::throwError('20003:文件不存在');
  14841. }
  14842. $content = file_get_contents($filePath);
  14843. // 尝试检测并转换编码
  14844. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  14845. if ($encoding && $encoding !== 'UTF-8') {
  14846. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  14847. }
  14848. return trim($content);
  14849. }
  14850. /**
  14851. * 提取 PDF 文件内容
  14852. */
  14853. private function extractPdfContent($filePath) {
  14854. if (!file_exists($filePath)) {
  14855. Utils::throwError('20003:文件不存在');
  14856. }
  14857. try {
  14858. $parser = new PdfParser();
  14859. $pdf = $parser->parseFile($filePath);
  14860. $content = $pdf->getText();
  14861. return trim($content);
  14862. } catch (\Exception $e) {
  14863. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  14864. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  14865. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  14866. }
  14867. }
  14868. /**
  14869. * 提取 Word 文件内容(支持 doc 和 docx)
  14870. */
  14871. private function extractWordContent($filePath) {
  14872. if (!file_exists($filePath)) {
  14873. Utils::throwError('20003:文件不存在');
  14874. }
  14875. try {
  14876. $phpWord = WordIOFactory::load($filePath);
  14877. $content = '';
  14878. foreach ($phpWord->getSections() as $section) {
  14879. foreach ($section->getElements() as $element) {
  14880. $content .= $this->extractWordElementText($element);
  14881. // 段落边界补换行(段落内的软换行已在元素递归中处理)
  14882. $content .= "\n";
  14883. }
  14884. }
  14885. return trim($content);
  14886. } catch (\Exception $e) {
  14887. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  14888. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  14889. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  14890. }
  14891. }
  14892. /**
  14893. * 递归提取 Word 元素中的文本
  14894. */
  14895. private function extractWordElementText($element) {
  14896. $text = '';
  14897. if ($element instanceof \PhpOffice\PhpWord\Element\TextBreak
  14898. || $element instanceof \PhpOffice\PhpWord\Element\LineBreak) {
  14899. // 软换行:保留 Word 中的换行显示,避免"第X集"标题与正文粘连
  14900. $text .= "\n";
  14901. } elseif (method_exists($element, 'getElements')) {
  14902. foreach ($element->getElements() as $childElement) {
  14903. $text .= $this->extractWordElementText($childElement);
  14904. }
  14905. } elseif (method_exists($element, 'getText')) {
  14906. $text .= $element->getText();
  14907. }
  14908. return $text;
  14909. }
  14910. /**
  14911. * 提取图片内容(使用火山引擎 OCR)
  14912. */
  14913. private function extractImageContent($filePath) {
  14914. if (!file_exists($filePath)) {
  14915. Utils::throwError('20003:文件不存在');
  14916. }
  14917. try {
  14918. // 读取图片并转换为 base64
  14919. $imageData = file_get_contents($filePath);
  14920. $base64Image = base64_encode($imageData);
  14921. // 调用火山引擎 OCR 服务
  14922. $content = $this->callVolcEngineOCR($base64Image);
  14923. return trim($content);
  14924. } catch (\Exception $e) {
  14925. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  14926. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  14927. Utils::throwError('20003:图片识别失败');
  14928. }
  14929. }
  14930. /**
  14931. * 调用火山引擎 OCR 服务识别图片文字
  14932. *
  14933. * @param string $base64Image base64 编码的图片数据
  14934. * @return string 识别的文字内容
  14935. */
  14936. private function callVolcEngineOCR($base64Image) {
  14937. $method = 'POST';
  14938. $service = 'cv';
  14939. $host = 'visual.volcengineapi.com';
  14940. $region = env('VOLC_REGION', 'cn-north-1');
  14941. $access_key = env('VOLC_AK');
  14942. $secret_key = env('VOLC_SK');
  14943. $action = 'OCRNormal';
  14944. $version = '2020-08-26';
  14945. if (!$access_key || !$secret_key) {
  14946. Utils::throwError('20003:请配置火山引擎 AK/SK');
  14947. }
  14948. // 请求体
  14949. $body = json_encode([
  14950. 'image_base64' => $base64Image
  14951. ]);
  14952. // 生成签名
  14953. $headers = $this->getVolcEngineSignHeaders(
  14954. $method, $service, $host, $region,
  14955. "Action={$action}&Version={$version}",
  14956. $access_key, $secret_key, $body
  14957. );
  14958. $client = new Client(['timeout' => 1800, 'verify' => false]);
  14959. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  14960. 'headers' => $headers,
  14961. 'body' => $body
  14962. ]);
  14963. $response_arr = json_decode($response->getBody()->getContents(), true);
  14964. // 提取识别的文字
  14965. $textLines = [];
  14966. if (isset($response_arr['data']['line_texts'])) {
  14967. $textLines = $response_arr['data']['line_texts'];
  14968. } elseif (isset($response_arr['data']['ocr_infos'])) {
  14969. foreach ($response_arr['data']['ocr_infos'] as $info) {
  14970. if (isset($info['text'])) {
  14971. $textLines[] = $info['text'];
  14972. }
  14973. }
  14974. }
  14975. if (empty($textLines)) {
  14976. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  14977. return '';
  14978. }
  14979. return implode("\n", $textLines);
  14980. }
  14981. /**
  14982. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  14983. */
  14984. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  14985. $contentType = 'application/json';
  14986. $accept = 'application/json';
  14987. // 获取当前UTC时间
  14988. $t = new DateTime('now', new DateTimeZone('UTC'));
  14989. $xDate = $t->format('Ymd\THis\Z');
  14990. $dateStamp = $t->format('Ymd');
  14991. // 计算 body 的 sha256 哈希
  14992. $payloadHash = hash('sha256', $body);
  14993. // 1. 拼接规范请求串
  14994. $canonicalUri = '/';
  14995. $canonicalQueryString = $queryString;
  14996. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  14997. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  14998. $canonicalRequest = implode("\n", [
  14999. $method,
  15000. $canonicalUri,
  15001. $canonicalQueryString,
  15002. $canonicalHeaders,
  15003. $signedHeaders,
  15004. $payloadHash
  15005. ]);
  15006. // 2. 拼接待签名字符串
  15007. $algorithm = 'HMAC-SHA256';
  15008. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  15009. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  15010. $stringToSign = implode("\n", [
  15011. $algorithm,
  15012. $xDate,
  15013. $credentialScope,
  15014. $hashedCanonicalRequest
  15015. ]);
  15016. // 3. 计算签名
  15017. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  15018. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  15019. // 4. 添加签名到请求头
  15020. $authorizationHeader = sprintf(
  15021. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  15022. $algorithm,
  15023. $access_key,
  15024. $credentialScope,
  15025. $signedHeaders,
  15026. $signature
  15027. );
  15028. return [
  15029. 'Accept' => $accept,
  15030. 'Content-Type' => $contentType,
  15031. 'Host' => $host,
  15032. 'X-Date' => $xDate,
  15033. 'X-Content-Sha256'=> $payloadHash,
  15034. 'Authorization' => $authorizationHeader
  15035. ];
  15036. }
  15037. public function generateScriptWords($cid, $model = 'r1') {
  15038. ini_set('max_execution_time', 0);
  15039. if (!$cid) Utils::throwError('20003: 请选择章节!');
  15040. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  15041. // 模型兼容性处理和思考模式设置
  15042. $thinkingMode = 'disabled';
  15043. $reasoningEffort = 'high';
  15044. if ($model == 'r1') {
  15045. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  15046. $thinkingMode = 'enabled';
  15047. } else {
  15048. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  15049. $thinkingMode = 'disabled';
  15050. }
  15051. $messages = [
  15052. [
  15053. 'role' => 'system',
  15054. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  15055. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  15056. 2.非对话部分请全部用旁白角色代替
  15057. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  15058. ],
  15059. [
  15060. 'role' => 'user',
  15061. 'content' => $content
  15062. ]
  15063. ];
  15064. $post_data = [
  15065. 'model' => $model,
  15066. 'messages' => $messages,
  15067. // 'max_tokens' => 8192,
  15068. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  15069. 'frequency_penalty' => 0,
  15070. 'presence_penalty' => 0,
  15071. 'thinking' => ['type' => $thinkingMode],
  15072. 'response_format' => [
  15073. 'type' => 'text'
  15074. ],
  15075. 'stream' => false
  15076. ];
  15077. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  15078. // 根据模型类型选择调用方法
  15079. $fullContent = '';
  15080. $usage = [];
  15081. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  15082. if (is_array($chatResult)) {
  15083. $fullContent = $chatResult['fullContent'];
  15084. $usage = $chatResult['usage'] ?? [];
  15085. }
  15086. // 仅记录 token 使用明细(不扣积分)
  15087. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  15088. 'model' => $model,
  15089. 'cid' => $cid,
  15090. 'source' => 'generateScriptWords',
  15091. ], $model);
  15092. return $fullContent;
  15093. }
  15094. /**
  15095. * 智能化解析集数信息
  15096. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  15097. *
  15098. * @param string $prompt 用户输入的提示词
  15099. * @return int|null 解析出的集数,如果没有找到则返回null
  15100. */
  15101. private function extractEpisodeNumber($prompt)
  15102. {
  15103. if (empty($prompt)) {
  15104. return null;
  15105. }
  15106. // 定义各种可能的表达模式
  15107. $patterns = [
  15108. // 基本模式:改成N集、调整成N集、修改成N集
  15109. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  15110. // 扩展模式:分成N集、拆分成N集、分割成N集
  15111. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  15112. // 数量模式:N集、共N集、总共N集
  15113. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  15114. // 制作模式:制作N集、生成N集、创建N集
  15115. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  15116. // 计划模式:计划N集、预计N集、打算N集
  15117. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  15118. // 需要模式:需要N集、要N集
  15119. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  15120. // 中文数字模式:改成三集、调整成五集等
  15121. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  15122. // 英文数字模式
  15123. '/(?: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',
  15124. ];
  15125. // 中文数字转阿拉伯数字的映射
  15126. $chineseNumbers = [
  15127. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  15128. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  15129. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  15130. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  15131. ];
  15132. // 逐个尝试匹配模式
  15133. foreach ($patterns as $pattern) {
  15134. if (preg_match($pattern, $prompt, $matches)) {
  15135. $number = trim($matches[1]);
  15136. // 如果是中文数字,转换为阿拉伯数字
  15137. if (isset($chineseNumbers[$number])) {
  15138. return $chineseNumbers[$number];
  15139. }
  15140. // 如果是阿拉伯数字,直接返回
  15141. if (is_numeric($number)) {
  15142. $episodeNum = intval($number);
  15143. // 合理性检查:集数应该在1-100之间
  15144. if ($episodeNum >= 1 && $episodeNum <= 100) {
  15145. return $episodeNum;
  15146. }
  15147. }
  15148. }
  15149. }
  15150. return null;
  15151. }
  15152. /**
  15153. * 调用火山引擎对话(Chat) API
  15154. *
  15155. * @param array $params 包含以下参数:
  15156. * - model: 模型ID(必填)
  15157. * - messages: 消息列表(必填)
  15158. * - stream: 是否流式输出(可选,默认false)
  15159. * - max_tokens: 最大输出token数(可选)
  15160. * - temperature: 采样温度(可选,默认1)
  15161. * - top_p: 核采样概率(可选,默认0.7)
  15162. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  15163. * - presence_penalty: 存在惩罚系数(可选,默认0)
  15164. * - stop: 停止词(可选)
  15165. * - tools: 工具列表(可选)
  15166. * @return array|Generator 非流式返回数组,流式返回生成器
  15167. */
  15168. public function volcEngineChatCompletion(array $params)
  15169. {
  15170. // 百度 GLM 已由 dispatchStreamByModel / dispatchChatOnlyByModel 统一分发,此处不再转发
  15171. $frontModel = getProp($params, 'model', '');
  15172. if (in_array($frontModel, $this->baidu_glm_text_models, true)) {
  15173. Utils::throwError('20003:百度GLM模型请使用统一分发方法dispatchStreamByModel/dispatchChatOnlyByModel调用');
  15174. }
  15175. $apiKey = env('VOLC_AI_API_KEY');
  15176. if (empty($apiKey)) {
  15177. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  15178. }
  15179. // 构建请求参数
  15180. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  15181. $requestData = [
  15182. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  15183. 'messages' => $params['messages'] ?? [],
  15184. ];
  15185. if (!in_array($originalModel, $this->valid_text_models)) {
  15186. Utils::throwError('20003:该模型不支持!');
  15187. }
  15188. // 添加可选参数
  15189. if (isset($params['stream'])) {
  15190. $requestData['stream'] = $params['stream'];
  15191. }
  15192. if (isset($params['stream_options'])) {
  15193. $requestData['stream_options'] = $params['stream_options'];
  15194. }
  15195. if (isset($params['max_tokens'])) {
  15196. $requestData['max_tokens'] = $params['max_tokens'];
  15197. }else if (isset($params['max_completion_tokens'])) {
  15198. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  15199. }else {
  15200. $requestData['max_completion_tokens'] = 100000;
  15201. }
  15202. if (isset($params['temperature'])) {
  15203. $requestData['temperature'] = $params['temperature'];
  15204. }
  15205. if (isset($params['top_p'])) {
  15206. $requestData['top_p'] = $params['top_p'];
  15207. }
  15208. if (isset($params['frequency_penalty'])) {
  15209. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  15210. }
  15211. if (isset($params['presence_penalty'])) {
  15212. $requestData['presence_penalty'] = $params['presence_penalty'];
  15213. }
  15214. if (isset($params['stop'])) {
  15215. $requestData['stop'] = $params['stop'];
  15216. }
  15217. if (isset($params['tools'])) {
  15218. $requestData['tools'] = $params['tools'];
  15219. }
  15220. if (isset($params['tool_choice'])) {
  15221. $requestData['tool_choice'] = $params['tool_choice'];
  15222. }
  15223. if (isset($params['response_format'])) {
  15224. $requestData['response_format'] = $params['response_format'];
  15225. }
  15226. if (isset($params['thinking'])) {
  15227. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  15228. if (is_array($params['thinking'])) {
  15229. $requestData['thinking'] = $params['thinking'];
  15230. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  15231. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  15232. }
  15233. } else {
  15234. $requestData['thinking'] = ['type' => $params['thinking']];
  15235. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  15236. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  15237. }
  15238. }
  15239. } else {
  15240. $requestData['thinking'] = ['type' => 'disabled'];
  15241. }
  15242. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  15243. $client = new Client(['verify' => false, 'timeout' => 1800]);
  15244. try {
  15245. // 判断是否为流式输出
  15246. $isStream = isset($params['stream']) && $params['stream'] === true;
  15247. if ($isStream) {
  15248. // 流式输出
  15249. // 流式请求默认声明返回 usage(未显式传参时)
  15250. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  15251. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  15252. } else {
  15253. // 非流式输出
  15254. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  15255. 'headers' => [
  15256. 'Authorization' => 'Bearer ' . $apiKey,
  15257. 'Content-Type' => 'application/json',
  15258. ],
  15259. 'json' => $requestData
  15260. ]);
  15261. $responseData = json_decode($response->getBody(), true);
  15262. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  15263. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  15264. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  15265. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  15266. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  15267. }
  15268. return [
  15269. 'fullContent' => $fullContent,
  15270. 'fullReasoningContent' => $fullReasoningContent,
  15271. 'usage' => $usage
  15272. ];
  15273. }
  15274. } catch (\Exception $e) {
  15275. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  15276. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  15277. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  15278. }
  15279. }
  15280. /**
  15281. * 火山引擎对话API流式输出
  15282. *
  15283. * @param Client $client HTTP客户端
  15284. * @param string $apiKey API密钥
  15285. * @param array $requestData 请求数据
  15286. * @return Generator
  15287. */
  15288. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  15289. {
  15290. try {
  15291. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  15292. 'headers' => [
  15293. 'Authorization' => 'Bearer ' . $apiKey,
  15294. 'Content-Type' => 'application/json',
  15295. ],
  15296. 'json' => $requestData,
  15297. 'stream' => true
  15298. ]);
  15299. $body = $response->getBody();
  15300. $buffer = '';
  15301. $fullContent = '';
  15302. $fullReasoningContent = '';
  15303. $usage = [];
  15304. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  15305. // 逐行读取流式响应
  15306. while (!$body->eof()) {
  15307. $chunk = $body->read(1024);
  15308. $buffer .= $chunk;
  15309. // 按行分割
  15310. $lines = explode("\n", $buffer);
  15311. $buffer = array_pop($lines);
  15312. foreach ($lines as $line) {
  15313. $line = trim($line);
  15314. if (empty($line)) {
  15315. continue;
  15316. }
  15317. // 检查是否是SSE数据行
  15318. if (strpos($line, 'data: ') !== 0) {
  15319. continue;
  15320. }
  15321. $data = substr($line, 6);
  15322. if ($data === '[DONE]') {
  15323. dLog('deepseek')->info('收到结束标记');
  15324. break 2;
  15325. }
  15326. try {
  15327. $json = json_decode($data, true);
  15328. if (json_last_error() !== JSON_ERROR_NONE) {
  15329. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  15330. continue;
  15331. }
  15332. if (isset($json['choices'][0]['delta'])) {
  15333. $delta = $json['choices'][0]['delta'];
  15334. // 处理思维链内容
  15335. if (isset($delta['reasoning_content'])) {
  15336. $fullReasoningContent .= $delta['reasoning_content'];
  15337. yield [
  15338. 'type' => 'reasoning',
  15339. 'content' => $delta['reasoning_content'],
  15340. 'full_reasoning' => $fullReasoningContent
  15341. ];
  15342. }
  15343. // 处理回答内容
  15344. if (isset($delta['content'])) {
  15345. $fullContent .= $delta['content'];
  15346. yield [
  15347. 'type' => 'content',
  15348. 'content' => $delta['content'],
  15349. ];
  15350. }
  15351. }
  15352. // 获取使用统计信息
  15353. if (isset($json['usage'])) {
  15354. $usage = $json['usage'];
  15355. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  15356. }
  15357. } catch (\Exception $e) {
  15358. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  15359. continue;
  15360. }
  15361. }
  15362. }
  15363. dLog('deepseek')->info('流式读取完成', [
  15364. 'content_length' => strlen($fullContent),
  15365. 'reasoning_length' => strlen($fullReasoningContent)
  15366. ]);
  15367. yield [
  15368. 'type' => 'done',
  15369. 'full_content' => $fullContent,
  15370. 'full_reasoning' => $fullReasoningContent,
  15371. 'usage' => $usage
  15372. ];
  15373. } catch (\Exception $e) {
  15374. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  15375. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  15376. throw $e;
  15377. }
  15378. }
  15379. /**
  15380. * 检查并创建图片生成任务
  15381. *
  15382. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  15383. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  15384. * @param string $nameKey 资源名称字段('role' 或 'scene')
  15385. * @param string $art_style 美术风格
  15386. * @return array 更新后的资源列表
  15387. */
  15388. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  15389. {
  15390. // 确保参数为数组
  15391. $merged_items = is_array($merged_items) ? $merged_items : [];
  15392. $global_items = is_array($global_items) ? $global_items : [];
  15393. // 构建全局资源映射表,用于快速查找
  15394. $global_map = [];
  15395. foreach ($global_items as $item) {
  15396. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  15397. if ($itemKey === '') {
  15398. continue;
  15399. }
  15400. $global_map[$itemKey] = $item;
  15401. }
  15402. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  15403. foreach ($merged_items as &$item) {
  15404. $item_name = getProp($item, $nameKey);
  15405. $item_description = getProp($item, 'description');
  15406. // $item_url = getProp($item, 'url');
  15407. // // 如果已有图片URL,跳过
  15408. // if (!empty($item_url)) {
  15409. // continue;
  15410. // }
  15411. // 如果是旁白角色,跳过
  15412. if ($nameKey === 'role' && $item_name === '旁白') {
  15413. continue;
  15414. }
  15415. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  15416. if ($itemKey === '') {
  15417. continue;
  15418. }
  15419. $need_create_task = false;
  15420. // 条件1:在全局资源中找不到匹配的名称
  15421. if (!isset($global_map[$itemKey])) {
  15422. $need_create_task = true;
  15423. } else {
  15424. // 条件2:名称匹配但描述或 pic_prompt 不一致
  15425. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  15426. $current_description = trim((string)$item_description);
  15427. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  15428. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  15429. // 如果 description 或 pic_prompt 有变化,需要重新生成
  15430. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  15431. $need_create_task = true;
  15432. }
  15433. }
  15434. // 如果需要创建任务,调用图片生成服务
  15435. if ($need_create_task) {
  15436. try {
  15437. // 优先使用 pic_prompt,如果没有则使用 description
  15438. $pic_prompt = getProp($item, 'pic_prompt');
  15439. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  15440. // 添加美术风格前缀
  15441. if ($art_style) {
  15442. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  15443. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  15444. $description = "{$prefix}:{$description}";
  15445. }
  15446. $params = [
  15447. 'prompt' => $description,
  15448. 'ref_img_urls' => []
  15449. ];
  15450. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  15451. $task_id = $task->id;
  15452. if ($task_id) {
  15453. $item['task_id'] = $task_id;
  15454. $item['task_status'] = 'processing';
  15455. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  15456. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  15457. }
  15458. } catch (\Exception $e) {
  15459. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  15460. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  15461. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  15462. // 不抛出异常,继续处理其他资源
  15463. }
  15464. }
  15465. }
  15466. return $merged_items;
  15467. }
  15468. /**
  15469. * 同步新出现的主体和场景到全局
  15470. *
  15471. * @param int $anime_id 动漫ID
  15472. * @param array $merged_roles 合并后的角色列表
  15473. * @param array $merged_scenes 合并后的场景列表
  15474. * @param array $global_roles 全局角色列表
  15475. * @param array $global_scenes 全局场景列表
  15476. * @return void
  15477. */
  15478. private function syncNewResourcesToGlobal(
  15479. int $anime_id,
  15480. array $merged_roles,
  15481. array $merged_scenes,
  15482. array $global_roles,
  15483. array $global_scenes
  15484. ): void {
  15485. // 构建全局角色映射表
  15486. $global_role_map = [];
  15487. foreach ($global_roles as $role) {
  15488. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  15489. if ($roleKey !== '') {
  15490. $global_role_map[$roleKey] = $role;
  15491. }
  15492. }
  15493. // 构建全局场景映射表
  15494. $global_scene_map = [];
  15495. foreach ($global_scenes as $scene) {
  15496. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  15497. if ($sceneKey !== '') {
  15498. $global_scene_map[$sceneKey] = $scene;
  15499. }
  15500. }
  15501. $need_update = false;
  15502. $new_global_roles = $global_roles;
  15503. $new_global_scenes = $global_scenes;
  15504. // 检查并添加新角色到全局
  15505. foreach ($merged_roles as $role) {
  15506. $role_name = getProp($role, 'role');
  15507. // 跳过旁白
  15508. if ($role_name === '旁白') {
  15509. continue;
  15510. }
  15511. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  15512. if ($roleKey === '') {
  15513. continue;
  15514. }
  15515. // 如果全局中不存在该角色,添加到全局
  15516. if (!isset($global_role_map[$roleKey])) {
  15517. $new_global_roles[] = [
  15518. 'role' => $role_name,
  15519. 'description' => getProp($role, 'description', ''),
  15520. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  15521. 'voice_name' => getProp($role, 'voice_name', ''),
  15522. 'voice_type' => getProp($role, 'voice_type', ''),
  15523. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  15524. 'url' => getProp($role, 'url', ''),
  15525. 'task_id' => getProp($role, 'task_id', ''),
  15526. 'task_status' => getProp($role, 'task_status', ''),
  15527. ];
  15528. $global_role_map[$roleKey] = true; // 标记已添加
  15529. $need_update = true;
  15530. dLog('deepseek')->info("新角色同步到全局", [
  15531. 'anime_id' => $anime_id,
  15532. 'role' => $role_name,
  15533. 'task_id' => getProp($role, 'task_id', ''),
  15534. ]);
  15535. }
  15536. // else {
  15537. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  15538. // $global_role = $global_role_map[$roleKey];
  15539. // if (is_array($global_role)) {
  15540. // $updated = false;
  15541. // $update_fields = [];
  15542. // // 检查描述是否更新
  15543. // $current_description = trim((string)getProp($role, 'description'));
  15544. // $global_description = trim((string)getProp($global_role, 'description'));
  15545. // if ($current_description !== '' && $current_description !== $global_description) {
  15546. // $updated = true;
  15547. // $update_fields[] = 'description';
  15548. // }
  15549. // // 检查pic_prompt是否更新
  15550. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  15551. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  15552. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  15553. // $updated = true;
  15554. // $update_fields[] = 'pic_prompt';
  15555. // }
  15556. // // 检查图片任务信息是否更新
  15557. // $current_task_id = getProp($role, 'task_id');
  15558. // $global_task_id = getProp($global_role, 'task_id');
  15559. // if ($current_task_id && $current_task_id !== $global_task_id) {
  15560. // $updated = true;
  15561. // $update_fields[] = 'task_id';
  15562. // }
  15563. // // 如果有更新,同步到全局
  15564. // if ($updated) {
  15565. // foreach ($new_global_roles as &$global_role_item) {
  15566. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  15567. // if ($global_role_key === $roleKey) {
  15568. // if (in_array('description', $update_fields)) {
  15569. // $global_role_item['description'] = $current_description;
  15570. // }
  15571. // if (in_array('pic_prompt', $update_fields)) {
  15572. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  15573. // }
  15574. // if (in_array('task_id', $update_fields)) {
  15575. // $global_role_item['task_id'] = $current_task_id;
  15576. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  15577. // $global_role_item['url'] = getProp($role, 'url', '');
  15578. // }
  15579. // break;
  15580. // }
  15581. // }
  15582. // $need_update = true;
  15583. // dLog('deepseek')->info("角色信息更新到全局", [
  15584. // 'anime_id' => $anime_id,
  15585. // 'role' => $role_name,
  15586. // 'update_fields' => implode(',', $update_fields),
  15587. // ]);
  15588. // }
  15589. // }
  15590. // }
  15591. }
  15592. // 检查并添加新场景到全局
  15593. foreach ($merged_scenes as $scene) {
  15594. $scene_name = getProp($scene, 'scene');
  15595. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  15596. if ($sceneKey === '') {
  15597. continue;
  15598. }
  15599. // 如果全局中不存在该场景,添加到全局
  15600. if (!isset($global_scene_map[$sceneKey])) {
  15601. $new_global_scenes[] = [
  15602. 'scene' => $scene_name,
  15603. 'description' => getProp($scene, 'description', ''),
  15604. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  15605. 'url' => getProp($scene, 'url', ''),
  15606. 'task_id' => getProp($scene, 'task_id', ''),
  15607. 'task_status' => getProp($scene, 'task_status', ''),
  15608. ];
  15609. $global_scene_map[$sceneKey] = true; // 标记已添加
  15610. $need_update = true;
  15611. dLog('deepseek')->info("新场景同步到全局", [
  15612. 'anime_id' => $anime_id,
  15613. 'scene' => $scene_name,
  15614. 'task_id' => getProp($scene, 'task_id', ''),
  15615. ]);
  15616. }
  15617. // else {
  15618. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  15619. // $global_scene = $global_scene_map[$sceneKey];
  15620. // if (is_array($global_scene)) {
  15621. // $updated = false;
  15622. // $update_fields = [];
  15623. // // 检查描述是否更新
  15624. // $current_description = trim((string)getProp($scene, 'description'));
  15625. // $global_description = trim((string)getProp($global_scene, 'description'));
  15626. // if ($current_description !== '' && $current_description !== $global_description) {
  15627. // $updated = true;
  15628. // $update_fields[] = 'description';
  15629. // }
  15630. // // 检查pic_prompt是否更新
  15631. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  15632. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  15633. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  15634. // $updated = true;
  15635. // $update_fields[] = 'pic_prompt';
  15636. // }
  15637. // // 检查图片任务信息是否更新
  15638. // $current_task_id = getProp($scene, 'task_id');
  15639. // $global_task_id = getProp($global_scene, 'task_id');
  15640. // if ($current_task_id && $current_task_id !== $global_task_id) {
  15641. // $updated = true;
  15642. // $update_fields[] = 'task_id';
  15643. // }
  15644. // // 如果有更新,同步到全局
  15645. // if ($updated) {
  15646. // foreach ($new_global_scenes as &$global_scene_item) {
  15647. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  15648. // if ($global_scene_key === $sceneKey) {
  15649. // if (in_array('description', $update_fields)) {
  15650. // $global_scene_item['description'] = $current_description;
  15651. // }
  15652. // if (in_array('pic_prompt', $update_fields)) {
  15653. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  15654. // }
  15655. // if (in_array('task_id', $update_fields)) {
  15656. // $global_scene_item['task_id'] = $current_task_id;
  15657. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  15658. // $global_scene_item['url'] = getProp($scene, 'url', '');
  15659. // }
  15660. // break;
  15661. // }
  15662. // }
  15663. // $need_update = true;
  15664. // dLog('deepseek')->info("场景信息更新到全局", [
  15665. // 'anime_id' => $anime_id,
  15666. // 'scene' => $scene_name,
  15667. // 'update_fields' => implode(',', $update_fields),
  15668. // ]);
  15669. // }
  15670. // }
  15671. // }
  15672. }
  15673. // 如果有新增或更新,更新数据库
  15674. if ($need_update) {
  15675. $update_data = [
  15676. 'roles' => json_encode($new_global_roles, 256),
  15677. 'scenes' => json_encode($new_global_scenes, 256),
  15678. 'updated_at' => date('Y-m-d H:i:s'),
  15679. ];
  15680. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  15681. if ($result !== false) {
  15682. dLog('deepseek')->info("全局角色和场景更新成功", [
  15683. 'anime_id' => $anime_id,
  15684. 'roles_count' => count($new_global_roles),
  15685. 'scenes_count' => count($new_global_scenes),
  15686. ]);
  15687. } else {
  15688. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  15689. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  15690. }
  15691. }
  15692. }
  15693. }