DeepSeekService.php 948 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420
  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\JsonSafeRepair;
  7. use App\Libs\Utils;
  8. use GuzzleHttp\Client;
  9. use DateTime;
  10. use DateTimeZone;
  11. use App\Models\MpTaskCenter;
  12. use App\Models\MpUserPointsDetail;
  13. use App\Services\AIGeneration\AIImageGenerationService;
  14. use App\Services\PointsService;
  15. use Illuminate\Support\Facades\DB;
  16. use Illuminate\Support\Facades\Log;
  17. use Illuminate\Support\Facades\Redis;
  18. use OSS\Core\OssException;
  19. use OSS\OssClient;
  20. use Smalot\PdfParser\Parser as PdfParser;
  21. use TCPDF;
  22. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  23. use Predis\Command\Traits\Get\Get;
  24. class DeepSeekService
  25. {
  26. private $url;
  27. private $api_key;
  28. private $sys_message;
  29. private $headers;
  30. private $valid_text_models;
  31. private $gpt_text_models;
  32. private $gemini_text_models;
  33. private $baidu_glm_text_models;
  34. protected $aiImageGenerationService;
  35. protected $pointsService;
  36. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  37. $this->aiImageGenerationService = $aiImageGenerationService;
  38. $this->pointsService = $pointsService;
  39. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  40. $this->api_key = env('DEEPSEEK_API_KEY');
  41. $this->headers = [
  42. 'Authorization' => 'Bearer '.$this->api_key,
  43. 'Content-Type' => 'application/json; charset=UTF-8'
  44. ];
  45. // 火山引擎模型列表
  46. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  47. // GPT文本模型列表
  48. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  49. // Gemini文本模型列表
  50. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  51. // 百度 AI 网关 GLM 文本模型列表
  52. $this->baidu_glm_text_models = BaseConst::BAIDU_GLM_TEXT_MODELS;
  53. $this->sys_message = [
  54. 'role' => 'system',
  55. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  56. 强制要求:\n
  57. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  58. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  59. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  60. 普通要求:\n
  61. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  62. 2.<分集剧本>的要求如下:
  63.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  64.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  65.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  66.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  67. \n\n
  68. 示例如下:\n
  69. ###剧本名:西昆仑
  70. ###故事梗概
  71. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  72. ###剧本亮点
  73. 亮点1:绝境奇药,生死一线
  74. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  75. 亮点2:结拜兄妹,化解尴尬
  76. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  77. 亮点3:纤发夺命,情愫暗涌
  78. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  79. ###人物关系
  80. 阿雪与梁萧之间存在兄妹之情。
  81. ###核心矛盾
  82. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  83. ###主体列表
  84. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  85. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  86. 阴阳球:天地异宝,能化生精气,救人于危难。
  87. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  88. ###美术风格
  89. 基础画风风格词:厚涂古风
  90. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  91. ###场景列表
  92. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  93. ###分集剧本
  94. ##分集01
  95. 第1集: 第一集的标题
  96. 场景描述:地点、时间、场景
  97. 运镜:固定近距离
  98. 出场角色:男主、女主
  99. 台词内容:
  100. 女主: 女主对话
  101. 男主:男主对话
  102. 女主: 女主对话
  103. 男主: 男主对话
  104. ##分集02
  105. 第2集: 第二集的标题
  106. 场景描述:地点、时间、场景
  107. 运镜:固定近距离
  108. 出场角色:男主、女主
  109. 台词内容:
  110. 女主: 女主对话
  111. 男主:男主对话
  112. 女主: 女主对话
  113. 男主: 男主对话"
  114. ];
  115. }
  116. /**
  117. * 通用文生文方法 - 支持多模型流式输出、图片输入;视频输入仅 Gemini 模型支持
  118. *
  119. * @param array $data 请求参数
  120. * @return \Generator 返回生成器,用于流式输出
  121. */
  122. public function generateText($data) {
  123. // 获取请求参数
  124. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  125. $messages = getProp($data, 'messages', []);
  126. $systemPrompt = getProp($data, 'system_prompt', '');
  127. $prompt = getProp($data, 'prompt', '');
  128. $images = getProp($data, 'images', []); // 支持多张图片
  129. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  130. $videos = getProp($data, 'videos', []); // Gemini 支持视频文件
  131. $videoUrls = getProp($data, 'video_urls', []); // Gemini 支持视频URL
  132. $isGeminiModel = in_array($model, $this->gemini_text_models);
  133. if ((!empty($videos) || !empty($videoUrls)) && !$isGeminiModel) {
  134. Utils::throwError('20003:仅Gemini模型支持视频输入');
  135. }
  136. // 计费预检:纯文生文按 normal 档(3);有参考图/视频输入按模型固定价格(图生文)
  137. $uid = Site::getUid();
  138. $chargeModality = '';
  139. $chargePoints = 0;
  140. $hasImageMedia = !empty($images) || !empty($imageUrls)
  141. || $this->messagesContainMedia($messages, ['image_url', 'image']);
  142. $hasVideoMedia = !empty($videos) || !empty($videoUrls)
  143. || $this->messagesContainMedia($messages, ['video_url', 'video']);
  144. if ($hasImageMedia || $hasVideoMedia) {
  145. $chargeModality = $hasVideoMedia ? 'video' : 'image';
  146. $chargePoints = $this->pointsService->getImageChatChargePoints($model);
  147. } else {
  148. $chargeModality = 'text';
  149. $chargePoints = $this->pointsService->getChatChargePoints('', 'normal');
  150. }
  151. if ($chargePoints > 0) {
  152. $this->pointsService->checkUserPointsEnough($chargePoints, $uid);
  153. }
  154. // 如果没有提供messages,则根据system_prompt、content和images构建
  155. if (empty($messages)) {
  156. $messages = [];
  157. // 添加系统提示词
  158. if (!empty($systemPrompt)) {
  159. $messages[] = [
  160. 'role' => 'system',
  161. 'content' => $systemPrompt
  162. ];
  163. }
  164. // 构建用户消息内容(支持文本+图片)
  165. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  166. $userMessage = [
  167. 'role' => 'user',
  168. 'content' => []
  169. ];
  170. // 添加文本内容
  171. if (!empty($prompt)) {
  172. $userMessage['content'][] = [
  173. 'type' => 'text',
  174. 'text' => $prompt
  175. ];
  176. }
  177. // 处理上传的图片文件
  178. if (!empty($images)) {
  179. if (!is_array($images)) {
  180. $images = [$images];
  181. }
  182. foreach ($images as $image) {
  183. $imageBase64 = $this->processImageToBase64($image);
  184. if ($imageBase64) {
  185. $userMessage['content'][] = [
  186. 'type' => 'image_url',
  187. 'image_url' => [
  188. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  189. ]
  190. ];
  191. }
  192. }
  193. }
  194. // 处理图片URL
  195. if (!empty($imageUrls)) {
  196. if (!is_array($imageUrls)) {
  197. $imageUrls = [$imageUrls];
  198. }
  199. foreach ($imageUrls as $url) {
  200. if (!empty($url)) {
  201. $userMessage['content'][] = [
  202. 'type' => 'image_url',
  203. 'image_url' => [
  204. 'url' => $url
  205. ]
  206. ];
  207. }
  208. }
  209. }
  210. // 处理上传的视频文件(仅 Gemini)
  211. if (!empty($videos) && $isGeminiModel) {
  212. if (!is_array($videos)) {
  213. $videos = [$videos];
  214. }
  215. foreach ($videos as $video) {
  216. $inlineData = $this->processMediaToInlineData($video);
  217. if ($inlineData) {
  218. $userMessage['content'][] = [
  219. 'type' => 'video',
  220. 'inline_data' => $inlineData
  221. ];
  222. }
  223. }
  224. }
  225. // 处理视频URL(仅 Gemini)
  226. if (!empty($videoUrls) && $isGeminiModel) {
  227. if (!is_array($videoUrls)) {
  228. $videoUrls = [$videoUrls];
  229. }
  230. foreach ($videoUrls as $url) {
  231. if (!empty($url)) {
  232. $userMessage['content'][] = [
  233. 'type' => 'video_url',
  234. 'video_url' => ['url' => $url]
  235. ];
  236. }
  237. }
  238. }
  239. // 如果只有文本内容,简化为字符串格式
  240. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  241. $userMessage['content'] = $userMessage['content'][0]['text'];
  242. }
  243. $messages[] = $userMessage;
  244. }
  245. }
  246. // 验证messages不为空
  247. if (empty($messages)) {
  248. Utils::throwError('20003:请提供有效的对话内容');
  249. }
  250. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  251. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  252. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  253. if ($model === 'deepseek-chat') {
  254. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  255. $model = 'deepseek-v4-flash';
  256. $thinkingMode = 'disabled';
  257. } elseif ($model === 'deepseek-reasoner') {
  258. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  259. $model = 'deepseek-v4-flash';
  260. $thinkingMode = 'enabled';
  261. }
  262. // 构建请求参数
  263. $post_data = [
  264. 'model' => $model,
  265. 'messages' => $messages,
  266. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  267. 'temperature' => getProp($data, 'temperature', 1),
  268. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  269. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  270. 'thinking' => ['type' => $thinkingMode],
  271. 'stream' => true // 启用流式输出
  272. ];
  273. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  274. // 添加可选参数
  275. if (isset($data['top_p'])) {
  276. $post_data['top_p'] = $data['top_p'];
  277. }
  278. if (isset($data['response_format'])) {
  279. $post_data['response_format'] = $data['response_format'];
  280. }
  281. // 根据模型类型选择流式实现
  282. $streamGenerator = $this->dispatchStreamByModel($post_data);
  283. if ($chargePoints > 0) {
  284. return $this->wrapGenerateTextCharge($streamGenerator, $uid, $model, $chargePoints, $chargeModality);
  285. }
  286. // 免费场景(0 积分):流式生成成功后仅记录 token 使用明细
  287. return $this->wrapGenerateTextTokenRecord($streamGenerator, $uid, $model);
  288. }
  289. /**
  290. * 流式生成成功后仅记录 token 明细(纯文本免费场景,不扣积分)
  291. *
  292. * @param \Generator $generator
  293. * @param int $uid
  294. * @param string $model
  295. * @return \Generator
  296. */
  297. private function wrapGenerateTextTokenRecord(\Generator $generator, int $uid, string $model, string $source = 'generateText'): \Generator
  298. {
  299. $recorded = false;
  300. foreach ($generator as $chunk) {
  301. if (!$recorded && isset($chunk['type']) && $chunk['type'] === 'done') {
  302. $this->recordTextTokenOnly($uid, $this->pointsService->getTokensFromUsage(getProp($chunk, 'usage', [])), [
  303. 'model' => $model,
  304. 'source' => $source,
  305. ], $model);
  306. $recorded = true;
  307. }
  308. yield $chunk;
  309. }
  310. }
  311. /**
  312. * 流式生成成功后再按档位/模型规则扣费(文生文 normal 档 / 图生文按模型固定价格)
  313. *
  314. * @param \Generator $generator
  315. * @param int $uid
  316. * @param string $model
  317. * @param int $points
  318. * @param string $modality
  319. * @return \Generator
  320. */
  321. private function wrapGenerateTextCharge(\Generator $generator, int $uid, string $model, int $points, string $modality): \Generator
  322. {
  323. $charged = false;
  324. foreach ($generator as $chunk) {
  325. if (!$charged && isset($chunk['type']) && $chunk['type'] === 'done') {
  326. $fullContent = (string)getProp($chunk, 'full_content', getProp($chunk, 'answer', ''));
  327. if ($fullContent !== '') {
  328. $this->chargeMultimodal($uid, $model, $points, $modality, getProp($chunk, 'usage', []));
  329. $charged = true;
  330. }
  331. }
  332. yield $chunk;
  333. }
  334. }
  335. /**
  336. * AI 对话(含图片/视频 -> 文本)成功后扣费并记录积分与 token 明细
  337. *
  338. * @param int $uid
  339. * @param string $model
  340. * @param int $points
  341. * @param string $modality
  342. * @param mixed $usage
  343. * @return void
  344. */
  345. private function chargeMultimodal(int $uid, string $model, int $points, string $modality, $usage): void
  346. {
  347. $result = $this->pointsService->recordChatCharge(
  348. $uid,
  349. $points,
  350. $this->pointsService->getTokensFromUsage($usage),
  351. [
  352. 'model' => $model,
  353. 'modality' => $modality,
  354. 'source' => 'generateText',
  355. ],
  356. '',
  357. $model
  358. );
  359. if (empty($result['charged'])) {
  360. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  361. }
  362. }
  363. /**
  364. * 检查 OpenAI 风格消息中是否包含指定媒体类型
  365. *
  366. * @param array $messages
  367. * @param array $mediaTypes
  368. * @return bool
  369. */
  370. private function messagesContainMedia(array $messages, array $mediaTypes): bool
  371. {
  372. foreach ($messages as $message) {
  373. $content = getProp($message, 'content', '');
  374. if (!is_array($content)) {
  375. continue;
  376. }
  377. foreach ($content as $part) {
  378. if (is_array($part) && in_array(getProp($part, 'type', ''), $mediaTypes, true)) {
  379. return true;
  380. }
  381. }
  382. }
  383. return false;
  384. }
  385. public function createGenerateText($data) {
  386. $file = getProp($data, 'file');
  387. $episode_num = getProp($data, 'episode_num');
  388. $uid = Site::getUid();
  389. $cpid = Site::getCpid();
  390. if (!$file) {
  391. Utils::throwError('20003:请上传文件');
  392. }
  393. // 提取文件内容
  394. $content = $this->extractFileContent($file);
  395. if (!$content) {
  396. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  397. }
  398. // 拆分章节并校验章节总数、标题连续性
  399. if ($episode_num) {
  400. $this->validateGenerateTextChapters($content, (int)$episode_num);
  401. }
  402. // 获取原始文件名(不含扩展名)作为script_name
  403. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  404. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  405. // 字节安全剥离,不依赖服务器locale设置
  406. $originalName = $file->getClientOriginalName();
  407. $extension = $file->getClientOriginalExtension();
  408. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  409. ? substr($originalName, 0, -strlen($extension) - 1)
  410. : $originalName;
  411. if ($script_name === '') {
  412. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  413. }
  414. // 如果同一用户的剧本名存在则提示
  415. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  416. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  417. }
  418. // 插入数据到mp_scripts表
  419. $script_id = DB::table('mp_scripts')->insertGetId([
  420. 'script_name' => $script_name,
  421. 'user_id' => $uid,
  422. 'cpid' => $cpid,
  423. 'content' => $content,
  424. 'created_at' => date('Y-m-d H:i:s'),
  425. 'updated_at' => date('Y-m-d H:i:s')
  426. ]);
  427. return [
  428. 'script_id' => $script_id,
  429. 'script_name' => $script_name
  430. ];
  431. }
  432. /**
  433. * AI对话调用成功后的积分扣费(返回结果前调用)
  434. *
  435. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  436. *
  437. * @param int $uid
  438. * @param int $tokens
  439. * @param array $chargeInfo
  440. * @return void
  441. */
  442. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo, string $chargeType = 'special'): void
  443. {
  444. // api_type 记录真实模型名(缺失时回退 deepseek 大类),保证明细与统计口径准确
  445. $model = (string)getProp($chargeInfo, 'model', '');
  446. $result = $this->pointsService->recordChatCharge(
  447. $uid,
  448. $this->pointsService->getChatChargePoints($model, $chargeType),
  449. $tokens,
  450. $chargeInfo,
  451. '',
  452. $model !== '' ? $model : 'deepseek'
  453. );
  454. if (empty($result['charged'])) {
  455. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  456. }
  457. }
  458. /**
  459. * 安全获取当前登录用户ID
  460. *
  461. * 命令行/队列等无用户上下文的场景返回 0,由记录方法自行跳过。
  462. *
  463. * @return int
  464. */
  465. private function getCurrentUid(): int
  466. {
  467. try {
  468. return (int)Site::getUid();
  469. } catch (\Throwable $e) {
  470. return 0;
  471. }
  472. }
  473. /**
  474. * 记录文生文 token 使用明细(仅记录,不扣积分)
  475. *
  476. * 用于不按积分计费的文生文接口;记录失败不影响主流程。
  477. *
  478. * @param int $uid 用户ID(0 时跳过)
  479. * @param int $tokens 消耗 token 数
  480. * @param array $chargeInfo 计费/来源信息(model、source 等)
  481. * @param string $apiType API 类型/模型标识
  482. * @return void
  483. */
  484. private function recordTextTokenOnly(int $uid, int $tokens, array $chargeInfo, string $apiType = ''): void
  485. {
  486. try {
  487. $this->pointsService->recordTokenOnlyDetail(
  488. $uid,
  489. $tokens,
  490. $chargeInfo,
  491. MpUserPointsDetail::TYPE_CHAT,
  492. $apiType,
  493. ''
  494. );
  495. } catch (\Throwable $e) {
  496. dLog('points')->warning('token明细记录异常(不影响主流程): ' . $e->getMessage(), [
  497. 'uid' => $uid,
  498. 'source' => $chargeInfo['source'] ?? '',
  499. ]);
  500. }
  501. }
  502. /**
  503. * 拆分剧本内容并校验章节总数与标题连续性
  504. *
  505. * @param string $content
  506. * @param int $episodeNum
  507. * @return void
  508. */
  509. private function validateGenerateTextChapters($content, $episodeNum)
  510. {
  511. $chapters = splitContent($content);
  512. if (count($chapters) !== $episodeNum) {
  513. Utils::throwError('20003:章节总数与集数不一致,请检查上传内容');
  514. }
  515. if (empty($chapters)) {
  516. return;
  517. }
  518. // 先尝试从标题正则中解析序号,确认是否从1开始连续递增
  519. $numbers = [];
  520. $unparsedIndex = null;
  521. foreach ($chapters as $index => $chapter) {
  522. $num = $this->parseChapterNumber($chapter['title']);
  523. if ($num === null) {
  524. $unparsedIndex = $index;
  525. break;
  526. }
  527. $numbers[] = $num;
  528. }
  529. if ($unparsedIndex === null) {
  530. $expected = 1;
  531. foreach ($numbers as $index => $num) {
  532. if ($num !== $expected) {
  533. $title = mb_substr(trim((string)$chapters[$index]['title']), 0, 40);
  534. Utils::throwError('20003:章节序号不连续:第' . ($index + 1) . '个章节“' . $title . '”序号为' . $num . ',预期为' . $expected);
  535. }
  536. $expected++;
  537. }
  538. return;
  539. }
  540. // 标题格式无法用正则确认时,交给模型分析
  541. $titles = array_column($chapters, 'title');
  542. $aiResult = $this->validateChapterSequenceByAI($titles);
  543. if ($aiResult['valid'] === false) {
  544. $badIndex = $aiResult['invalid_index'] ?: $unparsedIndex + 1;
  545. if (isset($chapters[$badIndex - 1])) {
  546. $title = mb_substr(trim((string)$chapters[$badIndex - 1]['title']), 0, 40);
  547. Utils::throwError('20003:章节序号不连续:第' . $badIndex . '个章节“' . $title . '”序号异常,请检查');
  548. }
  549. Utils::throwError('20003:章节序号不连续,请检查章节标题格式');
  550. }
  551. if ($aiResult['valid'] === null) {
  552. if (isset($chapters[$unparsedIndex])) {
  553. $title = mb_substr(trim((string)$chapters[$unparsedIndex]['title']), 0, 40);
  554. Utils::throwError('20003:无法确认第' . ($unparsedIndex + 1) . '个章节“' . $title . '”的章节序号,请检查标题格式');
  555. }
  556. Utils::throwError('20003:无法确认章节标题连续性,请检查章节标题格式');
  557. }
  558. }
  559. /**
  560. * 从章节标题中解析序号,支持阿拉伯数字和中文数字
  561. *
  562. * @param string $title
  563. * @return int|null
  564. */
  565. private function parseChapterNumber($title)
  566. {
  567. if (!preg_match('/第\s*([一二两三四五六七八九十百千万0-9]+)\s*[章节集幕场回话]/u', $title, $match)) {
  568. return null;
  569. }
  570. return $this->convertChineseNumber($match[1]);
  571. }
  572. /**
  573. * 中文数字转阿拉伯数字(支持到千)
  574. *
  575. * @param string $numStr
  576. * @return int
  577. */
  578. private function convertChineseNumber($numStr)
  579. {
  580. if (preg_match('/^\d+$/', $numStr)) {
  581. return (int)$numStr;
  582. }
  583. $map = [
  584. '零' => 0,
  585. '一' => 1,
  586. '二' => 2,
  587. '两' => 2,
  588. '三' => 3,
  589. '四' => 4,
  590. '五' => 5,
  591. '六' => 6,
  592. '七' => 7,
  593. '八' => 8,
  594. '九' => 9
  595. ];
  596. $total = 0;
  597. $section = 0;
  598. $length = mb_strlen($numStr);
  599. for ($i = 0; $i < $length; $i++) {
  600. $char = mb_substr($numStr, $i, 1);
  601. if (isset($map[$char])) {
  602. $section = $map[$char];
  603. } elseif ($char === '十') {
  604. $total += $section === 0 ? 10 : $section * 10;
  605. $section = 0;
  606. } elseif ($char === '百') {
  607. $total += $section === 0 ? 100 : $section * 100;
  608. $section = 0;
  609. } elseif ($char === '千') {
  610. $total += $section === 0 ? 1000 : $section * 1000;
  611. $section = 0;
  612. }
  613. }
  614. return $total + $section;
  615. }
  616. /**
  617. * 用 deepseek-v4-flash 非流式判断章节标题是否从1开始连续编号
  618. *
  619. * @param array $titles
  620. * @return array{valid: bool|null, invalid_index: int|null}
  621. */
  622. private function validateChapterSequenceByAI($titles)
  623. {
  624. $titleLines = [];
  625. foreach (array_slice($titles, 0, 200) as $index => $title) {
  626. $titleLines[] = ($index + 1) . '. ' . mb_substr(trim((string)$title), 0, 80);
  627. }
  628. $result = [
  629. 'valid' => null,
  630. 'invalid_index' => null
  631. ];
  632. $post_data = [
  633. 'model' => 'deepseek-v4-flash',
  634. 'messages' => [
  635. [
  636. 'role' => 'system',
  637. 'content' => '你是剧本章节校验助手。用户会给出章节标题列表,请判断这些标题中的编号是否从第1章/第1集开始连续递增,支持阿拉伯数字和中文数字。只输出 JSON,格式为 {"valid":true};若不连续则输出 {"valid":false,"invalid_index":N},其中 N 是第一个序号异常的章节序号(从1开始),不要输出其他内容。',
  638. ],
  639. [
  640. 'role' => 'user',
  641. 'content' => implode("\n", $titleLines),
  642. ],
  643. ],
  644. 'temperature' => 0,
  645. 'frequency_penalty' => 0,
  646. 'presence_penalty' => 0,
  647. 'stream' => false,
  648. ];
  649. try {
  650. $result = $this->chatOnly($post_data, 8);
  651. $content = trim((string)($result['fullContent'] ?? ''));
  652. if (preg_match('/"valid"\s*:\s*(true|false)/i', $content, $match)) {
  653. $result['valid'] = strtolower($match[1]) === 'true';
  654. }
  655. if (preg_match('/"invalid_index"\s*:\s*(\d+)/i', $content, $match)) {
  656. $result['invalid_index'] = (int)$match[1];
  657. }
  658. // 仅记录 token 使用明细(不扣积分):该校验为流程内的额外模型调用
  659. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  660. 'model' => 'deepseek-v4-flash',
  661. 'source' => 'validateChapterSequenceByAI',
  662. ], 'deepseek-v4-flash');
  663. } catch (\Exception $e) {
  664. dLog('deepseek')->error('章节连续性AI校验失败: ' . $e->getMessage());
  665. }
  666. return $result;
  667. }
  668. /**
  669. * 通用文生文(流式版本)- newGenerateText 的 stream=1 分支
  670. * 支持与 newGenerateText 相同的参数(模板/剧本/JSON输出/图片输入),
  671. * 输出格式与 generateText 一致:yield type=content / reasoning / done
  672. *
  673. * @param array $data 请求参数
  674. * @return \Generator
  675. */
  676. public function newGenerateTextStream($data, $existingTask = null) {
  677. $model = getProp($data, 'model', 'deepseek-v4-pro');
  678. $messages = getProp($data, 'messages', []);
  679. $systemPrompt = getProp($data, 'system_prompt', '');
  680. $prompt = getProp($data, 'prompt', '');
  681. $images = getProp($data, 'images', []);
  682. $imageUrls = getProp($data, 'image_urls', []);
  683. $responseFormat = getProp($data, 'response_format', 'text');
  684. $templateId = getProp($data, 'template_id', 0);
  685. $script_id = getProp($data, 'script_id', 0);
  686. $sequence = getProp($data, 'sequence', 0);
  687. $generateTaskId = 0;
  688. // 异步 worker 场景直接使用任务记录中的用户,避免命令行下无登录上下文
  689. $uid = $existingTask ? (int)$existingTask->uid : (int)Site::getUid();
  690. if ($script_id > 0 && !$existingTask) {
  691. $runningTask = DB::table('mp_script_generate_tasks')
  692. ->where('uid', $uid)
  693. ->where('script_id', $script_id)
  694. ->orderByDesc('id')
  695. ->first();
  696. if ($runningTask && in_array(getProp($runningTask, 'status'), ['pending', 'processing'])) {
  697. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  698. }
  699. }
  700. // 如果提供了script_id,从数据库获取剧本内容作为原文
  701. $originalContent = '';
  702. $hasValidScript = false;
  703. $rawPrompt = $prompt; // 保存用户原始输入,供模板一致性判断
  704. if ($script_id > 0) {
  705. $script = DB::table('mp_scripts')
  706. ->where('id', $script_id)
  707. ->where('is_deleted', 0)
  708. ->first();
  709. if (!$script) {
  710. Utils::throwError('20003:剧本不存在或已删除');
  711. }
  712. $originalContent = $script->content ?? '';
  713. if (empty($originalContent)) {
  714. Utils::throwError('20003:剧本内容为空');
  715. }
  716. $hasValidScript = true;
  717. if (!empty($prompt)) {
  718. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  719. } else {
  720. $prompt = "原文内容:\n" . $originalContent;
  721. }
  722. }
  723. // 如果提供了template_id,从数据库获取template_prompt
  724. if ($templateId > 0) {
  725. $template = DB::table('mp_prompt_templates')
  726. ->where('id', $templateId)
  727. ->where('is_deleted', 0)
  728. ->first();
  729. if (!$template) {
  730. Utils::throwError('20003:模板不存在或已删除');
  731. }
  732. $templatePrompt = $template->template_prompt ?? '';
  733. if (!empty($templatePrompt)) {
  734. // 模板提示词与用户输入基本一致时只保留一个,避免重复提示词
  735. // 剧本模式下当前 prompt 含原文内容需保留,其余情况以模板内容为准
  736. $trimmedRawPrompt = trim((string)$rawPrompt);
  737. if ($trimmedRawPrompt !== '' && mb_strtolower($trimmedRawPrompt) === mb_strtolower(trim($templatePrompt))) {
  738. if (!$hasValidScript) {
  739. $prompt = $templatePrompt;
  740. }
  741. } elseif (!empty($prompt)) {
  742. $prompt = $templatePrompt . "\n\n" . $prompt;
  743. } else {
  744. $prompt = $templatePrompt;
  745. }
  746. }
  747. }
  748. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  749. if (empty($messages)) {
  750. $messages = [];
  751. if (!empty($systemPrompt)) {
  752. $messages[] = [
  753. 'role' => 'system',
  754. 'content' => $systemPrompt
  755. ];
  756. }
  757. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  758. $userMessage = [
  759. 'role' => 'user',
  760. 'content' => []
  761. ];
  762. if (!empty($prompt)) {
  763. $userMessage['content'][] = [
  764. 'type' => 'text',
  765. 'text' => $prompt
  766. ];
  767. }
  768. if (!empty($images)) {
  769. if (!is_array($images)) {
  770. $images = [$images];
  771. }
  772. foreach ($images as $image) {
  773. $imageBase64 = $this->processImageToBase64($image);
  774. if ($imageBase64) {
  775. $userMessage['content'][] = [
  776. 'type' => 'image_url',
  777. 'image_url' => [
  778. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  779. ]
  780. ];
  781. }
  782. }
  783. }
  784. if (!empty($imageUrls)) {
  785. if (!is_array($imageUrls)) {
  786. $imageUrls = [$imageUrls];
  787. }
  788. foreach ($imageUrls as $url) {
  789. if (!empty($url)) {
  790. $userMessage['content'][] = [
  791. 'type' => 'image_url',
  792. 'image_url' => [
  793. 'url' => $url
  794. ]
  795. ];
  796. }
  797. }
  798. }
  799. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  800. $userMessage['content'] = $userMessage['content'][0]['text'];
  801. }
  802. $messages[] = $userMessage;
  803. }
  804. }
  805. if (empty($messages)) {
  806. Utils::throwError('20003:请提供有效的对话内容');
  807. }
  808. // 模型兼容性处理
  809. $thinkingMode = getProp($data, 'thinking', 'disabled');
  810. $reasoningEffort = getProp($data, 'reasoning_effort', 'high');
  811. if ($model === 'deepseek-chat') {
  812. $model = 'deepseek-v4-flash';
  813. $thinkingMode = 'disabled';
  814. } elseif ($model === 'deepseek-reasoner') {
  815. $model = 'deepseek-v4-flash';
  816. $thinkingMode = 'enabled';
  817. }
  818. // 构建请求参数(流式)
  819. $post_data = [
  820. 'model' => $model,
  821. 'messages' => $messages,
  822. 'temperature' => getProp($data, 'temperature', 1),
  823. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  824. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  825. 'thinking' => ['type' => $thinkingMode],
  826. 'stream' => true
  827. ];
  828. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  829. if (isset($data['top_p'])) {
  830. $post_data['top_p'] = $data['top_p'];
  831. }
  832. // response_format=json 时附加 JSON 说明与响应格式(与 newGenerateText 一致)
  833. if ($responseFormat === 'json') {
  834. $hasJsonKeyword = false;
  835. foreach ($post_data['messages'] as $message) {
  836. if (isset($message['content'])) {
  837. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  838. if (stripos($content, 'json') !== false) {
  839. $hasJsonKeyword = true;
  840. break;
  841. }
  842. }
  843. }
  844. if (!$hasJsonKeyword) {
  845. $lastMessageIndex = count($post_data['messages']) - 1;
  846. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  847. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  848. if (is_string($lastContent)) {
  849. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  850. } elseif (is_array($lastContent)) {
  851. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  852. if ($contentPart['type'] === 'text') {
  853. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  854. break;
  855. }
  856. }
  857. }
  858. }
  859. }
  860. $post_data['response_format'] = ['type' => 'json_object'];
  861. }
  862. // 如果提供了script_id,创建剧本资产生成任务
  863. if ($script_id > 0) {
  864. if ($existingTask) {
  865. // 异步 worker:接管已创建的 pending 任务,不再新建
  866. $generateTaskId = (int)$existingTask->id;
  867. } else {
  868. // 同步调用:保持原行为,创建 processing 任务
  869. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  870. 'uid' => $uid,
  871. 'script_id' => $script_id,
  872. 'sequence' => $sequence,
  873. 'status' => 'processing',
  874. 'prompt' => getProp($data, 'prompt', ''),
  875. 'started_at' => date('Y-m-d H:i:s'),
  876. 'created_at' => date('Y-m-d H:i:s'),
  877. 'updated_at' => date('Y-m-d H:i:s')
  878. ]);
  879. }
  880. }
  881. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  882. if ($hasValidScript) {
  883. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  884. }
  885. // 根据模型类型选择流式实现
  886. $streamGenerator = $this->dispatchStreamByModel($post_data);
  887. // 流式输出包装:done 时更新任务状态、扣费并保存对话记录
  888. return $this->wrapNewGenerateTextStream($streamGenerator, [
  889. 'uid' => $uid,
  890. 'model' => $model,
  891. 'generate_task_id' => $generateTaskId,
  892. 'has_valid_script' => $hasValidScript,
  893. 'script_id' => $script_id,
  894. 'sequence' => $sequence,
  895. 'original_prompt' => getProp($data, 'prompt', ''),
  896. 'response_format' => $responseFormat,
  897. ]);
  898. }
  899. /**
  900. * 流式生成收尾包装:done 时更新剧本资产生成任务、扣除积分并保存对话记录
  901. *
  902. * @param \Generator $generator
  903. * @param array $ctx
  904. * @return \Generator
  905. */
  906. private function wrapNewGenerateTextStream(\Generator $generator, array $ctx): \Generator
  907. {
  908. $fullContent = '';
  909. $usage = [];
  910. $finished = false;
  911. try {
  912. foreach ($generator as $chunk) {
  913. if (isset($chunk['type']) && $chunk['type'] === 'content') {
  914. $fullContent .= (string)getProp($chunk, 'content', '');
  915. }
  916. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  917. $fullContent = (string)getProp($chunk, 'full_content', $fullContent);
  918. $usage = getProp($chunk, 'usage', []);
  919. // 流式场景下部分模型/中转站不强制 JSON 输出,兜底提取标准 JSON
  920. if (($ctx['response_format'] ?? 'text') === 'json') {
  921. $fullContent = $this->extractJsonContent($fullContent);
  922. }
  923. $finished = true;
  924. // 保存对话记录并将 records 附加到 done 消息(无论 script_id 是否有值都返回 records 数组)
  925. $chunk['records'] = [];
  926. if (!empty($ctx['script_id'])) {
  927. try {
  928. $now = now();
  929. // 两条对话记录(user/assistant)在同一事务内写入,保证原子性
  930. $chunk['records'] = DB::transaction(function () use ($ctx, $fullContent, $now) {
  931. DB::table('mp_script_records')->insert([
  932. [
  933. 'uid' => $ctx['uid'],
  934. 'script_id' => $ctx['script_id'],
  935. 'sequence' => $ctx['sequence'],
  936. 'role' => 'user',
  937. 'content' => $ctx['original_prompt'],
  938. 'created_at' => $now,
  939. 'updated_at' => $now,
  940. ],
  941. [
  942. 'uid' => $ctx['uid'],
  943. 'script_id' => $ctx['script_id'],
  944. 'sequence' => $ctx['sequence'],
  945. 'role' => 'assistant',
  946. 'content' => $fullContent,
  947. 'created_at' => $now,
  948. 'updated_at' => $now,
  949. ],
  950. ]);
  951. return DB::table('mp_script_records')
  952. ->where('uid', $ctx['uid'])
  953. ->where('script_id', $ctx['script_id'])
  954. ->where('sequence', $ctx['sequence'])
  955. ->orderBy('id', 'desc')
  956. ->limit(2)
  957. ->get()
  958. ->map(function ($record) {
  959. return [
  960. 'rid' => $record->id,
  961. 'script_id' => $record->script_id,
  962. 'sequence' => $record->sequence,
  963. 'role' => $record->role,
  964. 'content' => $record->content,
  965. 'created_at' => $record->created_at,
  966. ];
  967. })
  968. ->reverse()
  969. ->values()
  970. ->toArray();
  971. });
  972. } catch (\Exception $e) {
  973. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  974. $chunk['records'] = [];
  975. }
  976. }
  977. }
  978. yield $chunk;
  979. }
  980. if ($finished) {
  981. // 任务状态与扣费在同一事务内:扣费失败则任务状态一并回滚,由外层 catch 置为 failed
  982. DB::transaction(function () use ($ctx, $fullContent, $usage) {
  983. if (!empty($ctx['generate_task_id'])) {
  984. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  985. 'status' => 'success',
  986. 'result' => $fullContent,
  987. 'completed_at' => date('Y-m-d H:i:s'),
  988. 'updated_at' => date('Y-m-d H:i:s'),
  989. ]);
  990. }
  991. if ($ctx['has_valid_script'] && $fullContent !== '') {
  992. $this->chargeChatSuccess($ctx['uid'], $this->pointsService->getTokensFromUsage($usage), [
  993. 'model' => $ctx['model'],
  994. 'script_id' => $ctx['script_id'],
  995. 'sequence' => $ctx['sequence'],
  996. 'source' => 'newGenerateText',
  997. ]);
  998. }
  999. });
  1000. // JSON 输出结果的安全校验/修复与观察(事务外执行,不改变 result 与 SSE 推送内容)
  1001. if (!empty($ctx['generate_task_id'])) {
  1002. $this->guardScriptGenerateJsonResult(
  1003. (int)$ctx['generate_task_id'],
  1004. (int)($ctx['script_id'] ?? 0),
  1005. (int)($ctx['uid'] ?? 0),
  1006. (string)$fullContent,
  1007. (string)($ctx['response_format'] ?? '')
  1008. );
  1009. }
  1010. }
  1011. } catch (\Throwable $e) {
  1012. if (!empty($ctx['generate_task_id'])) {
  1013. DB::table('mp_script_generate_tasks')->where('id', $ctx['generate_task_id'])->update([
  1014. 'status' => 'failed',
  1015. 'error_message' => $e->getMessage(),
  1016. 'completed_at' => date('Y-m-d H:i:s'),
  1017. 'updated_at' => date('Y-m-d H:i:s'),
  1018. ]);
  1019. }
  1020. yield [
  1021. 'type' => 'error',
  1022. 'message' => $e->getMessage(),
  1023. ];
  1024. }
  1025. }
  1026. /**
  1027. * 从模型输出中提取标准 JSON(剥离 markdown 代码块及前后说明文字)
  1028. *
  1029. * @param string $content
  1030. * @return string
  1031. */
  1032. private function extractJsonContent(string $content): string
  1033. {
  1034. $content = trim($content);
  1035. if ($content === '') {
  1036. return $content;
  1037. }
  1038. // 剥离 ```json ... ``` 代码块
  1039. if (preg_match('/```(?:json)?\s*(.*?)```/s', $content, $m)) {
  1040. $content = trim($m[1]);
  1041. }
  1042. // 提取第一个 { 到最后一个 } 之间的内容(去除前后说明文字)
  1043. $first = strpos($content, '{');
  1044. $last = strrpos($content, '}');
  1045. if ($first !== false && $last !== false && $last > $first) {
  1046. $content = substr($content, $first, $last - $first + 1);
  1047. }
  1048. // 校验是否为合法 JSON,非法则原样返回(不强行截断)
  1049. json_decode($content, true);
  1050. if (json_last_error() !== JSON_ERROR_NONE) {
  1051. return trim($content);
  1052. }
  1053. return $content;
  1054. }
  1055. /**
  1056. * 剧本资产生成结果的 JSON 安全校验/修复与观察
  1057. *
  1058. * 规则:
  1059. * - result 永远保留模型原文,本方法不修改 result;
  1060. * - 仅当原文非法 JSON 且 JsonSafeRepair 安全修复成功时,才把修复后的标准
  1061. * JSON 写入 mp_script_generate_tasks.json_result;
  1062. * - 每次生成结果都写一条 system_logs(channel=script_generate_json),
  1063. * 用于观察非法 JSON 的发生率与修复率。
  1064. *
  1065. * @param int $taskId 剧本资产生成任务 ID
  1066. * @param int $scriptId 剧本 ID
  1067. * @param int $uid 用户 ID
  1068. * @param string $raw 已落库的 result 原文
  1069. * @param string $responseFormat 请求的 response_format
  1070. * @return void
  1071. */
  1072. private function guardScriptGenerateJsonResult(int $taskId, int $scriptId, int $uid, string $raw, string $responseFormat): void
  1073. {
  1074. if ($taskId <= 0 || $raw === '') {
  1075. return;
  1076. }
  1077. // 仅对"要求 JSON 输出"或"内容明显是 JSON"的结果做校验,避免误伤普通文本结果
  1078. $trimmed = ltrim($raw);
  1079. $looksLikeJson = $responseFormat === 'json'
  1080. || (isset($trimmed[0]) && ($trimmed[0] === '{' || $trimmed[0] === '['));
  1081. if (!$looksLikeJson) {
  1082. return;
  1083. }
  1084. $repair = JsonSafeRepair::repair($raw);
  1085. $common = [
  1086. 'task_id' => $taskId,
  1087. 'script_id' => $scriptId,
  1088. 'uid' => $uid,
  1089. 'raw_length' => strlen($raw),
  1090. ];
  1091. if ($repair['ok'] && $repair['json'] !== $raw) {
  1092. // 原文非法但安全修复成功:修复版另存 json_result,result 仍保留原文
  1093. DB::table('mp_script_generate_tasks')->where('id', $taskId)->update([
  1094. 'json_result' => $repair['json'],
  1095. 'updated_at' => date('Y-m-d H:i:s'),
  1096. ]);
  1097. logDB('script_generate_json', 'warning', '生成JSON修复成功', $common + [
  1098. 'json_state' => 'repaired',
  1099. 'json_length' => strlen((string)$repair['json']),
  1100. 'removed_count' => count($repair['removed_positions']),
  1101. 'removed_positions' => $repair['removed_positions'],
  1102. ]);
  1103. return;
  1104. }
  1105. if ($repair['ok']) {
  1106. // 原文本身就是合法 JSON
  1107. logDB('script_generate_json', 'info', '生成JSON校验通过', $common + [
  1108. 'json_state' => 'valid',
  1109. ]);
  1110. return;
  1111. }
  1112. // 非法 JSON 且不在安全修复范围内:保留原文,只记录观察日志
  1113. logDB('script_generate_json', 'error', '生成JSON修复失败', $common + [
  1114. 'json_state' => 'repair_failed',
  1115. 'reason' => $repair['reason'],
  1116. ]);
  1117. }
  1118. /**
  1119. * 创建剧本资产生成异步任务(stream=1 + script_id 走异步任务模式)
  1120. *
  1121. * @param array $data 原请求参数
  1122. * @return int 任务ID
  1123. */
  1124. public function createScriptGenerateAsyncTask(array $data): int
  1125. {
  1126. $script_id = (int)getProp($data, 'script_id', 0);
  1127. if ($script_id <= 0) {
  1128. Utils::throwError('20003:缺少剧本ID');
  1129. }
  1130. $uid = (int)Site::getUid();
  1131. // 与同步逻辑一致:同一剧本存在生成中任务时直接拒绝
  1132. $runningTask = DB::table('mp_script_generate_tasks')
  1133. ->where('uid', $uid)
  1134. ->where('script_id', $script_id)
  1135. ->orderByDesc('id')
  1136. ->first();
  1137. if ($runningTask && in_array(getProp($runningTask, 'status'), ['pending', 'processing'])) {
  1138. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  1139. }
  1140. // 前置校验剧本存在且内容非空,避免创建无效任务
  1141. $script = DB::table('mp_scripts')
  1142. ->where('id', $script_id)
  1143. ->where('is_deleted', 0)
  1144. ->first();
  1145. if (!$script) {
  1146. Utils::throwError('20003:剧本不存在或已删除');
  1147. }
  1148. if (empty($script->content)) {
  1149. Utils::throwError('20003:剧本内容为空');
  1150. }
  1151. // newGenerateText 请求不含上传文件对象,images/image_urls 以字符串形式传入,可直接序列化
  1152. $paramsJson = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  1153. if ($paramsJson === false) {
  1154. Utils::throwError('20003:请求参数序列化失败');
  1155. }
  1156. $now = date('Y-m-d H:i:s');
  1157. return (int)DB::table('mp_script_generate_tasks')->insertGetId([
  1158. 'uid' => $uid,
  1159. 'script_id' => $script_id,
  1160. 'sequence' => (int)getProp($data, 'sequence', 0),
  1161. 'status' => 'pending',
  1162. 'prompt' => (string)getProp($data, 'prompt', ''),
  1163. 'request_params' => $paramsJson,
  1164. 'started_at' => $now,
  1165. 'created_at' => $now,
  1166. 'updated_at' => $now,
  1167. ]);
  1168. }
  1169. /**
  1170. * 供 SSE 轮询:查询任务状态与增量 chunks
  1171. *
  1172. * @param int $taskId
  1173. * @param int $uid 当前登录用户,防越权
  1174. * @param int $afterSeq 已推送的最大 seq
  1175. * @return array{found:bool, task:?object, chunks:array, status:?string, error_message:?string}
  1176. */
  1177. public function pollScriptGenerateTask(int $taskId, int $uid, int $afterSeq = -1): array
  1178. {
  1179. $task = DB::table('mp_script_generate_tasks')
  1180. ->where('id', $taskId)
  1181. ->where('uid', $uid)
  1182. ->first();
  1183. if (!$task) {
  1184. return ['found' => false, 'task' => null, 'chunks' => [], 'status' => null, 'error_message' => null];
  1185. }
  1186. $rows = DB::table('mp_script_generate_task_chunks')
  1187. ->where('task_id', $taskId)
  1188. ->where('seq', '>', $afterSeq)
  1189. ->orderBy('seq')
  1190. ->get();
  1191. $chunks = [];
  1192. foreach ($rows as $row) {
  1193. $payload = json_decode((string)$row->payload, true);
  1194. if (is_array($payload)) {
  1195. $chunks[] = $payload;
  1196. }
  1197. }
  1198. return [
  1199. 'found' => true,
  1200. 'task' => $task,
  1201. 'chunks' => $chunks,
  1202. 'status' => (string)$task->status,
  1203. 'error_message' => (string)($task->error_message ?? ''),
  1204. ];
  1205. }
  1206. /**
  1207. * 异步 worker 执行入口:抢占 pending 任务并流式请求大模型
  1208. *
  1209. * 由 text:generate:run 命令调用;worker 内完成 chunks 落库,模型结束后
  1210. * 由流式包装(wrapNewGenerateTextStream)完成 records/扣费/任务状态/json 修复收尾。
  1211. *
  1212. * @param int $taskId
  1213. * @return array{ok:bool, task_id:int, status:?string, seq:int, error:?string}
  1214. */
  1215. public function runScriptGenerateTaskAsync(int $taskId): array
  1216. {
  1217. // 原子抢占:只允许 pending -> processing,避免重复执行
  1218. $claimed = DB::table('mp_script_generate_tasks')
  1219. ->where('id', $taskId)
  1220. ->where('status', 'pending')
  1221. ->update([
  1222. 'status' => 'processing',
  1223. 'started_at' => date('Y-m-d H:i:s'),
  1224. 'updated_at' => date('Y-m-d H:i:s'),
  1225. ]);
  1226. if (!$claimed) {
  1227. return ['ok' => false, 'task_id' => $taskId, 'status' => null, 'seq' => 0, 'error' => '任务已被处理或状态异常'];
  1228. }
  1229. $task = DB::table('mp_script_generate_tasks')->where('id', $taskId)->first();
  1230. if (!$task) {
  1231. return ['ok' => false, 'task_id' => $taskId, 'status' => null, 'seq' => 0, 'error' => '任务不存在'];
  1232. }
  1233. $params = json_decode((string)getProp($task, 'request_params', ''), true);
  1234. if (!is_array($params)) {
  1235. DB::table('mp_script_generate_tasks')->where('id', $taskId)->update([
  1236. 'status' => 'failed',
  1237. 'error_message' => '任务请求参数缺失',
  1238. 'completed_at' => date('Y-m-d H:i:s'),
  1239. 'updated_at' => date('Y-m-d H:i:s'),
  1240. ]);
  1241. return ['ok' => false, 'task_id' => $taskId, 'status' => 'failed', 'seq' => 0, 'error' => '任务请求参数缺失'];
  1242. }
  1243. // 兼容旧参数未带 stream 的情况
  1244. $params['stream'] = 1;
  1245. $seq = 0;
  1246. try {
  1247. $generator = $this->newGenerateTextStream($params, $task);
  1248. foreach ($generator as $chunk) {
  1249. DB::table('mp_script_generate_task_chunks')->insert([
  1250. 'task_id' => $taskId,
  1251. 'seq' => $seq,
  1252. 'chunk_type' => (string)getProp($chunk, 'type', 'content'),
  1253. 'payload' => json_encode($chunk, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE),
  1254. 'created_at' => date('Y-m-d H:i:s'),
  1255. ]);
  1256. $seq++;
  1257. }
  1258. $finalStatus = (string)DB::table('mp_script_generate_tasks')->where('id', $taskId)->value('status');
  1259. return ['ok' => $finalStatus === 'success', 'task_id' => $taskId, 'status' => $finalStatus, 'seq' => $seq, 'error' => null];
  1260. } catch (\Throwable $e) {
  1261. // 兜底:正常流程中 wrap 会自行把任务置为 failed,这里防止未知异常导致任务卡死
  1262. DB::table('mp_script_generate_tasks')->where('id', $taskId)->update([
  1263. 'status' => 'failed',
  1264. 'error_message' => $e->getMessage(),
  1265. 'completed_at' => date('Y-m-d H:i:s'),
  1266. 'updated_at' => date('Y-m-d H:i:s'),
  1267. ]);
  1268. return ['ok' => false, 'task_id' => $taskId, 'status' => 'failed', 'seq' => $seq, 'error' => $e->getMessage()];
  1269. }
  1270. }
  1271. /**
  1272. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  1273. *
  1274. * @param array $data 请求参数
  1275. * @return array 返回结果数组
  1276. */
  1277. public function newGenerateText($data) {
  1278. // stream=1 时改为流式请求大模型(输出格式参考 generateText:yield type=content/reasoning/done)
  1279. if ((int)getProp($data, 'stream', 0) === 1) {
  1280. return $this->newGenerateTextStream($data);
  1281. }
  1282. // 获取请求参数
  1283. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  1284. $messages = getProp($data, 'messages', []);
  1285. $systemPrompt = getProp($data, 'system_prompt', '');
  1286. $prompt = getProp($data, 'prompt', '');
  1287. $images = getProp($data, 'images', []); // 支持多张图片
  1288. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  1289. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  1290. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  1291. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  1292. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  1293. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  1294. $generateTaskId = 0;
  1295. $uid = Site::getUid();
  1296. if ($script_id > 0) {
  1297. $existingTask = DB::table('mp_script_generate_tasks')
  1298. ->where('uid', $uid)
  1299. ->where('script_id', $script_id)
  1300. ->orderByDesc('id')
  1301. ->first();
  1302. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  1303. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  1304. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  1305. }
  1306. }
  1307. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  1308. $originalContent = '';
  1309. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  1310. $rawPrompt = $prompt; // 保存用户原始输入,供模板一致性判断
  1311. if ($script_id > 0) {
  1312. $script = DB::table('mp_scripts')
  1313. ->where('id', $script_id)
  1314. ->where('is_deleted', 0)
  1315. ->first();
  1316. if (!$script) {
  1317. Utils::throwError('20003:剧本不存在或已删除');
  1318. }
  1319. $originalContent = $script->content ?? '';
  1320. if (empty($originalContent)) {
  1321. Utils::throwError('20003:剧本内容为空');
  1322. }
  1323. $hasValidScript = true;
  1324. // 将剧本内容添加到提示词前面
  1325. if (!empty($originalContent)) {
  1326. if (!empty($prompt)) {
  1327. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  1328. } else {
  1329. $prompt = "原文内容:\n" . $originalContent;
  1330. }
  1331. }
  1332. }
  1333. // 新增: 如果提供了template_id,从数据库获取template_prompt
  1334. if ($templateId > 0) {
  1335. $template = DB::table('mp_prompt_templates')
  1336. ->where('id', $templateId)
  1337. ->where('is_deleted', 0)
  1338. ->first();
  1339. if (!$template) {
  1340. Utils::throwError('20003:模板不存在或已删除');
  1341. }
  1342. $templatePrompt = $template->template_prompt ?? '';
  1343. // 将模板提示词和用户输入的prompt组合
  1344. // 模板为准,用户输入作为补充要求
  1345. // 模板提示词与用户输入基本一致时只保留一个,避免重复提示词
  1346. // 剧本模式下当前 prompt 含原文内容需保留,其余情况以模板内容为准
  1347. if (!empty($templatePrompt)) {
  1348. $trimmedRawPrompt = trim((string)$rawPrompt);
  1349. if ($trimmedRawPrompt !== '' && mb_strtolower($trimmedRawPrompt) === mb_strtolower(trim($templatePrompt))) {
  1350. if (!$hasValidScript) {
  1351. $prompt = $templatePrompt;
  1352. }
  1353. } elseif (!empty($prompt)) {
  1354. $prompt = $templatePrompt . "\n\n" . $prompt;
  1355. } else {
  1356. $prompt = $templatePrompt;
  1357. }
  1358. }
  1359. }
  1360. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  1361. if (empty($messages)) {
  1362. $messages = [];
  1363. // 添加系统提示词
  1364. if (!empty($systemPrompt)) {
  1365. $messages[] = [
  1366. 'role' => 'system',
  1367. 'content' => $systemPrompt
  1368. ];
  1369. }
  1370. // 构建用户消息内容(支持文本+图片)
  1371. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1372. $userMessage = [
  1373. 'role' => 'user',
  1374. 'content' => []
  1375. ];
  1376. // 添加文本内容
  1377. if (!empty($prompt)) {
  1378. $userMessage['content'][] = [
  1379. 'type' => 'text',
  1380. 'text' => $prompt
  1381. ];
  1382. }
  1383. // 处理上传的图片文件
  1384. if (!empty($images)) {
  1385. if (!is_array($images)) {
  1386. $images = [$images];
  1387. }
  1388. foreach ($images as $image) {
  1389. $imageBase64 = $this->processImageToBase64($image);
  1390. if ($imageBase64) {
  1391. $userMessage['content'][] = [
  1392. 'type' => 'image_url',
  1393. 'image_url' => [
  1394. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  1395. ]
  1396. ];
  1397. }
  1398. }
  1399. }
  1400. // 处理图片URL
  1401. if (!empty($imageUrls)) {
  1402. if (!is_array($imageUrls)) {
  1403. $imageUrls = [$imageUrls];
  1404. }
  1405. foreach ($imageUrls as $url) {
  1406. if (!empty($url)) {
  1407. $userMessage['content'][] = [
  1408. 'type' => 'image_url',
  1409. 'image_url' => [
  1410. 'url' => $url
  1411. ]
  1412. ];
  1413. }
  1414. }
  1415. }
  1416. // 如果只有文本内容,简化为字符串格式
  1417. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  1418. $userMessage['content'] = $userMessage['content'][0]['text'];
  1419. }
  1420. $messages[] = $userMessage;
  1421. }
  1422. }
  1423. // 验证messages不为空
  1424. if (empty($messages)) {
  1425. Utils::throwError('20003:请提供有效的对话内容');
  1426. }
  1427. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1428. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1429. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1430. if ($model === 'deepseek-chat') {
  1431. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1432. $model = 'deepseek-v4-flash';
  1433. $thinkingMode = 'disabled';
  1434. } elseif ($model === 'deepseek-reasoner') {
  1435. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1436. $model = 'deepseek-v4-flash';
  1437. $thinkingMode = 'enabled';
  1438. }
  1439. // 构建请求参数(非流式)
  1440. $post_data = [
  1441. 'model' => $model,
  1442. 'messages' => $messages,
  1443. 'temperature' => getProp($data, 'temperature', 1),
  1444. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  1445. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  1446. 'thinking' => ['type' => $thinkingMode],
  1447. 'stream' => false // 非流式输出
  1448. ];
  1449. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1450. // 添加可选参数
  1451. if (isset($data['top_p'])) {
  1452. $post_data['top_p'] = $data['top_p'];
  1453. }
  1454. // 新增: 根据response_format设置响应格式
  1455. if ($responseFormat === 'json') {
  1456. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  1457. $hasJsonKeyword = false;
  1458. foreach ($post_data['messages'] as $message) {
  1459. if (isset($message['content'])) {
  1460. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  1461. if (stripos($content, 'json') !== false) {
  1462. $hasJsonKeyword = true;
  1463. break;
  1464. }
  1465. }
  1466. }
  1467. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  1468. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  1469. if (!$hasJsonKeyword) {
  1470. $lastMessageIndex = count($post_data['messages']) - 1;
  1471. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  1472. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  1473. // 如果content是字符串,直接追加
  1474. if (is_string($lastContent)) {
  1475. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  1476. }
  1477. // 如果content是数组(包含文本和图片),在文本部分追加
  1478. else if (is_array($lastContent)) {
  1479. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  1480. if ($contentPart['type'] === 'text') {
  1481. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  1482. break;
  1483. }
  1484. }
  1485. }
  1486. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  1487. }
  1488. }
  1489. // 设置response_format参数(所有支持的模型)
  1490. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1491. // DeepSeek模型
  1492. $post_data['response_format'] = ['type' => 'json_object'];
  1493. } else if (in_array($model, $this->gpt_text_models)) {
  1494. // GPT模型
  1495. $post_data['response_format'] = ['type' => 'json_object'];
  1496. } else if (in_array($model, $this->valid_text_models)) {
  1497. // 火山引擎模型
  1498. $post_data['response_format'] = ['type' => 'json_object'];
  1499. }
  1500. }
  1501. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  1502. if ($script_id > 0) {
  1503. $uid = Site::getUid();
  1504. // 创建新的生成任务
  1505. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  1506. 'uid' => $uid,
  1507. 'script_id' => $script_id,
  1508. 'sequence' => $sequence,
  1509. 'status' => 'processing',
  1510. 'prompt' => getProp($data, 'prompt', ''),
  1511. 'started_at' => date('Y-m-d H:i:s'),
  1512. 'created_at' => date('Y-m-d H:i:s'),
  1513. 'updated_at' => date('Y-m-d H:i:s')
  1514. ]);
  1515. }
  1516. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  1517. if ($hasValidScript) {
  1518. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  1519. }
  1520. // 统一分模型调用非流式实现
  1521. try {
  1522. $aiResult = null;
  1523. $result = $this->dispatchChatOnlyByModel($post_data);
  1524. dLog('deepseek')->info('newGenerateText模型调用完成', ['requested_model' => $model]);
  1525. $aiResult = [
  1526. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  1527. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  1528. 'usage' => $result['usage'] ?? [],
  1529. 'model' => $model,
  1530. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  1531. ];
  1532. } catch (\Exception $e) {
  1533. // 生成失败,更新任务状态
  1534. if ($generateTaskId) {
  1535. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1536. 'status' => 'failed',
  1537. 'error_message' => $e->getMessage(),
  1538. 'completed_at' => date('Y-m-d H:i:s'),
  1539. 'updated_at' => date('Y-m-d H:i:s')
  1540. ]);
  1541. }
  1542. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  1543. }
  1544. // 生成成功,更新任务状态
  1545. if ($generateTaskId && $aiResult) {
  1546. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1547. 'status' => 'success',
  1548. 'result' => getProp($aiResult, 'content', ''),
  1549. 'completed_at' => date('Y-m-d H:i:s'),
  1550. 'updated_at' => date('Y-m-d H:i:s')
  1551. ]);
  1552. $aiResult['generate_task_id'] = $generateTaskId;
  1553. // JSON 输出结果的安全校验/修复与观察(不改变 result)
  1554. $this->guardScriptGenerateJsonResult(
  1555. (int)$generateTaskId,
  1556. (int)$script_id,
  1557. (int)$uid,
  1558. (string)getProp($aiResult, 'content', ''),
  1559. (string)$responseFormat
  1560. );
  1561. }
  1562. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  1563. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  1564. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  1565. 'model' => $model,
  1566. 'script_id' => $script_id,
  1567. 'sequence' => $sequence,
  1568. 'source' => 'newGenerateText',
  1569. ]);
  1570. }
  1571. // 新增: 如果提供了script_id,保存对话记录
  1572. if ($script_id > 0 && $aiResult) {
  1573. try {
  1574. $uid = Site::getUid();
  1575. $now = now();
  1576. // 获取用户原始的prompt(不包含剧本内容)
  1577. $originalPrompt = getProp($data, 'prompt', '');
  1578. $recordsToInsert = [
  1579. [
  1580. 'uid' => $uid,
  1581. 'script_id' => $script_id,
  1582. 'sequence' => $sequence,
  1583. 'role' => 'user',
  1584. 'content' => $originalPrompt,
  1585. 'created_at' => $now,
  1586. 'updated_at' => $now,
  1587. ],
  1588. [
  1589. 'uid' => $uid,
  1590. 'script_id' => $script_id,
  1591. 'sequence' => $sequence,
  1592. 'role' => 'assistant',
  1593. 'content' => $aiResult['content'],
  1594. 'created_at' => $now,
  1595. 'updated_at' => $now,
  1596. ]
  1597. ];
  1598. DB::table('mp_script_records')->insert($recordsToInsert);
  1599. // 获取刚插入的记录ID(假设按插入顺序返回)
  1600. $insertedRecords = DB::table('mp_script_records')
  1601. ->where('uid', $uid)
  1602. ->where('script_id', $script_id)
  1603. ->where('sequence', $sequence)
  1604. ->orderBy('id', 'desc')
  1605. ->limit(2)
  1606. ->get()
  1607. ->map(function ($record) {
  1608. return [
  1609. 'rid' => $record->id,
  1610. 'script_id' => $record->script_id,
  1611. 'sequence' => $record->sequence,
  1612. 'role' => $record->role,
  1613. 'content' => $record->content,
  1614. 'created_at' => $record->created_at,
  1615. ];
  1616. })
  1617. ->reverse()
  1618. ->values()
  1619. ->toArray();
  1620. // 将记录信息添加到返回结果中
  1621. $aiResult['records'] = $insertedRecords;
  1622. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  1623. } catch (\Exception $e) {
  1624. // 记录错误但不影响主流程
  1625. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  1626. }
  1627. }
  1628. // 未提供 script_id 或保存失败时,也返回 records 数组(保持返回结构一致)
  1629. if (!isset($aiResult['records'])) {
  1630. $aiResult['records'] = [];
  1631. }
  1632. return $aiResult;
  1633. }
  1634. /**
  1635. * 通用 Gemini 文生文方法(支持流式和非流式)
  1636. *
  1637. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  1638. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  1639. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  1640. * system_prompt 系统提示词(可选)
  1641. * prompt 用户提示词(可选)
  1642. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  1643. * image_urls 图片/视频URL列表(可选,同上)
  1644. * temperature 温度(可选,默认 1)
  1645. * top_p 核采样(可选)
  1646. * max_tokens 最大输出 token(可选,默认 8192)
  1647. * response_format text/json(可选)
  1648. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  1649. * thinking_budget 思考预算(可选,默认 20)
  1650. * stream 是否流式(可选,默认 false)
  1651. *
  1652. * @param array $data 请求参数
  1653. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  1654. */
  1655. public function geminiGenerateText($data) {
  1656. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  1657. $isStream = (bool)getProp($data, 'stream', false);
  1658. if (!in_array($model, $this->gemini_text_models)) {
  1659. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  1660. }
  1661. $requestData = $this->buildGeminiRequestBody($data, $model);
  1662. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  1663. if ($isStream) {
  1664. // 流式返回生成器,成功后记录 token 使用明细(不扣积分)
  1665. return $this->wrapGenerateTextTokenRecord(
  1666. $this->geminiStreamResponse($requestData, $model),
  1667. $this->getCurrentUid(),
  1668. $model,
  1669. 'geminiGenerateText'
  1670. );
  1671. }
  1672. // 非流式:成功后记录 token 使用明细(不扣积分)
  1673. $result = $this->geminiChatOnly($requestData, $model);
  1674. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  1675. 'model' => $model,
  1676. 'source' => 'geminiGenerateText',
  1677. ], $model);
  1678. return $result;
  1679. }
  1680. /**
  1681. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  1682. */
  1683. private function geminiMediaMaxBytes() {
  1684. return 14 * 1024 * 1024;
  1685. }
  1686. /**
  1687. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  1688. */
  1689. private function buildGeminiRequestBody($data, $model) {
  1690. $messages = getProp($data, 'messages', []);
  1691. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  1692. if (empty($messages)) {
  1693. $systemPrompt = getProp($data, 'system_prompt', '');
  1694. $prompt = getProp($data, 'prompt', '');
  1695. $images = getProp($data, 'images', []);
  1696. $imageUrls = getProp($data, 'image_urls', []);
  1697. $messages = [];
  1698. if (!empty($systemPrompt)) {
  1699. $messages[] = [
  1700. 'role' => 'system',
  1701. 'content' => $systemPrompt
  1702. ];
  1703. }
  1704. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1705. $userMessage = ['role' => 'user', 'content' => []];
  1706. if (!empty($prompt)) {
  1707. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  1708. }
  1709. if (!empty($images)) {
  1710. if (!is_array($images)) {
  1711. $images = [$images];
  1712. }
  1713. foreach ($images as $image) {
  1714. $inlineData = $this->processMediaToInlineData($image);
  1715. if ($inlineData) {
  1716. $userMessage['content'][] = [
  1717. 'type' => 'image',
  1718. 'inline_data' => $inlineData
  1719. ];
  1720. }
  1721. }
  1722. }
  1723. if (!empty($imageUrls)) {
  1724. if (!is_array($imageUrls)) {
  1725. $imageUrls = [$imageUrls];
  1726. }
  1727. foreach ($imageUrls as $url) {
  1728. if (!empty($url)) {
  1729. $inlineData = $this->processMediaToInlineData($url);
  1730. if ($inlineData) {
  1731. $userMessage['content'][] = [
  1732. 'type' => 'image',
  1733. 'inline_data' => $inlineData
  1734. ];
  1735. }
  1736. }
  1737. }
  1738. }
  1739. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  1740. $userMessage['content'] = $userMessage['content'][0]['text'];
  1741. }
  1742. $messages[] = $userMessage;
  1743. }
  1744. }
  1745. if (empty($messages)) {
  1746. Utils::throwError('20003:请提供有效的对话内容');
  1747. }
  1748. // 转换为 Gemini contents 格式
  1749. $systemInstruction = '';
  1750. $contents = [];
  1751. foreach ($messages as $message) {
  1752. $role = getProp($message, 'role', 'user');
  1753. $content = getProp($message, 'content', '');
  1754. if ($role === 'system') {
  1755. if (is_array($content)) {
  1756. $systemInstruction = $this->extractGeminiTextFromParts($content);
  1757. } else {
  1758. $systemInstruction = (string)$content;
  1759. }
  1760. continue;
  1761. }
  1762. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  1763. $parts = [];
  1764. if (is_array($content)) {
  1765. foreach ($content as $part) {
  1766. $partType = getProp($part, 'type', 'text');
  1767. if ($partType === 'text') {
  1768. $text = (string)getProp($part, 'text', '');
  1769. if ($text !== '') {
  1770. $parts[] = ['text' => $text];
  1771. }
  1772. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  1773. if (in_array($partType, ['image_url', 'video_url'])) {
  1774. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  1775. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  1776. } elseif (isset($part['inline_data'])) {
  1777. // 已处理过的 inline_data 直接使用
  1778. $parts[] = ['inline_data' => $part['inline_data']];
  1779. continue;
  1780. } else {
  1781. $url = '';
  1782. }
  1783. $inlineData = $this->processMediaToInlineData($url);
  1784. if ($inlineData) {
  1785. $parts[] = ['inline_data' => $inlineData];
  1786. }
  1787. }
  1788. }
  1789. } else {
  1790. $text = (string)$content;
  1791. if ($text !== '') {
  1792. $parts[] = ['text' => $text];
  1793. }
  1794. }
  1795. if (!empty($parts)) {
  1796. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  1797. }
  1798. }
  1799. if (empty($contents)) {
  1800. Utils::throwError('20003:请提供有效的对话内容');
  1801. }
  1802. // 构建生成配置
  1803. $generationConfig = [];
  1804. if (getProp($data, 'temperature', null) !== null) {
  1805. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  1806. }
  1807. if (getProp($data, 'top_p', null) !== null) {
  1808. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  1809. }
  1810. if (getProp($data, 'frequency_penalty', null) !== null) {
  1811. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  1812. }
  1813. if (getProp($data, 'presence_penalty', null) !== null) {
  1814. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  1815. }
  1816. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  1817. if ($maxOutputTokens <= 0) {
  1818. $maxOutputTokens = 8192;
  1819. }
  1820. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  1821. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  1822. $maxOutputTokens = 32768;
  1823. }
  1824. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  1825. // response_format 映射:text -> text/plain,json -> application/json
  1826. $responseFormat = getProp($data, 'response_format', 'text');
  1827. if (is_array($responseFormat)) {
  1828. $responseFormat = getProp($responseFormat, 'type', 'text');
  1829. }
  1830. if (in_array($responseFormat, ['json', 'json_object'])) {
  1831. $generationConfig['responseMimeType'] = 'application/json';
  1832. } else {
  1833. $generationConfig['responseMimeType'] = 'text/plain';
  1834. }
  1835. $requestData = [
  1836. 'contents' => $contents,
  1837. 'generationConfig' => $generationConfig,
  1838. ];
  1839. if ($systemInstruction !== '') {
  1840. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  1841. }
  1842. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  1843. $thinkingMode = getProp($data, 'thinking', null);
  1844. if (is_array($thinkingMode)) {
  1845. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  1846. }
  1847. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  1848. if ($thinkingMode === null) {
  1849. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  1850. }
  1851. if ($thinkingMode === 'enabled') {
  1852. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  1853. if ($thinkingBudget <= 0) {
  1854. $thinkingBudget = 20;
  1855. }
  1856. $requestData['generationConfig']['thinkingConfig'] = [
  1857. 'thinkingBudget' => $thinkingBudget
  1858. ];
  1859. } elseif ($defaultThinking) {
  1860. // 该模型仅支持思考模式,传 0 会返回 400
  1861. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  1862. } else {
  1863. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  1864. }
  1865. return $requestData;
  1866. }
  1867. /**
  1868. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  1869. *
  1870. * 模型名 -> env 变量名映射:
  1871. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  1872. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  1873. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  1874. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  1875. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  1876. */
  1877. private function getGeminiApiKey($model) {
  1878. $map = [
  1879. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  1880. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  1881. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  1882. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  1883. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  1884. ];
  1885. if (isset($map[$model])) {
  1886. $key = env($map[$model]);
  1887. if (!empty($key)) {
  1888. return $key;
  1889. }
  1890. }
  1891. return env('GEMINI_API_KEY', '');
  1892. }
  1893. /**
  1894. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  1895. */
  1896. private function geminiChatOnly($requestData, $model) {
  1897. $apiKey = $this->getGeminiApiKey($model);
  1898. if (empty($apiKey)) {
  1899. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1900. }
  1901. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1902. if (isset($requestData['messages'])) {
  1903. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1904. }
  1905. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1906. . '/models/' . $model . ':generateContent';
  1907. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1908. $headers = [
  1909. 'Authorization' => 'Bearer ' . $apiKey,
  1910. 'Content-Type' => 'application/json'
  1911. ];
  1912. $maxRetries = $this->gptRetryTimes();
  1913. $interval = $this->gptRetryInterval();
  1914. $attempt = 0;
  1915. while (true) {
  1916. try {
  1917. $response = $client->post($url, [
  1918. 'json' => $requestData,
  1919. 'headers' => $headers
  1920. ]);
  1921. $responseArr = json_decode($response->getBody()->getContents(), true);
  1922. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  1923. $fullContent = $this->extractGeminiContent($responseArr);
  1924. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  1925. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  1926. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  1927. ? $responseArr['candidates'][0]['finishReason']
  1928. : '';
  1929. return [
  1930. 'fullContent' => $fullContent,
  1931. 'fullReasoningContent' => $fullReasoningContent,
  1932. 'usage' => $usage,
  1933. 'finish_reason' => $finishReason
  1934. ];
  1935. } catch (\Exception $e) {
  1936. $retryable = true;
  1937. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1938. $status = $e->getResponse()->getStatusCode();
  1939. $retryable = $status >= 500 || $status == 429;
  1940. }
  1941. if (!$retryable || $attempt >= $maxRetries) {
  1942. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  1943. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  1944. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  1945. }
  1946. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  1947. 'retry' => $attempt + 1,
  1948. 'max_retries' => $maxRetries,
  1949. 'error' => $e->getMessage()
  1950. ]);
  1951. sleep($interval);
  1952. $attempt++;
  1953. }
  1954. }
  1955. }
  1956. /**
  1957. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  1958. */
  1959. private function geminiStreamResponse($requestData, $model) {
  1960. $apiKey = $this->getGeminiApiKey($model);
  1961. if (empty($apiKey)) {
  1962. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1963. }
  1964. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1965. if (isset($requestData['messages'])) {
  1966. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1967. }
  1968. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1969. . '/models/' . $model . ':generateContent?alt=sse';
  1970. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1971. $headers = [
  1972. 'Authorization' => 'Bearer ' . $apiKey,
  1973. 'Content-Type' => 'application/json'
  1974. ];
  1975. try {
  1976. $response = $client->post($url, [
  1977. 'json' => $requestData,
  1978. 'headers' => $headers,
  1979. 'stream' => true
  1980. ]);
  1981. $body = $response->getBody();
  1982. $fullContent = '';
  1983. $fullReasoningContent = '';
  1984. $usage = [];
  1985. $buffer = '';
  1986. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1987. while (!$body->eof()) {
  1988. $chunk = $body->read(1024);
  1989. $buffer .= $chunk;
  1990. $lines = explode("\n", $buffer);
  1991. $buffer = array_pop($lines);
  1992. foreach ($lines as $line) {
  1993. $line = trim($line);
  1994. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1995. continue;
  1996. }
  1997. $data = substr($line, 6);
  1998. if ($data === '[DONE]') {
  1999. break 2;
  2000. }
  2001. try {
  2002. $json = json_decode($data, true);
  2003. if (json_last_error() !== JSON_ERROR_NONE) {
  2004. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2005. continue;
  2006. }
  2007. // 思考内容(thoughts)
  2008. $thoughts = $this->extractGeminiThoughts($json);
  2009. if ($thoughts !== '') {
  2010. $fullReasoningContent .= $thoughts;
  2011. yield [
  2012. 'type' => 'reasoning',
  2013. 'content' => $thoughts,
  2014. 'full_reasoning' => $fullReasoningContent
  2015. ];
  2016. }
  2017. // 回答内容
  2018. $partText = $this->extractGeminiContent($json);
  2019. if ($partText !== '') {
  2020. $fullContent .= $partText;
  2021. yield [
  2022. 'type' => 'content',
  2023. 'content' => $partText,
  2024. ];
  2025. }
  2026. // 使用统计
  2027. if (isset($json['usageMetadata'])) {
  2028. $usage = $json['usageMetadata'];
  2029. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  2030. }
  2031. } catch (\Exception $e) {
  2032. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2033. continue;
  2034. }
  2035. }
  2036. }
  2037. dLog('deepseek')->info('Gemini流式读取完成', [
  2038. 'content_length' => strlen($fullContent),
  2039. 'reasoning_length' => strlen($fullReasoningContent)
  2040. ]);
  2041. yield [
  2042. 'type' => 'done',
  2043. 'full_content' => $fullContent,
  2044. 'full_reasoning' => $fullReasoningContent,
  2045. 'usage' => $usage
  2046. ];
  2047. } catch (\Exception $e) {
  2048. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  2049. yield [
  2050. 'type' => 'error',
  2051. 'msg' => $e->getMessage(),
  2052. 'code' => $e->getCode()
  2053. ];
  2054. }
  2055. }
  2056. /**
  2057. * 从 Gemini 响应中提取回答文本
  2058. */
  2059. private function extractGeminiContent($responseArr) {
  2060. $text = '';
  2061. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  2062. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  2063. if (isset($part['text'])) {
  2064. $text .= $part['text'];
  2065. }
  2066. }
  2067. }
  2068. return $text;
  2069. }
  2070. /**
  2071. * 从 Gemini 响应中提取思考内容
  2072. */
  2073. private function extractGeminiReasoningContent($responseArr) {
  2074. $reasoning = '';
  2075. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  2076. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  2077. if (isset($thought['text'])) {
  2078. $reasoning .= $thought['text'];
  2079. }
  2080. }
  2081. }
  2082. return $reasoning;
  2083. }
  2084. /**
  2085. * 从 Gemini 流式响应中提取本次增量思考内容
  2086. */
  2087. private function extractGeminiThoughts($responseArr) {
  2088. $thoughts = '';
  2089. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  2090. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  2091. if (isset($thought['text'])) {
  2092. $thoughts .= $thought['text'];
  2093. }
  2094. }
  2095. }
  2096. return $thoughts;
  2097. }
  2098. /**
  2099. * 提取消息数组中的纯文本
  2100. */
  2101. private function extractGeminiTextFromParts($parts) {
  2102. $text = '';
  2103. if (is_array($parts)) {
  2104. foreach ($parts as $part) {
  2105. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  2106. $text .= (string)getProp($part, 'text', '');
  2107. }
  2108. }
  2109. }
  2110. return $text;
  2111. }
  2112. /**
  2113. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  2114. *
  2115. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  2116. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  2117. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  2118. *
  2119. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  2120. * @return array|null ['mime_type' => string, 'data' => string]
  2121. */
  2122. private function processMediaToInlineData($media) {
  2123. if (empty($media)) {
  2124. return null;
  2125. }
  2126. $localPath = null;
  2127. $isTempFile = false;
  2128. try {
  2129. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  2130. if (is_string($media) && strpos($media, 'data:') === 0) {
  2131. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  2132. return [
  2133. 'mime_type' => $matches[1],
  2134. 'data' => $matches[2]
  2135. ];
  2136. }
  2137. return null;
  2138. }
  2139. // 2. 获取本地文件路径
  2140. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  2141. $localPath = $this->downloadMediaToTemp($media);
  2142. $isTempFile = true;
  2143. } elseif (is_string($media)) {
  2144. $localPath = $media;
  2145. } else {
  2146. // Laravel UploadedFile 对象
  2147. $localPath = $media->getRealPath();
  2148. }
  2149. if (!$localPath || !file_exists($localPath)) {
  2150. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  2151. return null;
  2152. }
  2153. $fileSize = filesize($localPath);
  2154. $maxBytes = $this->geminiMediaMaxBytes();
  2155. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  2156. $mimeType = $this->detectMediaMime($localPath);
  2157. $isVideo = strpos($mimeType, 'video/') === 0;
  2158. $needCompress = $fileSize > $maxBytes;
  2159. $duration = 0;
  2160. if ($isVideo) {
  2161. $duration = $this->getMediaDuration($localPath);
  2162. if ($duration > 300) {
  2163. $needCompress = true;
  2164. }
  2165. }
  2166. $finalPath = $localPath;
  2167. $compressedPath = null;
  2168. if ($needCompress && $this->ffmpegAvailable()) {
  2169. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  2170. if ($compressed && file_exists($compressed)) {
  2171. $compressedPath = $compressed;
  2172. if (filesize($compressed) < $fileSize || $isVideo) {
  2173. $finalPath = $compressed;
  2174. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  2175. } else {
  2176. @unlink($compressed);
  2177. $compressedPath = null;
  2178. }
  2179. }
  2180. }
  2181. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  2182. $finalSize = filesize($finalPath);
  2183. if ($finalSize > $maxBytes) {
  2184. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  2185. 'path' => $localPath,
  2186. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  2187. 'limit_mb' => 14
  2188. ]);
  2189. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  2190. }
  2191. // 兜底校验:视频时长超过5分钟且未能压缩成功
  2192. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  2193. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  2194. }
  2195. $data = base64_encode(file_get_contents($finalPath));
  2196. return [
  2197. 'mime_type' => $mimeType,
  2198. 'data' => $data
  2199. ];
  2200. } catch (\App\Exceptions\ApiException $e) {
  2201. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  2202. throw $e;
  2203. } catch (\Exception $e) {
  2204. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  2205. return null;
  2206. } finally {
  2207. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  2208. @unlink($compressedPath);
  2209. }
  2210. if ($isTempFile && $localPath && file_exists($localPath)) {
  2211. @unlink($localPath);
  2212. }
  2213. }
  2214. }
  2215. /**
  2216. * 下载远程多媒体到临时目录
  2217. *
  2218. * @return string|null 本地临时文件路径
  2219. */
  2220. private function downloadMediaToTemp($url) {
  2221. try {
  2222. $tempDir = storage_path('app/temp/gemini');
  2223. if (!is_dir($tempDir)) {
  2224. mkdir($tempDir, 0775, true);
  2225. }
  2226. $extension = 'tmp';
  2227. $pathInfo = parse_url($url, PHP_URL_PATH);
  2228. if ($pathInfo) {
  2229. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  2230. if ($ext && strlen($ext) <= 10) {
  2231. $extension = strtolower($ext);
  2232. }
  2233. }
  2234. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  2235. $client = new Client(['timeout' => 300, 'verify' => false]);
  2236. $response = $client->get($url, ['sink' => $tmpFile]);
  2237. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  2238. @unlink($tmpFile);
  2239. return null;
  2240. }
  2241. return $tmpFile;
  2242. } catch (\Exception $e) {
  2243. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  2244. return null;
  2245. }
  2246. }
  2247. /**
  2248. * 检测多媒体文件 MIME 类型
  2249. */
  2250. private function detectMediaMime($filePath) {
  2251. $imageInfo = @getimagesize($filePath);
  2252. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  2253. return $imageInfo['mime'];
  2254. }
  2255. // 视频按扩展名粗略判断
  2256. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  2257. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  2258. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  2259. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  2260. if (isset($videoExts[$ext])) {
  2261. return $videoExts[$ext];
  2262. }
  2263. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  2264. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  2265. if (isset($imageExts[$ext])) {
  2266. return $imageExts[$ext];
  2267. }
  2268. return 'application/octet-stream';
  2269. }
  2270. /**
  2271. * 获取多媒体时长(秒),非视频或失败返回 0
  2272. */
  2273. private function getMediaDuration($filePath) {
  2274. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  2275. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  2276. $output = trim((string)shell_exec($cmd));
  2277. $duration = (float)$output;
  2278. return $duration > 0 ? $duration : 0;
  2279. }
  2280. /**
  2281. * 检查 ffmpeg 是否可用
  2282. */
  2283. private function ffmpegAvailable() {
  2284. static $available = null;
  2285. if ($available !== null) {
  2286. return $available;
  2287. }
  2288. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2289. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  2290. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  2291. $available = false;
  2292. return $available;
  2293. }
  2294. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  2295. $output = shell_exec($cmd);
  2296. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  2297. return $available;
  2298. }
  2299. /**
  2300. * 使用 ffmpeg 压缩多媒体文件
  2301. *
  2302. * @param string $inputFile 输入文件路径
  2303. * @param bool $isVideo 是否为视频
  2304. * @param float $duration 视频时长(秒),非视频传 0
  2305. * @return string|null 压缩后的文件路径,失败返回 null
  2306. */
  2307. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  2308. try {
  2309. $tempDir = storage_path('app/temp/gemini');
  2310. if (!is_dir($tempDir)) {
  2311. mkdir($tempDir, 0775, true);
  2312. }
  2313. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  2314. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  2315. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  2316. if ($isVideo) {
  2317. // 视频:时长超过5分钟则加速压缩到5分钟以内
  2318. $speedFactor = 1.0;
  2319. if ($duration > 300) {
  2320. $speedFactor = $duration / 300;
  2321. }
  2322. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  2323. $finalDuration = $duration / max(1.0, $speedFactor);
  2324. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  2325. $targetBitrate = max(300, min(6000, $targetBitrate));
  2326. $filters = [];
  2327. $filters[] = 'scale=min(1280,iw):-2';
  2328. $filters[] = 'fps=24';
  2329. if ($speedFactor > 1.0) {
  2330. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  2331. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  2332. $fullCount = (int)ceil($speedFactor / 2.0);
  2333. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2334. if ($lastTempo < 0.5) {
  2335. $fullCount++;
  2336. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  2337. }
  2338. for ($i = 0; $i < $fullCount; $i++) {
  2339. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  2340. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  2341. }
  2342. }
  2343. $filterStr = implode(',', $filters);
  2344. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  2345. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  2346. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  2347. } else {
  2348. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  2349. $imageInfo = @getimagesize($inputFile);
  2350. $scaleW = 2048;
  2351. $scaleH = 2048;
  2352. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  2353. if ($imageInfo[0] >= $imageInfo[1]) {
  2354. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  2355. $scaleW = 2048;
  2356. } else {
  2357. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  2358. $scaleH = 2048;
  2359. }
  2360. }
  2361. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  2362. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  2363. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  2364. }
  2365. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  2366. $output = shell_exec($cmd);
  2367. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  2368. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  2369. 'input' => $inputFile,
  2370. 'output' => $output
  2371. ]);
  2372. @unlink($outputFile);
  2373. return null;
  2374. }
  2375. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  2376. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  2377. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  2378. ]);
  2379. return $outputFile;
  2380. } catch (\Exception $e) {
  2381. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  2382. return null;
  2383. }
  2384. }
  2385. /**
  2386. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  2387. *
  2388. * @param array $data
  2389. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  2390. */
  2391. public function getScriptGenerateTasks($data) {
  2392. $uid = Site::getUid();
  2393. return DB::table('mp_script_generate_tasks as t')
  2394. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  2395. ->where('t.uid', $uid)
  2396. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  2397. ->orderByDesc('t.id')
  2398. ->paginate(15);
  2399. }
  2400. public function saveScriptChatHistory($data) {
  2401. $uid = Site::getUid();
  2402. $rid = getProp($data, 'rid');
  2403. $script_id = getProp($data, 'script_id');
  2404. $sequence = getProp($data, 'sequence', 0);
  2405. $content = getProp($data, 'content');
  2406. if (!$rid) {
  2407. Utils::throwError('20003:请选择对话记录ID');
  2408. }
  2409. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  2410. if (!$record) {
  2411. Utils::throwError('20003:对话记录不存在');
  2412. }
  2413. if (!$script_id) {
  2414. Utils::throwError('20003:请选择剧本');
  2415. }
  2416. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  2417. if (!$script) {
  2418. Utils::throwError('20003:剧本不存在');
  2419. }
  2420. // 批量插入数据
  2421. return DB::table('mp_script_records')->where('id', $rid)->update([
  2422. 'content' => $content,
  2423. 'updated_at' => date('Y-m-d H:i:s')
  2424. ]);
  2425. }
  2426. /**
  2427. * 获取剧本的历史对话记录
  2428. *
  2429. * @param array $data 请求参数
  2430. * @return array 返回历史记录数组
  2431. */
  2432. public function getScriptChatHistory($data) {
  2433. $uid = Site::getUid();
  2434. $script_id = getProp($data, 'script_id');
  2435. $rid = getProp($data, 'rid');
  2436. $sequence = getProp($data, 'sequence', null);
  2437. if (!$script_id) {
  2438. Utils::throwError('20003:请提供剧本ID');
  2439. }
  2440. // 验证剧本是否存在
  2441. $script = DB::table('mp_scripts')
  2442. ->where('id', $script_id)
  2443. ->where('is_deleted', 0)
  2444. ->first();
  2445. if (!$script) {
  2446. Utils::throwError('20003:剧本不存在');
  2447. }
  2448. // 构建查询
  2449. $query = DB::table('mp_script_records')
  2450. ->where('script_id', $script_id);
  2451. // ->where('uid', $uid);
  2452. // 如果提供了 sequence,则过滤指定剧集
  2453. if ($sequence !== null) {
  2454. $query->where('sequence', $sequence);
  2455. }
  2456. // 记录ID筛选
  2457. if ($rid) {
  2458. $query->where('id', $rid);
  2459. }
  2460. // 查询记录并按 id 正序排序
  2461. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  2462. ->orderBy('created_at', 'asc')
  2463. ->orderBy('id', 'asc')
  2464. ->get()
  2465. ->map(function ($record) {
  2466. return [
  2467. 'rid' => $record->id,
  2468. 'script_id' => $record->script_id,
  2469. 'sequence' => $record->sequence,
  2470. 'role' => $record->role,
  2471. 'content' => $record->content,
  2472. 'products' => $record->products ? json_decode($record->products) : [],
  2473. 'created_at' => $record->created_at,
  2474. ];
  2475. })
  2476. ->toArray();
  2477. return $records;
  2478. }
  2479. /**
  2480. * 处理图片转换为base64
  2481. *
  2482. * @param mixed $image 图片文件对象或文件路径
  2483. * @return string|null base64编码的图片数据
  2484. */
  2485. private function processImageToBase64($image) {
  2486. try {
  2487. // 获取文件路径
  2488. if (is_string($image)) {
  2489. $filePath = $image;
  2490. } else {
  2491. // Laravel UploadedFile 对象
  2492. $filePath = $image->getRealPath();
  2493. }
  2494. if (!file_exists($filePath)) {
  2495. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  2496. return null;
  2497. }
  2498. // 验证是否为图片文件
  2499. $imageInfo = @getimagesize($filePath);
  2500. if ($imageInfo === false) {
  2501. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  2502. return null;
  2503. }
  2504. // 读取图片并转换为base64
  2505. $imageData = file_get_contents($filePath);
  2506. $base64Image = base64_encode($imageData);
  2507. dLog('deepseek')->info('图片转换成功', [
  2508. 'size' => strlen($imageData),
  2509. 'type' => $imageInfo['mime']
  2510. ]);
  2511. return $base64Image;
  2512. } catch (\Exception $e) {
  2513. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  2514. return null;
  2515. }
  2516. }
  2517. private function getArtStylePromptMappings($art_style='')
  2518. {
  2519. // 优先从画风表读取(入库后以表数据为准,保持原返回结构:['画风名' => ['aliases' => [...], 'prompt' => "..."]]
  2520. $dbRows = DB::table('mp_art_styles')
  2521. ->where('is_deleted', 0)
  2522. ->orderBy('id')
  2523. ->get(['art_style', 'aliases', 'prompt']);
  2524. if ($dbRows->isNotEmpty()) {
  2525. $arr = [];
  2526. foreach ($dbRows as $row) {
  2527. $arr[$row->art_style] = [
  2528. 'aliases' => is_string($row->aliases) ? json_decode($row->aliases, true) : [],
  2529. 'prompt' => (string)$row->prompt,
  2530. ];
  2531. }
  2532. if ($art_style) {
  2533. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2534. }
  2535. return $arr;
  2536. }
  2537. $arr = [
  2538. '唯美真人风格' => [
  2539. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2540. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  2541. ],
  2542. '真人古风风格' => [
  2543. 'aliases' => ['真人古风风格', '真人古风'],
  2544. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  2545. ],
  2546. '日系动漫风格' => [
  2547. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2548. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  2549. ],
  2550. '国漫风格' => [
  2551. 'aliases' => ['国漫风格', '国漫'],
  2552. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  2553. ],
  2554. 'Q版卡通风格' => [
  2555. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2556. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  2557. ],
  2558. '简约扁平风格' => [
  2559. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2560. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  2561. ],
  2562. '武侠风格' => [
  2563. 'aliases' => ['武侠风格', '武侠'],
  2564. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  2565. ],
  2566. '古风仙侠风格' => [
  2567. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2568. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  2569. ],
  2570. '新中式水墨风格' => [
  2571. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2572. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  2573. ],
  2574. '写实插画风格' => [
  2575. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2576. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  2577. ],
  2578. '3D卡通风格' => [
  2579. 'aliases' => ['3D卡通风格', '3D卡通'],
  2580. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  2581. ],
  2582. '条漫风格' => [
  2583. 'aliases' => ['条漫风格', '条漫'],
  2584. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  2585. ],
  2586. '赛博朋克风格' => [
  2587. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2588. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  2589. ],
  2590. '暗黑悬疑风格' => [
  2591. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2592. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  2593. ],
  2594. '治愈清新风格' => [
  2595. 'aliases' => ['治愈清新风格', '治愈清新'],
  2596. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  2597. ],
  2598. '3D真人风格' => [
  2599. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  2600. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  2601. ],
  2602. ];
  2603. if($art_style) {
  2604. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2605. }
  2606. return $arr;
  2607. $arr = [
  2608. '唯美真人风格' => [
  2609. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2610. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  2611. 2. 色彩色调
  2612. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  2613. 3. 画质精度
  2614. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  2615. 4. 画面观感
  2616. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  2617. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  2618. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  2619. ],
  2620. '真人古风风格' => [
  2621. 'aliases' => ['真人古风风格', '真人古风'],
  2622. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  2623. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  2624. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  2625. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  2626. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  2627. ],
  2628. '日系动漫风格' => [
  2629. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2630. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  2631. 正向提示词(中文)
  2632. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  2633. 必须遵守规则
  2634. • 全程保持日系动漫风格,不混入其他画风
  2635. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  2636. • 画面适配所选画面比例,构图居中,主体突出
  2637. • 线条干净、色彩统一,不杂乱、不突兀
  2638. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  2639. ],
  2640. '国漫风格' => [
  2641. 'aliases' => ['国漫风格', '国漫'],
  2642. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  2643. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  2644. 必须遵守规则
  2645. • 严格保持国漫画风,不串风格、不混画风
  2646. • 角色形象统一,不随意改变五官、身材、服饰
  2647. • 画面构图稳定,适合漫剧叙事展示
  2648. • 色调统一,不出现脏色、杂色
  2649. 禁止/避免词汇
  2650. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  2651. ],
  2652. 'Q版卡通风格' => [
  2653. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2654. 'prompt' => "风格说明
  2655. 头大身小,造型可爱圆润,简约干净
  2656. 正向提示词(中文)
  2657. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  2658. 必须遵守规则
  2659. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  2660. • 角色造型统一,表情可爱,不诡异
  2661. • 画面简洁清爽,无多余复杂元素
  2662. • 色彩明亮柔和,不刺眼
  2663. 禁止/避免词汇
  2664. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  2665. ],
  2666. '简约扁平风格' => [
  2667. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2668. 'prompt' => "风格说明
  2669. 色块简洁、无复杂渐变,现代极简风
  2670. 正向提示词(中文)
  2671. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  2672. 必须遵守规则
  2673. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  2674. • 构图简洁,主体突出,无多余装饰
  2675. • 色彩统一、干净,不杂乱
  2676. 禁止/避免词汇
  2677. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  2678. ],
  2679. '武侠风格' => [
  2680. 'aliases' => ['武侠风格', '武侠'],
  2681. 'prompt' => "风格说明
  2682. 江湖气息,线条硬朗,动作感强
  2683. 正向提示词(中文)
  2684. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  2685. 必须遵守规则
  2686. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  2687. • 角色形象、服饰、身材比例统一
  2688. • 画面动作自然,不扭曲、不畸形
  2689. 禁止/避免词汇
  2690. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  2691. ],
  2692. '古风仙侠风格' => [
  2693. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2694. 'prompt' => "风格说明
  2695. 飘逸汉服、云雾仙气、唯美空灵
  2696. 正向提示词(中文)
  2697. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  2698. 必须遵守规则
  2699. • 保持古风仙侠统一画风,不混入现代、科幻元素
  2700. • 角色服饰、发型、形象前后一致
  2701. • 场景仙气飘逸,色调清雅统一
  2702. • 画面唯美柔和,不阴暗、不诡异
  2703. 禁止/避免词汇
  2704. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  2705. ],
  2706. '新中式水墨风格' => [
  2707. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2708. 'prompt' => "风格说明
  2709. 淡墨渲染,毛笔笔触,留白意境
  2710. 正向提示词(中文)
  2711. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  2712. 必须遵守规则
  2713. • 严格保持水墨质感,不混入厚涂、写实、卡通
  2714. • 色调淡雅统一,不浓艳杂乱
  2715. • 画面干净有意境,不堆砌元素
  2716. 禁止/避免词汇
  2717. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  2718. ],
  2719. '写实插画风格' => [
  2720. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2721. 'prompt' => "风格说明
  2722. 接近真人比例,光影真实,质感细腻
  2723. 正向提示词(中文)
  2724. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  2725. 必须遵守规则
  2726. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  2727. • 角色五官、身材、服饰高度统一
  2728. • 画面清晰、光影自然、不扭曲
  2729. 禁止/避免词汇
  2730. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  2731. ],
  2732. '3D卡通风格' => [
  2733. 'aliases' => ['3D卡通风格', '3D卡通'],
  2734. 'prompt' => "风格说明
  2735. 3D建模质感,柔和渲染,圆润可爱
  2736. 正向提示词(中文)
  2737. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  2738. 必须遵守规则
  2739. • 保持3D卡通统一质感,不出现2D杂乱线条
  2740. • 角色模型、比例、形象前后一致
  2741. • 画面干净,不模糊、不穿模
  2742. 禁止/避免词汇
  2743. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  2744. ],
  2745. '条漫风格' => [
  2746. 'aliases' => ['条漫风格', '条漫'],
  2747. 'prompt' => "风格说明
  2748. 纵向分镜,上下滑动阅读,轻量化
  2749. 正向提示词(中文)
  2750. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  2751. 必须遵守规则
  2752. • 保持条漫纵向阅读逻辑,构图简洁
  2753. • 画风统一,不混写实、3D、水墨
  2754. • 画面干净,不杂乱
  2755. 禁止/避免词汇
  2756. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  2757. ],
  2758. '赛博朋克风格' => [
  2759. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2760. 'prompt' => "风格说明
  2761. 霓虹灯光、未来都市、暗色调、科技机械
  2762. 正向提示词(中文)
  2763. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  2764. 必须遵守规则
  2765. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  2766. • 色调以暗调+霓虹为主,色彩统一
  2767. • 画面科技感强,不杂乱
  2768. 禁止/避免词汇
  2769. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  2770. ],
  2771. '暗黑悬疑风格' => [
  2772. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2773. 'prompt' => "风格说明
  2774. 低饱和、冷色调、阴影重、神秘压抑
  2775. 正向提示词(中文)
  2776. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  2777. 必须遵守规则
  2778. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  2779. • 画面氛围压抑神秘,但不低俗、不血腥
  2780. • 角色形象统一,不崩坏
  2781. 禁止/避免词汇
  2782. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  2783. ],
  2784. '治愈清新风格' => [
  2785. 'aliases' => ['治愈清新风格', '治愈清新'],
  2786. 'prompt' => "风格说明
  2787. 马卡龙色系、柔光、温暖干净
  2788. 正向提示词(中文)
  2789. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  2790. 必须遵守规则
  2791. • 保持治愈清新统一色调,不阴暗、不诡异
  2792. • 画面柔和干净,无杂乱元素
  2793. • 角色形象柔和可爱,不狰狞
  2794. 禁止/避免词汇
  2795. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  2796. ],
  2797. ];
  2798. return $arr;
  2799. }
  2800. public function getArtStylePromptByInput($inputArtStyle): string
  2801. {
  2802. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  2803. if ($normalizedInput === '') {
  2804. return '';
  2805. }
  2806. return $this->getArtStylePromptMappings($normalizedInput);
  2807. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  2808. // foreach ($mapping['aliases'] as $alias) {
  2809. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  2810. // if ($normalizedAlias === '') {
  2811. // continue;
  2812. // }
  2813. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  2814. // return $mapping['prompt'];
  2815. // }
  2816. // }
  2817. // }
  2818. return '';
  2819. }
  2820. public function getArtStyleShortPromptByInput($inputArtStyle) {
  2821. // 优先从画风表读取;character_prefix/scene_prefix 缺失时用通用 prompt 兜底,均缺失则返回空数组
  2822. $row = DB::table('mp_art_styles')
  2823. ->where('art_style', $inputArtStyle)
  2824. ->where('is_deleted', 0)
  2825. ->first(['character_prefix', 'scene_prefix', 'prompt']);
  2826. if ($row) {
  2827. $prompt = (string)$row->prompt;
  2828. $result = [
  2829. 'character_prefix' => (string)$row->character_prefix !== '' ? (string)$row->character_prefix : $prompt,
  2830. 'scene_prefix' => (string)$row->scene_prefix !== '' ? (string)$row->scene_prefix : $prompt,
  2831. ];
  2832. // 前缀与通用提示词均不存在时返回空数组
  2833. if ($result['character_prefix'] === '' && $result['scene_prefix'] === '') {
  2834. return [];
  2835. }
  2836. return $result;
  2837. }
  2838. $stylePrefixes = [
  2839. '唯美真人风格' => [
  2840. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  2841. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强',
  2842. 'prompt' => '唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质'
  2843. ],
  2844. '真人古风风格' => [
  2845. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  2846. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清',
  2847. 'prompt' => '真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清'
  2848. ],
  2849. '日系动漫风格' => [
  2850. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  2851. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强',
  2852. 'prompt' => '日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影'
  2853. ],
  2854. '国漫风格' => [
  2855. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  2856. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染',
  2857. 'prompt' => '国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节'
  2858. ],
  2859. 'Q版卡通风格' => [
  2860. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  2861. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感',
  2862. 'prompt' => 'Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画'
  2863. ],
  2864. '简约扁平风格' => [
  2865. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  2866. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽',
  2867. 'prompt' => '简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽'
  2868. ],
  2869. '武侠风格' => [
  2870. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  2871. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学',
  2872. 'prompt' => '武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制'
  2873. ],
  2874. '古风仙侠风格' => [
  2875. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  2876. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学',
  2877. 'prompt' => '古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面'
  2878. ],
  2879. '新中式水墨风格' => [
  2880. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  2881. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景',
  2882. 'prompt' => '新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感'
  2883. ],
  2884. '写实插画风格' => [
  2885. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  2886. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图',
  2887. 'prompt' => '写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染'
  2888. ],
  2889. '3D卡通风格' => [
  2890. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  2891. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染',
  2892. 'prompt' => '3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富'
  2893. ],
  2894. '条漫风格' => [
  2895. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  2896. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感',
  2897. 'prompt' => '条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制'
  2898. ],
  2899. '赛博朋克风格' => [
  2900. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  2901. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影',
  2902. 'prompt' => '赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染'
  2903. ],
  2904. '暗黑悬疑风格' => [
  2905. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  2906. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图',
  2907. 'prompt' => '暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现'
  2908. ],
  2909. '治愈清新风格' => [
  2910. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  2911. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强',
  2912. 'prompt' => '治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足'
  2913. ]
  2914. ];
  2915. if (isset($stylePrefixes[$inputArtStyle])) {
  2916. $item = $stylePrefixes[$inputArtStyle];
  2917. $prompt = (string)($item['prompt'] ?? '');
  2918. // 前缀缺失时用通用 prompt 兜底
  2919. $result = [
  2920. 'character_prefix' => !empty($item['character_prefix']) ? $item['character_prefix'] : $prompt,
  2921. 'scene_prefix' => !empty($item['scene_prefix']) ? $item['scene_prefix'] : $prompt,
  2922. ];
  2923. // 与表分支一致:前缀与通用提示词均不存在时返回空数组
  2924. if ($result['character_prefix'] === '' && $result['scene_prefix'] === '') {
  2925. return [];
  2926. }
  2927. return $result;
  2928. }
  2929. return [];
  2930. }
  2931. private function normalizeArtStyleInput($value): string
  2932. {
  2933. $value = trim((string)$value);
  2934. if ($value === '') {
  2935. return '';
  2936. }
  2937. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  2938. return mb_strtolower($value, 'UTF-8');
  2939. }
  2940. private function replaceArtStyleSection(string $content, string $artStyle): string
  2941. {
  2942. if ($content === '' || $artStyle === '') {
  2943. return $content;
  2944. }
  2945. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  2946. if (!preg_match($pattern, $content)) {
  2947. return $content;
  2948. }
  2949. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  2950. }
  2951. /**
  2952. * 解开模型偶发返回的 JSON 包装内容
  2953. *
  2954. * @param mixed $content 模型返回的原始内容
  2955. * @return mixed 解开后的内容(若无法解开则原样返回)
  2956. */
  2957. private function unwrapJsonWrappedContent($content) {
  2958. $trimmed = ltrim((string)$content);
  2959. if ($trimmed === '' || ($trimmed[0] !== '{' && $trimmed[0] !== '[')) {
  2960. return $content;
  2961. }
  2962. $decoded = json_decode($trimmed, true);
  2963. if (!is_array($decoded)) {
  2964. return $content;
  2965. }
  2966. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2967. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2968. return $decoded[$key];
  2969. }
  2970. }
  2971. return $content;
  2972. }
  2973. /**
  2974. * 流式文生文统一分发:根据模型路由到对应提供商的流式实现
  2975. *
  2976. * @param array $post_data 请求参数(含 model / messages / stream 等)
  2977. * @return \Generator
  2978. */
  2979. public function dispatchStreamByModel($post_data) {
  2980. // 强制按流式模式分发
  2981. $post_data['stream'] = true;
  2982. $model = (string)getProp($post_data, 'model', '');
  2983. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2984. // DeepSeek 官方模型
  2985. return $this->deepSeekStreamResponse($post_data);
  2986. } else if (in_array($model, $this->gpt_text_models)) {
  2987. // GPT 模型
  2988. return $this->gpt54StreamResponse($post_data);
  2989. } else if (in_array($model, $this->gemini_text_models)) {
  2990. // Gemini 模型
  2991. return $this->geminiStreamResponse($post_data, $model);
  2992. } else if (in_array($model, $this->baidu_glm_text_models)) {
  2993. // 百度 AI 网关 GLM 模型
  2994. return $this->baiduGLMStreamResponse($post_data);
  2995. } else if (in_array($model, $this->valid_text_models)) {
  2996. // 火山引擎等其他模型
  2997. return $this->volcEngineChatCompletion($post_data);
  2998. }
  2999. Utils::throwError('20003:不支持的模型: ' . $model);
  3000. }
  3001. /**
  3002. * 非流式文生文统一分发:根据模型路由到对应提供商的非流式实现
  3003. *
  3004. * @param array $post_data 请求参数(含 model / messages / stream 等)
  3005. * @return array
  3006. */
  3007. public function dispatchChatOnlyByModel($post_data) {
  3008. // 强制按非流式模式分发
  3009. $post_data['stream'] = false;
  3010. $model = (string)getProp($post_data, 'model', '');
  3011. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3012. // DeepSeek 官方模型
  3013. return $this->chatOnly($post_data);
  3014. } else if (in_array($model, $this->gpt_text_models)) {
  3015. // GPT 模型
  3016. return $this->gpt54ChatOnly($post_data);
  3017. } else if (in_array($model, $this->gemini_text_models)) {
  3018. // Gemini 模型
  3019. return $this->geminiChatOnly($post_data, $model);
  3020. } else if (in_array($model, $this->baidu_glm_text_models)) {
  3021. // 百度 AI 网关 GLM 模型
  3022. return $this->baiduGLMChatOnly($post_data);
  3023. } else if (in_array($model, $this->valid_text_models)) {
  3024. // 火山引擎等其他模型
  3025. return $this->volcEngineChatCompletion($post_data);
  3026. }
  3027. Utils::throwError('20003:不支持的模型: ' . $model);
  3028. }
  3029. /**
  3030. * 百度 AI 网关 GLM 流式实现(OpenAI Chat Completions 协议)
  3031. *
  3032. * @param array $post_data 请求参数(前端模型名 baidu-glm-5.2 / baidu-glm-5.3)
  3033. * @return \Generator
  3034. */
  3035. private function baiduGLMStreamResponse($post_data) {
  3036. $payload = $this->buildBaiduGLMPayload($post_data, true);
  3037. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3038. try {
  3039. $response = $client->post('https://ai-gateway.baidubce.com/v1/chat/completions', [
  3040. 'json' => $payload,
  3041. 'headers' => $this->baiduGLMHeaders(),
  3042. 'stream' => true,
  3043. ]);
  3044. } catch (\Exception $e) {
  3045. $errorDetail = $this->extractBaiduGLMErrorDetail($e);
  3046. dLog('deepseek')->error('百度GLM流式请求建立失败: ' . $e->getMessage(), [
  3047. 'payload' => $payload,
  3048. 'detail' => $errorDetail,
  3049. ]);
  3050. Utils::throwError('20003:百度GLM流式请求失败: ' . $errorDetail);
  3051. }
  3052. $body = $response->getBody();
  3053. $buffer = '';
  3054. $fullContent = '';
  3055. $fullReasoning = '';
  3056. $usage = [];
  3057. dLog('deepseek')->info('开始读取百度GLM流式响应');
  3058. try {
  3059. while (!$body->eof()) {
  3060. $chunk = $body->read(1024);
  3061. $buffer .= $chunk;
  3062. $lines = explode("\n", $buffer);
  3063. $buffer = array_pop($lines);
  3064. foreach ($lines as $line) {
  3065. $line = trim($line);
  3066. if (empty($line)) {
  3067. continue;
  3068. }
  3069. if (strpos($line, 'data: ') !== 0) {
  3070. dLog('deepseek')->warning('百度GLM非SSE数据行', ['line' => $line]);
  3071. continue;
  3072. }
  3073. $data = substr($line, 6);
  3074. if ($data === '[DONE]') {
  3075. dLog('deepseek')->info('百度GLM收到结束标记');
  3076. break 2;
  3077. }
  3078. try {
  3079. $json = json_decode($data, true);
  3080. if (json_last_error() !== JSON_ERROR_NONE) {
  3081. dLog('deepseek')->warning('百度GLM JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3082. continue;
  3083. }
  3084. if (isset($json['choices'][0]['delta'])) {
  3085. $delta = $json['choices'][0]['delta'];
  3086. // 思考链内容(兼容 reasoning_content / reasoning 两种字段)
  3087. $reasoningDelta = '';
  3088. if (isset($delta['reasoning_content']) && is_string($delta['reasoning_content'])) {
  3089. $reasoningDelta = $delta['reasoning_content'];
  3090. } elseif (isset($delta['reasoning']) && is_string($delta['reasoning'])) {
  3091. $reasoningDelta = $delta['reasoning'];
  3092. }
  3093. if ($reasoningDelta !== '') {
  3094. $fullReasoning .= $reasoningDelta;
  3095. yield [
  3096. 'type' => 'reasoning',
  3097. 'content' => $reasoningDelta,
  3098. 'full_reasoning' => $fullReasoning,
  3099. ];
  3100. }
  3101. // 正文内容
  3102. if (isset($delta['content']) && is_string($delta['content'])) {
  3103. $fullContent .= $delta['content'];
  3104. yield [
  3105. 'type' => 'content',
  3106. 'content' => $delta['content'],
  3107. ];
  3108. }
  3109. }
  3110. if (isset($json['usage'])) {
  3111. $usage = $json['usage'];
  3112. }
  3113. } catch (\Exception $e) {
  3114. dLog('deepseek')->error('百度GLM解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3115. continue;
  3116. }
  3117. }
  3118. }
  3119. } catch (\Exception $e) {
  3120. dLog('deepseek')->error('百度GLM流式读取中断: ' . $e->getMessage());
  3121. throw $e;
  3122. }
  3123. dLog('deepseek')->info('百度GLM流式读取完成', [
  3124. 'content_length' => strlen($fullContent),
  3125. 'reasoning_length' => strlen($fullReasoning),
  3126. ]);
  3127. yield [
  3128. 'type' => 'done',
  3129. 'full_content' => $fullContent,
  3130. 'full_reasoning' => $fullReasoning,
  3131. 'usage' => $usage,
  3132. ];
  3133. }
  3134. /**
  3135. * 百度 AI 网关 GLM 非流式实现(OpenAI Chat Completions 协议)
  3136. *
  3137. * @param array $post_data 请求参数(前端模型名 baidu-glm-5.2 / baidu-glm-5.3)
  3138. * @return array
  3139. */
  3140. private function baiduGLMChatOnly($post_data) {
  3141. $payload = $this->buildBaiduGLMPayload($post_data, false);
  3142. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3143. try {
  3144. $result = $client->post('https://ai-gateway.baidubce.com/v1/chat/completions', [
  3145. 'json' => $payload,
  3146. 'headers' => $this->baiduGLMHeaders(),
  3147. ]);
  3148. $response_arr = json_decode($result->getBody()->getContents(), true);
  3149. dLog('deepseek')->info('百度GLM非流式请求完成', ['response' => $response_arr]);
  3150. $fullContent = '';
  3151. $fullReasoningContent = '';
  3152. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  3153. if (isset($response_arr['choices'][0]['message'])) {
  3154. $message = $response_arr['choices'][0]['message'];
  3155. if (isset($message['content']) && is_string($message['content'])) {
  3156. $fullContent = $message['content'];
  3157. }
  3158. if (isset($message['reasoning_content']) && is_string($message['reasoning_content'])) {
  3159. $fullReasoningContent = $message['reasoning_content'];
  3160. } elseif (isset($message['reasoning']) && is_string($message['reasoning'])) {
  3161. $fullReasoningContent = $message['reasoning'];
  3162. }
  3163. }
  3164. return [
  3165. 'fullContent' => $fullContent,
  3166. 'fullReasoningContent' => $fullReasoningContent,
  3167. 'usage' => $usage,
  3168. ];
  3169. } catch (\Exception $e) {
  3170. $errorDetail = $this->extractBaiduGLMErrorDetail($e);
  3171. dLog('deepseek')->error('百度GLM非流式请求失败: ' . $e->getMessage(), [
  3172. 'payload' => $payload,
  3173. 'detail' => $errorDetail,
  3174. ]);
  3175. Utils::throwError('20003:百度GLM请求失败: ' . $errorDetail);
  3176. }
  3177. }
  3178. /**
  3179. * 组装百度 AI 网关 GLM 请求参数
  3180. *
  3181. * @param array $data 请求参数
  3182. * @param bool $stream 是否流式
  3183. * @return array
  3184. */
  3185. private function buildBaiduGLMPayload(array $data, bool $stream): array
  3186. {
  3187. if (empty(env('BAIDU_GLM_AK'))) {
  3188. Utils::throwError('20003:百度GLM API Key未配置,请检查环境变量BAIDU_GLM_AK');
  3189. }
  3190. $frontModel = (string)getProp($data, 'model', '');
  3191. $externalModel = isset(BaseConst::BAIDU_GLM_MODEL_MAP[$frontModel])
  3192. ? BaseConst::BAIDU_GLM_MODEL_MAP[$frontModel]
  3193. : '';
  3194. if ($externalModel === '') {
  3195. Utils::throwError('20003:不支持的百度GLM模型: ' . $frontModel);
  3196. }
  3197. $messages = getProp($data, 'messages', []);
  3198. if (empty($messages)) {
  3199. Utils::throwError('20003:请提供有效的对话内容');
  3200. }
  3201. // OpenAI Chat Completions 标准参数白名单。
  3202. // 注意:百度 GLM-5.x 始终思考,不支持 thinking 开关(传 disabled 会报 400),
  3203. // 因此不转发 thinking;仅透传网关原生支持的 reasoning_effort(low/high/max)。
  3204. $allowedKeys = [
  3205. 'temperature',
  3206. 'top_p',
  3207. 'max_tokens',
  3208. 'max_completion_tokens',
  3209. 'reasoning_effort',
  3210. 'frequency_penalty',
  3211. 'presence_penalty',
  3212. 'stop',
  3213. 'response_format',
  3214. 'stream_options',
  3215. 'tools',
  3216. 'tool_choice',
  3217. 'user',
  3218. 'seed',
  3219. ];
  3220. $payload = [
  3221. 'model' => $externalModel,
  3222. 'messages' => $messages,
  3223. 'stream' => $stream,
  3224. ];
  3225. foreach ($allowedKeys as $key) {
  3226. if (array_key_exists($key, $data) && $data[$key] !== null && $data[$key] !== '') {
  3227. $payload[$key] = $data[$key];
  3228. }
  3229. }
  3230. // 百度网关只接受 low / high / max;其它取值(如 none)会导致 400
  3231. if (isset($payload['reasoning_effort']) && !in_array($payload['reasoning_effort'], ['low', 'high', 'max'], true)) {
  3232. unset($payload['reasoning_effort']);
  3233. }
  3234. if ($stream && !isset($payload['stream_options'])) {
  3235. $payload['stream_options'] = ['include_usage' => true];
  3236. }
  3237. if (!isset($payload['max_tokens']) && !isset($payload['max_completion_tokens'])) {
  3238. // GLM-5.x 输出上限较高,给长文生成留足空间
  3239. $payload['max_tokens'] = 100000;
  3240. }
  3241. return $payload;
  3242. }
  3243. /**
  3244. * 百度 AI 网关 GLM 鉴权请求头
  3245. *
  3246. * @return array
  3247. */
  3248. private function baiduGLMHeaders(): array
  3249. {
  3250. return [
  3251. 'Authorization' => 'Bearer ' . env('BAIDU_GLM_AK'),
  3252. 'Content-Type' => 'application/json; charset=UTF-8',
  3253. 'Accept' => 'text/event-stream',
  3254. ];
  3255. }
  3256. /**
  3257. * 从 Guzzle 异常响应体中提取百度 AI 网关返回的错误信息
  3258. *
  3259. * @param \Exception $e
  3260. * @return string
  3261. */
  3262. private function extractBaiduGLMErrorDetail(\Exception $e): string
  3263. {
  3264. $detail = $e->getMessage();
  3265. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  3266. try {
  3267. $responseBody = (string)$e->getResponse()->getBody();
  3268. $decoded = json_decode($responseBody, true);
  3269. if (is_array($decoded)) {
  3270. if (isset($decoded['error']['message']) && $decoded['error']['message'] !== '') {
  3271. $detail = $decoded['error']['message'];
  3272. } elseif (isset($decoded['message']) && $decoded['message'] !== '') {
  3273. $detail = $decoded['message'];
  3274. } elseif (isset($decoded['error']) && is_string($decoded['error'])) {
  3275. $detail = $decoded['error'];
  3276. }
  3277. } elseif ($responseBody !== '') {
  3278. $detail = $responseBody;
  3279. }
  3280. } catch (\Throwable $parseError) {
  3281. // 保留原始异常信息
  3282. }
  3283. }
  3284. return mb_substr($detail, 0, 500);
  3285. }
  3286. private function deepSeekStreamResponse($post_data) {
  3287. // 设置最大输出tokens
  3288. $post_data['max_tokens'] = 300000;
  3289. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  3290. $post_data['stream_options'] = ['include_usage' => true];
  3291. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3292. $response = $client->post($this->url, [
  3293. 'json' => $post_data,
  3294. 'headers' => $this->headers,
  3295. 'stream' => true // 启用流式响应
  3296. ]);
  3297. $body = $response->getBody();
  3298. $fullContent = '';
  3299. $fullReasoningContent = '';
  3300. $usage = [];
  3301. $buffer = '';
  3302. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  3303. // 逐行读取流式响应
  3304. while (!$body->eof()) {
  3305. $chunk = $body->read(1024); // 每次读取 1KB
  3306. $buffer .= $chunk;
  3307. // 按行分割
  3308. $lines = explode("\n", $buffer);
  3309. // 保留最后一个不完整的行
  3310. $buffer = array_pop($lines);
  3311. foreach ($lines as $line) {
  3312. $line = trim($line);
  3313. // 跳过空行
  3314. if (empty($line)) {
  3315. continue;
  3316. }
  3317. // 检查是否是 SSE 数据行
  3318. if (strpos($line, 'data: ') !== 0) {
  3319. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  3320. continue;
  3321. }
  3322. $data = substr($line, 6); // 移除 "data: " 前缀
  3323. if ($data === '[DONE]') {
  3324. dLog('deepseek')->info('收到结束标记');
  3325. break 2; // 跳出两层循环
  3326. }
  3327. try {
  3328. $json = json_decode($data, true);
  3329. if (json_last_error() !== JSON_ERROR_NONE) {
  3330. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3331. continue;
  3332. }
  3333. if (isset($json['choices'][0]['delta'])) {
  3334. $delta = $json['choices'][0]['delta'];
  3335. // 处理思维链内容(仅 deepseek-reasoner 模型)
  3336. if (isset($delta['reasoning_content'])) {
  3337. $fullReasoningContent .= $delta['reasoning_content'];
  3338. yield [
  3339. 'type' => 'reasoning',
  3340. 'content' => $delta['reasoning_content'],
  3341. 'full_reasoning' => $fullReasoningContent
  3342. ];
  3343. }
  3344. // 处理最终回答内容
  3345. if (isset($delta['content'])) {
  3346. $fullContent .= $delta['content'];
  3347. yield [
  3348. 'type' => 'content',
  3349. 'content' => $delta['content'],
  3350. ];
  3351. }
  3352. }
  3353. // 获取使用统计信息
  3354. if (isset($json['usage'])) {
  3355. $usage = $json['usage'];
  3356. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  3357. }
  3358. } catch (\Exception $e) {
  3359. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3360. continue;
  3361. }
  3362. }
  3363. }
  3364. dLog('deepseek')->info('流式读取完成', [
  3365. 'content_length' => strlen($fullContent),
  3366. 'reasoning_length' => strlen($fullReasoningContent)
  3367. ]);
  3368. yield [
  3369. 'type' => 'done',
  3370. 'full_content' => $fullContent,
  3371. 'full_reasoning' => $fullReasoningContent,
  3372. 'usage' => $usage
  3373. ];
  3374. }
  3375. /**
  3376. * GPT 重试次数(env 可配置,默认 5 次)
  3377. */
  3378. private function gptRetryTimes()
  3379. {
  3380. return (int)env('GPT_RETRY_TIMES', 5);
  3381. }
  3382. /**
  3383. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  3384. */
  3385. private function gptRetryInterval()
  3386. {
  3387. return (int)env('GPT_RETRY_INTERVAL', 10);
  3388. }
  3389. /**
  3390. * 判断 GPT 请求异常是否可重试
  3391. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  3392. */
  3393. private function isGptRetryableException(\Exception $e)
  3394. {
  3395. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  3396. return false;
  3397. }
  3398. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  3399. $status = $e->getResponse()->getStatusCode();
  3400. return $status >= 500 || $status == 429;
  3401. }
  3402. return true;
  3403. }
  3404. /**
  3405. * GPT 中转站探活:GET /v1/models,5 秒短超时
  3406. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  3407. */
  3408. private function checkGptServiceAvailable($apiKey = null)
  3409. {
  3410. if ($apiKey === null) {
  3411. $apiKey = env('GPT_54_API_KEY');
  3412. }
  3413. if (empty($apiKey)) {
  3414. return false;
  3415. }
  3416. try {
  3417. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  3418. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  3419. 'headers' => [
  3420. 'Authorization' => 'Bearer ' . $apiKey,
  3421. 'Content-Type' => 'application/json'
  3422. ]
  3423. ]);
  3424. $status = $response->getStatusCode();
  3425. return $status < 500 && $status != 429;
  3426. } catch (\Exception $e) {
  3427. return false;
  3428. }
  3429. }
  3430. /**
  3431. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  3432. * 全部失败抛出友好错误
  3433. */
  3434. private function ensureGptServiceAvailable($apiKey = null)
  3435. {
  3436. $maxRetries = $this->gptRetryTimes();
  3437. $interval = $this->gptRetryInterval();
  3438. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  3439. if ($this->checkGptServiceAvailable($apiKey)) {
  3440. return;
  3441. }
  3442. if ($attempt < $maxRetries) {
  3443. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  3444. 'retry' => $attempt + 1,
  3445. 'max_retries' => $maxRetries
  3446. ]);
  3447. sleep($interval);
  3448. }
  3449. }
  3450. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  3451. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  3452. 'max_retries' => $maxRetries,
  3453. 'interval' => $interval
  3454. ]);
  3455. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  3456. }
  3457. /**
  3458. * GPT 流式输出处理方法
  3459. *
  3460. * @param array $post_data GPT API请求参数
  3461. * @return \Generator 返回生成器,用于流式输出
  3462. */
  3463. private function gpt54StreamResponse($post_data) {
  3464. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  3465. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  3466. // gpt-5.4 中转已下线,强制映射到 gpt-5.6-sol
  3467. if ($modelName === 'gpt-5.4') {
  3468. $modelName = 'gpt-5.6-terra';
  3469. $post_data['model'] = $modelName;
  3470. }
  3471. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  3472. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  3473. $usedLunaFallback = false;
  3474. // 流式请求长时间无任何返回(TTFB)超过该秒数时切换备用 Key(env 可配置,默认 600 秒)
  3475. $ttfbTimeoutSeconds = (int)env('GPT_SWITCH_LUNA_AFTER_SECONDS', 600);
  3476. if (empty($apiKey)) {
  3477. Utils::throwError('20003:GPT API Key未配置');
  3478. }
  3479. // 先探活,服务不可用时自动重试
  3480. $this->ensureGptServiceAvailable($apiKey);
  3481. $client = new Client(['timeout' => 1800, 'verify' => false, 'read_timeout' => $ttfbTimeoutSeconds]);
  3482. // 移除 thinking 参数,GPT-5.4 不支持
  3483. if (isset($post_data['thinking'])) {
  3484. unset($post_data['thinking']);
  3485. }
  3486. if (isset($post_data['reasoning_effort'])) {
  3487. unset($post_data['reasoning_effort']);
  3488. }
  3489. // 流式场景下保留 response_format(json 输出时强制模型输出完整 JSON,与非流式 gpt54ChatOnly 对齐)
  3490. // 中转站对 response_format 的兼容性由请求方控制:仅在需要 json 输出时传入
  3491. $post_data['max_completion_tokens'] = 100000;
  3492. $post_data['max_tokens'] = 100000;
  3493. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  3494. $post_data['stream_options'] = ['include_usage' => true];
  3495. $maxRetries = $this->gptRetryTimes();
  3496. $interval = $this->gptRetryInterval();
  3497. $attempt = 0;
  3498. while (true) {
  3499. $fullContent = '';
  3500. $usage = [];
  3501. $buffer = '';
  3502. // JSON 输出场景:不启用"整段正文包成 JSON 字符串"的暂缓缓存,流式过程中直接输出供前端展示
  3503. $isJsonRequest = isset($post_data['response_format'])
  3504. && is_array($post_data['response_format'])
  3505. && ($post_data['response_format']['type'] ?? '') === 'json_object';
  3506. $suspectJsonWrap = false;
  3507. $pendingContent = '';
  3508. $requestStartedAt = microtime(true);
  3509. $headers = [
  3510. 'Authorization' => 'Bearer ' . $apiKey,
  3511. 'Content-Type' => 'application/json',
  3512. 'Accept' => 'text/event-stream'
  3513. ];
  3514. try {
  3515. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  3516. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  3517. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  3518. 'json' => $post_data,
  3519. 'headers' => $headers,
  3520. 'stream' => true // 启用流式响应
  3521. ]);
  3522. $body = $response->getBody();
  3523. dLog('deepseek')->info('开始读取 GPT 流式响应');
  3524. // 逐行读取流式响应
  3525. while (!$body->eof()) {
  3526. // 长时间没有任何内容返回时,切换备用 Key 重试
  3527. if ($fullContent === '' && empty($usage) && (microtime(true) - $requestStartedAt) > $ttfbTimeoutSeconds) {
  3528. throw new \RuntimeException('GPT 流式响应长时间无返回,等待切换备用 Key');
  3529. }
  3530. $chunk = $body->read(1024); // 每次读取 1KB
  3531. $buffer .= $chunk;
  3532. // 按行分割
  3533. $lines = explode("\n", $buffer);
  3534. // 保留最后一个不完整的行
  3535. $buffer = array_pop($lines);
  3536. foreach ($lines as $line) {
  3537. $line = trim($line);
  3538. // 跳过空行
  3539. if (empty($line)) {
  3540. continue;
  3541. }
  3542. // 检查是否是 SSE 数据行
  3543. if (strpos($line, 'data: ') !== 0) {
  3544. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  3545. continue;
  3546. }
  3547. $data = substr($line, 6); // 移除 "data: " 前缀
  3548. if ($data === '[DONE]') {
  3549. dLog('deepseek')->info('收到结束标记');
  3550. break 2; // 跳出 foreach 和流读取循环
  3551. }
  3552. try {
  3553. $json = json_decode($data, true);
  3554. if (json_last_error() !== JSON_ERROR_NONE) {
  3555. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  3556. continue;
  3557. }
  3558. if (isset($json['choices'][0]['delta'])) {
  3559. $delta = $json['choices'][0]['delta'];
  3560. // 处理回答内容
  3561. if (isset($delta['content'])) {
  3562. $fullContent .= $delta['content'];
  3563. $trimmed = ltrim($fullContent);
  3564. if (!$suspectJsonWrap && !$isJsonRequest && $trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
  3565. // 可能模型把整段正文包成了 JSON 字符串,先暂缓输出
  3566. $suspectJsonWrap = true;
  3567. }
  3568. if (!$suspectJsonWrap) {
  3569. // 中转可能一次返回大段内容,按小块输出保持流式节奏
  3570. $chunkSize = 256;
  3571. $chunkLength = mb_strlen($delta['content']);
  3572. for ($offset = 0; $offset < $chunkLength; $offset += $chunkSize) {
  3573. yield [
  3574. 'type' => 'content',
  3575. 'content' => mb_substr($delta['content'], $offset, $chunkSize),
  3576. ];
  3577. }
  3578. } else {
  3579. $pendingContent .= $delta['content'];
  3580. }
  3581. }
  3582. }
  3583. // 获取使用统计信息
  3584. if (isset($json['usage'])) {
  3585. $usage = $json['usage'];
  3586. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  3587. }
  3588. } catch (\Exception $e) {
  3589. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  3590. continue;
  3591. }
  3592. }
  3593. }
  3594. dLog('deepseek')->info('流式读取完成', [
  3595. 'content_length' => strlen($fullContent)
  3596. ]);
  3597. // 兼容模型偶发把整段正文包裹成 JSON 字符串返回
  3598. if ($suspectJsonWrap) {
  3599. $decoded = json_decode(trim($fullContent), true);
  3600. $unwrapped = null;
  3601. if (is_array($decoded)) {
  3602. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  3603. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  3604. $unwrapped = $decoded[$key];
  3605. break;
  3606. }
  3607. }
  3608. }
  3609. if ($unwrapped !== null) {
  3610. $fullContent = $unwrapped;
  3611. $chunkSize = 256;
  3612. $contentLength = mb_strlen($fullContent);
  3613. for ($offset = 0; $offset < $contentLength; $offset += $chunkSize) {
  3614. yield [
  3615. 'type' => 'content',
  3616. 'content' => mb_substr($fullContent, $offset, $chunkSize),
  3617. ];
  3618. }
  3619. } elseif ($pendingContent !== '') {
  3620. // 误判:补发暂缓内容,避免内容丢失
  3621. yield [
  3622. 'type' => 'content',
  3623. 'content' => $pendingContent,
  3624. ];
  3625. }
  3626. }
  3627. yield [
  3628. 'type' => 'done',
  3629. 'full_content' => $fullContent,
  3630. 'full_reasoning' => '',
  3631. 'usage' => $usage
  3632. ];
  3633. return;
  3634. } catch (\Exception $e) {
  3635. // 报错或长时间无返回时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  3636. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  3637. $usedLunaFallback = true;
  3638. $apiKey = $lunaApiKey;
  3639. dLog('deepseek')->warning('GPT 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  3640. continue;
  3641. }
  3642. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  3643. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  3644. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  3645. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  3646. throw $e;
  3647. }
  3648. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  3649. 'retry' => $attempt + 1,
  3650. 'max_retries' => $maxRetries,
  3651. 'error' => $e->getMessage()
  3652. ]);
  3653. sleep($interval);
  3654. $attempt++;
  3655. }
  3656. }
  3657. }
  3658. // 与推理模型对话
  3659. public function chatWithReasoner($data) {
  3660. // 文生文计费预检(normal 档)
  3661. $uid = Site::getUid();
  3662. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'normal'), $uid);
  3663. $content = getProp($data, 'content');
  3664. $model = getProp($data, 'model', 'r1');
  3665. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3666. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3667. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3668. if ($model == 'r1') {
  3669. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  3670. $thinkingMode = 'disabled';
  3671. } else {
  3672. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  3673. $thinkingMode = 'disabled';
  3674. }
  3675. // 获取可选情感(根据音色可支持情感选)
  3676. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  3677. $emotion_list = [];
  3678. foreach ($timbre_emotion as $emotion) {
  3679. $tmp = explode(',', $emotion);
  3680. $emotion_list = array_merge($emotion_list, $tmp);
  3681. }
  3682. $emotion_list = array_unique($emotion_list);
  3683. $emotion_str = implode('、', $emotion_list);
  3684. // // 获取可选情感
  3685. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  3686. // $emotion_str = implode('、', $emotion_list);
  3687. // 是否启用情感
  3688. $enable_emotion = getProp($data, 'enable_emotion', 0);
  3689. if ($enable_emotion) {
  3690. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  3691. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3692. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  3693. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  3694. }else {
  3695. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  3696. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  3697. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  3698. }
  3699. $messages = [
  3700. [
  3701. 'role' => 'system',
  3702. 'content' => $sys_content
  3703. ],
  3704. [
  3705. 'role' => 'user',
  3706. 'content' => $content
  3707. ]
  3708. ];
  3709. $post_data = [
  3710. 'model' => $model,
  3711. 'messages' => $messages,
  3712. // 'max_tokens' => 8192,
  3713. 'temperature' => 1,
  3714. 'frequency_penalty' => 0,
  3715. 'presence_penalty' => 0,
  3716. 'thinking' => ['type' => $thinkingMode],
  3717. 'response_format' => [
  3718. 'type' => 'text'
  3719. ],
  3720. 'stream' => false
  3721. ];
  3722. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3723. // 根据模型类型选择调用方法
  3724. $fullContent = '';
  3725. $usage = [];
  3726. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  3727. if (is_array($chatResult)) {
  3728. $fullContent = $chatResult['fullContent'];
  3729. $usage = $chatResult['usage'];
  3730. }
  3731. // 处理获取到的剧本数据
  3732. $script_content = handleScriptWords($fullContent, $enable_emotion);
  3733. $result = [
  3734. 'origin_content' => $fullContent,
  3735. 'roles' => getProp($script_content, 'roles'),
  3736. 'words' => getProp($script_content, 'words'),
  3737. ];
  3738. // 文生文成功计费(normal 档):同时记录积分与 token 明细
  3739. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  3740. 'model' => $model,
  3741. 'source' => 'chatWithReasoner',
  3742. ], 'normal');
  3743. return $result;
  3744. }
  3745. public function resetParagraphAudio($data) {
  3746. $bid = getProp($data, 'bid');
  3747. $cid = getProp($data, 'cid');
  3748. $version_id = getProp($data, 'version_id');
  3749. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  3750. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  3751. 'generate_status' => '待制作',
  3752. 'updated_at' => date('Y-m-d H:i:s')
  3753. ]);
  3754. }
  3755. public function saveParagraphAudio($data) {
  3756. $bid = getProp($data, 'bid');
  3757. $cid = getProp($data, 'cid');
  3758. $version_id = getProp($data, 'version_id');
  3759. $sequence = getProp($data, 'sequence');
  3760. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  3761. // 获取所有情感
  3762. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3763. $emotion_list = array_flip($emotion_list);
  3764. // 获取音色支持情感
  3765. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  3766. $timbre_emotion = explode(',', $timbre_emotion);
  3767. $emotion = getProp($data, 'emotion');
  3768. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  3769. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  3770. $list = [
  3771. 'bid' => $bid,
  3772. 'cid' => $cid,
  3773. 'version_id' => $version_id,
  3774. 'sequence' => $sequence,
  3775. 'role' => getProp($data, 'role'),
  3776. 'gender' => getProp($data, 'gender'),
  3777. 'text' => trim(getProp($data, 'text')),
  3778. 'emotion' => $emotion,
  3779. 'emotion_type' => $emotion_type,
  3780. 'voice_type' => getProp($data, 'voice_type'),
  3781. 'voice_name' => getProp($data, 'voice_name'),
  3782. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  3783. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  3784. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  3785. 'pitch' => getProp($data, 'pitch', 0),
  3786. // 'paragraph_audio_url' => '',
  3787. 'generate_status' => '制作中',
  3788. 'error_msg' => '',
  3789. 'updated_at' => date('Y-m-d H:i:s')
  3790. ];
  3791. $continue = false;
  3792. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  3793. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  3794. $list['generate_status'] = '制作成功';
  3795. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  3796. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  3797. $continue = true;
  3798. }
  3799. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  3800. if ($id) {
  3801. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  3802. }else {
  3803. $list['created_at'] = date('Y-m-d H:i:s');
  3804. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  3805. $boolen = $id ? true : false;
  3806. }
  3807. // 如果更新成功则加入查询队列
  3808. if ($boolen) {
  3809. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  3810. Redis::sadd($redis_key, $id);
  3811. }
  3812. if ($boolen && !$continue) {
  3813. $boolen = false;
  3814. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3815. // 根据ID通过API通知合成音频
  3816. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  3817. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  3818. $response = $result->getBody()->getContents();
  3819. $response_arr = json_decode($response, true);
  3820. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3821. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3822. Log::info('通知火山生成段落音频失败: '.$error_msg);
  3823. Utils::throwError('20003:通知火山生成段落音频失败');
  3824. }
  3825. $boolen = true;
  3826. }
  3827. return $boolen;
  3828. }
  3829. public function insertAudioEffect($data) {
  3830. $audio_id = getProp($data, 'audio_id');
  3831. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3832. $bid = getProp($chapter_audio, 'bid');
  3833. $version_id = getProp($chapter_audio, 'version_id');
  3834. $cid = getProp($chapter_audio, 'cid');
  3835. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3836. $audio_effect_json = getProp($data, 'audio_effect_json');
  3837. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  3838. try {
  3839. DB::beginTransaction();
  3840. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3841. if (!$count) {
  3842. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3843. }else {
  3844. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3845. }
  3846. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3847. 'audio_effect_status' => '添加中',
  3848. 'audio_effect_json' => $audio_effect_json,
  3849. 'updated_at' => date('Y-m-d H:i:s')
  3850. ]);
  3851. if (!$boolen1) {
  3852. DB::rollBack();
  3853. Utils::throwError('20003:更新生成数据失败');
  3854. }
  3855. $id = DB::table('mp_audio_tasks')->insertGetId([
  3856. 'audio_id' => $audio_id,
  3857. 'generate_status' => '执行中',
  3858. 'generate_json' => json_encode([], 256),
  3859. 'bid' => $bid,
  3860. 'book_name' => getProp($chapter_audio, 'book_name'),
  3861. 'version_id' => $version_id,
  3862. 'version_name' => getProp($chapter_audio, 'version_name'),
  3863. 'cid' => $cid,
  3864. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3865. 'task_name' => $task_name,
  3866. 'created_at' => date('Y-m-d H:i:s'),
  3867. 'updated_at' => date('Y-m-d H:i:s')
  3868. ]);
  3869. if (!$id) {
  3870. DB::rollBack();
  3871. Utils::throwError('20003:创建任务失败');
  3872. }
  3873. }catch (\Exception $e) {
  3874. DB::rollBack();
  3875. Utils::throwError('20003:'.$e->getMessage());
  3876. }
  3877. DB::commit();
  3878. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3879. // 根据ID通过API通知合成音频
  3880. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3881. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3882. $response = $result->getBody()->getContents();
  3883. $response_arr = json_decode($response, true);
  3884. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3885. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3886. Log::info('通知火山插入音效失败: '.$error_msg);
  3887. Utils::throwError('20003:通知火山插入音效失败');
  3888. }
  3889. return true;
  3890. }
  3891. public function insertBgm($data) {
  3892. $audio_id = getProp($data, 'audio_id');
  3893. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  3894. $bid = getProp($chapter_audio, 'bid');
  3895. $version_id = getProp($chapter_audio, 'version_id');
  3896. $cid = getProp($chapter_audio, 'cid');
  3897. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  3898. $bgm_json = getProp($data, 'bgm_json');
  3899. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3900. if (!$bgm_json) {
  3901. $bgm_json = getProp($data, 'audio_effect_json');
  3902. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  3903. }
  3904. try {
  3905. DB::beginTransaction();
  3906. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  3907. if (!$count) {
  3908. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3909. }else {
  3910. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3911. }
  3912. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  3913. 'bgm_status' => '添加中',
  3914. 'bgm_json' => $bgm_json,
  3915. 'updated_at' => date('Y-m-d H:i:s')
  3916. ]);
  3917. if (!$boolen1) {
  3918. DB::rollBack();
  3919. Utils::throwError('20003:更新生成数据失败');
  3920. }
  3921. $id = DB::table('mp_audio_tasks')->insertGetId([
  3922. 'audio_id' => $audio_id,
  3923. 'generate_status' => '执行中',
  3924. 'generate_json' => json_encode([], 256),
  3925. 'bid' => $bid,
  3926. 'book_name' => getProp($chapter_audio, 'book_name'),
  3927. 'version_id' => $version_id,
  3928. 'version_name' => getProp($chapter_audio, 'version_name'),
  3929. 'cid' => $cid,
  3930. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3931. 'task_name' => $task_name,
  3932. 'created_at' => date('Y-m-d H:i:s'),
  3933. 'updated_at' => date('Y-m-d H:i:s')
  3934. ]);
  3935. if (!$id) {
  3936. DB::rollBack();
  3937. Utils::throwError('20003:创建任务失败');
  3938. }
  3939. }catch (\Exception $e) {
  3940. DB::rollBack();
  3941. Utils::throwError('20003:'.$e->getMessage());
  3942. }
  3943. DB::commit();
  3944. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3945. // 根据ID通过API通知合成音频
  3946. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3947. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3948. $response = $result->getBody()->getContents();
  3949. $response_arr = json_decode($response, true);
  3950. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3951. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3952. Log::info('通知火山插入bgm失败: '.$error_msg);
  3953. Utils::throwError('20003:通知火山插入bgm失败');
  3954. }
  3955. return true;
  3956. }
  3957. public function getParagraphAudios($data) {
  3958. $bid = getProp($data, 'bid');
  3959. $cid = getProp($data, 'cid');
  3960. $version_id = getProp($data, 'version_id');
  3961. $sequence = getProp($data, 'sequence');
  3962. // 获取已生成的音频
  3963. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  3964. if ($sequence) $query->where('sequence', $sequence);
  3965. $paragraph_audios = $query->orderBy('sequence')->get();
  3966. $result = [];
  3967. foreach($paragraph_audios as $item) {
  3968. $result[] = [
  3969. 'sequence' => getProp($item, 'sequence'),
  3970. 'role' => getProp($item, 'role'),
  3971. 'gender' => getProp($item, 'gender'),
  3972. 'text' => trim(getProp($item, 'text')),
  3973. 'emotion' => getProp($item, 'emotion'),
  3974. 'emotion_type' => getProp($item, 'emotion_type'),
  3975. 'voice_type' => getProp($item, 'voice_type'),
  3976. 'voice_name' => getProp($item, 'voice_name'),
  3977. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3978. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3979. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3980. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3981. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  3982. ];
  3983. }
  3984. return $result;
  3985. }
  3986. // 新增合成任务
  3987. public function addGenerateTask($data) {
  3988. $bid = getProp($data, 'bid');
  3989. $cid = getProp($data, 'cid');
  3990. $version_id = getProp($data, 'version_id');
  3991. $generate_json = getProp($data, 'generate_json');
  3992. // 获取已生成的音频
  3993. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  3994. $paragraph_list = [];
  3995. foreach($paragraph_audios as $item) {
  3996. $paragraph_list[getProp($item, 'sequence')] = [
  3997. 'role' => getProp($item, 'role'),
  3998. 'gender' => getProp($item, 'gender'),
  3999. 'text' => trim(getProp($item, 'text')),
  4000. 'emotion' => getProp($item, 'emotion'),
  4001. 'emotion_type' => getProp($item, 'emotion_type'),
  4002. 'voice_type' => getProp($item, 'voice_type'),
  4003. 'voice_name' => getProp($item, 'voice_name'),
  4004. 'speed_ratio' => getProp($item, 'speed_ratio'),
  4005. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  4006. 'emotion_scale' => getProp($item, 'emotion_scale'),
  4007. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  4008. ];
  4009. }
  4010. // 更新角色-音色信息
  4011. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  4012. $existed_role_info = json_decode($existed_role_info, true);
  4013. if (!$existed_role_info) $existed_role_info = [];
  4014. // 获取情感信息
  4015. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  4016. $emotion_list = array_flip($emotion_list);
  4017. // 获取音色对应情感组
  4018. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  4019. $timbre_emotion_list = [];
  4020. foreach($timbre_emotions as $item) {
  4021. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  4022. }
  4023. // 构造生成音频的json
  4024. $words = json_decode($generate_json, true);
  4025. // 最终合成前的参数组
  4026. $mp_chapter_paragraph_audios = [];
  4027. $sequence = 1;
  4028. $complete_paragraph_sequences = [];
  4029. foreach($words as &$word) {
  4030. 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:参数格式有误');
  4031. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  4032. $role = getProp($word, 'role');
  4033. $word['gender'] = (int)$word['gender'];
  4034. // 判断音色对应情感是否支持,不支持则调整为中性
  4035. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  4036. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  4037. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  4038. if (isset($emotion_list[getProp($word, 'emotion')])) {
  4039. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  4040. }else {
  4041. $word['emotion'] = '中性';
  4042. $word['emotion_type'] = 'neutral';
  4043. }
  4044. $existed_role_info[$role] = [
  4045. 'timbre_type' => $word['voice_type'],
  4046. 'timbre_name' => $word['voice_name'],
  4047. 'emotion' => $word['emotion'],
  4048. 'emotion_type' => $word['emotion_type'],
  4049. 'speed_ratio' => $word['speed_ratio'],
  4050. 'loudness_ratio'=> $word['loudness_ratio'],
  4051. 'emotion_scale' => $word['emotion_scale'],
  4052. 'pitch' => $word['pitch']
  4053. ];
  4054. $word['paragraph_audio_url'] = '';
  4055. // 判断生成参数是否相同,相同则直接使用已生成的音频
  4056. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  4057. // 如果音频存在并且参数都未改变则使用已生成的音频
  4058. if (getProp($paragraph, 'paragraph_audio_url')) {
  4059. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  4060. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  4061. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  4062. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  4063. // {
  4064. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  4065. // }
  4066. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  4067. }
  4068. $tmp = $word;
  4069. // 组装章节分句音频数据
  4070. // $tmp['sequence'] = getProp($word, 'sequence');
  4071. // $tmp['text'] = getProp($word, 'text');
  4072. // $tmp['emotion'] = getProp($word, 'emotion');
  4073. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  4074. // $tmp['voice_name'] = getProp($word, 'voice_name');
  4075. // $tmp['voice_type'] = getProp($word, 'voice_type');
  4076. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  4077. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  4078. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  4079. $tmp['bid'] = $bid;
  4080. $tmp['version_id'] = $version_id;
  4081. $tmp['cid'] = $cid;
  4082. $tmp['sequence'] = $sequence;
  4083. $tmp['created_at'] = date('Y-m-d H:i:s');
  4084. $tmp['updated_at'] = date('Y-m-d H:i:s');
  4085. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  4086. $mp_chapter_paragraph_audios[] = $tmp;
  4087. $complete_paragraph_sequences[] = $sequence;
  4088. $sequence++;
  4089. }
  4090. $generate_json = json_encode($words, 256);
  4091. // 判断是否有未生成字幕的段落
  4092. $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();
  4093. if ($no_subtitle_sequences) {
  4094. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  4095. }
  4096. try {
  4097. DB::beginTransaction();
  4098. $role_info = json_encode($existed_role_info, 256);
  4099. $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')]);
  4100. if (!$boolen) {
  4101. DB::rollBack();
  4102. Utils::throwError('20003:更新角色信息失败');
  4103. }
  4104. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  4105. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  4106. if (!$count) {
  4107. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  4108. }else {
  4109. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  4110. }
  4111. $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')]);
  4112. if (!$boolen1) {
  4113. DB::rollBack();
  4114. Utils::throwError('20003:更新生成数据失败');
  4115. }
  4116. $id = DB::table('mp_audio_tasks')->insertGetId([
  4117. 'audio_id' => getProp($chapter_audio, 'id'),
  4118. 'generate_status' => '执行中',
  4119. 'generate_json' => $generate_json,
  4120. 'bid' => $bid,
  4121. 'book_name' => getProp($chapter_audio, 'book_name'),
  4122. 'version_id' => $version_id,
  4123. 'version_name' => getProp($chapter_audio, 'version_name'),
  4124. 'cid' => $cid,
  4125. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  4126. 'task_name' => $task_name,
  4127. 'created_at' => date('Y-m-d H:i:s'),
  4128. 'updated_at' => date('Y-m-d H:i:s')
  4129. ]);
  4130. if (!$id) {
  4131. DB::rollBack();
  4132. Utils::throwError('20003:创建任务失败');
  4133. }
  4134. // 删除不在段落序号范围内的其他数据
  4135. if ($complete_paragraph_sequences) {
  4136. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  4137. }
  4138. // // 删除章节分句音频数据并重新插入
  4139. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  4140. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  4141. // if (!$boolen3) {
  4142. // DB::rollBack();
  4143. // Utils::throwError('20003:更新章节分句音频失败');
  4144. // }
  4145. } catch (\Exception $e) {
  4146. DB::rollBack();
  4147. Utils::throwError('20003:'.$e->getMessage());
  4148. }
  4149. DB::commit();
  4150. // 通知火山生成音频
  4151. $client = new Client(['timeout' => 1800, 'verify' => false]);
  4152. // 根据ID通过API通知合成音频
  4153. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  4154. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  4155. $response = $result->getBody()->getContents();
  4156. $response_arr = json_decode($response, true);
  4157. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  4158. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  4159. Log::info('通知火山生成音频失败: '.$error_msg);
  4160. Utils::throwError('20003:通知火山生成音频失败');
  4161. }
  4162. return true;
  4163. }
  4164. public function timbreList($data) {
  4165. $gender = getProp($data, 'gender');
  4166. $timbre_name = getProp($data, 'voice_name');
  4167. $category_id = getProp($data, 'category_id');
  4168. $age_stage = getProp($data, 'age_stage');
  4169. $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');
  4170. if ($gender) {
  4171. $query->where('gender', $gender);
  4172. }
  4173. if ($timbre_name) {
  4174. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  4175. }
  4176. if ($category_id) {
  4177. $query->where(function ($query) use ($category_id) {
  4178. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  4179. });
  4180. }
  4181. if ($age_stage) {
  4182. $query->where('age_stage', $age_stage);
  4183. }
  4184. $list = $query->get()->map(function ($value) {
  4185. $value = (array)$value;
  4186. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  4187. return $value;
  4188. })->toArray();
  4189. return $list;
  4190. }
  4191. // 生成火山临时token
  4192. public function setStsToken() {
  4193. // ************* 配置参数 *************
  4194. $method = 'GET';
  4195. $service = 'sts';
  4196. $host = 'open.volcengineapi.com';
  4197. $region = env('VOLC_REGION');
  4198. $endpoint = 'https://open.volcengineapi.com';
  4199. // $endpoint = 'https://tos-cn-beijing.volces.com';
  4200. $access_key = env('VOLC_AK');
  4201. $secret_key = env('VOLC_SK');
  4202. // 获取缓存中的token,如果没有则请求接口
  4203. $token = Redis::get('volc_sts_token');
  4204. if (!$token) {
  4205. // 查询参数
  4206. $query_parameters = [
  4207. 'Action' => 'AssumeRole',
  4208. 'RoleSessionName' => 'user@zw',
  4209. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  4210. 'Version' => '2018-01-01'
  4211. ];
  4212. // 生成URL编码的查询字符串
  4213. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  4214. // 获取签名头信息
  4215. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  4216. // 构建完整URL
  4217. $request_url = $endpoint . '?' . $request_parameters;
  4218. $client = new Client(['verify' => false]);
  4219. $response = $client->get($request_url, ['headers' => $headers]);
  4220. $response_arr = json_decode($response->getBody()->getContents(), true);
  4221. $result = [
  4222. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  4223. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  4224. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  4225. 'Region' => env('VOLC_REGION'),
  4226. 'Endpoint' => env('VOLC_END_POINT'),
  4227. 'Bucket' => env('VOLC_BUCKET'),
  4228. ];
  4229. // 缓存token
  4230. Redis::setex('volc_sts_token', 3000, json_encode($result));
  4231. return $result;
  4232. } else {
  4233. return json_decode($token, true);
  4234. }
  4235. // $response = $response['Response'];
  4236. // $access_key = $response['Credentials']['AccessKeyId'];
  4237. // $secret_key = $response['Credentials']['AccessKeySecret'];
  4238. // $security_token = $response['Credentials']['SecurityToken'];
  4239. // $expiration = $response['Credentials']['Expiration'];
  4240. // dd($response_arr);
  4241. }
  4242. public function emotionGroups($data) {
  4243. $id = getProp($data, 'group_id');
  4244. $group_name = getProp($data, 'group_name');
  4245. $voice_type = getProp($data, 'voice_type');
  4246. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  4247. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  4248. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  4249. if ($group_name) {
  4250. $query->where('group_name', 'like', "%{$group_name}%");
  4251. }
  4252. if ($id) {
  4253. $query->where('id', $id);
  4254. }
  4255. if ($voice_type) {
  4256. $query->where('voice_type', $voice_type);
  4257. }
  4258. return $query->orderBy('id')->get()->map(function ($value) {
  4259. return (array)$value;
  4260. })->toArray();
  4261. }
  4262. private function sign($key, $msg) {
  4263. return hash_hmac('sha256', $msg, $key, true);
  4264. }
  4265. // 生成签名密钥
  4266. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  4267. $kDate = $this->sign($key, $dateStamp);
  4268. $kRegion = $this->sign($kDate, $regionName);
  4269. $kService = $this->sign($kRegion, $serviceName);
  4270. $kSigning = $this->sign($kService, 'request');
  4271. return $kSigning;
  4272. }
  4273. // 获取签名头信息
  4274. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  4275. $contenttype = 'application/x-www-form-urlencoded';
  4276. $accept = 'application/json';
  4277. // 获取当前UTC时间
  4278. $t = new DateTime('now', new DateTimeZone('UTC'));
  4279. $xdate = $t->format('Ymd\THis\Z');
  4280. $datestamp = $t->format('Ymd');
  4281. // 1. 拼接规范请求串
  4282. $canonical_uri = '/';
  4283. $canonical_querystring = $request_parameters;
  4284. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  4285. $signed_headers = 'content-type;host;x-date';
  4286. // 空请求体的SHA256哈希
  4287. $payload_hash = hash('sha256', '');
  4288. $canonical_request = implode("\n", [
  4289. $method,
  4290. $canonical_uri,
  4291. $canonical_querystring,
  4292. $canonical_headers,
  4293. $signed_headers,
  4294. $payload_hash
  4295. ]);
  4296. // 2. 拼接待签名字符串
  4297. $algorithm = 'HMAC-SHA256';
  4298. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  4299. $hashed_canonical_request = hash('sha256', $canonical_request);
  4300. $string_to_sign = implode("\n", [
  4301. $algorithm,
  4302. $xdate,
  4303. $credential_scope,
  4304. $hashed_canonical_request
  4305. ]);
  4306. // 3. 计算签名
  4307. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  4308. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  4309. // 4. 添加签名到请求头
  4310. $authorization_header = sprintf(
  4311. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  4312. $algorithm,
  4313. $access_key,
  4314. $credential_scope,
  4315. $signed_headers,
  4316. $signature
  4317. );
  4318. return [
  4319. 'Accept' => $accept,
  4320. 'Content-Type' => $contenttype,
  4321. 'X-Date' => $xdate,
  4322. 'Authorization' => $authorization_header
  4323. ];
  4324. }
  4325. // 文字合成语音(火山引擎)
  4326. public function tts($data) {
  4327. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  4328. $headers = [
  4329. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  4330. 'Content-Type' => 'application/json; charset=UTF-8'
  4331. ];
  4332. $post_data = [
  4333. 'app' => [
  4334. 'appid' => env('VOLC_APPID'),
  4335. 'token' => env('VOLC_TOKEN'),
  4336. 'cluster' => 'volcano_tts'
  4337. ],
  4338. 'user' => [
  4339. 'uid' => 'mp_audio'
  4340. ],
  4341. // 'audio' => [
  4342. // 'voice_type' =>
  4343. // ],
  4344. ];
  4345. }
  4346. public function scriptList($data) {
  4347. $uid = Site::getUid();
  4348. $script_id = getProp($data, 'script_id');
  4349. $script_name = getProp($data, 'script_name');
  4350. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  4351. if ($script_id) {
  4352. $query->where('id', $script_id);
  4353. }
  4354. if ($script_name) {
  4355. $query->where('script_name', 'like', "%{$script_name}%");
  4356. }
  4357. return $query->orderBy('created_at', 'desc')->paginate(12);
  4358. }
  4359. public function scripts($data) {
  4360. $uid = Site::getUid();
  4361. $script_id = getProp($data, 'script_id');
  4362. $script_name = getProp($data, 'script_name');
  4363. $is_products = getProp($data, 'is_products');
  4364. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  4365. if ($script_id) {
  4366. $query->where('id', $script_id);
  4367. }
  4368. if ($is_products !== '') {
  4369. $query->where('is_products', $is_products);
  4370. }
  4371. if ($script_name) {
  4372. $query->where('script_name', 'like', "%{$script_name}%");
  4373. }
  4374. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  4375. return (array)$value;
  4376. })->toArray();
  4377. }
  4378. public function scriptInfo($data) {
  4379. $uid = Site::getUid();
  4380. $script_id = getProp($data, 'script_id');
  4381. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  4382. // ->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();
  4383. ->selectRaw('id as script_id, script_name')->first();
  4384. if (!$script) Utils::throwError('20003:该剧本不存在!');
  4385. $script = (array)$script;
  4386. // 获取分集组信息
  4387. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  4388. ->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')
  4389. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  4390. $value = (array)$value;
  4391. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  4392. return (array)$value;
  4393. })->toArray();
  4394. $script['group'] = $groups;
  4395. return $script;
  4396. }
  4397. public function createScript($data) {
  4398. $script_name = getProp($data, 'script_name');
  4399. $uid = Site::getUid(); // 获取当前用户ID
  4400. $cpid = Site::getCpid(); // 获取当前公司组ID
  4401. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  4402. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  4403. $script_name .= '_'.date('YmdHis');
  4404. }
  4405. return DB::table('mp_scripts')->insertGetId([
  4406. 'script_name' => $script_name,
  4407. 'user_id' => $uid,
  4408. 'cpid' => $cpid,
  4409. 'created_at' => date('Y-m-d H:i:s'),
  4410. 'updated_at' => date('Y-m-d H:i:s')
  4411. ]);
  4412. }
  4413. public function editScript($data) {
  4414. $script_id = getProp($data, 'script_id');
  4415. $script_name = getProp($data, 'script_name');
  4416. $uid = Site::getUid(); // 获取当前用户ID
  4417. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  4418. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  4419. if ($id && (int)$id !== (int)$script_id) {
  4420. $script_name .= '_'.date('YmdHis');
  4421. }
  4422. return DB::table('mp_scripts')->where('id', $script_id)->update([
  4423. 'script_name' => $script_name,
  4424. 'updated_at' => date('Y-m-d H:i:s')
  4425. ]);
  4426. }
  4427. public function delScript($data) {
  4428. $script_id = getProp($data, 'script_id');
  4429. $uid = Site::getUid(); // 获取当前用户ID
  4430. if (!$script_id) Utils::throwError('20003:请选择剧本');
  4431. return DB::table('mp_scripts')->where('id', $script_id)->update([
  4432. 'is_deleted' => 1,
  4433. 'updated_at' => date('Y-m-d H:i:s')
  4434. ]);
  4435. }
  4436. public function createEpisode($data) {
  4437. $script_id = getProp($data, 'script_id');
  4438. $group_name = getProp($data, 'group_name');
  4439. $remark = getProp($data, 'remark');
  4440. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  4441. $uid = Site::getUid(); // 获取当前用户ID
  4442. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  4443. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  4444. $group_name .= '_'.date('YmdHis');
  4445. }
  4446. return DB::table('mp_script_episode_group')->insertGetId([
  4447. 'script_id' => $script_id,
  4448. 'group_name' => $group_name,
  4449. 'user_id' => $uid,
  4450. 'remark' => $remark,
  4451. 'created_at' => date('Y-m-d H:i:s'),
  4452. 'updated_at' => date('Y-m-d H:i:s')
  4453. ]);
  4454. }
  4455. public function editEpisode($data) {
  4456. $group_id = getProp($data, 'group_id');
  4457. $start_episode_number = getProp($data, 'start_episode_number');
  4458. $end_episode_number = getProp($data, 'end_episode_number');
  4459. $group_name = getProp($data, 'group_name');
  4460. $uid = Site::getUid(); // 获取当前用户ID
  4461. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  4462. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  4463. if ($id && (int)$id !== (int)$group_id) {
  4464. $group_name .= '_'.date('YmdHis');
  4465. }
  4466. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4467. 'group_name' => $group_name,
  4468. 'start_episode_number' => $start_episode_number,
  4469. 'end_episode_number' => $end_episode_number,
  4470. 'updated_at' => date('Y-m-d H:i:s')
  4471. ]);
  4472. }
  4473. public function delEpisode($data) {
  4474. $group_id = getProp($data, 'group_id');
  4475. $uid = Site::getUid(); // 获取当前用户ID
  4476. if (!$group_id) Utils::throwError('20003:请选择分集');
  4477. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4478. 'is_deleted' => 1,
  4479. 'updated_at' => date('Y-m-d H:i:s')
  4480. ]);
  4481. }
  4482. /**
  4483. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4484. *
  4485. * @param array $data 包含以下参数:
  4486. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4487. * - question: 用户问题(可选)
  4488. * - model: 使用的模型(r1 或 v3,默认 v3)
  4489. * @return \Generator 返回生成器,用于流式输出
  4490. */
  4491. public function generateEpisodes($data) {
  4492. // 文生文计费预检(special 档,每次调用扣 10)
  4493. $uid = Site::getUid();
  4494. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  4495. $script_id = getProp($data, 'script_id');
  4496. $group_id = getProp($data, 'group_id');
  4497. // $file = getProp($data, 'file');
  4498. $file = '';
  4499. $content = getProp($data, 'content', '');
  4500. // $bid = getProp($data, 'bid', 0);
  4501. $bid = 0;
  4502. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4503. if (!$group) {
  4504. Utils::throwError('20003:剧本分集不存在');
  4505. }
  4506. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  4507. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  4508. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  4509. $prompt = getProp($data, 'prompt');
  4510. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  4511. $model = getProp($data, 'model');
  4512. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4513. Utils::throwError('20003:该模型不存在!');
  4514. }
  4515. // 检查是否存在重叠的剧集序号范围
  4516. $exists_groups = DB::table('mp_script_episode_group')
  4517. ->where('script_id', $script_id)
  4518. ->where('id', '<>', $group_id) // 排除当前组
  4519. ->where('is_deleted', 0)
  4520. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4521. // 检查新范围是否与现有范围重叠
  4522. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4523. // 新范围的开始在现有范围内
  4524. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4525. ->where('end_episode_number', '>=', $start_episode_sequence);
  4526. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4527. // 新范围的结束在现有范围内
  4528. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4529. ->where('end_episode_number', '>=', $end_episode_sequence);
  4530. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4531. // 新范围完全包含现有范围
  4532. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4533. ->where('end_episode_number', '<=', $end_episode_sequence);
  4534. });
  4535. })
  4536. ->select('start_episode_number', 'end_episode_number')
  4537. ->get();
  4538. if ($exists_groups->isNotEmpty()) {
  4539. $conflict_ranges = [];
  4540. foreach ($exists_groups as $group) {
  4541. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4542. }
  4543. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4544. }
  4545. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4546. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4547. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4548. if ($model === 'deepseek-chat') {
  4549. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4550. $model = 'deepseek-v4-flash';
  4551. $thinkingMode = 'disabled';
  4552. } elseif ($model === 'deepseek-reasoner') {
  4553. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4554. $model = 'deepseek-v4-flash';
  4555. $thinkingMode = 'enabled';
  4556. }
  4557. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4558. if (!$script) {
  4559. Utils::throwError('20003:剧本不存在');
  4560. }
  4561. $content = getProp($group, 'content');
  4562. if (!$file && !$content && !$bid) {
  4563. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4564. }
  4565. // 提取文件内容
  4566. if ($file) {
  4567. $content = $this->extractFileContent($file);
  4568. if (!$content) {
  4569. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4570. }
  4571. } elseif ($bid) {
  4572. $content = $this->getContentByBid($bid);
  4573. if (!$content) {
  4574. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4575. }
  4576. } elseif ($content) {
  4577. $content = filterContent($content);
  4578. } elseif ($prompt) {
  4579. $content = filterContent($prompt);
  4580. } else {
  4581. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4582. }
  4583. // 构建消息
  4584. $messages = [
  4585. $this->sys_message,
  4586. [
  4587. 'role' => 'user',
  4588. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4589. ]
  4590. ];
  4591. $post_data = [
  4592. 'model' => $model,
  4593. 'messages' => $messages,
  4594. // 'max_tokens' => 8192,
  4595. 'temperature' => 0.7,
  4596. 'frequency_penalty' => 0,
  4597. 'presence_penalty' => 0,
  4598. 'thinking' => ['type' => $thinkingMode],
  4599. 'response_format' => ['type' => 'text'],
  4600. 'stream' => true
  4601. ];
  4602. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4603. // 根据模型类型选择调用方法
  4604. $fullContent = '';
  4605. $fullReasoningContent = '';
  4606. $usage = [];
  4607. $streamGenerator = $this->dispatchStreamByModel($post_data);
  4608. // 处理流式输出
  4609. foreach ($streamGenerator as $chunk) {
  4610. if (isset($chunk['type'])) {
  4611. if ($chunk['type'] === 'done') {
  4612. // 最终结果
  4613. $fullContent = $chunk['full_content'];
  4614. $fullReasoningContent = $chunk['full_reasoning'];
  4615. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4616. } else {
  4617. // 逐块yield数据
  4618. yield $chunk;
  4619. }
  4620. }
  4621. }
  4622. dLog('deepseek')->info('完整内容: '.$fullContent);
  4623. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4624. // 处理完整内容并返回最终结果
  4625. $script_arr = [];
  4626. if ($fullContent) {
  4627. $script_arr = extractScriptContent($fullContent);
  4628. }
  4629. logDB('deepseek', 'info', '解析内容', $script_arr);
  4630. if (!$script_arr['episodes']) {
  4631. Utils::throwError('20003:未生成剧本相关信息');
  4632. // yield [
  4633. // 'type' => 'done',
  4634. // 'script' => $script_arr,
  4635. // 'msg' => '未生成剧本相关信息',
  4636. // 'answer' => $fullContent,
  4637. // 'reasoning' => $fullReasoningContent,
  4638. // 'usage' => $usage
  4639. // ];
  4640. // return ;
  4641. }
  4642. try {
  4643. DB::beginTransaction();
  4644. // // 返回前保存剧本内容
  4645. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4646. // 'content' => $content,
  4647. // 'updated_at' => date('Y-m-d H:i:s')
  4648. // ]);
  4649. // if (!$boolen) {
  4650. // Utils::throwError('20003:保存剧本内容失败');
  4651. // }
  4652. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4653. // 'start_episode_number' => $start_episode_sequence,
  4654. // 'end_episode_number' => $end_episode_sequence,
  4655. // 'updated_at' => date('Y-m-d H:i:s')
  4656. // ]);
  4657. // if (!$boolen1) {
  4658. // Utils::throwError('20003:保存分集失败');
  4659. // }
  4660. $episode_content = '';
  4661. $episodes = [];
  4662. foreach ($script_arr['episodes'] as $item) {
  4663. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  4664. // $episodes[] = [
  4665. // 'script_id' => $script_id,
  4666. // 'episode_number' => $item['episode_number'],
  4667. // 'episode_name' => $item['episode_name'],
  4668. // 'episode_content' => $item['episode_content'],
  4669. // 'created_at' => date('Y-m-d H:i:s'),
  4670. // 'updated_at' => date('Y-m-d H:i:s'),
  4671. // ];
  4672. }
  4673. if ($episode_content) {
  4674. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4675. 'episode_content' => $episode_content,
  4676. 'updated_at' => date('Y-m-d H:i:s')
  4677. ]);
  4678. if (!$boolen2) {
  4679. Utils::throwError('20003:保存分集内容失败');
  4680. }
  4681. }else {
  4682. Utils::throwError('20003:分集剧本解析失败');
  4683. }
  4684. // 文生文成功计费(special 档):与落库同事务
  4685. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  4686. 'model' => $model,
  4687. 'script_id' => $script_id,
  4688. 'group_id' => $group_id,
  4689. 'source' => 'generateEpisodes',
  4690. ]);
  4691. }catch (\Exception $e) {
  4692. DB::rollBack();
  4693. Utils::throwError('20003:'.$e->getMessage());
  4694. }
  4695. DB::commit();
  4696. yield [
  4697. 'type' => 'done',
  4698. 'script' => $script_arr,
  4699. 'episode_content' => $episode_content,
  4700. 'answer' => $fullContent,
  4701. 'reasoning' => $fullReasoningContent,
  4702. 'usage' => $usage
  4703. ];
  4704. }
  4705. public function chatWithFileStream($data) {
  4706. // 剧本解析资产表计费预检(special 档)
  4707. $uid = Site::getUid();
  4708. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  4709. $script_id = getProp($data, 'script_id');
  4710. $group_id = getProp($data, 'group_id');
  4711. $file = getProp($data, 'file');
  4712. $content = getProp($data, 'content', '');
  4713. $bid = getProp($data, 'bid', 0);
  4714. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4715. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4716. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  4717. $prompt = getProp($data, 'prompt');
  4718. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4719. if (!empty($prompt)) {
  4720. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4721. }
  4722. $question = getProp($data, 'question', $baseQuestion);
  4723. $model = getProp($data, 'model');
  4724. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  4725. Utils::throwError('20003:该模型不存在!');
  4726. }
  4727. // 检查是否存在重叠的剧集序号范围
  4728. $exists_groups = DB::table('mp_script_episode_group')
  4729. ->where('script_id', $script_id)
  4730. ->where('id', '<>', $group_id)
  4731. ->where('is_deleted', 0)
  4732. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4733. // 检查新范围是否与现有范围重叠
  4734. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4735. // 新范围的开始在现有范围内
  4736. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4737. ->where('end_episode_number', '>=', $start_episode_sequence);
  4738. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4739. // 新范围的结束在现有范围内
  4740. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4741. ->where('end_episode_number', '>=', $end_episode_sequence);
  4742. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4743. // 新范围完全包含现有范围
  4744. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4745. ->where('end_episode_number', '<=', $end_episode_sequence);
  4746. });
  4747. })
  4748. ->select('start_episode_number', 'end_episode_number')
  4749. ->get();
  4750. if ($exists_groups->isNotEmpty()) {
  4751. $conflict_ranges = [];
  4752. foreach ($exists_groups as $group) {
  4753. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4754. }
  4755. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4756. }
  4757. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4758. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4759. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4760. if ($model === 'deepseek-chat') {
  4761. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4762. $model = 'deepseek-v4-flash';
  4763. $thinkingMode = 'disabled';
  4764. } elseif ($model === 'deepseek-reasoner') {
  4765. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4766. $model = 'deepseek-v4-flash';
  4767. $thinkingMode = 'enabled';
  4768. }
  4769. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4770. if (!$script) {
  4771. Utils::throwError('20003:剧本不存在');
  4772. }
  4773. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  4774. if (!$group) {
  4775. Utils::throwError('20003:剧本分集不存在');
  4776. }
  4777. if (!$file && !$content && !$bid) {
  4778. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4779. }
  4780. // 提取文件内容
  4781. if ($file) {
  4782. $content = $this->extractFileContent($file);
  4783. if (!$content) {
  4784. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4785. }
  4786. } elseif ($bid) {
  4787. $content = $this->getContentByBid($bid);
  4788. if (!$content) {
  4789. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4790. }
  4791. } elseif ($content) {
  4792. $content = filterContent($content);
  4793. } elseif ($prompt) {
  4794. $content = filterContent($prompt);
  4795. } else {
  4796. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4797. }
  4798. // 构建消息
  4799. $messages = [
  4800. [
  4801. 'role' => 'system',
  4802. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4803. 强制要求:\n
  4804. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4805. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4806. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  4807. 普通要求:\n
  4808. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  4809. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  4810. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  4811. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  4812. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  4813. 示例如下:\n
  4814. ###剧本名:西昆仑
  4815. ###故事梗概
  4816. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4817. ###剧本亮点
  4818. 亮点1:绝境奇药,生死一线
  4819. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4820. 亮点2:结拜兄妹,化解尴尬
  4821. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4822. 亮点3:纤发夺命,情愫暗涌
  4823. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4824. ###人物关系
  4825. 阿雪与梁萧之间存在兄妹之情。
  4826. ###核心矛盾
  4827. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4828. ###主体列表
  4829. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  4830. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  4831. 阴阳球:天地异宝,能化生精气,救人于危难。
  4832. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  4833. ###美术风格
  4834. 基础画风风格词:厚涂古风
  4835. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4836. ###场景列表
  4837. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  4838. [
  4839. 'role' => 'user',
  4840. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4841. ]
  4842. ];
  4843. $post_data = [
  4844. 'model' => $model,
  4845. 'messages' => $messages,
  4846. // 'max_tokens' => 8192,
  4847. 'temperature' => 0.7,
  4848. 'frequency_penalty' => 0,
  4849. 'presence_penalty' => 0,
  4850. 'thinking' => ['type' => $thinkingMode],
  4851. 'response_format' => ['type' => 'text'],
  4852. 'stream' => true
  4853. ];
  4854. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4855. // 根据模型类型选择调用方法
  4856. $fullContent = '';
  4857. $fullReasoningContent = '';
  4858. $usage = [];
  4859. $streamGenerator = $this->dispatchStreamByModel($post_data);
  4860. // 处理流式输出
  4861. foreach ($streamGenerator as $chunk) {
  4862. if (isset($chunk['type'])) {
  4863. if ($chunk['type'] === 'done') {
  4864. // 最终结果
  4865. $fullContent = $chunk['full_content'];
  4866. $fullReasoningContent = $chunk['full_reasoning'];
  4867. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4868. } else {
  4869. // 逐块yield数据
  4870. yield $chunk;
  4871. }
  4872. }
  4873. }
  4874. dLog('deepseek')->info('完整内容: '.$fullContent);
  4875. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  4876. // 处理完整内容并返回最终结果
  4877. $script_arr = [];
  4878. if ($fullContent) {
  4879. $script_arr = extractScriptContent($fullContent);
  4880. }
  4881. logDB('deepseek', 'info', '解析内容', $script_arr);
  4882. if (!$script_arr['roles']) {
  4883. Utils::throwError('20003:未生成剧本相关信息');
  4884. // yield [
  4885. // 'type' => 'done',
  4886. // 'script' => $script_arr,
  4887. // 'msg' => '未生成剧本相关信息',
  4888. // 'answer' => $fullContent,
  4889. // 'reasoning' => $fullReasoningContent,
  4890. // 'usage' => $usage
  4891. // ];
  4892. }
  4893. try {
  4894. DB::beginTransaction();
  4895. // // 返回前保存剧本内容
  4896. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  4897. // 'content' => $content,
  4898. // 'status' => '解析完成',
  4899. // 'updated_at' => date('Y-m-d H:i:s')
  4900. // ]);
  4901. // if (!$boolen) {
  4902. // Utils::throwError('20003:保存剧本内容失败');
  4903. // }
  4904. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  4905. 'start_episode_number' => $start_episode_sequence,
  4906. 'end_episode_number' => $end_episode_sequence,
  4907. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4908. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4909. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4910. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4911. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4912. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4913. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4914. 'status' => '解析完成',
  4915. 'content' => $content,
  4916. 'updated_at' => date('Y-m-d H:i:s')
  4917. ]);
  4918. if (!$boolen1) {
  4919. Utils::throwError('20003:保存分集失败');
  4920. }
  4921. // 剧本解析资产表成功计费(special 档):与落库同事务
  4922. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  4923. 'model' => $model,
  4924. 'script_id' => $script_id,
  4925. 'group_id' => $group_id,
  4926. 'source' => 'chatWithFileStream',
  4927. ], 'special');
  4928. // $episodes = [];
  4929. // foreach ($script_arr['episodes'] as $item) {
  4930. // $episodes[] = [
  4931. // 'script_id' => $script_id,
  4932. // 'episode_number' => $item['episode_number'],
  4933. // 'episode_name' => $item['episode_name'],
  4934. // 'episode_content' => $item['episode_content'],
  4935. // 'created_at' => date('Y-m-d H:i:s'),
  4936. // 'updated_at' => date('Y-m-d H:i:s'),
  4937. // ];
  4938. // }
  4939. // if ($episodes) {
  4940. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4941. // if (!$boolen2) {
  4942. // Utils::throwError('20003:保存分集内容失败');
  4943. // }
  4944. // }else {
  4945. // Utils::throwError('20003:分集剧本解析失败');
  4946. // }
  4947. }catch (\Exception $e) {
  4948. DB::rollBack();
  4949. Utils::throwError('20003:'.$e->getMessage());
  4950. }
  4951. DB::commit();
  4952. yield [
  4953. 'type' => 'done',
  4954. 'script' => $script_arr,
  4955. 'answer' => $fullContent,
  4956. 'reasoning' => $fullReasoningContent,
  4957. 'usage' => $usage
  4958. ];
  4959. }
  4960. /**
  4961. * 上传文件识别文字内容并与 DeepSeek 进行对话
  4962. *
  4963. * @param array $data 包含以下参数:
  4964. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4965. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  4966. * - model: 使用的模型(r1 或 v3,默认 v3)
  4967. * @return array
  4968. */
  4969. public function chatWithFile($data) {
  4970. // 剧本解析资产表计费预检(special 档)
  4971. $uid = Site::getUid();
  4972. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'special'), $uid);
  4973. $script_id = getProp($data, 'script_id');
  4974. $file = getProp($data, 'file');
  4975. $content = getProp($data, 'content', '');
  4976. $bid = getProp($data, 'bid', 0);
  4977. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4978. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4979. $prompt = getProp($data, 'prompt');
  4980. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4981. if (!empty($prompt)) {
  4982. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4983. }
  4984. $question = getProp($data, 'question', $baseQuestion);
  4985. // 处理文本模型
  4986. $model = getProp($data, 'model');
  4987. if (!$model) {
  4988. // 用户没有输入,使用默认值
  4989. $model = 'doubao-seed-2-0-mini-260215';
  4990. }
  4991. // 验证模型是否在可用模型表中
  4992. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4993. $model = 'doubao-seed-2-0-mini-260215';
  4994. }
  4995. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4996. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4997. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4998. if ($model === 'deepseek-chat') {
  4999. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5000. $model = 'deepseek-v4-flash';
  5001. $thinkingMode = 'disabled';
  5002. } elseif ($model === 'deepseek-reasoner') {
  5003. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5004. $model = 'deepseek-v4-flash';
  5005. $thinkingMode = 'enabled';
  5006. }
  5007. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  5008. if (!$script) {
  5009. Utils::throwError('20003:剧本不存在');
  5010. }
  5011. if (!$file && !$content && !$bid) {
  5012. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5013. }
  5014. // 提取文件内容
  5015. if ($file) {
  5016. $content = $this->extractFileContent($file);
  5017. if (!$content) {
  5018. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5019. }
  5020. } elseif ($bid) {
  5021. $content = $this->getContentByBid($bid);
  5022. if (!$content) {
  5023. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5024. }
  5025. } elseif ($content) {
  5026. $content = filterContent($content);
  5027. } elseif ($prompt) {
  5028. $content = filterContent($prompt);
  5029. } else {
  5030. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5031. }
  5032. // 构建消息
  5033. $messages = [
  5034. $this->sys_message,
  5035. [
  5036. 'role' => 'user',
  5037. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  5038. ]
  5039. ];
  5040. $post_data = [
  5041. 'model' => $model,
  5042. 'messages' => $messages,
  5043. // 'max_tokens' => 8192,
  5044. 'temperature' => 0.7,
  5045. 'frequency_penalty' => 0,
  5046. 'presence_penalty' => 0,
  5047. 'thinking' => ['type' => $thinkingMode],
  5048. 'response_format' => ['type' => 'text'],
  5049. 'stream' => false
  5050. ];
  5051. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5052. // 根据模型类型选择调用方法
  5053. $fullContent = '';
  5054. $usage = [];
  5055. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  5056. if (is_array($chatResult)) {
  5057. $fullContent = $chatResult['fullContent'];
  5058. $usage = $chatResult['usage'];
  5059. }
  5060. $script_arr = [];
  5061. // 处理结果
  5062. if ($fullContent) {
  5063. $script_arr = extractScriptContent($fullContent);
  5064. }
  5065. // 返回前保存剧本内容
  5066. DB::table('mp_scripts')->where('id', $script_id)->update([
  5067. 'content' => $content,
  5068. 'updated_at' => date('Y-m-d H:i:s')
  5069. ]);
  5070. // 剧本解析资产表成功计费(special 档):同时记录积分与 token 明细
  5071. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5072. 'model' => $model,
  5073. 'script_id' => $script_id,
  5074. 'source' => 'chatWithFile',
  5075. ], 'special');
  5076. return [
  5077. 'script' => $script_arr,
  5078. 'answer' => $fullContent,
  5079. 'usage' => $usage
  5080. ];
  5081. }
  5082. public function getEpisodeContent($data) {
  5083. $group_id = getProp($data, 'group_id');
  5084. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  5085. }
  5086. public function saveEpisodeContent($data) {
  5087. $script_id = getProp($data, 'script_id');
  5088. $group_id = getProp($data, 'group_id');
  5089. $start_episode_sequence = getProp($data, 'start_episode_number');
  5090. $end_episode_sequence = getProp($data, 'end_episode_number');
  5091. // 检查是否存在重叠的剧集序号范围
  5092. $exists_groups = DB::table('mp_script_episode_group')
  5093. ->where('script_id', $script_id)
  5094. ->where('id', '<>', $group_id) // 排除当前组
  5095. ->where('is_deleted', 0)
  5096. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  5097. // 检查新范围是否与现有范围重叠
  5098. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5099. // 新范围的开始在现有范围内
  5100. $q->where('start_episode_number', '<=', $start_episode_sequence)
  5101. ->where('end_episode_number', '>=', $start_episode_sequence);
  5102. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5103. // 新范围的结束在现有范围内
  5104. $q->where('start_episode_number', '<=', $end_episode_sequence)
  5105. ->where('end_episode_number', '>=', $end_episode_sequence);
  5106. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  5107. // 新范围完全包含现有范围
  5108. $q->where('start_episode_number', '>=', $start_episode_sequence)
  5109. ->where('end_episode_number', '<=', $end_episode_sequence);
  5110. });
  5111. })
  5112. ->select('start_episode_number', 'end_episode_number')
  5113. ->get();
  5114. if ($exists_groups->isNotEmpty()) {
  5115. $conflict_ranges = [];
  5116. foreach ($exists_groups as $group) {
  5117. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  5118. }
  5119. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  5120. }
  5121. $episode_content = getProp($data, 'episode_content');
  5122. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  5123. 'content' => $episode_content,
  5124. 'start_episode_number' => $start_episode_sequence,
  5125. 'end_episode_number' => $end_episode_sequence,
  5126. 'updated_at' => date('Y-m-d H:i:s')
  5127. ]);
  5128. $script_arr =getProp($data, 'script', []);
  5129. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  5130. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  5131. $script_id = getProp($data, 'script_id');
  5132. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  5133. try {
  5134. DB::beginTransaction();
  5135. $update_data = [
  5136. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5137. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5138. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5139. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5140. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5141. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5142. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5143. 'status' => 3,
  5144. 'start_episode_sequence' => $start_episode_sequence,
  5145. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  5146. 'episode_num' => count($script_arr['episodes']),
  5147. 'updated_at' => date('Y-m-d H:i:s')
  5148. ];
  5149. // 保存剧本内容
  5150. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  5151. if (!$boolen) {
  5152. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  5153. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  5154. Utils::throwError('20003:剧本内容保存失败');
  5155. }
  5156. // 保存分集内容
  5157. // 删除历史分集内容
  5158. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  5159. $episodes = [];
  5160. $sequence = 1;
  5161. foreach ($script_arr['episodes'] as $episode) {
  5162. $segment_number = 1;
  5163. foreach($episode['segments'] as $segment) {
  5164. $episodes[] = [
  5165. 'script_id' => $script_id,
  5166. 'episode_number' => $episode['episode_number'],
  5167. 'title' => $episode['title'],
  5168. // 'content' => $episode['content'],
  5169. 'content' => '',
  5170. 'segment_number' => $segment_number,
  5171. 'segment_content' => $segment['segment_content'],
  5172. 'sequence' => $sequence,
  5173. 'created_at' => date('Y-m-d H:i:s'),
  5174. 'updated_at' => date('Y-m-d H:i:s')
  5175. ];
  5176. $sequence++;
  5177. $segment_number++;
  5178. }
  5179. }
  5180. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  5181. if (!$boolen2) {
  5182. dLog('deepseek')->info('分集内容保存失败', $episodes);
  5183. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  5184. Utils::throwError('20003:分集内容保存失败');
  5185. }
  5186. } catch (\Exception $e) {
  5187. DB::rollBack();
  5188. Utils::throwError('20003:'.$e->getMessage());
  5189. }
  5190. DB::commit();
  5191. return true;
  5192. }
  5193. public function getBookContent($data) {
  5194. $bid = getProp($data, 'bid');
  5195. $start_sequence = getProp($data, 'start_sequence');
  5196. $end_sequence = getProp($data, 'end_sequence');
  5197. $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])
  5198. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  5199. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  5200. return $return_content;
  5201. }
  5202. public function exportScript($data) {
  5203. $filename = getProp($data, 'filename');
  5204. $script_id = getProp($data, 'script_id');
  5205. $group_id = getProp($data, 'group_id');
  5206. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  5207. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  5208. if (!$script) Utils::throwError('20003:该剧本不存在!');
  5209. $script = (array)$script;
  5210. // 获取分集组信息
  5211. if ($group_id) {
  5212. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  5213. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  5214. ->get()->map(function($value) {
  5215. return (array)$value;
  5216. })->toArray();
  5217. }else {
  5218. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  5219. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  5220. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  5221. return (array)$value;
  5222. })->toArray();
  5223. }
  5224. if (!$groups) Utils::throwError('20003:分集不存在');
  5225. $script['group'] = $groups;
  5226. $export_type = getProp($data, 'export_type', 'txt');
  5227. // 生成文件名
  5228. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  5229. // 根据导出类型生成不同格式的文件
  5230. switch ($export_type) {
  5231. case 'txt':
  5232. return $this->exportScriptAsTxt($script, $filename);
  5233. case 'pdf':
  5234. return $this->exportScriptAsPdf($script, $filename);
  5235. default:
  5236. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  5237. }
  5238. }
  5239. /**
  5240. * 导出剧本为TXT格式
  5241. */
  5242. private function exportScriptAsTxt($script, $filename) {
  5243. // 构建TXT内容
  5244. $content = $this->buildScriptContent($script);
  5245. // 设置响应头,直接下载
  5246. header('Content-Type: text/plain; charset=utf-8');
  5247. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  5248. header('Content-Length: ' . strlen($content));
  5249. // 输出内容并结束
  5250. echo $content;
  5251. exit();
  5252. }
  5253. /**
  5254. * 导出剧本为PDF格式
  5255. */
  5256. private function exportScriptAsPdf($script, $filename) {
  5257. // 使用HTML转PDF的方式来更好地支持中文
  5258. $htmlContent = $this->buildScriptHtmlForPdf($script);
  5259. // 创建PDF实例
  5260. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  5261. // 设置文档信息
  5262. $pdf->SetCreator('剧本导出系统');
  5263. $pdf->SetAuthor('系统');
  5264. $pdf->SetTitle($script['script_name']);
  5265. $pdf->SetSubject('剧本导出');
  5266. // 设置边距
  5267. $pdf->SetMargins(15, 15, 15);
  5268. $pdf->SetAutoPageBreak(TRUE, 15);
  5269. // 添加页面
  5270. $pdf->AddPage();
  5271. // 注册并使用 simsun.ttf 字体
  5272. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  5273. // 使用HTML内容生成PDF
  5274. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  5275. // 直接输出PDF文件供下载
  5276. header('Content-Type: application/pdf');
  5277. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  5278. // 直接输出PDF内容
  5279. $pdf->Output($filename . '.pdf', 'D');
  5280. exit();
  5281. }
  5282. /**
  5283. * 构建用于PDF的HTML内容
  5284. */
  5285. private function buildScriptHtmlForPdf($script) {
  5286. $html = '<style>
  5287. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  5288. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  5289. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  5290. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  5291. .info { margin-bottom: 8px; }
  5292. .group { margin-bottom: 30px; page-break-inside: avoid; }
  5293. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  5294. .segment { margin-bottom: 10px; margin-left: 20px; }
  5295. .episode-content { white-space: pre-wrap; }
  5296. </style>';
  5297. // 标题
  5298. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  5299. // 处理分组数据
  5300. if (!empty($script['group']) && is_array($script['group'])) {
  5301. $groups = (array)$script['group'];
  5302. foreach ($groups as $group) {
  5303. $html .= '<div class="group">';
  5304. // 分组标题
  5305. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  5306. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  5307. // 故事梗概
  5308. if (!empty($group['intro'])) {
  5309. $html .= '<h3>故事梗概</h3>';
  5310. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  5311. }
  5312. // 剧本亮点
  5313. if (!empty($group['highlights'])) {
  5314. $html .= '<h3>剧本亮点</h3>';
  5315. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  5316. }
  5317. // 人物关系
  5318. if (!empty($group['role_relationship'])) {
  5319. $html .= '<h3>人物关系</h3>';
  5320. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  5321. }
  5322. // 核心矛盾
  5323. if (!empty($group['core_contradiction'])) {
  5324. $html .= '<h3>核心矛盾</h3>';
  5325. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  5326. }
  5327. // 主体列表
  5328. if (!empty($group['roles']) && is_array($group['roles'])) {
  5329. $html .= '<h3>主体列表</h3>';
  5330. $html .= '<ul>';
  5331. foreach ($group['roles'] as $role) {
  5332. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  5333. }
  5334. $html .= '</ul>';
  5335. }
  5336. // 美术风格
  5337. if (!empty($group['art_style'])) {
  5338. $html .= '<h3>美术风格</h3>';
  5339. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  5340. }
  5341. // 场景列表
  5342. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  5343. $html .= '<h3>场景列表</h3>';
  5344. $html .= '<ul>';
  5345. foreach ($group['scenes'] as $scene) {
  5346. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  5347. }
  5348. $html .= '</ul>';
  5349. }
  5350. // 分集剧本
  5351. if (!empty($group['episode_content'])) {
  5352. $html .= '<h3>分集剧本</h3>';
  5353. // 去除零宽字符和其他不可见字符
  5354. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  5355. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  5356. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  5357. }
  5358. $html .= '</div>';
  5359. }
  5360. }
  5361. return $html;
  5362. }
  5363. /**
  5364. * 构建PDF内容
  5365. */
  5366. private function buildPdfContent($pdf, $script) {
  5367. // 标题
  5368. $pdf->SetFont('dejavusans', 'B', 18);
  5369. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  5370. $pdf->Ln(5);
  5371. // 基本信息
  5372. $pdf->SetFont('dejavusans', '', 12);
  5373. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  5374. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  5375. $pdf->Ln(5);
  5376. // 剧本简介
  5377. if (!empty($script['intro'])) {
  5378. $pdf->SetFont('dejavusans', 'B', 14);
  5379. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  5380. $pdf->SetFont('dejavusans', '', 12);
  5381. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  5382. $pdf->Ln(3);
  5383. }
  5384. // 亮点
  5385. if (!empty($script['highlights'])) {
  5386. $pdf->SetFont('dejavusans', 'B', 14);
  5387. $pdf->Cell(0, 10, '亮点', 0, 1);
  5388. $pdf->SetFont('dejavusans', '', 12);
  5389. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  5390. $pdf->Ln(3);
  5391. }
  5392. // 核心矛盾
  5393. if (!empty($script['core_contradiction'])) {
  5394. $pdf->SetFont('dejavusans', 'B', 14);
  5395. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  5396. $pdf->SetFont('dejavusans', '', 12);
  5397. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  5398. $pdf->Ln(3);
  5399. }
  5400. // 艺术风格
  5401. if (!empty($script['art_style'])) {
  5402. $pdf->SetFont('dejavusans', 'B', 14);
  5403. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  5404. $pdf->SetFont('dejavusans', '', 12);
  5405. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  5406. $pdf->Ln(3);
  5407. }
  5408. // 备注
  5409. if (!empty($script['remark'])) {
  5410. $pdf->SetFont('dejavusans', 'B', 14);
  5411. $pdf->Cell(0, 10, '备注', 0, 1);
  5412. $pdf->SetFont('dejavusans', '', 12);
  5413. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  5414. $pdf->Ln(3);
  5415. }
  5416. // 角色列表
  5417. if (!empty($script['roles']) && is_array($script['roles'])) {
  5418. $pdf->SetFont('dejavusans', 'B', 14);
  5419. $pdf->Cell(0, 10, '角色列表', 0, 1);
  5420. $pdf->SetFont('dejavusans', '', 12);
  5421. foreach ($script['roles'] as $index => $role) {
  5422. if (is_array($role) || is_object($role)) {
  5423. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  5424. } else {
  5425. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  5426. }
  5427. }
  5428. $pdf->Ln(3);
  5429. }
  5430. // 角色关系
  5431. if (!empty($script['role_relationship'])) {
  5432. $pdf->SetFont('dejavusans', 'B', 14);
  5433. $pdf->Cell(0, 10, '角色关系', 0, 1);
  5434. $pdf->SetFont('dejavusans', '', 12);
  5435. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  5436. $pdf->Ln(3);
  5437. }
  5438. // 场景列表
  5439. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  5440. $pdf->SetFont('dejavusans', 'B', 14);
  5441. $pdf->Cell(0, 10, '场景列表', 0, 1);
  5442. $pdf->SetFont('dejavusans', '', 12);
  5443. foreach ($script['scenes'] as $index => $scene) {
  5444. if (is_array($scene) || is_object($scene)) {
  5445. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  5446. } else {
  5447. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  5448. }
  5449. }
  5450. $pdf->Ln(5);
  5451. }
  5452. // 分集内容
  5453. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  5454. $pdf->SetFont('dejavusans', 'B', 16);
  5455. $pdf->Cell(0, 12, '分集内容', 0, 1);
  5456. $pdf->Ln(3);
  5457. foreach ($script['episodes'] as $episode) {
  5458. // 检查是否需要新页面
  5459. if ($pdf->GetY() > 250) {
  5460. $pdf->AddPage();
  5461. }
  5462. $pdf->SetFont('dejavusans', 'B', 14);
  5463. $episodeTitle = '第' . $episode['episode_number'] . '集';
  5464. if (!empty($episode['title'])) {
  5465. $episodeTitle .= ':' . $episode['title'];
  5466. }
  5467. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  5468. // 处理分段内容
  5469. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  5470. $pdf->SetFont('dejavusans', '', 12);
  5471. foreach ($episode['segments'] as $segment) {
  5472. if (!empty($segment['segment_content'])) {
  5473. // 如果有分段编号,显示分段标题
  5474. if (!empty($segment['segment_number'])) {
  5475. $pdf->SetFont('dejavusans', 'B', 12);
  5476. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  5477. $pdf->SetFont('dejavusans', '', 12);
  5478. }
  5479. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  5480. $pdf->Ln(2);
  5481. }
  5482. }
  5483. }
  5484. $pdf->Ln(5);
  5485. }
  5486. }
  5487. }
  5488. /**
  5489. * 构建剧本文本内容
  5490. */
  5491. private function buildScriptContent($script) {
  5492. $content = '';
  5493. $groups = $script['group'];
  5494. $groups = (array)$groups;
  5495. foreach ($groups as $group) {
  5496. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  5497. // 剧本基本信息
  5498. if (!empty($group['intro'])) {
  5499. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  5500. }
  5501. if (!empty($group['highlights'])) {
  5502. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  5503. }
  5504. if (!empty($group['role_relationship'])) {
  5505. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  5506. }
  5507. if (!empty($group['core_contradiction'])) {
  5508. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  5509. }
  5510. if (!empty($group['roles']) && is_array($group['roles'])) {
  5511. $content .= "###主体列表\n";
  5512. foreach ($group['roles'] as $role) {
  5513. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  5514. }
  5515. $content .= "\n\n";
  5516. }
  5517. if (!empty($group['art_style'])) {
  5518. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  5519. }
  5520. // 场景信息
  5521. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  5522. $content .= "###场景列表\n";
  5523. foreach ($group['scenes'] as $scene) {
  5524. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  5525. }
  5526. $content .= "\n\n";
  5527. }
  5528. // 分集内容
  5529. if (!empty($group['episode_content'])) {
  5530. $content .= "###分集剧本\n";
  5531. $content .= $group['episode_content'];
  5532. // foreach ($script['episodes'] as $episode) {
  5533. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  5534. // // if (!empty($episode['episode_name'])) {
  5535. // // $content .= ":" . $episode['episode_name'];
  5536. // // }
  5537. // // $content .= "\n";
  5538. // $content .= $episode['episode_content'] . "\n\n";
  5539. // }
  5540. }
  5541. }
  5542. return $content;
  5543. }
  5544. /**
  5545. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  5546. *
  5547. * @param array $data 包含以下参数:
  5548. * - file: 上传的文件(UploadedFile 对象)或文件路径
  5549. * - question: 用户问题(可选)
  5550. * - model: 使用的模型(r1 或 v3,默认 v3)
  5551. * @return \Generator 返回生成器,用于流式输出
  5552. */
  5553. public function addChat($data) {
  5554. $uid = Site::getUid();
  5555. $anime_id = getProp($data, 'anime_id');
  5556. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5557. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5558. if (!$anime) Utils::throwError('20003:对话不存在');
  5559. $file = getProp($data, 'file');
  5560. $content = getProp($data, 'content', '');
  5561. $bid = getProp($data, 'bid', 0);
  5562. $script_id = getProp($data, 'script_id', 0);
  5563. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5564. $prompt = getProp($data, 'prompt');
  5565. $user_anime_name = getProp($anime, 'anime_name');
  5566. // 处理文本模型
  5567. $model = getProp($data, 'model');
  5568. if (!$model) {
  5569. // 用户没有输入,从anime表获取
  5570. $model = getProp($anime, 'model');
  5571. if (!$model) {
  5572. // anime表也没有,使用默认值
  5573. $model = 'doubao-seed-2-0-mini-260215';
  5574. }
  5575. }
  5576. // 验证模型是否在可用模型表中
  5577. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5578. $model = 'doubao-seed-2-0-mini-260215';
  5579. }
  5580. $is_multi = getProp($anime, 'is_multi');
  5581. $is_single = (int)$is_multi !== 1;
  5582. // 积分余额预检(仅单剧集模式收费)
  5583. if ($is_single) {
  5584. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5585. }
  5586. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5587. if ($prompt) {
  5588. $question .= "本次修改要求如下:\n{$prompt}";
  5589. }
  5590. // if (!$file && !$content && !$bid) {
  5591. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5592. // }
  5593. // 提取文件内容
  5594. if ($file) {
  5595. $content = $this->extractFileContent($file);
  5596. if (!$content) {
  5597. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5598. }
  5599. } elseif ($script_id) {
  5600. $content = $this->getContentByScriptId($script_id);
  5601. if (!$content) {
  5602. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5603. }
  5604. } elseif ($bid) {
  5605. $content = $this->getContentByBid($bid);
  5606. if (!$content) {
  5607. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5608. }
  5609. } elseif ($content) {
  5610. $content = filterContent($content);
  5611. } else {
  5612. $content = getProp($anime, 'content');
  5613. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5614. $need_generate_content = true;
  5615. }
  5616. }
  5617. // 美术风格
  5618. $input_art_style = getProp($data, 'art_style');
  5619. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5620. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5621. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5622. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5623. 中年女:邻居阿姨
  5624. 老年男:幽默大爷
  5625. 老年女:婆婆
  5626. 萌娃:奶气萌娃";
  5627. // 判断是否需要生成原文内容
  5628. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5629. // 如果需要生成原文内容,添加额外的要求
  5630. $content_generation_requirement = $need_generate_content
  5631. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5632. : "";
  5633. // 美术风格
  5634. if (!$mappedArtStyle) {
  5635. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5636. }else {
  5637. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5638. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5639. }else {
  5640. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5641. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5642. }
  5643. }
  5644. $systemPrompt = $is_single
  5645. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5646. 强制要求:
  5647. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5648. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5649. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5650. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5651. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5652. 普通要求:
  5653. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5654. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5655. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  5656. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5657. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5658. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5659. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5660. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5661. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5662. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5663. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5664. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5665. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5666. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5667. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5668. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5669. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5670. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5671. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5672. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5673. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5674. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5675. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5676. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5677. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5678. 5.{$mappedArtStyle_prompt}\n\n
  5679. 示例如下:\n
  5680. ###剧本名:西昆仑
  5681. ###故事梗概
  5682. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5683. ###剧本亮点
  5684. 亮点1:绝境奇药,生死一线
  5685. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5686. 亮点2:结拜兄妹,化解尴尬
  5687. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5688. 亮点3:纤发夺命,情愫暗涌
  5689. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5690. ###人物关系
  5691. 阿雪与梁萧之间存在兄妹之情。
  5692. ###核心矛盾
  5693. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5694. ###主体列表
  5695. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5696. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5697. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5698. 姿态:站立。}{{甜心小美}}
  5699. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5700. 全景,正面拍摄,青年女性,亚洲人。
  5701. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5702. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5703. 姿态:站立。}{{阳光青年}}
  5704. ###美术风格
  5705. 基础画风风格词:厚涂古风
  5706. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5707. ###场景列表
  5708. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5709. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5710. 无人物。}
  5711. ###分镜剧本
  5712. ##第1幕:徐家老旧厨房 白天 室内
  5713. 分镜1
  5714. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5715. 场景:徐家老旧厨房
  5716. 构图设计:全景,低角度仰视
  5717. 运镜调度:手持拍摄
  5718. 配音角色:旁白
  5719. 出镜角色:许芸-校服装、徐母
  5720. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5721. 画面类型:普通画面
  5722. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5723. 分镜2
  5724. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5725. 场景:徐家老旧厨房
  5726. 构图设计:近景,徐母面部特写
  5727. 运镜调度:固定镜头
  5728. 配音角色:徐母
  5729. 出镜角色:徐母
  5730. 台词内容:问我夜不归宿死哪儿去了。
  5731. 画面类型:对口型
  5732. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5733. ##第2幕:徐家简陋客厅 黄昏 室内
  5734. 分镜3
  5735. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5736. 场景:徐家简陋客厅
  5737. 构图设计:全景,景深虚化
  5738. 运镜调度:固定镜头
  5739. 配音角色:旁白
  5740. 出镜角色:无
  5741. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5742. 画面类型:普通画面
  5743. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5744. 分镜4
  5745. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5746. 场景:徐家简陋客厅
  5747. 构图设计:特写,火车票
  5748. 运镜调度:固定镜头
  5749. 配音角色:旁白
  5750. 出镜角色:无
  5751. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5752. 画面类型:普通画面
  5753. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5754. "
  5755. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5756. 强制要求:\n
  5757. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5758. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5759. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5760. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5761. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5762. 普通要求:\n
  5763. 1.剧本名(必须生成)必须与文档内容高度相关
  5764. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5765. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5766. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5767. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5768. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5769. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5770. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5771. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5772. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5773. 4.{$mappedArtStyle_prompt}\n\n
  5774. 示例如下:\n
  5775. ###剧本名:西昆仑
  5776. ###故事梗概
  5777. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5778. ###剧本亮点
  5779. 亮点1:绝境奇药,生死一线
  5780. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5781. 亮点2:结拜兄妹,化解尴尬
  5782. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5783. 亮点3:纤发夺命,情愫暗涌
  5784. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5785. ###人物关系
  5786. 阿雪与梁萧之间存在兄妹之情。
  5787. ###核心矛盾
  5788. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5789. ###主体列表
  5790. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5791. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5792. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5793. 姿态:站立。}{{甜心小美}}
  5794. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5795. 全景,正面拍摄,青年女性,亚洲人。
  5796. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5797. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5798. 姿态:站立。}{{阳光青年}}
  5799. ###美术风格
  5800. 基础画风风格词:厚涂古风
  5801. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5802. ###场景列表
  5803. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5804. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5805. 无人物。}";
  5806. // 构建消息
  5807. $messages = [
  5808. [
  5809. 'role' => 'system',
  5810. 'content' => $systemPrompt
  5811. ],
  5812. [
  5813. 'role' => 'user',
  5814. 'content' => "以下是文档内容:
  5815. {$content}
  5816. 用户问题:
  5817. {$question}"
  5818. ]
  5819. ];
  5820. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5821. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5822. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5823. if ($model === 'deepseek-chat') {
  5824. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5825. $model = 'deepseek-v4-flash';
  5826. $thinkingMode = 'disabled';
  5827. } elseif ($model === 'deepseek-reasoner') {
  5828. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5829. $model = 'deepseek-v4-flash';
  5830. $thinkingMode = 'enabled';
  5831. }
  5832. $post_data = [
  5833. 'model' => $model,
  5834. 'messages' => $messages,
  5835. // 'max_tokens' => 8192,
  5836. 'temperature' => 0.7,
  5837. 'frequency_penalty' => 0,
  5838. 'presence_penalty' => 0,
  5839. 'response_format' => ['type' => 'text'],
  5840. 'thinking' => ['type'=>$thinkingMode],
  5841. 'stream' => true // 启用流式输出
  5842. ];
  5843. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5844. // 根据模型类型选择调用方法
  5845. $fullContent = '';
  5846. $fullReasoningContent = '';
  5847. $usage = [];
  5848. try {
  5849. $streamGenerator = $this->dispatchStreamByModel($post_data);
  5850. // 验证返回值类型
  5851. if (!is_iterable($streamGenerator)) {
  5852. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5853. dLog('deepseek')->error('addChat流式生成器无效', [
  5854. 'generator_type' => $errorType,
  5855. 'model' => $model,
  5856. 'anime_id' => $anime_id
  5857. ]);
  5858. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5859. 'type' => $errorType,
  5860. 'model' => $model
  5861. ]);
  5862. yield [
  5863. 'type' => 'error',
  5864. 'script' => [],
  5865. 'episode' => [],
  5866. 'answer' => '',
  5867. 'reasoning' => '',
  5868. 'usage' => [],
  5869. 'error' => '接口返回数据异常,请重新请求'
  5870. ];
  5871. return;
  5872. }
  5873. // 处理流式输出
  5874. foreach ($streamGenerator as $chunk) {
  5875. if (isset($chunk['type'])) {
  5876. if ($chunk['type'] === 'done') {
  5877. // 最终结果
  5878. $fullContent = $chunk['full_content'];
  5879. $fullReasoningContent = $chunk['full_reasoning'];
  5880. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5881. } else {
  5882. // 逐块yield数据
  5883. yield $chunk;
  5884. }
  5885. }
  5886. }
  5887. } catch (\Exception $e) {
  5888. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5889. 'model' => $model,
  5890. 'anime_id' => $anime_id,
  5891. 'trace' => $e->getTraceAsString()
  5892. ]);
  5893. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5894. 'error' => $e->getMessage(),
  5895. 'model' => $model
  5896. ]);
  5897. yield [
  5898. 'type' => 'error',
  5899. 'script' => [],
  5900. 'episode' => [],
  5901. 'answer' => '',
  5902. 'reasoning' => '',
  5903. 'usage' => [],
  5904. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5905. ];
  5906. return;
  5907. }
  5908. dLog('deepseek')->info('完整内容: '.$fullContent);
  5909. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5910. // 处理完整内容并返回最终结果
  5911. $script_arr = [];
  5912. if ($fullContent) {
  5913. $script_arr = handleScriptContent($fullContent);
  5914. dLog('deepseek')->info('解析内容', $script_arr);
  5915. logDB('deepseek', 'info', '解析内容', $script_arr);
  5916. }
  5917. if (empty($script_arr['roles'])) {
  5918. // 未生成剧本相关内容,保存对话记录并返回提示
  5919. dLog('deepseek')->info('未生成剧本相关的内容');
  5920. try {
  5921. DB::beginTransaction();
  5922. $now = date('Y-m-d H:i:s');
  5923. // 保存对话记录
  5924. $records = [
  5925. [
  5926. 'uid' => $uid,
  5927. 'anime_id' => $anime_id,
  5928. 'sequence' => 0,
  5929. 'role' => 'user',
  5930. 'content' => $prompt,
  5931. 'created_at' => $now,
  5932. 'updated_at' => $now
  5933. ],
  5934. [
  5935. 'uid' => $uid,
  5936. 'anime_id' => $anime_id,
  5937. 'sequence' => 0,
  5938. 'role' => 'assistant',
  5939. // 'content' => $fullContent,
  5940. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5941. 'created_at' => $now,
  5942. 'updated_at' => $now
  5943. ]
  5944. ];
  5945. DB::table('mp_anime_records')->insert($records);
  5946. DB::commit();
  5947. } catch (\Exception $e) {
  5948. DB::rollBack();
  5949. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5950. }
  5951. yield [
  5952. 'type' => 'done',
  5953. 'script' => [],
  5954. 'episode' => [],
  5955. 'answer' => $fullContent,
  5956. 'reasoning' => $fullReasoningContent,
  5957. 'usage' => $usage,
  5958. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5959. ];
  5960. return;
  5961. }
  5962. // 如果需要生成原文内容,从script_arr中提取
  5963. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5964. $content = $script_arr['content'];
  5965. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5966. if (!$content) {
  5967. yield [
  5968. 'type' => 'done',
  5969. 'script' => [],
  5970. 'episode' => [],
  5971. 'answer' => $fullContent,
  5972. 'reasoning' => $fullReasoningContent,
  5973. 'usage' => $usage,
  5974. 'error' => '未生成剧本内容,请调整提示词再试'
  5975. ];
  5976. return;
  5977. }
  5978. }
  5979. // 替换美术风格
  5980. if ($mappedArtStyle !== '') {
  5981. $script_arr['art_style'] = $mappedArtStyle;
  5982. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5983. }
  5984. // 新建动漫
  5985. if ($user_anime_name == '新剧本策划') {
  5986. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5987. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5988. // if (!$anime_name) {
  5989. // // 未识别到剧本名,保存对话记录并返回提示
  5990. // dLog('deepseek')->info('未能识别到剧本名称');
  5991. // try {
  5992. // DB::beginTransaction();
  5993. // $now = date('Y-m-d H:i:s');
  5994. // // 保存对话记录
  5995. // $records = [
  5996. // [
  5997. // 'uid' => $uid,
  5998. // 'anime_id' => $anime_id,
  5999. // 'sequence' => 0,
  6000. // 'role' => 'user',
  6001. // 'content' => $prompt,
  6002. // 'created_at' => $now,
  6003. // 'updated_at' => $now
  6004. // ],
  6005. // [
  6006. // 'uid' => $uid,
  6007. // 'anime_id' => $anime_id,
  6008. // 'sequence' => 0,
  6009. // 'role' => 'assistant',
  6010. // 'content' => '未能生成剧本名称,请重试',
  6011. // 'created_at' => $now,
  6012. // 'updated_at' => $now
  6013. // ]
  6014. // ];
  6015. // DB::table('mp_anime_records')->insert($records);
  6016. // DB::commit();
  6017. // } catch (\Exception $e) {
  6018. // DB::rollBack();
  6019. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6020. // }
  6021. // yield [
  6022. // 'type' => 'done',
  6023. // 'script' => [],
  6024. // 'episode' => [],
  6025. // 'answer' => $fullContent,
  6026. // 'reasoning' => $fullReasoningContent,
  6027. // 'usage' => $usage,
  6028. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  6029. // ];
  6030. // return;
  6031. // }
  6032. // 确认对话名称唯一性
  6033. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6034. $anime_name = $anime_name . '_' . date('YmdHis');
  6035. }
  6036. }else {
  6037. $anime_name = $user_anime_name;
  6038. }
  6039. $table_data = [
  6040. 'user_id' => $uid,
  6041. 'anime_name' => $anime_name,
  6042. 'model' => $model,
  6043. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6044. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6045. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6046. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6047. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6048. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6049. 'art_style_type' => $input_art_style,
  6050. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6051. 'status' => '解析完成',
  6052. 'content' => $content,
  6053. 'is_multi' => $is_multi,
  6054. 'ace_mode' => $ace_mode,
  6055. 'generate_status' => '待执行',
  6056. 'updated_at' => date('Y-m-d H:i:s')
  6057. ];
  6058. if ($table_data['content']) {
  6059. $chapters = splitContent($table_data['content']);
  6060. $chapter_count = count($chapters);
  6061. if ($chapter_count > 0) {
  6062. $table_data['start_episode_sequence'] = 1;
  6063. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6064. }
  6065. }
  6066. // 如果有剧本ID则进行绑定
  6067. if ($script_id) {
  6068. $table_data['script_id'] = $script_id;
  6069. }
  6070. $single_episode = [];
  6071. try {
  6072. DB::beginTransaction();
  6073. $now = date('Y-m-d H:i:s');
  6074. // 更新动漫大纲
  6075. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6076. if (!$boolen) {
  6077. dLog('deepseek')->info('动漫保存失败', $table_data);
  6078. Utils::throwError('20003:动漫保存失败');
  6079. }
  6080. // 保存对话记录
  6081. $records = [
  6082. [
  6083. 'uid' => $uid,
  6084. 'anime_id' => $anime_id,
  6085. 'sequence' => 0,
  6086. 'role' => 'user',
  6087. 'content' => $prompt,
  6088. 'created_at' => date('Y-m-d H:i:s'),
  6089. 'updated_at' => date('Y-m-d H:i:s')
  6090. ],
  6091. [
  6092. 'uid' => $uid,
  6093. 'anime_id' => $anime_id,
  6094. 'sequence' => 0,
  6095. 'role' => 'assistant',
  6096. 'content' => $fullContent,
  6097. 'created_at' => date('Y-m-d H:i:s'),
  6098. 'updated_at' => date('Y-m-d H:i:s')
  6099. ]
  6100. ];
  6101. // 保存对话记录
  6102. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6103. if (!$boolen3) {
  6104. Utils::throwError('20003:对话记录保存失败');
  6105. }
  6106. if ($is_single) {
  6107. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6108. if (empty($episode_arr['acts'])) {
  6109. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6110. }
  6111. $saveResult = $this->saveEpisodeVersionData(
  6112. $anime_id,
  6113. 1,
  6114. $episode_arr,
  6115. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6116. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6117. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6118. null,
  6119. null,
  6120. false,
  6121. $content,
  6122. $now
  6123. );
  6124. $single_episode = $saveResult['episode'];
  6125. $episode_id = $saveResult['episode_id'];
  6126. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6127. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6128. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6129. 'props' => json_encode($saveResult['merged_props'], 256),
  6130. 'updated_at' => $now
  6131. ]);
  6132. if ($boolen5 === false) {
  6133. Utils::throwError('20003:单剧集主表资源同步失败');
  6134. }
  6135. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6136. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6137. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6138. $episode_record_content = '确认分镜大纲';
  6139. if ($content !== '') {
  6140. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6141. }
  6142. $episode_records = [
  6143. [
  6144. 'uid' => $uid,
  6145. 'anime_id' => $anime_id,
  6146. 'role' => 'user',
  6147. 'content' => $episode_record_content,
  6148. 'sequence' => 1,
  6149. 'episode_id' => $episode_id,
  6150. 'created_at' => $now,
  6151. 'updated_at' => $now
  6152. ],
  6153. [
  6154. 'uid' => $uid,
  6155. 'anime_id' => $anime_id,
  6156. 'role' => 'assistant',
  6157. 'content' => $fullContent,
  6158. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6159. 'sequence' => 1,
  6160. 'episode_id' => $episode_id,
  6161. 'created_at' => $now,
  6162. 'updated_at' => $now
  6163. ]
  6164. ];
  6165. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6166. if (!$boolen4) {
  6167. Utils::throwError('20003:单剧集分镜记录保存失败');
  6168. }
  6169. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6170. if ($is_single && !empty($single_episode)) {
  6171. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6172. 'anime_id' => $anime_id,
  6173. 'episode_id' => $episode_id ?? 0,
  6174. 'model' => $model,
  6175. 'source' => 'addChat',
  6176. ]);
  6177. }
  6178. }
  6179. }catch (\Exception $e) {
  6180. DB::rollBack();
  6181. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6182. yield [
  6183. 'type' => 'done',
  6184. 'answer' => $fullContent,
  6185. 'reasoning' => $fullReasoningContent,
  6186. 'usage' => $usage,
  6187. 'error' => $e->getMessage(),
  6188. ];
  6189. return;
  6190. }
  6191. DB::commit();
  6192. dLog('deepseek')->info('保存完毕');
  6193. if ($is_single && !empty($single_episode)) {
  6194. // $this->batchSetGlobalRoleImg([
  6195. // 'anime_id' => $anime_id,
  6196. // ]);
  6197. // $this->batchSetGlobalSceneImg([
  6198. // 'anime_id' => $anime_id,
  6199. // ]);
  6200. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6201. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6202. }
  6203. $table_data['anime_id'] = $anime_id;
  6204. $table_data['roles'] = json_decode($table_data['roles'], true);
  6205. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6206. // $table_data['episodes'] = $script_arr['episodes'];
  6207. unset($table_data['created_at']);
  6208. unset($table_data['updated_at']);
  6209. unset($table_data['status']);
  6210. dLog('deepseek')->info('开始返回');
  6211. yield [
  6212. 'type' => 'done',
  6213. 'script' => $table_data,
  6214. 'episode' => $single_episode,
  6215. 'answer' => $fullContent,
  6216. 'reasoning' => $fullReasoningContent,
  6217. 'usage' => $usage
  6218. ];
  6219. }
  6220. public function reGenerateAnime($data) {
  6221. $uid = Site::getUid();
  6222. $file = getProp($data, 'file');
  6223. $content = getProp($data, 'content', '');
  6224. $bid = getProp($data, 'bid', 0);
  6225. $script_id = getProp($data, 'script_id', 0);
  6226. $anime_id = getProp($data, 'anime_id');
  6227. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6228. if (!$anime) {
  6229. Utils::throwError('20003:该对话不存在');
  6230. }
  6231. $user_anime_name = getProp($anime, 'anime_name');
  6232. $prompt = getProp($data, 'prompt');
  6233. // 处理文本模型
  6234. $model = getProp($data, 'model');
  6235. if (!$model) {
  6236. // 用户没有输入,从anime表获取
  6237. $model = getProp($anime, 'model');
  6238. if (!$model) {
  6239. // anime表也没有,使用默认值
  6240. $model = 'doubao-seed-2-0-mini-260215';
  6241. }
  6242. }
  6243. // 验证模型是否在可用模型表中
  6244. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6245. $model = 'doubao-seed-2-0-mini-260215';
  6246. }
  6247. $is_multi = getProp($anime, 'is_multi', 1);
  6248. $is_single = (int)$is_multi !== 1;
  6249. // 积分余额预检(仅单剧集模式收费)
  6250. if ($is_single) {
  6251. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  6252. }
  6253. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  6254. if ($is_single) {
  6255. $episode_exists = DB::table('mp_anime_episodes')
  6256. ->where('anime_id', $anime_id)
  6257. ->where('sequence', 1)
  6258. ->exists();
  6259. if ($episode_exists) {
  6260. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  6261. }
  6262. }
  6263. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  6264. if ($prompt) {
  6265. $question .= "本次修改要求如下:\n{$prompt}";
  6266. }
  6267. // 提取文件内容
  6268. if ($file) {
  6269. $content = $this->extractFileContent($file);
  6270. if (!$content) {
  6271. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6272. }
  6273. } elseif ($script_id) {
  6274. $content = $this->getContentByScriptId($script_id);
  6275. if (!$content) {
  6276. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6277. }
  6278. } elseif ($bid) {
  6279. $content = $this->getContentByBid($bid);
  6280. if (!$content) {
  6281. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6282. }
  6283. } elseif ($content) {
  6284. $content = filterContent($content);
  6285. }else {
  6286. $content = filterContent(getProp($anime, 'content'));
  6287. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6288. $need_generate_content = true;
  6289. }
  6290. }
  6291. // 判断是否需要生成原文内容
  6292. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6293. // 如果需要生成原文内容,添加额外的要求
  6294. $content_generation_requirement = $need_generate_content
  6295. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6296. : "";
  6297. // 美术风格
  6298. $input_art_style = getProp($anime, 'art_style');
  6299. if (!$input_art_style) {
  6300. $input_art_style = getProp($data, 'art_style');
  6301. }
  6302. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6303. // 美术风格
  6304. if (!$mappedArtStyle) {
  6305. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6306. }else {
  6307. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6308. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6309. }else {
  6310. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6311. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6312. }
  6313. }
  6314. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  6315. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  6316. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  6317. 中年女:邻居阿姨
  6318. 老年男:幽默大爷
  6319. 老年女:婆婆
  6320. 萌娃:奶气萌娃";
  6321. $system_message = ['role'=>'system', 'content'=>$is_single
  6322. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6323. 强制要求:
  6324. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6325. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6326. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6327. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6328. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6329. 普通要求:
  6330. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6331. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6332. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6333. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6334. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6335. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6336. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6337. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6338. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6339. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6340. 3.$mappedArtStyle_prompt\n\n
  6341. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6342. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6343. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6344. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  6345. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  6346. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6347. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6348. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6349. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6350. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6351. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6352. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6353. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6354. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6355. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  6356. 示例如下:\n
  6357. ###剧本名:西昆仑
  6358. ###故事梗概
  6359. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6360. ###剧本亮点
  6361. 亮点1:绝境奇药,生死一线
  6362. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6363. 亮点2:结拜兄妹,化解尴尬
  6364. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6365. 亮点3:纤发夺命,情愫暗涌
  6366. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6367. ###人物关系
  6368. 阿雪与梁萧之间存在兄妹之情。
  6369. ###核心矛盾
  6370. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6371. ###主体列表
  6372. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6373. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6374. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6375. 姿态:站立。}{{甜心小美}}
  6376. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6377. 全景,正面拍摄,青年女性,亚洲人。
  6378. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6379. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6380. 姿态:站立。}{{阳光青年}}
  6381. ###美术风格
  6382. 基础画风风格词:厚涂古风
  6383. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6384. ###场景列表
  6385. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6386. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6387. 无人物。}
  6388. ###分镜剧本
  6389. ##第1幕:徐家老旧厨房 白天 室内
  6390. 分镜1
  6391. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6392. 场景:徐家老旧厨房
  6393. 构图设计:全景,低角度仰视
  6394. 运镜调度:手持拍摄
  6395. 配音角色:旁白
  6396. 出镜角色:许芸-校服装、徐母
  6397. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6398. 画面类型:普通画面
  6399. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6400. 分镜2
  6401. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6402. 场景:徐家老旧厨房
  6403. 构图设计:近景,徐母面部特写
  6404. 运镜调度:固定镜头
  6405. 配音角色:徐母
  6406. 出镜角色:徐母
  6407. 台词内容:问我夜不归宿死哪儿去了。
  6408. 画面类型:对口型
  6409. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6410. ##第2幕:徐家简陋客厅 黄昏 室内
  6411. 分镜3
  6412. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6413. 场景:徐家简陋客厅
  6414. 构图设计:全景,景深虚化
  6415. 运镜调度:固定镜头
  6416. 配音角色:旁白
  6417. 出镜角色:无
  6418. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6419. 画面类型:普通画面
  6420. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6421. 分镜4
  6422. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6423. 场景:徐家简陋客厅
  6424. 构图设计:特写,火车票
  6425. 运镜调度:固定镜头
  6426. 配音角色:旁白
  6427. 出镜角色:无
  6428. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6429. 画面类型:普通画面
  6430. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  6431. "
  6432. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6433. 强制要求:\n
  6434. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6435. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6436. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6437. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6438. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6439. 普通要求:\n
  6440. 1.剧本名(必须生成)必须与文档内容高度相关
  6441. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6442. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6443. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6444. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6445. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6446. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6447. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6448. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6449. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6450. 4.$mappedArtStyle_prompt\n\n
  6451. 示例如下:\n
  6452. ###剧本名:西昆仑
  6453. ###故事梗概
  6454. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6455. ###剧本亮点
  6456. 亮点1:绝境奇药,生死一线
  6457. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6458. 亮点2:结拜兄妹,化解尴尬
  6459. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6460. 亮点3:纤发夺命,情愫暗涌
  6461. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6462. ###人物关系
  6463. 阿雪与梁萧之间存在兄妹之情。
  6464. ###核心矛盾
  6465. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6466. ###主体列表
  6467. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6468. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6469. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6470. 姿态:站立。}{{甜心小美}}
  6471. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6472. 全景,正面拍摄,青年女性,亚洲人。
  6473. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6474. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6475. 姿态:站立。}{{阳光青年}}
  6476. ###美术风格
  6477. 基础画风风格词:厚涂古风
  6478. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6479. ###场景列表
  6480. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6481. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6482. 无人物。}"];
  6483. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6484. $episode_count = $this->extractEpisodeNumber($prompt);
  6485. if ((int)getProp($anime, 'is_multi') !== 1) {
  6486. yield [
  6487. 'type' => 'done',
  6488. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6489. 'reasoning' => '',
  6490. 'usage' => []
  6491. ];
  6492. return;
  6493. }
  6494. if ($episode_count) {
  6495. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6496. $system_message = [
  6497. 'role' => 'system',
  6498. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6499. 强制要求:\n
  6500. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6501. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6502. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6503. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6504. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6505. 普通要求:\n
  6506. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6507. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6508. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6509. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6510. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  6511. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6512. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6513. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6514. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6515. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6516. 示例如下:\n
  6517. ###剧本名:西昆仑
  6518. ###故事梗概
  6519. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6520. ###剧本亮点
  6521. 亮点1:绝境奇药,生死一线
  6522. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6523. 亮点2:结拜兄妹,化解尴尬
  6524. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6525. 亮点3:纤发夺命,情愫暗涌
  6526. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6527. ###人物关系
  6528. 阿雪与梁萧之间存在兄妹之情。
  6529. ###核心矛盾
  6530. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6531. ###主体列表
  6532. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6533. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6534. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6535. 姿态:站立。}{{甜心小美}}
  6536. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6537. 全景,正面拍摄,青年女性,亚洲人。
  6538. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6539. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6540. 姿态:站立。}{{阳光青年}}
  6541. ###美术风格
  6542. 基础画风风格词:厚涂古风
  6543. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6544. ###场景列表
  6545. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6546. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6547. 无人物。}
  6548. ###分集详细内容
  6549. ##第1章 重生
  6550. 我重生了。
  6551. 源于一个男人偏执的暗恋。
  6552. ##第2章 相救
  6553. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6554. 我眼睛扫向站在锅炉后的卞大伟。"
  6555. ];
  6556. // 构建消息
  6557. $messages = [
  6558. $system_message,
  6559. [
  6560. 'role' => 'user',
  6561. 'content' => "以下是文档内容:
  6562. {$content}
  6563. 用户问题:
  6564. {$question}"
  6565. ]
  6566. ];
  6567. }else {
  6568. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6569. // 构建消息
  6570. $messages = [
  6571. $system_message,
  6572. [
  6573. 'role' => 'user',
  6574. 'content' => "以下是文档内容:
  6575. {$content}
  6576. 用户问题:
  6577. {$question}"
  6578. ]
  6579. ];
  6580. }else {
  6581. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6582. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6583. return (array)$value;
  6584. })->toArray();
  6585. array_unshift($messages, $system_message);
  6586. $messages[] = [
  6587. 'role' => 'user',
  6588. 'content' => $prompt
  6589. ];
  6590. }
  6591. }
  6592. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6593. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6594. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6595. if ($model === 'deepseek-chat') {
  6596. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6597. $model = 'deepseek-v4-flash';
  6598. $thinkingMode = 'disabled';
  6599. } elseif ($model === 'deepseek-reasoner') {
  6600. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6601. $model = 'deepseek-v4-flash';
  6602. $thinkingMode = 'enabled';
  6603. }
  6604. $post_data = [
  6605. 'model' => $model,
  6606. 'messages' => $messages,
  6607. // 'max_tokens' => 8192,
  6608. 'temperature' => 0.7,
  6609. 'frequency_penalty' => 0,
  6610. 'presence_penalty' => 0,
  6611. 'response_format' => ['type' => 'text'],
  6612. 'thinking' => ['type' => $thinkingMode],
  6613. 'stream' => true // 启用流式输出
  6614. ];
  6615. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6616. // 根据模型类型选择调用方法
  6617. $fullContent = '';
  6618. $fullReasoningContent = '';
  6619. $usage = [];
  6620. // dd($post_data);
  6621. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6622. try {
  6623. $streamGenerator = $this->dispatchStreamByModel($post_data);
  6624. // 验证返回值类型
  6625. if (!is_iterable($streamGenerator)) {
  6626. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6627. dLog('deepseek')->error('方法名流式生成器无效', [
  6628. 'generator_type' => $errorType,
  6629. 'model' => $model,
  6630. // 添加其他上下文信息
  6631. ]);
  6632. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6633. 'type' => $errorType,
  6634. 'model' => $model
  6635. ]);
  6636. yield [
  6637. 'type' => 'error',
  6638. // 根据方法返回相应的空数据结构
  6639. 'answer' => '',
  6640. 'reasoning' => '',
  6641. 'usage' => [],
  6642. 'error' => '接口返回数据异常,请重新请求'
  6643. ];
  6644. return;
  6645. }
  6646. // 处理流式输出
  6647. foreach ($streamGenerator as $chunk) {
  6648. if (isset($chunk['type'])) {
  6649. if ($chunk['type'] === 'done') {
  6650. $fullContent = $chunk['full_content'];
  6651. $fullReasoningContent = $chunk['full_reasoning'];
  6652. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6653. } else {
  6654. yield $chunk;
  6655. }
  6656. }
  6657. }
  6658. } catch (\Exception $e) {
  6659. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6660. 'model' => $model,
  6661. 'trace' => $e->getTraceAsString()
  6662. ]);
  6663. logDB('deepseek', 'error', '方法名流式处理失败', [
  6664. 'error' => $e->getMessage(),
  6665. 'model' => $model
  6666. ]);
  6667. yield [
  6668. 'type' => 'error',
  6669. // 根据方法返回相应的空数据结构
  6670. 'answer' => '',
  6671. 'reasoning' => '',
  6672. 'usage' => [],
  6673. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6674. ];
  6675. return;
  6676. }
  6677. dLog('deepseek')->info('完整内容: '.$fullContent);
  6678. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6679. // 处理完整内容并返回最终结果
  6680. $script_arr = [];
  6681. if ($fullContent) {
  6682. $script_arr = handleScriptContent($fullContent);
  6683. dLog('deepseek')->info('解析内容', $script_arr);
  6684. logDB('deepseek', 'info', '解析内容', $script_arr);
  6685. }
  6686. if (empty($script_arr['roles'])) {
  6687. // 未生成剧本相关内容,保存对话记录并返回提示
  6688. dLog('deepseek')->info('未生成剧本相关的内容');
  6689. try {
  6690. $now = date('Y-m-d H:i:s');
  6691. // 保存对话记录
  6692. $records = [
  6693. [
  6694. 'uid' => $uid,
  6695. 'anime_id' => $anime_id,
  6696. 'sequence' => 0,
  6697. 'role' => 'user',
  6698. 'content' => $prompt,
  6699. 'created_at' => $now,
  6700. 'updated_at' => $now
  6701. ],
  6702. [
  6703. 'uid' => $uid,
  6704. 'anime_id' => $anime_id,
  6705. 'sequence' => 0,
  6706. 'role' => 'assistant',
  6707. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6708. 'created_at' => $now,
  6709. 'updated_at' => $now
  6710. ]
  6711. ];
  6712. DB::table('mp_anime_records')->insert($records);
  6713. } catch (\Exception $e) {
  6714. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6715. }
  6716. yield [
  6717. 'type' => 'done',
  6718. 'script' => [],
  6719. 'episode' => [],
  6720. 'answer' => $fullContent,
  6721. 'reasoning' => $fullReasoningContent,
  6722. 'usage' => $usage,
  6723. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6724. ];
  6725. return;
  6726. }
  6727. // 替换美术风格
  6728. if ($mappedArtStyle !== '') {
  6729. $script_arr['art_style'] = $mappedArtStyle;
  6730. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6731. }
  6732. if ($user_anime_name != '新剧本策划') {
  6733. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6734. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6735. // 确认对话名称唯一性
  6736. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6737. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6738. }
  6739. }else {
  6740. $anime_name = $user_anime_name;
  6741. }
  6742. $table_data = [
  6743. 'user_id' => $uid,
  6744. 'model' => $model,
  6745. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6746. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6747. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6748. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6749. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6750. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6751. 'art_style_type' => $input_art_style,
  6752. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6753. 'status' => '解析完成',
  6754. 'generate_status' => '待执行',
  6755. 'updated_at' => date('Y-m-d H:i:s')
  6756. ];
  6757. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6758. // 如果是修改集数,则将content内容更新(会改变原文)
  6759. if (isset($episode_count) && $episode_count > 0) {
  6760. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6761. $table_data['start_episode_sequence'] = 1;
  6762. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6763. }else {
  6764. // 如果需要生成原文内容,从script_arr中提取
  6765. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6766. $table_data['content'] = $script_arr['content'];
  6767. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6768. if (!$table_data['content']) {
  6769. yield [
  6770. 'type' => 'done',
  6771. 'script' => [],
  6772. 'episode' => [],
  6773. 'answer' => $fullContent,
  6774. 'reasoning' => $fullReasoningContent,
  6775. 'usage' => $usage,
  6776. 'error' => '未生成剧本内容,请调整提示词再试'
  6777. ];
  6778. return;
  6779. }
  6780. }
  6781. if (isset($table_data['content']) && $table_data['content']) {
  6782. $chapters = splitContent($table_data['content']);
  6783. $chapter_count = count($chapters);
  6784. if ($chapter_count > 0) {
  6785. $table_data['start_episode_sequence'] = 1;
  6786. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6787. }
  6788. }
  6789. }
  6790. $single_episode = [];
  6791. try {
  6792. DB::beginTransaction();
  6793. $now = date('Y-m-d H:i:s');
  6794. // 更新动漫大纲
  6795. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6796. if (!$boolen) {
  6797. dLog('deepseek')->info('对话修改失败', $table_data);
  6798. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6799. Utils::throwError('20003:对话修改失败');
  6800. }
  6801. // 保存对话记录
  6802. $records = [
  6803. [
  6804. 'uid' => $uid,
  6805. 'anime_id' => $anime_id,
  6806. 'sequence' => 0,
  6807. 'role' => 'user',
  6808. 'content' => $prompt,
  6809. 'created_at' => $now,
  6810. 'updated_at' => $now
  6811. ],
  6812. [
  6813. 'uid' => $uid,
  6814. 'anime_id' => $anime_id,
  6815. 'sequence' => 0,
  6816. 'role' => 'assistant',
  6817. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6818. 'content' => $fullContent,
  6819. 'created_at' => $now,
  6820. 'updated_at' => $now
  6821. ]
  6822. ];
  6823. // 保存对话记录
  6824. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6825. if (!$boolen3) {
  6826. Utils::throwError('20003:对话记录保存失败');
  6827. }
  6828. // 单剧集模式:生成并保存剧集信息
  6829. if ($is_single) {
  6830. $anime_name = getProp($anime, 'anime_name', '未命名');
  6831. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6832. if (empty($episode_arr['acts'])) {
  6833. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6834. }
  6835. $saveResult = $this->saveEpisodeVersionData(
  6836. $anime_id,
  6837. 1,
  6838. $episode_arr,
  6839. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6840. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6841. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6842. null,
  6843. null,
  6844. false,
  6845. $content,
  6846. $now
  6847. );
  6848. $single_episode = $saveResult['episode'];
  6849. $episode_id = $saveResult['episode_id'];
  6850. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6851. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6852. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6853. 'props' => json_encode($saveResult['merged_props'], 256),
  6854. 'updated_at' => $now
  6855. ]);
  6856. if ($boolen5 === false) {
  6857. Utils::throwError('20003:单剧集主表资源同步失败');
  6858. }
  6859. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6860. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6861. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6862. $episode_record_content = '确认分镜大纲';
  6863. if ($content !== '') {
  6864. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6865. }
  6866. $episode_records = [
  6867. [
  6868. 'uid' => $uid,
  6869. 'anime_id' => $anime_id,
  6870. 'role' => 'user',
  6871. 'content' => $episode_record_content,
  6872. 'sequence' => 1,
  6873. 'episode_id' => $episode_id,
  6874. 'created_at' => $now,
  6875. 'updated_at' => $now
  6876. ],
  6877. [
  6878. 'uid' => $uid,
  6879. 'anime_id' => $anime_id,
  6880. 'role' => 'assistant',
  6881. 'content' => $fullContent,
  6882. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6883. 'sequence' => 1,
  6884. 'episode_id' => $episode_id,
  6885. 'created_at' => $now,
  6886. 'updated_at' => $now
  6887. ]
  6888. ];
  6889. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6890. if (!$boolen4) {
  6891. Utils::throwError('20003:单剧集分镜记录保存失败');
  6892. }
  6893. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6894. if ($is_single && !empty($single_episode)) {
  6895. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6896. 'anime_id' => $anime_id,
  6897. 'episode_id' => $episode_id ?? 0,
  6898. 'model' => $model,
  6899. 'source' => 'reGenerateAnime',
  6900. ]);
  6901. }
  6902. }
  6903. }catch (\Exception $e) {
  6904. DB::rollBack();
  6905. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  6906. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  6907. yield [
  6908. 'type' => 'done',
  6909. 'answer' => $fullContent,
  6910. 'reasoning' => $fullReasoningContent,
  6911. 'usage' => $usage,
  6912. 'error' => $e->getMessage(),
  6913. ];
  6914. return;
  6915. }
  6916. DB::commit();
  6917. dLog('deepseek')->info('保存完毕');
  6918. if ($is_single && !empty($single_episode)) {
  6919. // $this->batchSetGlobalRoleImg([
  6920. // 'anime_id' => $anime_id,
  6921. // ]);
  6922. // $this->batchSetGlobalSceneImg([
  6923. // 'anime_id' => $anime_id,
  6924. // ]);
  6925. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6926. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6927. }
  6928. $table_data['anime_id'] = $anime_id;
  6929. $table_data['roles'] = json_decode($table_data['roles'], true);
  6930. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6931. unset($table_data['updated_at']);
  6932. unset($table_data['status']);
  6933. yield [
  6934. 'type' => 'done',
  6935. 'script' => $table_data,
  6936. 'episode' => $single_episode,
  6937. 'answer' => $fullContent,
  6938. 'reasoning' => $fullReasoningContent,
  6939. 'usage' => $usage
  6940. ];
  6941. }
  6942. public function chat($data) {
  6943. $uid = Site::getUid();
  6944. // 积分余额预检(不足直接报错)
  6945. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  6946. $anime_id = getProp($data, 'anime_id');
  6947. $file = getProp($data, 'file');
  6948. $content = getProp($data, 'content', '');
  6949. $bid = getProp($data, 'bid', 0);
  6950. $script_id = getProp($data, 'script_id', 0);
  6951. $episode_number = getProp($data, 'episode_number', 1);
  6952. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6953. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6954. if (!$anime) Utils::throwError('20003:该对话不存在!');
  6955. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  6956. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  6957. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  6958. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  6959. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  6960. $roles = is_array($roles) ? $roles : [];
  6961. $scenes = is_array($scenes) ? $scenes : [];
  6962. // 获取最后一集序号
  6963. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  6964. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  6965. // 转换主体列表和场景列表的格式
  6966. // 获取参考主体或场景
  6967. if ((int)$episode_number === 1) {
  6968. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  6969. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  6970. }else {
  6971. $prev_episode_number = $episode_number - 1;
  6972. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  6973. }
  6974. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  6975. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  6976. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  6977. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  6978. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  6979. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  6980. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  6981. 中年女:邻居阿姨
  6982. 老年男:幽默大爷
  6983. 老年女:婆婆
  6984. 萌娃:奶气萌娃";
  6985. if ($roles_content) {
  6986. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  6987. 主体范围:\n {$roles_content}\n
  6988. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  6989. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6990. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6991. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6992. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6993. }else {
  6994. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6995. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6996. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6997. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6998. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6999. }
  7000. if ($scenes_content) {
  7001. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7002. 场景范围:\n {$scenes_content}\n
  7003. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  7004. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7005. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7006. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  7007. }else {
  7008. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7009. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7010. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7011. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  7012. }
  7013. // 提取文件内容
  7014. if ($file) {
  7015. $uploaded_content = $this->extractFileContent($file);
  7016. if (!$uploaded_content) {
  7017. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7018. }
  7019. } elseif ($script_id) {
  7020. $uploaded_content = $this->getContentByScriptId($script_id);
  7021. if (!$uploaded_content) {
  7022. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7023. }
  7024. } elseif ($bid) {
  7025. $uploaded_content = $this->getContentByBid($bid);
  7026. if (!$uploaded_content) {
  7027. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7028. }
  7029. } elseif ($content) {
  7030. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  7031. }
  7032. // elseif ($prompt) {
  7033. // $uploaded_content = filterContent($prompt);
  7034. // }
  7035. else {
  7036. $uploaded_content = '';
  7037. }
  7038. $input_art_style = getProp($anime, 'art_style');
  7039. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7040. // 美术风格
  7041. if (!$mappedArtStyle) {
  7042. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7043. }else {
  7044. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7045. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7046. }else {
  7047. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7048. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7049. }
  7050. }
  7051. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7052. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7053. // 强制要求:
  7054. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7055. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7056. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7057. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  7058. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  7059. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  7060. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  7061. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  7062. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  7063. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  7064. // - 分镜要和场景列表、人物主体保持一致\n
  7065. // 普通要求:
  7066. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7067. // {$role_demo}
  7068. // {$scene_demo}
  7069. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  7070. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  7071. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  7072. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  7073. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  7074. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  7075. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  7076. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  7077. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  7078. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  7079. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  7080. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  7081. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  7082. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  7083. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  7084. // 5.$mappedArtStyle_prompt\n\n
  7085. // 示例格式:\n
  7086. // 第1集:隐形的守护者
  7087. // ###故事梗概
  7088. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7089. // ###美术风格
  7090. // 基础画风风格词:韩漫二次元
  7091. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  7092. // ###主体列表
  7093. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  7094. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  7095. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  7096. // ###场景列表
  7097. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  7098. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7099. // 无人物。}
  7100. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  7101. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  7102. // 无人物。}
  7103. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  7104. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  7105. // 无人物。}
  7106. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  7107. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  7108. // 无人物。}
  7109. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  7110. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  7111. // 无人物。}
  7112. // ###分镜剧本
  7113. // ##第1幕:徐家老旧厨房 白天 室内
  7114. // 分镜1
  7115. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  7116. // 场景:徐家老旧厨房
  7117. // 构图设计:全景,低角度仰视
  7118. // 运镜调度:手持拍摄
  7119. // 配音角色:旁白
  7120. // 出镜角色:许芸-校服装、徐母
  7121. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  7122. // 画面类型:普通画面
  7123. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  7124. // 分镜2
  7125. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  7126. // 场景:徐家老旧厨房
  7127. // 构图设计:近景,徐母面部特写
  7128. // 运镜调度:固定镜头
  7129. // 配音角色:徐母
  7130. // 出镜角色:徐母
  7131. // 台词内容:问我夜不归宿死哪儿去了。
  7132. // 画面类型:对口型
  7133. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  7134. // ##第2幕:徐家简陋客厅 黄昏 室内
  7135. // 分镜3
  7136. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  7137. // 场景:徐家简陋客厅
  7138. // 构图设计:全景,景深虚化
  7139. // 运镜调度:固定镜头
  7140. // 配音角色:旁白
  7141. // 出镜角色:无
  7142. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  7143. // 画面类型:普通画面
  7144. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  7145. // 分镜4
  7146. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  7147. // 场景:徐家简陋客厅
  7148. // 构图设计:特写,火车票
  7149. // 运镜调度:固定镜头
  7150. // 配音角色:旁白
  7151. // 出镜角色:无
  7152. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  7153. // 画面类型:普通画面
  7154. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  7155. // \n\n";
  7156. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7157. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7158. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  7159. 普通要求:
  7160. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7161. {$role_demo}
  7162. {$scene_demo}
  7163. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  7164. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  7165. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  7166. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7167. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  7168. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  7169. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  7170. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  7171. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  7172. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  7173. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  7174. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  7175. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  7176. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  7177. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  7178. 5.$mappedArtStyle_prompt
  7179. 6.《情绪-视听语言映射表》:
  7180. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7181. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7182. -----|---------|------------|----------------
  7183. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7184. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7185. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7186. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7187. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7188. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7189. -----|---------|------------|----------------
  7190. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7191. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7192. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7193. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7194. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7195. --------|---------|--------------|-------------
  7196. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7197. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7198. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7199. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7200. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7201. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7202. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7203. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7204. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7205. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7206. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7207. -----|---------|------------|------------
  7208. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7209. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7210. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7211. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7212. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7213. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7214. --------|---------|--------------|----------
  7215. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7216. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7217. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7218. 6.6 声音设计与潜意识影响 (Soundscape)
  7219. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7220. -----|---------|------------|------------------
  7221. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7222. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7223. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7224. 理论基石:
  7225. - The Five C's of Cinematography by Joseph V. Mascelli
  7226. - Film Art: An Introduction by David Bordwell
  7227. - Sight, Sound, Motion by Herbert Zettl
  7228. - Notes on the Cinematograph by Robert Bresson
  7229. \n\n
  7230. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  7231. 示例格式:\n
  7232. 第1集:隐形的守护者
  7233. ###故事梗概
  7234. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7235. ###美术风格
  7236. 基础画风风格词:韩漫二次元
  7237. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  7238. ###主体列表
  7239. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  7240. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  7241. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  7242. ###场景列表
  7243. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  7244. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7245. 无人物。}
  7246. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  7247. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  7248. 无人物。}
  7249. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  7250. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  7251. 无人物。}
  7252. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  7253. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  7254. 无人物。}
  7255. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  7256. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  7257. 无人物。}
  7258. ###分镜剧本
  7259. ##第1幕:徐家老旧厨房 白天 室内
  7260. 分镜1
  7261. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  7262. 场景:徐家老旧厨房
  7263. 构图设计:全景,低角度仰视
  7264. 运镜调度:手持拍摄
  7265. 配音角色:旁白
  7266. 出镜角色:许芸-校服装、徐母
  7267. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  7268. 画面类型:普通画面
  7269. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  7270. 分镜2
  7271. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  7272. 场景:徐家老旧厨房
  7273. 构图设计:近景,徐母面部特写
  7274. 运镜调度:固定镜头
  7275. 配音角色:徐母
  7276. 出镜角色:徐母
  7277. 台词内容:问我夜不归宿死哪儿去了。
  7278. 画面类型:对口型
  7279. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  7280. ##第2幕:徐家简陋客厅 黄昏 室内
  7281. 分镜3
  7282. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  7283. 场景:徐家简陋客厅
  7284. 构图设计:全景,景深虚化
  7285. 运镜调度:固定镜头
  7286. 配音角色:旁白
  7287. 出镜角色:无
  7288. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  7289. 画面类型:普通画面
  7290. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  7291. 分镜4
  7292. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  7293. 场景:徐家简陋客厅
  7294. 构图设计:特写,火车票
  7295. 运镜调度:固定镜头
  7296. 配音角色:旁白
  7297. 出镜角色:无
  7298. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  7299. 画面类型:普通画面
  7300. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  7301. \n\n";
  7302. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7303. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  7304. $is_regenerate_version = true;
  7305. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7306. $prompt = $origin_prompt;
  7307. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7308. // 获取章节内容
  7309. $full_content = getProp($anime, 'content');
  7310. if ($uploaded_content) {
  7311. $full_content = $uploaded_content;
  7312. }
  7313. // 根据章节内容拆分章节
  7314. $chapters = splitContent($full_content);
  7315. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7316. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7317. $messages = [];
  7318. if ($prompt == '确认分镜大纲') {
  7319. // 暂时保留
  7320. $content = $chapter_content;
  7321. if ($is_single) $content = $full_content; // 单剧集使用全文
  7322. if (!$content) {
  7323. Utils::throwError('20003:章节内容无法获取,请确认');
  7324. }
  7325. $question = $is_single
  7326. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7327. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7328. // 构建消息
  7329. $messages[] =
  7330. [
  7331. 'role' => 'user',
  7332. 'content' => $question
  7333. ];
  7334. }else if ($prompt == '继续策划下一集') {
  7335. if ($is_single) {
  7336. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7337. }
  7338. $content = $chapter_content;
  7339. if (!$content) {
  7340. Utils::throwError('20003:章节内容无法获取,请确认');
  7341. }
  7342. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7343. // 获取上一集最后记录
  7344. $prev_sequence = $episode_number - 1;
  7345. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7346. // 构建消息
  7347. $messages[] =
  7348. [
  7349. 'role' => 'user',
  7350. 'content' => $question
  7351. ];
  7352. }else {
  7353. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7354. if (!$content) {
  7355. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7356. }
  7357. if (!$content) {
  7358. Utils::throwError('20003:章节内容无法获取,请确认');
  7359. }
  7360. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7361. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7362. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7363. if ($origin_prompt) {
  7364. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  7365. }
  7366. $messages[] =
  7367. [
  7368. 'role' => 'user',
  7369. 'content' => $question
  7370. ];
  7371. }
  7372. // 处理文本模型
  7373. $model = getProp($data, 'model');
  7374. if (!$model) {
  7375. // 用户没有输入,从anime表获取
  7376. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7377. $model = getProp($anime, 'model');
  7378. if (!$model) {
  7379. // anime表也没有,使用默认值
  7380. $model = 'doubao-seed-2-0-mini-260215';
  7381. }
  7382. }
  7383. // 验证模型是否在可用模型表中
  7384. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7385. $model = 'doubao-seed-2-0-mini-260215';
  7386. }
  7387. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7388. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7389. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7390. if ($model === 'deepseek-chat') {
  7391. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7392. $model = 'deepseek-v4-flash';
  7393. $thinkingMode = 'disabled';
  7394. } elseif ($model === 'deepseek-reasoner') {
  7395. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7396. $model = 'deepseek-v4-flash';
  7397. $thinkingMode = 'enabled';
  7398. }
  7399. $post_data = [
  7400. 'model' => $model,
  7401. 'messages' => $messages,
  7402. // 'max_tokens' => 8192,
  7403. 'temperature' => 0.2,
  7404. 'frequency_penalty' => 0,
  7405. 'presence_penalty' => 0,
  7406. 'response_format' => ['type' => 'text'],
  7407. 'thinking' => ['type' => $thinkingMode],
  7408. 'stream' => true // 启用流式输出
  7409. ];
  7410. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7411. // 根据模型类型选择调用方法
  7412. $fullContent = '';
  7413. $fullReasoningContent = '';
  7414. $usage = [];
  7415. try {
  7416. $streamGenerator = $this->dispatchStreamByModel($post_data);
  7417. // 验证返回值类型
  7418. if (!is_iterable($streamGenerator)) {
  7419. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7420. dLog('deepseek')->error('chat流式生成器无效', [
  7421. 'generator_type' => $errorType,
  7422. 'model' => $model,
  7423. 'anime_id' => $anime_id,
  7424. 'episode_number' => $episode_number
  7425. ]);
  7426. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7427. 'type' => $errorType,
  7428. 'model' => $model
  7429. ]);
  7430. yield [
  7431. 'type' => 'error',
  7432. 'episode' => [],
  7433. 'answer' => '',
  7434. 'reasoning' => '',
  7435. 'usage' => [],
  7436. 'error' => '接口返回数据异常,请重新请求'
  7437. ];
  7438. return;
  7439. }
  7440. // 处理流式输出
  7441. foreach ($streamGenerator as $chunk) {
  7442. if (isset($chunk['type'])) {
  7443. if ($chunk['type'] === 'done') {
  7444. // 最终结果
  7445. $fullContent = $chunk['full_content'];
  7446. $fullReasoningContent = $chunk['full_reasoning'];
  7447. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7448. } else {
  7449. // 逐块yield数据
  7450. yield $chunk;
  7451. }
  7452. }
  7453. }
  7454. } catch (\Exception $e) {
  7455. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7456. 'model' => $model,
  7457. 'anime_id' => $anime_id,
  7458. 'episode_number' => $episode_number,
  7459. 'trace' => $e->getTraceAsString()
  7460. ]);
  7461. logDB('deepseek', 'error', 'chat流式处理失败', [
  7462. 'error' => $e->getMessage(),
  7463. 'model' => $model
  7464. ]);
  7465. yield [
  7466. 'type' => 'error',
  7467. 'episode' => [],
  7468. 'answer' => '',
  7469. 'reasoning' => '',
  7470. 'usage' => [],
  7471. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7472. ];
  7473. return;
  7474. }
  7475. dLog('deepseek')->info('完整内容: '.$fullContent);
  7476. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7477. // 处理完整内容并返回最终结果
  7478. $episode_arr = handleEpisodeContent($fullContent);
  7479. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7480. if (empty($episode_arr['acts'])) {
  7481. // 未生成剧本相关内容,保存对话记录并返回提示
  7482. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  7483. try {
  7484. $now = date('Y-m-d H:i:s');
  7485. // 保存对话记录
  7486. $records = [
  7487. [
  7488. 'uid' => $uid,
  7489. 'anime_id' => $anime_id,
  7490. 'sequence' => $episode_number,
  7491. 'role' => 'user',
  7492. 'content' => $prompt,
  7493. 'created_at' => $now,
  7494. 'updated_at' => $now
  7495. ],
  7496. [
  7497. 'uid' => $uid,
  7498. 'anime_id' => $anime_id,
  7499. 'sequence' => $episode_number,
  7500. 'role' => 'assistant',
  7501. 'content' => $fullContent,
  7502. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7503. 'created_at' => $now,
  7504. 'updated_at' => $now
  7505. ]
  7506. ];
  7507. DB::table('mp_anime_records')->insert($records);
  7508. } catch (\Exception $e) {
  7509. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7510. }
  7511. yield [
  7512. 'type' => 'done',
  7513. 'episode' => [],
  7514. 'answer' => $fullContent,
  7515. 'reasoning' => $fullReasoningContent,
  7516. 'usage' => $usage,
  7517. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  7518. ];
  7519. return;
  7520. }
  7521. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  7522. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  7523. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  7524. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  7525. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  7526. $existing_props = is_array($existing_props) ? $existing_props : [];
  7527. $now = date('Y-m-d H:i:s');
  7528. try {
  7529. DB::beginTransaction();
  7530. $saveResult = $this->saveEpisodeVersionData(
  7531. $anime_id,
  7532. $episode_number,
  7533. $episode_arr,
  7534. $existing_roles,
  7535. $existing_scenes,
  7536. $existing_props,
  7537. $current_episode,
  7538. $base_episode,
  7539. $is_regenerate_version,
  7540. $content,
  7541. $now
  7542. );
  7543. $episode = $saveResult['episode'];
  7544. $episode_id = $saveResult['episode_id'];
  7545. $merged_roles = $saveResult['merged_roles'];
  7546. $merged_scenes = $saveResult['merged_scenes'];
  7547. $merged_props = $saveResult['merged_props'];
  7548. $record_content = $origin_prompt;
  7549. if ($uploaded_content !== '') {
  7550. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  7551. }
  7552. $records = [
  7553. [
  7554. 'uid' => $uid,
  7555. 'anime_id' => $anime_id,
  7556. 'role' => 'user',
  7557. 'content' => $record_content,
  7558. 'sequence' => $episode_number,
  7559. 'episode_id' => $episode_id,
  7560. 'created_at' => $now,
  7561. 'updated_at' => $now
  7562. ],
  7563. [
  7564. 'uid' => $uid,
  7565. 'anime_id' => $anime_id,
  7566. 'role' => 'assistant',
  7567. 'content' => $fullContent,
  7568. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7569. 'sequence' => $episode_number,
  7570. 'episode_id' => $episode_id,
  7571. 'created_at' => $now,
  7572. 'updated_at' => $now
  7573. ]
  7574. ];
  7575. $boolen4 = DB::table('mp_anime_records')->insert($records);
  7576. if (!$boolen4) {
  7577. Utils::throwError('20003:对话记录保存失败');
  7578. }
  7579. // 保存模型和内容到anime表
  7580. $update_anime_data = [
  7581. 'model' => $model,
  7582. 'updated_at' => $now
  7583. ];
  7584. if ($uploaded_content) {
  7585. $update_anime_data['content'] = $uploaded_content;
  7586. }
  7587. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  7588. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7589. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7590. 'anime_id' => $anime_id,
  7591. 'episode_number' => $episode_number,
  7592. 'model' => $model,
  7593. 'source' => 'chat',
  7594. ]);
  7595. }catch (\Exception $e) {
  7596. DB::rollBack();
  7597. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7598. yield [
  7599. 'type' => 'done',
  7600. 'answer' => $fullContent,
  7601. 'reasoning' => $fullReasoningContent,
  7602. 'usage' => $usage,
  7603. 'error' => $e->getMessage(),
  7604. ];
  7605. return;
  7606. }
  7607. DB::commit();
  7608. if ($is_global_generate_pics) {
  7609. // // 批量生成全局角色图片
  7610. // $this->batchSetGlobalRoleImg([
  7611. // 'anime_id' => $anime_id,
  7612. // ], true);
  7613. // // 批量生成全局场景图片
  7614. // $this->batchSetGlobalSceneImg([
  7615. // 'anime_id' => $anime_id,
  7616. // ], true);
  7617. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7618. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7619. }
  7620. $episode['episode_id'] = $episode_id;
  7621. $episode['roles'] = $merged_roles;
  7622. $episode['scenes'] = $merged_scenes;
  7623. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  7624. yield [
  7625. 'type' => 'done',
  7626. 'episode' => $episode,
  7627. 'answer' => $fullContent,
  7628. 'reasoning' => $fullReasoningContent,
  7629. 'usage' => $usage
  7630. ];
  7631. }
  7632. public function addChatForAce($data) {
  7633. $uid = Site::getUid();
  7634. $anime_id = getProp($data, 'anime_id');
  7635. if (!$anime_id) Utils::throwError('20003:请选择对话');
  7636. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  7637. if (!$anime) Utils::throwError('20003:对话不存在');
  7638. $file = getProp($data, 'file');
  7639. $content = getProp($data, 'content', '');
  7640. $bid = getProp($data, 'bid', 0);
  7641. $script_id = getProp($data, 'script_id', 0);
  7642. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  7643. $prompt = getProp($data, 'prompt');
  7644. $is_multi = getProp($anime, 'is_multi');
  7645. $is_single = (int)$is_multi !== 1;
  7646. // 积分余额预检(仅单剧集模式收费)
  7647. if ($is_single) {
  7648. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  7649. }
  7650. $extra_products = getProp($data, 'products', []);
  7651. if (!$extra_products) {
  7652. $extra_products = getProp($anime, 'extra_products');
  7653. if ($extra_products) {
  7654. $extra_products = json_decode($extra_products, true);
  7655. }else {
  7656. $extra_products = [];
  7657. }
  7658. }else {
  7659. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7660. }
  7661. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7662. $anime_script_id = getProp($anime, 'script_id');
  7663. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  7664. $cpid = Site::getCpid();
  7665. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7666. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7667. ->where('mapping.script_id', $anime_script_id)
  7668. ->where('product.cpid', $cpid)
  7669. ->where('product.is_deleted', 0);
  7670. $mappings = $script_products_mappings->select(
  7671. 'mapping.product_id',
  7672. 'mapping.episode_number',
  7673. 'product.product_name',
  7674. 'product.type',
  7675. 'product.product',
  7676. 'product.pic_prompt',
  7677. 'product.url',
  7678. 'product.pic_task_id',
  7679. 'product.pic_task_status',
  7680. 'product.three_view_image_url'
  7681. )
  7682. ->get();
  7683. // 按 product_id 分组,合并 episode_number
  7684. $productMap = [];
  7685. foreach ($mappings as $item) {
  7686. $product_id = $item->product_id;
  7687. $product_name = $item->product_name;
  7688. // 处理product_name两边的符号
  7689. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7690. if (!isset($productMap[$product_id])) {
  7691. $productMap[$product_id] = [
  7692. 'product_id' => $product_id,
  7693. 'product_name' => $product_name,
  7694. 'type' => (int)$item->type,
  7695. 'product' => (int)$item->product,
  7696. 'pic_prompt' => $item->pic_prompt,
  7697. 'url' => $item->url,
  7698. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7699. 'pic_task_id' => $item->pic_task_id,
  7700. 'pic_task_status' => $item->pic_task_status,
  7701. 'episode_numbers' => [],
  7702. ];
  7703. }
  7704. // 添加 episode_number(去重)
  7705. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7706. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7707. }
  7708. }
  7709. // 将查询到的剧本资产合并到extra_products中
  7710. // 先构建extra_products的索引(以product_id为key,用于去重)
  7711. $extraProductsMap = [];
  7712. foreach ($extra_products as $item) {
  7713. $key = getProp($item, 'product_id');
  7714. if ($key) {
  7715. $extraProductsMap[$key] = $item;
  7716. }
  7717. }
  7718. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7719. foreach ($productMap as $product) {
  7720. $product_id = $product['product_id'];
  7721. // 如果不存在则添加(不带episode_number信息)
  7722. if (!isset($extraProductsMap[$product_id])) {
  7723. $extraProductsMap[$product_id] = [
  7724. 'product_id' => $product['product_id'],
  7725. 'product_name' => $product['product_name'],
  7726. 'type' => $product['type'],
  7727. 'product' => $product['product'],
  7728. 'pic_prompt' => $product['pic_prompt'],
  7729. 'url' => $product['url'],
  7730. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  7731. 'pic_task_id' => $product['pic_task_id'],
  7732. 'pic_task_status' => $product['pic_task_status'],
  7733. ];
  7734. }
  7735. }
  7736. // 重新赋值给extra_products
  7737. $extra_products = array_values($extraProductsMap);
  7738. }
  7739. $user_anime_name = getProp($anime, 'anime_name');
  7740. // 处理提示词
  7741. if ($prompt && $extra_products) {
  7742. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7743. foreach($extra_products as $item) {
  7744. $product_name = getProp($item, 'product_name');
  7745. if ($product_name) {
  7746. // 替换 {product_name} 为 product_name
  7747. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7748. }
  7749. }
  7750. }
  7751. // 处理文本模型
  7752. $model = getProp($data, 'model');
  7753. if (!$model) {
  7754. // 用户没有输入,从anime表获取
  7755. $model = getProp($anime, 'model');
  7756. if (!$model) {
  7757. // anime表也没有,使用默认值
  7758. $model = 'deepseek-v4-pro';
  7759. }
  7760. }
  7761. // 验证模型是否在可用模型表中
  7762. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7763. $model = 'deepseek-v4-pro';
  7764. }
  7765. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7766. if ($prompt) {
  7767. $question .= "本次修改要求如下:\n{$prompt}";
  7768. }
  7769. // if (!$file && !$content && !$bid) {
  7770. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  7771. // }
  7772. // 提取文件内容
  7773. if ($file) {
  7774. $content = $this->extractFileContent($file);
  7775. if (!$content) {
  7776. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7777. }
  7778. } elseif ($script_id) {
  7779. $content = $this->getContentByScriptId($script_id);
  7780. if (!$content) {
  7781. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7782. }
  7783. } elseif ($bid) {
  7784. $content = $this->getContentByBid($bid);
  7785. if (!$content) {
  7786. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7787. }
  7788. } elseif ($content) {
  7789. $content = filterContent($content);
  7790. } else {
  7791. $content = getProp($anime, 'content');
  7792. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7793. $need_generate_content = true;
  7794. }
  7795. }
  7796. // 美术风格
  7797. $input_art_style = getProp($data, 'art_style');
  7798. if (!$input_art_style) {
  7799. $mappedArtStyle = getProp($anime, 'art_style');
  7800. }else {
  7801. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7802. }
  7803. // 判断是否需要生成原文内容
  7804. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7805. // 如果需要生成原文内容,添加额外的要求
  7806. $content_generation_requirement = $need_generate_content
  7807. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7808. : "";
  7809. // 美术风格
  7810. if (!$mappedArtStyle) {
  7811. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7812. }else {
  7813. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7814. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7815. }else {
  7816. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7817. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7818. }
  7819. }
  7820. // 构建主体、场景和道具提示词
  7821. $extra_role_prompt = "\n";
  7822. $extra_scene_prompt = "\n";
  7823. $extra_prop_prompt = "\n";
  7824. $extra_roles = [];
  7825. $extra_scenes = [];
  7826. $extra_props = [];
  7827. $ref_products = []; // 参考资产
  7828. if ($extra_products) {
  7829. foreach($extra_products as $item) {
  7830. $product = getProp($item, 'product');
  7831. $product_name = getProp($item, 'product_name');
  7832. if ($product_name == '旁白') continue;
  7833. $ref_products[$product_name] = $item;
  7834. $pic_prompt = getProp($item, 'pic_prompt');
  7835. if ((int)$product === 1) {
  7836. // 拼接角色信息
  7837. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7838. $extra_roles[$product_name] = [
  7839. 'role' => $product_name,
  7840. 'pic_prompt' => $pic_prompt,
  7841. 'url' => getProp($item, 'url', ''),
  7842. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7843. ];
  7844. } elseif ((int)$product === 2) {
  7845. // 拼接场景信息
  7846. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7847. $extra_scenes[$product_name] = [
  7848. 'scene' => $product_name,
  7849. 'pic_prompt' => $pic_prompt,
  7850. 'url' => getProp($item, 'url', ''),
  7851. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7852. ];
  7853. } elseif ((int)$product === 3) {
  7854. // 拼接道具信息
  7855. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7856. $extra_props[$product_name] = [
  7857. 'prop' => $product_name,
  7858. 'pic_prompt' => $pic_prompt,
  7859. 'url' => getProp($item, 'url', ''),
  7860. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  7861. ];
  7862. }
  7863. }
  7864. // 优化提示词,融入剧本
  7865. if (!empty(trim($extra_role_prompt))) {
  7866. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7867. }
  7868. if (!empty(trim($extra_scene_prompt))) {
  7869. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7870. }
  7871. if (!empty(trim($extra_prop_prompt))) {
  7872. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7873. }
  7874. }
  7875. if ($anime_script_id && $is_single) {
  7876. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7877. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7878. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7879. }else {
  7880. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7881. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7882. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7883. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7884. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7885. {$extra_role_prompt}";
  7886. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7887. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7888. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7889. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7890. {$extra_scene_prompt}";
  7891. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7892. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7893. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7894. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7895. {$extra_prop_prompt}";
  7896. }
  7897. $systemPrompt = $is_single
  7898. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7899. 强制要求:
  7900. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7901. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7902. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7903. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7904. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7905. 普通要求:
  7906. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7907. $role_demo
  7908. $scene_demo
  7909. $prop_demo
  7910. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7911. 5.1片段分割逻辑(优先级从高到低):
  7912. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7913. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7914. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7915. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7916. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7917. - 片段数量格式为: 片段数量:8
  7918. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7919. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7920. 5.3分镜结构:每个分镜包含以下字段:
  7921. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  7922. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7923. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7924. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7925. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7926. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7927. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7928. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7929. - 运镜:场景+画面描述+运镜
  7930. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7931. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7932. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7933. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7934. 6.《情绪-视听语言映射表》:
  7935. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7936. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7937. -----|---------|------------|----------------
  7938. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7939. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7940. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7941. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7942. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7943. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7944. -----|---------|------------|----------------
  7945. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7946. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7947. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7948. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7949. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7950. --------|---------|--------------|-------------
  7951. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7952. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7953. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7954. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7955. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7956. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7957. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7958. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7959. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7960. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7961. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7962. -----|---------|------------|------------
  7963. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7964. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7965. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7966. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7967. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7968. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7969. --------|---------|--------------|----------
  7970. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7971. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7972. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7973. 6.6 声音设计与潜意识影响 (Soundscape)
  7974. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7975. -----|---------|------------|------------------
  7976. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7977. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7978. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7979. 理论基石:
  7980. - The Five C's of Cinematography by Joseph V. Mascelli
  7981. - Film Art: An Introduction by David Bordwell
  7982. - Sight, Sound, Motion by Herbert Zettl
  7983. - Notes on the Cinematograph by Robert Bresson
  7984. \n\n
  7985. 7.{$mappedArtStyle_prompt}\n\n
  7986. 示例如下:\n
  7987. ###剧本名:西昆仑
  7988. ###故事梗概
  7989. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7990. ###剧本亮点
  7991. 亮点1:绝境奇药,生死一线
  7992. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7993. 亮点2:结拜兄妹,化解尴尬
  7994. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7995. 亮点3:纤发夺命,情愫暗涌
  7996. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7997. ###人物关系
  7998. 阿雪与梁萧之间存在兄妹之情。
  7999. ###核心矛盾
  8000. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8001. ###主体列表
  8002. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8003. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8004. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8005. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8006. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8007. 全景,正面拍摄,青年女性,亚洲人。
  8008. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8009. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8010. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8011. ###美术风格
  8012. 基础画风风格词:厚涂古风
  8013. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8014. ###场景列表
  8015. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8016. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8017. 无人物。}
  8018. ###分段剧本
  8019. 片段数量:8
  8020. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8021. ##片段1
  8022. 时长:12s
  8023. 分镜1
  8024. 出场角色:刀疤脸
  8025. 场景:边境小镇街道
  8026. 出场道具:酒杯-高脚杯
  8027. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8028. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8029. 配音台词:
  8030. 背景音效:
  8031. 分镜2
  8032. 出场角色:刀疤脸
  8033. 场景:悦来酒馆
  8034. 出场道具:酒杯-高脚杯
  8035. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8036. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8037. 配音台词:
  8038. 背景音效:
  8039. 分镜3
  8040. 出场角色:刀疤脸
  8041. 场景:悦来酒馆
  8042. 出场道具:酒杯-高脚杯
  8043. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8044. 运镜:从中景推向令牌特写。
  8045. 配音台词:
  8046. 背景音效:
  8047. 分镜4
  8048. 出场角色:刀疤脸
  8049. 场景:悦来酒馆
  8050. 出场道具:酒杯-高脚杯
  8051. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8052. 运镜:极速推向酒水溅起的瞬间。
  8053. 配音台词:
  8054. 背景音效:
  8055. 分镜5
  8056. 出场角色:刀疤脸
  8057. 场景:悦来酒馆
  8058. 出场道具:酒杯-高脚杯
  8059. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8060. 运镜:固定机位,利用倾斜构图制造压迫感。
  8061. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8062. 背景音效:
  8063. \n\n"
  8064. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8065. 强制要求:\n
  8066. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8067. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8068. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8069. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8070. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8071. 普通要求:\n
  8072. 1.剧本名(必须生成)必须与文档内容高度相关
  8073. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8074. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8075. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8076. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8077. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8078. {$extra_role_prompt}
  8079. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8080. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  8081. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8082. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8083. {$extra_scene_prompt}
  8084. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8085. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  8086. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8087. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  8088. {$extra_prop_prompt}
  8089. 5.{$mappedArtStyle_prompt}\n\n
  8090. 示例如下:\n
  8091. ###剧本名:西昆仑
  8092. ###故事梗概
  8093. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8094. ###剧本亮点
  8095. 亮点1:绝境奇药,生死一线
  8096. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8097. 亮点2:结拜兄妹,化解尴尬
  8098. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8099. 亮点3:纤发夺命,情愫暗涌
  8100. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8101. ###人物关系
  8102. 阿雪与梁萧之间存在兄妹之情。
  8103. ###核心矛盾
  8104. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8105. ###主体列表
  8106. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8107. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8108. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8109. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8110. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8111. 全景,正面拍摄,青年女性,亚洲人。
  8112. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8113. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8114. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8115. ###美术风格
  8116. 基础画风风格词:厚涂古风
  8117. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8118. ###场景列表
  8119. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8120. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8121. 无人物。}
  8122. ###道具列表
  8123. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  8124. // 构建消息
  8125. $messages = [
  8126. [
  8127. 'role' => 'system',
  8128. 'content' => $systemPrompt
  8129. ],
  8130. [
  8131. 'role' => 'user',
  8132. 'content' => "以下是文档内容:
  8133. {$content}
  8134. 用户问题:
  8135. {$question}"
  8136. ]
  8137. ];
  8138. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8139. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  8140. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8141. if ($model === 'deepseek-chat') {
  8142. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8143. $model = 'deepseek-v4-flash';
  8144. $thinkingMode = 'disabled';
  8145. } elseif ($model === 'deepseek-reasoner') {
  8146. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8147. $model = 'deepseek-v4-flash';
  8148. $thinkingMode = 'enabled';
  8149. }
  8150. $post_data = [
  8151. 'model' => $model,
  8152. 'messages' => $messages,
  8153. // 'max_tokens' => 8192,
  8154. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8155. 'frequency_penalty' => 0,
  8156. 'presence_penalty' => 0,
  8157. 'response_format' => ['type' => 'text'],
  8158. 'thinking' => ['type'=>$thinkingMode],
  8159. 'stream' => true // 启用流式输出
  8160. ];
  8161. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8162. // 根据模型类型选择调用方法
  8163. $fullContent = '';
  8164. $fullReasoningContent = '';
  8165. $usage = [];
  8166. try {
  8167. $streamGenerator = $this->dispatchStreamByModel($post_data);
  8168. // 验证返回值类型
  8169. if (!is_iterable($streamGenerator)) {
  8170. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8171. dLog('deepseek')->error('addChat流式生成器无效', [
  8172. 'generator_type' => $errorType,
  8173. 'model' => $model,
  8174. 'anime_id' => $anime_id
  8175. ]);
  8176. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  8177. 'type' => $errorType,
  8178. 'model' => $model
  8179. ]);
  8180. yield [
  8181. 'type' => 'error',
  8182. 'script' => [],
  8183. 'episode' => [],
  8184. 'answer' => '',
  8185. 'reasoning' => '',
  8186. 'usage' => [],
  8187. 'error' => '接口返回数据异常,请重新请求'
  8188. ];
  8189. return;
  8190. }
  8191. // 处理流式输出
  8192. foreach ($streamGenerator as $chunk) {
  8193. if (isset($chunk['type'])) {
  8194. if ($chunk['type'] === 'done') {
  8195. // 最终结果
  8196. $fullContent = $chunk['full_content'];
  8197. $fullReasoningContent = $chunk['full_reasoning'];
  8198. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8199. } else {
  8200. // 逐块yield数据
  8201. yield $chunk;
  8202. }
  8203. }
  8204. }
  8205. } catch (\Exception $e) {
  8206. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  8207. 'model' => $model,
  8208. 'anime_id' => $anime_id,
  8209. 'trace' => $e->getTraceAsString()
  8210. ]);
  8211. logDB('deepseek', 'error', 'addChat流式处理失败', [
  8212. 'error' => $e->getMessage(),
  8213. 'model' => $model
  8214. ]);
  8215. yield [
  8216. 'type' => 'error',
  8217. 'script' => [],
  8218. 'episode' => [],
  8219. 'answer' => '',
  8220. 'reasoning' => '',
  8221. 'usage' => [],
  8222. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8223. ];
  8224. return;
  8225. }
  8226. dLog('deepseek')->info('完整内容: '.$fullContent);
  8227. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8228. // 处理完整内容并返回最终结果
  8229. $script_arr = [];
  8230. if ($fullContent) {
  8231. $script_arr = handleScriptContentForAce($fullContent);
  8232. dLog('deepseek')->info('解析内容', $script_arr);
  8233. logDB('deepseek', 'info', '解析内容', $script_arr);
  8234. }
  8235. if (empty($script_arr['roles'])) {
  8236. // 未生成剧本相关内容,保存对话记录并返回提示
  8237. dLog('deepseek')->info('未生成剧本相关的内容');
  8238. try {
  8239. DB::beginTransaction();
  8240. $now = date('Y-m-d H:i:s');
  8241. // 保存对话记录
  8242. $records = [
  8243. [
  8244. 'uid' => $uid,
  8245. 'anime_id' => $anime_id,
  8246. 'sequence' => 0,
  8247. 'role' => 'user',
  8248. 'content' => $prompt,
  8249. 'created_at' => $now,
  8250. 'updated_at' => $now
  8251. ],
  8252. [
  8253. 'uid' => $uid,
  8254. 'anime_id' => $anime_id,
  8255. 'sequence' => 0,
  8256. 'role' => 'assistant',
  8257. // 'content' => $fullContent,
  8258. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  8259. 'created_at' => $now,
  8260. 'updated_at' => $now
  8261. ]
  8262. ];
  8263. DB::table('mp_anime_records')->insert($records);
  8264. DB::commit();
  8265. } catch (\Exception $e) {
  8266. DB::rollBack();
  8267. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8268. }
  8269. yield [
  8270. 'type' => 'done',
  8271. 'script' => [],
  8272. 'episode' => [],
  8273. 'answer' => $fullContent,
  8274. 'reasoning' => $fullReasoningContent,
  8275. 'usage' => $usage,
  8276. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  8277. ];
  8278. return;
  8279. }
  8280. // 如果需要生成原文内容,从script_arr中提取
  8281. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  8282. $content = $script_arr['content'];
  8283. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  8284. if (!$content) {
  8285. yield [
  8286. 'type' => 'done',
  8287. 'script' => [],
  8288. 'episode' => [],
  8289. 'answer' => $fullContent,
  8290. 'reasoning' => $fullReasoningContent,
  8291. 'usage' => $usage,
  8292. 'error' => '未生成剧本内容,请调整提示词再试'
  8293. ];
  8294. return;
  8295. }
  8296. }
  8297. // 替换美术风格
  8298. if ($mappedArtStyle !== '') {
  8299. $script_arr['art_style'] = $mappedArtStyle;
  8300. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8301. }
  8302. // 新建动漫
  8303. if ($user_anime_name == '新剧本策划') {
  8304. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  8305. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  8306. // if (!$anime_name) {
  8307. // // 未识别到剧本名,保存对话记录并返回提示
  8308. // dLog('deepseek')->info('未能识别到剧本名称');
  8309. // try {
  8310. // DB::beginTransaction();
  8311. // $now = date('Y-m-d H:i:s');
  8312. // // 保存对话记录
  8313. // $records = [
  8314. // [
  8315. // 'uid' => $uid,
  8316. // 'anime_id' => $anime_id,
  8317. // 'sequence' => 0,
  8318. // 'role' => 'user',
  8319. // 'content' => $prompt,
  8320. // 'created_at' => $now,
  8321. // 'updated_at' => $now
  8322. // ],
  8323. // [
  8324. // 'uid' => $uid,
  8325. // 'anime_id' => $anime_id,
  8326. // 'sequence' => 0,
  8327. // 'role' => 'assistant',
  8328. // 'content' => '未能生成剧本名称,请重试',
  8329. // 'created_at' => $now,
  8330. // 'updated_at' => $now
  8331. // ]
  8332. // ];
  8333. // DB::table('mp_anime_records')->insert($records);
  8334. // DB::commit();
  8335. // } catch (\Exception $e) {
  8336. // DB::rollBack();
  8337. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8338. // }
  8339. // yield [
  8340. // 'type' => 'done',
  8341. // 'script' => [],
  8342. // 'episode' => [],
  8343. // 'answer' => $fullContent,
  8344. // 'reasoning' => $fullReasoningContent,
  8345. // 'usage' => $usage,
  8346. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  8347. // ];
  8348. // return;
  8349. // }
  8350. // 确认对话名称唯一性
  8351. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  8352. $anime_name = $anime_name . '_' . date('YmdHis');
  8353. }
  8354. }else {
  8355. $anime_name = $user_anime_name;
  8356. }
  8357. // 单剧集模式:按 chatForAce 逻辑校验并重试生成剧集与分段剧本
  8358. if ($is_single) {
  8359. $max_retries = 3;
  8360. $retry_count = 0;
  8361. $validation_failed = false;
  8362. $validation_error_msg = '';
  8363. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8364. // 首次校验
  8365. if ($anime_script_id) {
  8366. if (empty($episode_arr['acts'])) {
  8367. $validation_failed = true;
  8368. $validation_error_msg = '未生成分镜剧本相关的内容';
  8369. } else {
  8370. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8371. $generated_roles = array_filter($generated_roles, function($role) {
  8372. return $role !== '旁白';
  8373. });
  8374. if (empty($generated_roles)) {
  8375. $validation_failed = true;
  8376. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8377. }
  8378. if (!$validation_failed && !empty($extra_roles)) {
  8379. $expected_roles = array_keys($extra_roles);
  8380. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8381. if (!empty($invalid_roles)) {
  8382. $validation_failed = true;
  8383. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8384. }
  8385. }
  8386. if (!$validation_failed && !empty($extra_scenes)) {
  8387. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  8388. $expected_scenes = array_keys($extra_scenes);
  8389. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8390. if (!empty($invalid_scenes)) {
  8391. $validation_failed = true;
  8392. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8393. }
  8394. }
  8395. if (!$validation_failed && !empty($extra_props)) {
  8396. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8397. $expected_props = array_keys($extra_props);
  8398. $invalid_props = array_diff($generated_props, $expected_props);
  8399. if (!empty($invalid_props)) {
  8400. $validation_failed = true;
  8401. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8402. }
  8403. }
  8404. }
  8405. } else {
  8406. if (empty($episode_arr['acts'])) {
  8407. $validation_failed = true;
  8408. $validation_error_msg = '未生成分镜剧本相关的内容';
  8409. } else {
  8410. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8411. $generated_roles = array_filter($generated_roles, function($role) {
  8412. return $role !== '旁白';
  8413. });
  8414. if (empty($generated_roles)) {
  8415. $validation_failed = true;
  8416. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8417. }
  8418. }
  8419. }
  8420. // 重试循环
  8421. while ($validation_failed && $retry_count < $max_retries) {
  8422. $retry_count++;
  8423. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  8424. 'reason' => $validation_error_msg,
  8425. 'anime_id' => $anime_id,
  8426. 'episode_number' => 1
  8427. ]);
  8428. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  8429. 'reason' => $validation_error_msg,
  8430. 'anime_id' => $anime_id
  8431. ]);
  8432. yield [
  8433. 'type' => 'retry',
  8434. 'retry_count' => $retry_count,
  8435. 'reason' => $validation_error_msg
  8436. ];
  8437. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  8438. if ($anime_script_id) {
  8439. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  8440. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  8441. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  8442. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  8443. } else {
  8444. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  8445. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  8446. }
  8447. $messages[] = [
  8448. 'role' => 'assistant',
  8449. 'content' => $fullContent
  8450. ];
  8451. $messages[] = [
  8452. 'role' => 'user',
  8453. 'content' => $retry_prompt
  8454. ];
  8455. $post_data['messages'] = $messages;
  8456. try {
  8457. $streamGenerator = $this->dispatchStreamByModel($post_data);
  8458. $fullContent = '';
  8459. $fullReasoningContent = '';
  8460. foreach ($streamGenerator as $chunk) {
  8461. if (isset($chunk['type'])) {
  8462. if ($chunk['type'] === 'done') {
  8463. $fullContent = $chunk['full_content'];
  8464. $fullReasoningContent = $chunk['full_reasoning'];
  8465. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8466. } else {
  8467. yield $chunk;
  8468. }
  8469. }
  8470. }
  8471. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  8472. // 重试接口未返回有效内容时直接失败,避免空内容被兼容放行后保存
  8473. if ($fullContent === '') {
  8474. dLog('deepseek')->error("第{$retry_count}次重试接口未返回有效内容");
  8475. yield [
  8476. 'type' => 'done',
  8477. 'script' => [],
  8478. 'episode' => [],
  8479. 'answer' => '',
  8480. 'reasoning' => $fullReasoningContent,
  8481. 'usage' => $usage,
  8482. 'error' => '生成接口未返回有效内容,请稍后重试'
  8483. ];
  8484. return;
  8485. }
  8486. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  8487. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  8488. $script_arr = handleScriptContentForAce($fullContent);
  8489. if ($mappedArtStyle !== '') {
  8490. $script_arr['art_style'] = $mappedArtStyle;
  8491. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8492. }
  8493. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8494. $validation_failed = false;
  8495. $validation_error_msg = '';
  8496. if ($anime_script_id) {
  8497. if (empty($episode_arr['acts'])) {
  8498. $validation_failed = true;
  8499. $validation_error_msg = '未生成分镜剧本相关的内容';
  8500. } else {
  8501. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8502. $generated_roles = array_filter($generated_roles, function($role) {
  8503. return $role !== '旁白';
  8504. });
  8505. if (empty($generated_roles)) {
  8506. $validation_failed = true;
  8507. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8508. }
  8509. if (!$validation_failed && !empty($extra_roles)) {
  8510. $expected_roles = array_keys($extra_roles);
  8511. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8512. if (!empty($invalid_roles)) {
  8513. $validation_failed = true;
  8514. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8515. }
  8516. }
  8517. if (!$validation_failed && !empty($extra_scenes)) {
  8518. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  8519. $expected_scenes = array_keys($extra_scenes);
  8520. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8521. if (!empty($invalid_scenes)) {
  8522. $validation_failed = true;
  8523. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8524. }
  8525. }
  8526. if (!$validation_failed && !empty($extra_props)) {
  8527. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8528. $expected_props = array_keys($extra_props);
  8529. $invalid_props = array_diff($generated_props, $expected_props);
  8530. if (!empty($invalid_props)) {
  8531. $validation_failed = true;
  8532. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8533. }
  8534. }
  8535. }
  8536. } else {
  8537. if (empty($episode_arr['acts'])) {
  8538. $validation_failed = true;
  8539. $validation_error_msg = '未生成分镜剧本相关的内容';
  8540. } else {
  8541. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  8542. $generated_roles = array_filter($generated_roles, function($role) {
  8543. return $role !== '旁白';
  8544. });
  8545. if (empty($generated_roles)) {
  8546. $validation_failed = true;
  8547. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  8548. }
  8549. }
  8550. }
  8551. } catch (\Exception $e) {
  8552. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  8553. 'trace' => $e->getTraceAsString()
  8554. ]);
  8555. break;
  8556. }
  8557. }
  8558. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存
  8559. if ($validation_failed && $retry_count >= $max_retries) {
  8560. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  8561. 'retry_count' => $retry_count,
  8562. 'last_error' => $validation_error_msg
  8563. ]);
  8564. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  8565. 'error' => $validation_error_msg,
  8566. 'anime_id' => $anime_id
  8567. ]);
  8568. $validation_failed = false;
  8569. $validation_error_msg = '';
  8570. }
  8571. // 如果重试后仍然失败
  8572. if ($validation_failed) {
  8573. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  8574. 'retry_count' => $retry_count,
  8575. 'last_error' => $validation_error_msg
  8576. ]);
  8577. try {
  8578. $now = date('Y-m-d H:i:s');
  8579. $records = [
  8580. [
  8581. 'uid' => $uid,
  8582. 'anime_id' => $anime_id,
  8583. 'sequence' => 1,
  8584. 'role' => 'user',
  8585. 'content' => $prompt,
  8586. 'created_at' => $now,
  8587. 'updated_at' => $now
  8588. ],
  8589. [
  8590. 'uid' => $uid,
  8591. 'anime_id' => $anime_id,
  8592. 'sequence' => 1,
  8593. 'role' => 'assistant',
  8594. 'content' => $fullContent,
  8595. 'created_at' => $now,
  8596. 'updated_at' => $now
  8597. ]
  8598. ];
  8599. DB::table('mp_anime_records')->insert($records);
  8600. } catch (\Exception $e) {
  8601. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8602. }
  8603. yield [
  8604. 'type' => 'done',
  8605. 'script' => [],
  8606. 'episode' => [],
  8607. 'answer' => $fullContent,
  8608. 'reasoning' => $fullReasoningContent,
  8609. 'usage' => $usage,
  8610. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  8611. ];
  8612. return;
  8613. }
  8614. // 验证成功,记录日志
  8615. if ($retry_count > 0) {
  8616. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  8617. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  8618. }
  8619. }
  8620. $table_data = [
  8621. 'user_id' => $uid,
  8622. 'anime_name' => $anime_name,
  8623. 'model' => $model,
  8624. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  8625. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  8626. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  8627. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  8628. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  8629. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  8630. 'art_style_type' => $input_art_style,
  8631. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  8632. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  8633. 'status' => '解析完成',
  8634. 'content' => $content,
  8635. 'is_multi' => $is_multi,
  8636. 'ace_mode' => $ace_mode,
  8637. 'generate_status' => '待执行',
  8638. 'updated_at' => date('Y-m-d H:i:s')
  8639. ];
  8640. if ($table_data['content']) {
  8641. $chapters = splitContent($table_data['content']);
  8642. $chapter_count = count($chapters);
  8643. if ($chapter_count > 0) {
  8644. $table_data['start_episode_sequence'] = 1;
  8645. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  8646. }
  8647. }
  8648. if ($extra_products) {
  8649. $table_data['extra_products'] = json_encode($extra_products, 256);
  8650. }
  8651. // 如果有剧本ID则进行绑定
  8652. if ($script_id) {
  8653. $table_data['script_id'] = $script_id;
  8654. }
  8655. $single_episode = [];
  8656. try {
  8657. DB::beginTransaction();
  8658. $now = date('Y-m-d H:i:s');
  8659. // 更新动漫大纲
  8660. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  8661. if (!$boolen) {
  8662. dLog('deepseek')->info('动漫保存失败', $table_data);
  8663. Utils::throwError('20003:动漫保存失败');
  8664. }
  8665. // 保存对话记录
  8666. $records = [
  8667. [
  8668. 'uid' => $uid,
  8669. 'anime_id' => $anime_id,
  8670. 'sequence' => 0,
  8671. 'role' => 'user',
  8672. 'content' => $prompt,
  8673. 'created_at' => date('Y-m-d H:i:s'),
  8674. 'updated_at' => date('Y-m-d H:i:s')
  8675. ],
  8676. [
  8677. 'uid' => $uid,
  8678. 'anime_id' => $anime_id,
  8679. 'sequence' => 0,
  8680. 'role' => 'assistant',
  8681. 'content' => $fullContent,
  8682. 'created_at' => date('Y-m-d H:i:s'),
  8683. 'updated_at' => date('Y-m-d H:i:s')
  8684. ]
  8685. ];
  8686. // 保存对话记录
  8687. $boolen3 = DB::table('mp_anime_records')->insert($records);
  8688. if (!$boolen3) {
  8689. Utils::throwError('20003:对话记录保存失败');
  8690. }
  8691. if ($is_single) {
  8692. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8693. if (empty($episode_arr['acts'])) {
  8694. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  8695. }
  8696. $saveResult = $this->saveEpisodeVersionData(
  8697. $anime_id,
  8698. 1,
  8699. $episode_arr,
  8700. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8701. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8702. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  8703. null,
  8704. null,
  8705. false,
  8706. $content,
  8707. $now,
  8708. $ref_products
  8709. );
  8710. $single_episode = $saveResult['episode'];
  8711. $episode_id = $saveResult['episode_id'];
  8712. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  8713. 'roles' => json_encode($saveResult['merged_roles'], 256),
  8714. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  8715. 'props' => json_encode($saveResult['merged_props'], 256),
  8716. 'updated_at' => $now
  8717. ]);
  8718. if ($boolen5 === false) {
  8719. Utils::throwError('20003:单剧集主表资源同步失败');
  8720. }
  8721. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  8722. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  8723. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  8724. $episode_record_content = '确认分镜大纲';
  8725. if ($content !== '') {
  8726. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  8727. }
  8728. $episode_records = [
  8729. [
  8730. 'uid' => $uid,
  8731. 'anime_id' => $anime_id,
  8732. 'role' => 'user',
  8733. 'content' => $episode_record_content,
  8734. 'sequence' => 1,
  8735. 'episode_id' => $episode_id,
  8736. 'created_at' => $now,
  8737. 'updated_at' => $now
  8738. ],
  8739. [
  8740. 'uid' => $uid,
  8741. 'anime_id' => $anime_id,
  8742. 'role' => 'assistant',
  8743. 'content' => $fullContent,
  8744. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8745. 'sequence' => 1,
  8746. 'episode_id' => $episode_id,
  8747. 'created_at' => $now,
  8748. 'updated_at' => $now
  8749. ]
  8750. ];
  8751. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  8752. if (!$boolen4) {
  8753. Utils::throwError('20003:单剧集分镜记录保存失败');
  8754. }
  8755. }
  8756. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8757. if ($is_single && !empty($single_episode)) {
  8758. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8759. 'anime_id' => $anime_id,
  8760. 'episode_id' => $episode_id ?? 0,
  8761. 'model' => $model,
  8762. 'source' => 'addChatForAce',
  8763. ]);
  8764. }
  8765. }catch (\Exception $e) {
  8766. DB::rollBack();
  8767. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  8768. yield [
  8769. 'type' => 'done',
  8770. 'answer' => $fullContent,
  8771. 'reasoning' => $fullReasoningContent,
  8772. 'usage' => $usage,
  8773. 'error' => $e->getMessage(),
  8774. ];
  8775. return;
  8776. }
  8777. DB::commit();
  8778. dLog('deepseek')->info('保存完毕');
  8779. if ($is_single && !empty($single_episode)) {
  8780. // $this->batchSetGlobalRoleImg([
  8781. // 'anime_id' => $anime_id,
  8782. // ]);
  8783. // $this->batchSetGlobalSceneImg([
  8784. // 'anime_id' => $anime_id,
  8785. // ]);
  8786. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8787. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8788. }
  8789. $table_data['anime_id'] = $anime_id;
  8790. $table_data['roles'] = json_decode($table_data['roles'], true);
  8791. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8792. // $table_data['episodes'] = $script_arr['episodes'];
  8793. unset($table_data['created_at']);
  8794. unset($table_data['updated_at']);
  8795. unset($table_data['status']);
  8796. dLog('deepseek')->info('开始返回');
  8797. yield [
  8798. 'type' => 'done',
  8799. 'script' => $table_data,
  8800. 'episode' => $single_episode,
  8801. 'answer' => $fullContent,
  8802. 'reasoning' => $fullReasoningContent,
  8803. 'usage' => $usage
  8804. ];
  8805. }
  8806. public function reGenerateAnimeForAce($data) {
  8807. $uid = Site::getUid();
  8808. $file = getProp($data, 'file');
  8809. $content = getProp($data, 'content', '');
  8810. $bid = getProp($data, 'bid', 0);
  8811. $script_id = getProp($data, 'script_id', 0);
  8812. $anime_id = getProp($data, 'anime_id');
  8813. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8814. if (!$anime) {
  8815. Utils::throwError('20003:该对话不存在');
  8816. }
  8817. $is_multi = getProp($anime, 'is_multi', 1);
  8818. $is_single = (int)$is_multi !== 1;
  8819. // 积分余额预检(仅单剧集模式收费)
  8820. if ($is_single) {
  8821. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  8822. }
  8823. $extra_products = getProp($data, 'products', []);
  8824. if (!$extra_products) {
  8825. $extra_products = getProp($anime, 'extra_products');
  8826. if ($extra_products) {
  8827. $extra_products = json_decode($extra_products, true);
  8828. }else {
  8829. $extra_products = [];
  8830. }
  8831. }else {
  8832. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  8833. }
  8834. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  8835. $anime_script_id = getProp($anime, 'script_id');
  8836. if ($anime_script_id && $is_single) {
  8837. $cpid = Site::getCpid();
  8838. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  8839. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8840. ->where('mapping.script_id', $anime_script_id)
  8841. ->where('product.cpid', $cpid)
  8842. ->where('product.is_deleted', 0);
  8843. $mappings = $script_products_mappings->select(
  8844. 'mapping.product_id',
  8845. 'mapping.episode_number',
  8846. 'product.product_name',
  8847. 'product.type',
  8848. 'product.product',
  8849. 'product.pic_prompt',
  8850. 'product.url',
  8851. 'product.pic_task_id',
  8852. 'product.pic_task_status',
  8853. 'product.three_view_image_url'
  8854. )
  8855. ->get();
  8856. // 按 product_id 分组,合并 episode_number
  8857. $productMap = [];
  8858. foreach ($mappings as $item) {
  8859. $product_id = $item->product_id;
  8860. $product_name = $item->product_name;
  8861. // 处理product_name两边的符号
  8862. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8863. if (!isset($productMap[$product_id])) {
  8864. $productMap[$product_id] = [
  8865. 'product_id' => $product_id,
  8866. 'product_name' => $product_name,
  8867. 'type' => (int)$item->type,
  8868. 'product' => (int)$item->product,
  8869. 'pic_prompt' => $item->pic_prompt,
  8870. 'url' => $item->url,
  8871. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  8872. 'pic_task_id' => $item->pic_task_id,
  8873. 'pic_task_status' => $item->pic_task_status,
  8874. 'episode_numbers' => [],
  8875. ];
  8876. }
  8877. // 添加 episode_number(去重)
  8878. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8879. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8880. }
  8881. }
  8882. // 将查询到的剧本资产合并到extra_products中
  8883. // 先构建extra_products的索引(以product_id为key,用于去重)
  8884. $extraProductsMap = [];
  8885. foreach ($extra_products as $item) {
  8886. $key = getProp($item, 'product_id');
  8887. if ($key) {
  8888. $extraProductsMap[$key] = $item;
  8889. }
  8890. }
  8891. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  8892. foreach ($productMap as $product) {
  8893. $product_id = $product['product_id'];
  8894. // 如果不存在则添加(不带episode_number信息)
  8895. if (!isset($extraProductsMap[$product_id])) {
  8896. $extraProductsMap[$product_id] = [
  8897. 'product_id' => $product['product_id'],
  8898. 'product_name' => $product['product_name'],
  8899. 'type' => $product['type'],
  8900. 'product' => $product['product'],
  8901. 'pic_prompt' => $product['pic_prompt'],
  8902. 'url' => $product['url'],
  8903. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  8904. 'pic_task_id' => $product['pic_task_id'],
  8905. 'pic_task_status' => $product['pic_task_status'],
  8906. ];
  8907. }
  8908. }
  8909. // 重新赋值给extra_products
  8910. $extra_products = array_values($extraProductsMap);
  8911. }
  8912. $user_anime_name = getProp($anime, 'anime_name');
  8913. $prompt = getProp($data, 'prompt');
  8914. // 处理提示词
  8915. if ($prompt && $extra_products) {
  8916. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8917. foreach($extra_products as $item) {
  8918. $product_name = getProp($item, 'product_name');
  8919. if ($product_name) {
  8920. // 替换 {product_name} 为 product_name
  8921. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8922. }
  8923. }
  8924. }
  8925. // 处理文本模型
  8926. $model = getProp($data, 'model');
  8927. if (!$model) {
  8928. // 用户没有输入,从anime表获取
  8929. $model = getProp($anime, 'model');
  8930. if (!$model) {
  8931. // anime表也没有,使用默认值
  8932. $model = 'deepseek-v4-pro';
  8933. }
  8934. }
  8935. // 验证模型是否在可用模型表中
  8936. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8937. $model = 'deepseek-v4-pro';
  8938. }
  8939. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  8940. if ($is_single) {
  8941. $episode_exists = DB::table('mp_anime_episodes')
  8942. ->where('anime_id', $anime_id)
  8943. ->where('sequence', 1)
  8944. ->exists();
  8945. if ($episode_exists) {
  8946. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  8947. }
  8948. }
  8949. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  8950. if ($prompt) {
  8951. $question .= "本次修改要求如下:\n{$prompt}";
  8952. }
  8953. // 提取文件内容
  8954. if ($file) {
  8955. $content = $this->extractFileContent($file);
  8956. if (!$content) {
  8957. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8958. }
  8959. } elseif ($script_id) {
  8960. $content = $this->getContentByScriptId($script_id);
  8961. if (!$content) {
  8962. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  8963. }
  8964. } elseif ($bid) {
  8965. $content = $this->getContentByBid($bid);
  8966. if (!$content) {
  8967. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  8968. }
  8969. } elseif ($content) {
  8970. $content = filterContent($content);
  8971. }else {
  8972. $content = filterContent(getProp($anime, 'content'));
  8973. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  8974. $need_generate_content = true;
  8975. }
  8976. }
  8977. // 判断是否需要生成原文内容
  8978. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  8979. // 如果需要生成原文内容,添加额外的要求
  8980. $content_generation_requirement = $need_generate_content
  8981. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  8982. : "";
  8983. // 美术风格
  8984. $input_art_style = getProp($data, 'art_style');
  8985. if (!$input_art_style) {
  8986. $mappedArtStyle = getProp($anime, 'art_style');
  8987. }else {
  8988. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  8989. }
  8990. if (!$mappedArtStyle) {
  8991. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  8992. }else {
  8993. if (strstr($mappedArtStyle, '基础画风风格词')) {
  8994. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  8995. }else {
  8996. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  8997. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  8998. }
  8999. }
  9000. // 构建主体、场景和道具提示词
  9001. $extra_role_prompt = "\n";
  9002. $extra_scene_prompt = "\n";
  9003. $extra_prop_prompt = "\n";
  9004. $extra_roles = [];
  9005. $extra_scenes = [];
  9006. $extra_props = [];
  9007. $ref_products = []; // 参考资产
  9008. if ($extra_products) {
  9009. foreach($extra_products as $item) {
  9010. $product = getProp($item, 'product');
  9011. $product_name = getProp($item, 'product_name');
  9012. if ($product_name == '旁白') continue;
  9013. $ref_products[$product_name] = $item;
  9014. $pic_prompt = getProp($item, 'pic_prompt');
  9015. if ((int)$product === 1) {
  9016. // 拼接角色信息
  9017. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9018. $extra_roles[$product_name] = [
  9019. 'role' => $product_name,
  9020. 'pic_prompt' => $pic_prompt,
  9021. 'url' => getProp($item, 'url', ''),
  9022. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9023. ];
  9024. } elseif ((int)$product === 2) {
  9025. // 拼接场景信息
  9026. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9027. $extra_scenes[$product_name] = [
  9028. 'scene' => $product_name,
  9029. 'pic_prompt' => $pic_prompt,
  9030. 'url' => getProp($item, 'url', ''),
  9031. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9032. ];
  9033. } elseif ((int)$product === 3) {
  9034. // 拼接道具信息
  9035. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  9036. $extra_props[$product_name] = [
  9037. 'prop' => $product_name,
  9038. 'pic_prompt' => $pic_prompt,
  9039. 'url' => getProp($item, 'url', ''),
  9040. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  9041. ];
  9042. }
  9043. }
  9044. // 优化提示词,融入剧本
  9045. if (!empty(trim($extra_role_prompt))) {
  9046. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  9047. }
  9048. if (!empty(trim($extra_scene_prompt))) {
  9049. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  9050. }
  9051. if (!empty(trim($extra_prop_prompt))) {
  9052. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  9053. }
  9054. }
  9055. if ($anime_script_id && $is_single) {
  9056. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  9057. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  9058. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  9059. }else {
  9060. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  9061. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9062. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  9063. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9064. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9065. {$extra_role_prompt}";
  9066. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9067. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  9068. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9069. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  9070. {$extra_scene_prompt}";
  9071. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9072. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  9073. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  9074. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  9075. {$extra_prop_prompt}";
  9076. }
  9077. $system_message = ['role'=>'system', 'content'=>$is_single
  9078. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  9079. 强制要求:
  9080. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9081. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9082. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9083. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9084. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9085. 普通要求:
  9086. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  9087. $role_demo
  9088. $scene_demo
  9089. $prop_demo
  9090. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9091. 5.1片段分割逻辑(优先级从高到低):
  9092. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9093. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9094. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9095. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9096. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9097. - 片段数量格式为: 片段数量:8
  9098. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9099. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9100. 5.3分镜结构:每个分镜包含以下字段:
  9101. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  9102. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  9103. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9104. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9105. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9106. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9107. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9108. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9109. - 运镜:场景+画面描述+运镜
  9110. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  9111. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  9112. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9113. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  9114. 6.《情绪-视听语言映射表》:
  9115. 6.1 场景空间与时间心理学 (Scene & Temporality)
  9116. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9117. -----|---------|------------|----------------
  9118. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  9119. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  9120. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  9121. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  9122. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  9123. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9124. -----|---------|------------|----------------
  9125. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  9126. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  9127. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  9128. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  9129. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  9130. --------|---------|--------------|-------------
  9131. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  9132. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  9133. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  9134. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  9135. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  9136. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  9137. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  9138. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  9139. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  9140. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  9141. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  9142. -----|---------|------------|------------
  9143. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  9144. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  9145. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  9146. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  9147. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  9148. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  9149. --------|---------|--------------|----------
  9150. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  9151. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  9152. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  9153. 6.6 声音设计与潜意识影响 (Soundscape)
  9154. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  9155. -----|---------|------------|------------------
  9156. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  9157. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  9158. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  9159. 理论基石:
  9160. - The Five C's of Cinematography by Joseph V. Mascelli
  9161. - Film Art: An Introduction by David Bordwell
  9162. - Sight, Sound, Motion by Herbert Zettl
  9163. - Notes on the Cinematograph by Robert Bresson
  9164. \n\n
  9165. 7.{$mappedArtStyle_prompt}\n\n
  9166. 示例如下:\n
  9167. ###剧本名:西昆仑
  9168. ###故事梗概
  9169. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9170. ###剧本亮点
  9171. 亮点1:绝境奇药,生死一线
  9172. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9173. 亮点2:结拜兄妹,化解尴尬
  9174. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9175. 亮点3:纤发夺命,情愫暗涌
  9176. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9177. ###人物关系
  9178. 阿雪与梁萧之间存在兄妹之情。
  9179. ###核心矛盾
  9180. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9181. ###主体列表
  9182. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9183. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9184. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9185. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9186. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9187. 全景,正面拍摄,青年女性,亚洲人。
  9188. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9189. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9190. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9191. ###美术风格
  9192. 基础画风风格词:厚涂古风
  9193. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9194. ###场景列表
  9195. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9196. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9197. 无人物。}
  9198. ###分段剧本
  9199. 片段数量:8
  9200. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9201. ##片段1
  9202. 时长:12s
  9203. 分镜1
  9204. 出场角色:刀疤脸
  9205. 场景:边境小镇街道
  9206. 出场道具:酒杯-高脚杯
  9207. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9208. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9209. 配音台词:
  9210. 背景音效:
  9211. 分镜2
  9212. 出场角色:刀疤脸
  9213. 场景:悦来酒馆
  9214. 出场道具:酒杯-高脚杯
  9215. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9216. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9217. 配音台词:
  9218. 背景音效:
  9219. 分镜3
  9220. 出场角色:刀疤脸
  9221. 场景:悦来酒馆
  9222. 出场道具:酒杯-高脚杯
  9223. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9224. 运镜:从中景推向令牌特写。
  9225. 配音台词:
  9226. 背景音效:
  9227. 分镜4
  9228. 出场角色:刀疤脸
  9229. 场景:悦来酒馆
  9230. 出场道具:酒杯-高脚杯
  9231. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9232. 运镜:极速推向酒水溅起的瞬间。
  9233. 配音台词:
  9234. 背景音效:
  9235. 分镜5
  9236. 出场角色:刀疤脸
  9237. 场景:悦来酒馆
  9238. 出场道具:酒杯-高脚杯
  9239. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9240. 运镜:固定机位,利用倾斜构图制造压迫感。
  9241. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9242. 背景音效:
  9243. \n\n"
  9244. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  9245. 强制要求:\n
  9246. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9247. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9248. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9249. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9250. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9251. 普通要求:\n
  9252. 1.剧本名(必须生成)必须与文档内容高度相关
  9253. $role_demo
  9254. $scene_demo
  9255. $prop_demo
  9256. 5.{$mappedArtStyle_prompt}\n\n
  9257. 示例如下:\n
  9258. ###剧本名:西昆仑
  9259. ###故事梗概
  9260. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9261. ###剧本亮点
  9262. 亮点1:绝境奇药,生死一线
  9263. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9264. 亮点2:结拜兄妹,化解尴尬
  9265. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9266. 亮点3:纤发夺命,情愫暗涌
  9267. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9268. ###人物关系
  9269. 阿雪与梁萧之间存在兄妹之情。
  9270. ###核心矛盾
  9271. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9272. ###主体列表
  9273. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9274. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9275. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9276. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9277. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9278. 全景,正面拍摄,青年女性,亚洲人。
  9279. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9280. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9281. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9282. ###美术风格
  9283. 基础画风风格词:厚涂古风
  9284. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9285. ###场景列表
  9286. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9287. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9288. 无人物。}
  9289. ###道具列表
  9290. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  9291. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  9292. $episode_count = $this->extractEpisodeNumber($prompt);
  9293. if ((int)getProp($anime, 'is_multi') !== 1) {
  9294. yield [
  9295. 'type' => 'done',
  9296. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  9297. 'reasoning' => '',
  9298. 'usage' => []
  9299. ];
  9300. return;
  9301. }
  9302. if ($episode_count) {
  9303. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  9304. $system_message = [
  9305. 'role' => 'system',
  9306. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  9307. 强制要求:\n
  9308. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  9309. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  9310. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  9311. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  9312. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  9313. 普通要求:\n
  9314. 1.<故事梗概>控制在200-300字左右
  9315. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  9316. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  9317. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  9318. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  9319. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9320. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  9321. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  9322. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  9323. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  9324. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  9325. 示例如下:\n
  9326. ###剧本名:西昆仑
  9327. ###故事梗概
  9328. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9329. ###剧本亮点
  9330. 亮点1:绝境奇药,生死一线
  9331. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  9332. 亮点2:结拜兄妹,化解尴尬
  9333. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  9334. 亮点3:纤发夺命,情愫暗涌
  9335. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  9336. ###人物关系
  9337. 阿雪与梁萧之间存在兄妹之情。
  9338. ###核心矛盾
  9339. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  9340. ###主体列表
  9341. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  9342. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  9343. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  9344. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  9345. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  9346. 全景,正面拍摄,青年女性,亚洲人。
  9347. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  9348. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  9349. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9350. ###美术风格
  9351. 基础画风风格词:厚涂古风
  9352. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  9353. ###场景列表
  9354. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  9355. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  9356. 无人物。}
  9357. ###分集详细内容
  9358. ##第1章 重生
  9359. 我重生了。
  9360. 源于一个男人偏执的暗恋。
  9361. ##第2章 相救
  9362. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  9363. 我眼睛扫向站在锅炉后的卞大伟。"
  9364. ];
  9365. // 构建消息
  9366. $messages = [
  9367. $system_message,
  9368. [
  9369. 'role' => 'user',
  9370. 'content' => "以下是文档内容:
  9371. {$content}
  9372. 用户问题:
  9373. {$question}"
  9374. ]
  9375. ];
  9376. }else {
  9377. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  9378. // 构建消息
  9379. $messages = [
  9380. $system_message,
  9381. [
  9382. 'role' => 'user',
  9383. 'content' => "以下是文档内容:
  9384. {$content}
  9385. 用户问题:
  9386. {$question}"
  9387. ]
  9388. ];
  9389. }else {
  9390. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  9391. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  9392. return (array)$value;
  9393. })->toArray();
  9394. array_unshift($messages, $system_message);
  9395. $messages[] = [
  9396. 'role' => 'user',
  9397. 'content' => $prompt
  9398. ];
  9399. }
  9400. }
  9401. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  9402. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  9403. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  9404. if ($model === 'deepseek-chat') {
  9405. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  9406. $model = 'deepseek-v4-flash';
  9407. $thinkingMode = 'disabled';
  9408. } elseif ($model === 'deepseek-reasoner') {
  9409. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  9410. $model = 'deepseek-v4-flash';
  9411. $thinkingMode = 'enabled';
  9412. }
  9413. $post_data = [
  9414. 'model' => $model,
  9415. 'messages' => $messages,
  9416. // 'max_tokens' => 8192,
  9417. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9418. 'frequency_penalty' => 0,
  9419. 'presence_penalty' => 0,
  9420. 'response_format' => ['type' => 'text'],
  9421. 'thinking' => ['type' => $thinkingMode],
  9422. 'stream' => true // 启用流式输出
  9423. ];
  9424. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9425. // 根据模型类型选择调用方法
  9426. $fullContent = '';
  9427. $fullReasoningContent = '';
  9428. $usage = [];
  9429. // dd($post_data);
  9430. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  9431. try {
  9432. $streamGenerator = $this->dispatchStreamByModel($post_data);
  9433. // 验证返回值类型
  9434. if (!is_iterable($streamGenerator)) {
  9435. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  9436. dLog('deepseek')->error('方法名流式生成器无效', [
  9437. 'generator_type' => $errorType,
  9438. 'model' => $model,
  9439. // 添加其他上下文信息
  9440. ]);
  9441. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  9442. 'type' => $errorType,
  9443. 'model' => $model
  9444. ]);
  9445. yield [
  9446. 'type' => 'error',
  9447. // 根据方法返回相应的空数据结构
  9448. 'answer' => '',
  9449. 'reasoning' => '',
  9450. 'usage' => [],
  9451. 'error' => '接口返回数据异常,请重新请求'
  9452. ];
  9453. return;
  9454. }
  9455. // 处理流式输出
  9456. foreach ($streamGenerator as $chunk) {
  9457. if (isset($chunk['type'])) {
  9458. if ($chunk['type'] === 'done') {
  9459. $fullContent = $chunk['full_content'];
  9460. $fullReasoningContent = $chunk['full_reasoning'];
  9461. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9462. } else {
  9463. yield $chunk;
  9464. }
  9465. }
  9466. }
  9467. } catch (\Exception $e) {
  9468. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  9469. 'model' => $model,
  9470. 'trace' => $e->getTraceAsString()
  9471. ]);
  9472. logDB('deepseek', 'error', '方法名流式处理失败', [
  9473. 'error' => $e->getMessage(),
  9474. 'model' => $model
  9475. ]);
  9476. yield [
  9477. 'type' => 'error',
  9478. // 根据方法返回相应的空数据结构
  9479. 'answer' => '',
  9480. 'reasoning' => '',
  9481. 'usage' => [],
  9482. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  9483. ];
  9484. return;
  9485. }
  9486. dLog('deepseek')->info('完整内容: '.$fullContent);
  9487. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  9488. // 处理完整内容并返回最终结果
  9489. $script_arr = [];
  9490. if ($fullContent) {
  9491. $script_arr = handleScriptContentForAce($fullContent);
  9492. dLog('deepseek')->info('解析内容', $script_arr);
  9493. logDB('deepseek', 'info', '解析内容', $script_arr);
  9494. }
  9495. if (empty($script_arr['roles'])) {
  9496. // 未生成剧本相关内容,保存对话记录并返回提示
  9497. dLog('deepseek')->info('未生成剧本相关的内容');
  9498. try {
  9499. $now = date('Y-m-d H:i:s');
  9500. // 保存对话记录
  9501. $records = [
  9502. [
  9503. 'uid' => $uid,
  9504. 'anime_id' => $anime_id,
  9505. 'sequence' => 0,
  9506. 'role' => 'user',
  9507. 'content' => $prompt,
  9508. 'created_at' => $now,
  9509. 'updated_at' => $now
  9510. ],
  9511. [
  9512. 'uid' => $uid,
  9513. 'anime_id' => $anime_id,
  9514. 'sequence' => 0,
  9515. 'role' => 'assistant',
  9516. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  9517. 'created_at' => $now,
  9518. 'updated_at' => $now
  9519. ]
  9520. ];
  9521. DB::table('mp_anime_records')->insert($records);
  9522. } catch (\Exception $e) {
  9523. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9524. }
  9525. yield [
  9526. 'type' => 'done',
  9527. 'script' => [],
  9528. 'episode' => [],
  9529. 'answer' => $fullContent,
  9530. 'reasoning' => $fullReasoningContent,
  9531. 'usage' => $usage,
  9532. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  9533. ];
  9534. return;
  9535. }
  9536. // 替换美术风格
  9537. if ($mappedArtStyle !== '') {
  9538. $script_arr['art_style'] = $mappedArtStyle;
  9539. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  9540. }
  9541. if ($user_anime_name != '新剧本策划') {
  9542. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  9543. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  9544. // 确认对话名称唯一性
  9545. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  9546. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  9547. }
  9548. }else {
  9549. $anime_name = $user_anime_name;
  9550. }
  9551. // 单剧集模式:按 chatForAce 逻辑校验并重试生成剧集与分段剧本
  9552. if ($is_single) {
  9553. $max_retries = 3;
  9554. $retry_count = 0;
  9555. $validation_failed = false;
  9556. $validation_error_msg = '';
  9557. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9558. // 首次校验
  9559. if ($anime_script_id) {
  9560. if (empty($episode_arr['acts'])) {
  9561. $validation_failed = true;
  9562. $validation_error_msg = '未生成分镜剧本相关的内容';
  9563. } else {
  9564. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9565. $generated_roles = array_filter($generated_roles, function($role) {
  9566. return $role !== '旁白';
  9567. });
  9568. if (empty($generated_roles)) {
  9569. $validation_failed = true;
  9570. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9571. }
  9572. if (!$validation_failed && !empty($extra_roles)) {
  9573. $expected_roles = array_keys($extra_roles);
  9574. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9575. if (!empty($invalid_roles)) {
  9576. $validation_failed = true;
  9577. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9578. }
  9579. }
  9580. if (!$validation_failed && !empty($extra_scenes)) {
  9581. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  9582. $expected_scenes = array_keys($extra_scenes);
  9583. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9584. if (!empty($invalid_scenes)) {
  9585. $validation_failed = true;
  9586. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9587. }
  9588. }
  9589. if (!$validation_failed && !empty($extra_props)) {
  9590. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9591. $expected_props = array_keys($extra_props);
  9592. $invalid_props = array_diff($generated_props, $expected_props);
  9593. if (!empty($invalid_props)) {
  9594. $validation_failed = true;
  9595. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9596. }
  9597. }
  9598. }
  9599. } else {
  9600. if (empty($episode_arr['acts'])) {
  9601. $validation_failed = true;
  9602. $validation_error_msg = '未生成分镜剧本相关的内容';
  9603. } else {
  9604. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9605. $generated_roles = array_filter($generated_roles, function($role) {
  9606. return $role !== '旁白';
  9607. });
  9608. if (empty($generated_roles)) {
  9609. $validation_failed = true;
  9610. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9611. }
  9612. }
  9613. }
  9614. // 重试循环
  9615. while ($validation_failed && $retry_count < $max_retries) {
  9616. $retry_count++;
  9617. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  9618. 'reason' => $validation_error_msg,
  9619. 'anime_id' => $anime_id,
  9620. 'episode_number' => 1
  9621. ]);
  9622. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  9623. 'reason' => $validation_error_msg,
  9624. 'anime_id' => $anime_id
  9625. ]);
  9626. yield [
  9627. 'type' => 'retry',
  9628. 'retry_count' => $retry_count,
  9629. 'reason' => $validation_error_msg
  9630. ];
  9631. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  9632. if ($anime_script_id) {
  9633. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  9634. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9635. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  9636. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  9637. } else {
  9638. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9639. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  9640. }
  9641. $messages[] = [
  9642. 'role' => 'assistant',
  9643. 'content' => $fullContent
  9644. ];
  9645. $messages[] = [
  9646. 'role' => 'user',
  9647. 'content' => $retry_prompt
  9648. ];
  9649. $post_data['messages'] = $messages;
  9650. try {
  9651. $streamGenerator = $this->dispatchStreamByModel($post_data);
  9652. $fullContent = '';
  9653. $fullReasoningContent = '';
  9654. foreach ($streamGenerator as $chunk) {
  9655. if (isset($chunk['type'])) {
  9656. if ($chunk['type'] === 'done') {
  9657. $fullContent = $chunk['full_content'];
  9658. $fullReasoningContent = $chunk['full_reasoning'];
  9659. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9660. } else {
  9661. yield $chunk;
  9662. }
  9663. }
  9664. }
  9665. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9666. // 重试接口未返回有效内容时直接失败,避免空内容被兼容放行后保存
  9667. if ($fullContent === '') {
  9668. dLog('deepseek')->error("第{$retry_count}次重试接口未返回有效内容");
  9669. yield [
  9670. 'type' => 'done',
  9671. 'script' => [],
  9672. 'episode' => [],
  9673. 'answer' => '',
  9674. 'reasoning' => $fullReasoningContent,
  9675. 'usage' => $usage,
  9676. 'error' => '生成接口未返回有效内容,请稍后重试'
  9677. ];
  9678. return;
  9679. }
  9680. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  9681. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  9682. $script_arr = handleScriptContentForAce($fullContent);
  9683. if ($mappedArtStyle !== '') {
  9684. $script_arr['art_style'] = $mappedArtStyle;
  9685. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  9686. }
  9687. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9688. $validation_failed = false;
  9689. $validation_error_msg = '';
  9690. if ($anime_script_id) {
  9691. if (empty($episode_arr['acts'])) {
  9692. $validation_failed = true;
  9693. $validation_error_msg = '未生成分镜剧本相关的内容';
  9694. } else {
  9695. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9696. $generated_roles = array_filter($generated_roles, function($role) {
  9697. return $role !== '旁白';
  9698. });
  9699. if (empty($generated_roles)) {
  9700. $validation_failed = true;
  9701. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9702. }
  9703. if (!$validation_failed && !empty($extra_roles)) {
  9704. $expected_roles = array_keys($extra_roles);
  9705. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9706. if (!empty($invalid_roles)) {
  9707. $validation_failed = true;
  9708. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9709. }
  9710. }
  9711. if (!$validation_failed && !empty($extra_scenes)) {
  9712. $generated_scenes = array_column($episode_arr['scenes'] ?? [], 'scene');
  9713. $expected_scenes = array_keys($extra_scenes);
  9714. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9715. if (!empty($invalid_scenes)) {
  9716. $validation_failed = true;
  9717. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9718. }
  9719. }
  9720. if (!$validation_failed && !empty($extra_props)) {
  9721. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9722. $expected_props = array_keys($extra_props);
  9723. $invalid_props = array_diff($generated_props, $expected_props);
  9724. if (!empty($invalid_props)) {
  9725. $validation_failed = true;
  9726. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9727. }
  9728. }
  9729. }
  9730. } else {
  9731. if (empty($episode_arr['acts'])) {
  9732. $validation_failed = true;
  9733. $validation_error_msg = '未生成分镜剧本相关的内容';
  9734. } else {
  9735. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9736. $generated_roles = array_filter($generated_roles, function($role) {
  9737. return $role !== '旁白';
  9738. });
  9739. if (empty($generated_roles)) {
  9740. $validation_failed = true;
  9741. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9742. }
  9743. }
  9744. }
  9745. } catch (\Exception $e) {
  9746. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  9747. 'trace' => $e->getTraceAsString()
  9748. ]);
  9749. break;
  9750. }
  9751. }
  9752. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存
  9753. if ($validation_failed && $retry_count >= $max_retries) {
  9754. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  9755. 'retry_count' => $retry_count,
  9756. 'last_error' => $validation_error_msg
  9757. ]);
  9758. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  9759. 'error' => $validation_error_msg,
  9760. 'anime_id' => $anime_id
  9761. ]);
  9762. $validation_failed = false;
  9763. $validation_error_msg = '';
  9764. }
  9765. // 如果重试后仍然失败
  9766. if ($validation_failed) {
  9767. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  9768. 'retry_count' => $retry_count,
  9769. 'last_error' => $validation_error_msg
  9770. ]);
  9771. try {
  9772. $now = date('Y-m-d H:i:s');
  9773. $records = [
  9774. [
  9775. 'uid' => $uid,
  9776. 'anime_id' => $anime_id,
  9777. 'sequence' => 1,
  9778. 'role' => 'user',
  9779. 'content' => $prompt,
  9780. 'created_at' => $now,
  9781. 'updated_at' => $now
  9782. ],
  9783. [
  9784. 'uid' => $uid,
  9785. 'anime_id' => $anime_id,
  9786. 'sequence' => 1,
  9787. 'role' => 'assistant',
  9788. 'content' => $fullContent,
  9789. 'created_at' => $now,
  9790. 'updated_at' => $now
  9791. ]
  9792. ];
  9793. DB::table('mp_anime_records')->insert($records);
  9794. } catch (\Exception $e) {
  9795. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9796. }
  9797. yield [
  9798. 'type' => 'done',
  9799. 'script' => [],
  9800. 'episode' => [],
  9801. 'answer' => $fullContent,
  9802. 'reasoning' => $fullReasoningContent,
  9803. 'usage' => $usage,
  9804. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  9805. ];
  9806. return;
  9807. }
  9808. // 验证成功,记录日志
  9809. if ($retry_count > 0) {
  9810. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  9811. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  9812. }
  9813. }
  9814. $table_data = [
  9815. 'user_id' => $uid,
  9816. 'model' => $model,
  9817. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  9818. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  9819. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  9820. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  9821. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  9822. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  9823. 'art_style_type' => $input_art_style,
  9824. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  9825. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  9826. 'status' => '解析完成',
  9827. 'generate_status' => '待执行',
  9828. 'updated_at' => date('Y-m-d H:i:s')
  9829. ];
  9830. if ($anime_name) $table_data['anime_name'] = $anime_name;
  9831. // 如果是修改集数,则将content内容更新(会改变原文)
  9832. if (isset($episode_count) && $episode_count > 0) {
  9833. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  9834. $table_data['start_episode_sequence'] = 1;
  9835. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  9836. }else {
  9837. // 如果需要生成原文内容,从script_arr中提取
  9838. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  9839. $table_data['content'] = $script_arr['content'];
  9840. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  9841. if (!$table_data['content']) {
  9842. yield [
  9843. 'type' => 'done',
  9844. 'script' => [],
  9845. 'episode' => [],
  9846. 'answer' => $fullContent,
  9847. 'reasoning' => $fullReasoningContent,
  9848. 'usage' => $usage,
  9849. 'error' => '未生成剧本内容,请调整提示词再试'
  9850. ];
  9851. return;
  9852. }
  9853. }
  9854. if (isset($table_data['content']) && $table_data['content']) {
  9855. $chapters = splitContent($table_data['content']);
  9856. $chapter_count = count($chapters);
  9857. if ($chapter_count > 0) {
  9858. $table_data['start_episode_sequence'] = 1;
  9859. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  9860. }
  9861. }
  9862. }
  9863. if ($extra_products) {
  9864. $table_data['extra_products'] = json_encode($extra_products, 256);
  9865. }
  9866. $single_episode = [];
  9867. try {
  9868. DB::beginTransaction();
  9869. $now = date('Y-m-d H:i:s');
  9870. // 更新动漫大纲
  9871. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  9872. if (!$boolen) {
  9873. dLog('deepseek')->info('对话修改失败', $table_data);
  9874. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  9875. Utils::throwError('20003:对话修改失败');
  9876. }
  9877. // 保存对话记录
  9878. $records = [
  9879. [
  9880. 'uid' => $uid,
  9881. 'anime_id' => $anime_id,
  9882. 'sequence' => 0,
  9883. 'role' => 'user',
  9884. 'content' => $prompt,
  9885. 'created_at' => $now,
  9886. 'updated_at' => $now
  9887. ],
  9888. [
  9889. 'uid' => $uid,
  9890. 'anime_id' => $anime_id,
  9891. 'sequence' => 0,
  9892. 'role' => 'assistant',
  9893. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  9894. 'content' => $fullContent,
  9895. 'created_at' => $now,
  9896. 'updated_at' => $now
  9897. ]
  9898. ];
  9899. // 保存对话记录
  9900. $boolen3 = DB::table('mp_anime_records')->insert($records);
  9901. if (!$boolen3) {
  9902. Utils::throwError('20003:对话记录保存失败');
  9903. }
  9904. // 单剧集模式:生成并保存剧集信息
  9905. if ($is_single) {
  9906. $anime_name = getProp($anime, 'anime_name', '未命名');
  9907. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  9908. if (empty($episode_arr['acts'])) {
  9909. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  9910. }
  9911. $saveResult = $this->saveEpisodeVersionData(
  9912. $anime_id,
  9913. 1,
  9914. $episode_arr,
  9915. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  9916. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  9917. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  9918. null,
  9919. null,
  9920. false,
  9921. $content,
  9922. $now,
  9923. $ref_products
  9924. );
  9925. $single_episode = $saveResult['episode'];
  9926. $episode_id = $saveResult['episode_id'];
  9927. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  9928. 'roles' => json_encode($saveResult['merged_roles'], 256),
  9929. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  9930. 'props' => json_encode($saveResult['merged_props'], 256),
  9931. 'updated_at' => $now
  9932. ]);
  9933. if ($boolen5 === false) {
  9934. Utils::throwError('20003:单剧集主表资源同步失败');
  9935. }
  9936. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  9937. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  9938. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  9939. $episode_record_content = '确认分镜大纲';
  9940. if ($content !== '') {
  9941. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  9942. }
  9943. $episode_records = [
  9944. [
  9945. 'uid' => $uid,
  9946. 'anime_id' => $anime_id,
  9947. 'role' => 'user',
  9948. 'content' => $episode_record_content,
  9949. 'sequence' => 1,
  9950. 'episode_id' => $episode_id,
  9951. 'created_at' => $now,
  9952. 'updated_at' => $now
  9953. ],
  9954. [
  9955. 'uid' => $uid,
  9956. 'anime_id' => $anime_id,
  9957. 'role' => 'assistant',
  9958. 'content' => $fullContent,
  9959. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  9960. 'sequence' => 1,
  9961. 'episode_id' => $episode_id,
  9962. 'created_at' => $now,
  9963. 'updated_at' => $now
  9964. ]
  9965. ];
  9966. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  9967. if (!$boolen4) {
  9968. Utils::throwError('20003:单剧集分镜记录保存失败');
  9969. }
  9970. }
  9971. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  9972. if ($is_single && !empty($single_episode)) {
  9973. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  9974. 'anime_id' => $anime_id,
  9975. 'episode_id' => $episode_id ?? 0,
  9976. 'model' => $model,
  9977. 'source' => 'reGenerateAnimeForAce',
  9978. ]);
  9979. }
  9980. }catch (\Exception $e) {
  9981. DB::rollBack();
  9982. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  9983. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  9984. yield [
  9985. 'type' => 'done',
  9986. 'answer' => $fullContent,
  9987. 'reasoning' => $fullReasoningContent,
  9988. 'usage' => $usage,
  9989. 'error' => $e->getMessage(),
  9990. ];
  9991. return;
  9992. }
  9993. DB::commit();
  9994. dLog('deepseek')->info('保存完毕');
  9995. if ($is_single && !empty($single_episode)) {
  9996. // $this->batchSetGlobalRoleImg([
  9997. // 'anime_id' => $anime_id,
  9998. // ]);
  9999. // $this->batchSetGlobalSceneImg([
  10000. // 'anime_id' => $anime_id,
  10001. // ]);
  10002. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  10003. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  10004. }
  10005. $table_data['anime_id'] = $anime_id;
  10006. $table_data['roles'] = json_decode($table_data['roles'], true);
  10007. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  10008. $table_data['props'] = json_decode($table_data['props'], true);
  10009. unset($table_data['updated_at']);
  10010. unset($table_data['status']);
  10011. yield [
  10012. 'type' => 'done',
  10013. 'script' => $table_data,
  10014. 'episode' => $single_episode,
  10015. 'answer' => $fullContent,
  10016. 'reasoning' => $fullReasoningContent,
  10017. 'usage' => $usage
  10018. ];
  10019. }
  10020. public function chatForAce($data) {
  10021. $uid = Site::getUid();
  10022. // 积分余额预检(不足直接报错)
  10023. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  10024. $anime_id = getProp($data, 'anime_id');
  10025. $file = getProp($data, 'file');
  10026. $content = getProp($data, 'content', '');
  10027. $bid = getProp($data, 'bid', 0);
  10028. $script_id = getProp($data, 'script_id', 0);
  10029. $episode_number = getProp($data, 'episode_number', 1);
  10030. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10031. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10032. if (!$anime) Utils::throwError('20003:该对话不存在!');
  10033. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  10034. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  10035. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  10036. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  10037. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  10038. $roles = is_array($roles) ? $roles : [];
  10039. $scenes = is_array($scenes) ? $scenes : [];
  10040. $extra_products = getProp($data, 'products', []);
  10041. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  10042. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  10043. $anime_script_id = getProp($anime, 'script_id');
  10044. if ($anime_script_id) {
  10045. $cpid = Site::getCpid();
  10046. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  10047. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  10048. ->where('mapping.script_id', $anime_script_id)
  10049. ->where('product.cpid', $cpid)
  10050. ->where('product.is_deleted', 0);
  10051. // 如果提供了 episode_number,则过滤指定集数
  10052. if ($episode_number !== null && $episode_number !== '') {
  10053. $script_products_mappings->where('mapping.episode_number', $episode_number);
  10054. }
  10055. $mappings = $script_products_mappings->select(
  10056. 'mapping.product_id',
  10057. 'mapping.episode_number',
  10058. 'product.product_name',
  10059. 'product.type',
  10060. 'product.product',
  10061. 'product.pic_prompt',
  10062. 'product.url',
  10063. 'product.pic_task_id',
  10064. 'product.pic_task_status',
  10065. 'product.three_view_image_url'
  10066. )
  10067. ->get();
  10068. // 按 product_id 分组,合并 episode_number
  10069. $productMap = [];
  10070. foreach ($mappings as $item) {
  10071. $product_id = $item->product_id;
  10072. $product_name = $item->product_name;
  10073. // 处理product_name两边的符号
  10074. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  10075. if (!isset($productMap[$product_id])) {
  10076. $productMap[$product_id] = [
  10077. 'product_id' => $product_id,
  10078. 'product_name' => $product_name,
  10079. 'type' => (int)$item->type,
  10080. 'product' => (int)$item->product,
  10081. 'pic_prompt' => $item->pic_prompt,
  10082. 'url' => $item->url,
  10083. 'three_view_image_url' => getProp($item, 'three_view_image_url', ''),
  10084. 'pic_task_id' => $item->pic_task_id,
  10085. 'pic_task_status' => $item->pic_task_status,
  10086. 'episode_numbers' => [],
  10087. ];
  10088. }
  10089. // 添加 episode_number(去重)
  10090. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  10091. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  10092. }
  10093. }
  10094. // 将查询到的剧本资产合并到extra_products中
  10095. // 先构建extra_products的索引(以product_id+episode_number为key)
  10096. $extraProductsMap = [];
  10097. foreach ($extra_products as $item) {
  10098. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  10099. $extraProductsMap[$key] = $item;
  10100. }
  10101. // 合并剧本资产(去重:product_id+episode_number)
  10102. foreach ($productMap as $product) {
  10103. foreach ($product['episode_numbers'] as $ep_num) {
  10104. $key = $product['product_id'] . '_' . $ep_num;
  10105. // 如果不存在则添加
  10106. if (!isset($extraProductsMap[$key])) {
  10107. $extraProductsMap[$key] = [
  10108. 'product_id' => $product['product_id'],
  10109. 'product_name' => $product['product_name'],
  10110. 'type' => $product['type'],
  10111. 'product' => $product['product'],
  10112. 'pic_prompt' => $product['pic_prompt'],
  10113. 'url' => $product['url'],
  10114. 'three_view_image_url' => getProp($product, 'three_view_image_url', ''),
  10115. 'pic_task_id' => $product['pic_task_id'],
  10116. 'pic_task_status' => $product['pic_task_status'],
  10117. 'episode_number' => $ep_num,
  10118. ];
  10119. }
  10120. }
  10121. }
  10122. // 重新赋值给extra_products
  10123. $extra_products = array_values($extraProductsMap);
  10124. }
  10125. // 处理提示词
  10126. if ($prompt && $extra_products) {
  10127. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  10128. foreach($extra_products as $item) {
  10129. $product_name = getProp($item, 'product_name');
  10130. if ($product_name) {
  10131. // 替换 {product_name} 为 product_name
  10132. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  10133. }
  10134. }
  10135. }
  10136. // 获取最后一集序号
  10137. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  10138. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  10139. // 转换主体列表和场景列表的格式
  10140. // 获取参考主体或场景
  10141. if ((int)$episode_number === 1) {
  10142. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  10143. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  10144. }else {
  10145. $prev_episode_number = $episode_number - 1;
  10146. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  10147. }
  10148. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  10149. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  10150. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  10151. // 合并anime_products和extra_products(extra_products优先,去重)
  10152. $anime_products = getProp($anime, 'extra_products');
  10153. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  10154. $ref_products = [];
  10155. foreach($anime_products as $item) {
  10156. $product_name = getProp($item, 'product_name');
  10157. $ref_products[$product_name] = $item;
  10158. }
  10159. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  10160. $extra_roles = []; // 从extra_products中提取的角色
  10161. $extra_scenes = []; // 从extra_products中提取的场景
  10162. $extra_props = []; // 从extra_products中提取的道具
  10163. if ($extra_products && is_array($extra_products)) {
  10164. foreach($extra_products as $item) {
  10165. $product = (int)getProp($item, 'product');
  10166. $product_name = getProp($item, 'product_name');
  10167. if ($product_name == '旁白') continue;
  10168. $pic_prompt = getProp($item, 'pic_prompt');
  10169. $ref_products[$product_name] = $item;
  10170. if ($product === 1) {
  10171. // 角色
  10172. $extra_roles[$product_name] = [
  10173. 'role' => $product_name,
  10174. 'pic_prompt' => $pic_prompt,
  10175. 'url' => getProp($item, 'url', ''),
  10176. ];
  10177. } elseif ($product === 2) {
  10178. // 场景
  10179. $extra_scenes[$product_name] = [
  10180. 'scene' => $product_name,
  10181. 'pic_prompt' => $pic_prompt,
  10182. 'url' => getProp($item, 'url', ''),
  10183. ];
  10184. } elseif ($product === 3) {
  10185. // 道具
  10186. $extra_props[$product_name] = [
  10187. 'prop' => $product_name,
  10188. 'pic_prompt' => $pic_prompt,
  10189. 'url' => getProp($item, 'url', ''),
  10190. ];
  10191. }
  10192. }
  10193. }
  10194. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  10195. $merged_roles = [];
  10196. foreach($ref_roles as $role) {
  10197. $role_name = getProp($role, 'role');
  10198. if (!isset($extra_roles[$role_name])) {
  10199. $merged_roles[$role_name] = $role;
  10200. }
  10201. }
  10202. // 添加extra_roles
  10203. foreach($extra_roles as $role_name => $role) {
  10204. $merged_roles[$role_name] = $role;
  10205. }
  10206. $ref_roles = array_values($merged_roles);
  10207. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  10208. $merged_scenes = [];
  10209. foreach($ref_scenes as $scene) {
  10210. $scene_name = getProp($scene, 'scene');
  10211. if (!isset($extra_scenes[$scene_name])) {
  10212. $merged_scenes[$scene_name] = $scene;
  10213. }
  10214. }
  10215. // 添加extra_scenes
  10216. foreach($extra_scenes as $scene_name => $scene) {
  10217. $merged_scenes[$scene_name] = $scene;
  10218. }
  10219. $ref_scenes = array_values($merged_scenes);
  10220. // 合并ref_props和extra_props(extra_props优先,去重)
  10221. $merged_props = [];
  10222. foreach($ref_props as $prop) {
  10223. $prop_name = getProp($prop, 'prop');
  10224. if (!isset($extra_props[$prop_name])) {
  10225. $merged_props[$prop_name] = $prop;
  10226. }
  10227. }
  10228. // 添加extra_props
  10229. foreach($extra_props as $prop_name => $prop) {
  10230. $merged_props[$prop_name] = $prop;
  10231. }
  10232. $ref_props = array_values($merged_props);
  10233. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  10234. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  10235. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  10236. // 构建强制主体、场景和道具提示词
  10237. $forced_roles_prompt = "";
  10238. $forced_scenes_prompt = "";
  10239. $forced_props_prompt = "";
  10240. if (!empty($extra_roles)) {
  10241. $forced_roles_list = "";
  10242. foreach($extra_roles as $role_name => $role) {
  10243. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  10244. }
  10245. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  10246. }
  10247. if (!empty($extra_scenes)) {
  10248. $forced_scenes_list = "";
  10249. foreach($extra_scenes as $scene_name => $scene) {
  10250. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  10251. }
  10252. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  10253. }
  10254. if (!empty($extra_props)) {
  10255. $forced_props_list = "";
  10256. foreach($extra_props as $prop_name => $prop) {
  10257. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  10258. }
  10259. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  10260. }
  10261. if ($anime_script_id) {
  10262. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  10263. }else if ($roles_content) {
  10264. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  10265. 主体范围:\n {$roles_content}\n
  10266. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  10267. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  10268. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  10269. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  10270. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  10271. }else {
  10272. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  10273. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  10274. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  10275. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  10276. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  10277. }
  10278. if ($anime_script_id) {
  10279. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  10280. }else if ($scenes_content) {
  10281. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  10282. 场景范围:\n {$scenes_content}\n
  10283. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  10284. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  10285. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  10286. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  10287. }else {
  10288. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  10289. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  10290. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  10291. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  10292. }
  10293. if ($anime_script_id) {
  10294. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  10295. }else if ($props_content) {
  10296. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  10297. 道具范围:\n {$props_content}\n
  10298. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  10299. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  10300. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  10301. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  10302. }else {
  10303. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  10304. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  10305. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  10306. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  10307. }
  10308. // 提取文件内容
  10309. if ($file) {
  10310. $uploaded_content = $this->extractFileContent($file);
  10311. if (!$uploaded_content) {
  10312. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  10313. }
  10314. } elseif ($script_id) {
  10315. $uploaded_content = $this->getContentByScriptId($script_id);
  10316. if (!$uploaded_content) {
  10317. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  10318. }
  10319. } elseif ($bid) {
  10320. $uploaded_content = $this->getContentByBid($bid);
  10321. if (!$uploaded_content) {
  10322. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  10323. }
  10324. } elseif ($content) {
  10325. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  10326. }
  10327. // elseif ($prompt) {
  10328. // $uploaded_content = filterContent($prompt);
  10329. // }
  10330. else {
  10331. $uploaded_content = '';
  10332. }
  10333. // 美术风格
  10334. $input_art_style = getProp($data, 'art_style');
  10335. if (!$input_art_style) {
  10336. $mappedArtStyle = getProp($anime, 'art_style');
  10337. }else {
  10338. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  10339. }
  10340. if (!$mappedArtStyle) {
  10341. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  10342. }else {
  10343. if (strstr($mappedArtStyle, '基础画风风格词')) {
  10344. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  10345. }else {
  10346. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  10347. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  10348. }
  10349. }
  10350. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10351. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  10352. // 强制要求:
  10353. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  10354. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  10355. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  10356. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  10357. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  10358. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  10359. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  10360. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  10361. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  10362. // 10.分镜要和场景列表、人物主体保持一致\n
  10363. // 普通要求:
  10364. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  10365. // {$role_demo}
  10366. // {$scene_demo}
  10367. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10368. // 4.1片段分割逻辑(优先级从高到低):
  10369. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10370. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10371. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10372. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10373. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10374. // - 片段数量格式为: 片段数量:8
  10375. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10376. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10377. // 4.3分镜结构:每个分镜包含以下字段:
  10378. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  10379. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  10380. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10381. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  10382. // - 运镜:场景+画面描述+运镜
  10383. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  10384. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10385. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10386. // 5.$mappedArtStyle_prompt\n\n
  10387. // 示例格式:\n
  10388. // 第1集:隐形的守护者
  10389. // ###故事梗概
  10390. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10391. // ###美术风格
  10392. // 基础画风风格词:胡金铨武侠
  10393. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10394. // ###主体列表
  10395. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10396. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10397. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10398. // ###场景列表
  10399. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10400. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10401. // ###分段剧本
  10402. // 片段数量:8
  10403. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10404. // ##片段1
  10405. // 时长:12s
  10406. // 分镜1
  10407. // 场景:边境小镇街道
  10408. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10409. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10410. // 配音台词:
  10411. // 背景音效:
  10412. // 分镜2
  10413. // 场景:悦来酒馆
  10414. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10415. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10416. // 配音台词:
  10417. // 背景音效:
  10418. // 分镜3
  10419. // 场景:悦来酒馆
  10420. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10421. // 运镜:从中景推向令牌特写。
  10422. // 配音台词:
  10423. // 背景音效:
  10424. // 分镜4
  10425. // 场景:悦来酒馆
  10426. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10427. // 运镜:极速推向酒水溅起的瞬间。
  10428. // 配音台词:
  10429. // 背景音效:
  10430. // 分镜5
  10431. // 镜头描述
  10432. // 场景:悦来酒馆
  10433. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10434. // 运镜:固定机位,利用倾斜构图制造压迫感。
  10435. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10436. // 背景音效:
  10437. // \n\n";
  10438. /*
  10439. // ====== 旧版 $demo(缓存优化前版本,动态数据内嵌在规则中间) ======
  10440. // 如需换回:删除下方新版 $demo,并把本块恢复为活动代码(去掉首尾注释标记)
  10441. // ===================================================================
  10442. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  10443. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  10444. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  10445. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  10446. 强制要求:
  10447. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  10448. 普通要求:
  10449. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  10450. {$role_demo}
  10451. {$scene_demo}
  10452. {$prop_demo}
  10453. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10454. 5.1片段分割逻辑(优先级从高到低):
  10455. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10456. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10457. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10458. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10459. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10460. - 片段数量格式为: 片段数量:8
  10461. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10462. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10463. 5.3分镜结构:每个分镜包含以下字段:
  10464. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  10465. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10466. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10467. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10468. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10469. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10470. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10471. - 运镜:场景+画面描述+运镜
  10472. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  10473. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  10474. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10475. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10476. 6.《情绪-视听语言映射表》:
  10477. 6.1 场景空间与时间心理学 (Scene & Temporality)
  10478. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10479. -----|---------|------------|----------------
  10480. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  10481. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  10482. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  10483. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  10484. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  10485. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10486. -----|---------|------------|----------------
  10487. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  10488. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  10489. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  10490. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  10491. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  10492. --------|---------|--------------|-------------
  10493. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  10494. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  10495. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  10496. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  10497. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  10498. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  10499. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  10500. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  10501. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  10502. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  10503. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  10504. -----|---------|------------|------------
  10505. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  10506. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  10507. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  10508. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  10509. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  10510. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  10511. --------|---------|--------------|----------
  10512. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  10513. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  10514. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  10515. 6.6 声音设计与潜意识影响 (Soundscape)
  10516. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  10517. -----|---------|------------|------------------
  10518. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  10519. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  10520. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  10521. 理论基石:
  10522. - The Five C's of Cinematography by Joseph V. Mascelli
  10523. - Film Art: An Introduction by David Bordwell
  10524. - Sight, Sound, Motion by Herbert Zettl
  10525. - Notes on the Cinematograph by Robert Bresson
  10526. \n\n
  10527. 7.{$mappedArtStyle_prompt}
  10528. 示例格式:\n
  10529. 第1集:隐形的守护者
  10530. ###故事梗概
  10531. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10532. ###美术风格
  10533. 基础画风风格词:胡金铨武侠
  10534. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10535. ###主体列表
  10536. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10537. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10538. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10539. ###场景列表
  10540. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10541. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10542. ###道具列表
  10543. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  10544. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  10545. ###分段剧本
  10546. 片段数量:8
  10547. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10548. ##片段1
  10549. 时长:12s
  10550. 分镜1
  10551. 出场角色:刀疤脸
  10552. 场景:边境小镇街道
  10553. 出场道具:酒杯-高脚杯
  10554. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10555. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10556. 配音台词:
  10557. 背景音效:
  10558. 分镜2
  10559. 出场角色:刀疤脸
  10560. 场景:悦来酒馆
  10561. 出场道具:酒杯-高脚杯
  10562. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10563. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10564. 配音台词:
  10565. 背景音效:
  10566. 分镜3
  10567. 出场角色:刀疤脸
  10568. 场景:悦来酒馆
  10569. 出场道具:酒杯-高脚杯
  10570. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10571. 运镜:从中景推向令牌特写。
  10572. 配音台词:
  10573. 背景音效:
  10574. 分镜4
  10575. 出场角色:刀疤脸
  10576. 场景:悦来酒馆
  10577. 出场道具:酒杯-高脚杯
  10578. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10579. 运镜:极速推向酒水溅起的瞬间。
  10580. 配音台词:
  10581. 背景音效:
  10582. 分镜5
  10583. 出场角色:刀疤脸
  10584. 场景:悦来酒馆
  10585. 出场道具:酒杯-高脚杯
  10586. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10587. 运镜:固定机位,利用倾斜构图制造压迫感。
  10588. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10589. 背景音效:
  10590. \n\n";
  10591. */
  10592. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  10593. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  10594. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  10595. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  10596. 强制要求:
  10597. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  10598. 普通要求:
  10599. 1.剧集标题必须与文档内容高度相关,剧集序号见文末【本次剧集信息】。
  10600. 2.<主体列表>的详细规则和可选范围见文末【本次生成数据-主体列表】。
  10601. 3.<场景列表>的详细规则和可选范围见文末【本次生成数据-场景列表】。
  10602. 4.<道具列表>的详细规则和可选范围见文末【本次生成数据-道具列表】。
  10603. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  10604. 5.1片段分割逻辑(优先级从高到低):
  10605. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  10606. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  10607. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  10608. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  10609. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  10610. - 片段数量格式为: 片段数量:8
  10611. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  10612. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  10613. 5.3分镜结构:每个分镜包含以下字段:
  10614. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  10615. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  10616. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10617. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10618. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10619. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  10620. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10621. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  10622. - 运镜:场景+画面描述+运镜
  10623. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  10624. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  10625. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  10626. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  10627. 6.《情绪-视听语言映射表》:
  10628. 6.1 场景空间与时间心理学 (Scene & Temporality)
  10629. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10630. -----|---------|------------|----------------
  10631. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  10632. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  10633. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  10634. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  10635. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  10636. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  10637. -----|---------|------------|----------------
  10638. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  10639. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  10640. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  10641. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  10642. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  10643. --------|---------|--------------|-------------
  10644. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  10645. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  10646. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  10647. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  10648. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  10649. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  10650. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  10651. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  10652. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  10653. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  10654. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  10655. -----|---------|------------|------------
  10656. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  10657. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  10658. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  10659. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  10660. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  10661. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  10662. --------|---------|--------------|----------
  10663. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  10664. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  10665. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  10666. 6.6 声音设计与潜意识影响 (Soundscape)
  10667. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  10668. -----|---------|------------|------------------
  10669. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  10670. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  10671. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  10672. 理论基石:
  10673. - The Five C's of Cinematography by Joseph V. Mascelli
  10674. - Film Art: An Introduction by David Bordwell
  10675. - Sight, Sound, Motion by Herbert Zettl
  10676. - Notes on the Cinematograph by Robert Bresson
  10677. \n\n
  10678. 7.美术风格要求见文末【本次生成数据-美术风格】。
  10679. 示例格式:\n
  10680. 第1集:隐形的守护者
  10681. ###故事梗概
  10682. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  10683. ###美术风格
  10684. 基础画风风格词:胡金铨武侠
  10685. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  10686. ###主体列表
  10687. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  10688. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  10689. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  10690. ###场景列表
  10691. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  10692. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  10693. ###道具列表
  10694. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  10695. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  10696. ###分段剧本
  10697. 片段数量:8
  10698. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10699. ##片段1
  10700. 时长:12s
  10701. 分镜1
  10702. 出场角色:刀疤脸
  10703. 场景:边境小镇街道
  10704. 出场道具:酒杯-高脚杯
  10705. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10706. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10707. 配音台词:
  10708. 背景音效:
  10709. 分镜2
  10710. 出场角色:刀疤脸
  10711. 场景:悦来酒馆
  10712. 出场道具:酒杯-高脚杯
  10713. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10714. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10715. 配音台词:
  10716. 背景音效:
  10717. 分镜3
  10718. 出场角色:刀疤脸
  10719. 场景:悦来酒馆
  10720. 出场道具:酒杯-高脚杯
  10721. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10722. 运镜:从中景推向令牌特写。
  10723. 配音台词:
  10724. 背景音效:
  10725. 分镜4
  10726. 出场角色:刀疤脸
  10727. 场景:悦来酒馆
  10728. 出场道具:酒杯-高脚杯
  10729. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10730. 运镜:极速推向酒水溅起的瞬间。
  10731. 配音台词:
  10732. 背景音效:
  10733. 分镜5
  10734. 出场角色:刀疤脸
  10735. 场景:悦来酒馆
  10736. 出场道具:酒杯-高脚杯
  10737. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10738. 运镜:固定机位,利用倾斜构图制造压迫感。
  10739. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10740. 背景音效:
  10741. \n\n本次生成数据(以上规则的动态数据均在此处,优先级等同对应编号规则):
  10742. 【本次剧集信息】剧集序号是{$episode_number}。
  10743. 【本次生成数据-主体列表】{$role_demo}
  10744. 【本次生成数据-场景列表】{$scene_demo}
  10745. 【本次生成数据-道具列表】{$prop_demo}
  10746. 【本次生成数据-美术风格】{$mappedArtStyle_prompt}
  10747. \n\n";
  10748. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  10749. // 所有提示词统一走版本化:确认分镜大纲/继续策划下一集也创建新分集,不覆盖本分集
  10750. // $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  10751. $is_regenerate_version = true;
  10752. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  10753. $prompt = $origin_prompt;
  10754. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  10755. // 获取章节内容
  10756. $full_content = getProp($anime, 'content');
  10757. if ($uploaded_content) {
  10758. $full_content = $uploaded_content;
  10759. }
  10760. // 根据章节内容拆分章节
  10761. $chapters = splitContent($full_content);
  10762. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  10763. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  10764. $messages = [];
  10765. if ($prompt == '确认分镜大纲') {
  10766. // 暂时保留
  10767. $content = $chapter_content;
  10768. if ($is_single) $content = $full_content; // 单剧集使用全文
  10769. if (!$content) {
  10770. Utils::throwError('20003:章节内容无法获取,请确认');
  10771. }
  10772. $question = $is_single
  10773. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  10774. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  10775. // 构建消息
  10776. $messages[] =
  10777. [
  10778. 'role' => 'user',
  10779. 'content' => $question
  10780. ];
  10781. }else if ($prompt == '继续策划下一集') {
  10782. if ($is_single) {
  10783. Utils::throwError('20003:单剧集不支持继续策划下一集');
  10784. }
  10785. $content = $chapter_content;
  10786. if (!$content) {
  10787. Utils::throwError('20003:章节内容无法获取,请确认');
  10788. }
  10789. // 获取上一集最后记录
  10790. $prev_sequence = $episode_number - 1;
  10791. $messages = array_merge(
  10792. [
  10793. [
  10794. 'role' => 'system',
  10795. 'content' => $demo
  10796. ]
  10797. ],
  10798. $this->getEpisodeChatContent($anime_id, $prev_sequence, $content)
  10799. );
  10800. // 构建消息
  10801. $messages[] =
  10802. [
  10803. 'role' => 'user',
  10804. 'content' => "请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)"
  10805. ];
  10806. /*
  10807. // 旧版逻辑
  10808. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  10809. // 构建消息
  10810. $messages[] =
  10811. [
  10812. 'role' => 'user',
  10813. 'content' => $question
  10814. ];
  10815. */
  10816. // dd($messages);
  10817. }else {
  10818. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  10819. if (!$content) {
  10820. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  10821. }
  10822. if (!$content) {
  10823. Utils::throwError('20003:章节内容无法获取,请确认');
  10824. }
  10825. $messages = array_merge(
  10826. [
  10827. [
  10828. 'role' => 'system',
  10829. 'content' => $demo
  10830. ]
  10831. ],
  10832. $this->getEpisodeChatMessages($anime_id, $episode_number)
  10833. );
  10834. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  10835. $question = "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  10836. if ($origin_prompt) {
  10837. $question .= "本次修改要求如下:\n{$origin_prompt}";
  10838. }
  10839. // 将本集原文加入消息,供模型逐字摘录原文台词(修复重新生成时配音台词全部为"无"的问题)
  10840. $messages[] = [
  10841. 'role' => 'user',
  10842. 'content' => "本集剧情内容:\n\n{$content}\n"
  10843. ];
  10844. $messages[] =
  10845. [
  10846. 'role' => 'user',
  10847. 'content' => $question
  10848. ];
  10849. }
  10850. // 处理文本模型
  10851. $model = getProp($data, 'model');
  10852. if (!$model) {
  10853. // 用户没有输入,从anime表获取
  10854. $model = getProp($anime, 'model');
  10855. if (!$model) {
  10856. // anime表也没有,使用默认值
  10857. $model = 'deepseek-v4-pro';
  10858. }
  10859. }
  10860. // 验证模型是否在可用模型表中
  10861. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10862. $model = 'deepseek-v4-pro';
  10863. }
  10864. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  10865. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  10866. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  10867. if ($model === 'deepseek-chat') {
  10868. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  10869. $model = 'deepseek-v4-flash';
  10870. $thinkingMode = 'disabled';
  10871. } elseif ($model === 'deepseek-reasoner') {
  10872. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  10873. $model = 'deepseek-v4-flash';
  10874. $thinkingMode = 'enabled';
  10875. }
  10876. $post_data = [
  10877. 'model' => $model,
  10878. 'messages' => $messages,
  10879. // 'max_tokens' => 8192,
  10880. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  10881. 'frequency_penalty' => 0,
  10882. 'presence_penalty' => 0,
  10883. 'response_format' => ['type' => 'text'],
  10884. 'thinking' => ['type' => $thinkingMode],
  10885. 'stream' => true // 启用流式输出
  10886. ];
  10887. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  10888. // 根据模型类型选择调用方法
  10889. $fullContent = '';
  10890. $fullReasoningContent = '';
  10891. $usage = [];
  10892. try {
  10893. $streamGenerator = $this->dispatchStreamByModel($post_data);
  10894. // 验证返回值类型
  10895. if (!is_iterable($streamGenerator)) {
  10896. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  10897. dLog('deepseek')->error('chat流式生成器无效', [
  10898. 'generator_type' => $errorType,
  10899. 'model' => $model,
  10900. 'anime_id' => $anime_id,
  10901. 'episode_number' => $episode_number
  10902. ]);
  10903. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  10904. 'type' => $errorType,
  10905. 'model' => $model
  10906. ]);
  10907. yield [
  10908. 'type' => 'error',
  10909. 'episode' => [],
  10910. 'answer' => '',
  10911. 'reasoning' => '',
  10912. 'usage' => [],
  10913. 'error' => '接口返回数据异常,请重新请求'
  10914. ];
  10915. return;
  10916. }
  10917. // 处理流式输出
  10918. foreach ($streamGenerator as $chunk) {
  10919. if (isset($chunk['type'])) {
  10920. if ($chunk['type'] === 'done') {
  10921. // 最终结果
  10922. $fullContent = $chunk['full_content'];
  10923. $fullReasoningContent = $chunk['full_reasoning'];
  10924. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  10925. } else {
  10926. // 逐块yield数据
  10927. yield $chunk;
  10928. }
  10929. }
  10930. }
  10931. } catch (\Exception $e) {
  10932. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  10933. 'model' => $model,
  10934. 'anime_id' => $anime_id,
  10935. 'episode_number' => $episode_number,
  10936. 'trace' => $e->getTraceAsString()
  10937. ]);
  10938. logDB('deepseek', 'error', 'chat流式处理失败', [
  10939. 'error' => $e->getMessage(),
  10940. 'model' => $model
  10941. ]);
  10942. yield [
  10943. 'type' => 'error',
  10944. 'episode' => [],
  10945. 'answer' => '',
  10946. 'reasoning' => '',
  10947. 'usage' => [],
  10948. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  10949. ];
  10950. return;
  10951. }
  10952. // 兼容模型偶发将整段正文包裹成 JSON 字符串返回
  10953. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  10954. dLog('deepseek')->info('完整内容: '.$fullContent);
  10955. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  10956. // 处理完整内容并返回最终结果
  10957. $episode_arr = handleEpisodeContentForAce($fullContent);
  10958. dLog('deepseek')->info('解析内容: ', $episode_arr);
  10959. logDB('deepseek', 'info', '解析内容', $episode_arr);
  10960. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  10961. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  10962. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  10963. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  10964. // }
  10965. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  10966. $max_retries = 3;
  10967. $retry_count = 0;
  10968. $validation_failed = false;
  10969. $validation_error_msg = '';
  10970. // 验证生成的内容
  10971. if ($anime_script_id) {
  10972. // 检查是否有acts数据
  10973. if (empty($episode_arr['acts'])) {
  10974. $validation_failed = true;
  10975. $validation_error_msg = '未生成分镜剧本相关的内容';
  10976. } else {
  10977. // 校验主体列表:不能为空主体(旁白不算)
  10978. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  10979. // 过滤掉"旁白"角色
  10980. $generated_roles = array_filter($generated_roles, function($role) {
  10981. return $role !== '旁白';
  10982. });
  10983. if (empty($generated_roles)) {
  10984. $validation_failed = true;
  10985. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  10986. }
  10987. // 仅当存在强制主体设定时校验主体列表
  10988. if (!$validation_failed && !empty($extra_roles)) {
  10989. $expected_roles = array_keys($extra_roles);
  10990. // 找出生成的主体中不在预期列表中的主体
  10991. $invalid_roles = array_diff($generated_roles, $expected_roles);
  10992. if (!empty($invalid_roles)) {
  10993. $validation_failed = true;
  10994. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  10995. }
  10996. }
  10997. // 仅当存在强制场景设定时校验场景列表
  10998. if (!$validation_failed && !empty($extra_scenes)) {
  10999. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  11000. $expected_scenes = array_keys($extra_scenes);
  11001. // 找出生成的场景中不在预期列表中的场景
  11002. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  11003. if (!empty($invalid_scenes)) {
  11004. $validation_failed = true;
  11005. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  11006. }
  11007. }
  11008. // 仅当存在强制道具设定时校验道具列表
  11009. if (!$validation_failed && !empty($extra_props)) {
  11010. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  11011. $expected_props = array_keys($extra_props);
  11012. // 找出生成的道具中不在预期列表中的道具
  11013. $invalid_props = array_diff($generated_props, $expected_props);
  11014. if (!empty($invalid_props)) {
  11015. $validation_failed = true;
  11016. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  11017. }
  11018. }
  11019. }
  11020. } else {
  11021. // 如果没有anime_script_id,只检查是否有acts数据
  11022. if (empty($episode_arr['acts'])) {
  11023. $validation_failed = true;
  11024. $validation_error_msg = '未生成分镜剧本相关的内容';
  11025. } else {
  11026. // 校验主体列表:不能为空主体(旁白不算)
  11027. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11028. // 过滤掉"旁白"角色
  11029. $generated_roles = array_filter($generated_roles, function($role) {
  11030. return $role !== '旁白';
  11031. });
  11032. if (empty($generated_roles)) {
  11033. $validation_failed = true;
  11034. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11035. }
  11036. }
  11037. }
  11038. // 重试逻辑
  11039. while ($validation_failed && $retry_count < $max_retries) {
  11040. $retry_count++;
  11041. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  11042. 'reason' => $validation_error_msg,
  11043. 'anime_id' => $anime_id,
  11044. 'episode_number' => $episode_number
  11045. ]);
  11046. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  11047. 'reason' => $validation_error_msg,
  11048. 'anime_id' => $anime_id
  11049. ]);
  11050. // 发送流式重试提示
  11051. yield [
  11052. 'type' => 'retry',
  11053. 'retry_count' => $retry_count,
  11054. 'reason' => $validation_error_msg
  11055. ];
  11056. // 构建重试提示词
  11057. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  11058. if ($anime_script_id) {
  11059. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  11060. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  11061. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  11062. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  11063. } else {
  11064. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  11065. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  11066. }
  11067. // 添加重试消息到messages
  11068. $messages[] = [
  11069. 'role' => 'assistant',
  11070. 'content' => $fullContent
  11071. ];
  11072. $messages[] = [
  11073. 'role' => 'user',
  11074. 'content' => $retry_prompt
  11075. ];
  11076. // 更新post_data的messages
  11077. $post_data['messages'] = $messages;
  11078. // 重新调用API
  11079. try {
  11080. $streamGenerator = $this->dispatchStreamByModel($post_data);
  11081. // 处理流式输出
  11082. $fullContent = '';
  11083. $fullReasoningContent = '';
  11084. foreach ($streamGenerator as $chunk) {
  11085. if (isset($chunk['type'])) {
  11086. if ($chunk['type'] === 'done') {
  11087. $fullContent = $chunk['full_content'];
  11088. $fullReasoningContent = $chunk['full_reasoning'];
  11089. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  11090. } else {
  11091. yield $chunk;
  11092. }
  11093. }
  11094. }
  11095. // 重新解析内容
  11096. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  11097. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  11098. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  11099. $episode_arr = handleEpisodeContentForAce($fullContent);
  11100. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  11101. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  11102. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  11103. // }
  11104. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  11105. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  11106. // 重新验证
  11107. $validation_failed = false;
  11108. $validation_error_msg = '';
  11109. if ($anime_script_id) {
  11110. if (empty($episode_arr['acts'])) {
  11111. $validation_failed = true;
  11112. $validation_error_msg = '未生成分镜剧本相关的内容';
  11113. } else {
  11114. // 校验主体列表:不能为空主体(旁白不算)
  11115. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11116. // 过滤掉"旁白"角色
  11117. $generated_roles = array_filter($generated_roles, function($role) {
  11118. return $role !== '旁白';
  11119. });
  11120. if (empty($generated_roles)) {
  11121. $validation_failed = true;
  11122. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11123. }
  11124. // 仅当存在强制主体设定时校验主体列表
  11125. if (!$validation_failed && !empty($extra_roles)) {
  11126. $expected_roles = array_keys($extra_roles);
  11127. $invalid_roles = array_diff($generated_roles, $expected_roles);
  11128. if (!empty($invalid_roles)) {
  11129. $validation_failed = true;
  11130. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  11131. }
  11132. }
  11133. // 仅当存在强制场景设定时校验场景列表
  11134. if (!$validation_failed && !empty($extra_scenes)) {
  11135. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  11136. $expected_scenes = array_keys($extra_scenes);
  11137. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  11138. if (!empty($invalid_scenes)) {
  11139. $validation_failed = true;
  11140. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  11141. }
  11142. }
  11143. // 仅当存在强制道具设定时校验道具列表
  11144. if (!$validation_failed && !empty($extra_props)) {
  11145. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  11146. $expected_props = array_keys($extra_props);
  11147. $invalid_props = array_diff($generated_props, $expected_props);
  11148. if (!empty($invalid_props)) {
  11149. $validation_failed = true;
  11150. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  11151. }
  11152. }
  11153. }
  11154. } else {
  11155. if (empty($episode_arr['acts'])) {
  11156. $validation_failed = true;
  11157. $validation_error_msg = '未生成分镜剧本相关的内容';
  11158. } else {
  11159. // 校验主体列表:不能为空主体(旁白不算)
  11160. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  11161. // 过滤掉"旁白"角色
  11162. $generated_roles = array_filter($generated_roles, function($role) {
  11163. return $role !== '旁白';
  11164. });
  11165. if (empty($generated_roles)) {
  11166. $validation_failed = true;
  11167. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  11168. }
  11169. }
  11170. }
  11171. } catch (\Exception $e) {
  11172. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  11173. 'trace' => $e->getTraceAsString()
  11174. ]);
  11175. break;
  11176. }
  11177. }
  11178. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  11179. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  11180. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  11181. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  11182. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  11183. if ($validation_failed && $retry_count >= $max_retries) {
  11184. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  11185. 'retry_count' => $retry_count,
  11186. 'last_error' => $validation_error_msg
  11187. ]);
  11188. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  11189. 'error' => $validation_error_msg,
  11190. 'anime_id' => $anime_id
  11191. ]);
  11192. $validation_failed = false;
  11193. $validation_error_msg = '';
  11194. }
  11195. // 如果重试后仍然失败
  11196. if ($validation_failed) {
  11197. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  11198. 'retry_count' => $retry_count,
  11199. 'last_error' => $validation_error_msg
  11200. ]);
  11201. try {
  11202. $now = date('Y-m-d H:i:s');
  11203. $records = [
  11204. [
  11205. 'uid' => $uid,
  11206. 'anime_id' => $anime_id,
  11207. 'sequence' => $episode_number,
  11208. 'role' => 'user',
  11209. 'content' => $prompt,
  11210. 'created_at' => $now,
  11211. 'updated_at' => $now
  11212. ],
  11213. [
  11214. 'uid' => $uid,
  11215. 'anime_id' => $anime_id,
  11216. 'sequence' => $episode_number,
  11217. 'role' => 'assistant',
  11218. 'content' => $fullContent,
  11219. 'created_at' => $now,
  11220. 'updated_at' => $now
  11221. ]
  11222. ];
  11223. DB::table('mp_anime_records')->insert($records);
  11224. } catch (\Exception $e) {
  11225. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  11226. }
  11227. yield [
  11228. 'type' => 'done',
  11229. 'episode' => [],
  11230. 'answer' => $fullContent,
  11231. 'reasoning' => $fullReasoningContent,
  11232. 'usage' => $usage,
  11233. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  11234. ];
  11235. return;
  11236. }
  11237. // 验证成功,记录日志
  11238. if ($retry_count > 0) {
  11239. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  11240. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  11241. }
  11242. // 老逻辑
  11243. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  11244. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  11245. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  11246. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  11247. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  11248. $existing_props = is_array($existing_props) ? $existing_props : [];
  11249. $now = date('Y-m-d H:i:s');
  11250. try {
  11251. DB::beginTransaction();
  11252. $saveResult = $this->saveEpisodeVersionData(
  11253. $anime_id,
  11254. $episode_number,
  11255. $episode_arr,
  11256. $existing_roles,
  11257. $existing_scenes,
  11258. $existing_props,
  11259. $current_episode,
  11260. $base_episode,
  11261. $is_regenerate_version,
  11262. $content,
  11263. $now,
  11264. $ref_products
  11265. );
  11266. $episode = $saveResult['episode'];
  11267. $episode_id = $saveResult['episode_id'];
  11268. $merged_roles = $saveResult['merged_roles'];
  11269. $merged_scenes = $saveResult['merged_scenes'];
  11270. $merged_props = $saveResult['merged_props'];
  11271. $record_content = $origin_prompt;
  11272. if ($uploaded_content !== '') {
  11273. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  11274. }
  11275. $records = [
  11276. [
  11277. 'uid' => $uid,
  11278. 'anime_id' => $anime_id,
  11279. 'role' => 'user',
  11280. 'content' => $record_content,
  11281. 'sequence' => $episode_number,
  11282. 'episode_id' => $episode_id,
  11283. 'created_at' => $now,
  11284. 'updated_at' => $now
  11285. ],
  11286. [
  11287. 'uid' => $uid,
  11288. 'anime_id' => $anime_id,
  11289. 'role' => 'assistant',
  11290. 'content' => $fullContent,
  11291. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  11292. 'sequence' => $episode_number,
  11293. 'episode_id' => $episode_id,
  11294. 'created_at' => $now,
  11295. 'updated_at' => $now
  11296. ]
  11297. ];
  11298. $boolen4 = DB::table('mp_anime_records')->insert($records);
  11299. if (!$boolen4) {
  11300. Utils::throwError('20003:对话记录保存失败');
  11301. }
  11302. // 保存模型到anime表
  11303. $update_anime_data = [
  11304. 'model' => $model,
  11305. 'updated_at' => $now
  11306. ];
  11307. if ($uploaded_content) {
  11308. $update_anime_data['content'] = $uploaded_content;
  11309. }
  11310. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  11311. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  11312. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  11313. 'anime_id' => $anime_id,
  11314. 'episode_number' => $episode_number,
  11315. 'model' => $model,
  11316. 'source' => 'chatForAce',
  11317. ]);
  11318. }catch (\Exception $e) {
  11319. DB::rollBack();
  11320. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  11321. yield [
  11322. 'type' => 'done',
  11323. 'answer' => $fullContent,
  11324. 'reasoning' => $fullReasoningContent,
  11325. 'usage' => $usage,
  11326. 'error' => $e->getMessage(),
  11327. ];
  11328. return;
  11329. }
  11330. DB::commit();
  11331. if ($is_global_generate_pics) {
  11332. // // 批量生成全局角色图片
  11333. // $this->batchSetGlobalRoleImg([
  11334. // 'anime_id' => $anime_id,
  11335. // ], true);
  11336. // // 批量生成全局场景图片
  11337. // $this->batchSetGlobalSceneImg([
  11338. // 'anime_id' => $anime_id,
  11339. // ], true);
  11340. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  11341. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  11342. }
  11343. $episode['episode_id'] = $episode_id;
  11344. $episode['roles'] = $merged_roles;
  11345. $episode['scenes'] = $merged_scenes;
  11346. $episode['props'] = $merged_props;
  11347. $episode['end_episode_sequence'] = $end_episode_sequence;
  11348. // 获取mp_animes表中的视频参数
  11349. $episode['video_params'] = [
  11350. 'video_model' => getProp($anime, 'video_model'),
  11351. 'video_resolution' => getProp($anime, 'video_resolution'),
  11352. 'ratio' => getProp($anime, 'video_ratio'),
  11353. ];
  11354. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  11355. yield [
  11356. 'type' => 'done',
  11357. 'episode' => $episode,
  11358. 'answer' => $fullContent,
  11359. 'reasoning' => $fullReasoningContent,
  11360. 'usage' => $usage
  11361. ];
  11362. }
  11363. /**
  11364. * chatForAce的非流式版本 - 用于定时任务
  11365. * 只获取最终 type=done 的数据,并验证必要字段
  11366. *
  11367. * @param array $data 请求数据
  11368. * @return array 生成结果
  11369. */
  11370. public function chatForAceNonStream($data) {
  11371. $finalResult = null;
  11372. // 调用流式方法,只保存 type=done 的数据
  11373. foreach ($this->chatForAce($data) as $chunk) {
  11374. // 只关注最终结果
  11375. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  11376. $finalResult = $chunk;
  11377. break; // 找到 done 就退出循环
  11378. }
  11379. }
  11380. // 验证最终结果
  11381. if (!$finalResult) {
  11382. return ['error' => '生成失败:未获取到最终结果'];
  11383. }
  11384. // 检查是否有错误
  11385. if (isset($finalResult['error']) && $finalResult['error']) {
  11386. return $finalResult;
  11387. }
  11388. // 验证必要字段
  11389. $episode = $finalResult['episode'] ?? [];
  11390. // 验证 roles(旁白不算主体,过滤后不能为空)
  11391. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  11392. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  11393. }
  11394. $nonNarratorRoles = array_filter(array_column($episode['roles'], 'role'), function($role) {
  11395. return $role !== '旁白';
  11396. });
  11397. if (empty($nonNarratorRoles)) {
  11398. return ['error' => '生成失败:主体列表(roles)为空或格式错误(旁白不算)'];
  11399. }
  11400. // 验证 scenes
  11401. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  11402. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  11403. }
  11404. // 验证 props(道具可以为空,但必须存在且为数组)
  11405. if (!isset($episode['props']) || !is_array($episode['props'])) {
  11406. $episode['props'] = [];
  11407. }
  11408. // 验证 acts(分镜剧本)
  11409. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  11410. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  11411. }
  11412. // 更新验证后的 episode 数据
  11413. $finalResult['episode'] = $episode;
  11414. // 记录验证成功日志
  11415. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  11416. 'roles_count' => count($episode['roles']),
  11417. 'scenes_count' => count($episode['scenes']),
  11418. 'props_count' => count($episode['props']),
  11419. 'acts_count' => count($episode['acts'])
  11420. ]);
  11421. return $finalResult;
  11422. }
  11423. /**
  11424. * 批量生成多个分集
  11425. *
  11426. * @param array $data 请求数据
  11427. * @return array 任务信息
  11428. */
  11429. public function batchGenerateEpisodes($data) {
  11430. $uid = Site::getUid();
  11431. $cpid = Site::getCpid();
  11432. $anime_id = getProp($data, 'anime_id');
  11433. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  11434. $start_episode_number = getProp($data, 'start_episode_number');
  11435. $end_episode_number = getProp($data, 'end_episode_number');
  11436. if (!$anime_id) {
  11437. Utils::throwError('20003:anime_id参数缺失');
  11438. }
  11439. if ($generate_episode_number < 1) {
  11440. Utils::throwError('20003:生成集数必须大于0');
  11441. }
  11442. // 获取动漫信息
  11443. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  11444. if (!$anime) {
  11445. Utils::throwError('20003:该剧集不存在');
  11446. }
  11447. // 检查是否是全能模式
  11448. if ((int)getProp($anime, 'ace_mode') !== 1) {
  11449. Utils::throwError('20003:只有全能模式才支持批量生成');
  11450. }
  11451. // 检查是否是多剧集模式
  11452. if ((int)getProp($anime, 'is_multi') !== 1) {
  11453. Utils::throwError('20003:单剧集不支持批量生成');
  11454. }
  11455. // 指定起始/结束剧集序号时的校验
  11456. $hasSpecifiedRange = ($start_episode_number !== null && $start_episode_number !== '')
  11457. || ($end_episode_number !== null && $end_episode_number !== '');
  11458. if ($hasSpecifiedRange) {
  11459. if ($start_episode_number === null || $start_episode_number === ''
  11460. || $end_episode_number === null || $end_episode_number === '') {
  11461. Utils::throwError('20003:起始剧集序号和结束剧集序号必须同时提供');
  11462. }
  11463. $start_episode_number = (int)$start_episode_number;
  11464. $end_episode_number = (int)$end_episode_number;
  11465. if ($start_episode_number < 1 || $end_episode_number < $start_episode_number) {
  11466. Utils::throwError('20003:剧集序号范围错误,结束剧集序号不能小于起始剧集序号');
  11467. }
  11468. // 起始序号必须是已有剧集(is_default=1)的下一个序号,不允许跨序号创建
  11469. $currentMaxEpisode = DB::table('mp_anime_episodes')
  11470. ->where('anime_id', $anime_id)
  11471. ->where('is_default', 1)
  11472. ->max('episode_number');
  11473. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  11474. $nextEpisodeNumber = $currentMaxEpisode + 1;
  11475. if ($start_episode_number !== $nextEpisodeNumber) {
  11476. Utils::throwError('20003:起始剧集序号必须是已有剧集的下一个序号(第' . $nextEpisodeNumber . '集),不允许跨序号创建');
  11477. }
  11478. $startEpisodeNumber = $start_episode_number;
  11479. $endEpisodeNumber = $end_episode_number;
  11480. } else {
  11481. // 未指定范围时,以 generate_episode_number 判断要生成的集数,从当前已生成的最大集数的下一集开始
  11482. $currentMaxEpisode = DB::table('mp_anime_episodes')
  11483. ->where('anime_id', $anime_id)
  11484. ->where('is_default', 1)
  11485. ->max('episode_number');
  11486. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  11487. // 确定起始集数
  11488. $startEpisodeNumber = $currentMaxEpisode + 1;
  11489. // 计算结束集数
  11490. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  11491. }
  11492. // 本次实际生成的集数
  11493. $totalEpisodeCount = $endEpisodeNumber - $startEpisodeNumber + 1;
  11494. // 检查是否超过总集数限制
  11495. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  11496. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  11497. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  11498. }
  11499. // 创建任务前验重:批量任务表与剧集表中是否已存在范围内的剧集序号
  11500. $duplicatedBatchEpisodes = DB::table('mp_batch_episode_generation_details')
  11501. ->where('anime_id', $anime_id)
  11502. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11503. ->pluck('episode_number')
  11504. ->unique()
  11505. ->sort()
  11506. ->values()
  11507. ->toArray();
  11508. $duplicatedAnimeEpisodes = DB::table('mp_anime_episodes')
  11509. ->where('anime_id', $anime_id)
  11510. ->where('is_default', 1)
  11511. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11512. ->pluck('episode_number')
  11513. ->unique()
  11514. ->sort()
  11515. ->values()
  11516. ->toArray();
  11517. if (!empty($duplicatedBatchEpisodes) || !empty($duplicatedAnimeEpisodes)) {
  11518. $duplicateMessages = [];
  11519. if (!empty($duplicatedBatchEpisodes)) {
  11520. $duplicateMessages[] = '批量生成任务中已存在第' . implode('、', $duplicatedBatchEpisodes) . '集';
  11521. }
  11522. if (!empty($duplicatedAnimeEpisodes)) {
  11523. $duplicateMessages[] = '剧集中已存在第' . implode('、', $duplicatedAnimeEpisodes) . '集';
  11524. }
  11525. Utils::throwError('20003:' . implode(';', $duplicateMessages) . ',请勿重复创建');
  11526. }
  11527. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  11528. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  11529. ->where('anime_id', $anime_id)
  11530. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  11531. ->whereIn('status', ['pending', 'processing', 'completed'])
  11532. ->count();
  11533. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  11534. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  11535. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  11536. if ($needEpisodeCount > 0) {
  11537. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints() * $needEpisodeCount, $uid);
  11538. }
  11539. $now = date('Y-m-d H:i:s');
  11540. $createdTasks = [];
  11541. $skippedTasks = [];
  11542. // 为每一集创建详情记录
  11543. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  11544. // 检查是否已有该集的任务记录
  11545. $existingTask = DB::table('mp_batch_episode_generation_details')
  11546. ->where('anime_id', $anime_id)
  11547. ->where('episode_number', $episodeNumber)
  11548. ->first();
  11549. if ($existingTask) {
  11550. // 如果已存在且未完成,跳过
  11551. if (in_array($existingTask->status, ['pending', 'processing'])) {
  11552. $skippedTasks[] = $episodeNumber;
  11553. continue;
  11554. }
  11555. // 如果是失败状态,可以重新创建(删除旧记录)
  11556. if ($existingTask->status === 'failed') {
  11557. DB::table('mp_batch_episode_generation_details')
  11558. ->where('id', $existingTask->id)
  11559. ->delete();
  11560. }
  11561. // 如果是已完成状态,也跳过
  11562. if ($existingTask->status === 'completed') {
  11563. $skippedTasks[] = $episodeNumber;
  11564. continue;
  11565. }
  11566. }
  11567. // 准备任务数据
  11568. $taskData = [
  11569. 'anime_id' => $anime_id,
  11570. 'uid' => $uid,
  11571. 'cpid' => $cpid,
  11572. 'episode_number' => $episodeNumber,
  11573. 'status' => 'pending',
  11574. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  11575. 'retry_count' => 0,
  11576. 'created_at' => $now,
  11577. 'updated_at' => $now
  11578. ];
  11579. // 创建任务记录
  11580. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  11581. if ($taskId) {
  11582. $createdTasks[] = $episodeNumber;
  11583. }
  11584. }
  11585. if (empty($createdTasks)) {
  11586. if (!empty($skippedTasks)) {
  11587. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  11588. } else {
  11589. Utils::throwError('20003:创建批量生成任务失败');
  11590. }
  11591. }
  11592. // 创建/复用任务中心记录(按入参+type验重,避免重复任务)
  11593. $taskCenterId = $this->createBatchGenerateEpisodesTaskCenter(
  11594. $uid,
  11595. $cpid,
  11596. $anime_id,
  11597. $generate_episode_number,
  11598. $startEpisodeNumber,
  11599. $endEpisodeNumber
  11600. );
  11601. return [
  11602. 'anime_id' => $anime_id,
  11603. 'start_episode' => $startEpisodeNumber,
  11604. 'end_episode' => $endEpisodeNumber,
  11605. 'total_episodes' => $totalEpisodeCount,
  11606. 'created_episodes' => $createdTasks,
  11607. 'skipped_episodes' => $skippedTasks,
  11608. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$totalEpisodeCount}集。" .
  11609. "已创建: " . implode(',', $createdTasks) .
  11610. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : ""),
  11611. 'task_center_id' => $taskCenterId
  11612. ];
  11613. }
  11614. /**
  11615. * 根据入参创建或复用批量生成分集的任务中心记录
  11616. *
  11617. * 以入参(anime_id、generate_episode_number)计算 md5 存入 params_md5 字段用于验重:
  11618. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  11619. * 避免生成重复任务;唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复。
  11620. *
  11621. * @param int|string $uid
  11622. * @param int|string $cpid
  11623. * @param int|string $anime_id
  11624. * @param int $generate_episode_number
  11625. * @param int $startEpisodeNumber
  11626. * @param int $endEpisodeNumber
  11627. * @return int 任务中心ID
  11628. */
  11629. private function createBatchGenerateEpisodesTaskCenter($uid, $cpid, $anime_id, $generate_episode_number, $startEpisodeNumber, $endEpisodeNumber) {
  11630. $params = [
  11631. 'anime_id' => (int)$anime_id,
  11632. 'generate_episode_number' => (int)$generate_episode_number,
  11633. 'start_episode' => (int)$startEpisodeNumber,
  11634. 'end_episode' => (int)$endEpisodeNumber,
  11635. ];
  11636. // 验重键:入参 + 生成范围(anime_id + generate_episode_number + start/end)+ task_type
  11637. $paramsMd5 = md5(json_encode([
  11638. 'anime_id' => (int)$anime_id,
  11639. 'generate_episode_number' => (int)$generate_episode_number,
  11640. 'start_episode' => (int)$startEpisodeNumber,
  11641. 'end_episode' => (int)$endEpisodeNumber,
  11642. ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  11643. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  11644. $existing = DB::table('mp_task_center')
  11645. ->where('uid', (int)$uid)
  11646. ->where('cpid', (int)$cpid)
  11647. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11648. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  11649. ->where('params_md5', $paramsMd5)
  11650. ->orderBy('id', 'desc')
  11651. ->first();
  11652. if ($existing) {
  11653. dLog('deepseek')->info('复用批量生成分集任务中心记录,避免重复任务', [
  11654. 'anime_id' => $anime_id,
  11655. 'task_center_id' => $existing->id,
  11656. 'params_md5' => $paramsMd5,
  11657. ]);
  11658. return (int)$existing->id;
  11659. }
  11660. $now = date('Y-m-d H:i:s');
  11661. DB::table('mp_task_center')->insertOrIgnore([
  11662. 'uid' => (int)$uid,
  11663. 'cpid' => (int)$cpid,
  11664. 'task_type' => MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES,
  11665. 'title' => '批量生成分集',
  11666. 'ref_task_id' => 0,
  11667. 'status' => MpTaskCenter::STATUS_PROCESSING,
  11668. 'result' => null,
  11669. 'error_message' => null,
  11670. 'prompt' => null,
  11671. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  11672. 'params_md5' => $paramsMd5,
  11673. 'created_at' => $now,
  11674. 'updated_at' => $now,
  11675. ]);
  11676. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  11677. $taskId = (int)DB::table('mp_task_center')
  11678. ->where('uid', (int)$uid)
  11679. ->where('cpid', (int)$cpid)
  11680. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11681. ->where('params_md5', $paramsMd5)
  11682. ->orderBy('id', 'desc')
  11683. ->value('id');
  11684. dLog('deepseek')->info('创建批量生成分集任务中心记录', [
  11685. 'anime_id' => $anime_id,
  11686. 'task_center_id' => $taskId,
  11687. 'params_md5' => $paramsMd5,
  11688. ]);
  11689. return $taskId;
  11690. }
  11691. /**
  11692. * 批量生成分集全部结束后,更新任务中心记录的状态和结果
  11693. *
  11694. * 由批量生成 worker 子进程在退出前调用。分集详情任务的状态会在多处更新
  11695. * (completed/failed/pending/processing),这里只在所有详情任务均已结束时
  11696. * 统一汇总更新,避免在每个更新点重复处理。
  11697. *
  11698. * @param int|string $animeId
  11699. * @return int 更新的任务中心记录数
  11700. */
  11701. public function finishBatchGenerateEpisodesTaskCenters($animeId) {
  11702. $animeId = (int)$animeId;
  11703. $updated = 0;
  11704. // 该 anime 是否还有未结束的详情任务
  11705. $hasUnfinished = DB::table('mp_batch_episode_generation_details')
  11706. ->where('anime_id', $animeId)
  11707. ->whereIn('status', ['pending', 'processing'])
  11708. ->exists();
  11709. // 扫描该 anime 相关的未完成任务中心记录
  11710. $tasks = DB::table('mp_task_center')
  11711. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  11712. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  11713. ->orderBy('id', 'desc')
  11714. ->limit(500)
  11715. ->get();
  11716. if ($hasUnfinished && !$tasks) {
  11717. return 0;
  11718. }
  11719. foreach ($tasks as $task) {
  11720. try {
  11721. $taskParams = json_decode((string)$task->params, true);
  11722. if (!is_array($taskParams) || (int)($taskParams['anime_id'] ?? 0) !== $animeId) {
  11723. continue;
  11724. }
  11725. $startEpisode = (int)($taskParams['start_episode'] ?? 0);
  11726. $endEpisode = (int)($taskParams['end_episode'] ?? 0);
  11727. if ($startEpisode < 1 || $endEpisode < $startEpisode) {
  11728. continue;
  11729. }
  11730. $details = DB::table('mp_batch_episode_generation_details')
  11731. ->where('anime_id', $animeId)
  11732. ->whereBetween('episode_number', [$startEpisode, $endEpisode])
  11733. ->get();
  11734. // 该批次范围内存在缺失记录,等待下一次检查
  11735. if ($details->isEmpty() || $details->count() < ($endEpisode - $startEpisode + 1)) {
  11736. continue;
  11737. }
  11738. $completedEpisodes = [];
  11739. $failedEpisodes = [];
  11740. $allFinished = true;
  11741. foreach ($details as $detail) {
  11742. if ($detail->status === 'completed') {
  11743. $completedEpisodes[] = $detail->episode_number;
  11744. } elseif ($detail->status === 'failed') {
  11745. $failedEpisodes[] = [
  11746. 'episode_number' => $detail->episode_number,
  11747. 'error_message' => $detail->error_message ?? '',
  11748. ];
  11749. } else {
  11750. // pending/processing(防御处理,正常不会走到)
  11751. $allFinished = false;
  11752. break;
  11753. }
  11754. }
  11755. if (!$allFinished) {
  11756. continue;
  11757. }
  11758. $result = json_encode([
  11759. 'anime_id' => $animeId,
  11760. 'start_episode' => $startEpisode,
  11761. 'end_episode' => $endEpisode,
  11762. 'total_episodes' => count($details),
  11763. 'completed_count' => count($completedEpisodes),
  11764. 'failed_count' => count($failedEpisodes),
  11765. 'completed_episodes' => $completedEpisodes,
  11766. 'failed_episodes' => $failedEpisodes,
  11767. ], JSON_UNESCAPED_UNICODE);
  11768. DB::table('mp_task_center')
  11769. ->where('id', $task->id)
  11770. ->update([
  11771. 'status' => !empty($failedEpisodes) ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  11772. 'result' => $result,
  11773. 'error_message' => !empty($failedEpisodes) ? ('有 ' . count($failedEpisodes) . ' 集生成失败') : null,
  11774. 'updated_at' => date('Y-m-d H:i:s'),
  11775. ]);
  11776. $updated++;
  11777. dLog('command')->info('批量生成分集任务已完成,更新任务中心', [
  11778. 'task_center_id' => $task->id,
  11779. 'anime_id' => $animeId,
  11780. 'start_episode' => $startEpisode,
  11781. 'end_episode' => $endEpisode,
  11782. ]);
  11783. } catch (\Exception $e) {
  11784. dLog('command')->error('更新批量生成分集任务中心异常', [
  11785. 'task_center_id' => $task->id,
  11786. 'anime_id' => $animeId,
  11787. 'error' => $e->getMessage(),
  11788. ]);
  11789. }
  11790. }
  11791. return $updated;
  11792. }
  11793. /**
  11794. * 获取批量生成任务状态
  11795. *
  11796. * @param array $data 请求数据
  11797. * @return array 任务状态信息
  11798. */
  11799. public function getBatchGenerationTaskStatus($data) {
  11800. $anime_id = getProp($data, 'anime_id');
  11801. if (!$anime_id) {
  11802. Utils::throwError('20003:anime_id参数缺失');
  11803. }
  11804. // 获取该anime的所有任务
  11805. $tasks = DB::table('mp_batch_episode_generation_details')
  11806. ->where('anime_id', $anime_id)
  11807. ->orderBy('episode_number')
  11808. ->get()
  11809. ->map(function($item) {
  11810. return [
  11811. 'id' => $item->id,
  11812. 'episode_number' => $item->episode_number,
  11813. 'status' => $item->status,
  11814. 'error_message' => $item->error_message,
  11815. 'retry_count' => $item->retry_count,
  11816. 'created_at' => $item->created_at,
  11817. 'updated_at' => $item->updated_at,
  11818. 'completed_at' => $item->completed_at
  11819. ];
  11820. })
  11821. ->toArray();
  11822. if (empty($tasks)) {
  11823. Utils::throwError('20003:该剧集没有批量生成任务');
  11824. }
  11825. // 统计各状态数量
  11826. $totalCount = count($tasks);
  11827. $pendingCount = 0;
  11828. $processingCount = 0;
  11829. $completedCount = 0;
  11830. $failedCount = 0;
  11831. $failed_episodes = [];
  11832. foreach ($tasks as $task) {
  11833. switch ($task['status']) {
  11834. case 'pending':
  11835. $pendingCount++;
  11836. break;
  11837. case 'processing':
  11838. $processingCount++;
  11839. break;
  11840. case 'completed':
  11841. $completedCount++;
  11842. break;
  11843. case 'failed':
  11844. $failedCount++;
  11845. // 组装失败分集对象(新对象):分集序号、错误原因
  11846. $failed_episodes[] = [
  11847. 'episode_number' => $task['episode_number'],
  11848. 'error_message' => $task['error_message'] ?? ''
  11849. ];
  11850. break;
  11851. }
  11852. }
  11853. // 计算进度百分比
  11854. $progress = 0;
  11855. if ($totalCount > 0) {
  11856. $progress = round(($completedCount / $totalCount) * 100, 2);
  11857. }
  11858. // 判断整体状态
  11859. $overallStatus = 'processing';
  11860. if ($completedCount === $totalCount) {
  11861. $overallStatus = 'completed';
  11862. } elseif ($pendingCount === $totalCount) {
  11863. $overallStatus = 'pending';
  11864. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  11865. $overallStatus = 'failed';
  11866. }
  11867. return [
  11868. 'anime_id' => $anime_id,
  11869. 'total_episodes' => $totalCount,
  11870. 'pending_count' => $pendingCount,
  11871. 'processing_count' => $processingCount,
  11872. 'completed_count' => $completedCount,
  11873. 'failed_count' => $failedCount,
  11874. 'progress' => $progress,
  11875. 'overall_status' => $overallStatus,
  11876. 'failed_episodes' => $failed_episodes,
  11877. 'tasks' => $tasks
  11878. ];
  11879. }
  11880. /**
  11881. * 将生成内容中不在强制列表中的资源合并进强制列表
  11882. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  11883. *
  11884. * @param array $generated 生成内容中的资源列表
  11885. * @param array $forced 强制资源列表(key为资源名称)
  11886. * @param string $type 资源类型:role、scene、prop
  11887. * @return array
  11888. */
  11889. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  11890. {
  11891. foreach ($generated as $item) {
  11892. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  11893. if ($name === null || $name === '') {
  11894. continue;
  11895. }
  11896. if ($name === '旁白') {
  11897. continue;
  11898. }
  11899. if (!isset($forced[$name])) {
  11900. $forced[$name] = $item;
  11901. }
  11902. }
  11903. return $forced;
  11904. }
  11905. /**
  11906. * 智能匹配并替换主体和场景名称
  11907. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  11908. *
  11909. * @param array $episode_arr 解析后的剧集数据
  11910. * @param array $extra_roles 强制主体设定(key为主体名称)
  11911. * @param array $extra_scenes 强制场景设定(key为场景名称)
  11912. * @return array 替换后的剧集数据
  11913. */
  11914. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  11915. $replaced_count = 0;
  11916. // 1. 处理主体列表
  11917. if (!empty($episode_arr['roles'])) {
  11918. foreach ($episode_arr['roles'] as &$role) {
  11919. $generated_role_name = $role['role'] ?? '';
  11920. // 跳过旁白
  11921. if ($generated_role_name === '旁白') {
  11922. continue;
  11923. }
  11924. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  11925. if (!isset($extra_roles[$generated_role_name])) {
  11926. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  11927. if ($matched_role) {
  11928. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  11929. $role['role'] = $matched_role;
  11930. $replaced_count++;
  11931. }
  11932. }
  11933. }
  11934. }
  11935. // 2. 处理场景列表
  11936. if (!empty($episode_arr['scenes'])) {
  11937. foreach ($episode_arr['scenes'] as &$scene) {
  11938. $generated_scene_name = $scene['scene'] ?? '';
  11939. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  11940. if (!isset($extra_scenes[$generated_scene_name])) {
  11941. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  11942. if ($matched_scene) {
  11943. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  11944. $scene['scene'] = $matched_scene;
  11945. $replaced_count++;
  11946. }
  11947. }
  11948. }
  11949. }
  11950. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  11951. if (!empty($episode_arr['acts'])) {
  11952. foreach ($episode_arr['acts'] as &$act) {
  11953. if (!empty($act['segments'])) {
  11954. foreach ($act['segments'] as &$segment) {
  11955. if (!empty($segment['segment_content'])) {
  11956. $original_content = $segment['segment_content'];
  11957. $replaced_content = $original_content;
  11958. // 替换场景名 - 在文本中查找并替换
  11959. foreach (array_keys($extra_scenes) as $full_scene_name) {
  11960. // 尝试找到可能的短名称
  11961. $potential_short_names = [];
  11962. // 提取场景名的主要部分(冒号之前)
  11963. if (mb_strpos($full_scene_name, ':') !== false) {
  11964. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  11965. $potential_short_names[] = $short_name;
  11966. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  11967. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  11968. $potential_short_names[] = $short_name;
  11969. }
  11970. // 替换场景字段中的短名称
  11971. foreach ($potential_short_names as $short_name) {
  11972. if ($short_name !== $full_scene_name) {
  11973. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  11974. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  11975. if ($new_content !== $replaced_content) {
  11976. $replaced_content = $new_content;
  11977. $replaced_count++;
  11978. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  11979. }
  11980. }
  11981. }
  11982. }
  11983. // 替换配音角色名(跳过旁白)
  11984. foreach (array_keys($extra_roles) as $full_role_name) {
  11985. if ($full_role_name === '旁白') {
  11986. continue;
  11987. }
  11988. // 尝试找到可能的短名称
  11989. $potential_short_names = [];
  11990. // 提取角色名的主要部分(短横线之前)
  11991. if (mb_strpos($full_role_name, '-') !== false) {
  11992. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  11993. $potential_short_names[] = $short_name;
  11994. }
  11995. // 替换配音台词中的短名称
  11996. foreach ($potential_short_names as $short_name) {
  11997. if ($short_name !== $full_role_name) {
  11998. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  11999. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  12000. if ($new_content !== $replaced_content) {
  12001. $replaced_content = $new_content;
  12002. $replaced_count++;
  12003. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  12004. }
  12005. }
  12006. }
  12007. }
  12008. // 如果有替换,更新segment_content
  12009. if ($replaced_content !== $original_content) {
  12010. $segment['segment_content'] = $replaced_content;
  12011. }
  12012. }
  12013. }
  12014. }
  12015. }
  12016. }
  12017. if ($replaced_count > 0) {
  12018. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  12019. 'replaced_count' => $replaced_count
  12020. ]);
  12021. }
  12022. return $episode_arr;
  12023. }
  12024. /**
  12025. * 查找匹配的名称
  12026. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  12027. *
  12028. * @param string $generated_name 生成的名称
  12029. * @param array $expected_names 预期的名称列表
  12030. * @return string|null 匹配到的名称,如果没有匹配则返回null
  12031. */
  12032. private function findMatchingName($generated_name, $expected_names) {
  12033. if (empty($generated_name)) {
  12034. return null;
  12035. }
  12036. // 尝试精确匹配
  12037. if (in_array($generated_name, $expected_names)) {
  12038. return $generated_name;
  12039. }
  12040. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  12041. foreach ($expected_names as $expected_name) {
  12042. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  12043. if (mb_strpos($expected_name, $generated_name) === 0) {
  12044. return $expected_name;
  12045. }
  12046. }
  12047. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  12048. // 这样可以处理一些变体,但优先级较低
  12049. foreach ($expected_names as $expected_name) {
  12050. if (mb_strpos($expected_name, $generated_name) !== false) {
  12051. return $expected_name;
  12052. }
  12053. }
  12054. return null;
  12055. }
  12056. /**
  12057. * 重新生成分段剧本
  12058. * @param array $data 包含以下字段:
  12059. * - prompt: string|null 用户修改要求(可选)
  12060. * - template_id: int|null 提示词模板ID(可选)
  12061. * - act_id: int|null 单个片段ID(与episode_id二选一)
  12062. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  12063. * @return array 返回生成结果
  12064. */
  12065. public function regenerateSegmentScript($data) {
  12066. $uid = Site::getUid();
  12067. $prompt = trim((string)getProp($data, 'prompt', ''));
  12068. $template_id = getProp($data, 'template_id', 0);
  12069. $act_id = getProp($data, 'act_id', 0);
  12070. $episode_id = getProp($data, 'episode_id', 0);
  12071. $check_mode = (int)getProp($data, 'check_mode', 0); // 1=预览确认模式(仅 act_id 模式生效,不落库,返回 editAct 入参)
  12072. // 单片段模式:act_id 可以是数据库真实ID(数字)或预览生成的虚拟ID(字符串),非空即单片段模式
  12073. $isActIdMode = !empty($act_id);
  12074. // 验证:prompt和template_id至少提供一个
  12075. if (empty($prompt) && empty($template_id)) {
  12076. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  12077. }
  12078. // 验证:act_id和episode_id二选一
  12079. if (empty($act_id) && empty($episode_id)) {
  12080. Utils::throwError('20003:请提供片段ID或剧集ID');
  12081. }
  12082. if (!empty($act_id) && !empty($episode_id)) {
  12083. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  12084. }
  12085. // 积分余额预检:act_id 单片段模式按 normal 档,episode_id 剧集模式按 special 档
  12086. $chargeType = $isActIdMode ? 'normal' : 'special';
  12087. if ($isActIdMode) {
  12088. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', $chargeType), $uid);
  12089. } else {
  12090. $is_generated = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('is_generated');
  12091. if ($is_generated) Utils::throwError('20003:该分集已不支持重新生成片段,请创建副本后重试!');
  12092. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', $chargeType), $uid);
  12093. }
  12094. // 如果提供了template_id,获取模板提示词
  12095. $template_prompt = '';
  12096. if ($template_id > 0) {
  12097. $template = DB::table('mp_prompt_templates')
  12098. ->where('id', $template_id)
  12099. ->where('is_deleted', 0)
  12100. ->first();
  12101. if (!$template) {
  12102. Utils::throwError('20003:提示词模板不存在或已删除');
  12103. }
  12104. $template_prompt = $template->template_prompt ?? '';
  12105. }
  12106. // 合并用户提示词和模板提示词(模板提示词与用户输入基本一致时只保留一个,避免重复提示词)
  12107. $final_prompt = '';
  12108. if (!empty($template_prompt)) {
  12109. $trimmedPrompt = trim((string)$prompt);
  12110. if ($trimmedPrompt !== '' && mb_strtolower($trimmedPrompt) === mb_strtolower(trim($template_prompt))) {
  12111. $final_prompt = $template_prompt;
  12112. } elseif (!empty($prompt)) {
  12113. $final_prompt = $template_prompt . "\n\n补充要求:" . $prompt;
  12114. } else {
  12115. $final_prompt = $template_prompt;
  12116. }
  12117. } else {
  12118. $final_prompt = $prompt;
  12119. }
  12120. // 获取需要重新生成的内容参考
  12121. $reference_content = '';
  12122. $target_episode_id = 0;
  12123. $target_anime_id = 0;
  12124. $target_episode_number = 0;
  12125. if ($isActIdMode) {
  12126. // 单个片段模式:获取该片段的内容
  12127. $segment = DB::table('mp_episode_segments')
  12128. ->where('id', $act_id)
  12129. ->first();
  12130. // 数据库不存在时,尝试从预览虚拟 act_id 保存的 redis 数据中恢复
  12131. if (!$segment) {
  12132. $previewData = Redis::get($this->buildActPreviewKey($act_id));
  12133. if ($previewData) {
  12134. $previewData = json_decode($previewData, true);
  12135. $segment = (object)[
  12136. 'anime_id' => getProp($previewData, 'anime_id'),
  12137. 'episode_id' => getProp($previewData, 'episode_id'),
  12138. 'episode_number' => getProp($previewData, 'episode_number'),
  12139. 'act_number' => getProp($previewData, 'act_number'),
  12140. 'act_duration' => getProp($previewData, 'act_duration'),
  12141. 'act_content' => getProp($previewData, 'act_content'),
  12142. ];
  12143. }
  12144. }
  12145. if (!$segment) {
  12146. Utils::throwError('20003:片段不存在');
  12147. }
  12148. $target_episode_id = $segment->episode_id;
  12149. $target_anime_id = $segment->anime_id;
  12150. $target_episode_number = $segment->episode_number;
  12151. $reference_content = $segment->act_content ?? '';
  12152. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  12153. } else {
  12154. // 整个剧集模式:获取所有片段的内容
  12155. $segments = DB::table('mp_episode_segments')
  12156. ->where('episode_id', $episode_id)
  12157. ->orderBy('act_number')
  12158. ->get();
  12159. if ($segments->isEmpty()) {
  12160. Utils::throwError('20003:该剧集没有片段数据');
  12161. }
  12162. $target_episode_id = $episode_id;
  12163. $target_anime_id = $segments[0]->anime_id;
  12164. $target_episode_number = $segments[0]->episode_number;
  12165. // 拼接所有片段内容,保留格式用于AI理解
  12166. $act_contents = [];
  12167. foreach ($segments as $seg) {
  12168. $act_number = $seg->act_number;
  12169. $act_content = $seg->act_content ?? '';
  12170. if (!empty($act_content)) {
  12171. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  12172. }
  12173. }
  12174. $reference_content = implode("\n\n", $act_contents);
  12175. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  12176. if ($episode_content) {
  12177. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【原分段剧本内容】\n{$reference_content}";
  12178. //$reference_content = "\n\n【本集原始内容】\n{$episode_content}";
  12179. }else {
  12180. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  12181. }
  12182. }
  12183. if (empty($reference_content)) {
  12184. Utils::throwError('20003:没有可参考的片段内容');
  12185. }
  12186. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  12187. $episode = DB::table('mp_anime_episodes')
  12188. ->where('id', $target_episode_id)
  12189. ->first();
  12190. if (!$episode) {
  12191. Utils::throwError('20003:剧集不存在');
  12192. }
  12193. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  12194. $anime_script_id = getProp($anime, 'script_id');
  12195. $intro = $episode->intro ?? '';
  12196. $art_style = $episode->art_style ?? '';
  12197. $roles = json_decode($episode->roles ?? '[]', true);
  12198. $scenes = json_decode($episode->scenes ?? '[]', true);
  12199. $props = json_decode($episode->props ?? '[]', true);
  12200. // 构建提示词中的主体列表和场景列表参考
  12201. $roles_ref = '';
  12202. if (!empty($roles) && is_array($roles)) {
  12203. $roles_list = [];
  12204. foreach ($roles as $role) {
  12205. $role_name = getProp($role, 'role', '');
  12206. $role_desc = getProp($role, 'description', '');
  12207. $pic_prompt = getProp($role, 'pic_prompt', '');
  12208. $voice_prompt = getProp($role, 'voice_prompt', '');
  12209. if (!empty($role_name)) {
  12210. $role_line = $role_name;
  12211. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  12212. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  12213. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  12214. $roles_list[] = $role_line;
  12215. }
  12216. }
  12217. if (!empty($roles_list)) {
  12218. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  12219. }
  12220. }
  12221. $scenes_ref = '';
  12222. if (!empty($scenes) && is_array($scenes)) {
  12223. $scenes_list = [];
  12224. foreach ($scenes as $scene) {
  12225. $scene_name = getProp($scene, 'scene', '');
  12226. $scene_desc = getProp($scene, 'description', '');
  12227. $pic_prompt = getProp($scene, 'pic_prompt', '');
  12228. if (!empty($scene_name)) {
  12229. $scene_line = $scene_name;
  12230. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  12231. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  12232. $scenes_list[] = $scene_line;
  12233. }
  12234. }
  12235. if (!empty($scenes_list)) {
  12236. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  12237. }
  12238. }
  12239. $props_ref = '';
  12240. if (!empty($props) && is_array($props)) {
  12241. $props_list = [];
  12242. foreach ($props as $prop) {
  12243. $prop_name = getProp($prop, 'prop', '');
  12244. $prop_desc = getProp($prop, 'description', '');
  12245. $pic_prompt = getProp($prop, 'pic_prompt', '');
  12246. if (!empty($prop_name)) {
  12247. $prop_line = $prop_name;
  12248. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  12249. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  12250. $props_list[] = $prop_line;
  12251. }
  12252. }
  12253. if (!empty($props_list)) {
  12254. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  12255. }
  12256. }
  12257. // 构建美术风格参考
  12258. $art_style_ref = '';
  12259. if (!empty($art_style)) {
  12260. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  12261. }
  12262. // 构建内容简介参考
  12263. $intro_ref = '';
  12264. if (!empty($intro)) {
  12265. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  12266. }
  12267. // 构建完整的AI提示词
  12268. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  12269. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  12270. $user_prompt .= $intro_ref;
  12271. $user_prompt .= $art_style_ref;
  12272. $user_prompt .= $reference_content;
  12273. $user_prompt .= "\n\n【生成要求】\n- 请以【原分段剧本内容】为蓝本,保留剧情脉络、角色、场景与分段结构,但必须围绕【用户要求】对相关片段进行实质性修改;若【用户要求】未指定具体修改点,也需对画面、运镜、台词等描述进行改写,禁止整段原样复制。\n";
  12274. // $user_prompt .= $roles_ref;
  12275. // $user_prompt .= $scenes_ref;
  12276. // 输出格式铁律(用户消息侧再次强制,避免模型自由发挥)
  12277. $user_prompt .= "\n\n【输出格式铁律-必须严格遵守】\n";
  12278. if ($isActIdMode) {
  12279. $user_prompt .= "- 请直接以“##片段1”开头,紧跟“时长:X s”行,然后输出本片段的完整分镜内容(分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效),分镜从1开始连续编号。\n";
  12280. $user_prompt .= "- 只允许根据【原分段剧本内容】生成一个片段(即“##片段1”),禁止生成多个片段。\n";
  12281. } else {
  12282. $user_prompt .= "- 请以“###分段剧本”开头,依次输出“片段数量:N”、“旁白音色:...”,然后按“##片段N”逐段输出,每段必须紧跟“时长:X s”行,再输出该片段的完整分镜内容(分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效),分镜从1开始连续编号。\n";
  12283. }
  12284. $user_prompt .= "- 缺少“##片段N”标题或“时长:”行即为格式错误;输出前必须检查格式,不得输出其他任何内容。\n";
  12285. $user_prompt .= "- 片段时长必须在4秒到15秒之间(4s≤时长≤15s),超过15秒必须拆分为多个片段,不得输出低于4秒或超过15秒的片段。\n";
  12286. // 整集模式:强制生成与原来一致的片段数量
  12287. if ($episode_id > 0 && isset($segments)) {
  12288. $originSegmentCount = count($segments);
  12289. $user_prompt .= "- 本集原有{$originSegmentCount}个片段,必须严格生成{$originSegmentCount}个片段(##片段1 到 ##片段{$originSegmentCount}),不得多不得少。\n";
  12290. }
  12291. $system_prompt = "\n\n【输出格式铁律-最高优先级】\n";
  12292. if ($isActIdMode) {
  12293. $system_prompt .= "- 直接以“##片段1”开头,紧跟“时长:X s”行,然后输出本片段分镜内容\n";
  12294. $system_prompt .= "- 只允许根据【原分段剧本内容】生成一个片段(即“##片段1”),禁止生成多个片段。\n";
  12295. } else {
  12296. $system_prompt .= "- 以“###分段剧本”开头,输出“片段数量:N”、“旁白音色:...”\n";
  12297. $system_prompt .= "- 然后按“##片段N”逐段输出,每段紧跟“时长:X s”行\n";
  12298. }
  12299. $system_prompt .= "- 每个片段必须严格以“##片段N”开头(N从1开始连续),并且必须包含“时长:X s”行,缺少即为格式错误\n";
  12300. $system_prompt .= "- 片段时长必须在4~15秒之间(4s≤时长≤15s),超过15秒必须拆分为多个片段,禁止输出低于4秒或超过15秒的片段\n";
  12301. $system_prompt .= "- 输出前检查:若缺少##片段N标题或时长行,视为输出无效,必须修正后输出\n\n";
  12302. $system_prompt .= "【强制要求】\n";
  12303. // $system_prompt .= "- 请严格参考【本集原始内容】或【原分段剧本内容】进行本次生成,注意新生成的分段剧本内容一定不要跟【原分段剧本内容】一致,要进行一定程度调整\n";
  12304. $system_prompt .= "- 【重要】必须参考【本集原始内容】与【原分段剧本内容】中的剧情脉络、角色、场景、道具和分段结构,但严禁原样复制或几乎照抄原文;必须围绕【用户要求】对相关内容进行实质性修改,若生成结果与【原分段剧本内容】完全一致或未体现用户要求,视为生成失败\n";
  12305. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:\n";
  12306. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)\n";
  12307. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  12308. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  12309. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  12310. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  12311. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  12312. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  12313. $system_prompt .= "- 【重要】每个片段必须以“##片段N”开头(N为序号),并且必须包含“时长:X s”行,缺少片段标题或时长视为格式错误\n";
  12314. // 按模式构造强制输出格式:只传 act_id(单片段)时不需要 ###分段剧本/片段数量/旁白音色;传 episode_id(整集)时需要完整格式
  12315. $segmentHeader = '';
  12316. if ($episode_id > 0) {
  12317. $segmentHeader = "###分段剧本\n片段数量:8\n旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。\n\n";
  12318. }
  12319. $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背景音效:";
  12320. // 获取模型配置
  12321. $model = getProp($data, 'model');
  12322. if (!$model) {
  12323. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  12324. }
  12325. // 验证模型是否在可用模型表中
  12326. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  12327. $model = 'deepseek-v4-pro';
  12328. }
  12329. // 模型兼容性处理
  12330. $thinkingMode = 'disabled';
  12331. $reasoningEffort = 'high';
  12332. if ($model === 'deepseek-chat') {
  12333. $model = 'deepseek-v4-flash';
  12334. $thinkingMode = 'disabled';
  12335. } elseif ($model === 'deepseek-reasoner') {
  12336. $model = 'deepseek-v4-flash';
  12337. $thinkingMode = 'enabled';
  12338. }
  12339. // 构建消息
  12340. $messages = [
  12341. [
  12342. 'role' => 'system',
  12343. 'content' => $system_prompt
  12344. ],
  12345. [
  12346. 'role' => 'user',
  12347. 'content' => $user_prompt
  12348. ]
  12349. ];
  12350. // dd($messages);
  12351. // 构建请求参数
  12352. $post_data = [
  12353. 'model' => $model,
  12354. 'messages' => $messages,
  12355. 'temperature' => 1.35,
  12356. 'frequency_penalty' => 0.3,
  12357. 'presence_penalty' => 0,
  12358. 'response_format' => ['type' => 'text'],
  12359. 'thinking' => ['type' => $thinkingMode],
  12360. 'stream' => false // 非流式输出
  12361. ];
  12362. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  12363. // 调用AI生成新的分段剧本
  12364. try {
  12365. $fullContent = '';
  12366. $usage = [];
  12367. // 根据模型类型选择调用方法
  12368. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  12369. if (is_array($chatResult)) {
  12370. $fullContent = $chatResult['fullContent'] ?? '';
  12371. $usage = $chatResult['usage'] ?? [];
  12372. }
  12373. $generated_content = $fullContent;
  12374. // 归一化"场景:"标签换行格式:场景:\n场景名\n => 场景:场景名\n,保证场景字段为一行
  12375. $generated_content = preg_replace('/场景[::]\s*\n\s*([^\n]+)/u', '场景:$1', $generated_content);
  12376. if (empty($generated_content)) {
  12377. Utils::throwError('20003:AI生成内容为空,请重试');
  12378. }
  12379. dLog('deepseek')->info('regenerateSegmentScript AI生成内容', [
  12380. 'act_id' => $act_id,
  12381. 'episode_id' => $episode_id,
  12382. 'content_length' => mb_strlen($generated_content),
  12383. 'content_head' => mb_substr($generated_content, 0, 500),
  12384. 'content_tail' => mb_substr($generated_content, -200),
  12385. ]);
  12386. // 解析生成的内容 - 按片段分割
  12387. $parsed_segments = [];
  12388. // 先在开头添加换行符,确保第1片段也能被正确分割
  12389. $normalizedText = "\n" . $generated_content;
  12390. $parts = preg_split('/\n\s*##/', $normalizedText);
  12391. foreach ($parts as $part) {
  12392. $part = trim($part);
  12393. if (empty($part)) continue;
  12394. // 匹配"片段X"格式
  12395. if (!preg_match('/^片段\d+/', $part)) {
  12396. continue;
  12397. }
  12398. // 分离标题和内容
  12399. $lines = explode("\n", $part, 2);
  12400. $actTitle = trim($lines[0]);
  12401. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  12402. // 解析标题,提取序号
  12403. $actNumber = 0;
  12404. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  12405. $actNumber = intval($segmentTitleMatch[1]);
  12406. } else {
  12407. $actNumber = count($parsed_segments) + 1;
  12408. }
  12409. // 提取时长(仅保留数字)
  12410. $actDuration = 0;
  12411. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  12412. $actDurationStr = trim($actDurationMatch[1]);
  12413. // 提取数字部分(支持整数和小数)
  12414. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  12415. $actDuration = (float)$numMatch[1];
  12416. }
  12417. }
  12418. // 时长范围约束:4~15秒,超限兜底修正(0=未知按最低4秒)
  12419. if ($actDuration > 15) {
  12420. $actDuration = 15;
  12421. }
  12422. if ($actDuration < 4) {
  12423. $actDuration = 4;
  12424. }
  12425. // 清理act_content:去除时长、旁白音色等非分镜内容行,只保留分镜内容
  12426. $cleaned_content = $this->cleanSegmentContent($actContent);
  12427. $parsed_segments[] = [
  12428. 'act_number' => $actNumber,
  12429. 'act_title' => $actTitle,
  12430. 'act_duration' => $actDuration,
  12431. 'act_content' => $cleaned_content,
  12432. ];
  12433. }
  12434. // 兜底:模型未输出 ##片段N 标题时(如直接输出分镜正文),将整个生成内容作为单个片段解析(act_id 单片段场景)
  12435. if (empty($parsed_segments)) {
  12436. $fallbackContent = $this->cleanSegmentContent($generated_content);
  12437. if ($fallbackContent !== '') {
  12438. $fallbackDuration = 0;
  12439. if (preg_match('/时长[::]\s*([^\n]+)/u', $generated_content, $durationMatch)) {
  12440. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $durationMatch[1], $numMatch)) {
  12441. $fallbackDuration = (float)$numMatch[1];
  12442. }
  12443. }
  12444. // 内容未带时长时,单片段模式沿用原片段的时长
  12445. if ($fallbackDuration <= 0 && $isActIdMode && !empty($segment->act_duration)) {
  12446. $fallbackDuration = (float)$segment->act_duration;
  12447. }
  12448. // 时长范围约束:4~15秒,超限兜底修正(0=未知按最低4秒)
  12449. if ($fallbackDuration > 15) {
  12450. $fallbackDuration = 15;
  12451. }
  12452. if ($fallbackDuration < 4) {
  12453. $fallbackDuration = 4;
  12454. }
  12455. $parsed_segments[] = [
  12456. 'act_number' => 1,
  12457. 'act_title' => '片段1',
  12458. 'act_duration' => $fallbackDuration,
  12459. 'act_content' => $fallbackContent,
  12460. ];
  12461. }
  12462. }
  12463. // act_id 单片段模式:只允许一个片段,多余片段丢弃,仅保留第一个
  12464. if ($isActIdMode && count($parsed_segments) > 1) {
  12465. dLog('deepseek')->info('regenerateSegmentScript act_id 模式仅保留第一个片段', [
  12466. 'act_id' => $act_id,
  12467. 'original_count' => count($parsed_segments),
  12468. ]);
  12469. $parsed_segments = array_slice($parsed_segments, 0, 1);
  12470. }
  12471. dLog('deepseek')->info('regenerateSegmentScript 解析结果', [
  12472. 'act_id' => $act_id,
  12473. 'episode_id' => $episode_id,
  12474. 'segment_count' => count($parsed_segments),
  12475. 'segments' => array_map(function ($seg) {
  12476. return [
  12477. 'act_number' => $seg['act_number'],
  12478. 'act_duration' => $seg['act_duration'],
  12479. 'content_length' => mb_strlen($seg['act_content']),
  12480. ];
  12481. }, $parsed_segments),
  12482. ]);
  12483. if (empty($parsed_segments)) {
  12484. dLog('deepseek')->error('regenerateSegmentScript 无法解析生成的分段剧本', [
  12485. 'act_id' => $act_id,
  12486. 'episode_id' => $episode_id,
  12487. 'content_length' => mb_strlen($generated_content),
  12488. 'content_head' => mb_substr($generated_content, 0, 1000),
  12489. 'content_tail' => mb_substr($generated_content, -300),
  12490. ]);
  12491. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  12492. }
  12493. // 收集所有资产名称(角色、场景、道具)
  12494. $product_names = [];
  12495. // 收集角色名称
  12496. if (!empty($roles) && is_array($roles)) {
  12497. foreach ($roles as $role) {
  12498. $role_name = getProp($role, 'role', '');
  12499. if (!empty($role_name)) {
  12500. $product_names[] = $role_name;
  12501. }
  12502. }
  12503. }
  12504. // 收集场景名称
  12505. if (!empty($scenes) && is_array($scenes)) {
  12506. foreach ($scenes as $scene) {
  12507. $scene_name = getProp($scene, 'scene', '');
  12508. if (!empty($scene_name)) {
  12509. $product_names[] = $scene_name;
  12510. }
  12511. }
  12512. }
  12513. // 收集道具名称
  12514. if (!empty($props) && is_array($props)) {
  12515. foreach ($props as $prop) {
  12516. $prop_name = getProp($prop, 'prop', '');
  12517. if (!empty($prop_name)) {
  12518. $product_names[] = $prop_name;
  12519. }
  12520. }
  12521. }
  12522. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  12523. $product_names = array_unique($product_names);
  12524. usort($product_names, function($a, $b) {
  12525. return mb_strlen($b) - mb_strlen($a);
  12526. });
  12527. // 处理每个片段的 act_show_content
  12528. foreach ($parsed_segments as &$segment) {
  12529. $act_content = getProp($segment, 'act_content', '');
  12530. if (empty($act_content)) {
  12531. $segment['act_show_content'] = '';
  12532. continue;
  12533. }
  12534. $processed_content = $act_content;
  12535. // 统一替换所有资产名称为 {资产名} 格式
  12536. // 使用占位符避免嵌套替换问题
  12537. $placeholder_map = [];
  12538. $placeholder_index = 0;
  12539. foreach ($product_names as $product_name) {
  12540. // 转义特殊字符
  12541. $escaped_product = preg_quote($product_name, '/');
  12542. // 检查是否匹配且未被 {} 包裹
  12543. $processed_content = preg_replace_callback(
  12544. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  12545. function($matches) use (&$placeholder_map, &$placeholder_index) {
  12546. // 使用唯一占位符
  12547. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  12548. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  12549. $placeholder_index++;
  12550. return $placeholder;
  12551. },
  12552. $processed_content
  12553. );
  12554. }
  12555. // 将所有占位符替换回实际内容
  12556. foreach ($placeholder_map as $placeholder => $replacement) {
  12557. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  12558. }
  12559. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  12560. $shot_counter = 0;
  12561. $processed_content = preg_replace_callback(
  12562. // 兼容“【镜头 1】”“【分镜 1】”等分镜/镜头与数字间带空格的情况
  12563. '/【(?:镜头|分镜)\s*(\d+)】/u',
  12564. function($matches) use (&$shot_counter) {
  12565. $shot_counter++;
  12566. return '【镜头' . $shot_counter . '】';
  12567. },
  12568. $processed_content
  12569. );
  12570. $segment['act_show_content'] = $processed_content;
  12571. }
  12572. unset($segment); // 解除引用
  12573. // 保存到数据库
  12574. $now = date('Y-m-d H:i:s');
  12575. $saved_acts = []; // 用于记录保存后的片段信息
  12576. if ($isActIdMode) {
  12577. // 单个片段模式:更新单条记录
  12578. if (count($parsed_segments) > 0) {
  12579. $new_segment = $parsed_segments[0];
  12580. // 预览确认模式(check_mode=1):不落库,组装 editAct 入参返回,由前端确认后调用 editAct 更新
  12581. if ($check_mode === 1) {
  12582. // 单片段预览生成即按 normal 档扣费
  12583. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12584. 'anime_id' => $target_anime_id,
  12585. 'episode_id' => $target_episode_id,
  12586. 'model' => $model,
  12587. 'source' => 'regenerateSegmentScript',
  12588. ], 'normal');
  12589. return [
  12590. 'check_mode' => 1,
  12591. 'act_id' => $act_id,
  12592. 'act_title' => getProp($new_segment, 'act_title', ''),
  12593. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  12594. 'act_content' => getProp($new_segment, 'act_show_content', ''),
  12595. ];
  12596. }
  12597. // 虚拟 act_id 仅用于预览/参考,不允许直接保存到数据库
  12598. if (!is_numeric($act_id)) {
  12599. Utils::throwError('20003:该片段不可直接保存');
  12600. }
  12601. $update_data = [
  12602. 'act_content' => getProp($new_segment, 'act_content', ''),
  12603. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  12604. 'act_title' => getProp($new_segment, 'act_title', ''),
  12605. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  12606. 'updated_at' => $now,
  12607. ];
  12608. DB::table('mp_episode_segments')
  12609. ->where('id', $act_id)
  12610. ->update($update_data);
  12611. // 获取更新后的记录
  12612. $updated_act = DB::table('mp_episode_segments')
  12613. ->where('id', $act_id)
  12614. ->first();
  12615. if ($updated_act) {
  12616. $saved_acts[] = [
  12617. 'act_id' => $updated_act->id,
  12618. 'act_number' => $updated_act->act_number,
  12619. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  12620. 'act_content' => $updated_act->act_content,
  12621. 'act_show_content' => $updated_act->act_show_content,
  12622. 'video_url' => $updated_act->video_url ?? '',
  12623. 'video_duration' => $updated_act->video_duration ?? 0,
  12624. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  12625. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  12626. ];
  12627. }
  12628. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  12629. // 单片段模式成功扣费(normal 档)
  12630. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12631. 'anime_id' => $target_anime_id,
  12632. 'episode_id' => $target_episode_id,
  12633. 'model' => $model,
  12634. 'source' => 'regenerateSegmentScript',
  12635. ], 'normal');
  12636. }
  12637. } else {
  12638. // 预览确认模式(check_mode=1):不落库,返回展示参数供前端确认后调用 saveEpisodeActs 保存
  12639. if ($check_mode === 1) {
  12640. // 剧集模式预览生成即扣除积分并记录 token 明细(special 档)
  12641. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12642. 'anime_id' => $target_anime_id,
  12643. 'episode_id' => $target_episode_id,
  12644. 'model' => $model,
  12645. 'source' => 'regenerateSegmentScript',
  12646. ], 'special');
  12647. // 为每个片段生成虚拟 act_id 并写入 redis(1天有效),供后续按虚拟 act_id 恢复片段数据
  12648. $previewActs = [];
  12649. foreach ($parsed_segments as $seg) {
  12650. $virtualActId = 'preview_' . time() . '_' . uniqid();
  12651. Redis::setex($this->buildActPreviewKey($virtualActId), 86400, json_encode([
  12652. 'anime_id' => $target_anime_id,
  12653. 'episode_id' => $target_episode_id,
  12654. 'episode_number' => $target_episode_number,
  12655. 'act_number' => $seg['act_number'],
  12656. 'act_title' => $seg['act_title'],
  12657. 'act_duration' => $seg['act_duration'],
  12658. 'act_content' => $seg['act_content'],
  12659. 'act_show_content'=> $seg['act_show_content'],
  12660. ], JSON_UNESCAPED_UNICODE));
  12661. $previewActs[] = [
  12662. 'act_id' => $virtualActId,
  12663. 'act_number' => $seg['act_number'],
  12664. 'act_title' => $seg['act_title'],
  12665. 'act_duration' => $seg['act_duration'],
  12666. 'act_content' => $seg['act_content'],
  12667. 'act_show_content' => $seg['act_show_content'],
  12668. 'video_url' => '',
  12669. 'video_duration' => 0,
  12670. 'video_time_point_start' => 0,
  12671. 'video_time_point_end' => 0,
  12672. 'last_frame_url' => '',
  12673. 'current_type' => 0,
  12674. ];
  12675. }
  12676. return [
  12677. 'check_mode' => 1,
  12678. 'anime_id' => $target_anime_id,
  12679. 'episode_id' => $target_episode_id,
  12680. 'title' => getProp($episode, 'title', ''),
  12681. 'episode_number' => $target_episode_number,
  12682. 'is_generated' => getProp($episode, 'is_generated', 0),
  12683. 'acts' => $previewActs,
  12684. ];
  12685. }
  12686. // 整个剧集模式:删除原有记录并批量保存新记录
  12687. DB::beginTransaction();
  12688. try {
  12689. // 删除原有的所有片段记录
  12690. DB::table('mp_episode_segments')
  12691. ->where('episode_id', $target_episode_id)
  12692. ->delete();
  12693. // 批量插入新的片段记录
  12694. $segments_to_insert = [];
  12695. foreach ($parsed_segments as $index => $segment) {
  12696. $act_number = $index + 1;
  12697. $segments_to_insert[] = [
  12698. 'anime_id' => $target_anime_id,
  12699. 'episode_id' => $target_episode_id,
  12700. 'episode_number' => $target_episode_number,
  12701. 'act_number' => $act_number,
  12702. 'act_title' => getProp($segment, 'act_title', ''),
  12703. 'act_duration' => getProp($segment, 'act_duration', 0),
  12704. 'act_content' => getProp($segment, 'act_content', ''),
  12705. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  12706. 'created_at' => $now,
  12707. 'updated_at' => $now,
  12708. ];
  12709. }
  12710. if (!empty($segments_to_insert)) {
  12711. DB::table('mp_episode_segments')->insert($segments_to_insert);
  12712. }
  12713. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(special 档,与保存同事务)
  12714. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  12715. 'anime_id' => $target_anime_id,
  12716. 'episode_id' => $target_episode_id,
  12717. 'model' => $model,
  12718. 'source' => 'regenerateSegmentScript',
  12719. ], 'special');
  12720. DB::commit();
  12721. // 查询保存后的所有片段记录
  12722. $saved_segments = DB::table('mp_episode_segments')
  12723. ->where('episode_id', $target_episode_id)
  12724. ->orderBy('act_number')
  12725. ->get();
  12726. foreach ($saved_segments as $saved_segment) {
  12727. $saved_acts[] = [
  12728. 'act_id' => $saved_segment->id,
  12729. 'act_number' => $saved_segment->act_number,
  12730. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  12731. 'act_content' => $saved_segment->act_content,
  12732. 'act_show_content' => $saved_segment->act_show_content,
  12733. 'video_url' => $saved_segment->video_url ?? '',
  12734. 'video_duration' => $saved_segment->video_duration ?? 0,
  12735. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  12736. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  12737. ];
  12738. }
  12739. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  12740. 'episode_id' => $target_episode_id,
  12741. 'segments_count' => count($segments_to_insert)
  12742. ]);
  12743. } catch (\Exception $e) {
  12744. DB::rollBack();
  12745. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  12746. Utils::throwError('20003:保存失败,请重试');
  12747. }
  12748. }
  12749. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  12750. return [
  12751. 'anime_id' => $target_anime_id,
  12752. 'episode_id' => $target_episode_id,
  12753. 'title' => getProp($episode, 'title', ''),
  12754. 'episode_number' => $target_episode_number,
  12755. 'is_generated' => getProp($episode, 'is_generated', 0),
  12756. 'acts' => $saved_acts,
  12757. ];
  12758. } catch (\Exception $e) {
  12759. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  12760. throw $e;
  12761. }
  12762. }
  12763. /**
  12764. * 保存剧集片段(预览确认模式使用):删除旧数据并批量保存新数据到 mp_episode_segments
  12765. *
  12766. * 逻辑与 regenerateSegmentScript 的 episode_id + check_mode=0 保存保持一致。
  12767. *
  12768. * @param array $data 请求参数:episode_id 必填,acts 必填(预览返回的片段数组)
  12769. * @return array
  12770. */
  12771. public function saveEpisodeActs($data) {
  12772. $uid = Site::getUid();
  12773. $episode_id = (int)getProp($data, 'episode_id', 0);
  12774. $acts = getProp($data, 'acts', []);
  12775. if (!$episode_id) {
  12776. Utils::throwError('20003:请提供剧集ID');
  12777. }
  12778. if (!is_array($acts) || empty($acts)) {
  12779. Utils::throwError('20003:请提供片段数据');
  12780. }
  12781. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->first();
  12782. if (!$episode) {
  12783. Utils::throwError('20003:剧集不存在');
  12784. }
  12785. // 用户校验:只能调整自己的剧集
  12786. $anime = DB::table('mp_animes')->where('id', $episode->anime_id)->first();
  12787. if (!$anime || (int)$anime->user_id !== (int)$uid) {
  12788. Utils::throwError('20003:没有权限操作该剧集');
  12789. }
  12790. $anime_id = (int)$episode->anime_id;
  12791. $episode_number = (int)$episode->episode_number;
  12792. $now = date('Y-m-d H:i:s');
  12793. try {
  12794. DB::beginTransaction();
  12795. // 删除原有的所有片段记录
  12796. DB::table('mp_episode_segments')
  12797. ->where('episode_id', $episode_id)
  12798. ->delete();
  12799. // 批量插入新的片段记录
  12800. $segments_to_insert = [];
  12801. $index = 0;
  12802. foreach ($acts as $act) {
  12803. if (!is_array($act)) {
  12804. continue;
  12805. }
  12806. $index++;
  12807. $segments_to_insert[] = [
  12808. 'anime_id' => $anime_id,
  12809. 'episode_id' => $episode_id,
  12810. 'episode_number' => $episode_number,
  12811. 'act_number' => (int)getProp($act, 'act_number', $index),
  12812. 'act_title' => (string)getProp($act, 'act_title', ''),
  12813. 'act_duration' => (float)getProp($act, 'act_duration', 0),
  12814. 'act_content' => (string)getProp($act, 'act_content', ''),
  12815. // 'act_show_content' => (string)getProp($act, 'act_show_content', ''),
  12816. 'created_at' => $now,
  12817. 'updated_at' => $now,
  12818. ];
  12819. }
  12820. if (empty($segments_to_insert)) {
  12821. DB::rollBack();
  12822. Utils::throwError('20003:没有有效的片段数据');
  12823. }
  12824. DB::table('mp_episode_segments')->insert($segments_to_insert);
  12825. DB::commit();
  12826. } catch (\Exception $e) {
  12827. DB::rollBack();
  12828. dLog('deepseek')->error('保存剧集片段失败: ' . $e->getMessage(), [
  12829. 'episode_id' => $episode_id,
  12830. ]);
  12831. Utils::throwError('20003:保存失败,请重试');
  12832. }
  12833. // 查询保存后的所有片段记录(数组化,与 episodeInfoForAce 处理一致)
  12834. $saved_segments = DB::table('mp_episode_segments')
  12835. ->where('episode_id', $episode_id)
  12836. ->orderBy('act_number')
  12837. ->get()
  12838. ->map(function ($value) {
  12839. return (array)$value;
  12840. })
  12841. ->toArray();
  12842. // 构造与 episodeInfoForAce 一致的 acts 与 total_duration
  12843. $acts = [];
  12844. $totalDuration = 0;
  12845. foreach ($saved_segments as $segment) {
  12846. $videoDuration = getProp($segment, 'video_duration');
  12847. $actDuration = getProp($segment, 'act_duration');
  12848. if (!empty($videoDuration) && is_numeric($videoDuration)) {
  12849. $totalDuration += floatval($videoDuration);
  12850. } elseif (!empty($actDuration) && is_numeric($actDuration)) {
  12851. $totalDuration += floatval($actDuration);
  12852. } else {
  12853. $totalDuration += 5;
  12854. }
  12855. $acts[] = [
  12856. 'act_id' => getProp($segment, 'id'),
  12857. 'act_number' => getProp($segment, 'act_number'),
  12858. 'act_title' => getProp($segment, 'act_title'),
  12859. 'act_duration' => getProp($segment, 'act_duration'),
  12860. 'act_content' => getProp($segment, 'act_content'),
  12861. 'video_url' => getProp($segment, 'video_url'),
  12862. 'video_duration' => getProp($segment, 'video_duration', 0),
  12863. 'video_time_point_start' => getProp($segment, 'video_time_point_start', 0),
  12864. 'video_time_point_end' => getProp($segment, 'video_time_point_end', getProp($segment, 'video_duration', 0)),
  12865. 'last_frame_url' => getProp($segment, 'last_frame_url'),
  12866. 'current_type' => getProp($segment, 'current_type'),
  12867. ];
  12868. }
  12869. // 顶层与 episodeInfoForAce 一致
  12870. $result = [
  12871. 'episode_id' => $episode_id,
  12872. 'anime_id' => $anime_id,
  12873. 'episode_number' => $episode_number,
  12874. 'title' => getProp($episode, 'title'),
  12875. 'intro' => getProp($episode, 'intro'),
  12876. 'art_style' => getProp($episode, 'art_style'),
  12877. 'roles' => json_decode(getProp($episode, 'roles', '[]'), true),
  12878. 'scenes' => json_decode(getProp($episode, 'scenes', '[]'), true),
  12879. 'props' => getProp($episode, 'props') ? json_decode(getProp($episode, 'props'), true) : [],
  12880. 'is_generated' => getProp($episode, 'is_generated'),
  12881. 'acts' => array_values($acts),
  12882. 'total_duration' => intval(round($totalDuration)),
  12883. ];
  12884. // video_params(从 mp_animes 取,与 episodeInfoForAce 一致)
  12885. $animeRow = DB::table('mp_animes')->where('id', $anime_id)->first(['video_model', 'video_resolution', 'video_ratio']);
  12886. $result['video_params'] = [
  12887. 'video_model' => getProp($animeRow, 'video_model'),
  12888. 'video_resolution' => getProp($animeRow, 'video_resolution'),
  12889. 'ratio' => getProp($animeRow, 'video_ratio'),
  12890. ];
  12891. return $result;
  12892. }
  12893. /**
  12894. * 预览虚拟 act_id 在 redis 中的键
  12895. *
  12896. * @param mixed $actId
  12897. * @return string
  12898. */
  12899. private function buildActPreviewKey($actId): string
  12900. {
  12901. return 'anime_act_preview:' . $actId;
  12902. }
  12903. /**
  12904. * 清理分镜内容:去除时长、旁白音色等非分镜行,只保留完整分镜内容(分镜标记统一为【分镜N】/【镜头N】)
  12905. *
  12906. * @param string $actContent
  12907. * @return string
  12908. */
  12909. private function cleanSegmentContent(string $actContent): string
  12910. {
  12911. $cleaned_content = '';
  12912. $content_lines = explode("\n", $actContent);
  12913. $is_capturing = false; // 标记是否开始捕获分镜内容
  12914. $count = 0;
  12915. foreach ($content_lines as $line) {
  12916. $trimmed_line = trim($line);
  12917. // 跳过时长、旁白音色等非分镜行
  12918. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  12919. continue;
  12920. }
  12921. // 检测分镜开始(支持【分镜X】【镜头X】、分镜X、镜头X,以及分镜/镜头与数字间带空格的情况)
  12922. if (preg_match('/^(?:【)?(分镜|镜头)\s*(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  12923. $count++;
  12924. $is_capturing = true;
  12925. // 统一归一化为【分镜N】/【镜头N】(兼容“镜头 1”“【镜头 1】”等写法)
  12926. $trimmed_line = preg_replace('/^(?:【)?(分镜|镜头)\s*(\d+)(?:】)?/u', '【$1$2】', $trimmed_line);
  12927. if ($count > 1) {
  12928. $trimmed_line = "\n" . $trimmed_line;
  12929. }
  12930. }
  12931. if ($is_capturing && !empty($trimmed_line)) {
  12932. $cleaned_content .= $trimmed_line . "\n";
  12933. }
  12934. }
  12935. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  12936. return $cleaned_content;
  12937. }
  12938. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  12939. {
  12940. $episode_arr = [
  12941. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  12942. 'intro' => getProp($script_arr, 'intro'),
  12943. 'art_style' => getProp($script_arr, 'art_style'),
  12944. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  12945. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  12946. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  12947. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  12948. ];
  12949. if (empty($episode_arr['acts'])) {
  12950. $fallback_episode_arr = handleEpisodeContent($fullContent);
  12951. if (!empty($fallback_episode_arr['acts'])) {
  12952. $episode_arr = array_merge($fallback_episode_arr, [
  12953. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  12954. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  12955. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  12956. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  12957. ]);
  12958. }
  12959. }
  12960. // if (!getProp($episode_arr, 'episode_title')) {
  12961. // $episode_title = '';
  12962. // $episodes = getProp($script_arr, 'episodes', []);
  12963. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  12964. // $episode_title = '第1集:' . $episodes[0]['title'];
  12965. // }
  12966. // if (!$episode_title) {
  12967. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  12968. // }
  12969. // $episode_arr['episode_title'] = $episode_title;
  12970. // }
  12971. return $episode_arr;
  12972. }
  12973. private function saveEpisodeVersionData(
  12974. int $anime_id,
  12975. int $episode_number,
  12976. array $episode_arr,
  12977. array $existing_roles,
  12978. array $existing_scenes,
  12979. array $existing_props,
  12980. $current_episode,
  12981. $base_episode,
  12982. bool $is_regenerate_version,
  12983. string $content,
  12984. string $now,
  12985. array $ref_products = []
  12986. ): array {
  12987. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  12988. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  12989. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  12990. // 过滤掉关键字段为空的条目
  12991. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  12992. return !empty($item['role'] ?? null);
  12993. }));
  12994. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  12995. return !empty($item['scene'] ?? null);
  12996. }));
  12997. $merged_props = array_values(array_filter($generated_props, function ($item) {
  12998. return !empty($item['prop'] ?? null);
  12999. }));
  13000. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  13001. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  13002. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  13003. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  13004. $ace_mode = getProp($anime, 'ace_mode');
  13005. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  13006. $global_roles = json_decode(getProp($anime, 'roles'), true);
  13007. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  13008. $global_roles = is_array($global_roles) ? $global_roles : [];
  13009. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  13010. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  13011. $art_style_type = getProp($anime, 'art_style_type');
  13012. // 检查并创建 roles 的图片生成任务
  13013. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  13014. // 检查并创建 scenes 的图片生成任务
  13015. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  13016. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  13017. if ($arr && is_array($arr)) {
  13018. $merged_roles = $arr['roles'];
  13019. $merged_scenes = $arr['scenes'];
  13020. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  13021. }
  13022. // 确保数据是数组类型
  13023. if (!is_array($merged_roles)) {
  13024. dLog('deepseek')->error('merged_roles不是数组类型', [
  13025. 'type' => gettype($merged_roles),
  13026. 'value' => $merged_roles
  13027. ]);
  13028. $merged_roles = [];
  13029. }
  13030. if (!is_array($merged_scenes)) {
  13031. dLog('deepseek')->error('merged_scenes不是数组类型', [
  13032. 'type' => gettype($merged_scenes),
  13033. 'value' => $merged_scenes
  13034. ]);
  13035. $merged_scenes = [];
  13036. }
  13037. if (!is_array($merged_props)) {
  13038. dLog('deepseek')->error('merged_props不是数组类型', [
  13039. 'type' => gettype($merged_props),
  13040. 'value' => $merged_props
  13041. ]);
  13042. $merged_props = [];
  13043. }
  13044. // 同步新出现的主体和场景到全局
  13045. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  13046. $role_arr = [];
  13047. foreach ($merged_roles as $item) {
  13048. $role_arr[$item['role']] = $item;
  13049. }
  13050. $version_count = DB::table('mp_anime_episodes')
  13051. ->where('anime_id', $anime_id)
  13052. ->where('episode_number', $episode_number)
  13053. ->count('id');
  13054. $episode = [
  13055. 'anime_id' => $anime_id,
  13056. 'episode_number' => $episode_number,
  13057. 'title' => getProp($episode_arr, 'episode_title'),
  13058. 'content' => $content,
  13059. 'intro' => getProp($episode_arr, 'intro'),
  13060. 'art_style' => getProp($episode_arr, 'art_style'),
  13061. 'roles' => json_encode($merged_roles, 256),
  13062. 'scenes' => json_encode($merged_scenes, 256),
  13063. 'props' => json_encode($merged_props, 256),
  13064. 'generate_status' => '待执行',
  13065. 'generate_at' => $now,
  13066. 'is_default' => 1,
  13067. 'updated_at' => $now,
  13068. ];
  13069. $del_flag = false;
  13070. if ($is_regenerate_version) {
  13071. DB::table('mp_anime_episodes')
  13072. ->where('anime_id', $anime_id)
  13073. ->where('episode_number', $episode_number)
  13074. ->update(['is_default' => 0, 'updated_at' => $now]);
  13075. $episode['sequence'] = $version_count + 1;
  13076. $episode['created_at'] = $now;
  13077. $episode['cpid'] = Site::getCpid();
  13078. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  13079. if (!$episode_id) {
  13080. Utils::throwError('20003:创建剧集版本失败');
  13081. }
  13082. } else {
  13083. $target_episode = $current_episode ?: $base_episode;
  13084. if ($target_episode) {
  13085. $episode_id = getProp($target_episode, 'id');
  13086. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  13087. DB::table('mp_anime_episodes')
  13088. ->where('anime_id', $anime_id)
  13089. ->where('episode_number', $episode_number)
  13090. ->where('id', '<>', $episode_id)
  13091. ->update(['is_default' => 0, 'updated_at' => $now]);
  13092. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  13093. if ($boolen === false) {
  13094. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  13095. Utils::throwError('20003:分集内容保存失败');
  13096. }
  13097. $del_flag = true;
  13098. } else {
  13099. DB::table('mp_anime_episodes')
  13100. ->where('anime_id', $anime_id)
  13101. ->where('episode_number', $episode_number)
  13102. ->update(['is_default' => 0, 'updated_at' => $now]);
  13103. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  13104. $episode['created_at'] = $now;
  13105. $episode['cpid'] = Site::getCpid();
  13106. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  13107. if (!$episode_id) {
  13108. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  13109. Utils::throwError('20003:分集内容保存失败');
  13110. }
  13111. }
  13112. }
  13113. $segments = [];
  13114. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  13115. // 如果是第2集及以后,获取上一集的主体音色数据
  13116. $previous_roles_voice = [];
  13117. if ($episode_number >= 2) {
  13118. $previous_episode = DB::table('mp_anime_episodes')
  13119. ->where('anime_id', $anime_id)
  13120. ->where('episode_number', $episode_number - 1)
  13121. ->where('is_default', 1)
  13122. ->first();
  13123. if ($previous_episode) {
  13124. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  13125. if (is_array($previous_roles)) {
  13126. foreach ($previous_roles as $prev_role) {
  13127. $role_name = getProp($prev_role, 'role');
  13128. if ($role_name) {
  13129. $previous_roles_voice[$role_name] = [
  13130. 'voice_name' => getProp($prev_role, 'voice_name'),
  13131. 'voice_type' => getProp($prev_role, 'voice_type'),
  13132. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  13133. ];
  13134. $voice_prompt = getProp($prev_role, 'voice_prompt');
  13135. if ($voice_prompt) {
  13136. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  13137. }
  13138. }
  13139. }
  13140. }
  13141. }
  13142. }
  13143. // 将继承的音色数据同步到当前集的主体列表
  13144. if (!empty($previous_roles_voice)) {
  13145. foreach ($merged_roles as &$role) {
  13146. $role_name = getProp($role, 'role');
  13147. if ($role_name && isset($previous_roles_voice[$role_name])) {
  13148. // 强制继承上一集的音色数据
  13149. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  13150. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  13151. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  13152. // 如果上一集有 voice_prompt 则继承,否则跳过
  13153. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  13154. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  13155. }
  13156. }
  13157. }
  13158. unset($role); // 解除引用
  13159. // 更新 role_arr 以便后续使用
  13160. $role_arr = [];
  13161. foreach ($merged_roles as $item) {
  13162. $role_arr[$item['role']] = $item;
  13163. }
  13164. }
  13165. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  13166. $emotion_list = array_flip($emotion_list);
  13167. foreach ($acts as $act) {
  13168. $act_segments = getProp($act, 'segments', []);
  13169. if (!is_array($act_segments)) {
  13170. continue;
  13171. }
  13172. if ((int)$ace_mode === 1) {
  13173. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  13174. $merged_parts = [];
  13175. foreach ($act_segments as $seg) {
  13176. $seg_num = getProp($seg, 'segment_number');
  13177. $seg_content = getProp($seg, 'segment_content');
  13178. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  13179. }
  13180. $act_content = implode("\n", $merged_parts);
  13181. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  13182. $segments[] = [
  13183. 'anime_id' => $anime_id,
  13184. 'episode_id' => $episode_id,
  13185. 'episode_number' => $episode_number,
  13186. 'act_number' => getProp($act, 'act_number'),
  13187. 'act_title' => getProp($act, 'act_title'),
  13188. 'act_duration' => getProp($act, 'act_duration'),
  13189. 'act_content' => $act_content,
  13190. 'created_at' => $now,
  13191. 'updated_at' => $now
  13192. ];
  13193. } else {
  13194. foreach ($act_segments as $segment) {
  13195. $voice_actor = getProp($segment, 'voice_actor');
  13196. // 优先从上一集继承音色数据
  13197. $timbre_info = [];
  13198. if (isset($previous_roles_voice[$voice_actor])) {
  13199. // 从上一集继承音色数据
  13200. $timbre_info = $previous_roles_voice[$voice_actor];
  13201. } elseif (isset($role_arr[$voice_actor])) {
  13202. // 使用当前集的主体音色数据
  13203. $timbre_info = $role_arr[$voice_actor];
  13204. }
  13205. $voice_type = getProp($timbre_info, 'voice_type');
  13206. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  13207. if ($timbre_emotion) {
  13208. $timbre_emotion = explode(',', $timbre_emotion);
  13209. } else {
  13210. $timbre_emotion = [];
  13211. }
  13212. $emotion = getProp($segment, 'emotion', '中性');
  13213. if (!in_array($emotion, $timbre_emotion)) {
  13214. $emotion = '中性';
  13215. }
  13216. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  13217. $segments[] = [
  13218. 'anime_id' => $anime_id,
  13219. 'episode_id' => $episode_id,
  13220. 'episode_number' => $episode_number,
  13221. 'act_number' => getProp($act, 'act_number'),
  13222. 'act_title' => getProp($act, 'act_title'),
  13223. 'act_duration' => getProp($act, 'act_duration'),
  13224. 'segment_id' => getProp($segment, 'segment_id'),
  13225. 'segment_number' => getProp($segment, 'segment_number'),
  13226. 'segment_content' => getProp($segment, 'segment_content'),
  13227. 'description' => getProp($segment, 'description'),
  13228. 'composition' => getProp($segment, 'composition'),
  13229. 'camera_movement' => getProp($segment, 'camera_movement'),
  13230. 'voice_actor' => $voice_actor,
  13231. 'dialogue' => getProp($segment, 'dialogue'),
  13232. 'frame_type' => getProp($segment, 'frame_type'),
  13233. 'scene' => getProp($segment, 'scene'),
  13234. 'characters' => getProp($segment, 'characters'),
  13235. 'tail_frame' => getProp($segment, 'tail_frame'),
  13236. 'voice_name' => getProp($timbre_info, 'voice_name'),
  13237. 'voice_type' => $voice_type,
  13238. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  13239. 'emotion' => $emotion,
  13240. 'emotion_type' => $emotion_type,
  13241. 'gender' => getProp($segment, 'gender', '0'),
  13242. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  13243. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  13244. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  13245. 'pitch' => getProp($segment, 'pitch', 0),
  13246. 'created_at' => $now,
  13247. 'updated_at' => $now
  13248. ];
  13249. }
  13250. }
  13251. }
  13252. if ($segments) {
  13253. if ($del_flag) {
  13254. DB::table('mp_episode_segments')
  13255. ->where('anime_id', $anime_id)
  13256. ->where('episode_id', $episode_id)
  13257. ->delete();
  13258. }
  13259. $boolen = DB::table('mp_episode_segments')->insert($segments);
  13260. if (!$boolen) {
  13261. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  13262. Utils::throwError('20003:分镜内容保存失败');
  13263. }
  13264. }
  13265. dLog('deepseek')->info('segments', $segments);
  13266. // ace_mode=1: acts 返回值按合并格式调整
  13267. if ((int)$ace_mode === 1) {
  13268. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  13269. $act_map = [];
  13270. foreach ($table_act_data as $item) {
  13271. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  13272. }
  13273. $restructured_acts = [];
  13274. foreach ($acts as $act) {
  13275. $act_segments = getProp($act, 'segments', []);
  13276. if (!is_array($act_segments)) {
  13277. continue;
  13278. }
  13279. $merged_parts = [];
  13280. foreach ($act_segments as $seg) {
  13281. $seg_num = getProp($seg, 'segment_number');
  13282. $seg_content = getProp($seg, 'segment_content');
  13283. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  13284. }
  13285. $act_content = implode("\n", $merged_parts);
  13286. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  13287. $restructured_acts[] = [
  13288. 'anime_id' => $anime_id,
  13289. 'episode_id' => $episode_id,
  13290. 'episode_number' => $episode_number,
  13291. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  13292. 'act_number' => getProp($act, 'act_number'),
  13293. 'act_title' => getProp($act, 'act_title'),
  13294. 'act_duration' => getProp($act, 'act_duration'),
  13295. 'act_content' => $act_content,
  13296. 'created_at' => $now,
  13297. 'updated_at' => $now,
  13298. ];
  13299. }
  13300. $acts = $restructured_acts;
  13301. }
  13302. $episode['episode_id'] = $episode_id;
  13303. $episode['roles'] = $merged_roles;
  13304. $episode['scenes'] = $merged_scenes;
  13305. $episode['props'] = $merged_props;
  13306. $episode['acts'] = $acts;
  13307. return [
  13308. 'episode' => $episode,
  13309. 'episode_id' => $episode_id,
  13310. 'merged_roles' => $merged_roles,
  13311. 'merged_scenes' => $merged_scenes,
  13312. 'merged_props' => $merged_props,
  13313. ];
  13314. }
  13315. private function buildEpisodeItemContent(array $items, string $nameKey): string
  13316. {
  13317. $content = '';
  13318. foreach ($items as $item) {
  13319. $name = trim((string)getProp($item, $nameKey));
  13320. if ($name === '' || $name === '旁白') {
  13321. continue;
  13322. }
  13323. $description = trim((string)getProp($item, 'description'));
  13324. $content .= $name . ': ' . $description;
  13325. if ($nameKey == 'role') {
  13326. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  13327. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13328. $voice_name = trim(getProp($item, 'voice_name'));
  13329. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  13330. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  13331. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  13332. }else {
  13333. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  13334. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13335. }
  13336. $content .= "\n";
  13337. }
  13338. return trim($content);
  13339. }
  13340. private function getEpisodeChatContent($animeId, $sequence, $content) {
  13341. if ((int)$sequence <= 0) {
  13342. return [];
  13343. }
  13344. $origin_content = '';
  13345. if ($content) {
  13346. $origin_content = '本集剧情内容:'.$content;
  13347. }else {
  13348. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  13349. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  13350. }
  13351. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  13352. // 获取分集信息
  13353. $episode = DB::table('mp_anime_episodes')
  13354. ->where('anime_id', $animeId)
  13355. ->where('episode_number', $sequence)
  13356. ->where('is_default', 1)
  13357. ->first();
  13358. if (!$episode) {
  13359. return [];
  13360. }
  13361. $episode_id = getProp($episode, 'id');
  13362. $episode_number = getProp($episode, 'episode_number');
  13363. $title = getProp($episode, 'title');
  13364. $intro = getProp($episode, 'intro');
  13365. $art_style = getProp($episode, 'art_style');
  13366. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  13367. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  13368. // 组装纯文本内容
  13369. $content = '';
  13370. // 添加分集标题和梗概
  13371. $content .= "###第{$episode_number}集:{$title}\n\n";
  13372. $content .= "###故事梗概\n";
  13373. $content .= trim($intro) . "\n\n";
  13374. // 添加美术风格
  13375. $content .= "###美术风格\n";
  13376. $content .= trim($art_style) . "\n\n";
  13377. // 添加主体列表
  13378. $content .= "###主体列表\n";
  13379. $pangbai_voice_prompt = "";
  13380. foreach ($roles as $role) {
  13381. $name = getProp($role, 'role');
  13382. $description = getProp($role, 'description');
  13383. $pic_prompt = getProp($role, 'pic_prompt');
  13384. $voice_prompt = getProp($role, 'voice_prompt');
  13385. $voice_name = getProp($role, 'voice_name');
  13386. $content .= "{$name}: {$description}";
  13387. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13388. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  13389. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  13390. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  13391. $content .= "\n";
  13392. }
  13393. $content .= "\n";
  13394. // 添加场景列表
  13395. $content .= "###场景列表\n";
  13396. foreach ($scenes as $scene) {
  13397. $name = getProp($scene, 'scene');
  13398. $description = getProp($scene, 'description');
  13399. $pic_prompt = getProp($scene, 'pic_prompt');
  13400. $content .= "{$name}: {$description}";
  13401. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  13402. $content .= "\n";
  13403. }
  13404. $content .= "\n";
  13405. // 获取分镜信息
  13406. $segments = DB::table('mp_episode_segments')
  13407. ->where('anime_id', $animeId)
  13408. ->where('episode_id', $episode_id)
  13409. ->orderBy('segment_number')
  13410. ->get();
  13411. if ($segments && count($segments) > 0) {
  13412. if ((int)$ace_mode === 1) {
  13413. $content .= "###分段剧本\n";
  13414. // 获取片段数量
  13415. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  13416. $content .= "片段数量:{$act_count}\n";
  13417. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  13418. $content .= "\n";
  13419. }else {
  13420. $content .= "###分镜剧本\n";
  13421. }
  13422. // 按幕分组
  13423. $currentAct = null;
  13424. foreach ($segments as $segment) {
  13425. $act_number = getProp($segment, 'act_number');
  13426. $act_title = getProp($segment, 'act_title');
  13427. $act_duration = getProp($segment, 'act_duration');
  13428. $segment_number = getProp($segment, 'segment_number');
  13429. $segment_content = getProp($segment, 'segment_content');
  13430. $scene_description = getProp($segment, 'scene_description');
  13431. $scene_name = getProp($segment, 'scene_name');
  13432. $composition = getProp($segment, 'composition');
  13433. $camera_movement = getProp($segment, 'camera_movement');
  13434. $voice_type = getProp($segment, 'voice_type');
  13435. $characters = getProp($segment, 'characters');
  13436. $dialogue = getProp($segment, 'dialogue');
  13437. $frame_type = getProp($segment, 'frame_type');
  13438. $tail_frame_description = getProp($segment, 'tail_frame_description');
  13439. // 判断是否是全能模式
  13440. if ((int)$ace_mode === 1) { // 全能模式
  13441. // 如果是新的分段,添加分段标题
  13442. if ($act_number !== $currentAct) {
  13443. $currentAct = $act_number;
  13444. $content .= "##{$act_title}\n";
  13445. $content .= "时长:{$act_duration}s\n";
  13446. }
  13447. }else {
  13448. // 如果是新的幕,添加幕标题
  13449. if ($act_number !== $currentAct) {
  13450. $currentAct = $act_number;
  13451. $content .= "##第{$act_number}幕:{$scene_name}\n";
  13452. }
  13453. }
  13454. // 添加分镜信息
  13455. $content .= "分镜{$segment_number}\n";
  13456. $content .= "分镜内容:\n{$segment_content}\n";
  13457. // $content .= "画面描述:{$scene_description}\n";
  13458. // $content .= "场景:{$scene_name}\n";
  13459. // $content .= "构图设计:{$composition}\n";
  13460. // $content .= "运镜调度:{$camera_movement}\n";
  13461. // if (!empty($voice_type)) {
  13462. // $content .= "配音角色:{$voice_type}\n";
  13463. // }
  13464. // if (!empty($characters)) {
  13465. // $content .= "出镜角色:{$characters}\n";
  13466. // }
  13467. // if (!empty($dialogue)) {
  13468. // $content .= "台词内容:\"{$dialogue}\"\n";
  13469. // }
  13470. // $content .= "画面类型:{$frame_type}\n";
  13471. // $content .= "尾帧描述:{$tail_frame_description}\n";
  13472. $content .= "\n";
  13473. }
  13474. }
  13475. $content = trim($content);
  13476. if($content) $content = "上集剧本内容:\n{$content}";
  13477. return [
  13478. [
  13479. 'role' => 'user',
  13480. 'content' => $origin_content
  13481. ],
  13482. [
  13483. 'role' => 'assistant',
  13484. 'content' => $content
  13485. ]
  13486. ];
  13487. }
  13488. private function getEpisodeChatMessages($animeId, $sequence): array
  13489. {
  13490. if ((int)$sequence <= 0) {
  13491. return [];
  13492. }
  13493. return DB::table('mp_anime_records')
  13494. ->where('anime_id', $animeId)
  13495. ->where('sequence', $sequence)
  13496. ->where('episode_id', '>', 0)
  13497. ->select('role', 'content')
  13498. ->orderBy('created_at')
  13499. ->orderBy('id')
  13500. ->get()
  13501. ->map(function ($value) {
  13502. return (array)$value;
  13503. })
  13504. ->toArray();
  13505. }
  13506. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  13507. {
  13508. $existingMap = [];
  13509. foreach ($existingItems as $item) {
  13510. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13511. if ($itemKey === '') {
  13512. continue;
  13513. }
  13514. $existingMap[$itemKey] = $item;
  13515. }
  13516. if (!$generatedItems) {
  13517. return array_values($existingItems);
  13518. }
  13519. $merged = [];
  13520. foreach ($generatedItems as $item) {
  13521. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13522. if ($itemKey === '') {
  13523. continue;
  13524. }
  13525. if (isset($existingMap[$itemKey])) {
  13526. if (trim((string)getProp($item, 'description')) === '') {
  13527. $merged[] = $existingMap[$itemKey];
  13528. continue;
  13529. }
  13530. // 检查内容是否发生变化
  13531. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  13532. if (!$isChanged) {
  13533. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  13534. $mergedItem = [
  13535. $nameKey => trim((string)getProp($item, $nameKey)),
  13536. 'description' => trim((string)getProp($item, 'description')),
  13537. ];
  13538. // 如果有 pic_prompt,添加到合并项中
  13539. $picPrompt = getProp($item, 'pic_prompt');
  13540. if (!empty($picPrompt)) {
  13541. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  13542. }
  13543. // 继承现有项的 URL
  13544. $existingUrl = getProp($existingMap[$itemKey], 'url');
  13545. if (!empty($existingUrl)) {
  13546. $mergedItem['url'] = $existingUrl;
  13547. }
  13548. // 继承现有项的 task_id
  13549. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  13550. if (!empty($existingTaskId)) {
  13551. $mergedItem['task_id'] = $existingTaskId;
  13552. }
  13553. // 继承现有项的 task_status
  13554. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  13555. if (!empty($existingTaskStatus)) {
  13556. $mergedItem['task_status'] = $existingTaskStatus;
  13557. }
  13558. // 保留生成项的音色字段
  13559. $voiceName = getProp($item, 'voice_name');
  13560. if (!empty($voiceName)) {
  13561. $mergedItem['voice_name'] = $voiceName;
  13562. }
  13563. $voiceType = getProp($item, 'voice_type');
  13564. if (!empty($voiceType)) {
  13565. $mergedItem['voice_type'] = $voiceType;
  13566. }
  13567. $audioUrl = getProp($item, 'voice_audio_url');
  13568. if (!empty($audioUrl)) {
  13569. $mergedItem['voice_audio_url'] = $audioUrl;
  13570. }
  13571. $merged[] = $mergedItem;
  13572. } else {
  13573. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  13574. $mergedItem = [
  13575. $nameKey => trim((string)getProp($item, $nameKey)),
  13576. 'description' => trim((string)getProp($item, 'description')),
  13577. ];
  13578. // 如果有 pic_prompt,添加到合并项中
  13579. $picPrompt = getProp($item, 'pic_prompt');
  13580. if (!empty($picPrompt)) {
  13581. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  13582. }
  13583. // 保留生成项的音色字段
  13584. $voiceName = getProp($item, 'voice_name');
  13585. if (!empty($voiceName)) {
  13586. $mergedItem['voice_name'] = $voiceName;
  13587. }
  13588. $voiceType = getProp($item, 'voice_type');
  13589. if (!empty($voiceType)) {
  13590. $mergedItem['voice_type'] = $voiceType;
  13591. }
  13592. $audioUrl = getProp($item, 'voice_audio_url');
  13593. if (!empty($audioUrl)) {
  13594. $mergedItem['voice_audio_url'] = $audioUrl;
  13595. }
  13596. // 不继承 URL、task_id 和 task_status(重置状态)
  13597. $merged[] = $mergedItem;
  13598. }
  13599. } else {
  13600. // 新增项,保留生成项的所有字段
  13601. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  13602. }
  13603. }
  13604. return $merged ?: array_values($existingItems);
  13605. }
  13606. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  13607. {
  13608. $resetItem = [
  13609. $nameKey => trim((string)getProp($item, $nameKey)),
  13610. 'description' => trim((string)getProp($item, 'description')),
  13611. ];
  13612. // 保留指定的字段
  13613. foreach ($preserveFields as $field) {
  13614. $value = getProp($item, $field);
  13615. if (!empty($value)) {
  13616. $resetItem[$field] = $value;
  13617. }
  13618. }
  13619. return $resetItem;
  13620. }
  13621. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  13622. {
  13623. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  13624. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  13625. if ($existingKey !== $generatedKey) {
  13626. return true;
  13627. }
  13628. // 比较 description 是否变化
  13629. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  13630. return true;
  13631. }
  13632. // 比较 pic_prompt 是否变化
  13633. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  13634. }
  13635. private function normalizeEpisodeResourceKey($value): string
  13636. {
  13637. $value = trim((string)$value);
  13638. if ($value === '') {
  13639. return '';
  13640. }
  13641. return strtolower((string)preg_replace('/\s+/u', '', $value));
  13642. }
  13643. // 生成全局角色图片
  13644. private function batchSetGlobalRoleImg($data, $is_force=false) {
  13645. $anime_id = getProp($data, 'anime_id');
  13646. if (!$anime_id) Utils::throwError('1002:请选择对话');
  13647. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  13648. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  13649. $art_style = getProp($anime, 'art_style');
  13650. $update_flag = false;
  13651. foreach ($roles as &$role) {
  13652. $role_name = getProp($role, 'role');
  13653. if ($role_name == '旁白') continue;
  13654. // 优先使用 pic_prompt,如果没有则使用 description
  13655. $pic_prompt = getProp($role, 'pic_prompt');
  13656. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  13657. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  13658. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  13659. // 参考图地址
  13660. $ref_img_url = getProp($role, 'url');
  13661. if (!$is_force && $ref_img_url) continue;
  13662. $update_flag = true;
  13663. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  13664. try {
  13665. $params = [
  13666. 'prompt' => $description,
  13667. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  13668. 'ref_img_urls' => []
  13669. ];
  13670. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13671. $task_id = $task->id;
  13672. if (!$task_id) {
  13673. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  13674. }
  13675. $role['task_id'] = $task_id;
  13676. $role['task_status'] = 'processing';
  13677. } catch (\Exception $e) {
  13678. Utils::throwError("20003:" . $e->getMessage());
  13679. }
  13680. }
  13681. if (!$update_flag) return true;
  13682. // 保存角色信息
  13683. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  13684. 'roles' => json_encode($roles, 256),
  13685. 'generate_status' => '执行中',
  13686. 'generate_at' => date('Y-m-d H:i:s'),
  13687. 'updated_at' => date('Y-m-d H:i:s')
  13688. ]);
  13689. if (!$boolen) {
  13690. Utils::throwError('20003:保存角色信息失败');
  13691. }
  13692. return $boolen;
  13693. }
  13694. // 生成全局场景图片
  13695. private function batchSetGlobalSceneImg($data, $is_force=false) {
  13696. $anime_id = getProp($data, 'anime_id');
  13697. if (!$anime_id) Utils::throwError('1002:请选择对话');
  13698. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  13699. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  13700. $art_style = getProp($anime, 'art_style');
  13701. $update_flag = false;
  13702. foreach ($scenes as &$scene) {
  13703. $scene_name = getProp($scene, 'scene');
  13704. // 优先使用 pic_prompt,如果没有则使用 description
  13705. $pic_prompt = getProp($scene, 'pic_prompt');
  13706. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  13707. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  13708. // 参考图地址
  13709. $ref_img_url = getProp($scene, 'url');
  13710. if (!$is_force && $ref_img_url) continue;
  13711. $update_flag = true;
  13712. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  13713. try {
  13714. $params = [
  13715. 'prompt' => $description,
  13716. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  13717. 'ref_img_urls' => []
  13718. ];
  13719. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13720. $task_id = $task->id;
  13721. if (!$task_id) {
  13722. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  13723. }
  13724. $scene['task_id'] = $task_id;
  13725. $scene['task_status'] = 'processing';
  13726. } catch (\Exception $e) {
  13727. Utils::throwError("20003:" . $e->getMessage());
  13728. }
  13729. }
  13730. if (!$update_flag) return true;
  13731. // 保存角色信息
  13732. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  13733. 'scenes' => json_encode($scenes, 256),
  13734. 'generate_status' => '执行中',
  13735. 'generate_at' => date('Y-m-d H:i:s'),
  13736. 'updated_at' => date('Y-m-d H:i:s')
  13737. ]);
  13738. if (!$boolen) {
  13739. Utils::throwError('20003:保存角色信息失败');
  13740. }
  13741. return $boolen;
  13742. }
  13743. // 生成分镜主体、场景和道具图片
  13744. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  13745. $character_prefix = '';
  13746. $scene_prefix = '';
  13747. $prop_prefix = '';
  13748. if ($art_style_type) {
  13749. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  13750. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  13751. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  13752. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  13753. }
  13754. $update_flag = false;
  13755. // 获取上一集的roles、scenes和props数据
  13756. $prev_roles = [];
  13757. $prev_scenes = [];
  13758. $prev_props = [];
  13759. if ($episode_number > 1) {
  13760. $prev_episode = DB::table('mp_anime_episodes')
  13761. ->where('anime_id', $anime_id)
  13762. ->where('episode_number', $episode_number - 1)
  13763. ->where('is_default', 1)
  13764. ->first();
  13765. if ($prev_episode) {
  13766. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  13767. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  13768. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  13769. dLog('deepseek')->info("获取上一集数据成功", [
  13770. 'anime_id' => $anime_id,
  13771. 'prev_episode_number' => $episode_number - 1,
  13772. 'prev_roles_count' => count($prev_roles),
  13773. 'prev_scenes_count' => count($prev_scenes),
  13774. 'prev_props_count' => count($prev_props)
  13775. ]);
  13776. }
  13777. }
  13778. // 处理角色图片生成
  13779. foreach ($roles as &$role) {
  13780. $role_name = getProp($role, 'role');
  13781. if ($role_name == '旁白') continue;
  13782. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  13783. if (isset($ref_products[$role_name])) {
  13784. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  13785. $role['three_view_image_url'] = isset($ref_products[$role_name]['three_view_image_url']) ? $ref_products[$role_name]['three_view_image_url'] : '';
  13786. if ($role['url']) continue;
  13787. }
  13788. $role_description = getProp($role, 'description');
  13789. $role_pic_prompt = getProp($role, 'pic_prompt');
  13790. $role_url = getProp($role, 'url');
  13791. // 检查是否可以从上一集继承
  13792. $inherited = false;
  13793. if (!$is_force && !empty($prev_roles)) {
  13794. foreach ($prev_roles as $prev_role) {
  13795. $prev_role_name = getProp($prev_role, 'role');
  13796. $prev_description = getProp($prev_role, 'description');
  13797. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  13798. $prev_url = getProp($prev_role, 'url');
  13799. $prev_task_id = getProp($prev_role, 'task_id');
  13800. $prev_task_status = getProp($prev_role, 'task_status');
  13801. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  13802. if ($role_name == $prev_role_name
  13803. && $role_description == $prev_description
  13804. && $role_pic_prompt == $prev_pic_prompt
  13805. && !empty($prev_url)) {
  13806. $role['task_id'] = $prev_task_id;
  13807. $role['task_status'] = $prev_task_status;
  13808. $role['url'] = $prev_url;
  13809. $inherited = true;
  13810. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  13811. 'anime_id' => $anime_id,
  13812. 'episode_number' => $episode_number,
  13813. 'task_id' => $prev_task_id,
  13814. 'url' => $prev_url
  13815. ]);
  13816. break;
  13817. }
  13818. }
  13819. }
  13820. // 如果已继承或已有url,跳过生成
  13821. if ($inherited || (!$is_force && $role_url)) {
  13822. continue;
  13823. }
  13824. // 优先使用 pic_prompt,如果没有则使用 description
  13825. $pic_prompt = getProp($role, 'pic_prompt');
  13826. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  13827. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  13828. $update_flag = true;
  13829. // 调用AIImageGenerationService的生成图片任务接口
  13830. try {
  13831. $params = [
  13832. 'prompt' => $description,
  13833. 'ref_img_urls' => []
  13834. ];
  13835. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13836. $task_id = $task->id;
  13837. if (!$task_id) {
  13838. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  13839. continue; // 不中断,继续处理其他角色
  13840. }
  13841. $role['task_id'] = $task_id;
  13842. $role['task_status'] = 'processing';
  13843. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  13844. 'anime_id' => $anime_id,
  13845. 'episode_number' => $episode_number,
  13846. 'task_id' => $task_id
  13847. ]);
  13848. } catch (\Exception $e) {
  13849. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  13850. // 不抛出异常,继续处理其他角色
  13851. }
  13852. }
  13853. // 处理场景图片生成
  13854. foreach ($scenes as &$scene) {
  13855. $scene_name = getProp($scene, 'scene');
  13856. $scene_description = getProp($scene, 'description');
  13857. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  13858. $scene_url = getProp($scene, 'url');
  13859. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  13860. if (isset($ref_products[$scene_name])) {
  13861. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  13862. $scene['three_view_image_url'] = isset($ref_products[$scene_name]['three_view_image_url']) ? $ref_products[$scene_name]['three_view_image_url'] : '';
  13863. if ($scene['url']) continue;
  13864. }
  13865. // 检查是否可以从上一集继承
  13866. $inherited = false;
  13867. if (!$is_force && !empty($prev_scenes)) {
  13868. foreach ($prev_scenes as $prev_scene) {
  13869. $prev_scene_name = getProp($prev_scene, 'scene');
  13870. $prev_description = getProp($prev_scene, 'description');
  13871. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  13872. $prev_url = getProp($prev_scene, 'url');
  13873. $prev_task_id = getProp($prev_scene, 'task_id');
  13874. $prev_task_status = getProp($prev_scene, 'task_status');
  13875. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  13876. if ($scene_name == $prev_scene_name
  13877. && $scene_description == $prev_description
  13878. && $scene_pic_prompt == $prev_pic_prompt
  13879. && !empty($prev_url)) {
  13880. $scene['task_id'] = $prev_task_id;
  13881. $scene['task_status'] = $prev_task_status;
  13882. $scene['url'] = $prev_url;
  13883. $inherited = true;
  13884. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  13885. 'anime_id' => $anime_id,
  13886. 'episode_number' => $episode_number,
  13887. 'task_id' => $prev_task_id,
  13888. 'url' => $prev_url
  13889. ]);
  13890. break;
  13891. }
  13892. }
  13893. }
  13894. // 如果已继承或已有url,跳过生成
  13895. if ($inherited || (!$is_force && $scene_url)) {
  13896. continue;
  13897. }
  13898. // 优先使用 pic_prompt,如果没有则使用 description
  13899. $pic_prompt = getProp($scene, 'pic_prompt');
  13900. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  13901. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  13902. $update_flag = true;
  13903. // 调用AIImageGenerationService的生成图片任务接口
  13904. try {
  13905. $params = [
  13906. 'prompt' => $description,
  13907. 'ref_img_urls' => []
  13908. ];
  13909. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13910. $task_id = $task->id;
  13911. if (!$task_id) {
  13912. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  13913. continue; // 不中断,继续处理其他场景
  13914. }
  13915. $scene['task_id'] = $task_id;
  13916. $scene['task_status'] = 'processing';
  13917. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  13918. 'anime_id' => $anime_id,
  13919. 'episode_number' => $episode_number,
  13920. 'task_id' => $task_id
  13921. ]);
  13922. } catch (\Exception $e) {
  13923. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  13924. // 不抛出异常,继续处理其他场景
  13925. }
  13926. }
  13927. // 处理道具图片生成(逻辑与场景一致)
  13928. foreach ($props as &$prop) {
  13929. $prop_name = getProp($prop, 'prop');
  13930. $prop_description = getProp($prop, 'description');
  13931. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  13932. $prop_url = getProp($prop, 'url');
  13933. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  13934. if (isset($ref_products[$prop_name])) {
  13935. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  13936. $prop['three_view_image_url'] = isset($ref_products[$prop_name]['three_view_image_url']) ? $ref_products[$prop_name]['three_view_image_url'] : '';
  13937. if ($prop['url']) continue;
  13938. }
  13939. // 检查是否可以从上一集继承
  13940. $inherited = false;
  13941. if (!$is_force && !empty($prev_props)) {
  13942. foreach ($prev_props as $prev_prop) {
  13943. $prev_prop_name = getProp($prev_prop, 'prop');
  13944. $prev_description = getProp($prev_prop, 'description');
  13945. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  13946. $prev_url = getProp($prev_prop, 'url');
  13947. $prev_task_id = getProp($prev_prop, 'task_id');
  13948. $prev_task_status = getProp($prev_prop, 'task_status');
  13949. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  13950. if ($prop_name == $prev_prop_name
  13951. && $prop_description == $prev_description
  13952. && $prop_pic_prompt == $prev_pic_prompt
  13953. && !empty($prev_url)) {
  13954. $prop['task_id'] = $prev_task_id;
  13955. $prop['task_status'] = $prev_task_status;
  13956. $prop['url'] = $prev_url;
  13957. $inherited = true;
  13958. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  13959. 'anime_id' => $anime_id,
  13960. 'episode_number' => $episode_number,
  13961. 'task_id' => $prev_task_id,
  13962. 'url' => $prev_url
  13963. ]);
  13964. break;
  13965. }
  13966. }
  13967. }
  13968. // 如果已继承或已有url,跳过生成
  13969. if ($inherited || (!$is_force && $prop_url)) {
  13970. continue;
  13971. }
  13972. // 优先使用 pic_prompt,如果没有则使用 description
  13973. $pic_prompt = getProp($prop, 'pic_prompt');
  13974. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  13975. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  13976. $update_flag = true;
  13977. // 调用AIImageGenerationService的生成图片任务接口
  13978. try {
  13979. $params = [
  13980. 'prompt' => $description,
  13981. 'ref_img_urls' => []
  13982. ];
  13983. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13984. $task_id = $task->id;
  13985. if (!$task_id) {
  13986. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  13987. continue; // 不中断,继续处理其他道具
  13988. }
  13989. $prop['task_id'] = $task_id;
  13990. $prop['task_status'] = 'processing';
  13991. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  13992. 'anime_id' => $anime_id,
  13993. 'episode_number' => $episode_number,
  13994. 'task_id' => $task_id
  13995. ]);
  13996. } catch (\Exception $e) {
  13997. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  13998. // 不抛出异常,继续处理其他道具
  13999. }
  14000. }
  14001. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  14002. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  14003. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  14004. // // 保存剧集的角色和场景信息
  14005. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  14006. // 'roles' => json_encode($roles, 256),
  14007. // 'scenes' => json_encode($scenes, 256),
  14008. // 'generate_status' => '执行中',
  14009. // 'generate_at' => date('Y-m-d H:i:s'),
  14010. // 'updated_at' => date('Y-m-d H:i:s')
  14011. // ]);
  14012. // if (!$boolen) {
  14013. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  14014. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  14015. // }
  14016. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  14017. // 'episode_id' => $episode_id,
  14018. 'roles_count' => count($roles),
  14019. 'scenes_count' => count($scenes),
  14020. 'props_count' => count($props)
  14021. ]);
  14022. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  14023. }
  14024. /**
  14025. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  14026. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  14027. *
  14028. * @param int $anime_id 动漫对话ID
  14029. * @param array $episode_roles 剧集角色数据
  14030. * @param array $episode_scenes 剧集场景数据
  14031. * @param array $episode_props 剧集道具数据
  14032. * @return bool
  14033. */
  14034. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  14035. // 获取全局数据
  14036. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  14037. if (!$anime) {
  14038. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  14039. return false;
  14040. }
  14041. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  14042. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  14043. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  14044. $roles_added = false;
  14045. $roles_updated = false;
  14046. $scenes_added = false;
  14047. $props_added = false;
  14048. // 处理角色同步
  14049. foreach ($episode_roles as $episode_role) {
  14050. $episode_role_name = getProp($episode_role, 'role');
  14051. $episode_description = getProp($episode_role, 'description');
  14052. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  14053. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  14054. // 跳过旁白
  14055. if ($episode_role_name == '旁白') {
  14056. continue;
  14057. }
  14058. // 检查全局中是否已存在相同的角色
  14059. $exists = false;
  14060. $global_role_index = -1;
  14061. foreach ($global_roles as $index => $global_role) {
  14062. $global_role_name = getProp($global_role, 'role');
  14063. $global_description = getProp($global_role, 'description');
  14064. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  14065. // 如果role、description、pic_prompt三项都一致,则认为已存在
  14066. if ($episode_role_name == $global_role_name
  14067. && $episode_description == $global_description
  14068. && $episode_pic_prompt == $global_pic_prompt) {
  14069. $exists = true;
  14070. $global_role_index = $index;
  14071. break;
  14072. }
  14073. }
  14074. // 如果不存在,则添加到全局
  14075. if (!$exists) {
  14076. $global_roles[] = $episode_role;
  14077. $roles_added = true;
  14078. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  14079. 'anime_id' => $anime_id,
  14080. 'role' => $episode_role_name
  14081. ]);
  14082. } else {
  14083. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  14084. if (!empty($episode_voice_prompt)) {
  14085. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  14086. // 如果全局没有voice_prompt或与剧集不一致,则更新
  14087. if ($global_voice_prompt !== $episode_voice_prompt) {
  14088. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  14089. $roles_updated = true;
  14090. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  14091. 'anime_id' => $anime_id,
  14092. 'role' => $episode_role_name,
  14093. 'voice_prompt' => $episode_voice_prompt
  14094. ]);
  14095. }
  14096. }
  14097. }
  14098. }
  14099. // 处理场景同步
  14100. foreach ($episode_scenes as $episode_scene) {
  14101. $episode_scene_name = getProp($episode_scene, 'scene');
  14102. $episode_description = getProp($episode_scene, 'description');
  14103. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  14104. // 检查全局中是否已存在相同的场景
  14105. $exists = false;
  14106. foreach ($global_scenes as $global_scene) {
  14107. $global_scene_name = getProp($global_scene, 'scene');
  14108. $global_description = getProp($global_scene, 'description');
  14109. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  14110. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  14111. if ($episode_scene_name == $global_scene_name
  14112. && $episode_description == $global_description
  14113. && $episode_pic_prompt == $global_pic_prompt) {
  14114. $exists = true;
  14115. break;
  14116. }
  14117. }
  14118. // 如果不存在,则添加到全局
  14119. if (!$exists) {
  14120. $global_scenes[] = $episode_scene;
  14121. $scenes_added = true;
  14122. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  14123. 'anime_id' => $anime_id,
  14124. 'scene' => $episode_scene_name
  14125. ]);
  14126. }
  14127. }
  14128. // 处理道具同步(逻辑与场景一致)
  14129. foreach ($episode_props as $episode_prop) {
  14130. $episode_prop_name = getProp($episode_prop, 'prop');
  14131. $episode_description = getProp($episode_prop, 'description');
  14132. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  14133. // 检查全局中是否已存在相同的道具
  14134. $exists = false;
  14135. foreach ($global_props as $global_prop) {
  14136. $global_prop_name = getProp($global_prop, 'prop');
  14137. $global_description = getProp($global_prop, 'description');
  14138. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  14139. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  14140. if ($episode_prop_name == $global_prop_name
  14141. && $episode_description == $global_description
  14142. && $episode_pic_prompt == $global_pic_prompt) {
  14143. $exists = true;
  14144. break;
  14145. }
  14146. }
  14147. // 如果不存在,则添加到全局
  14148. if (!$exists) {
  14149. $global_props[] = $episode_prop;
  14150. $props_added = true;
  14151. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  14152. 'anime_id' => $anime_id,
  14153. 'prop' => $episode_prop_name
  14154. ]);
  14155. }
  14156. }
  14157. // 如果有新增或更新,则更新全局数据
  14158. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  14159. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  14160. if ($roles_added || $roles_updated) {
  14161. $update_data['roles'] = json_encode($global_roles, 256);
  14162. }
  14163. if ($scenes_added) {
  14164. $update_data['scenes'] = json_encode($global_scenes, 256);
  14165. }
  14166. if ($props_added) {
  14167. $update_data['props'] = json_encode($global_props, 256);
  14168. }
  14169. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  14170. dLog('deepseek')->info('剧集数据同步到全局完成', [
  14171. 'anime_id' => $anime_id,
  14172. 'roles_added' => $roles_added,
  14173. 'roles_updated' => $roles_updated,
  14174. 'scenes_added' => $scenes_added,
  14175. 'props_added' => $props_added,
  14176. 'global_roles_count' => count($global_roles),
  14177. 'global_scenes_count' => count($global_scenes),
  14178. 'global_props_count' => count($global_props)
  14179. ]);
  14180. }
  14181. return true;
  14182. }
  14183. /**
  14184. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  14185. *
  14186. * @param int $anime_id 动漫对话ID
  14187. * @param int $episode_id 分集ID
  14188. * @return bool
  14189. */
  14190. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  14191. // 获取全局角色和场景数据
  14192. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  14193. if (!$anime) {
  14194. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  14195. return false;
  14196. }
  14197. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  14198. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  14199. // 获取指定的分集
  14200. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  14201. if (!$episode) {
  14202. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  14203. return false;
  14204. }
  14205. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  14206. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  14207. $roles_updated = false;
  14208. $scenes_updated = false;
  14209. // 继承角色的task_id、task_status和url
  14210. foreach ($episode_roles as &$episode_role) {
  14211. $episode_role_name = getProp($episode_role, 'role');
  14212. $episode_description = getProp($episode_role, 'description');
  14213. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  14214. $episode_url = getProp($episode_role, 'url');
  14215. // 跳过旁白角色
  14216. if ($episode_role_name == '旁白') {
  14217. continue;
  14218. }
  14219. // 如果剧集中已有URL,跳过
  14220. if (!empty($episode_url)) {
  14221. continue;
  14222. }
  14223. // 遍历全局角色数据,查找匹配的角色
  14224. foreach ($global_roles as $global_role) {
  14225. $global_role_name = getProp($global_role, 'role');
  14226. $global_description = getProp($global_role, 'description');
  14227. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  14228. $global_url = getProp($global_role, 'url');
  14229. $global_task_id = getProp($global_role, 'task_id');
  14230. $global_task_status = getProp($global_role, 'task_status');
  14231. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  14232. if ($episode_role_name == $global_role_name
  14233. && $episode_description == $global_description
  14234. && $episode_pic_prompt == $global_pic_prompt) {
  14235. // 继承 task_id、task_status 和 url
  14236. if (!empty($global_task_id)) {
  14237. $episode_role['task_id'] = $global_task_id;
  14238. $episode_role['task_status'] = $global_task_status;
  14239. $roles_updated = true;
  14240. dLog('deepseek')->info('剧集角色继承全局task_id', [
  14241. 'episode_id' => $episode_id,
  14242. 'role' => $episode_role_name,
  14243. 'task_id' => $global_task_id,
  14244. 'task_status' => $global_task_status
  14245. ]);
  14246. }
  14247. if (!empty($global_url)) {
  14248. $episode_role['url'] = $global_url;
  14249. $roles_updated = true;
  14250. dLog('deepseek')->info('剧集角色继承全局url', [
  14251. 'episode_id' => $episode_id,
  14252. 'role' => $episode_role_name,
  14253. 'url' => $global_url
  14254. ]);
  14255. }
  14256. break;
  14257. }
  14258. }
  14259. }
  14260. // 继承场景的task_id、task_status和url
  14261. foreach ($episode_scenes as &$episode_scene) {
  14262. $episode_scene_name = getProp($episode_scene, 'scene');
  14263. $episode_description = getProp($episode_scene, 'description');
  14264. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  14265. $episode_url = getProp($episode_scene, 'url');
  14266. // 如果剧集中已有URL,跳过
  14267. if (!empty($episode_url)) {
  14268. continue;
  14269. }
  14270. // 遍历全局场景数据,查找匹配的场景
  14271. foreach ($global_scenes as $global_scene) {
  14272. $global_scene_name = getProp($global_scene, 'scene');
  14273. $global_description = getProp($global_scene, 'description');
  14274. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  14275. $global_url = getProp($global_scene, 'url');
  14276. $global_task_id = getProp($global_scene, 'task_id');
  14277. $global_task_status = getProp($global_scene, 'task_status');
  14278. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  14279. if ($episode_scene_name == $global_scene_name
  14280. && $episode_description == $global_description
  14281. && $episode_pic_prompt == $global_pic_prompt) {
  14282. // 继承 task_id、task_status 和 url
  14283. if (!empty($global_task_id)) {
  14284. $episode_scene['task_id'] = $global_task_id;
  14285. $episode_scene['task_status'] = $global_task_status;
  14286. $scenes_updated = true;
  14287. dLog('deepseek')->info('剧集场景继承全局task_id', [
  14288. 'episode_id' => $episode_id,
  14289. 'scene' => $episode_scene_name,
  14290. 'task_id' => $global_task_id,
  14291. 'task_status' => $global_task_status
  14292. ]);
  14293. }
  14294. if (!empty($global_url)) {
  14295. $episode_scene['url'] = $global_url;
  14296. $scenes_updated = true;
  14297. dLog('deepseek')->info('剧集场景继承全局url', [
  14298. 'episode_id' => $episode_id,
  14299. 'scene' => $episode_scene_name,
  14300. 'url' => $global_url
  14301. ]);
  14302. }
  14303. break;
  14304. }
  14305. }
  14306. }
  14307. // 如果有更新,则保存到数据库
  14308. if ($roles_updated || $scenes_updated) {
  14309. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  14310. if ($roles_updated) {
  14311. $update_data['roles'] = json_encode($episode_roles, 256);
  14312. }
  14313. if ($scenes_updated) {
  14314. $update_data['scenes'] = json_encode($episode_scenes, 256);
  14315. }
  14316. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  14317. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  14318. 'episode_id' => $episode_id,
  14319. 'roles_updated' => $roles_updated,
  14320. 'scenes_updated' => $scenes_updated
  14321. ]);
  14322. }
  14323. return true;
  14324. }
  14325. public function chatChangeImg($data) {
  14326. // 文生文计费预检(normal 档)
  14327. $uid = Site::getUid();
  14328. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints('', 'normal'), $uid);
  14329. $segment = getProp($data, 'segment');
  14330. $segment_content = getProp($segment, 'segment_content');
  14331. $prompt = getProp($data, 'prompt');
  14332. $ref_img = getProp($data, 'ref_img');
  14333. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  14334. // 处理文本模型
  14335. $model = getProp($data, 'model');
  14336. if (!$model) {
  14337. // 用户没有输入,从anime表获取
  14338. $segment_id = getProp($segment, 'segment_id');
  14339. if ($segment_id) {
  14340. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  14341. if ($episode_id) {
  14342. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  14343. if ($anime_id) {
  14344. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  14345. }
  14346. }
  14347. }
  14348. if (!$model) {
  14349. // anime表也没有,使用默认值
  14350. $model = 'doubao-seed-2-0-mini-260215';
  14351. }
  14352. }
  14353. // 验证模型是否在可用模型表中
  14354. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  14355. $model = 'doubao-seed-2-0-mini-260215';
  14356. }
  14357. $messages[] =
  14358. [
  14359. 'role' => 'user',
  14360. 'content' => $question
  14361. ];
  14362. $post_data = [
  14363. 'model' => $model,
  14364. 'messages' => $messages,
  14365. // 'max_tokens' => 8192,
  14366. 'temperature' => 0.7,
  14367. 'frequency_penalty' => 0,
  14368. 'presence_penalty' => 0,
  14369. 'response_format' => ['type' => 'text'],
  14370. 'stream' => false // 是否启用流式输出
  14371. ];
  14372. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  14373. if (is_array($chatResult)) {
  14374. extract($chatResult);
  14375. }else {
  14376. Utils::throwError('20003: 接口调用失败!');
  14377. }
  14378. // 文生文成功计费(normal 档):同时记录积分与 token 明细
  14379. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  14380. 'model' => $model,
  14381. 'source' => 'chatChangeImg',
  14382. ], 'normal');
  14383. return [
  14384. 'type' => 'done',
  14385. // 'episode' => $episode,
  14386. 'answer' => $fullContent,
  14387. 'reasoning' => $fullReasoningContent,
  14388. 'usage' => $usage
  14389. ];
  14390. }
  14391. /**
  14392. * 仅调用 deepseek 对话接口(非流式)
  14393. *
  14394. * @param array $post_data
  14395. * @param int $timeout
  14396. * @return array
  14397. */
  14398. private function chatOnly($post_data, $timeout = 1800) {
  14399. $post_data['max_tokens'] = 300000;
  14400. $client = new Client(['timeout' => $timeout, 'verify' => false]);
  14401. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  14402. $response = $result->getBody()->getContents();
  14403. $response_arr = json_decode($response, true);
  14404. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  14405. $fullContent = '';
  14406. $fullReasoningContent = [];
  14407. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  14408. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  14409. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  14410. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  14411. }
  14412. return [
  14413. 'fullContent' => $fullContent,
  14414. 'fullReasoningContent' => $fullReasoningContent,
  14415. 'usage' => $usage
  14416. ];
  14417. }
  14418. /**
  14419. * 用 deepseek-v4-flash 非流式分析报错,返回不超过50字的用户友好提示
  14420. *
  14421. * @param string $errorMessage
  14422. * @return string|null
  14423. */
  14424. public function analyzeErrorMessage($errorMessage)
  14425. {
  14426. try {
  14427. $post_data = [
  14428. 'model' => 'deepseek-v4-flash',
  14429. 'messages' => [
  14430. [
  14431. 'role' => 'system',
  14432. 'content' => '你是视频生成任务的报错分析助手。请根据用户给出的原始报错,用一句中文提示告诉用户问题原因和下一步怎么做,不超过50个字,直接输出提示内容,不要解释、不要输出代码。',
  14433. ],
  14434. [
  14435. 'role' => 'user',
  14436. 'content' => (string)$errorMessage,
  14437. ],
  14438. ],
  14439. 'temperature' => 0.3,
  14440. 'frequency_penalty' => 0,
  14441. 'presence_penalty' => 0,
  14442. 'response_format' => ['type' => 'text'],
  14443. 'stream' => false,
  14444. ];
  14445. $result = $this->chatOnly($post_data, 8);
  14446. // 调用成功即记录 token 使用明细(不扣积分),保证错误分析这类隐性 AI 调用进入统计口径
  14447. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  14448. 'model' => 'deepseek-v4-flash',
  14449. 'source' => 'analyzeErrorMessage',
  14450. ], 'deepseek-v4-flash');
  14451. $content = trim((string)($result['fullContent'] ?? ''));
  14452. if ($content === '') {
  14453. return null;
  14454. }
  14455. return mb_substr($content, 0, 50);
  14456. } catch (\Exception $e) {
  14457. dLog('deepseek')->error('视频任务报错分析失败: ' . $e->getMessage(), [
  14458. 'error_message' => $errorMessage
  14459. ]);
  14460. return null;
  14461. }
  14462. }
  14463. // 仅调用 GPT-5.4 对话接口(非流式)
  14464. private function gpt54ChatOnly($post_data) {
  14465. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  14466. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  14467. // gpt-5.4 中转已下线,强制映射到 gpt-5.6-sol
  14468. if ($modelName === 'gpt-5.4') {
  14469. $modelName = 'gpt-5.6-terra';
  14470. $post_data['model'] = $modelName;
  14471. }
  14472. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  14473. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  14474. $usedLunaFallback = false;
  14475. if (empty($apiKey)) {
  14476. Utils::throwError('20003:GPT-5.4 API Key未配置');
  14477. }
  14478. // 先探活,服务不可用时自动重试
  14479. $this->ensureGptServiceAvailable($apiKey);
  14480. $client = new Client(['timeout' => 1800, 'verify' => false]);
  14481. // 移除 thinking 参数,GPT-5.4 不支持
  14482. if (isset($post_data['thinking'])) {
  14483. unset($post_data['thinking']);
  14484. }
  14485. if (isset($post_data['reasoning_effort'])) {
  14486. unset($post_data['reasoning_effort']);
  14487. }
  14488. $post_data['max_completion_tokens'] = 100000;
  14489. // 确保 stream 为 false
  14490. $post_data['stream'] = false;
  14491. $maxRetries = $this->gptRetryTimes();
  14492. $interval = $this->gptRetryInterval();
  14493. $attempt = 0;
  14494. while (true) {
  14495. try {
  14496. $headers = [
  14497. 'Authorization' => 'Bearer ' . $apiKey,
  14498. 'Content-Type' => 'application/json'
  14499. ];
  14500. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  14501. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  14502. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  14503. 'json' => $post_data,
  14504. 'headers' => $headers
  14505. ]);
  14506. $response = $result->getBody()->getContents();
  14507. $response_arr = json_decode($response, true);
  14508. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  14509. $fullContent = '';
  14510. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  14511. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  14512. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  14513. }
  14514. return [
  14515. 'fullContent' => $fullContent,
  14516. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  14517. 'usage' => $usage
  14518. ];
  14519. } catch (\Exception $e) {
  14520. // 报错或超时时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  14521. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  14522. $usedLunaFallback = true;
  14523. $apiKey = $lunaApiKey;
  14524. dLog('deepseek')->warning('GPT-5.4 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  14525. continue;
  14526. }
  14527. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  14528. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  14529. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  14530. throw $e;
  14531. }
  14532. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  14533. 'retry' => $attempt + 1,
  14534. 'max_retries' => $maxRetries,
  14535. 'error' => $e->getMessage()
  14536. ]);
  14537. sleep($interval);
  14538. $attempt++;
  14539. }
  14540. }
  14541. }
  14542. public function getContentByBid($bid) {
  14543. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  14544. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  14545. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  14546. $content = '';
  14547. foreach ($chapters as $chapter) {
  14548. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  14549. }
  14550. return $content;
  14551. }
  14552. public function getContentByScriptId($script_id) {
  14553. $content = '';
  14554. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  14555. if ($contents) {
  14556. $content = implode(PHP_EOL, $contents);
  14557. }else {
  14558. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  14559. }
  14560. return $content;
  14561. }
  14562. /**
  14563. * 根据文件类型提取文本内容
  14564. *
  14565. * @param mixed $file 文件对象或文件路径
  14566. * @return string
  14567. */
  14568. public function extractFileContent($file) {
  14569. // 获取文件路径和扩展名
  14570. if (is_string($file)) {
  14571. $filePath = $file;
  14572. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  14573. } else {
  14574. // Laravel UploadedFile 对象
  14575. $filePath = $file->getRealPath();
  14576. $extension = strtolower($file->getClientOriginalExtension());
  14577. }
  14578. $content = '';
  14579. switch ($extension) {
  14580. case 'txt':
  14581. $content = $this->extractTxtContent($filePath);
  14582. break;
  14583. case 'pdf':
  14584. $content = $this->extractPdfContent($filePath);
  14585. break;
  14586. case 'doc':
  14587. case 'docx':
  14588. $content = $this->extractWordContent($filePath);
  14589. break;
  14590. // case 'jpg':
  14591. // case 'jpeg':
  14592. // case 'png':
  14593. // case 'gif':
  14594. // case 'bmp':
  14595. // case 'webp':
  14596. // $content = $this->extractImageContent($filePath);
  14597. // break;
  14598. default:
  14599. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  14600. }
  14601. // 移除非法 UTF-8 字节,避免后续 JSON 编码或正则解析异常
  14602. if (!mb_check_encoding($content, 'UTF-8')) {
  14603. $cleaned = @iconv('UTF-8', 'UTF-8//IGNORE', $content);
  14604. $content = $cleaned === false ? $content : $cleaned;
  14605. }
  14606. return $content;
  14607. }
  14608. /**
  14609. * 提取 TXT 文件内容
  14610. */
  14611. private function extractTxtContent($filePath) {
  14612. if (!file_exists($filePath)) {
  14613. Utils::throwError('20003:文件不存在');
  14614. }
  14615. $content = file_get_contents($filePath);
  14616. // 尝试检测并转换编码
  14617. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  14618. if ($encoding && $encoding !== 'UTF-8') {
  14619. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  14620. }
  14621. return trim($content);
  14622. }
  14623. /**
  14624. * 提取 PDF 文件内容
  14625. */
  14626. private function extractPdfContent($filePath) {
  14627. if (!file_exists($filePath)) {
  14628. Utils::throwError('20003:文件不存在');
  14629. }
  14630. try {
  14631. $parser = new PdfParser();
  14632. $pdf = $parser->parseFile($filePath);
  14633. $content = $pdf->getText();
  14634. return trim($content);
  14635. } catch (\Exception $e) {
  14636. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  14637. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  14638. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  14639. }
  14640. }
  14641. /**
  14642. * 提取 Word 文件内容(支持 doc 和 docx)
  14643. */
  14644. private function extractWordContent($filePath) {
  14645. if (!file_exists($filePath)) {
  14646. Utils::throwError('20003:文件不存在');
  14647. }
  14648. try {
  14649. $phpWord = WordIOFactory::load($filePath);
  14650. $content = '';
  14651. foreach ($phpWord->getSections() as $section) {
  14652. foreach ($section->getElements() as $element) {
  14653. $content .= $this->extractWordElementText($element);
  14654. // 段落边界补换行(段落内的软换行已在元素递归中处理)
  14655. $content .= "\n";
  14656. }
  14657. }
  14658. return trim($content);
  14659. } catch (\Exception $e) {
  14660. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  14661. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  14662. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  14663. }
  14664. }
  14665. /**
  14666. * 递归提取 Word 元素中的文本
  14667. */
  14668. private function extractWordElementText($element) {
  14669. $text = '';
  14670. if ($element instanceof \PhpOffice\PhpWord\Element\TextBreak
  14671. || $element instanceof \PhpOffice\PhpWord\Element\LineBreak) {
  14672. // 软换行:保留 Word 中的换行显示,避免"第X集"标题与正文粘连
  14673. $text .= "\n";
  14674. } elseif (method_exists($element, 'getElements')) {
  14675. foreach ($element->getElements() as $childElement) {
  14676. $text .= $this->extractWordElementText($childElement);
  14677. }
  14678. } elseif (method_exists($element, 'getText')) {
  14679. $text .= $element->getText();
  14680. }
  14681. return $text;
  14682. }
  14683. /**
  14684. * 提取图片内容(使用火山引擎 OCR)
  14685. */
  14686. private function extractImageContent($filePath) {
  14687. if (!file_exists($filePath)) {
  14688. Utils::throwError('20003:文件不存在');
  14689. }
  14690. try {
  14691. // 读取图片并转换为 base64
  14692. $imageData = file_get_contents($filePath);
  14693. $base64Image = base64_encode($imageData);
  14694. // 调用火山引擎 OCR 服务
  14695. $content = $this->callVolcEngineOCR($base64Image);
  14696. return trim($content);
  14697. } catch (\Exception $e) {
  14698. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  14699. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  14700. Utils::throwError('20003:图片识别失败');
  14701. }
  14702. }
  14703. /**
  14704. * 调用火山引擎 OCR 服务识别图片文字
  14705. *
  14706. * @param string $base64Image base64 编码的图片数据
  14707. * @return string 识别的文字内容
  14708. */
  14709. private function callVolcEngineOCR($base64Image) {
  14710. $method = 'POST';
  14711. $service = 'cv';
  14712. $host = 'visual.volcengineapi.com';
  14713. $region = env('VOLC_REGION', 'cn-north-1');
  14714. $access_key = env('VOLC_AK');
  14715. $secret_key = env('VOLC_SK');
  14716. $action = 'OCRNormal';
  14717. $version = '2020-08-26';
  14718. if (!$access_key || !$secret_key) {
  14719. Utils::throwError('20003:请配置火山引擎 AK/SK');
  14720. }
  14721. // 请求体
  14722. $body = json_encode([
  14723. 'image_base64' => $base64Image
  14724. ]);
  14725. // 生成签名
  14726. $headers = $this->getVolcEngineSignHeaders(
  14727. $method, $service, $host, $region,
  14728. "Action={$action}&Version={$version}",
  14729. $access_key, $secret_key, $body
  14730. );
  14731. $client = new Client(['timeout' => 1800, 'verify' => false]);
  14732. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  14733. 'headers' => $headers,
  14734. 'body' => $body
  14735. ]);
  14736. $response_arr = json_decode($response->getBody()->getContents(), true);
  14737. // 提取识别的文字
  14738. $textLines = [];
  14739. if (isset($response_arr['data']['line_texts'])) {
  14740. $textLines = $response_arr['data']['line_texts'];
  14741. } elseif (isset($response_arr['data']['ocr_infos'])) {
  14742. foreach ($response_arr['data']['ocr_infos'] as $info) {
  14743. if (isset($info['text'])) {
  14744. $textLines[] = $info['text'];
  14745. }
  14746. }
  14747. }
  14748. if (empty($textLines)) {
  14749. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  14750. return '';
  14751. }
  14752. return implode("\n", $textLines);
  14753. }
  14754. /**
  14755. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  14756. */
  14757. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  14758. $contentType = 'application/json';
  14759. $accept = 'application/json';
  14760. // 获取当前UTC时间
  14761. $t = new DateTime('now', new DateTimeZone('UTC'));
  14762. $xDate = $t->format('Ymd\THis\Z');
  14763. $dateStamp = $t->format('Ymd');
  14764. // 计算 body 的 sha256 哈希
  14765. $payloadHash = hash('sha256', $body);
  14766. // 1. 拼接规范请求串
  14767. $canonicalUri = '/';
  14768. $canonicalQueryString = $queryString;
  14769. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  14770. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  14771. $canonicalRequest = implode("\n", [
  14772. $method,
  14773. $canonicalUri,
  14774. $canonicalQueryString,
  14775. $canonicalHeaders,
  14776. $signedHeaders,
  14777. $payloadHash
  14778. ]);
  14779. // 2. 拼接待签名字符串
  14780. $algorithm = 'HMAC-SHA256';
  14781. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  14782. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  14783. $stringToSign = implode("\n", [
  14784. $algorithm,
  14785. $xDate,
  14786. $credentialScope,
  14787. $hashedCanonicalRequest
  14788. ]);
  14789. // 3. 计算签名
  14790. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  14791. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  14792. // 4. 添加签名到请求头
  14793. $authorizationHeader = sprintf(
  14794. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  14795. $algorithm,
  14796. $access_key,
  14797. $credentialScope,
  14798. $signedHeaders,
  14799. $signature
  14800. );
  14801. return [
  14802. 'Accept' => $accept,
  14803. 'Content-Type' => $contentType,
  14804. 'Host' => $host,
  14805. 'X-Date' => $xDate,
  14806. 'X-Content-Sha256'=> $payloadHash,
  14807. 'Authorization' => $authorizationHeader
  14808. ];
  14809. }
  14810. public function generateScriptWords($cid, $model = 'r1') {
  14811. ini_set('max_execution_time', 0);
  14812. if (!$cid) Utils::throwError('20003: 请选择章节!');
  14813. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  14814. // 模型兼容性处理和思考模式设置
  14815. $thinkingMode = 'disabled';
  14816. $reasoningEffort = 'high';
  14817. if ($model == 'r1') {
  14818. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  14819. $thinkingMode = 'enabled';
  14820. } else {
  14821. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  14822. $thinkingMode = 'disabled';
  14823. }
  14824. $messages = [
  14825. [
  14826. 'role' => 'system',
  14827. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  14828. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  14829. 2.非对话部分请全部用旁白角色代替
  14830. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  14831. ],
  14832. [
  14833. 'role' => 'user',
  14834. 'content' => $content
  14835. ]
  14836. ];
  14837. $post_data = [
  14838. 'model' => $model,
  14839. 'messages' => $messages,
  14840. // 'max_tokens' => 8192,
  14841. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  14842. 'frequency_penalty' => 0,
  14843. 'presence_penalty' => 0,
  14844. 'thinking' => ['type' => $thinkingMode],
  14845. 'response_format' => [
  14846. 'type' => 'text'
  14847. ],
  14848. 'stream' => false
  14849. ];
  14850. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  14851. // 根据模型类型选择调用方法
  14852. $fullContent = '';
  14853. $usage = [];
  14854. $chatResult = $this->dispatchChatOnlyByModel($post_data);
  14855. if (is_array($chatResult)) {
  14856. $fullContent = $chatResult['fullContent'];
  14857. $usage = $chatResult['usage'] ?? [];
  14858. }
  14859. // 仅记录 token 使用明细(不扣积分)
  14860. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  14861. 'model' => $model,
  14862. 'cid' => $cid,
  14863. 'source' => 'generateScriptWords',
  14864. ], $model);
  14865. return $fullContent;
  14866. }
  14867. /**
  14868. * 智能化解析集数信息
  14869. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  14870. *
  14871. * @param string $prompt 用户输入的提示词
  14872. * @return int|null 解析出的集数,如果没有找到则返回null
  14873. */
  14874. private function extractEpisodeNumber($prompt)
  14875. {
  14876. if (empty($prompt)) {
  14877. return null;
  14878. }
  14879. // 定义各种可能的表达模式
  14880. $patterns = [
  14881. // 基本模式:改成N集、调整成N集、修改成N集
  14882. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  14883. // 扩展模式:分成N集、拆分成N集、分割成N集
  14884. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  14885. // 数量模式:N集、共N集、总共N集
  14886. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  14887. // 制作模式:制作N集、生成N集、创建N集
  14888. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  14889. // 计划模式:计划N集、预计N集、打算N集
  14890. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  14891. // 需要模式:需要N集、要N集
  14892. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  14893. // 中文数字模式:改成三集、调整成五集等
  14894. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  14895. // 英文数字模式
  14896. '/(?: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',
  14897. ];
  14898. // 中文数字转阿拉伯数字的映射
  14899. $chineseNumbers = [
  14900. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  14901. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  14902. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  14903. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  14904. ];
  14905. // 逐个尝试匹配模式
  14906. foreach ($patterns as $pattern) {
  14907. if (preg_match($pattern, $prompt, $matches)) {
  14908. $number = trim($matches[1]);
  14909. // 如果是中文数字,转换为阿拉伯数字
  14910. if (isset($chineseNumbers[$number])) {
  14911. return $chineseNumbers[$number];
  14912. }
  14913. // 如果是阿拉伯数字,直接返回
  14914. if (is_numeric($number)) {
  14915. $episodeNum = intval($number);
  14916. // 合理性检查:集数应该在1-100之间
  14917. if ($episodeNum >= 1 && $episodeNum <= 100) {
  14918. return $episodeNum;
  14919. }
  14920. }
  14921. }
  14922. }
  14923. return null;
  14924. }
  14925. /**
  14926. * 调用火山引擎对话(Chat) API
  14927. *
  14928. * @param array $params 包含以下参数:
  14929. * - model: 模型ID(必填)
  14930. * - messages: 消息列表(必填)
  14931. * - stream: 是否流式输出(可选,默认false)
  14932. * - max_tokens: 最大输出token数(可选)
  14933. * - temperature: 采样温度(可选,默认1)
  14934. * - top_p: 核采样概率(可选,默认0.7)
  14935. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  14936. * - presence_penalty: 存在惩罚系数(可选,默认0)
  14937. * - stop: 停止词(可选)
  14938. * - tools: 工具列表(可选)
  14939. * @return array|Generator 非流式返回数组,流式返回生成器
  14940. */
  14941. public function volcEngineChatCompletion(array $params)
  14942. {
  14943. // 百度 GLM 已由 dispatchStreamByModel / dispatchChatOnlyByModel 统一分发,此处不再转发
  14944. $frontModel = getProp($params, 'model', '');
  14945. if (in_array($frontModel, $this->baidu_glm_text_models, true)) {
  14946. Utils::throwError('20003:百度GLM模型请使用统一分发方法dispatchStreamByModel/dispatchChatOnlyByModel调用');
  14947. }
  14948. $apiKey = env('VOLC_AI_API_KEY');
  14949. if (empty($apiKey)) {
  14950. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  14951. }
  14952. // 构建请求参数
  14953. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  14954. $requestData = [
  14955. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  14956. 'messages' => $params['messages'] ?? [],
  14957. ];
  14958. if (!in_array($originalModel, $this->valid_text_models)) {
  14959. Utils::throwError('20003:该模型不支持!');
  14960. }
  14961. // 添加可选参数
  14962. if (isset($params['stream'])) {
  14963. $requestData['stream'] = $params['stream'];
  14964. }
  14965. if (isset($params['stream_options'])) {
  14966. $requestData['stream_options'] = $params['stream_options'];
  14967. }
  14968. if (isset($params['max_tokens'])) {
  14969. $requestData['max_tokens'] = $params['max_tokens'];
  14970. }else if (isset($params['max_completion_tokens'])) {
  14971. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  14972. }else {
  14973. $requestData['max_completion_tokens'] = 100000;
  14974. }
  14975. if (isset($params['temperature'])) {
  14976. $requestData['temperature'] = $params['temperature'];
  14977. }
  14978. if (isset($params['top_p'])) {
  14979. $requestData['top_p'] = $params['top_p'];
  14980. }
  14981. if (isset($params['frequency_penalty'])) {
  14982. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  14983. }
  14984. if (isset($params['presence_penalty'])) {
  14985. $requestData['presence_penalty'] = $params['presence_penalty'];
  14986. }
  14987. if (isset($params['stop'])) {
  14988. $requestData['stop'] = $params['stop'];
  14989. }
  14990. if (isset($params['tools'])) {
  14991. $requestData['tools'] = $params['tools'];
  14992. }
  14993. if (isset($params['tool_choice'])) {
  14994. $requestData['tool_choice'] = $params['tool_choice'];
  14995. }
  14996. if (isset($params['response_format'])) {
  14997. $requestData['response_format'] = $params['response_format'];
  14998. }
  14999. if (isset($params['thinking'])) {
  15000. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  15001. if (is_array($params['thinking'])) {
  15002. $requestData['thinking'] = $params['thinking'];
  15003. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  15004. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  15005. }
  15006. } else {
  15007. $requestData['thinking'] = ['type' => $params['thinking']];
  15008. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  15009. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  15010. }
  15011. }
  15012. } else {
  15013. $requestData['thinking'] = ['type' => 'disabled'];
  15014. }
  15015. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  15016. $client = new Client(['verify' => false, 'timeout' => 1800]);
  15017. try {
  15018. // 判断是否为流式输出
  15019. $isStream = isset($params['stream']) && $params['stream'] === true;
  15020. if ($isStream) {
  15021. // 流式输出
  15022. // 流式请求默认声明返回 usage(未显式传参时)
  15023. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  15024. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  15025. } else {
  15026. // 非流式输出
  15027. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  15028. 'headers' => [
  15029. 'Authorization' => 'Bearer ' . $apiKey,
  15030. 'Content-Type' => 'application/json',
  15031. ],
  15032. 'json' => $requestData
  15033. ]);
  15034. $responseData = json_decode($response->getBody(), true);
  15035. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  15036. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  15037. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  15038. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  15039. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  15040. }
  15041. return [
  15042. 'fullContent' => $fullContent,
  15043. 'fullReasoningContent' => $fullReasoningContent,
  15044. 'usage' => $usage
  15045. ];
  15046. }
  15047. } catch (\Exception $e) {
  15048. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  15049. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  15050. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  15051. }
  15052. }
  15053. /**
  15054. * 火山引擎对话API流式输出
  15055. *
  15056. * @param Client $client HTTP客户端
  15057. * @param string $apiKey API密钥
  15058. * @param array $requestData 请求数据
  15059. * @return Generator
  15060. */
  15061. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  15062. {
  15063. try {
  15064. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  15065. 'headers' => [
  15066. 'Authorization' => 'Bearer ' . $apiKey,
  15067. 'Content-Type' => 'application/json',
  15068. ],
  15069. 'json' => $requestData,
  15070. 'stream' => true
  15071. ]);
  15072. $body = $response->getBody();
  15073. $buffer = '';
  15074. $fullContent = '';
  15075. $fullReasoningContent = '';
  15076. $usage = [];
  15077. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  15078. // 逐行读取流式响应
  15079. while (!$body->eof()) {
  15080. $chunk = $body->read(1024);
  15081. $buffer .= $chunk;
  15082. // 按行分割
  15083. $lines = explode("\n", $buffer);
  15084. $buffer = array_pop($lines);
  15085. foreach ($lines as $line) {
  15086. $line = trim($line);
  15087. if (empty($line)) {
  15088. continue;
  15089. }
  15090. // 检查是否是SSE数据行
  15091. if (strpos($line, 'data: ') !== 0) {
  15092. continue;
  15093. }
  15094. $data = substr($line, 6);
  15095. if ($data === '[DONE]') {
  15096. dLog('deepseek')->info('收到结束标记');
  15097. break 2;
  15098. }
  15099. try {
  15100. $json = json_decode($data, true);
  15101. if (json_last_error() !== JSON_ERROR_NONE) {
  15102. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  15103. continue;
  15104. }
  15105. if (isset($json['choices'][0]['delta'])) {
  15106. $delta = $json['choices'][0]['delta'];
  15107. // 处理思维链内容
  15108. if (isset($delta['reasoning_content'])) {
  15109. $fullReasoningContent .= $delta['reasoning_content'];
  15110. yield [
  15111. 'type' => 'reasoning',
  15112. 'content' => $delta['reasoning_content'],
  15113. 'full_reasoning' => $fullReasoningContent
  15114. ];
  15115. }
  15116. // 处理回答内容
  15117. if (isset($delta['content'])) {
  15118. $fullContent .= $delta['content'];
  15119. yield [
  15120. 'type' => 'content',
  15121. 'content' => $delta['content'],
  15122. ];
  15123. }
  15124. }
  15125. // 获取使用统计信息
  15126. if (isset($json['usage'])) {
  15127. $usage = $json['usage'];
  15128. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  15129. }
  15130. } catch (\Exception $e) {
  15131. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  15132. continue;
  15133. }
  15134. }
  15135. }
  15136. dLog('deepseek')->info('流式读取完成', [
  15137. 'content_length' => strlen($fullContent),
  15138. 'reasoning_length' => strlen($fullReasoningContent)
  15139. ]);
  15140. yield [
  15141. 'type' => 'done',
  15142. 'full_content' => $fullContent,
  15143. 'full_reasoning' => $fullReasoningContent,
  15144. 'usage' => $usage
  15145. ];
  15146. } catch (\Exception $e) {
  15147. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  15148. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  15149. throw $e;
  15150. }
  15151. }
  15152. /**
  15153. * 检查并创建图片生成任务
  15154. *
  15155. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  15156. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  15157. * @param string $nameKey 资源名称字段('role' 或 'scene')
  15158. * @param string $art_style 美术风格
  15159. * @return array 更新后的资源列表
  15160. */
  15161. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  15162. {
  15163. // 确保参数为数组
  15164. $merged_items = is_array($merged_items) ? $merged_items : [];
  15165. $global_items = is_array($global_items) ? $global_items : [];
  15166. // 构建全局资源映射表,用于快速查找
  15167. $global_map = [];
  15168. foreach ($global_items as $item) {
  15169. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  15170. if ($itemKey === '') {
  15171. continue;
  15172. }
  15173. $global_map[$itemKey] = $item;
  15174. }
  15175. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  15176. foreach ($merged_items as &$item) {
  15177. $item_name = getProp($item, $nameKey);
  15178. $item_description = getProp($item, 'description');
  15179. // $item_url = getProp($item, 'url');
  15180. // // 如果已有图片URL,跳过
  15181. // if (!empty($item_url)) {
  15182. // continue;
  15183. // }
  15184. // 如果是旁白角色,跳过
  15185. if ($nameKey === 'role' && $item_name === '旁白') {
  15186. continue;
  15187. }
  15188. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  15189. if ($itemKey === '') {
  15190. continue;
  15191. }
  15192. $need_create_task = false;
  15193. // 条件1:在全局资源中找不到匹配的名称
  15194. if (!isset($global_map[$itemKey])) {
  15195. $need_create_task = true;
  15196. } else {
  15197. // 条件2:名称匹配但描述或 pic_prompt 不一致
  15198. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  15199. $current_description = trim((string)$item_description);
  15200. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  15201. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  15202. // 如果 description 或 pic_prompt 有变化,需要重新生成
  15203. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  15204. $need_create_task = true;
  15205. }
  15206. }
  15207. // 如果需要创建任务,调用图片生成服务
  15208. if ($need_create_task) {
  15209. try {
  15210. // 优先使用 pic_prompt,如果没有则使用 description
  15211. $pic_prompt = getProp($item, 'pic_prompt');
  15212. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  15213. // 添加美术风格前缀
  15214. if ($art_style) {
  15215. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  15216. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  15217. $description = "{$prefix}:{$description}";
  15218. }
  15219. $params = [
  15220. 'prompt' => $description,
  15221. 'ref_img_urls' => []
  15222. ];
  15223. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  15224. $task_id = $task->id;
  15225. if ($task_id) {
  15226. $item['task_id'] = $task_id;
  15227. $item['task_status'] = 'processing';
  15228. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  15229. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  15230. }
  15231. } catch (\Exception $e) {
  15232. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  15233. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  15234. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  15235. // 不抛出异常,继续处理其他资源
  15236. }
  15237. }
  15238. }
  15239. return $merged_items;
  15240. }
  15241. /**
  15242. * 同步新出现的主体和场景到全局
  15243. *
  15244. * @param int $anime_id 动漫ID
  15245. * @param array $merged_roles 合并后的角色列表
  15246. * @param array $merged_scenes 合并后的场景列表
  15247. * @param array $global_roles 全局角色列表
  15248. * @param array $global_scenes 全局场景列表
  15249. * @return void
  15250. */
  15251. private function syncNewResourcesToGlobal(
  15252. int $anime_id,
  15253. array $merged_roles,
  15254. array $merged_scenes,
  15255. array $global_roles,
  15256. array $global_scenes
  15257. ): void {
  15258. // 构建全局角色映射表
  15259. $global_role_map = [];
  15260. foreach ($global_roles as $role) {
  15261. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  15262. if ($roleKey !== '') {
  15263. $global_role_map[$roleKey] = $role;
  15264. }
  15265. }
  15266. // 构建全局场景映射表
  15267. $global_scene_map = [];
  15268. foreach ($global_scenes as $scene) {
  15269. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  15270. if ($sceneKey !== '') {
  15271. $global_scene_map[$sceneKey] = $scene;
  15272. }
  15273. }
  15274. $need_update = false;
  15275. $new_global_roles = $global_roles;
  15276. $new_global_scenes = $global_scenes;
  15277. // 检查并添加新角色到全局
  15278. foreach ($merged_roles as $role) {
  15279. $role_name = getProp($role, 'role');
  15280. // 跳过旁白
  15281. if ($role_name === '旁白') {
  15282. continue;
  15283. }
  15284. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  15285. if ($roleKey === '') {
  15286. continue;
  15287. }
  15288. // 如果全局中不存在该角色,添加到全局
  15289. if (!isset($global_role_map[$roleKey])) {
  15290. $new_global_roles[] = [
  15291. 'role' => $role_name,
  15292. 'description' => getProp($role, 'description', ''),
  15293. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  15294. 'voice_name' => getProp($role, 'voice_name', ''),
  15295. 'voice_type' => getProp($role, 'voice_type', ''),
  15296. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  15297. 'url' => getProp($role, 'url', ''),
  15298. 'task_id' => getProp($role, 'task_id', ''),
  15299. 'task_status' => getProp($role, 'task_status', ''),
  15300. ];
  15301. $global_role_map[$roleKey] = true; // 标记已添加
  15302. $need_update = true;
  15303. dLog('deepseek')->info("新角色同步到全局", [
  15304. 'anime_id' => $anime_id,
  15305. 'role' => $role_name,
  15306. 'task_id' => getProp($role, 'task_id', ''),
  15307. ]);
  15308. }
  15309. // else {
  15310. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  15311. // $global_role = $global_role_map[$roleKey];
  15312. // if (is_array($global_role)) {
  15313. // $updated = false;
  15314. // $update_fields = [];
  15315. // // 检查描述是否更新
  15316. // $current_description = trim((string)getProp($role, 'description'));
  15317. // $global_description = trim((string)getProp($global_role, 'description'));
  15318. // if ($current_description !== '' && $current_description !== $global_description) {
  15319. // $updated = true;
  15320. // $update_fields[] = 'description';
  15321. // }
  15322. // // 检查pic_prompt是否更新
  15323. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  15324. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  15325. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  15326. // $updated = true;
  15327. // $update_fields[] = 'pic_prompt';
  15328. // }
  15329. // // 检查图片任务信息是否更新
  15330. // $current_task_id = getProp($role, 'task_id');
  15331. // $global_task_id = getProp($global_role, 'task_id');
  15332. // if ($current_task_id && $current_task_id !== $global_task_id) {
  15333. // $updated = true;
  15334. // $update_fields[] = 'task_id';
  15335. // }
  15336. // // 如果有更新,同步到全局
  15337. // if ($updated) {
  15338. // foreach ($new_global_roles as &$global_role_item) {
  15339. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  15340. // if ($global_role_key === $roleKey) {
  15341. // if (in_array('description', $update_fields)) {
  15342. // $global_role_item['description'] = $current_description;
  15343. // }
  15344. // if (in_array('pic_prompt', $update_fields)) {
  15345. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  15346. // }
  15347. // if (in_array('task_id', $update_fields)) {
  15348. // $global_role_item['task_id'] = $current_task_id;
  15349. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  15350. // $global_role_item['url'] = getProp($role, 'url', '');
  15351. // }
  15352. // break;
  15353. // }
  15354. // }
  15355. // $need_update = true;
  15356. // dLog('deepseek')->info("角色信息更新到全局", [
  15357. // 'anime_id' => $anime_id,
  15358. // 'role' => $role_name,
  15359. // 'update_fields' => implode(',', $update_fields),
  15360. // ]);
  15361. // }
  15362. // }
  15363. // }
  15364. }
  15365. // 检查并添加新场景到全局
  15366. foreach ($merged_scenes as $scene) {
  15367. $scene_name = getProp($scene, 'scene');
  15368. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  15369. if ($sceneKey === '') {
  15370. continue;
  15371. }
  15372. // 如果全局中不存在该场景,添加到全局
  15373. if (!isset($global_scene_map[$sceneKey])) {
  15374. $new_global_scenes[] = [
  15375. 'scene' => $scene_name,
  15376. 'description' => getProp($scene, 'description', ''),
  15377. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  15378. 'url' => getProp($scene, 'url', ''),
  15379. 'task_id' => getProp($scene, 'task_id', ''),
  15380. 'task_status' => getProp($scene, 'task_status', ''),
  15381. ];
  15382. $global_scene_map[$sceneKey] = true; // 标记已添加
  15383. $need_update = true;
  15384. dLog('deepseek')->info("新场景同步到全局", [
  15385. 'anime_id' => $anime_id,
  15386. 'scene' => $scene_name,
  15387. 'task_id' => getProp($scene, 'task_id', ''),
  15388. ]);
  15389. }
  15390. // else {
  15391. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  15392. // $global_scene = $global_scene_map[$sceneKey];
  15393. // if (is_array($global_scene)) {
  15394. // $updated = false;
  15395. // $update_fields = [];
  15396. // // 检查描述是否更新
  15397. // $current_description = trim((string)getProp($scene, 'description'));
  15398. // $global_description = trim((string)getProp($global_scene, 'description'));
  15399. // if ($current_description !== '' && $current_description !== $global_description) {
  15400. // $updated = true;
  15401. // $update_fields[] = 'description';
  15402. // }
  15403. // // 检查pic_prompt是否更新
  15404. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  15405. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  15406. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  15407. // $updated = true;
  15408. // $update_fields[] = 'pic_prompt';
  15409. // }
  15410. // // 检查图片任务信息是否更新
  15411. // $current_task_id = getProp($scene, 'task_id');
  15412. // $global_task_id = getProp($global_scene, 'task_id');
  15413. // if ($current_task_id && $current_task_id !== $global_task_id) {
  15414. // $updated = true;
  15415. // $update_fields[] = 'task_id';
  15416. // }
  15417. // // 如果有更新,同步到全局
  15418. // if ($updated) {
  15419. // foreach ($new_global_scenes as &$global_scene_item) {
  15420. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  15421. // if ($global_scene_key === $sceneKey) {
  15422. // if (in_array('description', $update_fields)) {
  15423. // $global_scene_item['description'] = $current_description;
  15424. // }
  15425. // if (in_array('pic_prompt', $update_fields)) {
  15426. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  15427. // }
  15428. // if (in_array('task_id', $update_fields)) {
  15429. // $global_scene_item['task_id'] = $current_task_id;
  15430. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  15431. // $global_scene_item['url'] = getProp($scene, 'url', '');
  15432. // }
  15433. // break;
  15434. // }
  15435. // }
  15436. // $need_update = true;
  15437. // dLog('deepseek')->info("场景信息更新到全局", [
  15438. // 'anime_id' => $anime_id,
  15439. // 'scene' => $scene_name,
  15440. // 'update_fields' => implode(',', $update_fields),
  15441. // ]);
  15442. // }
  15443. // }
  15444. // }
  15445. }
  15446. // 如果有新增或更新,更新数据库
  15447. if ($need_update) {
  15448. $update_data = [
  15449. 'roles' => json_encode($new_global_roles, 256),
  15450. 'scenes' => json_encode($new_global_scenes, 256),
  15451. 'updated_at' => date('Y-m-d H:i:s'),
  15452. ];
  15453. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  15454. if ($result !== false) {
  15455. dLog('deepseek')->info("全局角色和场景更新成功", [
  15456. 'anime_id' => $anime_id,
  15457. 'roles_count' => count($new_global_roles),
  15458. 'scenes_count' => count($new_global_scenes),
  15459. ]);
  15460. } else {
  15461. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  15462. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  15463. }
  15464. }
  15465. }
  15466. }