DeepSeekService.php 843 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466
  1. <?php
  2. namespace App\Services\DeepSeek;
  3. use App\Consts\ErrorConst;
  4. use App\Consts\BaseConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use GuzzleHttp\Client;
  8. use DateTime;
  9. use DateTimeZone;
  10. use App\Models\MpTaskCenter;
  11. use App\Models\MpUserPointsDetail;
  12. use App\Services\AIGeneration\AIImageGenerationService;
  13. use App\Services\PointsService;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Log;
  16. use Illuminate\Support\Facades\Redis;
  17. use OSS\Core\OssException;
  18. use OSS\OssClient;
  19. use Smalot\PdfParser\Parser as PdfParser;
  20. use TCPDF;
  21. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  22. use Predis\Command\Traits\Get\Get;
  23. class DeepSeekService
  24. {
  25. private $url;
  26. private $api_key;
  27. private $sys_message;
  28. private $headers;
  29. private $valid_text_models;
  30. private $gpt_text_models;
  31. private $gemini_text_models;
  32. protected $aiImageGenerationService;
  33. protected $pointsService;
  34. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  35. $this->aiImageGenerationService = $aiImageGenerationService;
  36. $this->pointsService = $pointsService;
  37. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  38. $this->api_key = env('DEEPSEEK_API_KEY');
  39. $this->headers = [
  40. 'Authorization' => 'Bearer '.$this->api_key,
  41. 'Content-Type' => 'application/json; charset=UTF-8'
  42. ];
  43. // 火山引擎模型列表
  44. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  45. // GPT文本模型列表
  46. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  47. // Gemini文本模型列表
  48. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  49. $this->sys_message = [
  50. 'role' => 'system',
  51. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  52. 强制要求:\n
  53. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  54. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  55. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  56. 普通要求:\n
  57. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  58. 2.<分集剧本>的要求如下:
  59.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  60.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  61.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  62.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  63. \n\n
  64. 示例如下:\n
  65. ###剧本名:西昆仑
  66. ###故事梗概
  67. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  68. ###剧本亮点
  69. 亮点1:绝境奇药,生死一线
  70. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  71. 亮点2:结拜兄妹,化解尴尬
  72. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  73. 亮点3:纤发夺命,情愫暗涌
  74. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  75. ###人物关系
  76. 阿雪与梁萧之间存在兄妹之情。
  77. ###核心矛盾
  78. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  79. ###主体列表
  80. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  81. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  82. 阴阳球:天地异宝,能化生精气,救人于危难。
  83. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  84. ###美术风格
  85. 基础画风风格词:厚涂古风
  86. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  87. ###场景列表
  88. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  89. ###分集剧本
  90. ##分集01
  91. 第1集: 第一集的标题
  92. 场景描述:地点、时间、场景
  93. 运镜:固定近距离
  94. 出场角色:男主、女主
  95. 台词内容:
  96. 女主: 女主对话
  97. 男主:男主对话
  98. 女主: 女主对话
  99. 男主: 男主对话
  100. ##分集02
  101. 第2集: 第二集的标题
  102. 场景描述:地点、时间、场景
  103. 运镜:固定近距离
  104. 出场角色:男主、女主
  105. 台词内容:
  106. 女主: 女主对话
  107. 男主:男主对话
  108. 女主: 女主对话
  109. 男主: 男主对话"
  110. ];
  111. }
  112. /**
  113. * 通用文生文方法 - 支持多模型流式输出、图片输入;视频输入仅 Gemini 模型支持
  114. *
  115. * @param array $data 请求参数
  116. * @return \Generator 返回生成器,用于流式输出
  117. */
  118. public function generateText($data) {
  119. // 获取请求参数
  120. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  121. $messages = getProp($data, 'messages', []);
  122. $systemPrompt = getProp($data, 'system_prompt', '');
  123. $prompt = getProp($data, 'prompt', '');
  124. $images = getProp($data, 'images', []); // 支持多张图片
  125. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  126. $videos = getProp($data, 'videos', []); // Gemini 支持视频文件
  127. $videoUrls = getProp($data, 'video_urls', []); // Gemini 支持视频URL
  128. $isGeminiModel = in_array($model, $this->gemini_text_models);
  129. if ((!empty($videos) || !empty($videoUrls)) && !$isGeminiModel) {
  130. Utils::throwError('20003:仅Gemini模型支持视频输入');
  131. }
  132. // Gemini 多模态(图片/视频 -> 文本)按模型预检积分;纯文本不扣费
  133. $uid = Site::getUid();
  134. $chargeModality = '';
  135. $chargePoints = 0;
  136. $hasImageMedia = !empty($images) || !empty($imageUrls)
  137. || $this->messagesContainMedia($messages, ['image_url', 'image']);
  138. $hasVideoMedia = !empty($videos) || !empty($videoUrls)
  139. || $this->messagesContainMedia($messages, ['video_url', 'video']);
  140. if ($isGeminiModel && ($hasImageMedia || $hasVideoMedia)) {
  141. $chargeModality = $hasVideoMedia ? 'video' : 'image';
  142. $pricingModel = $this->geminiMultimodalPricingModel($model);
  143. if ($pricingModel !== '') {
  144. $chargePoints = $this->pointsService->getVideoChargePoints(['model' => $pricingModel]);
  145. if ($chargePoints > 0) {
  146. $this->pointsService->checkUserPointsEnough($chargePoints, $uid);
  147. }
  148. }
  149. }
  150. // 如果没有提供messages,则根据system_prompt、content和images构建
  151. if (empty($messages)) {
  152. $messages = [];
  153. // 添加系统提示词
  154. if (!empty($systemPrompt)) {
  155. $messages[] = [
  156. 'role' => 'system',
  157. 'content' => $systemPrompt
  158. ];
  159. }
  160. // 构建用户消息内容(支持文本+图片)
  161. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  162. $userMessage = [
  163. 'role' => 'user',
  164. 'content' => []
  165. ];
  166. // 添加文本内容
  167. if (!empty($prompt)) {
  168. $userMessage['content'][] = [
  169. 'type' => 'text',
  170. 'text' => $prompt
  171. ];
  172. }
  173. // 处理上传的图片文件
  174. if (!empty($images)) {
  175. if (!is_array($images)) {
  176. $images = [$images];
  177. }
  178. foreach ($images as $image) {
  179. $imageBase64 = $this->processImageToBase64($image);
  180. if ($imageBase64) {
  181. $userMessage['content'][] = [
  182. 'type' => 'image_url',
  183. 'image_url' => [
  184. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  185. ]
  186. ];
  187. }
  188. }
  189. }
  190. // 处理图片URL
  191. if (!empty($imageUrls)) {
  192. if (!is_array($imageUrls)) {
  193. $imageUrls = [$imageUrls];
  194. }
  195. foreach ($imageUrls as $url) {
  196. if (!empty($url)) {
  197. $userMessage['content'][] = [
  198. 'type' => 'image_url',
  199. 'image_url' => [
  200. 'url' => $url
  201. ]
  202. ];
  203. }
  204. }
  205. }
  206. // 处理上传的视频文件(仅 Gemini)
  207. if (!empty($videos) && $isGeminiModel) {
  208. if (!is_array($videos)) {
  209. $videos = [$videos];
  210. }
  211. foreach ($videos as $video) {
  212. $inlineData = $this->processMediaToInlineData($video);
  213. if ($inlineData) {
  214. $userMessage['content'][] = [
  215. 'type' => 'video',
  216. 'inline_data' => $inlineData
  217. ];
  218. }
  219. }
  220. }
  221. // 处理视频URL(仅 Gemini)
  222. if (!empty($videoUrls) && $isGeminiModel) {
  223. if (!is_array($videoUrls)) {
  224. $videoUrls = [$videoUrls];
  225. }
  226. foreach ($videoUrls as $url) {
  227. if (!empty($url)) {
  228. $userMessage['content'][] = [
  229. 'type' => 'video_url',
  230. 'video_url' => ['url' => $url]
  231. ];
  232. }
  233. }
  234. }
  235. // 如果只有文本内容,简化为字符串格式
  236. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  237. $userMessage['content'] = $userMessage['content'][0]['text'];
  238. }
  239. $messages[] = $userMessage;
  240. }
  241. }
  242. // 验证messages不为空
  243. if (empty($messages)) {
  244. Utils::throwError('20003:请提供有效的对话内容');
  245. }
  246. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  247. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  248. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  249. if ($model === 'deepseek-chat') {
  250. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  251. $model = 'deepseek-v4-flash';
  252. $thinkingMode = 'disabled';
  253. } elseif ($model === 'deepseek-reasoner') {
  254. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  255. $model = 'deepseek-v4-flash';
  256. $thinkingMode = 'enabled';
  257. }
  258. // 构建请求参数
  259. $post_data = [
  260. 'model' => $model,
  261. 'messages' => $messages,
  262. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  263. 'temperature' => getProp($data, 'temperature', 1),
  264. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  265. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  266. 'thinking' => ['type' => $thinkingMode],
  267. 'stream' => true // 启用流式输出
  268. ];
  269. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  270. // 添加可选参数
  271. if (isset($data['top_p'])) {
  272. $post_data['top_p'] = $data['top_p'];
  273. }
  274. if (isset($data['response_format'])) {
  275. $post_data['response_format'] = $data['response_format'];
  276. }
  277. // 根据模型类型选择调用方法
  278. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  279. // DeepSeek 官方模型使用 DeepSeek API
  280. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  281. } else if (in_array($model, $this->gpt_text_models)) {
  282. // GPT 模型使用 TokenRouter API
  283. $streamGenerator = $this->gpt54StreamResponse($post_data);
  284. } else if (in_array($model, $this->gemini_text_models)) {
  285. // Gemini 模型使用 Gemini API
  286. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  287. } else if (in_array($model, $this->valid_text_models)) {
  288. // 火山引擎支持的模型使用火山引擎 API
  289. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  290. } else {
  291. Utils::throwError('20003:不支持的模型: ' . $model);
  292. }
  293. if ($chargePoints > 0) {
  294. return $this->wrapGenerateTextCharge($streamGenerator, $uid, $model, $chargePoints, $chargeModality);
  295. }
  296. // 纯文本(不扣积分):流式生成成功后仅记录 token 使用明细
  297. return $this->wrapGenerateTextTokenRecord($streamGenerator, $uid, $model);
  298. }
  299. /**
  300. * 流式生成成功后仅记录 token 明细(纯文本免费场景,不扣积分)
  301. *
  302. * @param \Generator $generator
  303. * @param int $uid
  304. * @param string $model
  305. * @return \Generator
  306. */
  307. private function wrapGenerateTextTokenRecord(\Generator $generator, int $uid, string $model, string $source = 'generateText'): \Generator
  308. {
  309. $recorded = false;
  310. foreach ($generator as $chunk) {
  311. if (!$recorded && isset($chunk['type']) && $chunk['type'] === 'done') {
  312. $this->recordTextTokenOnly($uid, $this->pointsService->getTokensFromUsage(getProp($chunk, 'usage', [])), [
  313. 'model' => $model,
  314. 'source' => $source,
  315. ], $model);
  316. $recorded = true;
  317. }
  318. yield $chunk;
  319. }
  320. }
  321. /**
  322. * 流式生成成功后再按 Gemini 多模态规则扣费
  323. *
  324. * @param \Generator $generator
  325. * @param int $uid
  326. * @param string $model
  327. * @param int $points
  328. * @param string $modality
  329. * @return \Generator
  330. */
  331. private function wrapGenerateTextCharge(\Generator $generator, int $uid, string $model, int $points, string $modality): \Generator
  332. {
  333. $charged = false;
  334. foreach ($generator as $chunk) {
  335. if (!$charged && isset($chunk['type']) && $chunk['type'] === 'done') {
  336. $fullContent = (string)getProp($chunk, 'full_content', getProp($chunk, 'answer', ''));
  337. if ($fullContent !== '') {
  338. $this->chargeGeminiMultimodal($uid, $model, $points, $modality, getProp($chunk, 'usage', []));
  339. $charged = true;
  340. }
  341. }
  342. yield $chunk;
  343. }
  344. }
  345. /**
  346. * Gemini 多模态(图片/视频 -> 文本)成功后扣费并记录 token 明细
  347. *
  348. * @param int $uid
  349. * @param string $model
  350. * @param int $points
  351. * @param string $modality
  352. * @param mixed $usage
  353. * @return void
  354. */
  355. private function chargeGeminiMultimodal(int $uid, string $model, int $points, string $modality, $usage): void
  356. {
  357. $result = $this->pointsService->recordChatCharge(
  358. $uid,
  359. $points,
  360. $this->pointsService->getTokensFromUsage($usage),
  361. [
  362. 'model' => $model,
  363. 'modality' => $modality,
  364. 'source' => 'generateText',
  365. ],
  366. '',
  367. $model
  368. );
  369. if (empty($result['charged'])) {
  370. throw new \Exception('Gemini多模态计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  371. }
  372. }
  373. /**
  374. * Gemini 文本模型 ID 转 mp_video_models 中的按次计费模型 ID
  375. *
  376. * @param string $model
  377. * @return string
  378. */
  379. private function geminiMultimodalPricingModel(string $model): string
  380. {
  381. $map = [
  382. 'gemini-3.1-flash-image-preview-t' => 'gemini-3.1-flash',
  383. 'gemini-3.1-pro-preview' => 'gemini-3.1-pro',
  384. 'gemini-3-flash-preview' => 'gemini-3.0-flash',
  385. 'gemini-3-pro-preview' => 'gemini-3.0-pro',
  386. 'gemini-3.6-flash' => 'gemini-3.6-flash',
  387. ];
  388. return $map[$model] ?? '';
  389. }
  390. /**
  391. * 检查 OpenAI 风格消息中是否包含指定媒体类型
  392. *
  393. * @param array $messages
  394. * @param array $mediaTypes
  395. * @return bool
  396. */
  397. private function messagesContainMedia(array $messages, array $mediaTypes): bool
  398. {
  399. foreach ($messages as $message) {
  400. $content = getProp($message, 'content', '');
  401. if (!is_array($content)) {
  402. continue;
  403. }
  404. foreach ($content as $part) {
  405. if (is_array($part) && in_array(getProp($part, 'type', ''), $mediaTypes, true)) {
  406. return true;
  407. }
  408. }
  409. }
  410. return false;
  411. }
  412. public function createGenerateText($data) {
  413. $file = getProp($data, 'file');
  414. $episode_num = getProp($data, 'episode_num');
  415. $uid = Site::getUid();
  416. $cpid = Site::getCpid();
  417. if (!$file) {
  418. Utils::throwError('20003:请上传文件');
  419. }
  420. // 提取文件内容
  421. $content = $this->extractFileContent($file);
  422. if (!$content) {
  423. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  424. }
  425. // 拆分章节并校验章节总数、标题连续性
  426. if ($episode_num) {
  427. $this->validateGenerateTextChapters($content, (int)$episode_num);
  428. }
  429. // 获取原始文件名(不含扩展名)作为script_name
  430. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  431. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  432. // 字节安全剥离,不依赖服务器locale设置
  433. $originalName = $file->getClientOriginalName();
  434. $extension = $file->getClientOriginalExtension();
  435. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  436. ? substr($originalName, 0, -strlen($extension) - 1)
  437. : $originalName;
  438. if ($script_name === '') {
  439. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  440. }
  441. // 如果同一用户的剧本名存在则提示
  442. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  443. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  444. }
  445. // 插入数据到mp_scripts表
  446. $script_id = DB::table('mp_scripts')->insertGetId([
  447. 'script_name' => $script_name,
  448. 'user_id' => $uid,
  449. 'cpid' => $cpid,
  450. 'content' => $content,
  451. 'created_at' => date('Y-m-d H:i:s'),
  452. 'updated_at' => date('Y-m-d H:i:s')
  453. ]);
  454. return [
  455. 'script_id' => $script_id,
  456. 'script_name' => $script_name
  457. ];
  458. }
  459. /**
  460. * AI对话调用成功后的积分扣费(返回结果前调用)
  461. *
  462. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  463. *
  464. * @param int $uid
  465. * @param int $tokens
  466. * @param array $chargeInfo
  467. * @return void
  468. */
  469. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo): void
  470. {
  471. // api_type 记录真实模型名(缺失时回退 deepseek 大类),保证明细与统计口径准确
  472. $model = (string)getProp($chargeInfo, 'model', '');
  473. $result = $this->pointsService->recordChatCharge(
  474. $uid,
  475. $this->pointsService->getChatChargePoints($model),
  476. $tokens,
  477. $chargeInfo,
  478. '',
  479. $model !== '' ? $model : 'deepseek'
  480. );
  481. if (empty($result['charged'])) {
  482. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  483. }
  484. }
  485. /**
  486. * 安全获取当前登录用户ID
  487. *
  488. * 命令行/队列等无用户上下文的场景返回 0,由记录方法自行跳过。
  489. *
  490. * @return int
  491. */
  492. private function getCurrentUid(): int
  493. {
  494. try {
  495. return (int)Site::getUid();
  496. } catch (\Throwable $e) {
  497. return 0;
  498. }
  499. }
  500. /**
  501. * 记录文生文 token 使用明细(仅记录,不扣积分)
  502. *
  503. * 用于不按积分计费的文生文接口;记录失败不影响主流程。
  504. *
  505. * @param int $uid 用户ID(0 时跳过)
  506. * @param int $tokens 消耗 token 数
  507. * @param array $chargeInfo 计费/来源信息(model、source 等)
  508. * @param string $apiType API 类型/模型标识
  509. * @return void
  510. */
  511. private function recordTextTokenOnly(int $uid, int $tokens, array $chargeInfo, string $apiType = ''): void
  512. {
  513. try {
  514. $this->pointsService->recordTokenOnlyDetail(
  515. $uid,
  516. $tokens,
  517. $chargeInfo,
  518. MpUserPointsDetail::TYPE_CHAT,
  519. $apiType,
  520. ''
  521. );
  522. } catch (\Throwable $e) {
  523. dLog('points')->warning('token明细记录异常(不影响主流程): ' . $e->getMessage(), [
  524. 'uid' => $uid,
  525. 'source' => $chargeInfo['source'] ?? '',
  526. ]);
  527. }
  528. }
  529. /**
  530. * 拆分剧本内容并校验章节总数与标题连续性
  531. *
  532. * @param string $content
  533. * @param int $episodeNum
  534. * @return void
  535. */
  536. private function validateGenerateTextChapters($content, $episodeNum)
  537. {
  538. $chapters = splitContent($content);
  539. if (count($chapters) !== $episodeNum) {
  540. Utils::throwError('20003:章节总数与集数不一致,请检查上传内容');
  541. }
  542. if (empty($chapters)) {
  543. return;
  544. }
  545. // 先尝试从标题正则中解析序号,确认是否从1开始连续递增
  546. $numbers = [];
  547. $unparsedIndex = null;
  548. foreach ($chapters as $index => $chapter) {
  549. $num = $this->parseChapterNumber($chapter['title']);
  550. if ($num === null) {
  551. $unparsedIndex = $index;
  552. break;
  553. }
  554. $numbers[] = $num;
  555. }
  556. if ($unparsedIndex === null) {
  557. $expected = 1;
  558. foreach ($numbers as $index => $num) {
  559. if ($num !== $expected) {
  560. $title = mb_substr(trim((string)$chapters[$index]['title']), 0, 40);
  561. Utils::throwError('20003:章节序号不连续:第' . ($index + 1) . '个章节“' . $title . '”序号为' . $num . ',预期为' . $expected);
  562. }
  563. $expected++;
  564. }
  565. return;
  566. }
  567. // 标题格式无法用正则确认时,交给模型分析
  568. $titles = array_column($chapters, 'title');
  569. $aiResult = $this->validateChapterSequenceByAI($titles);
  570. if ($aiResult['valid'] === false) {
  571. $badIndex = $aiResult['invalid_index'] ?: $unparsedIndex + 1;
  572. if (isset($chapters[$badIndex - 1])) {
  573. $title = mb_substr(trim((string)$chapters[$badIndex - 1]['title']), 0, 40);
  574. Utils::throwError('20003:章节序号不连续:第' . $badIndex . '个章节“' . $title . '”序号异常,请检查');
  575. }
  576. Utils::throwError('20003:章节序号不连续,请检查章节标题格式');
  577. }
  578. if ($aiResult['valid'] === null) {
  579. if (isset($chapters[$unparsedIndex])) {
  580. $title = mb_substr(trim((string)$chapters[$unparsedIndex]['title']), 0, 40);
  581. Utils::throwError('20003:无法确认第' . ($unparsedIndex + 1) . '个章节“' . $title . '”的章节序号,请检查标题格式');
  582. }
  583. Utils::throwError('20003:无法确认章节标题连续性,请检查章节标题格式');
  584. }
  585. }
  586. /**
  587. * 从章节标题中解析序号,支持阿拉伯数字和中文数字
  588. *
  589. * @param string $title
  590. * @return int|null
  591. */
  592. private function parseChapterNumber($title)
  593. {
  594. if (!preg_match('/第\s*([一二两三四五六七八九十百千万0-9]+)\s*[章节集幕场回话]/u', $title, $match)) {
  595. return null;
  596. }
  597. return $this->convertChineseNumber($match[1]);
  598. }
  599. /**
  600. * 中文数字转阿拉伯数字(支持到千)
  601. *
  602. * @param string $numStr
  603. * @return int
  604. */
  605. private function convertChineseNumber($numStr)
  606. {
  607. if (preg_match('/^\d+$/', $numStr)) {
  608. return (int)$numStr;
  609. }
  610. $map = [
  611. '零' => 0,
  612. '一' => 1,
  613. '二' => 2,
  614. '两' => 2,
  615. '三' => 3,
  616. '四' => 4,
  617. '五' => 5,
  618. '六' => 6,
  619. '七' => 7,
  620. '八' => 8,
  621. '九' => 9
  622. ];
  623. $total = 0;
  624. $section = 0;
  625. $length = mb_strlen($numStr);
  626. for ($i = 0; $i < $length; $i++) {
  627. $char = mb_substr($numStr, $i, 1);
  628. if (isset($map[$char])) {
  629. $section = $map[$char];
  630. } elseif ($char === '十') {
  631. $total += $section === 0 ? 10 : $section * 10;
  632. $section = 0;
  633. } elseif ($char === '百') {
  634. $total += $section === 0 ? 100 : $section * 100;
  635. $section = 0;
  636. } elseif ($char === '千') {
  637. $total += $section === 0 ? 1000 : $section * 1000;
  638. $section = 0;
  639. }
  640. }
  641. return $total + $section;
  642. }
  643. /**
  644. * 用 deepseek-v4-flash 非流式判断章节标题是否从1开始连续编号
  645. *
  646. * @param array $titles
  647. * @return array{valid: bool|null, invalid_index: int|null}
  648. */
  649. private function validateChapterSequenceByAI($titles)
  650. {
  651. $titleLines = [];
  652. foreach (array_slice($titles, 0, 200) as $index => $title) {
  653. $titleLines[] = ($index + 1) . '. ' . mb_substr(trim((string)$title), 0, 80);
  654. }
  655. $result = [
  656. 'valid' => null,
  657. 'invalid_index' => null
  658. ];
  659. $post_data = [
  660. 'model' => 'deepseek-v4-flash',
  661. 'messages' => [
  662. [
  663. 'role' => 'system',
  664. 'content' => '你是剧本章节校验助手。用户会给出章节标题列表,请判断这些标题中的编号是否从第1章/第1集开始连续递增,支持阿拉伯数字和中文数字。只输出 JSON,格式为 {"valid":true};若不连续则输出 {"valid":false,"invalid_index":N},其中 N 是第一个序号异常的章节序号(从1开始),不要输出其他内容。',
  665. ],
  666. [
  667. 'role' => 'user',
  668. 'content' => implode("\n", $titleLines),
  669. ],
  670. ],
  671. 'temperature' => 0,
  672. 'frequency_penalty' => 0,
  673. 'presence_penalty' => 0,
  674. 'stream' => false,
  675. ];
  676. try {
  677. $result = $this->chatOnly($post_data, 8);
  678. $content = trim((string)($result['fullContent'] ?? ''));
  679. if (preg_match('/"valid"\s*:\s*(true|false)/i', $content, $match)) {
  680. $result['valid'] = strtolower($match[1]) === 'true';
  681. }
  682. if (preg_match('/"invalid_index"\s*:\s*(\d+)/i', $content, $match)) {
  683. $result['invalid_index'] = (int)$match[1];
  684. }
  685. // 仅记录 token 使用明细(不扣积分):该校验为流程内的额外模型调用
  686. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  687. 'model' => 'deepseek-v4-flash',
  688. 'source' => 'validateChapterSequenceByAI',
  689. ], 'deepseek-v4-flash');
  690. } catch (\Exception $e) {
  691. dLog('deepseek')->error('章节连续性AI校验失败: ' . $e->getMessage());
  692. }
  693. return $result;
  694. }
  695. /**
  696. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  697. *
  698. * @param array $data 请求参数
  699. * @return array 返回结果数组
  700. */
  701. public function newGenerateText($data) {
  702. // 获取请求参数
  703. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  704. $messages = getProp($data, 'messages', []);
  705. $systemPrompt = getProp($data, 'system_prompt', '');
  706. $prompt = getProp($data, 'prompt', '');
  707. $images = getProp($data, 'images', []); // 支持多张图片
  708. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  709. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  710. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  711. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  712. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  713. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  714. $generateTaskId = 0;
  715. $uid = Site::getUid();
  716. if ($script_id > 0) {
  717. $existingTask = DB::table('mp_script_generate_tasks')
  718. ->where('uid', $uid)
  719. ->where('script_id', $script_id)
  720. ->orderByDesc('id')
  721. ->first();
  722. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  723. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  724. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  725. }
  726. }
  727. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  728. $originalContent = '';
  729. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  730. if ($script_id > 0) {
  731. $script = DB::table('mp_scripts')
  732. ->where('id', $script_id)
  733. ->where('is_deleted', 0)
  734. ->first();
  735. if (!$script) {
  736. Utils::throwError('20003:剧本不存在或已删除');
  737. }
  738. $originalContent = $script->content ?? '';
  739. if (empty($originalContent)) {
  740. Utils::throwError('20003:剧本内容为空');
  741. }
  742. $hasValidScript = true;
  743. // 将剧本内容添加到提示词前面
  744. if (!empty($originalContent)) {
  745. if (!empty($prompt)) {
  746. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  747. } else {
  748. $prompt = "原文内容:\n" . $originalContent;
  749. }
  750. }
  751. }
  752. // 新增: 如果提供了template_id,从数据库获取template_prompt
  753. if ($templateId > 0) {
  754. $template = DB::table('mp_prompt_templates')
  755. ->where('id', $templateId)
  756. ->where('is_deleted', 0)
  757. ->first();
  758. if (!$template) {
  759. Utils::throwError('20003:模板不存在或已删除');
  760. }
  761. $templatePrompt = $template->template_prompt ?? '';
  762. // 将模板提示词和用户输入的prompt组合
  763. // 模板为准,用户输入作为补充要求
  764. if (!empty($templatePrompt)) {
  765. if (!empty($prompt)) {
  766. $prompt = $templatePrompt . "\n\n" . $prompt;
  767. } else {
  768. $prompt = $templatePrompt;
  769. }
  770. }
  771. }
  772. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  773. if (empty($messages)) {
  774. $messages = [];
  775. // 添加系统提示词
  776. if (!empty($systemPrompt)) {
  777. $messages[] = [
  778. 'role' => 'system',
  779. 'content' => $systemPrompt
  780. ];
  781. }
  782. // 构建用户消息内容(支持文本+图片)
  783. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  784. $userMessage = [
  785. 'role' => 'user',
  786. 'content' => []
  787. ];
  788. // 添加文本内容
  789. if (!empty($prompt)) {
  790. $userMessage['content'][] = [
  791. 'type' => 'text',
  792. 'text' => $prompt
  793. ];
  794. }
  795. // 处理上传的图片文件
  796. if (!empty($images)) {
  797. if (!is_array($images)) {
  798. $images = [$images];
  799. }
  800. foreach ($images as $image) {
  801. $imageBase64 = $this->processImageToBase64($image);
  802. if ($imageBase64) {
  803. $userMessage['content'][] = [
  804. 'type' => 'image_url',
  805. 'image_url' => [
  806. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  807. ]
  808. ];
  809. }
  810. }
  811. }
  812. // 处理图片URL
  813. if (!empty($imageUrls)) {
  814. if (!is_array($imageUrls)) {
  815. $imageUrls = [$imageUrls];
  816. }
  817. foreach ($imageUrls as $url) {
  818. if (!empty($url)) {
  819. $userMessage['content'][] = [
  820. 'type' => 'image_url',
  821. 'image_url' => [
  822. 'url' => $url
  823. ]
  824. ];
  825. }
  826. }
  827. }
  828. // 如果只有文本内容,简化为字符串格式
  829. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  830. $userMessage['content'] = $userMessage['content'][0]['text'];
  831. }
  832. $messages[] = $userMessage;
  833. }
  834. }
  835. // 验证messages不为空
  836. if (empty($messages)) {
  837. Utils::throwError('20003:请提供有效的对话内容');
  838. }
  839. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  840. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  841. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  842. if ($model === 'deepseek-chat') {
  843. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  844. $model = 'deepseek-v4-flash';
  845. $thinkingMode = 'disabled';
  846. } elseif ($model === 'deepseek-reasoner') {
  847. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  848. $model = 'deepseek-v4-flash';
  849. $thinkingMode = 'enabled';
  850. }
  851. // 构建请求参数(非流式)
  852. $post_data = [
  853. 'model' => $model,
  854. 'messages' => $messages,
  855. 'temperature' => getProp($data, 'temperature', 1),
  856. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  857. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  858. 'thinking' => ['type' => $thinkingMode],
  859. 'stream' => false // 非流式输出
  860. ];
  861. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  862. // 添加可选参数
  863. if (isset($data['top_p'])) {
  864. $post_data['top_p'] = $data['top_p'];
  865. }
  866. // 新增: 根据response_format设置响应格式
  867. if ($responseFormat === 'json') {
  868. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  869. $hasJsonKeyword = false;
  870. foreach ($post_data['messages'] as $message) {
  871. if (isset($message['content'])) {
  872. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  873. if (stripos($content, 'json') !== false) {
  874. $hasJsonKeyword = true;
  875. break;
  876. }
  877. }
  878. }
  879. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  880. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  881. if (!$hasJsonKeyword) {
  882. $lastMessageIndex = count($post_data['messages']) - 1;
  883. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  884. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  885. // 如果content是字符串,直接追加
  886. if (is_string($lastContent)) {
  887. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  888. }
  889. // 如果content是数组(包含文本和图片),在文本部分追加
  890. else if (is_array($lastContent)) {
  891. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  892. if ($contentPart['type'] === 'text') {
  893. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  894. break;
  895. }
  896. }
  897. }
  898. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  899. }
  900. }
  901. // 设置response_format参数(所有支持的模型)
  902. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  903. // DeepSeek模型
  904. $post_data['response_format'] = ['type' => 'json_object'];
  905. } else if (in_array($model, $this->gpt_text_models)) {
  906. // GPT模型
  907. $post_data['response_format'] = ['type' => 'json_object'];
  908. } else if (in_array($model, $this->valid_text_models)) {
  909. // 火山引擎模型
  910. $post_data['response_format'] = ['type' => 'json_object'];
  911. }
  912. }
  913. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  914. if ($script_id > 0) {
  915. $uid = Site::getUid();
  916. // 创建新的生成任务
  917. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  918. 'uid' => $uid,
  919. 'script_id' => $script_id,
  920. 'sequence' => $sequence,
  921. 'status' => 'processing',
  922. 'prompt' => getProp($data, 'prompt', ''),
  923. 'started_at' => date('Y-m-d H:i:s'),
  924. 'created_at' => date('Y-m-d H:i:s'),
  925. 'updated_at' => date('Y-m-d H:i:s')
  926. ]);
  927. }
  928. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  929. if ($hasValidScript) {
  930. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  931. }
  932. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  933. try {
  934. $aiResult = null;
  935. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  936. // DeepSeek 官方模型使用现有的 chatOnly 方法
  937. $result = $this->chatOnly($post_data);
  938. // 记录实际使用的模型
  939. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  940. $aiResult = [
  941. 'content' => $result['fullContent'],
  942. 'reasoning_content' => $result['fullReasoningContent'],
  943. 'usage' => $result['usage'],
  944. 'model' => $model,
  945. 'finish_reason' => 'stop'
  946. ];
  947. } else if (in_array($model, $this->gpt_text_models)) {
  948. // GPT 模型使用现有的 gpt54ChatOnly 方法
  949. $result = $this->gpt54ChatOnly($post_data);
  950. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  951. $aiResult = [
  952. 'content' => $result['fullContent'],
  953. 'reasoning_content' => '',
  954. 'usage' => $result['usage'],
  955. 'model' => $model,
  956. 'finish_reason' => 'stop'
  957. ];
  958. } else if (in_array($model, $this->gemini_text_models)) {
  959. // Gemini 模型使用 Gemini API(非流式)
  960. $result = $this->geminiChatOnly($post_data, $model);
  961. dLog('deepseek')->info('newGenerateText使用Gemini模型', ['requested_model' => $model]);
  962. $aiResult = [
  963. 'content' => $result['fullContent'],
  964. 'reasoning_content' => $result['fullReasoningContent'] ?? '',
  965. 'usage' => $result['usage'],
  966. 'model' => $model,
  967. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  968. ];
  969. } else if (in_array($model, $this->valid_text_models)) {
  970. // 火山引擎支持的模型使用火山引擎 API(非流式)
  971. $post_data['stream'] = false;
  972. $result = $this->volcEngineChatCompletion($post_data);
  973. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  974. 'requested_model' => $model,
  975. 'result_keys' => array_keys($result),
  976. 'has_fullContent' => isset($result['fullContent']),
  977. 'has_content' => isset($result['content'])
  978. ]);
  979. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  980. $aiResult = [
  981. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  982. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  983. 'usage' => $result['usage'] ?? [],
  984. 'model' => $model,
  985. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  986. ];
  987. } else {
  988. Utils::throwError('20003:不支持的模型: ' . $model);
  989. }
  990. } catch (\Exception $e) {
  991. // 生成失败,更新任务状态
  992. if ($generateTaskId) {
  993. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  994. 'status' => 'failed',
  995. 'error_message' => $e->getMessage(),
  996. 'completed_at' => date('Y-m-d H:i:s'),
  997. 'updated_at' => date('Y-m-d H:i:s')
  998. ]);
  999. }
  1000. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  1001. }
  1002. // 生成成功,更新任务状态
  1003. if ($generateTaskId && $aiResult) {
  1004. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  1005. 'status' => 'success',
  1006. 'result' => getProp($aiResult, 'content', ''),
  1007. 'completed_at' => date('Y-m-d H:i:s'),
  1008. 'updated_at' => date('Y-m-d H:i:s')
  1009. ]);
  1010. $aiResult['generate_task_id'] = $generateTaskId;
  1011. }
  1012. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  1013. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  1014. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  1015. 'model' => $model,
  1016. 'script_id' => $script_id,
  1017. 'sequence' => $sequence,
  1018. 'source' => 'newGenerateText',
  1019. ]);
  1020. }
  1021. // 新增: 如果提供了script_id,保存对话记录
  1022. if ($script_id > 0 && $aiResult) {
  1023. try {
  1024. $uid = Site::getUid();
  1025. $now = now();
  1026. // 获取用户原始的prompt(不包含剧本内容)
  1027. $originalPrompt = getProp($data, 'prompt', '');
  1028. $recordsToInsert = [
  1029. [
  1030. 'uid' => $uid,
  1031. 'script_id' => $script_id,
  1032. 'sequence' => $sequence,
  1033. 'role' => 'user',
  1034. 'content' => $originalPrompt,
  1035. 'created_at' => $now,
  1036. 'updated_at' => $now,
  1037. ],
  1038. [
  1039. 'uid' => $uid,
  1040. 'script_id' => $script_id,
  1041. 'sequence' => $sequence,
  1042. 'role' => 'assistant',
  1043. 'content' => $aiResult['content'],
  1044. 'created_at' => $now,
  1045. 'updated_at' => $now,
  1046. ]
  1047. ];
  1048. DB::table('mp_script_records')->insert($recordsToInsert);
  1049. // 获取刚插入的记录ID(假设按插入顺序返回)
  1050. $insertedRecords = DB::table('mp_script_records')
  1051. ->where('uid', $uid)
  1052. ->where('script_id', $script_id)
  1053. ->where('sequence', $sequence)
  1054. ->orderBy('id', 'desc')
  1055. ->limit(2)
  1056. ->get()
  1057. ->map(function ($record) {
  1058. return [
  1059. 'rid' => $record->id,
  1060. 'script_id' => $record->script_id,
  1061. 'sequence' => $record->sequence,
  1062. 'role' => $record->role,
  1063. 'content' => $record->content,
  1064. 'created_at' => $record->created_at,
  1065. ];
  1066. })
  1067. ->reverse()
  1068. ->values()
  1069. ->toArray();
  1070. // 将记录信息添加到返回结果中
  1071. $aiResult['records'] = $insertedRecords;
  1072. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  1073. } catch (\Exception $e) {
  1074. // 记录错误但不影响主流程
  1075. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  1076. }
  1077. }
  1078. return $aiResult;
  1079. }
  1080. /**
  1081. * 通用 Gemini 文生文方法(支持流式和非流式)
  1082. *
  1083. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  1084. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  1085. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  1086. * system_prompt 系统提示词(可选)
  1087. * prompt 用户提示词(可选)
  1088. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  1089. * image_urls 图片/视频URL列表(可选,同上)
  1090. * temperature 温度(可选,默认 1)
  1091. * top_p 核采样(可选)
  1092. * max_tokens 最大输出 token(可选,默认 8192)
  1093. * response_format text/json(可选)
  1094. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  1095. * thinking_budget 思考预算(可选,默认 20)
  1096. * stream 是否流式(可选,默认 false)
  1097. *
  1098. * @param array $data 请求参数
  1099. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  1100. */
  1101. public function geminiGenerateText($data) {
  1102. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  1103. $isStream = (bool)getProp($data, 'stream', false);
  1104. if (!in_array($model, $this->gemini_text_models)) {
  1105. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  1106. }
  1107. $requestData = $this->buildGeminiRequestBody($data, $model);
  1108. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  1109. if ($isStream) {
  1110. // 流式返回生成器,成功后记录 token 使用明细(不扣积分)
  1111. return $this->wrapGenerateTextTokenRecord(
  1112. $this->geminiStreamResponse($requestData, $model),
  1113. $this->getCurrentUid(),
  1114. $model,
  1115. 'geminiGenerateText'
  1116. );
  1117. }
  1118. // 非流式:成功后记录 token 使用明细(不扣积分)
  1119. $result = $this->geminiChatOnly($requestData, $model);
  1120. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  1121. 'model' => $model,
  1122. 'source' => 'geminiGenerateText',
  1123. ], $model);
  1124. return $result;
  1125. }
  1126. /**
  1127. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  1128. */
  1129. private function geminiMediaMaxBytes() {
  1130. return 14 * 1024 * 1024;
  1131. }
  1132. /**
  1133. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  1134. */
  1135. private function buildGeminiRequestBody($data, $model) {
  1136. $messages = getProp($data, 'messages', []);
  1137. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  1138. if (empty($messages)) {
  1139. $systemPrompt = getProp($data, 'system_prompt', '');
  1140. $prompt = getProp($data, 'prompt', '');
  1141. $images = getProp($data, 'images', []);
  1142. $imageUrls = getProp($data, 'image_urls', []);
  1143. $messages = [];
  1144. if (!empty($systemPrompt)) {
  1145. $messages[] = [
  1146. 'role' => 'system',
  1147. 'content' => $systemPrompt
  1148. ];
  1149. }
  1150. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  1151. $userMessage = ['role' => 'user', 'content' => []];
  1152. if (!empty($prompt)) {
  1153. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  1154. }
  1155. if (!empty($images)) {
  1156. if (!is_array($images)) {
  1157. $images = [$images];
  1158. }
  1159. foreach ($images as $image) {
  1160. $inlineData = $this->processMediaToInlineData($image);
  1161. if ($inlineData) {
  1162. $userMessage['content'][] = [
  1163. 'type' => 'image',
  1164. 'inline_data' => $inlineData
  1165. ];
  1166. }
  1167. }
  1168. }
  1169. if (!empty($imageUrls)) {
  1170. if (!is_array($imageUrls)) {
  1171. $imageUrls = [$imageUrls];
  1172. }
  1173. foreach ($imageUrls as $url) {
  1174. if (!empty($url)) {
  1175. $inlineData = $this->processMediaToInlineData($url);
  1176. if ($inlineData) {
  1177. $userMessage['content'][] = [
  1178. 'type' => 'image',
  1179. 'inline_data' => $inlineData
  1180. ];
  1181. }
  1182. }
  1183. }
  1184. }
  1185. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  1186. $userMessage['content'] = $userMessage['content'][0]['text'];
  1187. }
  1188. $messages[] = $userMessage;
  1189. }
  1190. }
  1191. if (empty($messages)) {
  1192. Utils::throwError('20003:请提供有效的对话内容');
  1193. }
  1194. // 转换为 Gemini contents 格式
  1195. $systemInstruction = '';
  1196. $contents = [];
  1197. foreach ($messages as $message) {
  1198. $role = getProp($message, 'role', 'user');
  1199. $content = getProp($message, 'content', '');
  1200. if ($role === 'system') {
  1201. if (is_array($content)) {
  1202. $systemInstruction = $this->extractGeminiTextFromParts($content);
  1203. } else {
  1204. $systemInstruction = (string)$content;
  1205. }
  1206. continue;
  1207. }
  1208. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  1209. $parts = [];
  1210. if (is_array($content)) {
  1211. foreach ($content as $part) {
  1212. $partType = getProp($part, 'type', 'text');
  1213. if ($partType === 'text') {
  1214. $text = (string)getProp($part, 'text', '');
  1215. if ($text !== '') {
  1216. $parts[] = ['text' => $text];
  1217. }
  1218. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  1219. if (in_array($partType, ['image_url', 'video_url'])) {
  1220. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  1221. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  1222. } elseif (isset($part['inline_data'])) {
  1223. // 已处理过的 inline_data 直接使用
  1224. $parts[] = ['inline_data' => $part['inline_data']];
  1225. continue;
  1226. } else {
  1227. $url = '';
  1228. }
  1229. $inlineData = $this->processMediaToInlineData($url);
  1230. if ($inlineData) {
  1231. $parts[] = ['inline_data' => $inlineData];
  1232. }
  1233. }
  1234. }
  1235. } else {
  1236. $text = (string)$content;
  1237. if ($text !== '') {
  1238. $parts[] = ['text' => $text];
  1239. }
  1240. }
  1241. if (!empty($parts)) {
  1242. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  1243. }
  1244. }
  1245. if (empty($contents)) {
  1246. Utils::throwError('20003:请提供有效的对话内容');
  1247. }
  1248. // 构建生成配置
  1249. $generationConfig = [];
  1250. if (getProp($data, 'temperature', null) !== null) {
  1251. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  1252. }
  1253. if (getProp($data, 'top_p', null) !== null) {
  1254. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  1255. }
  1256. if (getProp($data, 'frequency_penalty', null) !== null) {
  1257. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  1258. }
  1259. if (getProp($data, 'presence_penalty', null) !== null) {
  1260. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  1261. }
  1262. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  1263. if ($maxOutputTokens <= 0) {
  1264. $maxOutputTokens = 8192;
  1265. }
  1266. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  1267. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  1268. $maxOutputTokens = 32768;
  1269. }
  1270. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  1271. // response_format 映射:text -> text/plain,json -> application/json
  1272. $responseFormat = getProp($data, 'response_format', 'text');
  1273. if (is_array($responseFormat)) {
  1274. $responseFormat = getProp($responseFormat, 'type', 'text');
  1275. }
  1276. if (in_array($responseFormat, ['json', 'json_object'])) {
  1277. $generationConfig['responseMimeType'] = 'application/json';
  1278. } else {
  1279. $generationConfig['responseMimeType'] = 'text/plain';
  1280. }
  1281. $requestData = [
  1282. 'contents' => $contents,
  1283. 'generationConfig' => $generationConfig,
  1284. ];
  1285. if ($systemInstruction !== '') {
  1286. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  1287. }
  1288. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  1289. $thinkingMode = getProp($data, 'thinking', null);
  1290. if (is_array($thinkingMode)) {
  1291. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  1292. }
  1293. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  1294. if ($thinkingMode === null) {
  1295. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  1296. }
  1297. if ($thinkingMode === 'enabled') {
  1298. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  1299. if ($thinkingBudget <= 0) {
  1300. $thinkingBudget = 20;
  1301. }
  1302. $requestData['generationConfig']['thinkingConfig'] = [
  1303. 'thinkingBudget' => $thinkingBudget
  1304. ];
  1305. } elseif ($defaultThinking) {
  1306. // 该模型仅支持思考模式,传 0 会返回 400
  1307. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  1308. } else {
  1309. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  1310. }
  1311. return $requestData;
  1312. }
  1313. /**
  1314. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  1315. *
  1316. * 模型名 -> env 变量名映射:
  1317. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  1318. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  1319. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  1320. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  1321. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  1322. */
  1323. private function getGeminiApiKey($model) {
  1324. $map = [
  1325. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  1326. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  1327. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  1328. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  1329. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  1330. ];
  1331. if (isset($map[$model])) {
  1332. $key = env($map[$model]);
  1333. if (!empty($key)) {
  1334. return $key;
  1335. }
  1336. }
  1337. return env('GEMINI_API_KEY', '');
  1338. }
  1339. /**
  1340. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  1341. */
  1342. private function geminiChatOnly($requestData, $model) {
  1343. $apiKey = $this->getGeminiApiKey($model);
  1344. if (empty($apiKey)) {
  1345. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1346. }
  1347. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1348. if (isset($requestData['messages'])) {
  1349. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1350. }
  1351. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1352. . '/models/' . $model . ':generateContent';
  1353. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1354. $headers = [
  1355. 'Authorization' => 'Bearer ' . $apiKey,
  1356. 'Content-Type' => 'application/json'
  1357. ];
  1358. $maxRetries = $this->gptRetryTimes();
  1359. $interval = $this->gptRetryInterval();
  1360. $attempt = 0;
  1361. while (true) {
  1362. try {
  1363. $response = $client->post($url, [
  1364. 'json' => $requestData,
  1365. 'headers' => $headers
  1366. ]);
  1367. $responseArr = json_decode($response->getBody()->getContents(), true);
  1368. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  1369. $fullContent = $this->extractGeminiContent($responseArr);
  1370. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  1371. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  1372. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  1373. ? $responseArr['candidates'][0]['finishReason']
  1374. : '';
  1375. return [
  1376. 'fullContent' => $fullContent,
  1377. 'fullReasoningContent' => $fullReasoningContent,
  1378. 'usage' => $usage,
  1379. 'finish_reason' => $finishReason
  1380. ];
  1381. } catch (\Exception $e) {
  1382. $retryable = true;
  1383. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1384. $status = $e->getResponse()->getStatusCode();
  1385. $retryable = $status >= 500 || $status == 429;
  1386. }
  1387. if (!$retryable || $attempt >= $maxRetries) {
  1388. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  1389. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  1390. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  1391. }
  1392. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  1393. 'retry' => $attempt + 1,
  1394. 'max_retries' => $maxRetries,
  1395. 'error' => $e->getMessage()
  1396. ]);
  1397. sleep($interval);
  1398. $attempt++;
  1399. }
  1400. }
  1401. }
  1402. /**
  1403. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  1404. */
  1405. private function geminiStreamResponse($requestData, $model) {
  1406. $apiKey = $this->getGeminiApiKey($model);
  1407. if (empty($apiKey)) {
  1408. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1409. }
  1410. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1411. if (isset($requestData['messages'])) {
  1412. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1413. }
  1414. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1415. . '/models/' . $model . ':generateContent?alt=sse';
  1416. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1417. $headers = [
  1418. 'Authorization' => 'Bearer ' . $apiKey,
  1419. 'Content-Type' => 'application/json'
  1420. ];
  1421. try {
  1422. $response = $client->post($url, [
  1423. 'json' => $requestData,
  1424. 'headers' => $headers,
  1425. 'stream' => true
  1426. ]);
  1427. $body = $response->getBody();
  1428. $fullContent = '';
  1429. $fullReasoningContent = '';
  1430. $usage = [];
  1431. $buffer = '';
  1432. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1433. while (!$body->eof()) {
  1434. $chunk = $body->read(1024);
  1435. $buffer .= $chunk;
  1436. $lines = explode("\n", $buffer);
  1437. $buffer = array_pop($lines);
  1438. foreach ($lines as $line) {
  1439. $line = trim($line);
  1440. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1441. continue;
  1442. }
  1443. $data = substr($line, 6);
  1444. if ($data === '[DONE]') {
  1445. break 2;
  1446. }
  1447. try {
  1448. $json = json_decode($data, true);
  1449. if (json_last_error() !== JSON_ERROR_NONE) {
  1450. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1451. continue;
  1452. }
  1453. // 思考内容(thoughts)
  1454. $thoughts = $this->extractGeminiThoughts($json);
  1455. if ($thoughts !== '') {
  1456. $fullReasoningContent .= $thoughts;
  1457. yield [
  1458. 'type' => 'reasoning',
  1459. 'content' => $thoughts,
  1460. 'full_reasoning' => $fullReasoningContent
  1461. ];
  1462. }
  1463. // 回答内容
  1464. $partText = $this->extractGeminiContent($json);
  1465. if ($partText !== '') {
  1466. $fullContent .= $partText;
  1467. yield [
  1468. 'type' => 'content',
  1469. 'content' => $partText,
  1470. ];
  1471. }
  1472. // 使用统计
  1473. if (isset($json['usageMetadata'])) {
  1474. $usage = $json['usageMetadata'];
  1475. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  1476. }
  1477. } catch (\Exception $e) {
  1478. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1479. continue;
  1480. }
  1481. }
  1482. }
  1483. dLog('deepseek')->info('Gemini流式读取完成', [
  1484. 'content_length' => strlen($fullContent),
  1485. 'reasoning_length' => strlen($fullReasoningContent)
  1486. ]);
  1487. yield [
  1488. 'type' => 'done',
  1489. 'full_content' => $fullContent,
  1490. 'full_reasoning' => $fullReasoningContent,
  1491. 'usage' => $usage
  1492. ];
  1493. } catch (\Exception $e) {
  1494. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  1495. yield [
  1496. 'type' => 'error',
  1497. 'msg' => $e->getMessage(),
  1498. 'code' => $e->getCode()
  1499. ];
  1500. }
  1501. }
  1502. /**
  1503. * 从 Gemini 响应中提取回答文本
  1504. */
  1505. private function extractGeminiContent($responseArr) {
  1506. $text = '';
  1507. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  1508. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  1509. if (isset($part['text'])) {
  1510. $text .= $part['text'];
  1511. }
  1512. }
  1513. }
  1514. return $text;
  1515. }
  1516. /**
  1517. * 从 Gemini 响应中提取思考内容
  1518. */
  1519. private function extractGeminiReasoningContent($responseArr) {
  1520. $reasoning = '';
  1521. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1522. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1523. if (isset($thought['text'])) {
  1524. $reasoning .= $thought['text'];
  1525. }
  1526. }
  1527. }
  1528. return $reasoning;
  1529. }
  1530. /**
  1531. * 从 Gemini 流式响应中提取本次增量思考内容
  1532. */
  1533. private function extractGeminiThoughts($responseArr) {
  1534. $thoughts = '';
  1535. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1536. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1537. if (isset($thought['text'])) {
  1538. $thoughts .= $thought['text'];
  1539. }
  1540. }
  1541. }
  1542. return $thoughts;
  1543. }
  1544. /**
  1545. * 提取消息数组中的纯文本
  1546. */
  1547. private function extractGeminiTextFromParts($parts) {
  1548. $text = '';
  1549. if (is_array($parts)) {
  1550. foreach ($parts as $part) {
  1551. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  1552. $text .= (string)getProp($part, 'text', '');
  1553. }
  1554. }
  1555. }
  1556. return $text;
  1557. }
  1558. /**
  1559. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  1560. *
  1561. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  1562. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  1563. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  1564. *
  1565. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  1566. * @return array|null ['mime_type' => string, 'data' => string]
  1567. */
  1568. private function processMediaToInlineData($media) {
  1569. if (empty($media)) {
  1570. return null;
  1571. }
  1572. $localPath = null;
  1573. $isTempFile = false;
  1574. try {
  1575. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  1576. if (is_string($media) && strpos($media, 'data:') === 0) {
  1577. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  1578. return [
  1579. 'mime_type' => $matches[1],
  1580. 'data' => $matches[2]
  1581. ];
  1582. }
  1583. return null;
  1584. }
  1585. // 2. 获取本地文件路径
  1586. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  1587. $localPath = $this->downloadMediaToTemp($media);
  1588. $isTempFile = true;
  1589. } elseif (is_string($media)) {
  1590. $localPath = $media;
  1591. } else {
  1592. // Laravel UploadedFile 对象
  1593. $localPath = $media->getRealPath();
  1594. }
  1595. if (!$localPath || !file_exists($localPath)) {
  1596. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  1597. return null;
  1598. }
  1599. $fileSize = filesize($localPath);
  1600. $maxBytes = $this->geminiMediaMaxBytes();
  1601. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  1602. $mimeType = $this->detectMediaMime($localPath);
  1603. $isVideo = strpos($mimeType, 'video/') === 0;
  1604. $needCompress = $fileSize > $maxBytes;
  1605. $duration = 0;
  1606. if ($isVideo) {
  1607. $duration = $this->getMediaDuration($localPath);
  1608. if ($duration > 300) {
  1609. $needCompress = true;
  1610. }
  1611. }
  1612. $finalPath = $localPath;
  1613. $compressedPath = null;
  1614. if ($needCompress && $this->ffmpegAvailable()) {
  1615. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  1616. if ($compressed && file_exists($compressed)) {
  1617. $compressedPath = $compressed;
  1618. if (filesize($compressed) < $fileSize || $isVideo) {
  1619. $finalPath = $compressed;
  1620. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  1621. } else {
  1622. @unlink($compressed);
  1623. $compressedPath = null;
  1624. }
  1625. }
  1626. }
  1627. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  1628. $finalSize = filesize($finalPath);
  1629. if ($finalSize > $maxBytes) {
  1630. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  1631. 'path' => $localPath,
  1632. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  1633. 'limit_mb' => 14
  1634. ]);
  1635. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  1636. }
  1637. // 兜底校验:视频时长超过5分钟且未能压缩成功
  1638. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  1639. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  1640. }
  1641. $data = base64_encode(file_get_contents($finalPath));
  1642. return [
  1643. 'mime_type' => $mimeType,
  1644. 'data' => $data
  1645. ];
  1646. } catch (\App\Exceptions\ApiException $e) {
  1647. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  1648. throw $e;
  1649. } catch (\Exception $e) {
  1650. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  1651. return null;
  1652. } finally {
  1653. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  1654. @unlink($compressedPath);
  1655. }
  1656. if ($isTempFile && $localPath && file_exists($localPath)) {
  1657. @unlink($localPath);
  1658. }
  1659. }
  1660. }
  1661. /**
  1662. * 下载远程多媒体到临时目录
  1663. *
  1664. * @return string|null 本地临时文件路径
  1665. */
  1666. private function downloadMediaToTemp($url) {
  1667. try {
  1668. $tempDir = storage_path('app/temp/gemini');
  1669. if (!is_dir($tempDir)) {
  1670. mkdir($tempDir, 0775, true);
  1671. }
  1672. $extension = 'tmp';
  1673. $pathInfo = parse_url($url, PHP_URL_PATH);
  1674. if ($pathInfo) {
  1675. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  1676. if ($ext && strlen($ext) <= 10) {
  1677. $extension = strtolower($ext);
  1678. }
  1679. }
  1680. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  1681. $client = new Client(['timeout' => 300, 'verify' => false]);
  1682. $response = $client->get($url, ['sink' => $tmpFile]);
  1683. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  1684. @unlink($tmpFile);
  1685. return null;
  1686. }
  1687. return $tmpFile;
  1688. } catch (\Exception $e) {
  1689. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  1690. return null;
  1691. }
  1692. }
  1693. /**
  1694. * 检测多媒体文件 MIME 类型
  1695. */
  1696. private function detectMediaMime($filePath) {
  1697. $imageInfo = @getimagesize($filePath);
  1698. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  1699. return $imageInfo['mime'];
  1700. }
  1701. // 视频按扩展名粗略判断
  1702. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  1703. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  1704. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  1705. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  1706. if (isset($videoExts[$ext])) {
  1707. return $videoExts[$ext];
  1708. }
  1709. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  1710. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  1711. if (isset($imageExts[$ext])) {
  1712. return $imageExts[$ext];
  1713. }
  1714. return 'application/octet-stream';
  1715. }
  1716. /**
  1717. * 获取多媒体时长(秒),非视频或失败返回 0
  1718. */
  1719. private function getMediaDuration($filePath) {
  1720. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  1721. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  1722. $output = trim((string)shell_exec($cmd));
  1723. $duration = (float)$output;
  1724. return $duration > 0 ? $duration : 0;
  1725. }
  1726. /**
  1727. * 检查 ffmpeg 是否可用
  1728. */
  1729. private function ffmpegAvailable() {
  1730. static $available = null;
  1731. if ($available !== null) {
  1732. return $available;
  1733. }
  1734. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1735. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  1736. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  1737. $available = false;
  1738. return $available;
  1739. }
  1740. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  1741. $output = shell_exec($cmd);
  1742. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  1743. return $available;
  1744. }
  1745. /**
  1746. * 使用 ffmpeg 压缩多媒体文件
  1747. *
  1748. * @param string $inputFile 输入文件路径
  1749. * @param bool $isVideo 是否为视频
  1750. * @param float $duration 视频时长(秒),非视频传 0
  1751. * @return string|null 压缩后的文件路径,失败返回 null
  1752. */
  1753. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  1754. try {
  1755. $tempDir = storage_path('app/temp/gemini');
  1756. if (!is_dir($tempDir)) {
  1757. mkdir($tempDir, 0775, true);
  1758. }
  1759. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1760. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  1761. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  1762. if ($isVideo) {
  1763. // 视频:时长超过5分钟则加速压缩到5分钟以内
  1764. $speedFactor = 1.0;
  1765. if ($duration > 300) {
  1766. $speedFactor = $duration / 300;
  1767. }
  1768. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  1769. $finalDuration = $duration / max(1.0, $speedFactor);
  1770. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  1771. $targetBitrate = max(300, min(6000, $targetBitrate));
  1772. $filters = [];
  1773. $filters[] = 'scale=min(1280,iw):-2';
  1774. $filters[] = 'fps=24';
  1775. if ($speedFactor > 1.0) {
  1776. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  1777. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  1778. $fullCount = (int)ceil($speedFactor / 2.0);
  1779. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1780. if ($lastTempo < 0.5) {
  1781. $fullCount++;
  1782. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1783. }
  1784. for ($i = 0; $i < $fullCount; $i++) {
  1785. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  1786. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  1787. }
  1788. }
  1789. $filterStr = implode(',', $filters);
  1790. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  1791. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  1792. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  1793. } else {
  1794. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  1795. $imageInfo = @getimagesize($inputFile);
  1796. $scaleW = 2048;
  1797. $scaleH = 2048;
  1798. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  1799. if ($imageInfo[0] >= $imageInfo[1]) {
  1800. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  1801. $scaleW = 2048;
  1802. } else {
  1803. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  1804. $scaleH = 2048;
  1805. }
  1806. }
  1807. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  1808. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  1809. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  1810. }
  1811. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  1812. $output = shell_exec($cmd);
  1813. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  1814. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  1815. 'input' => $inputFile,
  1816. 'output' => $output
  1817. ]);
  1818. @unlink($outputFile);
  1819. return null;
  1820. }
  1821. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  1822. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  1823. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  1824. ]);
  1825. return $outputFile;
  1826. } catch (\Exception $e) {
  1827. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  1828. return null;
  1829. }
  1830. }
  1831. /**
  1832. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  1833. *
  1834. * @param array $data
  1835. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  1836. */
  1837. public function getScriptGenerateTasks($data) {
  1838. $uid = Site::getUid();
  1839. return DB::table('mp_script_generate_tasks as t')
  1840. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  1841. ->where('t.uid', $uid)
  1842. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  1843. ->orderByDesc('t.id')
  1844. ->paginate(15);
  1845. }
  1846. public function saveScriptChatHistory($data) {
  1847. $uid = Site::getUid();
  1848. $rid = getProp($data, 'rid');
  1849. $script_id = getProp($data, 'script_id');
  1850. $sequence = getProp($data, 'sequence', 0);
  1851. $content = getProp($data, 'content');
  1852. if (!$rid) {
  1853. Utils::throwError('20003:请选择对话记录ID');
  1854. }
  1855. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  1856. if (!$record) {
  1857. Utils::throwError('20003:对话记录不存在');
  1858. }
  1859. if (!$script_id) {
  1860. Utils::throwError('20003:请选择剧本');
  1861. }
  1862. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  1863. if (!$script) {
  1864. Utils::throwError('20003:剧本不存在');
  1865. }
  1866. // 批量插入数据
  1867. return DB::table('mp_script_records')->where('id', $rid)->update([
  1868. 'content' => $content,
  1869. 'updated_at' => date('Y-m-d H:i:s')
  1870. ]);
  1871. }
  1872. /**
  1873. * 获取剧本的历史对话记录
  1874. *
  1875. * @param array $data 请求参数
  1876. * @return array 返回历史记录数组
  1877. */
  1878. public function getScriptChatHistory($data) {
  1879. $uid = Site::getUid();
  1880. $script_id = getProp($data, 'script_id');
  1881. $rid = getProp($data, 'rid');
  1882. $sequence = getProp($data, 'sequence', null);
  1883. if (!$script_id) {
  1884. Utils::throwError('20003:请提供剧本ID');
  1885. }
  1886. // 验证剧本是否存在
  1887. $script = DB::table('mp_scripts')
  1888. ->where('id', $script_id)
  1889. ->where('is_deleted', 0)
  1890. ->first();
  1891. if (!$script) {
  1892. Utils::throwError('20003:剧本不存在');
  1893. }
  1894. // 构建查询
  1895. $query = DB::table('mp_script_records')
  1896. ->where('script_id', $script_id);
  1897. // ->where('uid', $uid);
  1898. // 如果提供了 sequence,则过滤指定剧集
  1899. if ($sequence !== null) {
  1900. $query->where('sequence', $sequence);
  1901. }
  1902. // 记录ID筛选
  1903. if ($rid) {
  1904. $query->where('id', $rid);
  1905. }
  1906. // 查询记录并按 id 正序排序
  1907. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  1908. ->orderBy('created_at', 'asc')
  1909. ->orderBy('id', 'asc')
  1910. ->get()
  1911. ->map(function ($record) {
  1912. return [
  1913. 'rid' => $record->id,
  1914. 'script_id' => $record->script_id,
  1915. 'sequence' => $record->sequence,
  1916. 'role' => $record->role,
  1917. 'content' => $record->content,
  1918. 'products' => $record->products ? json_decode($record->products) : [],
  1919. 'created_at' => $record->created_at,
  1920. ];
  1921. })
  1922. ->toArray();
  1923. return $records;
  1924. }
  1925. /**
  1926. * 处理图片转换为base64
  1927. *
  1928. * @param mixed $image 图片文件对象或文件路径
  1929. * @return string|null base64编码的图片数据
  1930. */
  1931. private function processImageToBase64($image) {
  1932. try {
  1933. // 获取文件路径
  1934. if (is_string($image)) {
  1935. $filePath = $image;
  1936. } else {
  1937. // Laravel UploadedFile 对象
  1938. $filePath = $image->getRealPath();
  1939. }
  1940. if (!file_exists($filePath)) {
  1941. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  1942. return null;
  1943. }
  1944. // 验证是否为图片文件
  1945. $imageInfo = @getimagesize($filePath);
  1946. if ($imageInfo === false) {
  1947. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  1948. return null;
  1949. }
  1950. // 读取图片并转换为base64
  1951. $imageData = file_get_contents($filePath);
  1952. $base64Image = base64_encode($imageData);
  1953. dLog('deepseek')->info('图片转换成功', [
  1954. 'size' => strlen($imageData),
  1955. 'type' => $imageInfo['mime']
  1956. ]);
  1957. return $base64Image;
  1958. } catch (\Exception $e) {
  1959. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  1960. return null;
  1961. }
  1962. }
  1963. private function getArtStylePromptMappings($art_style='')
  1964. {
  1965. $arr = [
  1966. '唯美真人风格' => [
  1967. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  1968. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  1969. ],
  1970. '真人古风风格' => [
  1971. 'aliases' => ['真人古风风格', '真人古风'],
  1972. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  1973. ],
  1974. '日系动漫风格' => [
  1975. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  1976. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  1977. ],
  1978. '国漫风格' => [
  1979. 'aliases' => ['国漫风格', '国漫'],
  1980. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  1981. ],
  1982. 'Q版卡通风格' => [
  1983. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  1984. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  1985. ],
  1986. '简约扁平风格' => [
  1987. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  1988. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  1989. ],
  1990. '武侠风格' => [
  1991. 'aliases' => ['武侠风格', '武侠'],
  1992. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  1993. ],
  1994. '古风仙侠风格' => [
  1995. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  1996. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  1997. ],
  1998. '新中式水墨风格' => [
  1999. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2000. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  2001. ],
  2002. '写实插画风格' => [
  2003. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2004. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  2005. ],
  2006. '3D卡通风格' => [
  2007. 'aliases' => ['3D卡通风格', '3D卡通'],
  2008. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  2009. ],
  2010. '条漫风格' => [
  2011. 'aliases' => ['条漫风格', '条漫'],
  2012. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  2013. ],
  2014. '赛博朋克风格' => [
  2015. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2016. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  2017. ],
  2018. '暗黑悬疑风格' => [
  2019. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2020. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  2021. ],
  2022. '治愈清新风格' => [
  2023. 'aliases' => ['治愈清新风格', '治愈清新'],
  2024. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  2025. ],
  2026. '3D真人风格' => [
  2027. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  2028. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  2029. ],
  2030. ];
  2031. if($art_style) {
  2032. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  2033. }
  2034. return $arr;
  2035. $arr = [
  2036. '唯美真人风格' => [
  2037. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  2038. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  2039. 2. 色彩色调
  2040. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  2041. 3. 画质精度
  2042. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  2043. 4. 画面观感
  2044. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  2045. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  2046. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  2047. ],
  2048. '真人古风风格' => [
  2049. 'aliases' => ['真人古风风格', '真人古风'],
  2050. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  2051. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  2052. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  2053. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  2054. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  2055. ],
  2056. '日系动漫风格' => [
  2057. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  2058. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  2059. 正向提示词(中文)
  2060. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  2061. 必须遵守规则
  2062. • 全程保持日系动漫风格,不混入其他画风
  2063. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  2064. • 画面适配所选画面比例,构图居中,主体突出
  2065. • 线条干净、色彩统一,不杂乱、不突兀
  2066. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  2067. ],
  2068. '国漫风格' => [
  2069. 'aliases' => ['国漫风格', '国漫'],
  2070. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  2071. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  2072. 必须遵守规则
  2073. • 严格保持国漫画风,不串风格、不混画风
  2074. • 角色形象统一,不随意改变五官、身材、服饰
  2075. • 画面构图稳定,适合漫剧叙事展示
  2076. • 色调统一,不出现脏色、杂色
  2077. 禁止/避免词汇
  2078. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  2079. ],
  2080. 'Q版卡通风格' => [
  2081. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  2082. 'prompt' => "风格说明
  2083. 头大身小,造型可爱圆润,简约干净
  2084. 正向提示词(中文)
  2085. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  2086. 必须遵守规则
  2087. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  2088. • 角色造型统一,表情可爱,不诡异
  2089. • 画面简洁清爽,无多余复杂元素
  2090. • 色彩明亮柔和,不刺眼
  2091. 禁止/避免词汇
  2092. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  2093. ],
  2094. '简约扁平风格' => [
  2095. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  2096. 'prompt' => "风格说明
  2097. 色块简洁、无复杂渐变,现代极简风
  2098. 正向提示词(中文)
  2099. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  2100. 必须遵守规则
  2101. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  2102. • 构图简洁,主体突出,无多余装饰
  2103. • 色彩统一、干净,不杂乱
  2104. 禁止/避免词汇
  2105. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  2106. ],
  2107. '武侠风格' => [
  2108. 'aliases' => ['武侠风格', '武侠'],
  2109. 'prompt' => "风格说明
  2110. 江湖气息,线条硬朗,动作感强
  2111. 正向提示词(中文)
  2112. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  2113. 必须遵守规则
  2114. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  2115. • 角色形象、服饰、身材比例统一
  2116. • 画面动作自然,不扭曲、不畸形
  2117. 禁止/避免词汇
  2118. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  2119. ],
  2120. '古风仙侠风格' => [
  2121. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  2122. 'prompt' => "风格说明
  2123. 飘逸汉服、云雾仙气、唯美空灵
  2124. 正向提示词(中文)
  2125. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  2126. 必须遵守规则
  2127. • 保持古风仙侠统一画风,不混入现代、科幻元素
  2128. • 角色服饰、发型、形象前后一致
  2129. • 场景仙气飘逸,色调清雅统一
  2130. • 画面唯美柔和,不阴暗、不诡异
  2131. 禁止/避免词汇
  2132. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  2133. ],
  2134. '新中式水墨风格' => [
  2135. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  2136. 'prompt' => "风格说明
  2137. 淡墨渲染,毛笔笔触,留白意境
  2138. 正向提示词(中文)
  2139. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  2140. 必须遵守规则
  2141. • 严格保持水墨质感,不混入厚涂、写实、卡通
  2142. • 色调淡雅统一,不浓艳杂乱
  2143. • 画面干净有意境,不堆砌元素
  2144. 禁止/避免词汇
  2145. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  2146. ],
  2147. '写实插画风格' => [
  2148. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  2149. 'prompt' => "风格说明
  2150. 接近真人比例,光影真实,质感细腻
  2151. 正向提示词(中文)
  2152. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  2153. 必须遵守规则
  2154. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  2155. • 角色五官、身材、服饰高度统一
  2156. • 画面清晰、光影自然、不扭曲
  2157. 禁止/避免词汇
  2158. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  2159. ],
  2160. '3D卡通风格' => [
  2161. 'aliases' => ['3D卡通风格', '3D卡通'],
  2162. 'prompt' => "风格说明
  2163. 3D建模质感,柔和渲染,圆润可爱
  2164. 正向提示词(中文)
  2165. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  2166. 必须遵守规则
  2167. • 保持3D卡通统一质感,不出现2D杂乱线条
  2168. • 角色模型、比例、形象前后一致
  2169. • 画面干净,不模糊、不穿模
  2170. 禁止/避免词汇
  2171. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  2172. ],
  2173. '条漫风格' => [
  2174. 'aliases' => ['条漫风格', '条漫'],
  2175. 'prompt' => "风格说明
  2176. 纵向分镜,上下滑动阅读,轻量化
  2177. 正向提示词(中文)
  2178. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  2179. 必须遵守规则
  2180. • 保持条漫纵向阅读逻辑,构图简洁
  2181. • 画风统一,不混写实、3D、水墨
  2182. • 画面干净,不杂乱
  2183. 禁止/避免词汇
  2184. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  2185. ],
  2186. '赛博朋克风格' => [
  2187. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  2188. 'prompt' => "风格说明
  2189. 霓虹灯光、未来都市、暗色调、科技机械
  2190. 正向提示词(中文)
  2191. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  2192. 必须遵守规则
  2193. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  2194. • 色调以暗调+霓虹为主,色彩统一
  2195. • 画面科技感强,不杂乱
  2196. 禁止/避免词汇
  2197. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  2198. ],
  2199. '暗黑悬疑风格' => [
  2200. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  2201. 'prompt' => "风格说明
  2202. 低饱和、冷色调、阴影重、神秘压抑
  2203. 正向提示词(中文)
  2204. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  2205. 必须遵守规则
  2206. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  2207. • 画面氛围压抑神秘,但不低俗、不血腥
  2208. • 角色形象统一,不崩坏
  2209. 禁止/避免词汇
  2210. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  2211. ],
  2212. '治愈清新风格' => [
  2213. 'aliases' => ['治愈清新风格', '治愈清新'],
  2214. 'prompt' => "风格说明
  2215. 马卡龙色系、柔光、温暖干净
  2216. 正向提示词(中文)
  2217. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  2218. 必须遵守规则
  2219. • 保持治愈清新统一色调,不阴暗、不诡异
  2220. • 画面柔和干净,无杂乱元素
  2221. • 角色形象柔和可爱,不狰狞
  2222. 禁止/避免词汇
  2223. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  2224. ],
  2225. ];
  2226. return $arr;
  2227. }
  2228. public function getArtStylePromptByInput($inputArtStyle): string
  2229. {
  2230. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  2231. if ($normalizedInput === '') {
  2232. return '';
  2233. }
  2234. return $this->getArtStylePromptMappings($normalizedInput);
  2235. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  2236. // foreach ($mapping['aliases'] as $alias) {
  2237. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  2238. // if ($normalizedAlias === '') {
  2239. // continue;
  2240. // }
  2241. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  2242. // return $mapping['prompt'];
  2243. // }
  2244. // }
  2245. // }
  2246. return '';
  2247. }
  2248. public function getArtStyleShortPromptByInput($inputArtStyle) {
  2249. $stylePrefixes = [
  2250. '唯美真人风格' => [
  2251. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  2252. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  2253. ],
  2254. '真人古风风格' => [
  2255. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  2256. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  2257. ],
  2258. '日系动漫风格' => [
  2259. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  2260. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  2261. ],
  2262. '国漫风格' => [
  2263. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  2264. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  2265. ],
  2266. 'Q版卡通风格' => [
  2267. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  2268. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  2269. ],
  2270. '简约扁平风格' => [
  2271. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  2272. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  2273. ],
  2274. '武侠风格' => [
  2275. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  2276. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  2277. ],
  2278. '古风仙侠风格' => [
  2279. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  2280. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  2281. ],
  2282. '新中式水墨风格' => [
  2283. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  2284. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  2285. ],
  2286. '写实插画风格' => [
  2287. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  2288. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  2289. ],
  2290. '3D卡通风格' => [
  2291. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  2292. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  2293. ],
  2294. '条漫风格' => [
  2295. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  2296. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  2297. ],
  2298. '赛博朋克风格' => [
  2299. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  2300. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  2301. ],
  2302. '暗黑悬疑风格' => [
  2303. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  2304. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  2305. ],
  2306. '治愈清新风格' => [
  2307. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  2308. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  2309. ]
  2310. ];
  2311. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  2312. }
  2313. private function normalizeArtStyleInput($value): string
  2314. {
  2315. $value = trim((string)$value);
  2316. if ($value === '') {
  2317. return '';
  2318. }
  2319. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  2320. return mb_strtolower($value, 'UTF-8');
  2321. }
  2322. private function replaceArtStyleSection(string $content, string $artStyle): string
  2323. {
  2324. if ($content === '' || $artStyle === '') {
  2325. return $content;
  2326. }
  2327. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  2328. if (!preg_match($pattern, $content)) {
  2329. return $content;
  2330. }
  2331. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  2332. }
  2333. /**
  2334. * DeepSeek流式输出处理方法
  2335. *
  2336. * @param array $post_data DeepSeek API请求参数
  2337. * @return \Generator 返回生成器,用于流式输出
  2338. */
  2339. private function unwrapJsonWrappedContent($content) {
  2340. $trimmed = ltrim((string)$content);
  2341. if ($trimmed === '' || ($trimmed[0] !== '{' && $trimmed[0] !== '[')) {
  2342. return $content;
  2343. }
  2344. $decoded = json_decode($trimmed, true);
  2345. if (!is_array($decoded)) {
  2346. return $content;
  2347. }
  2348. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2349. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2350. return $decoded[$key];
  2351. }
  2352. }
  2353. return $content;
  2354. }
  2355. private function deepSeekStreamResponse($post_data) {
  2356. // 设置最大输出tokens
  2357. $post_data['max_tokens'] = 300000;
  2358. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2359. $post_data['stream_options'] = ['include_usage' => true];
  2360. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2361. $response = $client->post($this->url, [
  2362. 'json' => $post_data,
  2363. 'headers' => $this->headers,
  2364. 'stream' => true // 启用流式响应
  2365. ]);
  2366. $body = $response->getBody();
  2367. $fullContent = '';
  2368. $fullReasoningContent = '';
  2369. $usage = [];
  2370. $buffer = '';
  2371. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  2372. // 逐行读取流式响应
  2373. while (!$body->eof()) {
  2374. $chunk = $body->read(1024); // 每次读取 1KB
  2375. $buffer .= $chunk;
  2376. // 按行分割
  2377. $lines = explode("\n", $buffer);
  2378. // 保留最后一个不完整的行
  2379. $buffer = array_pop($lines);
  2380. foreach ($lines as $line) {
  2381. $line = trim($line);
  2382. // 跳过空行
  2383. if (empty($line)) {
  2384. continue;
  2385. }
  2386. // 检查是否是 SSE 数据行
  2387. if (strpos($line, 'data: ') !== 0) {
  2388. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2389. continue;
  2390. }
  2391. $data = substr($line, 6); // 移除 "data: " 前缀
  2392. if ($data === '[DONE]') {
  2393. dLog('deepseek')->info('收到结束标记');
  2394. break 2; // 跳出两层循环
  2395. }
  2396. try {
  2397. $json = json_decode($data, true);
  2398. if (json_last_error() !== JSON_ERROR_NONE) {
  2399. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2400. continue;
  2401. }
  2402. if (isset($json['choices'][0]['delta'])) {
  2403. $delta = $json['choices'][0]['delta'];
  2404. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2405. if (isset($delta['reasoning_content'])) {
  2406. $fullReasoningContent .= $delta['reasoning_content'];
  2407. yield [
  2408. 'type' => 'reasoning',
  2409. 'content' => $delta['reasoning_content'],
  2410. 'full_reasoning' => $fullReasoningContent
  2411. ];
  2412. }
  2413. // 处理最终回答内容
  2414. if (isset($delta['content'])) {
  2415. $fullContent .= $delta['content'];
  2416. yield [
  2417. 'type' => 'content',
  2418. 'content' => $delta['content'],
  2419. ];
  2420. }
  2421. }
  2422. // 获取使用统计信息
  2423. if (isset($json['usage'])) {
  2424. $usage = $json['usage'];
  2425. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2426. }
  2427. } catch (\Exception $e) {
  2428. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2429. continue;
  2430. }
  2431. }
  2432. }
  2433. dLog('deepseek')->info('流式读取完成', [
  2434. 'content_length' => strlen($fullContent),
  2435. 'reasoning_length' => strlen($fullReasoningContent)
  2436. ]);
  2437. yield [
  2438. 'type' => 'done',
  2439. 'full_content' => $fullContent,
  2440. 'full_reasoning' => $fullReasoningContent,
  2441. 'usage' => $usage
  2442. ];
  2443. }
  2444. /**
  2445. * GPT 重试次数(env 可配置,默认 5 次)
  2446. */
  2447. private function gptRetryTimes()
  2448. {
  2449. return (int)env('GPT_RETRY_TIMES', 5);
  2450. }
  2451. /**
  2452. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  2453. */
  2454. private function gptRetryInterval()
  2455. {
  2456. return (int)env('GPT_RETRY_INTERVAL', 10);
  2457. }
  2458. /**
  2459. * 判断 GPT 请求异常是否可重试
  2460. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  2461. */
  2462. private function isGptRetryableException(\Exception $e)
  2463. {
  2464. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  2465. return false;
  2466. }
  2467. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  2468. $status = $e->getResponse()->getStatusCode();
  2469. return $status >= 500 || $status == 429;
  2470. }
  2471. return true;
  2472. }
  2473. /**
  2474. * GPT 中转站探活:GET /v1/models,5 秒短超时
  2475. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  2476. */
  2477. private function checkGptServiceAvailable($apiKey = null)
  2478. {
  2479. if ($apiKey === null) {
  2480. $apiKey = env('GPT_54_API_KEY');
  2481. }
  2482. if (empty($apiKey)) {
  2483. return false;
  2484. }
  2485. try {
  2486. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  2487. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  2488. 'headers' => [
  2489. 'Authorization' => 'Bearer ' . $apiKey,
  2490. 'Content-Type' => 'application/json'
  2491. ]
  2492. ]);
  2493. $status = $response->getStatusCode();
  2494. return $status < 500 && $status != 429;
  2495. } catch (\Exception $e) {
  2496. return false;
  2497. }
  2498. }
  2499. /**
  2500. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  2501. * 全部失败抛出友好错误
  2502. */
  2503. private function ensureGptServiceAvailable($apiKey = null)
  2504. {
  2505. $maxRetries = $this->gptRetryTimes();
  2506. $interval = $this->gptRetryInterval();
  2507. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  2508. if ($this->checkGptServiceAvailable($apiKey)) {
  2509. return;
  2510. }
  2511. if ($attempt < $maxRetries) {
  2512. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  2513. 'retry' => $attempt + 1,
  2514. 'max_retries' => $maxRetries
  2515. ]);
  2516. sleep($interval);
  2517. }
  2518. }
  2519. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  2520. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  2521. 'max_retries' => $maxRetries,
  2522. 'interval' => $interval
  2523. ]);
  2524. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  2525. }
  2526. /**
  2527. * GPT 流式输出处理方法
  2528. *
  2529. * @param array $post_data GPT API请求参数
  2530. * @return \Generator 返回生成器,用于流式输出
  2531. */
  2532. private function gpt54StreamResponse($post_data) {
  2533. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  2534. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  2535. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  2536. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  2537. $usedLunaFallback = false;
  2538. // 流式请求长时间无任何返回(TTFB)超过该秒数时切换备用 Key(env 可配置,默认 600 秒)
  2539. $ttfbTimeoutSeconds = (int)env('GPT_SWITCH_LUNA_AFTER_SECONDS', 600);
  2540. if (empty($apiKey)) {
  2541. Utils::throwError('20003:GPT API Key未配置');
  2542. }
  2543. // 先探活,服务不可用时自动重试
  2544. $this->ensureGptServiceAvailable($apiKey);
  2545. $client = new Client(['timeout' => 1800, 'verify' => false, 'read_timeout' => $ttfbTimeoutSeconds]);
  2546. // 移除 thinking 参数,GPT-5.4 不支持
  2547. if (isset($post_data['thinking'])) {
  2548. unset($post_data['thinking']);
  2549. }
  2550. if (isset($post_data['reasoning_effort'])) {
  2551. unset($post_data['reasoning_effort']);
  2552. }
  2553. // 中转站不识别 response_format,可能被误转成 JSON 输出模式
  2554. if (isset($post_data['response_format'])) {
  2555. unset($post_data['response_format']);
  2556. }
  2557. $post_data['max_completion_tokens'] = 100000;
  2558. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  2559. $post_data['stream_options'] = ['include_usage' => true];
  2560. $maxRetries = $this->gptRetryTimes();
  2561. $interval = $this->gptRetryInterval();
  2562. $attempt = 0;
  2563. while (true) {
  2564. $fullContent = '';
  2565. $usage = [];
  2566. $buffer = '';
  2567. $suspectJsonWrap = false;
  2568. $pendingContent = '';
  2569. $requestStartedAt = microtime(true);
  2570. $headers = [
  2571. 'Authorization' => 'Bearer ' . $apiKey,
  2572. 'Content-Type' => 'application/json',
  2573. 'Accept' => 'text/event-stream'
  2574. ];
  2575. try {
  2576. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  2577. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  2578. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  2579. 'json' => $post_data,
  2580. 'headers' => $headers,
  2581. 'stream' => true // 启用流式响应
  2582. ]);
  2583. $body = $response->getBody();
  2584. dLog('deepseek')->info('开始读取 GPT 流式响应');
  2585. // 逐行读取流式响应
  2586. while (!$body->eof()) {
  2587. // 长时间没有任何内容返回时,切换备用 Key 重试
  2588. if ($fullContent === '' && empty($usage) && (microtime(true) - $requestStartedAt) > $ttfbTimeoutSeconds) {
  2589. throw new \RuntimeException('GPT 流式响应长时间无返回,等待切换备用 Key');
  2590. }
  2591. $chunk = $body->read(1024); // 每次读取 1KB
  2592. $buffer .= $chunk;
  2593. // 按行分割
  2594. $lines = explode("\n", $buffer);
  2595. // 保留最后一个不完整的行
  2596. $buffer = array_pop($lines);
  2597. foreach ($lines as $line) {
  2598. $line = trim($line);
  2599. // 跳过空行
  2600. if (empty($line)) {
  2601. continue;
  2602. }
  2603. // 检查是否是 SSE 数据行
  2604. if (strpos($line, 'data: ') !== 0) {
  2605. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2606. continue;
  2607. }
  2608. $data = substr($line, 6); // 移除 "data: " 前缀
  2609. if ($data === '[DONE]') {
  2610. dLog('deepseek')->info('收到结束标记');
  2611. break 2; // 跳出 foreach 和流读取循环
  2612. }
  2613. try {
  2614. $json = json_decode($data, true);
  2615. if (json_last_error() !== JSON_ERROR_NONE) {
  2616. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2617. continue;
  2618. }
  2619. if (isset($json['choices'][0]['delta'])) {
  2620. $delta = $json['choices'][0]['delta'];
  2621. // 处理回答内容
  2622. if (isset($delta['content'])) {
  2623. $fullContent .= $delta['content'];
  2624. $trimmed = ltrim($fullContent);
  2625. if (!$suspectJsonWrap && $trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
  2626. // 可能模型把整段正文包成了 JSON 字符串,先暂缓输出
  2627. $suspectJsonWrap = true;
  2628. }
  2629. if (!$suspectJsonWrap) {
  2630. // 中转可能一次返回大段内容,按小块输出保持流式节奏
  2631. $chunkSize = 256;
  2632. $chunkLength = mb_strlen($delta['content']);
  2633. for ($offset = 0; $offset < $chunkLength; $offset += $chunkSize) {
  2634. yield [
  2635. 'type' => 'content',
  2636. 'content' => mb_substr($delta['content'], $offset, $chunkSize),
  2637. ];
  2638. }
  2639. } else {
  2640. $pendingContent .= $delta['content'];
  2641. }
  2642. }
  2643. }
  2644. // 获取使用统计信息
  2645. if (isset($json['usage'])) {
  2646. $usage = $json['usage'];
  2647. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2648. }
  2649. } catch (\Exception $e) {
  2650. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2651. continue;
  2652. }
  2653. }
  2654. }
  2655. dLog('deepseek')->info('流式读取完成', [
  2656. 'content_length' => strlen($fullContent)
  2657. ]);
  2658. // 兼容模型偶发把整段正文包裹成 JSON 字符串返回
  2659. if ($suspectJsonWrap) {
  2660. $decoded = json_decode(trim($fullContent), true);
  2661. $unwrapped = null;
  2662. if (is_array($decoded)) {
  2663. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2664. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2665. $unwrapped = $decoded[$key];
  2666. break;
  2667. }
  2668. }
  2669. }
  2670. if ($unwrapped !== null) {
  2671. $fullContent = $unwrapped;
  2672. $chunkSize = 256;
  2673. $contentLength = mb_strlen($fullContent);
  2674. for ($offset = 0; $offset < $contentLength; $offset += $chunkSize) {
  2675. yield [
  2676. 'type' => 'content',
  2677. 'content' => mb_substr($fullContent, $offset, $chunkSize),
  2678. ];
  2679. }
  2680. } elseif ($pendingContent !== '') {
  2681. // 误判:补发暂缓内容,避免内容丢失
  2682. yield [
  2683. 'type' => 'content',
  2684. 'content' => $pendingContent,
  2685. ];
  2686. }
  2687. }
  2688. yield [
  2689. 'type' => 'done',
  2690. 'full_content' => $fullContent,
  2691. 'full_reasoning' => '',
  2692. 'usage' => $usage
  2693. ];
  2694. return;
  2695. } catch (\Exception $e) {
  2696. // 报错或长时间无返回时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  2697. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  2698. $usedLunaFallback = true;
  2699. $apiKey = $lunaApiKey;
  2700. dLog('deepseek')->warning('GPT 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  2701. continue;
  2702. }
  2703. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  2704. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  2705. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  2706. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  2707. throw $e;
  2708. }
  2709. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  2710. 'retry' => $attempt + 1,
  2711. 'max_retries' => $maxRetries,
  2712. 'error' => $e->getMessage()
  2713. ]);
  2714. sleep($interval);
  2715. $attempt++;
  2716. }
  2717. }
  2718. }
  2719. // 与推理模型对话
  2720. public function chatWithReasoner($data) {
  2721. $content = getProp($data, 'content');
  2722. $model = getProp($data, 'model', 'r1');
  2723. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2724. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2725. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2726. if ($model == 'r1') {
  2727. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  2728. $thinkingMode = 'disabled';
  2729. } else {
  2730. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  2731. $thinkingMode = 'disabled';
  2732. }
  2733. // 获取可选情感(根据音色可支持情感选)
  2734. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  2735. $emotion_list = [];
  2736. foreach ($timbre_emotion as $emotion) {
  2737. $tmp = explode(',', $emotion);
  2738. $emotion_list = array_merge($emotion_list, $tmp);
  2739. }
  2740. $emotion_list = array_unique($emotion_list);
  2741. $emotion_str = implode('、', $emotion_list);
  2742. // // 获取可选情感
  2743. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  2744. // $emotion_str = implode('、', $emotion_list);
  2745. // 是否启用情感
  2746. $enable_emotion = getProp($data, 'enable_emotion', 0);
  2747. if ($enable_emotion) {
  2748. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  2749. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2750. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  2751. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  2752. }else {
  2753. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  2754. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2755. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  2756. }
  2757. $messages = [
  2758. [
  2759. 'role' => 'system',
  2760. 'content' => $sys_content
  2761. ],
  2762. [
  2763. 'role' => 'user',
  2764. 'content' => $content
  2765. ]
  2766. ];
  2767. $post_data = [
  2768. 'model' => $model,
  2769. 'messages' => $messages,
  2770. // 'max_tokens' => 8192,
  2771. 'temperature' => 1,
  2772. 'frequency_penalty' => 0,
  2773. 'presence_penalty' => 0,
  2774. 'thinking' => ['type' => $thinkingMode],
  2775. 'response_format' => [
  2776. 'type' => 'text'
  2777. ],
  2778. 'stream' => false
  2779. ];
  2780. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2781. // 根据模型类型选择调用方法
  2782. $fullContent = '';
  2783. $usage = [];
  2784. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2785. // DeepSeek 官方模型使用 DeepSeek API
  2786. $chatResult = $this->chatOnly($post_data);
  2787. } else if (in_array($model, $this->gpt_text_models)) {
  2788. // GPT-5.4 模型使用 TokenRouter API
  2789. $chatResult = $this->gpt54ChatOnly($post_data);
  2790. } else {
  2791. // 其他模型使用火山引擎API
  2792. $chatResult = $this->volcEngineChatCompletion($post_data);
  2793. }
  2794. if (is_array($chatResult)) {
  2795. $fullContent = $chatResult['fullContent'];
  2796. $usage = $chatResult['usage'];
  2797. }
  2798. // 处理获取到的剧本数据
  2799. $script_content = handleScriptWords($fullContent, $enable_emotion);
  2800. $result = [
  2801. 'origin_content' => $fullContent,
  2802. 'roles' => getProp($script_content, 'roles'),
  2803. 'words' => getProp($script_content, 'words'),
  2804. ];
  2805. // 仅记录 token 使用明细(不扣积分)
  2806. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  2807. 'model' => $model,
  2808. 'source' => 'chatWithReasoner',
  2809. ], $model);
  2810. return $result;
  2811. }
  2812. public function resetParagraphAudio($data) {
  2813. $bid = getProp($data, 'bid');
  2814. $cid = getProp($data, 'cid');
  2815. $version_id = getProp($data, 'version_id');
  2816. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  2817. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  2818. 'generate_status' => '待制作',
  2819. 'updated_at' => date('Y-m-d H:i:s')
  2820. ]);
  2821. }
  2822. public function saveParagraphAudio($data) {
  2823. $bid = getProp($data, 'bid');
  2824. $cid = getProp($data, 'cid');
  2825. $version_id = getProp($data, 'version_id');
  2826. $sequence = getProp($data, 'sequence');
  2827. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  2828. // 获取所有情感
  2829. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  2830. $emotion_list = array_flip($emotion_list);
  2831. // 获取音色支持情感
  2832. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  2833. $timbre_emotion = explode(',', $timbre_emotion);
  2834. $emotion = getProp($data, 'emotion');
  2835. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  2836. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  2837. $list = [
  2838. 'bid' => $bid,
  2839. 'cid' => $cid,
  2840. 'version_id' => $version_id,
  2841. 'sequence' => $sequence,
  2842. 'role' => getProp($data, 'role'),
  2843. 'gender' => getProp($data, 'gender'),
  2844. 'text' => trim(getProp($data, 'text')),
  2845. 'emotion' => $emotion,
  2846. 'emotion_type' => $emotion_type,
  2847. 'voice_type' => getProp($data, 'voice_type'),
  2848. 'voice_name' => getProp($data, 'voice_name'),
  2849. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  2850. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  2851. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  2852. 'pitch' => getProp($data, 'pitch', 0),
  2853. // 'paragraph_audio_url' => '',
  2854. 'generate_status' => '制作中',
  2855. 'error_msg' => '',
  2856. 'updated_at' => date('Y-m-d H:i:s')
  2857. ];
  2858. $continue = false;
  2859. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  2860. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  2861. $list['generate_status'] = '制作成功';
  2862. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2863. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  2864. $continue = true;
  2865. }
  2866. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  2867. if ($id) {
  2868. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  2869. }else {
  2870. $list['created_at'] = date('Y-m-d H:i:s');
  2871. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  2872. $boolen = $id ? true : false;
  2873. }
  2874. // 如果更新成功则加入查询队列
  2875. if ($boolen) {
  2876. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  2877. Redis::sadd($redis_key, $id);
  2878. }
  2879. if ($boolen && !$continue) {
  2880. $boolen = false;
  2881. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2882. // 根据ID通过API通知合成音频
  2883. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  2884. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  2885. $response = $result->getBody()->getContents();
  2886. $response_arr = json_decode($response, true);
  2887. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2888. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2889. Log::info('通知火山生成段落音频失败: '.$error_msg);
  2890. Utils::throwError('20003:通知火山生成段落音频失败');
  2891. }
  2892. $boolen = true;
  2893. }
  2894. return $boolen;
  2895. }
  2896. public function insertAudioEffect($data) {
  2897. $audio_id = getProp($data, 'audio_id');
  2898. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2899. $bid = getProp($chapter_audio, 'bid');
  2900. $version_id = getProp($chapter_audio, 'version_id');
  2901. $cid = getProp($chapter_audio, 'cid');
  2902. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2903. $audio_effect_json = getProp($data, 'audio_effect_json');
  2904. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  2905. try {
  2906. DB::beginTransaction();
  2907. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2908. if (!$count) {
  2909. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2910. }else {
  2911. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2912. }
  2913. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2914. 'audio_effect_status' => '添加中',
  2915. 'audio_effect_json' => $audio_effect_json,
  2916. 'updated_at' => date('Y-m-d H:i:s')
  2917. ]);
  2918. if (!$boolen1) {
  2919. DB::rollBack();
  2920. Utils::throwError('20003:更新生成数据失败');
  2921. }
  2922. $id = DB::table('mp_audio_tasks')->insertGetId([
  2923. 'audio_id' => $audio_id,
  2924. 'generate_status' => '执行中',
  2925. 'generate_json' => json_encode([], 256),
  2926. 'bid' => $bid,
  2927. 'book_name' => getProp($chapter_audio, 'book_name'),
  2928. 'version_id' => $version_id,
  2929. 'version_name' => getProp($chapter_audio, 'version_name'),
  2930. 'cid' => $cid,
  2931. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2932. 'task_name' => $task_name,
  2933. 'created_at' => date('Y-m-d H:i:s'),
  2934. 'updated_at' => date('Y-m-d H:i:s')
  2935. ]);
  2936. if (!$id) {
  2937. DB::rollBack();
  2938. Utils::throwError('20003:创建任务失败');
  2939. }
  2940. }catch (\Exception $e) {
  2941. DB::rollBack();
  2942. Utils::throwError('20003:'.$e->getMessage());
  2943. }
  2944. DB::commit();
  2945. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2946. // 根据ID通过API通知合成音频
  2947. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2948. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2949. $response = $result->getBody()->getContents();
  2950. $response_arr = json_decode($response, true);
  2951. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2952. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2953. Log::info('通知火山插入音效失败: '.$error_msg);
  2954. Utils::throwError('20003:通知火山插入音效失败');
  2955. }
  2956. return true;
  2957. }
  2958. public function insertBgm($data) {
  2959. $audio_id = getProp($data, 'audio_id');
  2960. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2961. $bid = getProp($chapter_audio, 'bid');
  2962. $version_id = getProp($chapter_audio, 'version_id');
  2963. $cid = getProp($chapter_audio, 'cid');
  2964. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2965. $bgm_json = getProp($data, 'bgm_json');
  2966. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2967. if (!$bgm_json) {
  2968. $bgm_json = getProp($data, 'audio_effect_json');
  2969. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2970. }
  2971. try {
  2972. DB::beginTransaction();
  2973. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2974. if (!$count) {
  2975. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2976. }else {
  2977. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2978. }
  2979. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2980. 'bgm_status' => '添加中',
  2981. 'bgm_json' => $bgm_json,
  2982. 'updated_at' => date('Y-m-d H:i:s')
  2983. ]);
  2984. if (!$boolen1) {
  2985. DB::rollBack();
  2986. Utils::throwError('20003:更新生成数据失败');
  2987. }
  2988. $id = DB::table('mp_audio_tasks')->insertGetId([
  2989. 'audio_id' => $audio_id,
  2990. 'generate_status' => '执行中',
  2991. 'generate_json' => json_encode([], 256),
  2992. 'bid' => $bid,
  2993. 'book_name' => getProp($chapter_audio, 'book_name'),
  2994. 'version_id' => $version_id,
  2995. 'version_name' => getProp($chapter_audio, 'version_name'),
  2996. 'cid' => $cid,
  2997. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2998. 'task_name' => $task_name,
  2999. 'created_at' => date('Y-m-d H:i:s'),
  3000. 'updated_at' => date('Y-m-d H:i:s')
  3001. ]);
  3002. if (!$id) {
  3003. DB::rollBack();
  3004. Utils::throwError('20003:创建任务失败');
  3005. }
  3006. }catch (\Exception $e) {
  3007. DB::rollBack();
  3008. Utils::throwError('20003:'.$e->getMessage());
  3009. }
  3010. DB::commit();
  3011. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3012. // 根据ID通过API通知合成音频
  3013. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  3014. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  3015. $response = $result->getBody()->getContents();
  3016. $response_arr = json_decode($response, true);
  3017. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3018. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3019. Log::info('通知火山插入bgm失败: '.$error_msg);
  3020. Utils::throwError('20003:通知火山插入bgm失败');
  3021. }
  3022. return true;
  3023. }
  3024. public function getParagraphAudios($data) {
  3025. $bid = getProp($data, 'bid');
  3026. $cid = getProp($data, 'cid');
  3027. $version_id = getProp($data, 'version_id');
  3028. $sequence = getProp($data, 'sequence');
  3029. // 获取已生成的音频
  3030. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  3031. if ($sequence) $query->where('sequence', $sequence);
  3032. $paragraph_audios = $query->orderBy('sequence')->get();
  3033. $result = [];
  3034. foreach($paragraph_audios as $item) {
  3035. $result[] = [
  3036. 'sequence' => getProp($item, 'sequence'),
  3037. 'role' => getProp($item, 'role'),
  3038. 'gender' => getProp($item, 'gender'),
  3039. 'text' => trim(getProp($item, 'text')),
  3040. 'emotion' => getProp($item, 'emotion'),
  3041. 'emotion_type' => getProp($item, 'emotion_type'),
  3042. 'voice_type' => getProp($item, 'voice_type'),
  3043. 'voice_name' => getProp($item, 'voice_name'),
  3044. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3045. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3046. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3047. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3048. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  3049. ];
  3050. }
  3051. return $result;
  3052. }
  3053. // 新增合成任务
  3054. public function addGenerateTask($data) {
  3055. $bid = getProp($data, 'bid');
  3056. $cid = getProp($data, 'cid');
  3057. $version_id = getProp($data, 'version_id');
  3058. $generate_json = getProp($data, 'generate_json');
  3059. // 获取已生成的音频
  3060. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  3061. $paragraph_list = [];
  3062. foreach($paragraph_audios as $item) {
  3063. $paragraph_list[getProp($item, 'sequence')] = [
  3064. 'role' => getProp($item, 'role'),
  3065. 'gender' => getProp($item, 'gender'),
  3066. 'text' => trim(getProp($item, 'text')),
  3067. 'emotion' => getProp($item, 'emotion'),
  3068. 'emotion_type' => getProp($item, 'emotion_type'),
  3069. 'voice_type' => getProp($item, 'voice_type'),
  3070. 'voice_name' => getProp($item, 'voice_name'),
  3071. 'speed_ratio' => getProp($item, 'speed_ratio'),
  3072. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  3073. 'emotion_scale' => getProp($item, 'emotion_scale'),
  3074. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  3075. ];
  3076. }
  3077. // 更新角色-音色信息
  3078. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  3079. $existed_role_info = json_decode($existed_role_info, true);
  3080. if (!$existed_role_info) $existed_role_info = [];
  3081. // 获取情感信息
  3082. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  3083. $emotion_list = array_flip($emotion_list);
  3084. // 获取音色对应情感组
  3085. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  3086. $timbre_emotion_list = [];
  3087. foreach($timbre_emotions as $item) {
  3088. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  3089. }
  3090. // 构造生成音频的json
  3091. $words = json_decode($generate_json, true);
  3092. // 最终合成前的参数组
  3093. $mp_chapter_paragraph_audios = [];
  3094. $sequence = 1;
  3095. $complete_paragraph_sequences = [];
  3096. foreach($words as &$word) {
  3097. 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:参数格式有误');
  3098. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  3099. $role = getProp($word, 'role');
  3100. $word['gender'] = (int)$word['gender'];
  3101. // 判断音色对应情感是否支持,不支持则调整为中性
  3102. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  3103. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  3104. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  3105. if (isset($emotion_list[getProp($word, 'emotion')])) {
  3106. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  3107. }else {
  3108. $word['emotion'] = '中性';
  3109. $word['emotion_type'] = 'neutral';
  3110. }
  3111. $existed_role_info[$role] = [
  3112. 'timbre_type' => $word['voice_type'],
  3113. 'timbre_name' => $word['voice_name'],
  3114. 'emotion' => $word['emotion'],
  3115. 'emotion_type' => $word['emotion_type'],
  3116. 'speed_ratio' => $word['speed_ratio'],
  3117. 'loudness_ratio'=> $word['loudness_ratio'],
  3118. 'emotion_scale' => $word['emotion_scale'],
  3119. 'pitch' => $word['pitch']
  3120. ];
  3121. $word['paragraph_audio_url'] = '';
  3122. // 判断生成参数是否相同,相同则直接使用已生成的音频
  3123. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  3124. // 如果音频存在并且参数都未改变则使用已生成的音频
  3125. if (getProp($paragraph, 'paragraph_audio_url')) {
  3126. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  3127. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  3128. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  3129. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  3130. // {
  3131. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3132. // }
  3133. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  3134. }
  3135. $tmp = $word;
  3136. // 组装章节分句音频数据
  3137. // $tmp['sequence'] = getProp($word, 'sequence');
  3138. // $tmp['text'] = getProp($word, 'text');
  3139. // $tmp['emotion'] = getProp($word, 'emotion');
  3140. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  3141. // $tmp['voice_name'] = getProp($word, 'voice_name');
  3142. // $tmp['voice_type'] = getProp($word, 'voice_type');
  3143. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  3144. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  3145. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  3146. $tmp['bid'] = $bid;
  3147. $tmp['version_id'] = $version_id;
  3148. $tmp['cid'] = $cid;
  3149. $tmp['sequence'] = $sequence;
  3150. $tmp['created_at'] = date('Y-m-d H:i:s');
  3151. $tmp['updated_at'] = date('Y-m-d H:i:s');
  3152. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  3153. $mp_chapter_paragraph_audios[] = $tmp;
  3154. $complete_paragraph_sequences[] = $sequence;
  3155. $sequence++;
  3156. }
  3157. $generate_json = json_encode($words, 256);
  3158. // 判断是否有未生成字幕的段落
  3159. $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();
  3160. if ($no_subtitle_sequences) {
  3161. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  3162. }
  3163. try {
  3164. DB::beginTransaction();
  3165. $role_info = json_encode($existed_role_info, 256);
  3166. $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')]);
  3167. if (!$boolen) {
  3168. DB::rollBack();
  3169. Utils::throwError('20003:更新角色信息失败');
  3170. }
  3171. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  3172. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  3173. if (!$count) {
  3174. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  3175. }else {
  3176. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  3177. }
  3178. $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')]);
  3179. if (!$boolen1) {
  3180. DB::rollBack();
  3181. Utils::throwError('20003:更新生成数据失败');
  3182. }
  3183. $id = DB::table('mp_audio_tasks')->insertGetId([
  3184. 'audio_id' => getProp($chapter_audio, 'id'),
  3185. 'generate_status' => '执行中',
  3186. 'generate_json' => $generate_json,
  3187. 'bid' => $bid,
  3188. 'book_name' => getProp($chapter_audio, 'book_name'),
  3189. 'version_id' => $version_id,
  3190. 'version_name' => getProp($chapter_audio, 'version_name'),
  3191. 'cid' => $cid,
  3192. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  3193. 'task_name' => $task_name,
  3194. 'created_at' => date('Y-m-d H:i:s'),
  3195. 'updated_at' => date('Y-m-d H:i:s')
  3196. ]);
  3197. if (!$id) {
  3198. DB::rollBack();
  3199. Utils::throwError('20003:创建任务失败');
  3200. }
  3201. // 删除不在段落序号范围内的其他数据
  3202. if ($complete_paragraph_sequences) {
  3203. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  3204. }
  3205. // // 删除章节分句音频数据并重新插入
  3206. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  3207. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  3208. // if (!$boolen3) {
  3209. // DB::rollBack();
  3210. // Utils::throwError('20003:更新章节分句音频失败');
  3211. // }
  3212. } catch (\Exception $e) {
  3213. DB::rollBack();
  3214. Utils::throwError('20003:'.$e->getMessage());
  3215. }
  3216. DB::commit();
  3217. // 通知火山生成音频
  3218. $client = new Client(['timeout' => 1800, 'verify' => false]);
  3219. // 根据ID通过API通知合成音频
  3220. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  3221. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  3222. $response = $result->getBody()->getContents();
  3223. $response_arr = json_decode($response, true);
  3224. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  3225. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  3226. Log::info('通知火山生成音频失败: '.$error_msg);
  3227. Utils::throwError('20003:通知火山生成音频失败');
  3228. }
  3229. return true;
  3230. }
  3231. public function timbreList($data) {
  3232. $gender = getProp($data, 'gender');
  3233. $timbre_name = getProp($data, 'voice_name');
  3234. $category_id = getProp($data, 'category_id');
  3235. $age_stage = getProp($data, 'age_stage');
  3236. $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');
  3237. if ($gender) {
  3238. $query->where('gender', $gender);
  3239. }
  3240. if ($timbre_name) {
  3241. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  3242. }
  3243. if ($category_id) {
  3244. $query->where(function ($query) use ($category_id) {
  3245. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  3246. });
  3247. }
  3248. if ($age_stage) {
  3249. $query->where('age_stage', $age_stage);
  3250. }
  3251. $list = $query->get()->map(function ($value) {
  3252. $value = (array)$value;
  3253. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  3254. return $value;
  3255. })->toArray();
  3256. return $list;
  3257. }
  3258. // 生成火山临时token
  3259. public function setStsToken() {
  3260. // ************* 配置参数 *************
  3261. $method = 'GET';
  3262. $service = 'sts';
  3263. $host = 'open.volcengineapi.com';
  3264. $region = env('VOLC_REGION');
  3265. $endpoint = 'https://open.volcengineapi.com';
  3266. // $endpoint = 'https://tos-cn-beijing.volces.com';
  3267. $access_key = env('VOLC_AK');
  3268. $secret_key = env('VOLC_SK');
  3269. // 获取缓存中的token,如果没有则请求接口
  3270. $token = Redis::get('volc_sts_token');
  3271. if (!$token) {
  3272. // 查询参数
  3273. $query_parameters = [
  3274. 'Action' => 'AssumeRole',
  3275. 'RoleSessionName' => 'user@zw',
  3276. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  3277. 'Version' => '2018-01-01'
  3278. ];
  3279. // 生成URL编码的查询字符串
  3280. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  3281. // 获取签名头信息
  3282. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  3283. // 构建完整URL
  3284. $request_url = $endpoint . '?' . $request_parameters;
  3285. $client = new Client(['verify' => false]);
  3286. $response = $client->get($request_url, ['headers' => $headers]);
  3287. $response_arr = json_decode($response->getBody()->getContents(), true);
  3288. $result = [
  3289. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  3290. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  3291. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  3292. 'Region' => env('VOLC_REGION'),
  3293. 'Endpoint' => env('VOLC_END_POINT'),
  3294. 'Bucket' => env('VOLC_BUCKET'),
  3295. ];
  3296. // 缓存token
  3297. Redis::setex('volc_sts_token', 3000, json_encode($result));
  3298. return $result;
  3299. } else {
  3300. return json_decode($token, true);
  3301. }
  3302. // $response = $response['Response'];
  3303. // $access_key = $response['Credentials']['AccessKeyId'];
  3304. // $secret_key = $response['Credentials']['AccessKeySecret'];
  3305. // $security_token = $response['Credentials']['SecurityToken'];
  3306. // $expiration = $response['Credentials']['Expiration'];
  3307. // dd($response_arr);
  3308. }
  3309. public function emotionGroups($data) {
  3310. $id = getProp($data, 'group_id');
  3311. $group_name = getProp($data, 'group_name');
  3312. $voice_type = getProp($data, 'voice_type');
  3313. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  3314. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  3315. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  3316. if ($group_name) {
  3317. $query->where('group_name', 'like', "%{$group_name}%");
  3318. }
  3319. if ($id) {
  3320. $query->where('id', $id);
  3321. }
  3322. if ($voice_type) {
  3323. $query->where('voice_type', $voice_type);
  3324. }
  3325. return $query->orderBy('id')->get()->map(function ($value) {
  3326. return (array)$value;
  3327. })->toArray();
  3328. }
  3329. private function sign($key, $msg) {
  3330. return hash_hmac('sha256', $msg, $key, true);
  3331. }
  3332. // 生成签名密钥
  3333. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  3334. $kDate = $this->sign($key, $dateStamp);
  3335. $kRegion = $this->sign($kDate, $regionName);
  3336. $kService = $this->sign($kRegion, $serviceName);
  3337. $kSigning = $this->sign($kService, 'request');
  3338. return $kSigning;
  3339. }
  3340. // 获取签名头信息
  3341. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  3342. $contenttype = 'application/x-www-form-urlencoded';
  3343. $accept = 'application/json';
  3344. // 获取当前UTC时间
  3345. $t = new DateTime('now', new DateTimeZone('UTC'));
  3346. $xdate = $t->format('Ymd\THis\Z');
  3347. $datestamp = $t->format('Ymd');
  3348. // 1. 拼接规范请求串
  3349. $canonical_uri = '/';
  3350. $canonical_querystring = $request_parameters;
  3351. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  3352. $signed_headers = 'content-type;host;x-date';
  3353. // 空请求体的SHA256哈希
  3354. $payload_hash = hash('sha256', '');
  3355. $canonical_request = implode("\n", [
  3356. $method,
  3357. $canonical_uri,
  3358. $canonical_querystring,
  3359. $canonical_headers,
  3360. $signed_headers,
  3361. $payload_hash
  3362. ]);
  3363. // 2. 拼接待签名字符串
  3364. $algorithm = 'HMAC-SHA256';
  3365. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  3366. $hashed_canonical_request = hash('sha256', $canonical_request);
  3367. $string_to_sign = implode("\n", [
  3368. $algorithm,
  3369. $xdate,
  3370. $credential_scope,
  3371. $hashed_canonical_request
  3372. ]);
  3373. // 3. 计算签名
  3374. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  3375. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  3376. // 4. 添加签名到请求头
  3377. $authorization_header = sprintf(
  3378. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  3379. $algorithm,
  3380. $access_key,
  3381. $credential_scope,
  3382. $signed_headers,
  3383. $signature
  3384. );
  3385. return [
  3386. 'Accept' => $accept,
  3387. 'Content-Type' => $contenttype,
  3388. 'X-Date' => $xdate,
  3389. 'Authorization' => $authorization_header
  3390. ];
  3391. }
  3392. // 文字合成语音(火山引擎)
  3393. public function tts($data) {
  3394. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  3395. $headers = [
  3396. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  3397. 'Content-Type' => 'application/json; charset=UTF-8'
  3398. ];
  3399. $post_data = [
  3400. 'app' => [
  3401. 'appid' => env('VOLC_APPID'),
  3402. 'token' => env('VOLC_TOKEN'),
  3403. 'cluster' => 'volcano_tts'
  3404. ],
  3405. 'user' => [
  3406. 'uid' => 'mp_audio'
  3407. ],
  3408. // 'audio' => [
  3409. // 'voice_type' =>
  3410. // ],
  3411. ];
  3412. }
  3413. public function scriptList($data) {
  3414. $uid = Site::getUid();
  3415. $script_id = getProp($data, 'script_id');
  3416. $script_name = getProp($data, 'script_name');
  3417. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  3418. if ($script_id) {
  3419. $query->where('id', $script_id);
  3420. }
  3421. if ($script_name) {
  3422. $query->where('script_name', 'like', "%{$script_name}%");
  3423. }
  3424. return $query->orderBy('created_at', 'desc')->paginate(12);
  3425. }
  3426. public function scripts($data) {
  3427. $uid = Site::getUid();
  3428. $script_id = getProp($data, 'script_id');
  3429. $script_name = getProp($data, 'script_name');
  3430. $is_products = getProp($data, 'is_products');
  3431. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  3432. if ($script_id) {
  3433. $query->where('id', $script_id);
  3434. }
  3435. if ($is_products !== '') {
  3436. $query->where('is_products', $is_products);
  3437. }
  3438. if ($script_name) {
  3439. $query->where('script_name', 'like', "%{$script_name}%");
  3440. }
  3441. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  3442. return (array)$value;
  3443. })->toArray();
  3444. }
  3445. public function scriptInfo($data) {
  3446. $uid = Site::getUid();
  3447. $script_id = getProp($data, 'script_id');
  3448. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  3449. // ->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();
  3450. ->selectRaw('id as script_id, script_name')->first();
  3451. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3452. $script = (array)$script;
  3453. // 获取分集组信息
  3454. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  3455. ->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')
  3456. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  3457. $value = (array)$value;
  3458. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  3459. return (array)$value;
  3460. })->toArray();
  3461. $script['group'] = $groups;
  3462. return $script;
  3463. }
  3464. public function createScript($data) {
  3465. $script_name = getProp($data, 'script_name');
  3466. $uid = Site::getUid(); // 获取当前用户ID
  3467. $cpid = Site::getCpid(); // 获取当前公司组ID
  3468. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  3469. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  3470. $script_name .= '_'.date('YmdHis');
  3471. }
  3472. return DB::table('mp_scripts')->insertGetId([
  3473. 'script_name' => $script_name,
  3474. 'user_id' => $uid,
  3475. 'cpid' => $cpid,
  3476. 'created_at' => date('Y-m-d H:i:s'),
  3477. 'updated_at' => date('Y-m-d H:i:s')
  3478. ]);
  3479. }
  3480. public function editScript($data) {
  3481. $script_id = getProp($data, 'script_id');
  3482. $script_name = getProp($data, 'script_name');
  3483. $uid = Site::getUid(); // 获取当前用户ID
  3484. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  3485. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  3486. if ($id && (int)$id !== (int)$script_id) {
  3487. $script_name .= '_'.date('YmdHis');
  3488. }
  3489. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3490. 'script_name' => $script_name,
  3491. 'updated_at' => date('Y-m-d H:i:s')
  3492. ]);
  3493. }
  3494. public function delScript($data) {
  3495. $script_id = getProp($data, 'script_id');
  3496. $uid = Site::getUid(); // 获取当前用户ID
  3497. if (!$script_id) Utils::throwError('20003:请选择剧本');
  3498. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3499. 'is_deleted' => 1,
  3500. 'updated_at' => date('Y-m-d H:i:s')
  3501. ]);
  3502. }
  3503. public function createEpisode($data) {
  3504. $script_id = getProp($data, 'script_id');
  3505. $group_name = getProp($data, 'group_name');
  3506. $remark = getProp($data, 'remark');
  3507. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  3508. $uid = Site::getUid(); // 获取当前用户ID
  3509. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  3510. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  3511. $group_name .= '_'.date('YmdHis');
  3512. }
  3513. return DB::table('mp_script_episode_group')->insertGetId([
  3514. 'script_id' => $script_id,
  3515. 'group_name' => $group_name,
  3516. 'user_id' => $uid,
  3517. 'remark' => $remark,
  3518. 'created_at' => date('Y-m-d H:i:s'),
  3519. 'updated_at' => date('Y-m-d H:i:s')
  3520. ]);
  3521. }
  3522. public function editEpisode($data) {
  3523. $group_id = getProp($data, 'group_id');
  3524. $start_episode_number = getProp($data, 'start_episode_number');
  3525. $end_episode_number = getProp($data, 'end_episode_number');
  3526. $group_name = getProp($data, 'group_name');
  3527. $uid = Site::getUid(); // 获取当前用户ID
  3528. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  3529. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  3530. if ($id && (int)$id !== (int)$group_id) {
  3531. $group_name .= '_'.date('YmdHis');
  3532. }
  3533. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3534. 'group_name' => $group_name,
  3535. 'start_episode_number' => $start_episode_number,
  3536. 'end_episode_number' => $end_episode_number,
  3537. 'updated_at' => date('Y-m-d H:i:s')
  3538. ]);
  3539. }
  3540. public function delEpisode($data) {
  3541. $group_id = getProp($data, 'group_id');
  3542. $uid = Site::getUid(); // 获取当前用户ID
  3543. if (!$group_id) Utils::throwError('20003:请选择分集');
  3544. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3545. 'is_deleted' => 1,
  3546. 'updated_at' => date('Y-m-d H:i:s')
  3547. ]);
  3548. }
  3549. /**
  3550. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3551. *
  3552. * @param array $data 包含以下参数:
  3553. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3554. * - question: 用户问题(可选)
  3555. * - model: 使用的模型(r1 或 v3,默认 v3)
  3556. * @return \Generator 返回生成器,用于流式输出
  3557. */
  3558. public function generateEpisodes($data) {
  3559. $script_id = getProp($data, 'script_id');
  3560. $group_id = getProp($data, 'group_id');
  3561. // $file = getProp($data, 'file');
  3562. $file = '';
  3563. $content = getProp($data, 'content', '');
  3564. // $bid = getProp($data, 'bid', 0);
  3565. $bid = 0;
  3566. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3567. if (!$group) {
  3568. Utils::throwError('20003:剧本分集不存在');
  3569. }
  3570. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  3571. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  3572. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  3573. $prompt = getProp($data, 'prompt');
  3574. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  3575. $model = getProp($data, 'model');
  3576. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3577. Utils::throwError('20003:该模型不存在!');
  3578. }
  3579. // 检查是否存在重叠的剧集序号范围
  3580. $exists_groups = DB::table('mp_script_episode_group')
  3581. ->where('script_id', $script_id)
  3582. ->where('id', '<>', $group_id) // 排除当前组
  3583. ->where('is_deleted', 0)
  3584. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3585. // 检查新范围是否与现有范围重叠
  3586. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3587. // 新范围的开始在现有范围内
  3588. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3589. ->where('end_episode_number', '>=', $start_episode_sequence);
  3590. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3591. // 新范围的结束在现有范围内
  3592. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3593. ->where('end_episode_number', '>=', $end_episode_sequence);
  3594. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3595. // 新范围完全包含现有范围
  3596. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3597. ->where('end_episode_number', '<=', $end_episode_sequence);
  3598. });
  3599. })
  3600. ->select('start_episode_number', 'end_episode_number')
  3601. ->get();
  3602. if ($exists_groups->isNotEmpty()) {
  3603. $conflict_ranges = [];
  3604. foreach ($exists_groups as $group) {
  3605. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3606. }
  3607. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3608. }
  3609. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3610. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3611. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3612. if ($model === 'deepseek-chat') {
  3613. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3614. $model = 'deepseek-v4-flash';
  3615. $thinkingMode = 'disabled';
  3616. } elseif ($model === 'deepseek-reasoner') {
  3617. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3618. $model = 'deepseek-v4-flash';
  3619. $thinkingMode = 'enabled';
  3620. }
  3621. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3622. if (!$script) {
  3623. Utils::throwError('20003:剧本不存在');
  3624. }
  3625. $content = getProp($group, 'content');
  3626. if (!$file && !$content && !$bid) {
  3627. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3628. }
  3629. // 提取文件内容
  3630. if ($file) {
  3631. $content = $this->extractFileContent($file);
  3632. if (!$content) {
  3633. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3634. }
  3635. } elseif ($bid) {
  3636. $content = $this->getContentByBid($bid);
  3637. if (!$content) {
  3638. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3639. }
  3640. } elseif ($content) {
  3641. $content = filterContent($content);
  3642. } elseif ($prompt) {
  3643. $content = filterContent($prompt);
  3644. } else {
  3645. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3646. }
  3647. // 构建消息
  3648. $messages = [
  3649. $this->sys_message,
  3650. [
  3651. 'role' => 'user',
  3652. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3653. ]
  3654. ];
  3655. $post_data = [
  3656. 'model' => $model,
  3657. 'messages' => $messages,
  3658. // 'max_tokens' => 8192,
  3659. 'temperature' => 0.7,
  3660. 'frequency_penalty' => 0,
  3661. 'presence_penalty' => 0,
  3662. 'thinking' => ['type' => $thinkingMode],
  3663. 'response_format' => ['type' => 'text'],
  3664. 'stream' => true
  3665. ];
  3666. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3667. // 根据模型类型选择调用方法
  3668. $fullContent = '';
  3669. $fullReasoningContent = '';
  3670. $usage = [];
  3671. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3672. // DeepSeek 官方模型使用 DeepSeek API
  3673. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3674. } else if (in_array($model, $this->gpt_text_models)) {
  3675. // GPT-5.4 模型使用 TokenRouter API
  3676. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3677. } else if (in_array($model, $this->gemini_text_models)) {
  3678. // Gemini 模型使用 Gemini API
  3679. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3680. } else {
  3681. // 其他模型使用火山引擎API
  3682. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3683. }
  3684. // 处理流式输出
  3685. foreach ($streamGenerator as $chunk) {
  3686. if (isset($chunk['type'])) {
  3687. if ($chunk['type'] === 'done') {
  3688. // 最终结果
  3689. $fullContent = $chunk['full_content'];
  3690. $fullReasoningContent = $chunk['full_reasoning'];
  3691. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3692. } else {
  3693. // 逐块yield数据
  3694. yield $chunk;
  3695. }
  3696. }
  3697. }
  3698. dLog('deepseek')->info('完整内容: '.$fullContent);
  3699. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3700. // 处理完整内容并返回最终结果
  3701. $script_arr = [];
  3702. if ($fullContent) {
  3703. $script_arr = extractScriptContent($fullContent);
  3704. }
  3705. logDB('deepseek', 'info', '解析内容', $script_arr);
  3706. if (!$script_arr['episodes']) {
  3707. Utils::throwError('20003:未生成剧本相关信息');
  3708. // yield [
  3709. // 'type' => 'done',
  3710. // 'script' => $script_arr,
  3711. // 'msg' => '未生成剧本相关信息',
  3712. // 'answer' => $fullContent,
  3713. // 'reasoning' => $fullReasoningContent,
  3714. // 'usage' => $usage
  3715. // ];
  3716. // return ;
  3717. }
  3718. try {
  3719. DB::beginTransaction();
  3720. // // 返回前保存剧本内容
  3721. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3722. // 'content' => $content,
  3723. // 'updated_at' => date('Y-m-d H:i:s')
  3724. // ]);
  3725. // if (!$boolen) {
  3726. // Utils::throwError('20003:保存剧本内容失败');
  3727. // }
  3728. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3729. // 'start_episode_number' => $start_episode_sequence,
  3730. // 'end_episode_number' => $end_episode_sequence,
  3731. // 'updated_at' => date('Y-m-d H:i:s')
  3732. // ]);
  3733. // if (!$boolen1) {
  3734. // Utils::throwError('20003:保存分集失败');
  3735. // }
  3736. $episode_content = '';
  3737. $episodes = [];
  3738. foreach ($script_arr['episodes'] as $item) {
  3739. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  3740. // $episodes[] = [
  3741. // 'script_id' => $script_id,
  3742. // 'episode_number' => $item['episode_number'],
  3743. // 'episode_name' => $item['episode_name'],
  3744. // 'episode_content' => $item['episode_content'],
  3745. // 'created_at' => date('Y-m-d H:i:s'),
  3746. // 'updated_at' => date('Y-m-d H:i:s'),
  3747. // ];
  3748. }
  3749. if ($episode_content) {
  3750. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3751. 'episode_content' => $episode_content,
  3752. 'updated_at' => date('Y-m-d H:i:s')
  3753. ]);
  3754. if (!$boolen2) {
  3755. Utils::throwError('20003:保存分集内容失败');
  3756. }
  3757. }else {
  3758. Utils::throwError('20003:分集剧本解析失败');
  3759. }
  3760. }catch (\Exception $e) {
  3761. DB::rollBack();
  3762. Utils::throwError('20003:'.$e->getMessage());
  3763. }
  3764. DB::commit();
  3765. // 仅记录 token 使用明细(不扣积分)
  3766. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  3767. 'model' => $model,
  3768. 'script_id' => $script_id,
  3769. 'group_id' => $group_id,
  3770. 'source' => 'generateEpisodes',
  3771. ], $model);
  3772. yield [
  3773. 'type' => 'done',
  3774. 'script' => $script_arr,
  3775. 'episode_content' => $episode_content,
  3776. 'answer' => $fullContent,
  3777. 'reasoning' => $fullReasoningContent,
  3778. 'usage' => $usage
  3779. ];
  3780. }
  3781. public function chatWithFileStream($data) {
  3782. $script_id = getProp($data, 'script_id');
  3783. $group_id = getProp($data, 'group_id');
  3784. $file = getProp($data, 'file');
  3785. $content = getProp($data, 'content', '');
  3786. $bid = getProp($data, 'bid', 0);
  3787. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3788. $total_episode_num = getProp($data, 'total_episode_num', 30);
  3789. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  3790. $prompt = getProp($data, 'prompt');
  3791. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  3792. if (!empty($prompt)) {
  3793. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  3794. }
  3795. $question = getProp($data, 'question', $baseQuestion);
  3796. $model = getProp($data, 'model');
  3797. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3798. Utils::throwError('20003:该模型不存在!');
  3799. }
  3800. // 检查是否存在重叠的剧集序号范围
  3801. $exists_groups = DB::table('mp_script_episode_group')
  3802. ->where('script_id', $script_id)
  3803. ->where('id', '<>', $group_id)
  3804. ->where('is_deleted', 0)
  3805. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3806. // 检查新范围是否与现有范围重叠
  3807. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3808. // 新范围的开始在现有范围内
  3809. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3810. ->where('end_episode_number', '>=', $start_episode_sequence);
  3811. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3812. // 新范围的结束在现有范围内
  3813. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3814. ->where('end_episode_number', '>=', $end_episode_sequence);
  3815. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3816. // 新范围完全包含现有范围
  3817. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3818. ->where('end_episode_number', '<=', $end_episode_sequence);
  3819. });
  3820. })
  3821. ->select('start_episode_number', 'end_episode_number')
  3822. ->get();
  3823. if ($exists_groups->isNotEmpty()) {
  3824. $conflict_ranges = [];
  3825. foreach ($exists_groups as $group) {
  3826. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3827. }
  3828. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3829. }
  3830. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3831. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3832. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3833. if ($model === 'deepseek-chat') {
  3834. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3835. $model = 'deepseek-v4-flash';
  3836. $thinkingMode = 'disabled';
  3837. } elseif ($model === 'deepseek-reasoner') {
  3838. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3839. $model = 'deepseek-v4-flash';
  3840. $thinkingMode = 'enabled';
  3841. }
  3842. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3843. if (!$script) {
  3844. Utils::throwError('20003:剧本不存在');
  3845. }
  3846. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3847. if (!$group) {
  3848. Utils::throwError('20003:剧本分集不存在');
  3849. }
  3850. if (!$file && !$content && !$bid) {
  3851. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3852. }
  3853. // 提取文件内容
  3854. if ($file) {
  3855. $content = $this->extractFileContent($file);
  3856. if (!$content) {
  3857. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3858. }
  3859. } elseif ($bid) {
  3860. $content = $this->getContentByBid($bid);
  3861. if (!$content) {
  3862. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3863. }
  3864. } elseif ($content) {
  3865. $content = filterContent($content);
  3866. } elseif ($prompt) {
  3867. $content = filterContent($prompt);
  3868. } else {
  3869. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3870. }
  3871. // 构建消息
  3872. $messages = [
  3873. [
  3874. 'role' => 'system',
  3875. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3876. 强制要求:\n
  3877. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3878. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  3879. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  3880. 普通要求:\n
  3881. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  3882. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  3883. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  3884. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  3885. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  3886. 示例如下:\n
  3887. ###剧本名:西昆仑
  3888. ###故事梗概
  3889. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3890. ###剧本亮点
  3891. 亮点1:绝境奇药,生死一线
  3892. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3893. 亮点2:结拜兄妹,化解尴尬
  3894. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3895. 亮点3:纤发夺命,情愫暗涌
  3896. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3897. ###人物关系
  3898. 阿雪与梁萧之间存在兄妹之情。
  3899. ###核心矛盾
  3900. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3901. ###主体列表
  3902. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  3903. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  3904. 阴阳球:天地异宝,能化生精气,救人于危难。
  3905. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  3906. ###美术风格
  3907. 基础画风风格词:厚涂古风
  3908. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3909. ###场景列表
  3910. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  3911. [
  3912. 'role' => 'user',
  3913. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3914. ]
  3915. ];
  3916. $post_data = [
  3917. 'model' => $model,
  3918. 'messages' => $messages,
  3919. // 'max_tokens' => 8192,
  3920. 'temperature' => 0.7,
  3921. 'frequency_penalty' => 0,
  3922. 'presence_penalty' => 0,
  3923. 'thinking' => ['type' => $thinkingMode],
  3924. 'response_format' => ['type' => 'text'],
  3925. 'stream' => true
  3926. ];
  3927. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3928. // 根据模型类型选择调用方法
  3929. $fullContent = '';
  3930. $fullReasoningContent = '';
  3931. $usage = [];
  3932. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3933. // DeepSeek 官方模型使用 DeepSeek API
  3934. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3935. } else if (in_array($model, $this->gpt_text_models)) {
  3936. // GPT-5.4 模型使用 TokenRouter API
  3937. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3938. } else if (in_array($model, $this->gemini_text_models)) {
  3939. // Gemini 模型使用 Gemini API
  3940. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3941. } else {
  3942. // 其他模型使用火山引擎API
  3943. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3944. }
  3945. // 处理流式输出
  3946. foreach ($streamGenerator as $chunk) {
  3947. if (isset($chunk['type'])) {
  3948. if ($chunk['type'] === 'done') {
  3949. // 最终结果
  3950. $fullContent = $chunk['full_content'];
  3951. $fullReasoningContent = $chunk['full_reasoning'];
  3952. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3953. } else {
  3954. // 逐块yield数据
  3955. yield $chunk;
  3956. }
  3957. }
  3958. }
  3959. dLog('deepseek')->info('完整内容: '.$fullContent);
  3960. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3961. // 处理完整内容并返回最终结果
  3962. $script_arr = [];
  3963. if ($fullContent) {
  3964. $script_arr = extractScriptContent($fullContent);
  3965. }
  3966. logDB('deepseek', 'info', '解析内容', $script_arr);
  3967. if (!$script_arr['roles']) {
  3968. Utils::throwError('20003:未生成剧本相关信息');
  3969. // yield [
  3970. // 'type' => 'done',
  3971. // 'script' => $script_arr,
  3972. // 'msg' => '未生成剧本相关信息',
  3973. // 'answer' => $fullContent,
  3974. // 'reasoning' => $fullReasoningContent,
  3975. // 'usage' => $usage
  3976. // ];
  3977. }
  3978. try {
  3979. DB::beginTransaction();
  3980. // // 返回前保存剧本内容
  3981. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3982. // 'content' => $content,
  3983. // 'status' => '解析完成',
  3984. // 'updated_at' => date('Y-m-d H:i:s')
  3985. // ]);
  3986. // if (!$boolen) {
  3987. // Utils::throwError('20003:保存剧本内容失败');
  3988. // }
  3989. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3990. 'start_episode_number' => $start_episode_sequence,
  3991. 'end_episode_number' => $end_episode_sequence,
  3992. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3993. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3994. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3995. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3996. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3997. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3998. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3999. 'status' => '解析完成',
  4000. 'content' => $content,
  4001. 'updated_at' => date('Y-m-d H:i:s')
  4002. ]);
  4003. if (!$boolen1) {
  4004. Utils::throwError('20003:保存分集失败');
  4005. }
  4006. // $episodes = [];
  4007. // foreach ($script_arr['episodes'] as $item) {
  4008. // $episodes[] = [
  4009. // 'script_id' => $script_id,
  4010. // 'episode_number' => $item['episode_number'],
  4011. // 'episode_name' => $item['episode_name'],
  4012. // 'episode_content' => $item['episode_content'],
  4013. // 'created_at' => date('Y-m-d H:i:s'),
  4014. // 'updated_at' => date('Y-m-d H:i:s'),
  4015. // ];
  4016. // }
  4017. // if ($episodes) {
  4018. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4019. // if (!$boolen2) {
  4020. // Utils::throwError('20003:保存分集内容失败');
  4021. // }
  4022. // }else {
  4023. // Utils::throwError('20003:分集剧本解析失败');
  4024. // }
  4025. }catch (\Exception $e) {
  4026. DB::rollBack();
  4027. Utils::throwError('20003:'.$e->getMessage());
  4028. }
  4029. DB::commit();
  4030. // 仅记录 token 使用明细(不扣积分)
  4031. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  4032. 'model' => $model,
  4033. 'script_id' => $script_id,
  4034. 'group_id' => $group_id,
  4035. 'source' => 'chatWithFileStream',
  4036. ], $model);
  4037. yield [
  4038. 'type' => 'done',
  4039. 'script' => $script_arr,
  4040. 'answer' => $fullContent,
  4041. 'reasoning' => $fullReasoningContent,
  4042. 'usage' => $usage
  4043. ];
  4044. }
  4045. /**
  4046. * 上传文件识别文字内容并与 DeepSeek 进行对话
  4047. *
  4048. * @param array $data 包含以下参数:
  4049. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4050. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  4051. * - model: 使用的模型(r1 或 v3,默认 v3)
  4052. * @return array
  4053. */
  4054. public function chatWithFile($data) {
  4055. $script_id = getProp($data, 'script_id');
  4056. $file = getProp($data, 'file');
  4057. $content = getProp($data, 'content', '');
  4058. $bid = getProp($data, 'bid', 0);
  4059. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4060. $total_episode_num = getProp($data, 'total_episode_num', 30);
  4061. $prompt = getProp($data, 'prompt');
  4062. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  4063. if (!empty($prompt)) {
  4064. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  4065. }
  4066. $question = getProp($data, 'question', $baseQuestion);
  4067. // 处理文本模型
  4068. $model = getProp($data, 'model');
  4069. if (!$model) {
  4070. // 用户没有输入,使用默认值
  4071. $model = 'doubao-seed-2-0-mini-260215';
  4072. }
  4073. // 验证模型是否在可用模型表中
  4074. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4075. $model = 'doubao-seed-2-0-mini-260215';
  4076. }
  4077. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4078. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4079. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4080. if ($model === 'deepseek-chat') {
  4081. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4082. $model = 'deepseek-v4-flash';
  4083. $thinkingMode = 'disabled';
  4084. } elseif ($model === 'deepseek-reasoner') {
  4085. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4086. $model = 'deepseek-v4-flash';
  4087. $thinkingMode = 'enabled';
  4088. }
  4089. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  4090. if (!$script) {
  4091. Utils::throwError('20003:剧本不存在');
  4092. }
  4093. if (!$file && !$content && !$bid) {
  4094. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4095. }
  4096. // 提取文件内容
  4097. if ($file) {
  4098. $content = $this->extractFileContent($file);
  4099. if (!$content) {
  4100. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4101. }
  4102. } elseif ($bid) {
  4103. $content = $this->getContentByBid($bid);
  4104. if (!$content) {
  4105. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4106. }
  4107. } elseif ($content) {
  4108. $content = filterContent($content);
  4109. } elseif ($prompt) {
  4110. $content = filterContent($prompt);
  4111. } else {
  4112. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4113. }
  4114. // 构建消息
  4115. $messages = [
  4116. $this->sys_message,
  4117. [
  4118. 'role' => 'user',
  4119. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  4120. ]
  4121. ];
  4122. $post_data = [
  4123. 'model' => $model,
  4124. 'messages' => $messages,
  4125. // 'max_tokens' => 8192,
  4126. 'temperature' => 0.7,
  4127. 'frequency_penalty' => 0,
  4128. 'presence_penalty' => 0,
  4129. 'thinking' => ['type' => $thinkingMode],
  4130. 'response_format' => ['type' => 'text'],
  4131. 'stream' => false
  4132. ];
  4133. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4134. // 根据模型类型选择调用方法
  4135. $fullContent = '';
  4136. $usage = [];
  4137. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4138. // DeepSeek 官方模型使用 DeepSeek API
  4139. $chatResult = $this->chatOnly($post_data);
  4140. } else if (in_array($model, $this->gpt_text_models)) {
  4141. // GPT-5.4 模型使用 TokenRouter API
  4142. $chatResult = $this->gpt54ChatOnly($post_data);
  4143. } else {
  4144. // 其他模型使用火山引擎API
  4145. $chatResult = $this->volcEngineChatCompletion($post_data);
  4146. }
  4147. if (is_array($chatResult)) {
  4148. $fullContent = $chatResult['fullContent'];
  4149. $usage = $chatResult['usage'];
  4150. }
  4151. $script_arr = [];
  4152. // 处理结果
  4153. if ($fullContent) {
  4154. $script_arr = extractScriptContent($fullContent);
  4155. }
  4156. // 返回前保存剧本内容
  4157. DB::table('mp_scripts')->where('id', $script_id)->update([
  4158. 'content' => $content,
  4159. 'updated_at' => date('Y-m-d H:i:s')
  4160. ]);
  4161. // 仅记录 token 使用明细(不扣积分)
  4162. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  4163. 'model' => $model,
  4164. 'script_id' => $script_id,
  4165. 'source' => 'chatWithFile',
  4166. ], $model);
  4167. return [
  4168. 'script' => $script_arr,
  4169. 'answer' => $fullContent,
  4170. 'usage' => $usage
  4171. ];
  4172. }
  4173. public function getEpisodeContent($data) {
  4174. $group_id = getProp($data, 'group_id');
  4175. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  4176. }
  4177. public function saveEpisodeContent($data) {
  4178. $script_id = getProp($data, 'script_id');
  4179. $group_id = getProp($data, 'group_id');
  4180. $start_episode_sequence = getProp($data, 'start_episode_number');
  4181. $end_episode_sequence = getProp($data, 'end_episode_number');
  4182. // 检查是否存在重叠的剧集序号范围
  4183. $exists_groups = DB::table('mp_script_episode_group')
  4184. ->where('script_id', $script_id)
  4185. ->where('id', '<>', $group_id) // 排除当前组
  4186. ->where('is_deleted', 0)
  4187. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  4188. // 检查新范围是否与现有范围重叠
  4189. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4190. // 新范围的开始在现有范围内
  4191. $q->where('start_episode_number', '<=', $start_episode_sequence)
  4192. ->where('end_episode_number', '>=', $start_episode_sequence);
  4193. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4194. // 新范围的结束在现有范围内
  4195. $q->where('start_episode_number', '<=', $end_episode_sequence)
  4196. ->where('end_episode_number', '>=', $end_episode_sequence);
  4197. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  4198. // 新范围完全包含现有范围
  4199. $q->where('start_episode_number', '>=', $start_episode_sequence)
  4200. ->where('end_episode_number', '<=', $end_episode_sequence);
  4201. });
  4202. })
  4203. ->select('start_episode_number', 'end_episode_number')
  4204. ->get();
  4205. if ($exists_groups->isNotEmpty()) {
  4206. $conflict_ranges = [];
  4207. foreach ($exists_groups as $group) {
  4208. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  4209. }
  4210. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  4211. }
  4212. $episode_content = getProp($data, 'episode_content');
  4213. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  4214. 'content' => $episode_content,
  4215. 'start_episode_number' => $start_episode_sequence,
  4216. 'end_episode_number' => $end_episode_sequence,
  4217. 'updated_at' => date('Y-m-d H:i:s')
  4218. ]);
  4219. $script_arr =getProp($data, 'script', []);
  4220. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  4221. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  4222. $script_id = getProp($data, 'script_id');
  4223. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  4224. try {
  4225. DB::beginTransaction();
  4226. $update_data = [
  4227. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4228. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4229. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4230. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4231. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4232. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4233. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4234. 'status' => 3,
  4235. 'start_episode_sequence' => $start_episode_sequence,
  4236. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  4237. 'episode_num' => count($script_arr['episodes']),
  4238. 'updated_at' => date('Y-m-d H:i:s')
  4239. ];
  4240. // 保存剧本内容
  4241. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  4242. if (!$boolen) {
  4243. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  4244. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  4245. Utils::throwError('20003:剧本内容保存失败');
  4246. }
  4247. // 保存分集内容
  4248. // 删除历史分集内容
  4249. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  4250. $episodes = [];
  4251. $sequence = 1;
  4252. foreach ($script_arr['episodes'] as $episode) {
  4253. $segment_number = 1;
  4254. foreach($episode['segments'] as $segment) {
  4255. $episodes[] = [
  4256. 'script_id' => $script_id,
  4257. 'episode_number' => $episode['episode_number'],
  4258. 'title' => $episode['title'],
  4259. // 'content' => $episode['content'],
  4260. 'content' => '',
  4261. 'segment_number' => $segment_number,
  4262. 'segment_content' => $segment['segment_content'],
  4263. 'sequence' => $sequence,
  4264. 'created_at' => date('Y-m-d H:i:s'),
  4265. 'updated_at' => date('Y-m-d H:i:s')
  4266. ];
  4267. $sequence++;
  4268. $segment_number++;
  4269. }
  4270. }
  4271. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  4272. if (!$boolen2) {
  4273. dLog('deepseek')->info('分集内容保存失败', $episodes);
  4274. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  4275. Utils::throwError('20003:分集内容保存失败');
  4276. }
  4277. } catch (\Exception $e) {
  4278. DB::rollBack();
  4279. Utils::throwError('20003:'.$e->getMessage());
  4280. }
  4281. DB::commit();
  4282. return true;
  4283. }
  4284. public function getBookContent($data) {
  4285. $bid = getProp($data, 'bid');
  4286. $start_sequence = getProp($data, 'start_sequence');
  4287. $end_sequence = getProp($data, 'end_sequence');
  4288. $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])
  4289. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  4290. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  4291. return $return_content;
  4292. }
  4293. public function exportScript($data) {
  4294. $filename = getProp($data, 'filename');
  4295. $script_id = getProp($data, 'script_id');
  4296. $group_id = getProp($data, 'group_id');
  4297. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  4298. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  4299. if (!$script) Utils::throwError('20003:该剧本不存在!');
  4300. $script = (array)$script;
  4301. // 获取分集组信息
  4302. if ($group_id) {
  4303. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4304. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4305. ->get()->map(function($value) {
  4306. return (array)$value;
  4307. })->toArray();
  4308. }else {
  4309. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  4310. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  4311. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  4312. return (array)$value;
  4313. })->toArray();
  4314. }
  4315. if (!$groups) Utils::throwError('20003:分集不存在');
  4316. $script['group'] = $groups;
  4317. $export_type = getProp($data, 'export_type', 'txt');
  4318. // 生成文件名
  4319. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  4320. // 根据导出类型生成不同格式的文件
  4321. switch ($export_type) {
  4322. case 'txt':
  4323. return $this->exportScriptAsTxt($script, $filename);
  4324. case 'pdf':
  4325. return $this->exportScriptAsPdf($script, $filename);
  4326. default:
  4327. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  4328. }
  4329. }
  4330. /**
  4331. * 导出剧本为TXT格式
  4332. */
  4333. private function exportScriptAsTxt($script, $filename) {
  4334. // 构建TXT内容
  4335. $content = $this->buildScriptContent($script);
  4336. // 设置响应头,直接下载
  4337. header('Content-Type: text/plain; charset=utf-8');
  4338. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  4339. header('Content-Length: ' . strlen($content));
  4340. // 输出内容并结束
  4341. echo $content;
  4342. exit();
  4343. }
  4344. /**
  4345. * 导出剧本为PDF格式
  4346. */
  4347. private function exportScriptAsPdf($script, $filename) {
  4348. // 使用HTML转PDF的方式来更好地支持中文
  4349. $htmlContent = $this->buildScriptHtmlForPdf($script);
  4350. // 创建PDF实例
  4351. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  4352. // 设置文档信息
  4353. $pdf->SetCreator('剧本导出系统');
  4354. $pdf->SetAuthor('系统');
  4355. $pdf->SetTitle($script['script_name']);
  4356. $pdf->SetSubject('剧本导出');
  4357. // 设置边距
  4358. $pdf->SetMargins(15, 15, 15);
  4359. $pdf->SetAutoPageBreak(TRUE, 15);
  4360. // 添加页面
  4361. $pdf->AddPage();
  4362. // 注册并使用 simsun.ttf 字体
  4363. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  4364. // 使用HTML内容生成PDF
  4365. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  4366. // 直接输出PDF文件供下载
  4367. header('Content-Type: application/pdf');
  4368. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  4369. // 直接输出PDF内容
  4370. $pdf->Output($filename . '.pdf', 'D');
  4371. exit();
  4372. }
  4373. /**
  4374. * 构建用于PDF的HTML内容
  4375. */
  4376. private function buildScriptHtmlForPdf($script) {
  4377. $html = '<style>
  4378. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  4379. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  4380. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  4381. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  4382. .info { margin-bottom: 8px; }
  4383. .group { margin-bottom: 30px; page-break-inside: avoid; }
  4384. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  4385. .segment { margin-bottom: 10px; margin-left: 20px; }
  4386. .episode-content { white-space: pre-wrap; }
  4387. </style>';
  4388. // 标题
  4389. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  4390. // 处理分组数据
  4391. if (!empty($script['group']) && is_array($script['group'])) {
  4392. $groups = (array)$script['group'];
  4393. foreach ($groups as $group) {
  4394. $html .= '<div class="group">';
  4395. // 分组标题
  4396. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  4397. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  4398. // 故事梗概
  4399. if (!empty($group['intro'])) {
  4400. $html .= '<h3>故事梗概</h3>';
  4401. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  4402. }
  4403. // 剧本亮点
  4404. if (!empty($group['highlights'])) {
  4405. $html .= '<h3>剧本亮点</h3>';
  4406. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  4407. }
  4408. // 人物关系
  4409. if (!empty($group['role_relationship'])) {
  4410. $html .= '<h3>人物关系</h3>';
  4411. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  4412. }
  4413. // 核心矛盾
  4414. if (!empty($group['core_contradiction'])) {
  4415. $html .= '<h3>核心矛盾</h3>';
  4416. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  4417. }
  4418. // 主体列表
  4419. if (!empty($group['roles']) && is_array($group['roles'])) {
  4420. $html .= '<h3>主体列表</h3>';
  4421. $html .= '<ul>';
  4422. foreach ($group['roles'] as $role) {
  4423. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  4424. }
  4425. $html .= '</ul>';
  4426. }
  4427. // 美术风格
  4428. if (!empty($group['art_style'])) {
  4429. $html .= '<h3>美术风格</h3>';
  4430. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  4431. }
  4432. // 场景列表
  4433. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4434. $html .= '<h3>场景列表</h3>';
  4435. $html .= '<ul>';
  4436. foreach ($group['scenes'] as $scene) {
  4437. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  4438. }
  4439. $html .= '</ul>';
  4440. }
  4441. // 分集剧本
  4442. if (!empty($group['episode_content'])) {
  4443. $html .= '<h3>分集剧本</h3>';
  4444. // 去除零宽字符和其他不可见字符
  4445. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  4446. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  4447. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  4448. }
  4449. $html .= '</div>';
  4450. }
  4451. }
  4452. return $html;
  4453. }
  4454. /**
  4455. * 构建PDF内容
  4456. */
  4457. private function buildPdfContent($pdf, $script) {
  4458. // 标题
  4459. $pdf->SetFont('dejavusans', 'B', 18);
  4460. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  4461. $pdf->Ln(5);
  4462. // 基本信息
  4463. $pdf->SetFont('dejavusans', '', 12);
  4464. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  4465. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  4466. $pdf->Ln(5);
  4467. // 剧本简介
  4468. if (!empty($script['intro'])) {
  4469. $pdf->SetFont('dejavusans', 'B', 14);
  4470. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  4471. $pdf->SetFont('dejavusans', '', 12);
  4472. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  4473. $pdf->Ln(3);
  4474. }
  4475. // 亮点
  4476. if (!empty($script['highlights'])) {
  4477. $pdf->SetFont('dejavusans', 'B', 14);
  4478. $pdf->Cell(0, 10, '亮点', 0, 1);
  4479. $pdf->SetFont('dejavusans', '', 12);
  4480. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  4481. $pdf->Ln(3);
  4482. }
  4483. // 核心矛盾
  4484. if (!empty($script['core_contradiction'])) {
  4485. $pdf->SetFont('dejavusans', 'B', 14);
  4486. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  4487. $pdf->SetFont('dejavusans', '', 12);
  4488. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  4489. $pdf->Ln(3);
  4490. }
  4491. // 艺术风格
  4492. if (!empty($script['art_style'])) {
  4493. $pdf->SetFont('dejavusans', 'B', 14);
  4494. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  4495. $pdf->SetFont('dejavusans', '', 12);
  4496. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  4497. $pdf->Ln(3);
  4498. }
  4499. // 备注
  4500. if (!empty($script['remark'])) {
  4501. $pdf->SetFont('dejavusans', 'B', 14);
  4502. $pdf->Cell(0, 10, '备注', 0, 1);
  4503. $pdf->SetFont('dejavusans', '', 12);
  4504. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  4505. $pdf->Ln(3);
  4506. }
  4507. // 角色列表
  4508. if (!empty($script['roles']) && is_array($script['roles'])) {
  4509. $pdf->SetFont('dejavusans', 'B', 14);
  4510. $pdf->Cell(0, 10, '角色列表', 0, 1);
  4511. $pdf->SetFont('dejavusans', '', 12);
  4512. foreach ($script['roles'] as $index => $role) {
  4513. if (is_array($role) || is_object($role)) {
  4514. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  4515. } else {
  4516. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  4517. }
  4518. }
  4519. $pdf->Ln(3);
  4520. }
  4521. // 角色关系
  4522. if (!empty($script['role_relationship'])) {
  4523. $pdf->SetFont('dejavusans', 'B', 14);
  4524. $pdf->Cell(0, 10, '角色关系', 0, 1);
  4525. $pdf->SetFont('dejavusans', '', 12);
  4526. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  4527. $pdf->Ln(3);
  4528. }
  4529. // 场景列表
  4530. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  4531. $pdf->SetFont('dejavusans', 'B', 14);
  4532. $pdf->Cell(0, 10, '场景列表', 0, 1);
  4533. $pdf->SetFont('dejavusans', '', 12);
  4534. foreach ($script['scenes'] as $index => $scene) {
  4535. if (is_array($scene) || is_object($scene)) {
  4536. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  4537. } else {
  4538. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  4539. }
  4540. }
  4541. $pdf->Ln(5);
  4542. }
  4543. // 分集内容
  4544. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  4545. $pdf->SetFont('dejavusans', 'B', 16);
  4546. $pdf->Cell(0, 12, '分集内容', 0, 1);
  4547. $pdf->Ln(3);
  4548. foreach ($script['episodes'] as $episode) {
  4549. // 检查是否需要新页面
  4550. if ($pdf->GetY() > 250) {
  4551. $pdf->AddPage();
  4552. }
  4553. $pdf->SetFont('dejavusans', 'B', 14);
  4554. $episodeTitle = '第' . $episode['episode_number'] . '集';
  4555. if (!empty($episode['title'])) {
  4556. $episodeTitle .= ':' . $episode['title'];
  4557. }
  4558. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  4559. // 处理分段内容
  4560. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  4561. $pdf->SetFont('dejavusans', '', 12);
  4562. foreach ($episode['segments'] as $segment) {
  4563. if (!empty($segment['segment_content'])) {
  4564. // 如果有分段编号,显示分段标题
  4565. if (!empty($segment['segment_number'])) {
  4566. $pdf->SetFont('dejavusans', 'B', 12);
  4567. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  4568. $pdf->SetFont('dejavusans', '', 12);
  4569. }
  4570. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  4571. $pdf->Ln(2);
  4572. }
  4573. }
  4574. }
  4575. $pdf->Ln(5);
  4576. }
  4577. }
  4578. }
  4579. /**
  4580. * 构建剧本文本内容
  4581. */
  4582. private function buildScriptContent($script) {
  4583. $content = '';
  4584. $groups = $script['group'];
  4585. $groups = (array)$groups;
  4586. foreach ($groups as $group) {
  4587. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  4588. // 剧本基本信息
  4589. if (!empty($group['intro'])) {
  4590. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  4591. }
  4592. if (!empty($group['highlights'])) {
  4593. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  4594. }
  4595. if (!empty($group['role_relationship'])) {
  4596. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  4597. }
  4598. if (!empty($group['core_contradiction'])) {
  4599. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  4600. }
  4601. if (!empty($group['roles']) && is_array($group['roles'])) {
  4602. $content .= "###主体列表\n";
  4603. foreach ($group['roles'] as $role) {
  4604. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  4605. }
  4606. $content .= "\n\n";
  4607. }
  4608. if (!empty($group['art_style'])) {
  4609. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  4610. }
  4611. // 场景信息
  4612. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4613. $content .= "###场景列表\n";
  4614. foreach ($group['scenes'] as $scene) {
  4615. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  4616. }
  4617. $content .= "\n\n";
  4618. }
  4619. // 分集内容
  4620. if (!empty($group['episode_content'])) {
  4621. $content .= "###分集剧本\n";
  4622. $content .= $group['episode_content'];
  4623. // foreach ($script['episodes'] as $episode) {
  4624. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  4625. // // if (!empty($episode['episode_name'])) {
  4626. // // $content .= ":" . $episode['episode_name'];
  4627. // // }
  4628. // // $content .= "\n";
  4629. // $content .= $episode['episode_content'] . "\n\n";
  4630. // }
  4631. }
  4632. }
  4633. return $content;
  4634. }
  4635. /**
  4636. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4637. *
  4638. * @param array $data 包含以下参数:
  4639. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4640. * - question: 用户问题(可选)
  4641. * - model: 使用的模型(r1 或 v3,默认 v3)
  4642. * @return \Generator 返回生成器,用于流式输出
  4643. */
  4644. public function addChat($data) {
  4645. $uid = Site::getUid();
  4646. $anime_id = getProp($data, 'anime_id');
  4647. if (!$anime_id) Utils::throwError('20003:请选择对话');
  4648. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4649. if (!$anime) Utils::throwError('20003:对话不存在');
  4650. $file = getProp($data, 'file');
  4651. $content = getProp($data, 'content', '');
  4652. $bid = getProp($data, 'bid', 0);
  4653. $script_id = getProp($data, 'script_id', 0);
  4654. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  4655. $prompt = getProp($data, 'prompt');
  4656. $user_anime_name = getProp($anime, 'anime_name');
  4657. // 处理文本模型
  4658. $model = getProp($data, 'model');
  4659. if (!$model) {
  4660. // 用户没有输入,从anime表获取
  4661. $model = getProp($anime, 'model');
  4662. if (!$model) {
  4663. // anime表也没有,使用默认值
  4664. $model = 'doubao-seed-2-0-mini-260215';
  4665. }
  4666. }
  4667. // 验证模型是否在可用模型表中
  4668. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4669. $model = 'doubao-seed-2-0-mini-260215';
  4670. }
  4671. $is_multi = getProp($anime, 'is_multi');
  4672. $is_single = (int)$is_multi !== 1;
  4673. // 积分余额预检(仅单剧集模式收费)
  4674. if ($is_single) {
  4675. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  4676. }
  4677. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4678. if ($prompt) {
  4679. $question .= "本次修改要求如下:\n{$prompt}";
  4680. }
  4681. // if (!$file && !$content && !$bid) {
  4682. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4683. // }
  4684. // 提取文件内容
  4685. if ($file) {
  4686. $content = $this->extractFileContent($file);
  4687. if (!$content) {
  4688. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4689. }
  4690. } elseif ($script_id) {
  4691. $content = $this->getContentByScriptId($script_id);
  4692. if (!$content) {
  4693. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4694. }
  4695. } elseif ($bid) {
  4696. $content = $this->getContentByBid($bid);
  4697. if (!$content) {
  4698. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4699. }
  4700. } elseif ($content) {
  4701. $content = filterContent($content);
  4702. } else {
  4703. $content = getProp($anime, 'content');
  4704. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4705. $need_generate_content = true;
  4706. }
  4707. }
  4708. // 美术风格
  4709. $input_art_style = getProp($data, 'art_style');
  4710. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4711. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4712. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4713. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4714. 中年女:邻居阿姨
  4715. 老年男:幽默大爷
  4716. 老年女:婆婆
  4717. 萌娃:奶气萌娃";
  4718. // 判断是否需要生成原文内容
  4719. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4720. // 如果需要生成原文内容,添加额外的要求
  4721. $content_generation_requirement = $need_generate_content
  4722. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4723. : "";
  4724. // 美术风格
  4725. if (!$mappedArtStyle) {
  4726. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4727. }else {
  4728. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4729. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4730. }else {
  4731. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4732. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4733. }
  4734. }
  4735. $systemPrompt = $is_single
  4736. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4737. 强制要求:
  4738. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4739. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4740. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4741. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4742. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4743. 普通要求:
  4744. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4745. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4746. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  4747. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4748. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4749. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4750. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4751. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4752. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4753. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4754. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4755. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4756. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4757. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4758. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4759. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4760. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4761. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4762. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4763. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4764. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4765. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4766. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4767. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4768. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4769. 5.{$mappedArtStyle_prompt}\n\n
  4770. 示例如下:\n
  4771. ###剧本名:西昆仑
  4772. ###故事梗概
  4773. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4774. ###剧本亮点
  4775. 亮点1:绝境奇药,生死一线
  4776. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4777. 亮点2:结拜兄妹,化解尴尬
  4778. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4779. 亮点3:纤发夺命,情愫暗涌
  4780. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4781. ###人物关系
  4782. 阿雪与梁萧之间存在兄妹之情。
  4783. ###核心矛盾
  4784. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4785. ###主体列表
  4786. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4787. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4788. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4789. 姿态:站立。}{{甜心小美}}
  4790. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4791. 全景,正面拍摄,青年女性,亚洲人。
  4792. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4793. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4794. 姿态:站立。}{{阳光青年}}
  4795. ###美术风格
  4796. 基础画风风格词:厚涂古风
  4797. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4798. ###场景列表
  4799. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4800. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4801. 无人物。}
  4802. ###分镜剧本
  4803. ##第1幕:徐家老旧厨房 白天 室内
  4804. 分镜1
  4805. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4806. 场景:徐家老旧厨房
  4807. 构图设计:全景,低角度仰视
  4808. 运镜调度:手持拍摄
  4809. 配音角色:旁白
  4810. 出镜角色:许芸-校服装、徐母
  4811. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4812. 画面类型:普通画面
  4813. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4814. 分镜2
  4815. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4816. 场景:徐家老旧厨房
  4817. 构图设计:近景,徐母面部特写
  4818. 运镜调度:固定镜头
  4819. 配音角色:徐母
  4820. 出镜角色:徐母
  4821. 台词内容:问我夜不归宿死哪儿去了。
  4822. 画面类型:对口型
  4823. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4824. ##第2幕:徐家简陋客厅 黄昏 室内
  4825. 分镜3
  4826. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4827. 场景:徐家简陋客厅
  4828. 构图设计:全景,景深虚化
  4829. 运镜调度:固定镜头
  4830. 配音角色:旁白
  4831. 出镜角色:无
  4832. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4833. 画面类型:普通画面
  4834. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4835. 分镜4
  4836. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4837. 场景:徐家简陋客厅
  4838. 构图设计:特写,火车票
  4839. 运镜调度:固定镜头
  4840. 配音角色:旁白
  4841. 出镜角色:无
  4842. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4843. 画面类型:普通画面
  4844. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4845. "
  4846. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4847. 强制要求:\n
  4848. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4849. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4850. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4851. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4852. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4853. 普通要求:\n
  4854. 1.剧本名(必须生成)必须与文档内容高度相关
  4855. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4856. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4857. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4858. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4859. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4860. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4861. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4862. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4863. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4864. 4.{$mappedArtStyle_prompt}\n\n
  4865. 示例如下:\n
  4866. ###剧本名:西昆仑
  4867. ###故事梗概
  4868. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4869. ###剧本亮点
  4870. 亮点1:绝境奇药,生死一线
  4871. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4872. 亮点2:结拜兄妹,化解尴尬
  4873. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4874. 亮点3:纤发夺命,情愫暗涌
  4875. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4876. ###人物关系
  4877. 阿雪与梁萧之间存在兄妹之情。
  4878. ###核心矛盾
  4879. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4880. ###主体列表
  4881. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4882. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4883. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4884. 姿态:站立。}{{甜心小美}}
  4885. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4886. 全景,正面拍摄,青年女性,亚洲人。
  4887. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4888. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4889. 姿态:站立。}{{阳光青年}}
  4890. ###美术风格
  4891. 基础画风风格词:厚涂古风
  4892. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4893. ###场景列表
  4894. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4895. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4896. 无人物。}";
  4897. // 构建消息
  4898. $messages = [
  4899. [
  4900. 'role' => 'system',
  4901. 'content' => $systemPrompt
  4902. ],
  4903. [
  4904. 'role' => 'user',
  4905. 'content' => "以下是文档内容:
  4906. {$content}
  4907. 用户问题:
  4908. {$question}"
  4909. ]
  4910. ];
  4911. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4912. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4913. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4914. if ($model === 'deepseek-chat') {
  4915. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4916. $model = 'deepseek-v4-flash';
  4917. $thinkingMode = 'disabled';
  4918. } elseif ($model === 'deepseek-reasoner') {
  4919. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4920. $model = 'deepseek-v4-flash';
  4921. $thinkingMode = 'enabled';
  4922. }
  4923. $post_data = [
  4924. 'model' => $model,
  4925. 'messages' => $messages,
  4926. // 'max_tokens' => 8192,
  4927. 'temperature' => 0.7,
  4928. 'frequency_penalty' => 0,
  4929. 'presence_penalty' => 0,
  4930. 'response_format' => ['type' => 'text'],
  4931. 'thinking' => ['type'=>$thinkingMode],
  4932. 'stream' => true // 启用流式输出
  4933. ];
  4934. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4935. // 根据模型类型选择调用方法
  4936. $fullContent = '';
  4937. $fullReasoningContent = '';
  4938. $usage = [];
  4939. try {
  4940. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4941. // DeepSeek 官方模型使用 DeepSeek API
  4942. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4943. } else if (in_array($model, $this->gpt_text_models)) {
  4944. // GPT-5.4 模型使用 TokenRouter API
  4945. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4946. } else if (in_array($model, $this->gemini_text_models)) {
  4947. // Gemini 模型使用 Gemini API
  4948. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4949. } else {
  4950. // 其他模型使用火山引擎API
  4951. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4952. }
  4953. // 验证返回值类型
  4954. if (!is_iterable($streamGenerator)) {
  4955. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4956. dLog('deepseek')->error('addChat流式生成器无效', [
  4957. 'generator_type' => $errorType,
  4958. 'model' => $model,
  4959. 'anime_id' => $anime_id
  4960. ]);
  4961. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  4962. 'type' => $errorType,
  4963. 'model' => $model
  4964. ]);
  4965. yield [
  4966. 'type' => 'error',
  4967. 'script' => [],
  4968. 'episode' => [],
  4969. 'answer' => '',
  4970. 'reasoning' => '',
  4971. 'usage' => [],
  4972. 'error' => '接口返回数据异常,请重新请求'
  4973. ];
  4974. return;
  4975. }
  4976. // 处理流式输出
  4977. foreach ($streamGenerator as $chunk) {
  4978. if (isset($chunk['type'])) {
  4979. if ($chunk['type'] === 'done') {
  4980. // 最终结果
  4981. $fullContent = $chunk['full_content'];
  4982. $fullReasoningContent = $chunk['full_reasoning'];
  4983. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4984. } else {
  4985. // 逐块yield数据
  4986. yield $chunk;
  4987. }
  4988. }
  4989. }
  4990. } catch (\Exception $e) {
  4991. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  4992. 'model' => $model,
  4993. 'anime_id' => $anime_id,
  4994. 'trace' => $e->getTraceAsString()
  4995. ]);
  4996. logDB('deepseek', 'error', 'addChat流式处理失败', [
  4997. 'error' => $e->getMessage(),
  4998. 'model' => $model
  4999. ]);
  5000. yield [
  5001. 'type' => 'error',
  5002. 'script' => [],
  5003. 'episode' => [],
  5004. 'answer' => '',
  5005. 'reasoning' => '',
  5006. 'usage' => [],
  5007. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5008. ];
  5009. return;
  5010. }
  5011. dLog('deepseek')->info('完整内容: '.$fullContent);
  5012. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5013. // 处理完整内容并返回最终结果
  5014. $script_arr = [];
  5015. if ($fullContent) {
  5016. $script_arr = handleScriptContent($fullContent);
  5017. dLog('deepseek')->info('解析内容', $script_arr);
  5018. logDB('deepseek', 'info', '解析内容', $script_arr);
  5019. }
  5020. if (empty($script_arr['roles'])) {
  5021. // 未生成剧本相关内容,保存对话记录并返回提示
  5022. dLog('deepseek')->info('未生成剧本相关的内容');
  5023. try {
  5024. DB::beginTransaction();
  5025. $now = date('Y-m-d H:i:s');
  5026. // 保存对话记录
  5027. $records = [
  5028. [
  5029. 'uid' => $uid,
  5030. 'anime_id' => $anime_id,
  5031. 'sequence' => 0,
  5032. 'role' => 'user',
  5033. 'content' => $prompt,
  5034. 'created_at' => $now,
  5035. 'updated_at' => $now
  5036. ],
  5037. [
  5038. 'uid' => $uid,
  5039. 'anime_id' => $anime_id,
  5040. 'sequence' => 0,
  5041. 'role' => 'assistant',
  5042. // 'content' => $fullContent,
  5043. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5044. 'created_at' => $now,
  5045. 'updated_at' => $now
  5046. ]
  5047. ];
  5048. DB::table('mp_anime_records')->insert($records);
  5049. DB::commit();
  5050. } catch (\Exception $e) {
  5051. DB::rollBack();
  5052. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5053. }
  5054. yield [
  5055. 'type' => 'done',
  5056. 'script' => [],
  5057. 'episode' => [],
  5058. 'answer' => $fullContent,
  5059. 'reasoning' => $fullReasoningContent,
  5060. 'usage' => $usage,
  5061. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5062. ];
  5063. return;
  5064. }
  5065. // 如果需要生成原文内容,从script_arr中提取
  5066. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5067. $content = $script_arr['content'];
  5068. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5069. if (!$content) {
  5070. yield [
  5071. 'type' => 'done',
  5072. 'script' => [],
  5073. 'episode' => [],
  5074. 'answer' => $fullContent,
  5075. 'reasoning' => $fullReasoningContent,
  5076. 'usage' => $usage,
  5077. 'error' => '未生成剧本内容,请调整提示词再试'
  5078. ];
  5079. return;
  5080. }
  5081. }
  5082. // 替换美术风格
  5083. if ($mappedArtStyle !== '') {
  5084. $script_arr['art_style'] = $mappedArtStyle;
  5085. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5086. }
  5087. // 新建动漫
  5088. if ($user_anime_name == '新剧本策划') {
  5089. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5090. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5091. // if (!$anime_name) {
  5092. // // 未识别到剧本名,保存对话记录并返回提示
  5093. // dLog('deepseek')->info('未能识别到剧本名称');
  5094. // try {
  5095. // DB::beginTransaction();
  5096. // $now = date('Y-m-d H:i:s');
  5097. // // 保存对话记录
  5098. // $records = [
  5099. // [
  5100. // 'uid' => $uid,
  5101. // 'anime_id' => $anime_id,
  5102. // 'sequence' => 0,
  5103. // 'role' => 'user',
  5104. // 'content' => $prompt,
  5105. // 'created_at' => $now,
  5106. // 'updated_at' => $now
  5107. // ],
  5108. // [
  5109. // 'uid' => $uid,
  5110. // 'anime_id' => $anime_id,
  5111. // 'sequence' => 0,
  5112. // 'role' => 'assistant',
  5113. // 'content' => '未能生成剧本名称,请重试',
  5114. // 'created_at' => $now,
  5115. // 'updated_at' => $now
  5116. // ]
  5117. // ];
  5118. // DB::table('mp_anime_records')->insert($records);
  5119. // DB::commit();
  5120. // } catch (\Exception $e) {
  5121. // DB::rollBack();
  5122. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5123. // }
  5124. // yield [
  5125. // 'type' => 'done',
  5126. // 'script' => [],
  5127. // 'episode' => [],
  5128. // 'answer' => $fullContent,
  5129. // 'reasoning' => $fullReasoningContent,
  5130. // 'usage' => $usage,
  5131. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  5132. // ];
  5133. // return;
  5134. // }
  5135. // 确认对话名称唯一性
  5136. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5137. $anime_name = $anime_name . '_' . date('YmdHis');
  5138. }
  5139. }else {
  5140. $anime_name = $user_anime_name;
  5141. }
  5142. $table_data = [
  5143. 'user_id' => $uid,
  5144. 'anime_name' => $anime_name,
  5145. 'model' => $model,
  5146. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5147. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5148. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5149. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5150. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5151. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5152. 'art_style_type' => $input_art_style,
  5153. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5154. 'status' => '解析完成',
  5155. 'content' => $content,
  5156. 'is_multi' => $is_multi,
  5157. 'ace_mode' => $ace_mode,
  5158. 'generate_status' => '待执行',
  5159. 'updated_at' => date('Y-m-d H:i:s')
  5160. ];
  5161. if ($table_data['content']) {
  5162. $chapters = splitContent($table_data['content']);
  5163. $chapter_count = count($chapters);
  5164. if ($chapter_count > 0) {
  5165. $table_data['start_episode_sequence'] = 1;
  5166. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5167. }
  5168. }
  5169. // 如果有剧本ID则进行绑定
  5170. if ($script_id) {
  5171. $table_data['script_id'] = $script_id;
  5172. }
  5173. $single_episode = [];
  5174. try {
  5175. DB::beginTransaction();
  5176. $now = date('Y-m-d H:i:s');
  5177. // 更新动漫大纲
  5178. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5179. if (!$boolen) {
  5180. dLog('deepseek')->info('动漫保存失败', $table_data);
  5181. Utils::throwError('20003:动漫保存失败');
  5182. }
  5183. // 保存对话记录
  5184. $records = [
  5185. [
  5186. 'uid' => $uid,
  5187. 'anime_id' => $anime_id,
  5188. 'sequence' => 0,
  5189. 'role' => 'user',
  5190. 'content' => $prompt,
  5191. 'created_at' => date('Y-m-d H:i:s'),
  5192. 'updated_at' => date('Y-m-d H:i:s')
  5193. ],
  5194. [
  5195. 'uid' => $uid,
  5196. 'anime_id' => $anime_id,
  5197. 'sequence' => 0,
  5198. 'role' => 'assistant',
  5199. 'content' => $fullContent,
  5200. 'created_at' => date('Y-m-d H:i:s'),
  5201. 'updated_at' => date('Y-m-d H:i:s')
  5202. ]
  5203. ];
  5204. // 保存对话记录
  5205. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5206. if (!$boolen3) {
  5207. Utils::throwError('20003:对话记录保存失败');
  5208. }
  5209. if ($is_single) {
  5210. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5211. if (empty($episode_arr['acts'])) {
  5212. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5213. }
  5214. $saveResult = $this->saveEpisodeVersionData(
  5215. $anime_id,
  5216. 1,
  5217. $episode_arr,
  5218. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5219. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5220. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5221. null,
  5222. null,
  5223. false,
  5224. $content,
  5225. $now
  5226. );
  5227. $single_episode = $saveResult['episode'];
  5228. $episode_id = $saveResult['episode_id'];
  5229. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5230. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5231. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5232. 'props' => json_encode($saveResult['merged_props'], 256),
  5233. 'updated_at' => $now
  5234. ]);
  5235. if ($boolen5 === false) {
  5236. Utils::throwError('20003:单剧集主表资源同步失败');
  5237. }
  5238. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5239. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5240. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5241. $episode_record_content = '确认分镜大纲';
  5242. if ($content !== '') {
  5243. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5244. }
  5245. $episode_records = [
  5246. [
  5247. 'uid' => $uid,
  5248. 'anime_id' => $anime_id,
  5249. 'role' => 'user',
  5250. 'content' => $episode_record_content,
  5251. 'sequence' => 1,
  5252. 'episode_id' => $episode_id,
  5253. 'created_at' => $now,
  5254. 'updated_at' => $now
  5255. ],
  5256. [
  5257. 'uid' => $uid,
  5258. 'anime_id' => $anime_id,
  5259. 'role' => 'assistant',
  5260. 'content' => $fullContent,
  5261. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5262. 'sequence' => 1,
  5263. 'episode_id' => $episode_id,
  5264. 'created_at' => $now,
  5265. 'updated_at' => $now
  5266. ]
  5267. ];
  5268. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5269. if (!$boolen4) {
  5270. Utils::throwError('20003:单剧集分镜记录保存失败');
  5271. }
  5272. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  5273. if ($is_single && !empty($single_episode)) {
  5274. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  5275. 'anime_id' => $anime_id,
  5276. 'episode_id' => $episode_id ?? 0,
  5277. 'model' => $model,
  5278. 'source' => 'addChat',
  5279. ]);
  5280. }
  5281. }
  5282. }catch (\Exception $e) {
  5283. DB::rollBack();
  5284. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5285. yield [
  5286. 'type' => 'done',
  5287. 'answer' => $fullContent,
  5288. 'reasoning' => $fullReasoningContent,
  5289. 'usage' => $usage,
  5290. 'error' => $e->getMessage(),
  5291. ];
  5292. return;
  5293. }
  5294. DB::commit();
  5295. dLog('deepseek')->info('保存完毕');
  5296. if ($is_single && !empty($single_episode)) {
  5297. // $this->batchSetGlobalRoleImg([
  5298. // 'anime_id' => $anime_id,
  5299. // ]);
  5300. // $this->batchSetGlobalSceneImg([
  5301. // 'anime_id' => $anime_id,
  5302. // ]);
  5303. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5304. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5305. }
  5306. $table_data['anime_id'] = $anime_id;
  5307. $table_data['roles'] = json_decode($table_data['roles'], true);
  5308. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5309. // $table_data['episodes'] = $script_arr['episodes'];
  5310. unset($table_data['created_at']);
  5311. unset($table_data['updated_at']);
  5312. unset($table_data['status']);
  5313. dLog('deepseek')->info('开始返回');
  5314. yield [
  5315. 'type' => 'done',
  5316. 'script' => $table_data,
  5317. 'episode' => $single_episode,
  5318. 'answer' => $fullContent,
  5319. 'reasoning' => $fullReasoningContent,
  5320. 'usage' => $usage
  5321. ];
  5322. }
  5323. public function reGenerateAnime($data) {
  5324. $uid = Site::getUid();
  5325. $file = getProp($data, 'file');
  5326. $content = getProp($data, 'content', '');
  5327. $bid = getProp($data, 'bid', 0);
  5328. $script_id = getProp($data, 'script_id', 0);
  5329. $anime_id = getProp($data, 'anime_id');
  5330. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5331. if (!$anime) {
  5332. Utils::throwError('20003:该对话不存在');
  5333. }
  5334. $user_anime_name = getProp($anime, 'anime_name');
  5335. $prompt = getProp($data, 'prompt');
  5336. // 处理文本模型
  5337. $model = getProp($data, 'model');
  5338. if (!$model) {
  5339. // 用户没有输入,从anime表获取
  5340. $model = getProp($anime, 'model');
  5341. if (!$model) {
  5342. // anime表也没有,使用默认值
  5343. $model = 'doubao-seed-2-0-mini-260215';
  5344. }
  5345. }
  5346. // 验证模型是否在可用模型表中
  5347. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5348. $model = 'doubao-seed-2-0-mini-260215';
  5349. }
  5350. $is_multi = getProp($anime, 'is_multi', 1);
  5351. $is_single = (int)$is_multi !== 1;
  5352. // 积分余额预检(仅单剧集模式收费)
  5353. if ($is_single) {
  5354. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  5355. }
  5356. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  5357. if ($is_single) {
  5358. $episode_exists = DB::table('mp_anime_episodes')
  5359. ->where('anime_id', $anime_id)
  5360. ->where('sequence', 1)
  5361. ->exists();
  5362. if ($episode_exists) {
  5363. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  5364. }
  5365. }
  5366. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  5367. if ($prompt) {
  5368. $question .= "本次修改要求如下:\n{$prompt}";
  5369. }
  5370. // 提取文件内容
  5371. if ($file) {
  5372. $content = $this->extractFileContent($file);
  5373. if (!$content) {
  5374. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5375. }
  5376. } elseif ($script_id) {
  5377. $content = $this->getContentByScriptId($script_id);
  5378. if (!$content) {
  5379. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5380. }
  5381. } elseif ($bid) {
  5382. $content = $this->getContentByBid($bid);
  5383. if (!$content) {
  5384. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5385. }
  5386. } elseif ($content) {
  5387. $content = filterContent($content);
  5388. }else {
  5389. $content = filterContent(getProp($anime, 'content'));
  5390. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5391. $need_generate_content = true;
  5392. }
  5393. }
  5394. // 判断是否需要生成原文内容
  5395. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5396. // 如果需要生成原文内容,添加额外的要求
  5397. $content_generation_requirement = $need_generate_content
  5398. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5399. : "";
  5400. // 美术风格
  5401. $input_art_style = getProp($anime, 'art_style');
  5402. if (!$input_art_style) {
  5403. $input_art_style = getProp($data, 'art_style');
  5404. }
  5405. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5406. // 美术风格
  5407. if (!$mappedArtStyle) {
  5408. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5409. }else {
  5410. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5411. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5412. }else {
  5413. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5414. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5415. }
  5416. }
  5417. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5418. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5419. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5420. 中年女:邻居阿姨
  5421. 老年男:幽默大爷
  5422. 老年女:婆婆
  5423. 萌娃:奶气萌娃";
  5424. $system_message = ['role'=>'system', 'content'=>$is_single
  5425. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5426. 强制要求:
  5427. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5428. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5429. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5430. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5431. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5432. 普通要求:
  5433. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5434. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5435. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5436. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5437. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5438. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5439. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5440. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5441. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5442. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5443. 3.$mappedArtStyle_prompt\n\n
  5444. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5445. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5446. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5447. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5448. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  5449. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5450. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5451. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5452. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5453. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5454. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5455. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5456. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5457. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5458. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  5459. 示例如下:\n
  5460. ###剧本名:西昆仑
  5461. ###故事梗概
  5462. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5463. ###剧本亮点
  5464. 亮点1:绝境奇药,生死一线
  5465. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5466. 亮点2:结拜兄妹,化解尴尬
  5467. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5468. 亮点3:纤发夺命,情愫暗涌
  5469. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5470. ###人物关系
  5471. 阿雪与梁萧之间存在兄妹之情。
  5472. ###核心矛盾
  5473. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5474. ###主体列表
  5475. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5476. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5477. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5478. 姿态:站立。}{{甜心小美}}
  5479. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5480. 全景,正面拍摄,青年女性,亚洲人。
  5481. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5482. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5483. 姿态:站立。}{{阳光青年}}
  5484. ###美术风格
  5485. 基础画风风格词:厚涂古风
  5486. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5487. ###场景列表
  5488. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5489. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5490. 无人物。}
  5491. ###分镜剧本
  5492. ##第1幕:徐家老旧厨房 白天 室内
  5493. 分镜1
  5494. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5495. 场景:徐家老旧厨房
  5496. 构图设计:全景,低角度仰视
  5497. 运镜调度:手持拍摄
  5498. 配音角色:旁白
  5499. 出镜角色:许芸-校服装、徐母
  5500. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5501. 画面类型:普通画面
  5502. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5503. 分镜2
  5504. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5505. 场景:徐家老旧厨房
  5506. 构图设计:近景,徐母面部特写
  5507. 运镜调度:固定镜头
  5508. 配音角色:徐母
  5509. 出镜角色:徐母
  5510. 台词内容:问我夜不归宿死哪儿去了。
  5511. 画面类型:对口型
  5512. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5513. ##第2幕:徐家简陋客厅 黄昏 室内
  5514. 分镜3
  5515. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5516. 场景:徐家简陋客厅
  5517. 构图设计:全景,景深虚化
  5518. 运镜调度:固定镜头
  5519. 配音角色:旁白
  5520. 出镜角色:无
  5521. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5522. 画面类型:普通画面
  5523. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5524. 分镜4
  5525. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5526. 场景:徐家简陋客厅
  5527. 构图设计:特写,火车票
  5528. 运镜调度:固定镜头
  5529. 配音角色:旁白
  5530. 出镜角色:无
  5531. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5532. 画面类型:普通画面
  5533. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5534. "
  5535. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5536. 强制要求:\n
  5537. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5538. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5539. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5540. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5541. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5542. 普通要求:\n
  5543. 1.剧本名(必须生成)必须与文档内容高度相关
  5544. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5545. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5546. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5547. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5548. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5549. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5550. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5551. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5552. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5553. 4.$mappedArtStyle_prompt\n\n
  5554. 示例如下:\n
  5555. ###剧本名:西昆仑
  5556. ###故事梗概
  5557. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5558. ###剧本亮点
  5559. 亮点1:绝境奇药,生死一线
  5560. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5561. 亮点2:结拜兄妹,化解尴尬
  5562. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5563. 亮点3:纤发夺命,情愫暗涌
  5564. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5565. ###人物关系
  5566. 阿雪与梁萧之间存在兄妹之情。
  5567. ###核心矛盾
  5568. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5569. ###主体列表
  5570. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5571. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5572. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5573. 姿态:站立。}{{甜心小美}}
  5574. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5575. 全景,正面拍摄,青年女性,亚洲人。
  5576. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5577. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5578. 姿态:站立。}{{阳光青年}}
  5579. ###美术风格
  5580. 基础画风风格词:厚涂古风
  5581. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5582. ###场景列表
  5583. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5584. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5585. 无人物。}"];
  5586. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  5587. $episode_count = $this->extractEpisodeNumber($prompt);
  5588. if ((int)getProp($anime, 'is_multi') !== 1) {
  5589. yield [
  5590. 'type' => 'done',
  5591. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  5592. 'reasoning' => '',
  5593. 'usage' => []
  5594. ];
  5595. return;
  5596. }
  5597. if ($episode_count) {
  5598. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  5599. $system_message = [
  5600. 'role' => 'system',
  5601. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5602. 强制要求:\n
  5603. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5604. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5605. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5606. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5607. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5608. 普通要求:\n
  5609. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5610. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5611. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5612. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5613. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5614. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5615. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5616. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5617. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5618. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  5619. 示例如下:\n
  5620. ###剧本名:西昆仑
  5621. ###故事梗概
  5622. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5623. ###剧本亮点
  5624. 亮点1:绝境奇药,生死一线
  5625. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5626. 亮点2:结拜兄妹,化解尴尬
  5627. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5628. 亮点3:纤发夺命,情愫暗涌
  5629. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5630. ###人物关系
  5631. 阿雪与梁萧之间存在兄妹之情。
  5632. ###核心矛盾
  5633. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5634. ###主体列表
  5635. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5636. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5637. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5638. 姿态:站立。}{{甜心小美}}
  5639. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5640. 全景,正面拍摄,青年女性,亚洲人。
  5641. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5642. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5643. 姿态:站立。}{{阳光青年}}
  5644. ###美术风格
  5645. 基础画风风格词:厚涂古风
  5646. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5647. ###场景列表
  5648. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5649. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5650. 无人物。}
  5651. ###分集详细内容
  5652. ##第1章 重生
  5653. 我重生了。
  5654. 源于一个男人偏执的暗恋。
  5655. ##第2章 相救
  5656. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  5657. 我眼睛扫向站在锅炉后的卞大伟。"
  5658. ];
  5659. // 构建消息
  5660. $messages = [
  5661. $system_message,
  5662. [
  5663. 'role' => 'user',
  5664. 'content' => "以下是文档内容:
  5665. {$content}
  5666. 用户问题:
  5667. {$question}"
  5668. ]
  5669. ];
  5670. }else {
  5671. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  5672. // 构建消息
  5673. $messages = [
  5674. $system_message,
  5675. [
  5676. 'role' => 'user',
  5677. 'content' => "以下是文档内容:
  5678. {$content}
  5679. 用户问题:
  5680. {$question}"
  5681. ]
  5682. ];
  5683. }else {
  5684. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  5685. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  5686. return (array)$value;
  5687. })->toArray();
  5688. array_unshift($messages, $system_message);
  5689. $messages[] = [
  5690. 'role' => 'user',
  5691. 'content' => $prompt
  5692. ];
  5693. }
  5694. }
  5695. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5696. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5697. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5698. if ($model === 'deepseek-chat') {
  5699. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5700. $model = 'deepseek-v4-flash';
  5701. $thinkingMode = 'disabled';
  5702. } elseif ($model === 'deepseek-reasoner') {
  5703. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5704. $model = 'deepseek-v4-flash';
  5705. $thinkingMode = 'enabled';
  5706. }
  5707. $post_data = [
  5708. 'model' => $model,
  5709. 'messages' => $messages,
  5710. // 'max_tokens' => 8192,
  5711. 'temperature' => 0.7,
  5712. 'frequency_penalty' => 0,
  5713. 'presence_penalty' => 0,
  5714. 'response_format' => ['type' => 'text'],
  5715. 'thinking' => ['type' => $thinkingMode],
  5716. 'stream' => true // 启用流式输出
  5717. ];
  5718. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5719. // 根据模型类型选择调用方法
  5720. $fullContent = '';
  5721. $fullReasoningContent = '';
  5722. $usage = [];
  5723. // dd($post_data);
  5724. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  5725. try {
  5726. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5727. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5728. } else if (in_array($model, $this->gpt_text_models)) {
  5729. // GPT-5.4 模型使用 TokenRouter API
  5730. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5731. } else if (in_array($model, $this->gemini_text_models)) {
  5732. // Gemini 模型使用 Gemini API
  5733. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  5734. } else {
  5735. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5736. }
  5737. // 验证返回值类型
  5738. if (!is_iterable($streamGenerator)) {
  5739. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5740. dLog('deepseek')->error('方法名流式生成器无效', [
  5741. 'generator_type' => $errorType,
  5742. 'model' => $model,
  5743. // 添加其他上下文信息
  5744. ]);
  5745. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  5746. 'type' => $errorType,
  5747. 'model' => $model
  5748. ]);
  5749. yield [
  5750. 'type' => 'error',
  5751. // 根据方法返回相应的空数据结构
  5752. 'answer' => '',
  5753. 'reasoning' => '',
  5754. 'usage' => [],
  5755. 'error' => '接口返回数据异常,请重新请求'
  5756. ];
  5757. return;
  5758. }
  5759. // 处理流式输出
  5760. foreach ($streamGenerator as $chunk) {
  5761. if (isset($chunk['type'])) {
  5762. if ($chunk['type'] === 'done') {
  5763. $fullContent = $chunk['full_content'];
  5764. $fullReasoningContent = $chunk['full_reasoning'];
  5765. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5766. } else {
  5767. yield $chunk;
  5768. }
  5769. }
  5770. }
  5771. } catch (\Exception $e) {
  5772. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  5773. 'model' => $model,
  5774. 'trace' => $e->getTraceAsString()
  5775. ]);
  5776. logDB('deepseek', 'error', '方法名流式处理失败', [
  5777. 'error' => $e->getMessage(),
  5778. 'model' => $model
  5779. ]);
  5780. yield [
  5781. 'type' => 'error',
  5782. // 根据方法返回相应的空数据结构
  5783. 'answer' => '',
  5784. 'reasoning' => '',
  5785. 'usage' => [],
  5786. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5787. ];
  5788. return;
  5789. }
  5790. dLog('deepseek')->info('完整内容: '.$fullContent);
  5791. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5792. // 处理完整内容并返回最终结果
  5793. $script_arr = [];
  5794. if ($fullContent) {
  5795. $script_arr = handleScriptContent($fullContent);
  5796. dLog('deepseek')->info('解析内容', $script_arr);
  5797. logDB('deepseek', 'info', '解析内容', $script_arr);
  5798. }
  5799. if (empty($script_arr['roles'])) {
  5800. // 未生成剧本相关内容,保存对话记录并返回提示
  5801. dLog('deepseek')->info('未生成剧本相关的内容');
  5802. try {
  5803. $now = date('Y-m-d H:i:s');
  5804. // 保存对话记录
  5805. $records = [
  5806. [
  5807. 'uid' => $uid,
  5808. 'anime_id' => $anime_id,
  5809. 'sequence' => 0,
  5810. 'role' => 'user',
  5811. 'content' => $prompt,
  5812. 'created_at' => $now,
  5813. 'updated_at' => $now
  5814. ],
  5815. [
  5816. 'uid' => $uid,
  5817. 'anime_id' => $anime_id,
  5818. 'sequence' => 0,
  5819. 'role' => 'assistant',
  5820. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  5821. 'created_at' => $now,
  5822. 'updated_at' => $now
  5823. ]
  5824. ];
  5825. DB::table('mp_anime_records')->insert($records);
  5826. } catch (\Exception $e) {
  5827. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5828. }
  5829. yield [
  5830. 'type' => 'done',
  5831. 'script' => [],
  5832. 'episode' => [],
  5833. 'answer' => $fullContent,
  5834. 'reasoning' => $fullReasoningContent,
  5835. 'usage' => $usage,
  5836. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5837. ];
  5838. return;
  5839. }
  5840. // 替换美术风格
  5841. if ($mappedArtStyle !== '') {
  5842. $script_arr['art_style'] = $mappedArtStyle;
  5843. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5844. }
  5845. if ($user_anime_name != '新剧本策划') {
  5846. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5847. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5848. // 确认对话名称唯一性
  5849. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5850. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  5851. }
  5852. }else {
  5853. $anime_name = $user_anime_name;
  5854. }
  5855. $table_data = [
  5856. 'user_id' => $uid,
  5857. 'model' => $model,
  5858. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5859. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5860. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5861. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5862. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5863. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5864. 'art_style_type' => $input_art_style,
  5865. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5866. 'status' => '解析完成',
  5867. 'generate_status' => '待执行',
  5868. 'updated_at' => date('Y-m-d H:i:s')
  5869. ];
  5870. if ($anime_name) $table_data['anime_name'] = $anime_name;
  5871. // 如果是修改集数,则将content内容更新(会改变原文)
  5872. if (isset($episode_count) && $episode_count > 0) {
  5873. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  5874. $table_data['start_episode_sequence'] = 1;
  5875. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  5876. }else {
  5877. // 如果需要生成原文内容,从script_arr中提取
  5878. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5879. $table_data['content'] = $script_arr['content'];
  5880. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  5881. if (!$table_data['content']) {
  5882. yield [
  5883. 'type' => 'done',
  5884. 'script' => [],
  5885. 'episode' => [],
  5886. 'answer' => $fullContent,
  5887. 'reasoning' => $fullReasoningContent,
  5888. 'usage' => $usage,
  5889. 'error' => '未生成剧本内容,请调整提示词再试'
  5890. ];
  5891. return;
  5892. }
  5893. }
  5894. if (isset($table_data['content']) && $table_data['content']) {
  5895. $chapters = splitContent($table_data['content']);
  5896. $chapter_count = count($chapters);
  5897. if ($chapter_count > 0) {
  5898. $table_data['start_episode_sequence'] = 1;
  5899. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5900. }
  5901. }
  5902. }
  5903. $single_episode = [];
  5904. try {
  5905. DB::beginTransaction();
  5906. $now = date('Y-m-d H:i:s');
  5907. // 更新动漫大纲
  5908. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5909. if (!$boolen) {
  5910. dLog('deepseek')->info('对话修改失败', $table_data);
  5911. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  5912. Utils::throwError('20003:对话修改失败');
  5913. }
  5914. // 保存对话记录
  5915. $records = [
  5916. [
  5917. 'uid' => $uid,
  5918. 'anime_id' => $anime_id,
  5919. 'sequence' => 0,
  5920. 'role' => 'user',
  5921. 'content' => $prompt,
  5922. 'created_at' => $now,
  5923. 'updated_at' => $now
  5924. ],
  5925. [
  5926. 'uid' => $uid,
  5927. 'anime_id' => $anime_id,
  5928. 'sequence' => 0,
  5929. 'role' => 'assistant',
  5930. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5931. 'content' => $fullContent,
  5932. 'created_at' => $now,
  5933. 'updated_at' => $now
  5934. ]
  5935. ];
  5936. // 保存对话记录
  5937. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5938. if (!$boolen3) {
  5939. Utils::throwError('20003:对话记录保存失败');
  5940. }
  5941. // 单剧集模式:生成并保存剧集信息
  5942. if ($is_single) {
  5943. $anime_name = getProp($anime, 'anime_name', '未命名');
  5944. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5945. if (empty($episode_arr['acts'])) {
  5946. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5947. }
  5948. $saveResult = $this->saveEpisodeVersionData(
  5949. $anime_id,
  5950. 1,
  5951. $episode_arr,
  5952. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5953. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5954. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5955. null,
  5956. null,
  5957. false,
  5958. $content,
  5959. $now
  5960. );
  5961. $single_episode = $saveResult['episode'];
  5962. $episode_id = $saveResult['episode_id'];
  5963. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5964. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5965. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5966. 'props' => json_encode($saveResult['merged_props'], 256),
  5967. 'updated_at' => $now
  5968. ]);
  5969. if ($boolen5 === false) {
  5970. Utils::throwError('20003:单剧集主表资源同步失败');
  5971. }
  5972. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5973. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5974. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5975. $episode_record_content = '确认分镜大纲';
  5976. if ($content !== '') {
  5977. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5978. }
  5979. $episode_records = [
  5980. [
  5981. 'uid' => $uid,
  5982. 'anime_id' => $anime_id,
  5983. 'role' => 'user',
  5984. 'content' => $episode_record_content,
  5985. 'sequence' => 1,
  5986. 'episode_id' => $episode_id,
  5987. 'created_at' => $now,
  5988. 'updated_at' => $now
  5989. ],
  5990. [
  5991. 'uid' => $uid,
  5992. 'anime_id' => $anime_id,
  5993. 'role' => 'assistant',
  5994. 'content' => $fullContent,
  5995. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5996. 'sequence' => 1,
  5997. 'episode_id' => $episode_id,
  5998. 'created_at' => $now,
  5999. 'updated_at' => $now
  6000. ]
  6001. ];
  6002. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6003. if (!$boolen4) {
  6004. Utils::throwError('20003:单剧集分镜记录保存失败');
  6005. }
  6006. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6007. if ($is_single && !empty($single_episode)) {
  6008. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6009. 'anime_id' => $anime_id,
  6010. 'episode_id' => $episode_id ?? 0,
  6011. 'model' => $model,
  6012. 'source' => 'reGenerateAnime',
  6013. ]);
  6014. }
  6015. }
  6016. }catch (\Exception $e) {
  6017. DB::rollBack();
  6018. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  6019. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  6020. yield [
  6021. 'type' => 'done',
  6022. 'answer' => $fullContent,
  6023. 'reasoning' => $fullReasoningContent,
  6024. 'usage' => $usage,
  6025. 'error' => $e->getMessage(),
  6026. ];
  6027. return;
  6028. }
  6029. DB::commit();
  6030. dLog('deepseek')->info('保存完毕');
  6031. if ($is_single && !empty($single_episode)) {
  6032. // $this->batchSetGlobalRoleImg([
  6033. // 'anime_id' => $anime_id,
  6034. // ]);
  6035. // $this->batchSetGlobalSceneImg([
  6036. // 'anime_id' => $anime_id,
  6037. // ]);
  6038. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6039. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6040. }
  6041. $table_data['anime_id'] = $anime_id;
  6042. $table_data['roles'] = json_decode($table_data['roles'], true);
  6043. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6044. unset($table_data['updated_at']);
  6045. unset($table_data['status']);
  6046. yield [
  6047. 'type' => 'done',
  6048. 'script' => $table_data,
  6049. 'episode' => $single_episode,
  6050. 'answer' => $fullContent,
  6051. 'reasoning' => $fullReasoningContent,
  6052. 'usage' => $usage
  6053. ];
  6054. }
  6055. public function chat($data) {
  6056. $uid = Site::getUid();
  6057. // 积分余额预检(不足直接报错)
  6058. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  6059. $anime_id = getProp($data, 'anime_id');
  6060. $file = getProp($data, 'file');
  6061. $content = getProp($data, 'content', '');
  6062. $bid = getProp($data, 'bid', 0);
  6063. $script_id = getProp($data, 'script_id', 0);
  6064. $episode_number = getProp($data, 'episode_number', 1);
  6065. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6066. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6067. if (!$anime) Utils::throwError('20003:该对话不存在!');
  6068. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  6069. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  6070. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  6071. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  6072. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  6073. $roles = is_array($roles) ? $roles : [];
  6074. $scenes = is_array($scenes) ? $scenes : [];
  6075. // 获取最后一集序号
  6076. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  6077. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  6078. // 转换主体列表和场景列表的格式
  6079. // 获取参考主体或场景
  6080. if ((int)$episode_number === 1) {
  6081. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  6082. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  6083. }else {
  6084. $prev_episode_number = $episode_number - 1;
  6085. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  6086. }
  6087. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  6088. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  6089. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  6090. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  6091. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  6092. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  6093. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  6094. 中年女:邻居阿姨
  6095. 老年男:幽默大爷
  6096. 老年女:婆婆
  6097. 萌娃:奶气萌娃";
  6098. if ($roles_content) {
  6099. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  6100. 主体范围:\n {$roles_content}\n
  6101. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  6102. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6103. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6104. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6105. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6106. }else {
  6107. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6108. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  6109. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6110. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6111. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  6112. }
  6113. if ($scenes_content) {
  6114. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  6115. 场景范围:\n {$scenes_content}\n
  6116. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  6117. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6118. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6119. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  6120. }else {
  6121. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6122. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6123. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6124. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  6125. }
  6126. // 提取文件内容
  6127. if ($file) {
  6128. $uploaded_content = $this->extractFileContent($file);
  6129. if (!$uploaded_content) {
  6130. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6131. }
  6132. } elseif ($script_id) {
  6133. $uploaded_content = $this->getContentByScriptId($script_id);
  6134. if (!$uploaded_content) {
  6135. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6136. }
  6137. } elseif ($bid) {
  6138. $uploaded_content = $this->getContentByBid($bid);
  6139. if (!$uploaded_content) {
  6140. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6141. }
  6142. } elseif ($content) {
  6143. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  6144. }
  6145. // elseif ($prompt) {
  6146. // $uploaded_content = filterContent($prompt);
  6147. // }
  6148. else {
  6149. $uploaded_content = '';
  6150. }
  6151. $input_art_style = getProp($anime, 'art_style');
  6152. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6153. // 美术风格
  6154. if (!$mappedArtStyle) {
  6155. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6156. }else {
  6157. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6158. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6159. }else {
  6160. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6161. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6162. }
  6163. }
  6164. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6165. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6166. // 强制要求:
  6167. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6168. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6169. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6170. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  6171. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  6172. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  6173. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  6174. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  6175. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  6176. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  6177. // - 分镜要和场景列表、人物主体保持一致\n
  6178. // 普通要求:
  6179. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6180. // {$role_demo}
  6181. // {$scene_demo}
  6182. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6183. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6184. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6185. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  6186. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6187. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6188. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6189. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6190. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6191. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6192. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6193. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6194. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6195. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6196. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6197. // 5.$mappedArtStyle_prompt\n\n
  6198. // 示例格式:\n
  6199. // 第1集:隐形的守护者
  6200. // ###故事梗概
  6201. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6202. // ###美术风格
  6203. // 基础画风风格词:韩漫二次元
  6204. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6205. // ###主体列表
  6206. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6207. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6208. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6209. // ###场景列表
  6210. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6211. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6212. // 无人物。}
  6213. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6214. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6215. // 无人物。}
  6216. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6217. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6218. // 无人物。}
  6219. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6220. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6221. // 无人物。}
  6222. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6223. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6224. // 无人物。}
  6225. // ###分镜剧本
  6226. // ##第1幕:徐家老旧厨房 白天 室内
  6227. // 分镜1
  6228. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6229. // 场景:徐家老旧厨房
  6230. // 构图设计:全景,低角度仰视
  6231. // 运镜调度:手持拍摄
  6232. // 配音角色:旁白
  6233. // 出镜角色:许芸-校服装、徐母
  6234. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6235. // 画面类型:普通画面
  6236. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6237. // 分镜2
  6238. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6239. // 场景:徐家老旧厨房
  6240. // 构图设计:近景,徐母面部特写
  6241. // 运镜调度:固定镜头
  6242. // 配音角色:徐母
  6243. // 出镜角色:徐母
  6244. // 台词内容:问我夜不归宿死哪儿去了。
  6245. // 画面类型:对口型
  6246. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6247. // ##第2幕:徐家简陋客厅 黄昏 室内
  6248. // 分镜3
  6249. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6250. // 场景:徐家简陋客厅
  6251. // 构图设计:全景,景深虚化
  6252. // 运镜调度:固定镜头
  6253. // 配音角色:旁白
  6254. // 出镜角色:无
  6255. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6256. // 画面类型:普通画面
  6257. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6258. // 分镜4
  6259. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6260. // 场景:徐家简陋客厅
  6261. // 构图设计:特写,火车票
  6262. // 运镜调度:固定镜头
  6263. // 配音角色:旁白
  6264. // 出镜角色:无
  6265. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6266. // 画面类型:普通画面
  6267. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6268. // \n\n";
  6269. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  6270. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  6271. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  6272. 普通要求:
  6273. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6274. {$role_demo}
  6275. {$scene_demo}
  6276. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  6277. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  6278. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  6279. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6280. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  6281. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  6282. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  6283. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  6284. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  6285. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  6286. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  6287. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  6288. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  6289. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  6290. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  6291. 5.$mappedArtStyle_prompt
  6292. 6.《情绪-视听语言映射表》:
  6293. 6.1 场景空间与时间心理学 (Scene & Temporality)
  6294. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6295. -----|---------|------------|----------------
  6296. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  6297. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  6298. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  6299. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  6300. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  6301. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  6302. -----|---------|------------|----------------
  6303. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  6304. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  6305. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  6306. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  6307. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  6308. --------|---------|--------------|-------------
  6309. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  6310. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  6311. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  6312. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  6313. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  6314. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  6315. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  6316. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  6317. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  6318. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  6319. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  6320. -----|---------|------------|------------
  6321. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  6322. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  6323. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  6324. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  6325. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  6326. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  6327. --------|---------|--------------|----------
  6328. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  6329. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  6330. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  6331. 6.6 声音设计与潜意识影响 (Soundscape)
  6332. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  6333. -----|---------|------------|------------------
  6334. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  6335. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  6336. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  6337. 理论基石:
  6338. - The Five C's of Cinematography by Joseph V. Mascelli
  6339. - Film Art: An Introduction by David Bordwell
  6340. - Sight, Sound, Motion by Herbert Zettl
  6341. - Notes on the Cinematograph by Robert Bresson
  6342. \n\n
  6343. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  6344. 示例格式:\n
  6345. 第1集:隐形的守护者
  6346. ###故事梗概
  6347. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6348. ###美术风格
  6349. 基础画风风格词:韩漫二次元
  6350. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  6351. ###主体列表
  6352. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  6353. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  6354. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  6355. ###场景列表
  6356. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  6357. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6358. 无人物。}
  6359. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  6360. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  6361. 无人物。}
  6362. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  6363. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  6364. 无人物。}
  6365. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  6366. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  6367. 无人物。}
  6368. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  6369. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  6370. 无人物。}
  6371. ###分镜剧本
  6372. ##第1幕:徐家老旧厨房 白天 室内
  6373. 分镜1
  6374. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  6375. 场景:徐家老旧厨房
  6376. 构图设计:全景,低角度仰视
  6377. 运镜调度:手持拍摄
  6378. 配音角色:旁白
  6379. 出镜角色:许芸-校服装、徐母
  6380. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  6381. 画面类型:普通画面
  6382. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  6383. 分镜2
  6384. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  6385. 场景:徐家老旧厨房
  6386. 构图设计:近景,徐母面部特写
  6387. 运镜调度:固定镜头
  6388. 配音角色:徐母
  6389. 出镜角色:徐母
  6390. 台词内容:问我夜不归宿死哪儿去了。
  6391. 画面类型:对口型
  6392. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  6393. ##第2幕:徐家简陋客厅 黄昏 室内
  6394. 分镜3
  6395. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  6396. 场景:徐家简陋客厅
  6397. 构图设计:全景,景深虚化
  6398. 运镜调度:固定镜头
  6399. 配音角色:旁白
  6400. 出镜角色:无
  6401. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  6402. 画面类型:普通画面
  6403. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  6404. 分镜4
  6405. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  6406. 场景:徐家简陋客厅
  6407. 构图设计:特写,火车票
  6408. 运镜调度:固定镜头
  6409. 配音角色:旁白
  6410. 出镜角色:无
  6411. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  6412. 画面类型:普通画面
  6413. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  6414. \n\n";
  6415. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6416. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  6417. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  6418. $prompt = $origin_prompt;
  6419. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  6420. // 获取章节内容
  6421. $full_content = getProp($anime, 'content');
  6422. if ($uploaded_content) {
  6423. $full_content = $uploaded_content;
  6424. }
  6425. // 根据章节内容拆分章节
  6426. $chapters = splitContent($full_content);
  6427. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  6428. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  6429. $messages = [];
  6430. if ($prompt == '确认分镜大纲') {
  6431. // 暂时保留
  6432. $content = $chapter_content;
  6433. if ($is_single) $content = $full_content; // 单剧集使用全文
  6434. if (!$content) {
  6435. Utils::throwError('20003:章节内容无法获取,请确认');
  6436. }
  6437. $question = $is_single
  6438. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  6439. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  6440. // 构建消息
  6441. $messages[] =
  6442. [
  6443. 'role' => 'user',
  6444. 'content' => $question
  6445. ];
  6446. }else if ($prompt == '继续策划下一集') {
  6447. if ($is_single) {
  6448. Utils::throwError('20003:单剧集不支持继续策划下一集');
  6449. }
  6450. $content = $chapter_content;
  6451. if (!$content) {
  6452. Utils::throwError('20003:章节内容无法获取,请确认');
  6453. }
  6454. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  6455. // 获取上一集最后记录
  6456. $prev_sequence = $episode_number - 1;
  6457. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  6458. // 构建消息
  6459. $messages[] =
  6460. [
  6461. 'role' => 'user',
  6462. 'content' => $question
  6463. ];
  6464. }else {
  6465. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  6466. if (!$content) {
  6467. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  6468. }
  6469. if (!$content) {
  6470. Utils::throwError('20003:章节内容无法获取,请确认');
  6471. }
  6472. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  6473. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  6474. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  6475. if ($origin_prompt) {
  6476. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  6477. }
  6478. $messages[] =
  6479. [
  6480. 'role' => 'user',
  6481. 'content' => $question
  6482. ];
  6483. }
  6484. // 处理文本模型
  6485. $model = getProp($data, 'model');
  6486. if (!$model) {
  6487. // 用户没有输入,从anime表获取
  6488. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6489. $model = getProp($anime, 'model');
  6490. if (!$model) {
  6491. // anime表也没有,使用默认值
  6492. $model = 'doubao-seed-2-0-mini-260215';
  6493. }
  6494. }
  6495. // 验证模型是否在可用模型表中
  6496. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6497. $model = 'doubao-seed-2-0-mini-260215';
  6498. }
  6499. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6500. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6501. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6502. if ($model === 'deepseek-chat') {
  6503. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6504. $model = 'deepseek-v4-flash';
  6505. $thinkingMode = 'disabled';
  6506. } elseif ($model === 'deepseek-reasoner') {
  6507. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6508. $model = 'deepseek-v4-flash';
  6509. $thinkingMode = 'enabled';
  6510. }
  6511. $post_data = [
  6512. 'model' => $model,
  6513. 'messages' => $messages,
  6514. // 'max_tokens' => 8192,
  6515. 'temperature' => 0.2,
  6516. 'frequency_penalty' => 0,
  6517. 'presence_penalty' => 0,
  6518. 'response_format' => ['type' => 'text'],
  6519. 'thinking' => ['type' => $thinkingMode],
  6520. 'stream' => true // 启用流式输出
  6521. ];
  6522. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6523. // 根据模型类型选择调用方法
  6524. $fullContent = '';
  6525. $fullReasoningContent = '';
  6526. $usage = [];
  6527. try {
  6528. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6529. // DeepSeek 官方模型使用 DeepSeek API
  6530. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6531. } else if (in_array($model, $this->gpt_text_models)) {
  6532. // GPT-5.4 模型使用 TokenRouter API
  6533. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6534. } else if (in_array($model, $this->gemini_text_models)) {
  6535. // Gemini 模型使用 Gemini API
  6536. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6537. } else {
  6538. // 其他模型使用火山引擎API
  6539. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6540. }
  6541. // 验证返回值类型
  6542. if (!is_iterable($streamGenerator)) {
  6543. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6544. dLog('deepseek')->error('chat流式生成器无效', [
  6545. 'generator_type' => $errorType,
  6546. 'model' => $model,
  6547. 'anime_id' => $anime_id,
  6548. 'episode_number' => $episode_number
  6549. ]);
  6550. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  6551. 'type' => $errorType,
  6552. 'model' => $model
  6553. ]);
  6554. yield [
  6555. 'type' => 'error',
  6556. 'episode' => [],
  6557. 'answer' => '',
  6558. 'reasoning' => '',
  6559. 'usage' => [],
  6560. 'error' => '接口返回数据异常,请重新请求'
  6561. ];
  6562. return;
  6563. }
  6564. // 处理流式输出
  6565. foreach ($streamGenerator as $chunk) {
  6566. if (isset($chunk['type'])) {
  6567. if ($chunk['type'] === 'done') {
  6568. // 最终结果
  6569. $fullContent = $chunk['full_content'];
  6570. $fullReasoningContent = $chunk['full_reasoning'];
  6571. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6572. } else {
  6573. // 逐块yield数据
  6574. yield $chunk;
  6575. }
  6576. }
  6577. }
  6578. } catch (\Exception $e) {
  6579. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  6580. 'model' => $model,
  6581. 'anime_id' => $anime_id,
  6582. 'episode_number' => $episode_number,
  6583. 'trace' => $e->getTraceAsString()
  6584. ]);
  6585. logDB('deepseek', 'error', 'chat流式处理失败', [
  6586. 'error' => $e->getMessage(),
  6587. 'model' => $model
  6588. ]);
  6589. yield [
  6590. 'type' => 'error',
  6591. 'episode' => [],
  6592. 'answer' => '',
  6593. 'reasoning' => '',
  6594. 'usage' => [],
  6595. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6596. ];
  6597. return;
  6598. }
  6599. dLog('deepseek')->info('完整内容: '.$fullContent);
  6600. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6601. // 处理完整内容并返回最终结果
  6602. $episode_arr = handleEpisodeContent($fullContent);
  6603. logDB('deepseek', 'info', '解析内容', $episode_arr);
  6604. if (empty($episode_arr['acts'])) {
  6605. // 未生成剧本相关内容,保存对话记录并返回提示
  6606. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  6607. try {
  6608. $now = date('Y-m-d H:i:s');
  6609. // 保存对话记录
  6610. $records = [
  6611. [
  6612. 'uid' => $uid,
  6613. 'anime_id' => $anime_id,
  6614. 'sequence' => $episode_number,
  6615. 'role' => 'user',
  6616. 'content' => $prompt,
  6617. 'created_at' => $now,
  6618. 'updated_at' => $now
  6619. ],
  6620. [
  6621. 'uid' => $uid,
  6622. 'anime_id' => $anime_id,
  6623. 'sequence' => $episode_number,
  6624. 'role' => 'assistant',
  6625. 'content' => $fullContent,
  6626. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6627. 'created_at' => $now,
  6628. 'updated_at' => $now
  6629. ]
  6630. ];
  6631. DB::table('mp_anime_records')->insert($records);
  6632. } catch (\Exception $e) {
  6633. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6634. }
  6635. yield [
  6636. 'type' => 'done',
  6637. 'episode' => [],
  6638. 'answer' => $fullContent,
  6639. 'reasoning' => $fullReasoningContent,
  6640. 'usage' => $usage,
  6641. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  6642. ];
  6643. return;
  6644. }
  6645. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  6646. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  6647. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  6648. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  6649. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  6650. $existing_props = is_array($existing_props) ? $existing_props : [];
  6651. $now = date('Y-m-d H:i:s');
  6652. try {
  6653. DB::beginTransaction();
  6654. $saveResult = $this->saveEpisodeVersionData(
  6655. $anime_id,
  6656. $episode_number,
  6657. $episode_arr,
  6658. $existing_roles,
  6659. $existing_scenes,
  6660. $existing_props,
  6661. $current_episode,
  6662. $base_episode,
  6663. $is_regenerate_version,
  6664. $content,
  6665. $now
  6666. );
  6667. $episode = $saveResult['episode'];
  6668. $episode_id = $saveResult['episode_id'];
  6669. $merged_roles = $saveResult['merged_roles'];
  6670. $merged_scenes = $saveResult['merged_scenes'];
  6671. $merged_props = $saveResult['merged_props'];
  6672. $record_content = $origin_prompt;
  6673. if ($uploaded_content !== '') {
  6674. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  6675. }
  6676. $records = [
  6677. [
  6678. 'uid' => $uid,
  6679. 'anime_id' => $anime_id,
  6680. 'role' => 'user',
  6681. 'content' => $record_content,
  6682. 'sequence' => $episode_number,
  6683. 'episode_id' => $episode_id,
  6684. 'created_at' => $now,
  6685. 'updated_at' => $now
  6686. ],
  6687. [
  6688. 'uid' => $uid,
  6689. 'anime_id' => $anime_id,
  6690. 'role' => 'assistant',
  6691. 'content' => $fullContent,
  6692. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6693. 'sequence' => $episode_number,
  6694. 'episode_id' => $episode_id,
  6695. 'created_at' => $now,
  6696. 'updated_at' => $now
  6697. ]
  6698. ];
  6699. $boolen4 = DB::table('mp_anime_records')->insert($records);
  6700. if (!$boolen4) {
  6701. Utils::throwError('20003:对话记录保存失败');
  6702. }
  6703. // 保存模型和内容到anime表
  6704. $update_anime_data = [
  6705. 'model' => $model,
  6706. 'updated_at' => $now
  6707. ];
  6708. if ($uploaded_content) {
  6709. $update_anime_data['content'] = $uploaded_content;
  6710. }
  6711. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  6712. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6713. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6714. 'anime_id' => $anime_id,
  6715. 'episode_number' => $episode_number,
  6716. 'model' => $model,
  6717. 'source' => 'chat',
  6718. ]);
  6719. }catch (\Exception $e) {
  6720. DB::rollBack();
  6721. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6722. yield [
  6723. 'type' => 'done',
  6724. 'answer' => $fullContent,
  6725. 'reasoning' => $fullReasoningContent,
  6726. 'usage' => $usage,
  6727. 'error' => $e->getMessage(),
  6728. ];
  6729. return;
  6730. }
  6731. DB::commit();
  6732. if ($is_global_generate_pics) {
  6733. // // 批量生成全局角色图片
  6734. // $this->batchSetGlobalRoleImg([
  6735. // 'anime_id' => $anime_id,
  6736. // ], true);
  6737. // // 批量生成全局场景图片
  6738. // $this->batchSetGlobalSceneImg([
  6739. // 'anime_id' => $anime_id,
  6740. // ], true);
  6741. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6742. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6743. }
  6744. $episode['episode_id'] = $episode_id;
  6745. $episode['roles'] = $merged_roles;
  6746. $episode['scenes'] = $merged_scenes;
  6747. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  6748. yield [
  6749. 'type' => 'done',
  6750. 'episode' => $episode,
  6751. 'answer' => $fullContent,
  6752. 'reasoning' => $fullReasoningContent,
  6753. 'usage' => $usage
  6754. ];
  6755. }
  6756. public function addChatForAce($data) {
  6757. $uid = Site::getUid();
  6758. $anime_id = getProp($data, 'anime_id');
  6759. if (!$anime_id) Utils::throwError('20003:请选择对话');
  6760. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  6761. if (!$anime) Utils::throwError('20003:对话不存在');
  6762. $file = getProp($data, 'file');
  6763. $content = getProp($data, 'content', '');
  6764. $bid = getProp($data, 'bid', 0);
  6765. $script_id = getProp($data, 'script_id', 0);
  6766. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  6767. $prompt = getProp($data, 'prompt');
  6768. $is_multi = getProp($anime, 'is_multi');
  6769. $is_single = (int)$is_multi !== 1;
  6770. // 积分余额预检(仅单剧集模式收费)
  6771. if ($is_single) {
  6772. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  6773. }
  6774. $extra_products = getProp($data, 'products', []);
  6775. if (!$extra_products) {
  6776. $extra_products = getProp($anime, 'extra_products');
  6777. if ($extra_products) {
  6778. $extra_products = json_decode($extra_products, true);
  6779. }else {
  6780. $extra_products = [];
  6781. }
  6782. }else {
  6783. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6784. }
  6785. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6786. $anime_script_id = getProp($anime, 'script_id');
  6787. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  6788. $cpid = Site::getCpid();
  6789. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6790. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6791. ->where('mapping.script_id', $anime_script_id)
  6792. ->where('product.cpid', $cpid)
  6793. ->where('product.is_deleted', 0);
  6794. $mappings = $script_products_mappings->select(
  6795. 'mapping.product_id',
  6796. 'mapping.episode_number',
  6797. 'product.product_name',
  6798. 'product.type',
  6799. 'product.product',
  6800. 'product.pic_prompt',
  6801. 'product.url',
  6802. 'product.pic_task_id',
  6803. 'product.pic_task_status',
  6804. 'product.three_view_image_url'
  6805. )
  6806. ->get();
  6807. // 按 product_id 分组,合并 episode_number
  6808. $productMap = [];
  6809. foreach ($mappings as $item) {
  6810. $product_id = $item->product_id;
  6811. $product_name = $item->product_name;
  6812. // 处理product_name两边的符号
  6813. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6814. if (!isset($productMap[$product_id])) {
  6815. $productMap[$product_id] = [
  6816. 'product_id' => $product_id,
  6817. 'product_name' => $product_name,
  6818. 'type' => (int)$item->type,
  6819. 'product' => (int)$item->product,
  6820. 'pic_prompt' => $item->pic_prompt,
  6821. 'url' => $item->url,
  6822. 'pic_task_id' => $item->pic_task_id,
  6823. 'pic_task_status' => $item->pic_task_status,
  6824. 'episode_numbers' => [],
  6825. ];
  6826. }
  6827. // 添加 episode_number(去重)
  6828. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6829. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6830. }
  6831. }
  6832. // 将查询到的剧本资产合并到extra_products中
  6833. // 先构建extra_products的索引(以product_id为key,用于去重)
  6834. $extraProductsMap = [];
  6835. foreach ($extra_products as $item) {
  6836. $key = getProp($item, 'product_id');
  6837. if ($key) {
  6838. $extraProductsMap[$key] = $item;
  6839. }
  6840. }
  6841. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6842. foreach ($productMap as $product) {
  6843. $product_id = $product['product_id'];
  6844. // 如果不存在则添加(不带episode_number信息)
  6845. if (!isset($extraProductsMap[$product_id])) {
  6846. $extraProductsMap[$product_id] = [
  6847. 'product_id' => $product['product_id'],
  6848. 'product_name' => $product['product_name'],
  6849. 'type' => $product['type'],
  6850. 'product' => $product['product'],
  6851. 'pic_prompt' => $product['pic_prompt'],
  6852. 'url' => $product['url'],
  6853. 'pic_task_id' => $product['pic_task_id'],
  6854. 'pic_task_status' => $product['pic_task_status'],
  6855. ];
  6856. }
  6857. }
  6858. // 重新赋值给extra_products
  6859. $extra_products = array_values($extraProductsMap);
  6860. }
  6861. $user_anime_name = getProp($anime, 'anime_name');
  6862. // 处理提示词
  6863. if ($prompt && $extra_products) {
  6864. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6865. foreach($extra_products as $item) {
  6866. $product_name = getProp($item, 'product_name');
  6867. if ($product_name) {
  6868. // 替换 {product_name} 为 product_name
  6869. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6870. }
  6871. }
  6872. }
  6873. // 处理文本模型
  6874. $model = getProp($data, 'model');
  6875. if (!$model) {
  6876. // 用户没有输入,从anime表获取
  6877. $model = getProp($anime, 'model');
  6878. if (!$model) {
  6879. // anime表也没有,使用默认值
  6880. $model = 'deepseek-v4-pro';
  6881. }
  6882. }
  6883. // 验证模型是否在可用模型表中
  6884. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6885. $model = 'deepseek-v4-pro';
  6886. }
  6887. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6888. if ($prompt) {
  6889. $question .= "本次修改要求如下:\n{$prompt}";
  6890. }
  6891. // if (!$file && !$content && !$bid) {
  6892. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  6893. // }
  6894. // 提取文件内容
  6895. if ($file) {
  6896. $content = $this->extractFileContent($file);
  6897. if (!$content) {
  6898. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6899. }
  6900. } elseif ($script_id) {
  6901. $content = $this->getContentByScriptId($script_id);
  6902. if (!$content) {
  6903. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6904. }
  6905. } elseif ($bid) {
  6906. $content = $this->getContentByBid($bid);
  6907. if (!$content) {
  6908. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6909. }
  6910. } elseif ($content) {
  6911. $content = filterContent($content);
  6912. } else {
  6913. $content = getProp($anime, 'content');
  6914. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6915. $need_generate_content = true;
  6916. }
  6917. }
  6918. // 美术风格
  6919. $input_art_style = getProp($data, 'art_style');
  6920. if (!$input_art_style) {
  6921. $mappedArtStyle = getProp($anime, 'art_style');
  6922. }else {
  6923. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6924. }
  6925. // 判断是否需要生成原文内容
  6926. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6927. // 如果需要生成原文内容,添加额外的要求
  6928. $content_generation_requirement = $need_generate_content
  6929. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6930. : "";
  6931. // 美术风格
  6932. if (!$mappedArtStyle) {
  6933. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6934. }else {
  6935. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6936. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6937. }else {
  6938. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6939. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6940. }
  6941. }
  6942. // 构建主体、场景和道具提示词
  6943. $extra_role_prompt = "\n";
  6944. $extra_scene_prompt = "\n";
  6945. $extra_prop_prompt = "\n";
  6946. $ref_products = []; // 参考资产
  6947. if ($extra_products) {
  6948. foreach($extra_products as $item) {
  6949. $product = getProp($item, 'product');
  6950. $product_name = getProp($item, 'product_name');
  6951. if ($product_name == '旁白') continue;
  6952. $ref_products[$product_name] = $item;
  6953. $pic_prompt = getProp($item, 'pic_prompt');
  6954. if ((int)$product === 1) {
  6955. // 拼接角色信息
  6956. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6957. } elseif ((int)$product === 2) {
  6958. // 拼接场景信息
  6959. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6960. } elseif ((int)$product === 3) {
  6961. // 拼接道具信息
  6962. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6963. }
  6964. }
  6965. // 优化提示词,融入剧本
  6966. if (!empty(trim($extra_role_prompt))) {
  6967. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6968. }
  6969. if (!empty(trim($extra_scene_prompt))) {
  6970. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6971. }
  6972. if (!empty(trim($extra_prop_prompt))) {
  6973. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6974. }
  6975. }
  6976. if ($anime_script_id && $is_single) {
  6977. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6978. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6979. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6980. }else {
  6981. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6982. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6983. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6984. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6985. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6986. {$extra_role_prompt}";
  6987. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6988. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6989. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6990. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6991. {$extra_scene_prompt}";
  6992. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6993. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6994. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6995. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6996. {$extra_prop_prompt}";
  6997. }
  6998. $systemPrompt = $is_single
  6999. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7000. 强制要求:
  7001. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7002. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7003. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7004. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7005. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7006. 普通要求:
  7007. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7008. $role_demo
  7009. $scene_demo
  7010. $prop_demo
  7011. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7012. 5.1片段分割逻辑(优先级从高到低):
  7013. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7014. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7015. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7016. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7017. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7018. - 片段数量格式为: 片段数量:8
  7019. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7020. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7021. 5.3分镜结构:每个分镜包含以下字段:
  7022. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7023. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7024. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7025. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7026. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7027. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7028. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7029. - 运镜:场景+画面描述+运镜
  7030. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7031. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7032. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7033. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7034. 6.{$mappedArtStyle_prompt}\n\n
  7035. 示例如下:\n
  7036. ###剧本名:西昆仑
  7037. ###故事梗概
  7038. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7039. ###剧本亮点
  7040. 亮点1:绝境奇药,生死一线
  7041. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7042. 亮点2:结拜兄妹,化解尴尬
  7043. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7044. 亮点3:纤发夺命,情愫暗涌
  7045. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7046. ###人物关系
  7047. 阿雪与梁萧之间存在兄妹之情。
  7048. ###核心矛盾
  7049. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7050. ###主体列表
  7051. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7052. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7053. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7054. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7055. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7056. 全景,正面拍摄,青年女性,亚洲人。
  7057. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7058. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7059. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7060. ###美术风格
  7061. 基础画风风格词:厚涂古风
  7062. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7063. ###场景列表
  7064. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7065. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7066. 无人物。}
  7067. ###分段剧本
  7068. 片段数量:8
  7069. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7070. ##片段1
  7071. 时长:12s
  7072. 分镜1
  7073. 出场角色:刀疤脸
  7074. 场景:边境小镇街道
  7075. 出场道具:酒杯-高脚杯
  7076. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7077. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7078. 配音台词:
  7079. 背景音效:
  7080. 分镜2
  7081. 出场角色:刀疤脸
  7082. 场景:悦来酒馆
  7083. 出场道具:酒杯-高脚杯
  7084. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7085. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7086. 配音台词:
  7087. 背景音效:
  7088. 分镜3
  7089. 出场角色:刀疤脸
  7090. 场景:悦来酒馆
  7091. 出场道具:酒杯-高脚杯
  7092. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7093. 运镜:从中景推向令牌特写。
  7094. 配音台词:
  7095. 背景音效:
  7096. 分镜4
  7097. 出场角色:刀疤脸
  7098. 场景:悦来酒馆
  7099. 出场道具:酒杯-高脚杯
  7100. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7101. 运镜:极速推向酒水溅起的瞬间。
  7102. 配音台词:
  7103. 背景音效:
  7104. 分镜5
  7105. 出场角色:刀疤脸
  7106. 场景:悦来酒馆
  7107. 出场道具:酒杯-高脚杯
  7108. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7109. 运镜:固定机位,利用倾斜构图制造压迫感。
  7110. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7111. 背景音效:
  7112. \n\n"
  7113. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7114. 强制要求:\n
  7115. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7116. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7117. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7118. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7119. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7120. 普通要求:\n
  7121. 1.剧本名(必须生成)必须与文档内容高度相关
  7122. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7123. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7124. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7125. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7126. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7127. {$extra_role_prompt}
  7128. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7129. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7130. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7131. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7132. {$extra_scene_prompt}
  7133. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7134. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7135. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7136. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7137. {$extra_prop_prompt}
  7138. 5.{$mappedArtStyle_prompt}\n\n
  7139. 示例如下:\n
  7140. ###剧本名:西昆仑
  7141. ###故事梗概
  7142. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7143. ###剧本亮点
  7144. 亮点1:绝境奇药,生死一线
  7145. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7146. 亮点2:结拜兄妹,化解尴尬
  7147. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7148. 亮点3:纤发夺命,情愫暗涌
  7149. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7150. ###人物关系
  7151. 阿雪与梁萧之间存在兄妹之情。
  7152. ###核心矛盾
  7153. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7154. ###主体列表
  7155. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7156. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7157. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7158. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7159. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7160. 全景,正面拍摄,青年女性,亚洲人。
  7161. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7162. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7163. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7164. ###美术风格
  7165. 基础画风风格词:厚涂古风
  7166. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7167. ###场景列表
  7168. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7169. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7170. 无人物。}
  7171. ###道具列表
  7172. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  7173. // 构建消息
  7174. $messages = [
  7175. [
  7176. 'role' => 'system',
  7177. 'content' => $systemPrompt
  7178. ],
  7179. [
  7180. 'role' => 'user',
  7181. 'content' => "以下是文档内容:
  7182. {$content}
  7183. 用户问题:
  7184. {$question}"
  7185. ]
  7186. ];
  7187. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7188. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7189. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7190. if ($model === 'deepseek-chat') {
  7191. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7192. $model = 'deepseek-v4-flash';
  7193. $thinkingMode = 'disabled';
  7194. } elseif ($model === 'deepseek-reasoner') {
  7195. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7196. $model = 'deepseek-v4-flash';
  7197. $thinkingMode = 'enabled';
  7198. }
  7199. $post_data = [
  7200. 'model' => $model,
  7201. 'messages' => $messages,
  7202. // 'max_tokens' => 8192,
  7203. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7204. 'frequency_penalty' => 0,
  7205. 'presence_penalty' => 0,
  7206. 'response_format' => ['type' => 'text'],
  7207. 'thinking' => ['type'=>$thinkingMode],
  7208. 'stream' => true // 启用流式输出
  7209. ];
  7210. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7211. // 根据模型类型选择调用方法
  7212. $fullContent = '';
  7213. $fullReasoningContent = '';
  7214. $usage = [];
  7215. try {
  7216. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7217. // DeepSeek 官方模型使用 DeepSeek API
  7218. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7219. } else if (in_array($model, $this->gpt_text_models)) {
  7220. // GPT-5.4 模型使用 TokenRouter API
  7221. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7222. } else if (in_array($model, $this->gemini_text_models)) {
  7223. // Gemini 模型使用 Gemini API
  7224. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  7225. } else {
  7226. // 其他模型使用火山引擎API
  7227. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7228. }
  7229. // 验证返回值类型
  7230. if (!is_iterable($streamGenerator)) {
  7231. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7232. dLog('deepseek')->error('addChat流式生成器无效', [
  7233. 'generator_type' => $errorType,
  7234. 'model' => $model,
  7235. 'anime_id' => $anime_id
  7236. ]);
  7237. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  7238. 'type' => $errorType,
  7239. 'model' => $model
  7240. ]);
  7241. yield [
  7242. 'type' => 'error',
  7243. 'script' => [],
  7244. 'episode' => [],
  7245. 'answer' => '',
  7246. 'reasoning' => '',
  7247. 'usage' => [],
  7248. 'error' => '接口返回数据异常,请重新请求'
  7249. ];
  7250. return;
  7251. }
  7252. // 处理流式输出
  7253. foreach ($streamGenerator as $chunk) {
  7254. if (isset($chunk['type'])) {
  7255. if ($chunk['type'] === 'done') {
  7256. // 最终结果
  7257. $fullContent = $chunk['full_content'];
  7258. $fullReasoningContent = $chunk['full_reasoning'];
  7259. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7260. } else {
  7261. // 逐块yield数据
  7262. yield $chunk;
  7263. }
  7264. }
  7265. }
  7266. } catch (\Exception $e) {
  7267. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  7268. 'model' => $model,
  7269. 'anime_id' => $anime_id,
  7270. 'trace' => $e->getTraceAsString()
  7271. ]);
  7272. logDB('deepseek', 'error', 'addChat流式处理失败', [
  7273. 'error' => $e->getMessage(),
  7274. 'model' => $model
  7275. ]);
  7276. yield [
  7277. 'type' => 'error',
  7278. 'script' => [],
  7279. 'episode' => [],
  7280. 'answer' => '',
  7281. 'reasoning' => '',
  7282. 'usage' => [],
  7283. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7284. ];
  7285. return;
  7286. }
  7287. dLog('deepseek')->info('完整内容: '.$fullContent);
  7288. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7289. // 处理完整内容并返回最终结果
  7290. $script_arr = [];
  7291. if ($fullContent) {
  7292. $script_arr = handleScriptContentForAce($fullContent);
  7293. dLog('deepseek')->info('解析内容', $script_arr);
  7294. logDB('deepseek', 'info', '解析内容', $script_arr);
  7295. }
  7296. if (empty($script_arr['roles'])) {
  7297. // 未生成剧本相关内容,保存对话记录并返回提示
  7298. dLog('deepseek')->info('未生成剧本相关的内容');
  7299. try {
  7300. DB::beginTransaction();
  7301. $now = date('Y-m-d H:i:s');
  7302. // 保存对话记录
  7303. $records = [
  7304. [
  7305. 'uid' => $uid,
  7306. 'anime_id' => $anime_id,
  7307. 'sequence' => 0,
  7308. 'role' => 'user',
  7309. 'content' => $prompt,
  7310. 'created_at' => $now,
  7311. 'updated_at' => $now
  7312. ],
  7313. [
  7314. 'uid' => $uid,
  7315. 'anime_id' => $anime_id,
  7316. 'sequence' => 0,
  7317. 'role' => 'assistant',
  7318. // 'content' => $fullContent,
  7319. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  7320. 'created_at' => $now,
  7321. 'updated_at' => $now
  7322. ]
  7323. ];
  7324. DB::table('mp_anime_records')->insert($records);
  7325. DB::commit();
  7326. } catch (\Exception $e) {
  7327. DB::rollBack();
  7328. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7329. }
  7330. yield [
  7331. 'type' => 'done',
  7332. 'script' => [],
  7333. 'episode' => [],
  7334. 'answer' => $fullContent,
  7335. 'reasoning' => $fullReasoningContent,
  7336. 'usage' => $usage,
  7337. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  7338. ];
  7339. return;
  7340. }
  7341. // 如果需要生成原文内容,从script_arr中提取
  7342. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  7343. $content = $script_arr['content'];
  7344. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  7345. if (!$content) {
  7346. yield [
  7347. 'type' => 'done',
  7348. 'script' => [],
  7349. 'episode' => [],
  7350. 'answer' => $fullContent,
  7351. 'reasoning' => $fullReasoningContent,
  7352. 'usage' => $usage,
  7353. 'error' => '未生成剧本内容,请调整提示词再试'
  7354. ];
  7355. return;
  7356. }
  7357. }
  7358. // 替换美术风格
  7359. if ($mappedArtStyle !== '') {
  7360. $script_arr['art_style'] = $mappedArtStyle;
  7361. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  7362. }
  7363. // 新建动漫
  7364. if ($user_anime_name == '新剧本策划') {
  7365. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  7366. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  7367. // if (!$anime_name) {
  7368. // // 未识别到剧本名,保存对话记录并返回提示
  7369. // dLog('deepseek')->info('未能识别到剧本名称');
  7370. // try {
  7371. // DB::beginTransaction();
  7372. // $now = date('Y-m-d H:i:s');
  7373. // // 保存对话记录
  7374. // $records = [
  7375. // [
  7376. // 'uid' => $uid,
  7377. // 'anime_id' => $anime_id,
  7378. // 'sequence' => 0,
  7379. // 'role' => 'user',
  7380. // 'content' => $prompt,
  7381. // 'created_at' => $now,
  7382. // 'updated_at' => $now
  7383. // ],
  7384. // [
  7385. // 'uid' => $uid,
  7386. // 'anime_id' => $anime_id,
  7387. // 'sequence' => 0,
  7388. // 'role' => 'assistant',
  7389. // 'content' => '未能生成剧本名称,请重试',
  7390. // 'created_at' => $now,
  7391. // 'updated_at' => $now
  7392. // ]
  7393. // ];
  7394. // DB::table('mp_anime_records')->insert($records);
  7395. // DB::commit();
  7396. // } catch (\Exception $e) {
  7397. // DB::rollBack();
  7398. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7399. // }
  7400. // yield [
  7401. // 'type' => 'done',
  7402. // 'script' => [],
  7403. // 'episode' => [],
  7404. // 'answer' => $fullContent,
  7405. // 'reasoning' => $fullReasoningContent,
  7406. // 'usage' => $usage,
  7407. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  7408. // ];
  7409. // return;
  7410. // }
  7411. // 确认对话名称唯一性
  7412. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  7413. $anime_name = $anime_name . '_' . date('YmdHis');
  7414. }
  7415. }else {
  7416. $anime_name = $user_anime_name;
  7417. }
  7418. $table_data = [
  7419. 'user_id' => $uid,
  7420. 'anime_name' => $anime_name,
  7421. 'model' => $model,
  7422. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  7423. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  7424. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  7425. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  7426. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  7427. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  7428. 'art_style_type' => $input_art_style,
  7429. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  7430. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  7431. 'status' => '解析完成',
  7432. 'content' => $content,
  7433. 'is_multi' => $is_multi,
  7434. 'ace_mode' => $ace_mode,
  7435. 'generate_status' => '待执行',
  7436. 'updated_at' => date('Y-m-d H:i:s')
  7437. ];
  7438. if ($table_data['content']) {
  7439. $chapters = splitContent($table_data['content']);
  7440. $chapter_count = count($chapters);
  7441. if ($chapter_count > 0) {
  7442. $table_data['start_episode_sequence'] = 1;
  7443. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  7444. }
  7445. }
  7446. if ($extra_products) {
  7447. $table_data['extra_products'] = json_encode($extra_products, 256);
  7448. }
  7449. // 如果有剧本ID则进行绑定
  7450. if ($script_id) {
  7451. $table_data['script_id'] = $script_id;
  7452. }
  7453. $single_episode = [];
  7454. try {
  7455. DB::beginTransaction();
  7456. $now = date('Y-m-d H:i:s');
  7457. // 更新动漫大纲
  7458. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7459. if (!$boolen) {
  7460. dLog('deepseek')->info('动漫保存失败', $table_data);
  7461. Utils::throwError('20003:动漫保存失败');
  7462. }
  7463. // 保存对话记录
  7464. $records = [
  7465. [
  7466. 'uid' => $uid,
  7467. 'anime_id' => $anime_id,
  7468. 'sequence' => 0,
  7469. 'role' => 'user',
  7470. 'content' => $prompt,
  7471. 'created_at' => date('Y-m-d H:i:s'),
  7472. 'updated_at' => date('Y-m-d H:i:s')
  7473. ],
  7474. [
  7475. 'uid' => $uid,
  7476. 'anime_id' => $anime_id,
  7477. 'sequence' => 0,
  7478. 'role' => 'assistant',
  7479. 'content' => $fullContent,
  7480. 'created_at' => date('Y-m-d H:i:s'),
  7481. 'updated_at' => date('Y-m-d H:i:s')
  7482. ]
  7483. ];
  7484. // 保存对话记录
  7485. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7486. if (!$boolen3) {
  7487. Utils::throwError('20003:对话记录保存失败');
  7488. }
  7489. if ($is_single) {
  7490. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7491. if (empty($episode_arr['acts'])) {
  7492. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7493. }
  7494. $saveResult = $this->saveEpisodeVersionData(
  7495. $anime_id,
  7496. 1,
  7497. $episode_arr,
  7498. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7499. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7500. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7501. null,
  7502. null,
  7503. false,
  7504. $content,
  7505. $now,
  7506. $ref_products
  7507. );
  7508. $single_episode = $saveResult['episode'];
  7509. $episode_id = $saveResult['episode_id'];
  7510. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7511. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7512. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7513. 'props' => json_encode($saveResult['merged_props'], 256),
  7514. 'updated_at' => $now
  7515. ]);
  7516. if ($boolen5 === false) {
  7517. Utils::throwError('20003:单剧集主表资源同步失败');
  7518. }
  7519. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7520. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7521. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7522. $episode_record_content = '确认分镜大纲';
  7523. if ($content !== '') {
  7524. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7525. }
  7526. $episode_records = [
  7527. [
  7528. 'uid' => $uid,
  7529. 'anime_id' => $anime_id,
  7530. 'role' => 'user',
  7531. 'content' => $episode_record_content,
  7532. 'sequence' => 1,
  7533. 'episode_id' => $episode_id,
  7534. 'created_at' => $now,
  7535. 'updated_at' => $now
  7536. ],
  7537. [
  7538. 'uid' => $uid,
  7539. 'anime_id' => $anime_id,
  7540. 'role' => 'assistant',
  7541. 'content' => $fullContent,
  7542. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7543. 'sequence' => 1,
  7544. 'episode_id' => $episode_id,
  7545. 'created_at' => $now,
  7546. 'updated_at' => $now
  7547. ]
  7548. ];
  7549. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7550. if (!$boolen4) {
  7551. Utils::throwError('20003:单剧集分镜记录保存失败');
  7552. }
  7553. }
  7554. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7555. if ($is_single && !empty($single_episode)) {
  7556. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7557. 'anime_id' => $anime_id,
  7558. 'episode_id' => $episode_id ?? 0,
  7559. 'model' => $model,
  7560. 'source' => 'addChatForAce',
  7561. ]);
  7562. }
  7563. }catch (\Exception $e) {
  7564. DB::rollBack();
  7565. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7566. yield [
  7567. 'type' => 'done',
  7568. 'answer' => $fullContent,
  7569. 'reasoning' => $fullReasoningContent,
  7570. 'usage' => $usage,
  7571. 'error' => $e->getMessage(),
  7572. ];
  7573. return;
  7574. }
  7575. DB::commit();
  7576. dLog('deepseek')->info('保存完毕');
  7577. if ($is_single && !empty($single_episode)) {
  7578. // $this->batchSetGlobalRoleImg([
  7579. // 'anime_id' => $anime_id,
  7580. // ]);
  7581. // $this->batchSetGlobalSceneImg([
  7582. // 'anime_id' => $anime_id,
  7583. // ]);
  7584. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7585. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7586. }
  7587. $table_data['anime_id'] = $anime_id;
  7588. $table_data['roles'] = json_decode($table_data['roles'], true);
  7589. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7590. // $table_data['episodes'] = $script_arr['episodes'];
  7591. unset($table_data['created_at']);
  7592. unset($table_data['updated_at']);
  7593. unset($table_data['status']);
  7594. dLog('deepseek')->info('开始返回');
  7595. yield [
  7596. 'type' => 'done',
  7597. 'script' => $table_data,
  7598. 'episode' => $single_episode,
  7599. 'answer' => $fullContent,
  7600. 'reasoning' => $fullReasoningContent,
  7601. 'usage' => $usage
  7602. ];
  7603. }
  7604. public function reGenerateAnimeForAce($data) {
  7605. $uid = Site::getUid();
  7606. $file = getProp($data, 'file');
  7607. $content = getProp($data, 'content', '');
  7608. $bid = getProp($data, 'bid', 0);
  7609. $script_id = getProp($data, 'script_id', 0);
  7610. $anime_id = getProp($data, 'anime_id');
  7611. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7612. if (!$anime) {
  7613. Utils::throwError('20003:该对话不存在');
  7614. }
  7615. $is_multi = getProp($anime, 'is_multi', 1);
  7616. $is_single = (int)$is_multi !== 1;
  7617. // 积分余额预检(仅单剧集模式收费)
  7618. if ($is_single) {
  7619. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints((string)$model), $uid);
  7620. }
  7621. $extra_products = getProp($data, 'products', []);
  7622. if (!$extra_products) {
  7623. $extra_products = getProp($anime, 'extra_products');
  7624. if ($extra_products) {
  7625. $extra_products = json_decode($extra_products, true);
  7626. }else {
  7627. $extra_products = [];
  7628. }
  7629. }else {
  7630. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7631. }
  7632. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7633. $anime_script_id = getProp($anime, 'script_id');
  7634. if ($anime_script_id && $is_single) {
  7635. $cpid = Site::getCpid();
  7636. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7637. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7638. ->where('mapping.script_id', $anime_script_id)
  7639. ->where('product.cpid', $cpid)
  7640. ->where('product.is_deleted', 0);
  7641. $mappings = $script_products_mappings->select(
  7642. 'mapping.product_id',
  7643. 'mapping.episode_number',
  7644. 'product.product_name',
  7645. 'product.type',
  7646. 'product.product',
  7647. 'product.pic_prompt',
  7648. 'product.url',
  7649. 'product.pic_task_id',
  7650. 'product.pic_task_status',
  7651. 'product.three_view_image_url'
  7652. )
  7653. ->get();
  7654. // 按 product_id 分组,合并 episode_number
  7655. $productMap = [];
  7656. foreach ($mappings as $item) {
  7657. $product_id = $item->product_id;
  7658. $product_name = $item->product_name;
  7659. // 处理product_name两边的符号
  7660. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7661. if (!isset($productMap[$product_id])) {
  7662. $productMap[$product_id] = [
  7663. 'product_id' => $product_id,
  7664. 'product_name' => $product_name,
  7665. 'type' => (int)$item->type,
  7666. 'product' => (int)$item->product,
  7667. 'pic_prompt' => $item->pic_prompt,
  7668. 'url' => $item->url,
  7669. 'pic_task_id' => $item->pic_task_id,
  7670. 'pic_task_status' => $item->pic_task_status,
  7671. 'episode_numbers' => [],
  7672. ];
  7673. }
  7674. // 添加 episode_number(去重)
  7675. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7676. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7677. }
  7678. }
  7679. // 将查询到的剧本资产合并到extra_products中
  7680. // 先构建extra_products的索引(以product_id为key,用于去重)
  7681. $extraProductsMap = [];
  7682. foreach ($extra_products as $item) {
  7683. $key = getProp($item, 'product_id');
  7684. if ($key) {
  7685. $extraProductsMap[$key] = $item;
  7686. }
  7687. }
  7688. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7689. foreach ($productMap as $product) {
  7690. $product_id = $product['product_id'];
  7691. // 如果不存在则添加(不带episode_number信息)
  7692. if (!isset($extraProductsMap[$product_id])) {
  7693. $extraProductsMap[$product_id] = [
  7694. 'product_id' => $product['product_id'],
  7695. 'product_name' => $product['product_name'],
  7696. 'type' => $product['type'],
  7697. 'product' => $product['product'],
  7698. 'pic_prompt' => $product['pic_prompt'],
  7699. 'url' => $product['url'],
  7700. 'pic_task_id' => $product['pic_task_id'],
  7701. 'pic_task_status' => $product['pic_task_status'],
  7702. ];
  7703. }
  7704. }
  7705. // 重新赋值给extra_products
  7706. $extra_products = array_values($extraProductsMap);
  7707. }
  7708. $user_anime_name = getProp($anime, 'anime_name');
  7709. $prompt = getProp($data, 'prompt');
  7710. // 处理提示词
  7711. if ($prompt && $extra_products) {
  7712. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7713. foreach($extra_products as $item) {
  7714. $product_name = getProp($item, 'product_name');
  7715. if ($product_name) {
  7716. // 替换 {product_name} 为 product_name
  7717. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7718. }
  7719. }
  7720. }
  7721. // 处理文本模型
  7722. $model = getProp($data, 'model');
  7723. if (!$model) {
  7724. // 用户没有输入,从anime表获取
  7725. $model = getProp($anime, 'model');
  7726. if (!$model) {
  7727. // anime表也没有,使用默认值
  7728. $model = 'deepseek-v4-pro';
  7729. }
  7730. }
  7731. // 验证模型是否在可用模型表中
  7732. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7733. $model = 'deepseek-v4-pro';
  7734. }
  7735. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  7736. if ($is_single) {
  7737. $episode_exists = DB::table('mp_anime_episodes')
  7738. ->where('anime_id', $anime_id)
  7739. ->where('sequence', 1)
  7740. ->exists();
  7741. if ($episode_exists) {
  7742. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  7743. }
  7744. }
  7745. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7746. if ($prompt) {
  7747. $question .= "本次修改要求如下:\n{$prompt}";
  7748. }
  7749. // 提取文件内容
  7750. if ($file) {
  7751. $content = $this->extractFileContent($file);
  7752. if (!$content) {
  7753. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7754. }
  7755. } elseif ($script_id) {
  7756. $content = $this->getContentByScriptId($script_id);
  7757. if (!$content) {
  7758. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7759. }
  7760. } elseif ($bid) {
  7761. $content = $this->getContentByBid($bid);
  7762. if (!$content) {
  7763. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7764. }
  7765. } elseif ($content) {
  7766. $content = filterContent($content);
  7767. }else {
  7768. $content = filterContent(getProp($anime, 'content'));
  7769. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7770. $need_generate_content = true;
  7771. }
  7772. }
  7773. // 判断是否需要生成原文内容
  7774. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7775. // 如果需要生成原文内容,添加额外的要求
  7776. $content_generation_requirement = $need_generate_content
  7777. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7778. : "";
  7779. // 美术风格
  7780. $input_art_style = getProp($data, 'art_style');
  7781. if (!$input_art_style) {
  7782. $mappedArtStyle = getProp($anime, 'art_style');
  7783. }else {
  7784. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7785. }
  7786. if (!$mappedArtStyle) {
  7787. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7788. }else {
  7789. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7790. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7791. }else {
  7792. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7793. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7794. }
  7795. }
  7796. // 构建主体、场景和道具提示词
  7797. $extra_role_prompt = "\n";
  7798. $extra_scene_prompt = "\n";
  7799. $extra_prop_prompt = "\n";
  7800. $ref_products = []; // 参考资产
  7801. if ($extra_products) {
  7802. foreach($extra_products as $item) {
  7803. $product = getProp($item, 'product');
  7804. $product_name = getProp($item, 'product_name');
  7805. if ($product_name == '旁白') continue;
  7806. $ref_products[$product_name] = $item;
  7807. $pic_prompt = getProp($item, 'pic_prompt');
  7808. if ((int)$product === 1) {
  7809. // 拼接角色信息
  7810. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7811. } elseif ((int)$product === 2) {
  7812. // 拼接场景信息
  7813. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7814. } elseif ((int)$product === 3) {
  7815. // 拼接道具信息
  7816. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7817. }
  7818. }
  7819. // 优化提示词,融入剧本
  7820. if (!empty(trim($extra_role_prompt))) {
  7821. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7822. }
  7823. if (!empty(trim($extra_scene_prompt))) {
  7824. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7825. }
  7826. if (!empty(trim($extra_prop_prompt))) {
  7827. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7828. }
  7829. }
  7830. if ($anime_script_id && $is_single) {
  7831. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7832. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7833. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7834. }else {
  7835. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7836. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7837. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7838. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7839. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7840. {$extra_role_prompt}";
  7841. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7842. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7843. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7844. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7845. {$extra_scene_prompt}";
  7846. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7847. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7848. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7849. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7850. {$extra_prop_prompt}";
  7851. }
  7852. $system_message = ['role'=>'system', 'content'=>$is_single
  7853. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7854. 强制要求:
  7855. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7856. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7857. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7858. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7859. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7860. 普通要求:
  7861. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7862. $role_demo
  7863. $scene_demo
  7864. $prop_demo
  7865. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7866. 5.1片段分割逻辑(优先级从高到低):
  7867. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7868. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7869. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7870. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7871. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7872. - 片段数量格式为: 片段数量:8
  7873. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7874. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7875. 5.3分镜结构:每个分镜包含以下字段:
  7876. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7877. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7878. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7879. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7880. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7881. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7882. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7883. - 运镜:场景+画面描述+运镜
  7884. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7885. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7886. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7887. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7888. 6.{$mappedArtStyle_prompt}\n\n
  7889. 示例如下:\n
  7890. ###剧本名:西昆仑
  7891. ###故事梗概
  7892. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7893. ###剧本亮点
  7894. 亮点1:绝境奇药,生死一线
  7895. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7896. 亮点2:结拜兄妹,化解尴尬
  7897. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7898. 亮点3:纤发夺命,情愫暗涌
  7899. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7900. ###人物关系
  7901. 阿雪与梁萧之间存在兄妹之情。
  7902. ###核心矛盾
  7903. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7904. ###主体列表
  7905. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7906. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7907. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7908. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7909. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7910. 全景,正面拍摄,青年女性,亚洲人。
  7911. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7912. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7913. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7914. ###美术风格
  7915. 基础画风风格词:厚涂古风
  7916. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7917. ###场景列表
  7918. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7919. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7920. 无人物。}
  7921. ###分段剧本
  7922. 片段数量:8
  7923. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7924. ##片段1
  7925. 时长:12s
  7926. 分镜1
  7927. 出场角色:刀疤脸
  7928. 场景:边境小镇街道
  7929. 出场道具:酒杯-高脚杯
  7930. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7931. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7932. 配音台词:
  7933. 背景音效:
  7934. 分镜2
  7935. 出场角色:刀疤脸
  7936. 场景:悦来酒馆
  7937. 出场道具:酒杯-高脚杯
  7938. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7939. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7940. 配音台词:
  7941. 背景音效:
  7942. 分镜3
  7943. 出场角色:刀疤脸
  7944. 场景:悦来酒馆
  7945. 出场道具:酒杯-高脚杯
  7946. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7947. 运镜:从中景推向令牌特写。
  7948. 配音台词:
  7949. 背景音效:
  7950. 分镜4
  7951. 出场角色:刀疤脸
  7952. 场景:悦来酒馆
  7953. 出场道具:酒杯-高脚杯
  7954. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7955. 运镜:极速推向酒水溅起的瞬间。
  7956. 配音台词:
  7957. 背景音效:
  7958. 分镜5
  7959. 出场角色:刀疤脸
  7960. 场景:悦来酒馆
  7961. 出场道具:酒杯-高脚杯
  7962. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7963. 运镜:固定机位,利用倾斜构图制造压迫感。
  7964. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7965. 背景音效:
  7966. \n\n"
  7967. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7968. 强制要求:\n
  7969. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7970. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7971. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7972. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7973. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7974. 普通要求:\n
  7975. 1.剧本名(必须生成)必须与文档内容高度相关
  7976. $role_demo
  7977. $scene_demo
  7978. $prop_demo
  7979. 5.{$mappedArtStyle_prompt}\n\n
  7980. 示例如下:\n
  7981. ###剧本名:西昆仑
  7982. ###故事梗概
  7983. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7984. ###剧本亮点
  7985. 亮点1:绝境奇药,生死一线
  7986. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7987. 亮点2:结拜兄妹,化解尴尬
  7988. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7989. 亮点3:纤发夺命,情愫暗涌
  7990. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7991. ###人物关系
  7992. 阿雪与梁萧之间存在兄妹之情。
  7993. ###核心矛盾
  7994. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7995. ###主体列表
  7996. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7997. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7998. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7999. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8000. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8001. 全景,正面拍摄,青年女性,亚洲人。
  8002. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8003. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8004. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8005. ###美术风格
  8006. 基础画风风格词:厚涂古风
  8007. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8008. ###场景列表
  8009. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8010. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8011. 无人物。}
  8012. ###道具列表
  8013. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  8014. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  8015. $episode_count = $this->extractEpisodeNumber($prompt);
  8016. if ((int)getProp($anime, 'is_multi') !== 1) {
  8017. yield [
  8018. 'type' => 'done',
  8019. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  8020. 'reasoning' => '',
  8021. 'usage' => []
  8022. ];
  8023. return;
  8024. }
  8025. if ($episode_count) {
  8026. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  8027. $system_message = [
  8028. 'role' => 'system',
  8029. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8030. 强制要求:\n
  8031. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8032. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8033. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8034. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  8035. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  8036. 普通要求:\n
  8037. 1.<故事梗概>控制在200-300字左右
  8038. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8039. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8040. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  8041. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8042. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8043. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8044. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8045. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8046. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  8047. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  8048. 示例如下:\n
  8049. ###剧本名:西昆仑
  8050. ###故事梗概
  8051. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8052. ###剧本亮点
  8053. 亮点1:绝境奇药,生死一线
  8054. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  8055. 亮点2:结拜兄妹,化解尴尬
  8056. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  8057. 亮点3:纤发夺命,情愫暗涌
  8058. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  8059. ###人物关系
  8060. 阿雪与梁萧之间存在兄妹之情。
  8061. ###核心矛盾
  8062. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  8063. ###主体列表
  8064. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  8065. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  8066. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  8067. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  8068. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  8069. 全景,正面拍摄,青年女性,亚洲人。
  8070. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  8071. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  8072. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8073. ###美术风格
  8074. 基础画风风格词:厚涂古风
  8075. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  8076. ###场景列表
  8077. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  8078. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  8079. 无人物。}
  8080. ###分集详细内容
  8081. ##第1章 重生
  8082. 我重生了。
  8083. 源于一个男人偏执的暗恋。
  8084. ##第2章 相救
  8085. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  8086. 我眼睛扫向站在锅炉后的卞大伟。"
  8087. ];
  8088. // 构建消息
  8089. $messages = [
  8090. $system_message,
  8091. [
  8092. 'role' => 'user',
  8093. 'content' => "以下是文档内容:
  8094. {$content}
  8095. 用户问题:
  8096. {$question}"
  8097. ]
  8098. ];
  8099. }else {
  8100. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  8101. // 构建消息
  8102. $messages = [
  8103. $system_message,
  8104. [
  8105. 'role' => 'user',
  8106. 'content' => "以下是文档内容:
  8107. {$content}
  8108. 用户问题:
  8109. {$question}"
  8110. ]
  8111. ];
  8112. }else {
  8113. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  8114. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  8115. return (array)$value;
  8116. })->toArray();
  8117. array_unshift($messages, $system_message);
  8118. $messages[] = [
  8119. 'role' => 'user',
  8120. 'content' => $prompt
  8121. ];
  8122. }
  8123. }
  8124. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8125. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  8126. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8127. if ($model === 'deepseek-chat') {
  8128. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8129. $model = 'deepseek-v4-flash';
  8130. $thinkingMode = 'disabled';
  8131. } elseif ($model === 'deepseek-reasoner') {
  8132. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8133. $model = 'deepseek-v4-flash';
  8134. $thinkingMode = 'enabled';
  8135. }
  8136. $post_data = [
  8137. 'model' => $model,
  8138. 'messages' => $messages,
  8139. // 'max_tokens' => 8192,
  8140. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8141. 'frequency_penalty' => 0,
  8142. 'presence_penalty' => 0,
  8143. 'response_format' => ['type' => 'text'],
  8144. 'thinking' => ['type' => $thinkingMode],
  8145. 'stream' => true // 启用流式输出
  8146. ];
  8147. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8148. // 根据模型类型选择调用方法
  8149. $fullContent = '';
  8150. $fullReasoningContent = '';
  8151. $usage = [];
  8152. // dd($post_data);
  8153. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  8154. try {
  8155. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8156. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8157. } else if (in_array($model, $this->gpt_text_models)) {
  8158. // GPT-5.4 模型使用 TokenRouter API
  8159. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8160. } else if (in_array($model, $this->gemini_text_models)) {
  8161. // Gemini 模型使用 Gemini API
  8162. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8163. } else {
  8164. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8165. }
  8166. // 验证返回值类型
  8167. if (!is_iterable($streamGenerator)) {
  8168. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8169. dLog('deepseek')->error('方法名流式生成器无效', [
  8170. 'generator_type' => $errorType,
  8171. 'model' => $model,
  8172. // 添加其他上下文信息
  8173. ]);
  8174. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  8175. 'type' => $errorType,
  8176. 'model' => $model
  8177. ]);
  8178. yield [
  8179. 'type' => 'error',
  8180. // 根据方法返回相应的空数据结构
  8181. 'answer' => '',
  8182. 'reasoning' => '',
  8183. 'usage' => [],
  8184. 'error' => '接口返回数据异常,请重新请求'
  8185. ];
  8186. return;
  8187. }
  8188. // 处理流式输出
  8189. foreach ($streamGenerator as $chunk) {
  8190. if (isset($chunk['type'])) {
  8191. if ($chunk['type'] === 'done') {
  8192. $fullContent = $chunk['full_content'];
  8193. $fullReasoningContent = $chunk['full_reasoning'];
  8194. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8195. } else {
  8196. yield $chunk;
  8197. }
  8198. }
  8199. }
  8200. } catch (\Exception $e) {
  8201. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  8202. 'model' => $model,
  8203. 'trace' => $e->getTraceAsString()
  8204. ]);
  8205. logDB('deepseek', 'error', '方法名流式处理失败', [
  8206. 'error' => $e->getMessage(),
  8207. 'model' => $model
  8208. ]);
  8209. yield [
  8210. 'type' => 'error',
  8211. // 根据方法返回相应的空数据结构
  8212. 'answer' => '',
  8213. 'reasoning' => '',
  8214. 'usage' => [],
  8215. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8216. ];
  8217. return;
  8218. }
  8219. dLog('deepseek')->info('完整内容: '.$fullContent);
  8220. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8221. // 处理完整内容并返回最终结果
  8222. $script_arr = [];
  8223. if ($fullContent) {
  8224. $script_arr = handleScriptContentForAce($fullContent);
  8225. dLog('deepseek')->info('解析内容', $script_arr);
  8226. logDB('deepseek', 'info', '解析内容', $script_arr);
  8227. }
  8228. if (empty($script_arr['roles'])) {
  8229. // 未生成剧本相关内容,保存对话记录并返回提示
  8230. dLog('deepseek')->info('未生成剧本相关的内容');
  8231. try {
  8232. $now = date('Y-m-d H:i:s');
  8233. // 保存对话记录
  8234. $records = [
  8235. [
  8236. 'uid' => $uid,
  8237. 'anime_id' => $anime_id,
  8238. 'sequence' => 0,
  8239. 'role' => 'user',
  8240. 'content' => $prompt,
  8241. 'created_at' => $now,
  8242. 'updated_at' => $now
  8243. ],
  8244. [
  8245. 'uid' => $uid,
  8246. 'anime_id' => $anime_id,
  8247. 'sequence' => 0,
  8248. 'role' => 'assistant',
  8249. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  8250. 'created_at' => $now,
  8251. 'updated_at' => $now
  8252. ]
  8253. ];
  8254. DB::table('mp_anime_records')->insert($records);
  8255. } catch (\Exception $e) {
  8256. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8257. }
  8258. yield [
  8259. 'type' => 'done',
  8260. 'script' => [],
  8261. 'episode' => [],
  8262. 'answer' => $fullContent,
  8263. 'reasoning' => $fullReasoningContent,
  8264. 'usage' => $usage,
  8265. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  8266. ];
  8267. return;
  8268. }
  8269. // 替换美术风格
  8270. if ($mappedArtStyle !== '') {
  8271. $script_arr['art_style'] = $mappedArtStyle;
  8272. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  8273. }
  8274. if ($user_anime_name != '新剧本策划') {
  8275. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  8276. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  8277. // 确认对话名称唯一性
  8278. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  8279. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  8280. }
  8281. }else {
  8282. $anime_name = $user_anime_name;
  8283. }
  8284. $table_data = [
  8285. 'user_id' => $uid,
  8286. 'model' => $model,
  8287. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  8288. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  8289. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  8290. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  8291. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  8292. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  8293. 'art_style_type' => $input_art_style,
  8294. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  8295. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  8296. 'status' => '解析完成',
  8297. 'generate_status' => '待执行',
  8298. 'updated_at' => date('Y-m-d H:i:s')
  8299. ];
  8300. if ($anime_name) $table_data['anime_name'] = $anime_name;
  8301. // 如果是修改集数,则将content内容更新(会改变原文)
  8302. if (isset($episode_count) && $episode_count > 0) {
  8303. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  8304. $table_data['start_episode_sequence'] = 1;
  8305. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  8306. }else {
  8307. // 如果需要生成原文内容,从script_arr中提取
  8308. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  8309. $table_data['content'] = $script_arr['content'];
  8310. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  8311. if (!$table_data['content']) {
  8312. yield [
  8313. 'type' => 'done',
  8314. 'script' => [],
  8315. 'episode' => [],
  8316. 'answer' => $fullContent,
  8317. 'reasoning' => $fullReasoningContent,
  8318. 'usage' => $usage,
  8319. 'error' => '未生成剧本内容,请调整提示词再试'
  8320. ];
  8321. return;
  8322. }
  8323. }
  8324. if (isset($table_data['content']) && $table_data['content']) {
  8325. $chapters = splitContent($table_data['content']);
  8326. $chapter_count = count($chapters);
  8327. if ($chapter_count > 0) {
  8328. $table_data['start_episode_sequence'] = 1;
  8329. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  8330. }
  8331. }
  8332. }
  8333. if ($extra_products) {
  8334. $table_data['extra_products'] = json_encode($extra_products, 256);
  8335. }
  8336. $single_episode = [];
  8337. try {
  8338. DB::beginTransaction();
  8339. $now = date('Y-m-d H:i:s');
  8340. // 更新动漫大纲
  8341. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  8342. if (!$boolen) {
  8343. dLog('deepseek')->info('对话修改失败', $table_data);
  8344. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  8345. Utils::throwError('20003:对话修改失败');
  8346. }
  8347. // 保存对话记录
  8348. $records = [
  8349. [
  8350. 'uid' => $uid,
  8351. 'anime_id' => $anime_id,
  8352. 'sequence' => 0,
  8353. 'role' => 'user',
  8354. 'content' => $prompt,
  8355. 'created_at' => $now,
  8356. 'updated_at' => $now
  8357. ],
  8358. [
  8359. 'uid' => $uid,
  8360. 'anime_id' => $anime_id,
  8361. 'sequence' => 0,
  8362. 'role' => 'assistant',
  8363. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8364. 'content' => $fullContent,
  8365. 'created_at' => $now,
  8366. 'updated_at' => $now
  8367. ]
  8368. ];
  8369. // 保存对话记录
  8370. $boolen3 = DB::table('mp_anime_records')->insert($records);
  8371. if (!$boolen3) {
  8372. Utils::throwError('20003:对话记录保存失败');
  8373. }
  8374. // 单剧集模式:生成并保存剧集信息
  8375. if ($is_single) {
  8376. $anime_name = getProp($anime, 'anime_name', '未命名');
  8377. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  8378. if (empty($episode_arr['acts'])) {
  8379. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  8380. }
  8381. $saveResult = $this->saveEpisodeVersionData(
  8382. $anime_id,
  8383. 1,
  8384. $episode_arr,
  8385. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8386. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8387. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  8388. null,
  8389. null,
  8390. false,
  8391. $content,
  8392. $now,
  8393. $ref_products
  8394. );
  8395. $single_episode = $saveResult['episode'];
  8396. $episode_id = $saveResult['episode_id'];
  8397. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  8398. 'roles' => json_encode($saveResult['merged_roles'], 256),
  8399. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  8400. 'props' => json_encode($saveResult['merged_props'], 256),
  8401. 'updated_at' => $now
  8402. ]);
  8403. if ($boolen5 === false) {
  8404. Utils::throwError('20003:单剧集主表资源同步失败');
  8405. }
  8406. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  8407. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  8408. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  8409. $episode_record_content = '确认分镜大纲';
  8410. if ($content !== '') {
  8411. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  8412. }
  8413. $episode_records = [
  8414. [
  8415. 'uid' => $uid,
  8416. 'anime_id' => $anime_id,
  8417. 'role' => 'user',
  8418. 'content' => $episode_record_content,
  8419. 'sequence' => 1,
  8420. 'episode_id' => $episode_id,
  8421. 'created_at' => $now,
  8422. 'updated_at' => $now
  8423. ],
  8424. [
  8425. 'uid' => $uid,
  8426. 'anime_id' => $anime_id,
  8427. 'role' => 'assistant',
  8428. 'content' => $fullContent,
  8429. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8430. 'sequence' => 1,
  8431. 'episode_id' => $episode_id,
  8432. 'created_at' => $now,
  8433. 'updated_at' => $now
  8434. ]
  8435. ];
  8436. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  8437. if (!$boolen4) {
  8438. Utils::throwError('20003:单剧集分镜记录保存失败');
  8439. }
  8440. }
  8441. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8442. if ($is_single && !empty($single_episode)) {
  8443. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8444. 'anime_id' => $anime_id,
  8445. 'episode_id' => $episode_id ?? 0,
  8446. 'model' => $model,
  8447. 'source' => 'reGenerateAnimeForAce',
  8448. ]);
  8449. }
  8450. }catch (\Exception $e) {
  8451. DB::rollBack();
  8452. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  8453. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  8454. yield [
  8455. 'type' => 'done',
  8456. 'answer' => $fullContent,
  8457. 'reasoning' => $fullReasoningContent,
  8458. 'usage' => $usage,
  8459. 'error' => $e->getMessage(),
  8460. ];
  8461. return;
  8462. }
  8463. DB::commit();
  8464. dLog('deepseek')->info('保存完毕');
  8465. if ($is_single && !empty($single_episode)) {
  8466. // $this->batchSetGlobalRoleImg([
  8467. // 'anime_id' => $anime_id,
  8468. // ]);
  8469. // $this->batchSetGlobalSceneImg([
  8470. // 'anime_id' => $anime_id,
  8471. // ]);
  8472. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8473. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8474. }
  8475. $table_data['anime_id'] = $anime_id;
  8476. $table_data['roles'] = json_decode($table_data['roles'], true);
  8477. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  8478. $table_data['props'] = json_decode($table_data['props'], true);
  8479. unset($table_data['updated_at']);
  8480. unset($table_data['status']);
  8481. yield [
  8482. 'type' => 'done',
  8483. 'script' => $table_data,
  8484. 'episode' => $single_episode,
  8485. 'answer' => $fullContent,
  8486. 'reasoning' => $fullReasoningContent,
  8487. 'usage' => $usage
  8488. ];
  8489. }
  8490. public function chatForAce($data) {
  8491. $uid = Site::getUid();
  8492. // 积分余额预检(不足直接报错)
  8493. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  8494. $anime_id = getProp($data, 'anime_id');
  8495. $file = getProp($data, 'file');
  8496. $content = getProp($data, 'content', '');
  8497. $bid = getProp($data, 'bid', 0);
  8498. $script_id = getProp($data, 'script_id', 0);
  8499. $episode_number = getProp($data, 'episode_number', 1);
  8500. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8501. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8502. if (!$anime) Utils::throwError('20003:该对话不存在!');
  8503. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  8504. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  8505. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  8506. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  8507. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  8508. $roles = is_array($roles) ? $roles : [];
  8509. $scenes = is_array($scenes) ? $scenes : [];
  8510. $extra_products = getProp($data, 'products', []);
  8511. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  8512. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  8513. $anime_script_id = getProp($anime, 'script_id');
  8514. if ($anime_script_id) {
  8515. $cpid = Site::getCpid();
  8516. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  8517. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  8518. ->where('mapping.script_id', $anime_script_id)
  8519. ->where('product.cpid', $cpid)
  8520. ->where('product.is_deleted', 0);
  8521. // 如果提供了 episode_number,则过滤指定集数
  8522. if ($episode_number !== null && $episode_number !== '') {
  8523. $script_products_mappings->where('mapping.episode_number', $episode_number);
  8524. }
  8525. $mappings = $script_products_mappings->select(
  8526. 'mapping.product_id',
  8527. 'mapping.episode_number',
  8528. 'product.product_name',
  8529. 'product.type',
  8530. 'product.product',
  8531. 'product.pic_prompt',
  8532. 'product.url',
  8533. 'product.pic_task_id',
  8534. 'product.pic_task_status',
  8535. 'product.three_view_image_url'
  8536. )
  8537. ->get();
  8538. // 按 product_id 分组,合并 episode_number
  8539. $productMap = [];
  8540. foreach ($mappings as $item) {
  8541. $product_id = $item->product_id;
  8542. $product_name = $item->product_name;
  8543. // 处理product_name两边的符号
  8544. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8545. if (!isset($productMap[$product_id])) {
  8546. $productMap[$product_id] = [
  8547. 'product_id' => $product_id,
  8548. 'product_name' => $product_name,
  8549. 'type' => (int)$item->type,
  8550. 'product' => (int)$item->product,
  8551. 'pic_prompt' => $item->pic_prompt,
  8552. 'url' => $item->url,
  8553. 'pic_task_id' => $item->pic_task_id,
  8554. 'pic_task_status' => $item->pic_task_status,
  8555. 'episode_numbers' => [],
  8556. ];
  8557. }
  8558. // 添加 episode_number(去重)
  8559. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8560. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8561. }
  8562. }
  8563. // 将查询到的剧本资产合并到extra_products中
  8564. // 先构建extra_products的索引(以product_id+episode_number为key)
  8565. $extraProductsMap = [];
  8566. foreach ($extra_products as $item) {
  8567. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  8568. $extraProductsMap[$key] = $item;
  8569. }
  8570. // 合并剧本资产(去重:product_id+episode_number)
  8571. foreach ($productMap as $product) {
  8572. foreach ($product['episode_numbers'] as $ep_num) {
  8573. $key = $product['product_id'] . '_' . $ep_num;
  8574. // 如果不存在则添加
  8575. if (!isset($extraProductsMap[$key])) {
  8576. $extraProductsMap[$key] = [
  8577. 'product_id' => $product['product_id'],
  8578. 'product_name' => $product['product_name'],
  8579. 'type' => $product['type'],
  8580. 'product' => $product['product'],
  8581. 'pic_prompt' => $product['pic_prompt'],
  8582. 'url' => $product['url'],
  8583. 'pic_task_id' => $product['pic_task_id'],
  8584. 'pic_task_status' => $product['pic_task_status'],
  8585. 'episode_number' => $ep_num,
  8586. ];
  8587. }
  8588. }
  8589. }
  8590. // 重新赋值给extra_products
  8591. $extra_products = array_values($extraProductsMap);
  8592. }
  8593. // 处理提示词
  8594. if ($prompt && $extra_products) {
  8595. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8596. foreach($extra_products as $item) {
  8597. $product_name = getProp($item, 'product_name');
  8598. if ($product_name) {
  8599. // 替换 {product_name} 为 product_name
  8600. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8601. }
  8602. }
  8603. }
  8604. // 获取最后一集序号
  8605. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  8606. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  8607. // 转换主体列表和场景列表的格式
  8608. // 获取参考主体或场景
  8609. if ((int)$episode_number === 1) {
  8610. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  8611. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  8612. }else {
  8613. $prev_episode_number = $episode_number - 1;
  8614. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  8615. }
  8616. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  8617. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  8618. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  8619. // 合并anime_products和extra_products(extra_products优先,去重)
  8620. $anime_products = getProp($anime, 'extra_products');
  8621. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  8622. $ref_products = [];
  8623. foreach($anime_products as $item) {
  8624. $product_name = getProp($item, 'product_name');
  8625. $ref_products[$product_name] = $item;
  8626. }
  8627. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  8628. $extra_roles = []; // 从extra_products中提取的角色
  8629. $extra_scenes = []; // 从extra_products中提取的场景
  8630. $extra_props = []; // 从extra_products中提取的道具
  8631. if ($extra_products && is_array($extra_products)) {
  8632. foreach($extra_products as $item) {
  8633. $product = (int)getProp($item, 'product');
  8634. $product_name = getProp($item, 'product_name');
  8635. if ($product_name == '旁白') continue;
  8636. $pic_prompt = getProp($item, 'pic_prompt');
  8637. $ref_products[$product_name] = $item;
  8638. if ($product === 1) {
  8639. // 角色
  8640. $extra_roles[$product_name] = [
  8641. 'role' => $product_name,
  8642. 'pic_prompt' => $pic_prompt,
  8643. 'url' => getProp($item, 'url', ''),
  8644. ];
  8645. } elseif ($product === 2) {
  8646. // 场景
  8647. $extra_scenes[$product_name] = [
  8648. 'scene' => $product_name,
  8649. 'pic_prompt' => $pic_prompt,
  8650. 'url' => getProp($item, 'url', ''),
  8651. ];
  8652. } elseif ($product === 3) {
  8653. // 道具
  8654. $extra_props[$product_name] = [
  8655. 'prop' => $product_name,
  8656. 'pic_prompt' => $pic_prompt,
  8657. 'url' => getProp($item, 'url', ''),
  8658. ];
  8659. }
  8660. }
  8661. }
  8662. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  8663. $merged_roles = [];
  8664. foreach($ref_roles as $role) {
  8665. $role_name = getProp($role, 'role');
  8666. if (!isset($extra_roles[$role_name])) {
  8667. $merged_roles[$role_name] = $role;
  8668. }
  8669. }
  8670. // 添加extra_roles
  8671. foreach($extra_roles as $role_name => $role) {
  8672. $merged_roles[$role_name] = $role;
  8673. }
  8674. $ref_roles = array_values($merged_roles);
  8675. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  8676. $merged_scenes = [];
  8677. foreach($ref_scenes as $scene) {
  8678. $scene_name = getProp($scene, 'scene');
  8679. if (!isset($extra_scenes[$scene_name])) {
  8680. $merged_scenes[$scene_name] = $scene;
  8681. }
  8682. }
  8683. // 添加extra_scenes
  8684. foreach($extra_scenes as $scene_name => $scene) {
  8685. $merged_scenes[$scene_name] = $scene;
  8686. }
  8687. $ref_scenes = array_values($merged_scenes);
  8688. // 合并ref_props和extra_props(extra_props优先,去重)
  8689. $merged_props = [];
  8690. foreach($ref_props as $prop) {
  8691. $prop_name = getProp($prop, 'prop');
  8692. if (!isset($extra_props[$prop_name])) {
  8693. $merged_props[$prop_name] = $prop;
  8694. }
  8695. }
  8696. // 添加extra_props
  8697. foreach($extra_props as $prop_name => $prop) {
  8698. $merged_props[$prop_name] = $prop;
  8699. }
  8700. $ref_props = array_values($merged_props);
  8701. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  8702. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  8703. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  8704. // 构建强制主体、场景和道具提示词
  8705. $forced_roles_prompt = "";
  8706. $forced_scenes_prompt = "";
  8707. $forced_props_prompt = "";
  8708. if (!empty($extra_roles)) {
  8709. $forced_roles_list = "";
  8710. foreach($extra_roles as $role_name => $role) {
  8711. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  8712. }
  8713. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  8714. }
  8715. if (!empty($extra_scenes)) {
  8716. $forced_scenes_list = "";
  8717. foreach($extra_scenes as $scene_name => $scene) {
  8718. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  8719. }
  8720. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  8721. }
  8722. if (!empty($extra_props)) {
  8723. $forced_props_list = "";
  8724. foreach($extra_props as $prop_name => $prop) {
  8725. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  8726. }
  8727. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  8728. }
  8729. if ($anime_script_id) {
  8730. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  8731. }else if ($roles_content) {
  8732. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  8733. 主体范围:\n {$roles_content}\n
  8734. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  8735. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8736. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8737. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8738. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8739. }else {
  8740. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8741. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8742. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8743. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8744. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8745. }
  8746. if ($anime_script_id) {
  8747. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  8748. }else if ($scenes_content) {
  8749. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8750. 场景范围:\n {$scenes_content}\n
  8751. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  8752. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  8753. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8754. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8755. }else {
  8756. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8757. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8758. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8759. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8760. }
  8761. if ($anime_script_id) {
  8762. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  8763. }else if ($props_content) {
  8764. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8765. 道具范围:\n {$props_content}\n
  8766. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  8767. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  8768. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8769. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8770. }else {
  8771. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8772. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  8773. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8774. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8775. }
  8776. // 提取文件内容
  8777. if ($file) {
  8778. $uploaded_content = $this->extractFileContent($file);
  8779. if (!$uploaded_content) {
  8780. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8781. }
  8782. } elseif ($script_id) {
  8783. $uploaded_content = $this->getContentByScriptId($script_id);
  8784. if (!$uploaded_content) {
  8785. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  8786. }
  8787. } elseif ($bid) {
  8788. $uploaded_content = $this->getContentByBid($bid);
  8789. if (!$uploaded_content) {
  8790. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  8791. }
  8792. } elseif ($content) {
  8793. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  8794. }
  8795. // elseif ($prompt) {
  8796. // $uploaded_content = filterContent($prompt);
  8797. // }
  8798. else {
  8799. $uploaded_content = '';
  8800. }
  8801. // 美术风格
  8802. $input_art_style = getProp($data, 'art_style');
  8803. if (!$input_art_style) {
  8804. $mappedArtStyle = getProp($anime, 'art_style');
  8805. }else {
  8806. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  8807. }
  8808. if (!$mappedArtStyle) {
  8809. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  8810. }else {
  8811. if (strstr($mappedArtStyle, '基础画风风格词')) {
  8812. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  8813. }else {
  8814. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  8815. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  8816. }
  8817. }
  8818. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8819. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8820. // 强制要求:
  8821. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8822. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8823. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8824. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  8825. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  8826. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  8827. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  8828. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  8829. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  8830. // 10.分镜要和场景列表、人物主体保持一致\n
  8831. // 普通要求:
  8832. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8833. // {$role_demo}
  8834. // {$scene_demo}
  8835. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8836. // 4.1片段分割逻辑(优先级从高到低):
  8837. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8838. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8839. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8840. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8841. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8842. // - 片段数量格式为: 片段数量:8
  8843. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8844. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8845. // 4.3分镜结构:每个分镜包含以下字段:
  8846. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  8847. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  8848. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8849. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  8850. // - 运镜:场景+画面描述+运镜
  8851. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  8852. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8853. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8854. // 5.$mappedArtStyle_prompt\n\n
  8855. // 示例格式:\n
  8856. // 第1集:隐形的守护者
  8857. // ###故事梗概
  8858. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8859. // ###美术风格
  8860. // 基础画风风格词:胡金铨武侠
  8861. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8862. // ###主体列表
  8863. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8864. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8865. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8866. // ###场景列表
  8867. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8868. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8869. // ###分段剧本
  8870. // 片段数量:8
  8871. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8872. // ##片段1
  8873. // 时长:12s
  8874. // 分镜1
  8875. // 场景:边境小镇街道
  8876. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8877. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8878. // 配音台词:
  8879. // 背景音效:
  8880. // 分镜2
  8881. // 场景:悦来酒馆
  8882. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8883. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8884. // 配音台词:
  8885. // 背景音效:
  8886. // 分镜3
  8887. // 场景:悦来酒馆
  8888. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8889. // 运镜:从中景推向令牌特写。
  8890. // 配音台词:
  8891. // 背景音效:
  8892. // 分镜4
  8893. // 场景:悦来酒馆
  8894. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8895. // 运镜:极速推向酒水溅起的瞬间。
  8896. // 配音台词:
  8897. // 背景音效:
  8898. // 分镜5
  8899. // 镜头描述
  8900. // 场景:悦来酒馆
  8901. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8902. // 运镜:固定机位,利用倾斜构图制造压迫感。
  8903. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8904. // 背景音效:
  8905. // \n\n";
  8906. /*
  8907. // ====== 旧版 $demo(缓存优化前版本,动态数据内嵌在规则中间) ======
  8908. // 如需换回:删除下方新版 $demo,并把本块恢复为活动代码(去掉首尾注释标记)
  8909. // ===================================================================
  8910. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  8911. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  8912. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  8913. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  8914. 强制要求:
  8915. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  8916. 普通要求:
  8917. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8918. {$role_demo}
  8919. {$scene_demo}
  8920. {$prop_demo}
  8921. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8922. 5.1片段分割逻辑(优先级从高到低):
  8923. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8924. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8925. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8926. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8927. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8928. - 片段数量格式为: 片段数量:8
  8929. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8930. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8931. 5.3分镜结构:每个分镜包含以下字段:
  8932. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8933. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8934. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8935. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8936. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8937. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8938. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8939. - 运镜:场景+画面描述+运镜
  8940. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8941. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8942. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8943. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8944. 6.《情绪-视听语言映射表》:
  8945. 6.1 场景空间与时间心理学 (Scene & Temporality)
  8946. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8947. -----|---------|------------|----------------
  8948. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  8949. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  8950. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  8951. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  8952. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  8953. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8954. -----|---------|------------|----------------
  8955. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  8956. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  8957. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  8958. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  8959. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  8960. --------|---------|--------------|-------------
  8961. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  8962. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  8963. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  8964. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  8965. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  8966. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  8967. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  8968. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  8969. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  8970. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  8971. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  8972. -----|---------|------------|------------
  8973. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  8974. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  8975. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  8976. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  8977. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  8978. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  8979. --------|---------|--------------|----------
  8980. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  8981. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  8982. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  8983. 6.6 声音设计与潜意识影响 (Soundscape)
  8984. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  8985. -----|---------|------------|------------------
  8986. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  8987. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  8988. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  8989. 理论基石:
  8990. - The Five C's of Cinematography by Joseph V. Mascelli
  8991. - Film Art: An Introduction by David Bordwell
  8992. - Sight, Sound, Motion by Herbert Zettl
  8993. - Notes on the Cinematograph by Robert Bresson
  8994. \n\n
  8995. 7.{$mappedArtStyle_prompt}
  8996. 示例格式:\n
  8997. 第1集:隐形的守护者
  8998. ###故事梗概
  8999. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9000. ###美术风格
  9001. 基础画风风格词:胡金铨武侠
  9002. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  9003. ###主体列表
  9004. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9005. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  9006. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  9007. ###场景列表
  9008. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  9009. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  9010. ###道具列表
  9011. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  9012. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  9013. ###分段剧本
  9014. 片段数量:8
  9015. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9016. ##片段1
  9017. 时长:12s
  9018. 分镜1
  9019. 出场角色:刀疤脸
  9020. 场景:边境小镇街道
  9021. 出场道具:酒杯-高脚杯
  9022. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9023. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9024. 配音台词:
  9025. 背景音效:
  9026. 分镜2
  9027. 出场角色:刀疤脸
  9028. 场景:悦来酒馆
  9029. 出场道具:酒杯-高脚杯
  9030. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9031. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9032. 配音台词:
  9033. 背景音效:
  9034. 分镜3
  9035. 出场角色:刀疤脸
  9036. 场景:悦来酒馆
  9037. 出场道具:酒杯-高脚杯
  9038. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9039. 运镜:从中景推向令牌特写。
  9040. 配音台词:
  9041. 背景音效:
  9042. 分镜4
  9043. 出场角色:刀疤脸
  9044. 场景:悦来酒馆
  9045. 出场道具:酒杯-高脚杯
  9046. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9047. 运镜:极速推向酒水溅起的瞬间。
  9048. 配音台词:
  9049. 背景音效:
  9050. 分镜5
  9051. 出场角色:刀疤脸
  9052. 场景:悦来酒馆
  9053. 出场道具:酒杯-高脚杯
  9054. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9055. 运镜:固定机位,利用倾斜构图制造压迫感。
  9056. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9057. 背景音效:
  9058. \n\n";
  9059. */
  9060. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  9061. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  9062. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  9063. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  9064. 强制要求:
  9065. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  9066. 普通要求:
  9067. 1.剧集标题必须与文档内容高度相关,剧集序号见文末【本次剧集信息】。
  9068. 2.<主体列表>的详细规则和可选范围见文末【本次生成数据-主体列表】。
  9069. 3.<场景列表>的详细规则和可选范围见文末【本次生成数据-场景列表】。
  9070. 4.<道具列表>的详细规则和可选范围见文末【本次生成数据-道具列表】。
  9071. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  9072. 5.1片段分割逻辑(优先级从高到低):
  9073. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  9074. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  9075. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  9076. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  9077. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  9078. - 片段数量格式为: 片段数量:8
  9079. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  9080. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  9081. 5.3分镜结构:每个分镜包含以下字段:
  9082. - 分镜设计原则: 所有分镜原则上优先以人物及人物间的对话为主(权重90%以上),场景或物品空境为辅,尽可能少出现无台词的分镜设计
  9083. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  9084. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9085. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9086. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9087. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  9088. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9089. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  9090. - 运镜:场景+画面描述+运镜
  9091. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  9092. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  9093. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容或“角色:”后的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  9094. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  9095. 6.《情绪-视听语言映射表》:
  9096. 6.1 场景空间与时间心理学 (Scene & Temporality)
  9097. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9098. -----|---------|------------|----------------
  9099. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  9100. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  9101. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  9102. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  9103. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  9104. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  9105. -----|---------|------------|----------------
  9106. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  9107. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  9108. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  9109. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  9110. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  9111. --------|---------|--------------|-------------
  9112. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  9113. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  9114. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  9115. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  9116. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  9117. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  9118. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  9119. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  9120. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  9121. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  9122. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  9123. -----|---------|------------|------------
  9124. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  9125. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  9126. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  9127. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  9128. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  9129. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  9130. --------|---------|--------------|----------
  9131. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  9132. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  9133. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  9134. 6.6 声音设计与潜意识影响 (Soundscape)
  9135. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  9136. -----|---------|------------|------------------
  9137. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  9138. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  9139. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  9140. 理论基石:
  9141. - The Five C's of Cinematography by Joseph V. Mascelli
  9142. - Film Art: An Introduction by David Bordwell
  9143. - Sight, Sound, Motion by Herbert Zettl
  9144. - Notes on the Cinematograph by Robert Bresson
  9145. \n\n
  9146. 7.美术风格要求见文末【本次生成数据-美术风格】。
  9147. 示例格式:\n
  9148. 第1集:隐形的守护者
  9149. ###故事梗概
  9150. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  9151. ###美术风格
  9152. 基础画风风格词:胡金铨武侠
  9153. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  9154. ###主体列表
  9155. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  9156. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  9157. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  9158. ###场景列表
  9159. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  9160. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  9161. ###道具列表
  9162. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  9163. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  9164. ###分段剧本
  9165. 片段数量:8
  9166. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9167. ##片段1
  9168. 时长:12s
  9169. 分镜1
  9170. 出场角色:刀疤脸
  9171. 场景:边境小镇街道
  9172. 出场道具:酒杯-高脚杯
  9173. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9174. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9175. 配音台词:
  9176. 背景音效:
  9177. 分镜2
  9178. 出场角色:刀疤脸
  9179. 场景:悦来酒馆
  9180. 出场道具:酒杯-高脚杯
  9181. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9182. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9183. 配音台词:
  9184. 背景音效:
  9185. 分镜3
  9186. 出场角色:刀疤脸
  9187. 场景:悦来酒馆
  9188. 出场道具:酒杯-高脚杯
  9189. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9190. 运镜:从中景推向令牌特写。
  9191. 配音台词:
  9192. 背景音效:
  9193. 分镜4
  9194. 出场角色:刀疤脸
  9195. 场景:悦来酒馆
  9196. 出场道具:酒杯-高脚杯
  9197. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9198. 运镜:极速推向酒水溅起的瞬间。
  9199. 配音台词:
  9200. 背景音效:
  9201. 分镜5
  9202. 出场角色:刀疤脸
  9203. 场景:悦来酒馆
  9204. 出场道具:酒杯-高脚杯
  9205. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9206. 运镜:固定机位,利用倾斜构图制造压迫感。
  9207. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9208. 背景音效:
  9209. \n\n本次生成数据(以上规则的动态数据均在此处,优先级等同对应编号规则):
  9210. 【本次剧集信息】剧集序号是{$episode_number}。
  9211. 【本次生成数据-主体列表】{$role_demo}
  9212. 【本次生成数据-场景列表】{$scene_demo}
  9213. 【本次生成数据-道具列表】{$prop_demo}
  9214. 【本次生成数据-美术风格】{$mappedArtStyle_prompt}
  9215. \n\n";
  9216. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  9217. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  9218. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  9219. $prompt = $origin_prompt;
  9220. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  9221. // 获取章节内容
  9222. $full_content = getProp($anime, 'content');
  9223. if ($uploaded_content) {
  9224. $full_content = $uploaded_content;
  9225. }
  9226. // 根据章节内容拆分章节
  9227. $chapters = splitContent($full_content);
  9228. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  9229. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  9230. $messages = [];
  9231. if ($prompt == '确认分镜大纲') {
  9232. // 暂时保留
  9233. $content = $chapter_content;
  9234. if ($is_single) $content = $full_content; // 单剧集使用全文
  9235. if (!$content) {
  9236. Utils::throwError('20003:章节内容无法获取,请确认');
  9237. }
  9238. $question = $is_single
  9239. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  9240. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  9241. // 构建消息
  9242. $messages[] =
  9243. [
  9244. 'role' => 'user',
  9245. 'content' => $question
  9246. ];
  9247. }else if ($prompt == '继续策划下一集') {
  9248. if ($is_single) {
  9249. Utils::throwError('20003:单剧集不支持继续策划下一集');
  9250. }
  9251. $content = $chapter_content;
  9252. if (!$content) {
  9253. Utils::throwError('20003:章节内容无法获取,请确认');
  9254. }
  9255. // 获取上一集最后记录
  9256. $prev_sequence = $episode_number - 1;
  9257. $messages = array_merge(
  9258. [
  9259. [
  9260. 'role' => 'system',
  9261. 'content' => $demo
  9262. ]
  9263. ],
  9264. $this->getEpisodeChatContent($anime_id, $prev_sequence, $content)
  9265. );
  9266. // 构建消息
  9267. $messages[] =
  9268. [
  9269. 'role' => 'user',
  9270. 'content' => "请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)"
  9271. ];
  9272. /*
  9273. // 旧版逻辑
  9274. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  9275. // 构建消息
  9276. $messages[] =
  9277. [
  9278. 'role' => 'user',
  9279. 'content' => $question
  9280. ];
  9281. */
  9282. // dd($messages);
  9283. }else {
  9284. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  9285. if (!$content) {
  9286. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  9287. }
  9288. if (!$content) {
  9289. Utils::throwError('20003:章节内容无法获取,请确认');
  9290. }
  9291. $messages = array_merge(
  9292. [
  9293. [
  9294. 'role' => 'system',
  9295. 'content' => $demo
  9296. ]
  9297. ],
  9298. $this->getEpisodeChatMessages($anime_id, $episode_number)
  9299. );
  9300. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  9301. $question = "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  9302. if ($origin_prompt) {
  9303. $question .= "本次修改要求如下:\n{$origin_prompt}";
  9304. }
  9305. // 将本集原文加入消息,供模型逐字摘录原文台词(修复重新生成时配音台词全部为"无"的问题)
  9306. $messages[] = [
  9307. 'role' => 'user',
  9308. 'content' => "本集剧情内容:\n\n{$content}\n"
  9309. ];
  9310. $messages[] =
  9311. [
  9312. 'role' => 'user',
  9313. 'content' => $question
  9314. ];
  9315. }
  9316. // 处理文本模型
  9317. $model = getProp($data, 'model');
  9318. if (!$model) {
  9319. // 用户没有输入,从anime表获取
  9320. $model = getProp($anime, 'model');
  9321. if (!$model) {
  9322. // anime表也没有,使用默认值
  9323. $model = 'deepseek-v4-pro';
  9324. }
  9325. }
  9326. // 验证模型是否在可用模型表中
  9327. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9328. $model = 'deepseek-v4-pro';
  9329. }
  9330. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  9331. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  9332. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  9333. if ($model === 'deepseek-chat') {
  9334. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  9335. $model = 'deepseek-v4-flash';
  9336. $thinkingMode = 'disabled';
  9337. } elseif ($model === 'deepseek-reasoner') {
  9338. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  9339. $model = 'deepseek-v4-flash';
  9340. $thinkingMode = 'enabled';
  9341. }
  9342. $post_data = [
  9343. 'model' => $model,
  9344. 'messages' => $messages,
  9345. // 'max_tokens' => 8192,
  9346. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9347. 'frequency_penalty' => 0,
  9348. 'presence_penalty' => 0,
  9349. 'response_format' => ['type' => 'text'],
  9350. 'thinking' => ['type' => $thinkingMode],
  9351. 'stream' => true // 启用流式输出
  9352. ];
  9353. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9354. // 根据模型类型选择调用方法
  9355. $fullContent = '';
  9356. $fullReasoningContent = '';
  9357. $usage = [];
  9358. try {
  9359. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9360. // DeepSeek 官方模型使用 DeepSeek API
  9361. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9362. } else if (in_array($model, $this->gpt_text_models)) {
  9363. // GPT-5.4 模型使用 TokenRouter API
  9364. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9365. } else if (in_array($model, $this->gemini_text_models)) {
  9366. // Gemini 模型使用 Gemini API
  9367. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9368. } else {
  9369. // 其他模型使用火山引擎API
  9370. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9371. }
  9372. // 验证返回值类型
  9373. if (!is_iterable($streamGenerator)) {
  9374. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  9375. dLog('deepseek')->error('chat流式生成器无效', [
  9376. 'generator_type' => $errorType,
  9377. 'model' => $model,
  9378. 'anime_id' => $anime_id,
  9379. 'episode_number' => $episode_number
  9380. ]);
  9381. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  9382. 'type' => $errorType,
  9383. 'model' => $model
  9384. ]);
  9385. yield [
  9386. 'type' => 'error',
  9387. 'episode' => [],
  9388. 'answer' => '',
  9389. 'reasoning' => '',
  9390. 'usage' => [],
  9391. 'error' => '接口返回数据异常,请重新请求'
  9392. ];
  9393. return;
  9394. }
  9395. // 处理流式输出
  9396. foreach ($streamGenerator as $chunk) {
  9397. if (isset($chunk['type'])) {
  9398. if ($chunk['type'] === 'done') {
  9399. // 最终结果
  9400. $fullContent = $chunk['full_content'];
  9401. $fullReasoningContent = $chunk['full_reasoning'];
  9402. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9403. } else {
  9404. // 逐块yield数据
  9405. yield $chunk;
  9406. }
  9407. }
  9408. }
  9409. } catch (\Exception $e) {
  9410. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  9411. 'model' => $model,
  9412. 'anime_id' => $anime_id,
  9413. 'episode_number' => $episode_number,
  9414. 'trace' => $e->getTraceAsString()
  9415. ]);
  9416. logDB('deepseek', 'error', 'chat流式处理失败', [
  9417. 'error' => $e->getMessage(),
  9418. 'model' => $model
  9419. ]);
  9420. yield [
  9421. 'type' => 'error',
  9422. 'episode' => [],
  9423. 'answer' => '',
  9424. 'reasoning' => '',
  9425. 'usage' => [],
  9426. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  9427. ];
  9428. return;
  9429. }
  9430. // 兼容模型偶发将整段正文包裹成 JSON 字符串返回
  9431. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9432. dLog('deepseek')->info('完整内容: '.$fullContent);
  9433. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  9434. // 处理完整内容并返回最终结果
  9435. $episode_arr = handleEpisodeContentForAce($fullContent);
  9436. dLog('deepseek')->info('解析内容: ', $episode_arr);
  9437. logDB('deepseek', 'info', '解析内容', $episode_arr);
  9438. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  9439. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  9440. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  9441. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  9442. // }
  9443. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  9444. $max_retries = 3;
  9445. $retry_count = 0;
  9446. $validation_failed = false;
  9447. $validation_error_msg = '';
  9448. // 验证生成的内容
  9449. if ($anime_script_id) {
  9450. // 检查是否有acts数据
  9451. if (empty($episode_arr['acts'])) {
  9452. $validation_failed = true;
  9453. $validation_error_msg = '未生成分镜剧本相关的内容';
  9454. } else {
  9455. // 校验主体列表:不能为空主体(旁白不算)
  9456. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9457. // 过滤掉"旁白"角色
  9458. $generated_roles = array_filter($generated_roles, function($role) {
  9459. return $role !== '旁白';
  9460. });
  9461. if (empty($generated_roles)) {
  9462. $validation_failed = true;
  9463. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9464. }
  9465. // 仅当存在强制主体设定时校验主体列表
  9466. if (!$validation_failed && !empty($extra_roles)) {
  9467. $expected_roles = array_keys($extra_roles);
  9468. // 找出生成的主体中不在预期列表中的主体
  9469. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9470. if (!empty($invalid_roles)) {
  9471. $validation_failed = true;
  9472. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9473. }
  9474. }
  9475. // 仅当存在强制场景设定时校验场景列表
  9476. if (!$validation_failed && !empty($extra_scenes)) {
  9477. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  9478. $expected_scenes = array_keys($extra_scenes);
  9479. // 找出生成的场景中不在预期列表中的场景
  9480. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9481. if (!empty($invalid_scenes)) {
  9482. $validation_failed = true;
  9483. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9484. }
  9485. }
  9486. // 仅当存在强制道具设定时校验道具列表
  9487. if (!$validation_failed && !empty($extra_props)) {
  9488. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9489. $expected_props = array_keys($extra_props);
  9490. // 找出生成的道具中不在预期列表中的道具
  9491. $invalid_props = array_diff($generated_props, $expected_props);
  9492. if (!empty($invalid_props)) {
  9493. $validation_failed = true;
  9494. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9495. }
  9496. }
  9497. }
  9498. } else {
  9499. // 如果没有anime_script_id,只检查是否有acts数据
  9500. if (empty($episode_arr['acts'])) {
  9501. $validation_failed = true;
  9502. $validation_error_msg = '未生成分镜剧本相关的内容';
  9503. } else {
  9504. // 校验主体列表:不能为空主体(旁白不算)
  9505. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9506. // 过滤掉"旁白"角色
  9507. $generated_roles = array_filter($generated_roles, function($role) {
  9508. return $role !== '旁白';
  9509. });
  9510. if (empty($generated_roles)) {
  9511. $validation_failed = true;
  9512. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9513. }
  9514. }
  9515. }
  9516. // 重试逻辑
  9517. while ($validation_failed && $retry_count < $max_retries) {
  9518. $retry_count++;
  9519. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  9520. 'reason' => $validation_error_msg,
  9521. 'anime_id' => $anime_id,
  9522. 'episode_number' => $episode_number
  9523. ]);
  9524. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  9525. 'reason' => $validation_error_msg,
  9526. 'anime_id' => $anime_id
  9527. ]);
  9528. // 发送流式重试提示
  9529. yield [
  9530. 'type' => 'retry',
  9531. 'retry_count' => $retry_count,
  9532. 'reason' => $validation_error_msg
  9533. ];
  9534. // 构建重试提示词
  9535. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  9536. if ($anime_script_id) {
  9537. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  9538. $retry_prompt .= "2. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9539. $retry_prompt .= "3. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  9540. $retry_prompt .= "4. 必须包含完整的分镜剧本内容\n";
  9541. } else {
  9542. $retry_prompt .= "1. 主体列表不能为空,必须至少包含一个非“旁白”的主体\n";
  9543. $retry_prompt .= "2. 必须包含完整的分镜剧本内容\n";
  9544. }
  9545. // 添加重试消息到messages
  9546. $messages[] = [
  9547. 'role' => 'assistant',
  9548. 'content' => $fullContent
  9549. ];
  9550. $messages[] = [
  9551. 'role' => 'user',
  9552. 'content' => $retry_prompt
  9553. ];
  9554. // 更新post_data的messages
  9555. $post_data['messages'] = $messages;
  9556. // 重新调用API
  9557. try {
  9558. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9559. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  9560. } else if (in_array($model, $this->gpt_text_models)) {
  9561. $streamGenerator = $this->gpt54StreamResponse($post_data);
  9562. } else if (in_array($model, $this->gemini_text_models)) {
  9563. // Gemini 模型使用 Gemini API
  9564. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  9565. } else {
  9566. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  9567. }
  9568. // 处理流式输出
  9569. $fullContent = '';
  9570. $fullReasoningContent = '';
  9571. foreach ($streamGenerator as $chunk) {
  9572. if (isset($chunk['type'])) {
  9573. if ($chunk['type'] === 'done') {
  9574. $fullContent = $chunk['full_content'];
  9575. $fullReasoningContent = $chunk['full_reasoning'];
  9576. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  9577. } else {
  9578. yield $chunk;
  9579. }
  9580. }
  9581. }
  9582. // 重新解析内容
  9583. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  9584. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  9585. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  9586. $episode_arr = handleEpisodeContentForAce($fullContent);
  9587. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  9588. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  9589. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  9590. // }
  9591. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  9592. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  9593. // 重新验证
  9594. $validation_failed = false;
  9595. $validation_error_msg = '';
  9596. if ($anime_script_id) {
  9597. if (empty($episode_arr['acts'])) {
  9598. $validation_failed = true;
  9599. $validation_error_msg = '未生成分镜剧本相关的内容';
  9600. } else {
  9601. // 校验主体列表:不能为空主体(旁白不算)
  9602. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9603. // 过滤掉"旁白"角色
  9604. $generated_roles = array_filter($generated_roles, function($role) {
  9605. return $role !== '旁白';
  9606. });
  9607. if (empty($generated_roles)) {
  9608. $validation_failed = true;
  9609. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9610. }
  9611. // 仅当存在强制主体设定时校验主体列表
  9612. if (!$validation_failed && !empty($extra_roles)) {
  9613. $expected_roles = array_keys($extra_roles);
  9614. $invalid_roles = array_diff($generated_roles, $expected_roles);
  9615. if (!empty($invalid_roles)) {
  9616. $validation_failed = true;
  9617. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  9618. }
  9619. }
  9620. // 仅当存在强制场景设定时校验场景列表
  9621. if (!$validation_failed && !empty($extra_scenes)) {
  9622. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  9623. $expected_scenes = array_keys($extra_scenes);
  9624. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  9625. if (!empty($invalid_scenes)) {
  9626. $validation_failed = true;
  9627. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  9628. }
  9629. }
  9630. // 仅当存在强制道具设定时校验道具列表
  9631. if (!$validation_failed && !empty($extra_props)) {
  9632. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  9633. $expected_props = array_keys($extra_props);
  9634. $invalid_props = array_diff($generated_props, $expected_props);
  9635. if (!empty($invalid_props)) {
  9636. $validation_failed = true;
  9637. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  9638. }
  9639. }
  9640. }
  9641. } else {
  9642. if (empty($episode_arr['acts'])) {
  9643. $validation_failed = true;
  9644. $validation_error_msg = '未生成分镜剧本相关的内容';
  9645. } else {
  9646. // 校验主体列表:不能为空主体(旁白不算)
  9647. $generated_roles = array_column($episode_arr['roles'] ?? [], 'role');
  9648. // 过滤掉"旁白"角色
  9649. $generated_roles = array_filter($generated_roles, function($role) {
  9650. return $role !== '旁白';
  9651. });
  9652. if (empty($generated_roles)) {
  9653. $validation_failed = true;
  9654. $validation_error_msg = '生成的主体列表不能为空(旁白不算)';
  9655. }
  9656. }
  9657. }
  9658. } catch (\Exception $e) {
  9659. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  9660. 'trace' => $e->getTraceAsString()
  9661. ]);
  9662. break;
  9663. }
  9664. }
  9665. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  9666. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  9667. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  9668. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  9669. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  9670. if ($validation_failed && $retry_count >= $max_retries) {
  9671. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  9672. 'retry_count' => $retry_count,
  9673. 'last_error' => $validation_error_msg
  9674. ]);
  9675. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  9676. 'error' => $validation_error_msg,
  9677. 'anime_id' => $anime_id
  9678. ]);
  9679. $validation_failed = false;
  9680. $validation_error_msg = '';
  9681. }
  9682. // 如果重试后仍然失败
  9683. if ($validation_failed) {
  9684. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  9685. 'retry_count' => $retry_count,
  9686. 'last_error' => $validation_error_msg
  9687. ]);
  9688. try {
  9689. $now = date('Y-m-d H:i:s');
  9690. $records = [
  9691. [
  9692. 'uid' => $uid,
  9693. 'anime_id' => $anime_id,
  9694. 'sequence' => $episode_number,
  9695. 'role' => 'user',
  9696. 'content' => $prompt,
  9697. 'created_at' => $now,
  9698. 'updated_at' => $now
  9699. ],
  9700. [
  9701. 'uid' => $uid,
  9702. 'anime_id' => $anime_id,
  9703. 'sequence' => $episode_number,
  9704. 'role' => 'assistant',
  9705. 'content' => $fullContent,
  9706. 'created_at' => $now,
  9707. 'updated_at' => $now
  9708. ]
  9709. ];
  9710. DB::table('mp_anime_records')->insert($records);
  9711. } catch (\Exception $e) {
  9712. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  9713. }
  9714. yield [
  9715. 'type' => 'done',
  9716. 'episode' => [],
  9717. 'answer' => $fullContent,
  9718. 'reasoning' => $fullReasoningContent,
  9719. 'usage' => $usage,
  9720. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  9721. ];
  9722. return;
  9723. }
  9724. // 验证成功,记录日志
  9725. if ($retry_count > 0) {
  9726. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  9727. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  9728. }
  9729. // 老逻辑
  9730. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  9731. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  9732. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  9733. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  9734. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  9735. $existing_props = is_array($existing_props) ? $existing_props : [];
  9736. $now = date('Y-m-d H:i:s');
  9737. try {
  9738. DB::beginTransaction();
  9739. $saveResult = $this->saveEpisodeVersionData(
  9740. $anime_id,
  9741. $episode_number,
  9742. $episode_arr,
  9743. $existing_roles,
  9744. $existing_scenes,
  9745. $existing_props,
  9746. $current_episode,
  9747. $base_episode,
  9748. $is_regenerate_version,
  9749. $content,
  9750. $now,
  9751. $ref_products
  9752. );
  9753. $episode = $saveResult['episode'];
  9754. $episode_id = $saveResult['episode_id'];
  9755. $merged_roles = $saveResult['merged_roles'];
  9756. $merged_scenes = $saveResult['merged_scenes'];
  9757. $merged_props = $saveResult['merged_props'];
  9758. $record_content = $origin_prompt;
  9759. if ($uploaded_content !== '') {
  9760. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  9761. }
  9762. $records = [
  9763. [
  9764. 'uid' => $uid,
  9765. 'anime_id' => $anime_id,
  9766. 'role' => 'user',
  9767. 'content' => $record_content,
  9768. 'sequence' => $episode_number,
  9769. 'episode_id' => $episode_id,
  9770. 'created_at' => $now,
  9771. 'updated_at' => $now
  9772. ],
  9773. [
  9774. 'uid' => $uid,
  9775. 'anime_id' => $anime_id,
  9776. 'role' => 'assistant',
  9777. 'content' => $fullContent,
  9778. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  9779. 'sequence' => $episode_number,
  9780. 'episode_id' => $episode_id,
  9781. 'created_at' => $now,
  9782. 'updated_at' => $now
  9783. ]
  9784. ];
  9785. $boolen4 = DB::table('mp_anime_records')->insert($records);
  9786. if (!$boolen4) {
  9787. Utils::throwError('20003:对话记录保存失败');
  9788. }
  9789. // 保存模型到anime表
  9790. $update_anime_data = [
  9791. 'model' => $model,
  9792. 'updated_at' => $now
  9793. ];
  9794. if ($uploaded_content) {
  9795. $update_anime_data['content'] = $uploaded_content;
  9796. }
  9797. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  9798. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  9799. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  9800. 'anime_id' => $anime_id,
  9801. 'episode_number' => $episode_number,
  9802. 'model' => $model,
  9803. 'source' => 'chatForAce',
  9804. ]);
  9805. }catch (\Exception $e) {
  9806. DB::rollBack();
  9807. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  9808. yield [
  9809. 'type' => 'done',
  9810. 'answer' => $fullContent,
  9811. 'reasoning' => $fullReasoningContent,
  9812. 'usage' => $usage,
  9813. 'error' => $e->getMessage(),
  9814. ];
  9815. return;
  9816. }
  9817. DB::commit();
  9818. if ($is_global_generate_pics) {
  9819. // // 批量生成全局角色图片
  9820. // $this->batchSetGlobalRoleImg([
  9821. // 'anime_id' => $anime_id,
  9822. // ], true);
  9823. // // 批量生成全局场景图片
  9824. // $this->batchSetGlobalSceneImg([
  9825. // 'anime_id' => $anime_id,
  9826. // ], true);
  9827. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  9828. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  9829. }
  9830. $episode['episode_id'] = $episode_id;
  9831. $episode['roles'] = $merged_roles;
  9832. $episode['scenes'] = $merged_scenes;
  9833. $episode['props'] = $merged_props;
  9834. $episode['end_episode_sequence'] = $end_episode_sequence;
  9835. // 获取mp_animes表中的视频参数
  9836. $episode['video_params'] = [
  9837. 'video_model' => getProp($anime, 'video_model'),
  9838. 'video_resolution' => getProp($anime, 'video_resolution'),
  9839. 'ratio' => getProp($anime, 'video_ratio'),
  9840. ];
  9841. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9842. yield [
  9843. 'type' => 'done',
  9844. 'episode' => $episode,
  9845. 'answer' => $fullContent,
  9846. 'reasoning' => $fullReasoningContent,
  9847. 'usage' => $usage
  9848. ];
  9849. }
  9850. /**
  9851. * chatForAce的非流式版本 - 用于定时任务
  9852. * 只获取最终 type=done 的数据,并验证必要字段
  9853. *
  9854. * @param array $data 请求数据
  9855. * @return array 生成结果
  9856. */
  9857. public function chatForAceNonStream($data) {
  9858. $finalResult = null;
  9859. // 调用流式方法,只保存 type=done 的数据
  9860. foreach ($this->chatForAce($data) as $chunk) {
  9861. // 只关注最终结果
  9862. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  9863. $finalResult = $chunk;
  9864. break; // 找到 done 就退出循环
  9865. }
  9866. }
  9867. // 验证最终结果
  9868. if (!$finalResult) {
  9869. return ['error' => '生成失败:未获取到最终结果'];
  9870. }
  9871. // 检查是否有错误
  9872. if (isset($finalResult['error']) && $finalResult['error']) {
  9873. return $finalResult;
  9874. }
  9875. // 验证必要字段
  9876. $episode = $finalResult['episode'] ?? [];
  9877. // 验证 roles(旁白不算主体,过滤后不能为空)
  9878. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  9879. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  9880. }
  9881. $nonNarratorRoles = array_filter(array_column($episode['roles'], 'role'), function($role) {
  9882. return $role !== '旁白';
  9883. });
  9884. if (empty($nonNarratorRoles)) {
  9885. return ['error' => '生成失败:主体列表(roles)为空或格式错误(旁白不算)'];
  9886. }
  9887. // 验证 scenes
  9888. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  9889. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  9890. }
  9891. // 验证 props(道具可以为空,但必须存在且为数组)
  9892. if (!isset($episode['props']) || !is_array($episode['props'])) {
  9893. $episode['props'] = [];
  9894. }
  9895. // 验证 acts(分镜剧本)
  9896. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  9897. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  9898. }
  9899. // 更新验证后的 episode 数据
  9900. $finalResult['episode'] = $episode;
  9901. // 记录验证成功日志
  9902. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  9903. 'roles_count' => count($episode['roles']),
  9904. 'scenes_count' => count($episode['scenes']),
  9905. 'props_count' => count($episode['props']),
  9906. 'acts_count' => count($episode['acts'])
  9907. ]);
  9908. return $finalResult;
  9909. }
  9910. /**
  9911. * 批量生成多个分集
  9912. *
  9913. * @param array $data 请求数据
  9914. * @return array 任务信息
  9915. */
  9916. public function batchGenerateEpisodes($data) {
  9917. $uid = Site::getUid();
  9918. $cpid = Site::getCpid();
  9919. $anime_id = getProp($data, 'anime_id');
  9920. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  9921. $start_episode_number = getProp($data, 'start_episode_number');
  9922. $end_episode_number = getProp($data, 'end_episode_number');
  9923. if (!$anime_id) {
  9924. Utils::throwError('20003:anime_id参数缺失');
  9925. }
  9926. if ($generate_episode_number < 1) {
  9927. Utils::throwError('20003:生成集数必须大于0');
  9928. }
  9929. // 获取动漫信息
  9930. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9931. if (!$anime) {
  9932. Utils::throwError('20003:该剧集不存在');
  9933. }
  9934. // 检查是否是全能模式
  9935. if ((int)getProp($anime, 'ace_mode') !== 1) {
  9936. Utils::throwError('20003:只有全能模式才支持批量生成');
  9937. }
  9938. // 检查是否是多剧集模式
  9939. if ((int)getProp($anime, 'is_multi') !== 1) {
  9940. Utils::throwError('20003:单剧集不支持批量生成');
  9941. }
  9942. // 指定起始/结束剧集序号时的校验
  9943. $hasSpecifiedRange = ($start_episode_number !== null && $start_episode_number !== '')
  9944. || ($end_episode_number !== null && $end_episode_number !== '');
  9945. if ($hasSpecifiedRange) {
  9946. if ($start_episode_number === null || $start_episode_number === ''
  9947. || $end_episode_number === null || $end_episode_number === '') {
  9948. Utils::throwError('20003:起始剧集序号和结束剧集序号必须同时提供');
  9949. }
  9950. $start_episode_number = (int)$start_episode_number;
  9951. $end_episode_number = (int)$end_episode_number;
  9952. if ($start_episode_number < 1 || $end_episode_number < $start_episode_number) {
  9953. Utils::throwError('20003:剧集序号范围错误,结束剧集序号不能小于起始剧集序号');
  9954. }
  9955. $startEpisodeNumber = $start_episode_number;
  9956. $endEpisodeNumber = $end_episode_number;
  9957. } else {
  9958. // 未指定范围时,以 generate_episode_number 判断要生成的集数,从当前已生成的最大集数的下一集开始
  9959. $currentMaxEpisode = DB::table('mp_anime_episodes')
  9960. ->where('anime_id', $anime_id)
  9961. ->where('is_default', 1)
  9962. ->max('episode_number');
  9963. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  9964. // 确定起始集数
  9965. $startEpisodeNumber = $currentMaxEpisode + 1;
  9966. // 计算结束集数
  9967. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  9968. }
  9969. // 本次实际生成的集数
  9970. $totalEpisodeCount = $endEpisodeNumber - $startEpisodeNumber + 1;
  9971. // 检查是否超过总集数限制
  9972. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  9973. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  9974. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  9975. }
  9976. // 创建任务前验重:批量任务表与剧集表中是否已存在范围内的剧集序号
  9977. $duplicatedBatchEpisodes = DB::table('mp_batch_episode_generation_details')
  9978. ->where('anime_id', $anime_id)
  9979. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  9980. ->pluck('episode_number')
  9981. ->unique()
  9982. ->sort()
  9983. ->values()
  9984. ->toArray();
  9985. $duplicatedAnimeEpisodes = DB::table('mp_anime_episodes')
  9986. ->where('anime_id', $anime_id)
  9987. ->where('is_default', 1)
  9988. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  9989. ->pluck('episode_number')
  9990. ->unique()
  9991. ->sort()
  9992. ->values()
  9993. ->toArray();
  9994. if (!empty($duplicatedBatchEpisodes) || !empty($duplicatedAnimeEpisodes)) {
  9995. $duplicateMessages = [];
  9996. if (!empty($duplicatedBatchEpisodes)) {
  9997. $duplicateMessages[] = '批量生成任务中已存在第' . implode('、', $duplicatedBatchEpisodes) . '集';
  9998. }
  9999. if (!empty($duplicatedAnimeEpisodes)) {
  10000. $duplicateMessages[] = '剧集中已存在第' . implode('、', $duplicatedAnimeEpisodes) . '集';
  10001. }
  10002. Utils::throwError('20003:' . implode(';', $duplicateMessages) . ',请勿重复创建');
  10003. }
  10004. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  10005. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  10006. ->where('anime_id', $anime_id)
  10007. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  10008. ->whereIn('status', ['pending', 'processing', 'completed'])
  10009. ->count();
  10010. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  10011. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  10012. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  10013. if ($needEpisodeCount > 0) {
  10014. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints() * $needEpisodeCount, $uid);
  10015. }
  10016. $now = date('Y-m-d H:i:s');
  10017. $createdTasks = [];
  10018. $skippedTasks = [];
  10019. // 为每一集创建详情记录
  10020. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  10021. // 检查是否已有该集的任务记录
  10022. $existingTask = DB::table('mp_batch_episode_generation_details')
  10023. ->where('anime_id', $anime_id)
  10024. ->where('episode_number', $episodeNumber)
  10025. ->first();
  10026. if ($existingTask) {
  10027. // 如果已存在且未完成,跳过
  10028. if (in_array($existingTask->status, ['pending', 'processing'])) {
  10029. $skippedTasks[] = $episodeNumber;
  10030. continue;
  10031. }
  10032. // 如果是失败状态,可以重新创建(删除旧记录)
  10033. if ($existingTask->status === 'failed') {
  10034. DB::table('mp_batch_episode_generation_details')
  10035. ->where('id', $existingTask->id)
  10036. ->delete();
  10037. }
  10038. // 如果是已完成状态,也跳过
  10039. if ($existingTask->status === 'completed') {
  10040. $skippedTasks[] = $episodeNumber;
  10041. continue;
  10042. }
  10043. }
  10044. // 准备任务数据
  10045. $taskData = [
  10046. 'anime_id' => $anime_id,
  10047. 'uid' => $uid,
  10048. 'cpid' => $cpid,
  10049. 'episode_number' => $episodeNumber,
  10050. 'status' => 'pending',
  10051. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  10052. 'retry_count' => 0,
  10053. 'created_at' => $now,
  10054. 'updated_at' => $now
  10055. ];
  10056. // 创建任务记录
  10057. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  10058. if ($taskId) {
  10059. $createdTasks[] = $episodeNumber;
  10060. }
  10061. }
  10062. if (empty($createdTasks)) {
  10063. if (!empty($skippedTasks)) {
  10064. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  10065. } else {
  10066. Utils::throwError('20003:创建批量生成任务失败');
  10067. }
  10068. }
  10069. // 创建/复用任务中心记录(按入参+type验重,避免重复任务)
  10070. $taskCenterId = $this->createBatchGenerateEpisodesTaskCenter(
  10071. $uid,
  10072. $cpid,
  10073. $anime_id,
  10074. $generate_episode_number,
  10075. $startEpisodeNumber,
  10076. $endEpisodeNumber
  10077. );
  10078. return [
  10079. 'anime_id' => $anime_id,
  10080. 'start_episode' => $startEpisodeNumber,
  10081. 'end_episode' => $endEpisodeNumber,
  10082. 'total_episodes' => $totalEpisodeCount,
  10083. 'created_episodes' => $createdTasks,
  10084. 'skipped_episodes' => $skippedTasks,
  10085. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$totalEpisodeCount}集。" .
  10086. "已创建: " . implode(',', $createdTasks) .
  10087. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : ""),
  10088. 'task_center_id' => $taskCenterId
  10089. ];
  10090. }
  10091. /**
  10092. * 根据入参创建或复用批量生成分集的任务中心记录
  10093. *
  10094. * 以入参(anime_id、generate_episode_number)计算 md5 存入 params_md5 字段用于验重:
  10095. * 同一用户/企业下,相同入参且任务未结束(pending/processing)时复用已有任务,
  10096. * 避免生成重复任务;唯一索引 (uid, cpid, task_type, params_md5) 兜底并发重复。
  10097. *
  10098. * @param int|string $uid
  10099. * @param int|string $cpid
  10100. * @param int|string $anime_id
  10101. * @param int $generate_episode_number
  10102. * @param int $startEpisodeNumber
  10103. * @param int $endEpisodeNumber
  10104. * @return int 任务中心ID
  10105. */
  10106. private function createBatchGenerateEpisodesTaskCenter($uid, $cpid, $anime_id, $generate_episode_number, $startEpisodeNumber, $endEpisodeNumber) {
  10107. $params = [
  10108. 'anime_id' => (int)$anime_id,
  10109. 'generate_episode_number' => (int)$generate_episode_number,
  10110. 'start_episode' => (int)$startEpisodeNumber,
  10111. 'end_episode' => (int)$endEpisodeNumber,
  10112. ];
  10113. // 验重键:入参 + 生成范围(anime_id + generate_episode_number + start/end)+ task_type
  10114. $paramsMd5 = md5(json_encode([
  10115. 'anime_id' => (int)$anime_id,
  10116. 'generate_episode_number' => (int)$generate_episode_number,
  10117. 'start_episode' => (int)$startEpisodeNumber,
  10118. 'end_episode' => (int)$endEpisodeNumber,
  10119. ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
  10120. // 验重:相同 md5 且任务未结束(pending/processing)时复用已有任务中心记录
  10121. $existing = DB::table('mp_task_center')
  10122. ->where('uid', (int)$uid)
  10123. ->where('cpid', (int)$cpid)
  10124. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10125. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  10126. ->where('params_md5', $paramsMd5)
  10127. ->orderBy('id', 'desc')
  10128. ->first();
  10129. if ($existing) {
  10130. dLog('deepseek')->info('复用批量生成分集任务中心记录,避免重复任务', [
  10131. 'anime_id' => $anime_id,
  10132. 'task_center_id' => $existing->id,
  10133. 'params_md5' => $paramsMd5,
  10134. ]);
  10135. return (int)$existing->id;
  10136. }
  10137. $now = date('Y-m-d H:i:s');
  10138. DB::table('mp_task_center')->insertOrIgnore([
  10139. 'uid' => (int)$uid,
  10140. 'cpid' => (int)$cpid,
  10141. 'task_type' => MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES,
  10142. 'title' => '批量生成分集',
  10143. 'ref_task_id' => 0,
  10144. 'status' => MpTaskCenter::STATUS_PROCESSING,
  10145. 'result' => null,
  10146. 'error_message' => null,
  10147. 'prompt' => null,
  10148. 'params' => json_encode($params + ['params_md5' => $paramsMd5], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
  10149. 'params_md5' => $paramsMd5,
  10150. 'created_at' => $now,
  10151. 'updated_at' => $now,
  10152. ]);
  10153. // 获取任务中心ID(insertOrIgnore 冲突时复用并发插入的已有记录)
  10154. $taskId = (int)DB::table('mp_task_center')
  10155. ->where('uid', (int)$uid)
  10156. ->where('cpid', (int)$cpid)
  10157. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10158. ->where('params_md5', $paramsMd5)
  10159. ->orderBy('id', 'desc')
  10160. ->value('id');
  10161. dLog('deepseek')->info('创建批量生成分集任务中心记录', [
  10162. 'anime_id' => $anime_id,
  10163. 'task_center_id' => $taskId,
  10164. 'params_md5' => $paramsMd5,
  10165. ]);
  10166. return $taskId;
  10167. }
  10168. /**
  10169. * 批量生成分集全部结束后,更新任务中心记录的状态和结果
  10170. *
  10171. * 由批量生成 worker 子进程在退出前调用。分集详情任务的状态会在多处更新
  10172. * (completed/failed/pending/processing),这里只在所有详情任务均已结束时
  10173. * 统一汇总更新,避免在每个更新点重复处理。
  10174. *
  10175. * @param int|string $animeId
  10176. * @return int 更新的任务中心记录数
  10177. */
  10178. public function finishBatchGenerateEpisodesTaskCenters($animeId) {
  10179. $animeId = (int)$animeId;
  10180. $updated = 0;
  10181. // 该 anime 是否还有未结束的详情任务
  10182. $hasUnfinished = DB::table('mp_batch_episode_generation_details')
  10183. ->where('anime_id', $animeId)
  10184. ->whereIn('status', ['pending', 'processing'])
  10185. ->exists();
  10186. // 扫描该 anime 相关的未完成任务中心记录
  10187. $tasks = DB::table('mp_task_center')
  10188. ->where('task_type', MpTaskCenter::TYPE_BATCH_GENERATE_EPISODES)
  10189. ->whereIn('status', [MpTaskCenter::STATUS_PENDING, MpTaskCenter::STATUS_PROCESSING])
  10190. ->orderBy('id', 'desc')
  10191. ->limit(500)
  10192. ->get();
  10193. if ($hasUnfinished && !$tasks) {
  10194. return 0;
  10195. }
  10196. foreach ($tasks as $task) {
  10197. try {
  10198. $taskParams = json_decode((string)$task->params, true);
  10199. if (!is_array($taskParams) || (int)($taskParams['anime_id'] ?? 0) !== $animeId) {
  10200. continue;
  10201. }
  10202. $startEpisode = (int)($taskParams['start_episode'] ?? 0);
  10203. $endEpisode = (int)($taskParams['end_episode'] ?? 0);
  10204. if ($startEpisode < 1 || $endEpisode < $startEpisode) {
  10205. continue;
  10206. }
  10207. $details = DB::table('mp_batch_episode_generation_details')
  10208. ->where('anime_id', $animeId)
  10209. ->whereBetween('episode_number', [$startEpisode, $endEpisode])
  10210. ->get();
  10211. // 该批次范围内存在缺失记录,等待下一次检查
  10212. if ($details->isEmpty() || $details->count() < ($endEpisode - $startEpisode + 1)) {
  10213. continue;
  10214. }
  10215. $completedEpisodes = [];
  10216. $failedEpisodes = [];
  10217. $allFinished = true;
  10218. foreach ($details as $detail) {
  10219. if ($detail->status === 'completed') {
  10220. $completedEpisodes[] = $detail->episode_number;
  10221. } elseif ($detail->status === 'failed') {
  10222. $failedEpisodes[] = [
  10223. 'episode_number' => $detail->episode_number,
  10224. 'error_message' => $detail->error_message ?? '',
  10225. ];
  10226. } else {
  10227. // pending/processing(防御处理,正常不会走到)
  10228. $allFinished = false;
  10229. break;
  10230. }
  10231. }
  10232. if (!$allFinished) {
  10233. continue;
  10234. }
  10235. $result = json_encode([
  10236. 'anime_id' => $animeId,
  10237. 'start_episode' => $startEpisode,
  10238. 'end_episode' => $endEpisode,
  10239. 'total_episodes' => count($details),
  10240. 'completed_count' => count($completedEpisodes),
  10241. 'failed_count' => count($failedEpisodes),
  10242. 'completed_episodes' => $completedEpisodes,
  10243. 'failed_episodes' => $failedEpisodes,
  10244. ], JSON_UNESCAPED_UNICODE);
  10245. DB::table('mp_task_center')
  10246. ->where('id', $task->id)
  10247. ->update([
  10248. 'status' => !empty($failedEpisodes) ? MpTaskCenter::STATUS_FAILED : MpTaskCenter::STATUS_SUCCESS,
  10249. 'result' => $result,
  10250. 'error_message' => !empty($failedEpisodes) ? ('有 ' . count($failedEpisodes) . ' 集生成失败') : null,
  10251. 'updated_at' => date('Y-m-d H:i:s'),
  10252. ]);
  10253. $updated++;
  10254. dLog('command')->info('批量生成分集任务已完成,更新任务中心', [
  10255. 'task_center_id' => $task->id,
  10256. 'anime_id' => $animeId,
  10257. 'start_episode' => $startEpisode,
  10258. 'end_episode' => $endEpisode,
  10259. ]);
  10260. } catch (\Exception $e) {
  10261. dLog('command')->error('更新批量生成分集任务中心异常', [
  10262. 'task_center_id' => $task->id,
  10263. 'anime_id' => $animeId,
  10264. 'error' => $e->getMessage(),
  10265. ]);
  10266. }
  10267. }
  10268. return $updated;
  10269. }
  10270. /**
  10271. * 获取批量生成任务状态
  10272. *
  10273. * @param array $data 请求数据
  10274. * @return array 任务状态信息
  10275. */
  10276. public function getBatchGenerationTaskStatus($data) {
  10277. $anime_id = getProp($data, 'anime_id');
  10278. if (!$anime_id) {
  10279. Utils::throwError('20003:anime_id参数缺失');
  10280. }
  10281. // 获取该anime的所有任务
  10282. $tasks = DB::table('mp_batch_episode_generation_details')
  10283. ->where('anime_id', $anime_id)
  10284. ->orderBy('episode_number')
  10285. ->get()
  10286. ->map(function($item) {
  10287. return [
  10288. 'id' => $item->id,
  10289. 'episode_number' => $item->episode_number,
  10290. 'status' => $item->status,
  10291. 'error_message' => $item->error_message,
  10292. 'retry_count' => $item->retry_count,
  10293. 'created_at' => $item->created_at,
  10294. 'updated_at' => $item->updated_at,
  10295. 'completed_at' => $item->completed_at
  10296. ];
  10297. })
  10298. ->toArray();
  10299. if (empty($tasks)) {
  10300. Utils::throwError('20003:该剧集没有批量生成任务');
  10301. }
  10302. // 统计各状态数量
  10303. $totalCount = count($tasks);
  10304. $pendingCount = 0;
  10305. $processingCount = 0;
  10306. $completedCount = 0;
  10307. $failedCount = 0;
  10308. $failed_episodes = [];
  10309. foreach ($tasks as $task) {
  10310. switch ($task['status']) {
  10311. case 'pending':
  10312. $pendingCount++;
  10313. break;
  10314. case 'processing':
  10315. $processingCount++;
  10316. break;
  10317. case 'completed':
  10318. $completedCount++;
  10319. break;
  10320. case 'failed':
  10321. $failedCount++;
  10322. // 组装失败分集对象(新对象):分集序号、错误原因
  10323. $failed_episodes[] = [
  10324. 'episode_number' => $task['episode_number'],
  10325. 'error_message' => $task['error_message'] ?? ''
  10326. ];
  10327. break;
  10328. }
  10329. }
  10330. // 计算进度百分比
  10331. $progress = 0;
  10332. if ($totalCount > 0) {
  10333. $progress = round(($completedCount / $totalCount) * 100, 2);
  10334. }
  10335. // 判断整体状态
  10336. $overallStatus = 'processing';
  10337. if ($completedCount === $totalCount) {
  10338. $overallStatus = 'completed';
  10339. } elseif ($pendingCount === $totalCount) {
  10340. $overallStatus = 'pending';
  10341. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  10342. $overallStatus = 'failed';
  10343. }
  10344. return [
  10345. 'anime_id' => $anime_id,
  10346. 'total_episodes' => $totalCount,
  10347. 'pending_count' => $pendingCount,
  10348. 'processing_count' => $processingCount,
  10349. 'completed_count' => $completedCount,
  10350. 'failed_count' => $failedCount,
  10351. 'progress' => $progress,
  10352. 'overall_status' => $overallStatus,
  10353. 'failed_episodes' => $failed_episodes,
  10354. 'tasks' => $tasks
  10355. ];
  10356. }
  10357. /**
  10358. * 将生成内容中不在强制列表中的资源合并进强制列表
  10359. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  10360. *
  10361. * @param array $generated 生成内容中的资源列表
  10362. * @param array $forced 强制资源列表(key为资源名称)
  10363. * @param string $type 资源类型:role、scene、prop
  10364. * @return array
  10365. */
  10366. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  10367. {
  10368. foreach ($generated as $item) {
  10369. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  10370. if ($name === null || $name === '') {
  10371. continue;
  10372. }
  10373. if ($name === '旁白') {
  10374. continue;
  10375. }
  10376. if (!isset($forced[$name])) {
  10377. $forced[$name] = $item;
  10378. }
  10379. }
  10380. return $forced;
  10381. }
  10382. /**
  10383. * 智能匹配并替换主体和场景名称
  10384. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  10385. *
  10386. * @param array $episode_arr 解析后的剧集数据
  10387. * @param array $extra_roles 强制主体设定(key为主体名称)
  10388. * @param array $extra_scenes 强制场景设定(key为场景名称)
  10389. * @return array 替换后的剧集数据
  10390. */
  10391. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  10392. $replaced_count = 0;
  10393. // 1. 处理主体列表
  10394. if (!empty($episode_arr['roles'])) {
  10395. foreach ($episode_arr['roles'] as &$role) {
  10396. $generated_role_name = $role['role'] ?? '';
  10397. // 跳过旁白
  10398. if ($generated_role_name === '旁白') {
  10399. continue;
  10400. }
  10401. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  10402. if (!isset($extra_roles[$generated_role_name])) {
  10403. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  10404. if ($matched_role) {
  10405. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  10406. $role['role'] = $matched_role;
  10407. $replaced_count++;
  10408. }
  10409. }
  10410. }
  10411. }
  10412. // 2. 处理场景列表
  10413. if (!empty($episode_arr['scenes'])) {
  10414. foreach ($episode_arr['scenes'] as &$scene) {
  10415. $generated_scene_name = $scene['scene'] ?? '';
  10416. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  10417. if (!isset($extra_scenes[$generated_scene_name])) {
  10418. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  10419. if ($matched_scene) {
  10420. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  10421. $scene['scene'] = $matched_scene;
  10422. $replaced_count++;
  10423. }
  10424. }
  10425. }
  10426. }
  10427. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  10428. if (!empty($episode_arr['acts'])) {
  10429. foreach ($episode_arr['acts'] as &$act) {
  10430. if (!empty($act['segments'])) {
  10431. foreach ($act['segments'] as &$segment) {
  10432. if (!empty($segment['segment_content'])) {
  10433. $original_content = $segment['segment_content'];
  10434. $replaced_content = $original_content;
  10435. // 替换场景名 - 在文本中查找并替换
  10436. foreach (array_keys($extra_scenes) as $full_scene_name) {
  10437. // 尝试找到可能的短名称
  10438. $potential_short_names = [];
  10439. // 提取场景名的主要部分(冒号之前)
  10440. if (mb_strpos($full_scene_name, ':') !== false) {
  10441. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  10442. $potential_short_names[] = $short_name;
  10443. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  10444. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  10445. $potential_short_names[] = $short_name;
  10446. }
  10447. // 替换场景字段中的短名称
  10448. foreach ($potential_short_names as $short_name) {
  10449. if ($short_name !== $full_scene_name) {
  10450. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  10451. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  10452. if ($new_content !== $replaced_content) {
  10453. $replaced_content = $new_content;
  10454. $replaced_count++;
  10455. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  10456. }
  10457. }
  10458. }
  10459. }
  10460. // 替换配音角色名(跳过旁白)
  10461. foreach (array_keys($extra_roles) as $full_role_name) {
  10462. if ($full_role_name === '旁白') {
  10463. continue;
  10464. }
  10465. // 尝试找到可能的短名称
  10466. $potential_short_names = [];
  10467. // 提取角色名的主要部分(短横线之前)
  10468. if (mb_strpos($full_role_name, '-') !== false) {
  10469. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  10470. $potential_short_names[] = $short_name;
  10471. }
  10472. // 替换配音台词中的短名称
  10473. foreach ($potential_short_names as $short_name) {
  10474. if ($short_name !== $full_role_name) {
  10475. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  10476. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  10477. if ($new_content !== $replaced_content) {
  10478. $replaced_content = $new_content;
  10479. $replaced_count++;
  10480. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  10481. }
  10482. }
  10483. }
  10484. }
  10485. // 如果有替换,更新segment_content
  10486. if ($replaced_content !== $original_content) {
  10487. $segment['segment_content'] = $replaced_content;
  10488. }
  10489. }
  10490. }
  10491. }
  10492. }
  10493. }
  10494. if ($replaced_count > 0) {
  10495. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  10496. 'replaced_count' => $replaced_count
  10497. ]);
  10498. }
  10499. return $episode_arr;
  10500. }
  10501. /**
  10502. * 查找匹配的名称
  10503. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  10504. *
  10505. * @param string $generated_name 生成的名称
  10506. * @param array $expected_names 预期的名称列表
  10507. * @return string|null 匹配到的名称,如果没有匹配则返回null
  10508. */
  10509. private function findMatchingName($generated_name, $expected_names) {
  10510. if (empty($generated_name)) {
  10511. return null;
  10512. }
  10513. // 尝试精确匹配
  10514. if (in_array($generated_name, $expected_names)) {
  10515. return $generated_name;
  10516. }
  10517. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  10518. foreach ($expected_names as $expected_name) {
  10519. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  10520. if (mb_strpos($expected_name, $generated_name) === 0) {
  10521. return $expected_name;
  10522. }
  10523. }
  10524. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  10525. // 这样可以处理一些变体,但优先级较低
  10526. foreach ($expected_names as $expected_name) {
  10527. if (mb_strpos($expected_name, $generated_name) !== false) {
  10528. return $expected_name;
  10529. }
  10530. }
  10531. return null;
  10532. }
  10533. /**
  10534. * 重新生成分段剧本
  10535. * @param array $data 包含以下字段:
  10536. * - prompt: string|null 用户修改要求(可选)
  10537. * - template_id: int|null 提示词模板ID(可选)
  10538. * - act_id: int|null 单个片段ID(与episode_id二选一)
  10539. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  10540. * @return array 返回生成结果
  10541. */
  10542. public function regenerateSegmentScript($data) {
  10543. $uid = Site::getUid();
  10544. $prompt = trim((string)getProp($data, 'prompt', ''));
  10545. $template_id = getProp($data, 'template_id', 0);
  10546. $act_id = getProp($data, 'act_id', 0);
  10547. $episode_id = getProp($data, 'episode_id', 0);
  10548. // 验证:prompt和template_id至少提供一个
  10549. if (empty($prompt) && empty($template_id)) {
  10550. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  10551. }
  10552. // 验证:act_id和episode_id二选一
  10553. if (empty($act_id) && empty($episode_id)) {
  10554. Utils::throwError('20003:请提供片段ID或剧集ID');
  10555. }
  10556. if (!empty($act_id) && !empty($episode_id)) {
  10557. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  10558. }
  10559. // 积分余额预检(仅剧集ID模式收费)
  10560. if (!empty($episode_id)) {
  10561. $this->pointsService->checkUserPointsEnough($this->pointsService->getChatChargePoints(), $uid);
  10562. }
  10563. // 如果提供了template_id,获取模板提示词
  10564. $template_prompt = '';
  10565. if ($template_id > 0) {
  10566. $template = DB::table('mp_prompt_templates')
  10567. ->where('id', $template_id)
  10568. ->where('is_deleted', 0)
  10569. ->first();
  10570. if (!$template) {
  10571. Utils::throwError('20003:提示词模板不存在或已删除');
  10572. }
  10573. $template_prompt = $template->template_prompt ?? '';
  10574. }
  10575. // 合并用户提示词和模板提示词
  10576. $final_prompt = '';
  10577. if (!empty($template_prompt)) {
  10578. $final_prompt = $template_prompt;
  10579. if (!empty($prompt)) {
  10580. $final_prompt .= "\n\n补充要求:" . $prompt;
  10581. }
  10582. } else {
  10583. $final_prompt = $prompt;
  10584. }
  10585. // 获取需要重新生成的内容参考
  10586. $reference_content = '';
  10587. $target_episode_id = 0;
  10588. $target_anime_id = 0;
  10589. $target_episode_number = 0;
  10590. if ($act_id > 0) {
  10591. // 单个片段模式:获取该片段的内容
  10592. $segment = DB::table('mp_episode_segments')
  10593. ->where('id', $act_id)
  10594. ->first();
  10595. if (!$segment) {
  10596. Utils::throwError('20003:片段不存在');
  10597. }
  10598. $target_episode_id = $segment->episode_id;
  10599. $target_anime_id = $segment->anime_id;
  10600. $target_episode_number = $segment->episode_number;
  10601. $reference_content = $segment->act_content ?? '';
  10602. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  10603. } else {
  10604. // 整个剧集模式:获取所有片段的内容
  10605. $segments = DB::table('mp_episode_segments')
  10606. ->where('episode_id', $episode_id)
  10607. ->orderBy('act_number')
  10608. ->get();
  10609. if ($segments->isEmpty()) {
  10610. Utils::throwError('20003:该剧集没有片段数据');
  10611. }
  10612. $target_episode_id = $episode_id;
  10613. $target_anime_id = $segments[0]->anime_id;
  10614. $target_episode_number = $segments[0]->episode_number;
  10615. // 拼接所有片段内容,保留格式用于AI理解
  10616. $act_contents = [];
  10617. foreach ($segments as $seg) {
  10618. $act_number = $seg->act_number;
  10619. $act_content = $seg->act_content ?? '';
  10620. if (!empty($act_content)) {
  10621. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  10622. }
  10623. }
  10624. $reference_content = implode("\n\n", $act_contents);
  10625. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  10626. if ($episode_content) {
  10627. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  10628. }else {
  10629. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  10630. }
  10631. }
  10632. if (empty($reference_content)) {
  10633. Utils::throwError('20003:没有可参考的片段内容');
  10634. }
  10635. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  10636. $episode = DB::table('mp_anime_episodes')
  10637. ->where('id', $target_episode_id)
  10638. ->first();
  10639. if (!$episode) {
  10640. Utils::throwError('20003:剧集不存在');
  10641. }
  10642. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  10643. $anime_script_id = getProp($anime, 'script_id');
  10644. $intro = $episode->intro ?? '';
  10645. $art_style = $episode->art_style ?? '';
  10646. $roles = json_decode($episode->roles ?? '[]', true);
  10647. $scenes = json_decode($episode->scenes ?? '[]', true);
  10648. $props = json_decode($episode->props ?? '[]', true);
  10649. // 构建提示词中的主体列表和场景列表参考
  10650. $roles_ref = '';
  10651. if (!empty($roles) && is_array($roles)) {
  10652. $roles_list = [];
  10653. foreach ($roles as $role) {
  10654. $role_name = getProp($role, 'role', '');
  10655. $role_desc = getProp($role, 'description', '');
  10656. $pic_prompt = getProp($role, 'pic_prompt', '');
  10657. $voice_prompt = getProp($role, 'voice_prompt', '');
  10658. if (!empty($role_name)) {
  10659. $role_line = $role_name;
  10660. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  10661. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  10662. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  10663. $roles_list[] = $role_line;
  10664. }
  10665. }
  10666. if (!empty($roles_list)) {
  10667. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  10668. }
  10669. }
  10670. $scenes_ref = '';
  10671. if (!empty($scenes) && is_array($scenes)) {
  10672. $scenes_list = [];
  10673. foreach ($scenes as $scene) {
  10674. $scene_name = getProp($scene, 'scene', '');
  10675. $scene_desc = getProp($scene, 'description', '');
  10676. $pic_prompt = getProp($scene, 'pic_prompt', '');
  10677. if (!empty($scene_name)) {
  10678. $scene_line = $scene_name;
  10679. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  10680. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  10681. $scenes_list[] = $scene_line;
  10682. }
  10683. }
  10684. if (!empty($scenes_list)) {
  10685. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  10686. }
  10687. }
  10688. $props_ref = '';
  10689. if (!empty($props) && is_array($props)) {
  10690. $props_list = [];
  10691. foreach ($props as $prop) {
  10692. $prop_name = getProp($prop, 'prop', '');
  10693. $prop_desc = getProp($prop, 'description', '');
  10694. $pic_prompt = getProp($prop, 'pic_prompt', '');
  10695. if (!empty($prop_name)) {
  10696. $prop_line = $prop_name;
  10697. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  10698. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  10699. $props_list[] = $prop_line;
  10700. }
  10701. }
  10702. if (!empty($props_list)) {
  10703. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  10704. }
  10705. }
  10706. // 构建美术风格参考
  10707. $art_style_ref = '';
  10708. if (!empty($art_style)) {
  10709. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  10710. }
  10711. // 构建内容简介参考
  10712. $intro_ref = '';
  10713. if (!empty($intro)) {
  10714. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  10715. }
  10716. // 构建完整的AI提示词
  10717. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  10718. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  10719. $user_prompt .= $intro_ref;
  10720. $user_prompt .= $art_style_ref;
  10721. $user_prompt .= $reference_content;
  10722. // $user_prompt .= $roles_ref;
  10723. // $user_prompt .= $scenes_ref;
  10724. $system_prompt = "\n\n【强制要求】\n";
  10725. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  10726. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  10727. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  10728. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  10729. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  10730. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  10731. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  10732. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  10733. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  10734. ###分段剧本
  10735. 片段数量:8
  10736. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  10737. ##片段1
  10738. 时长:12s
  10739. 分镜1
  10740. 出场角色:刀疤脸
  10741. 场景:边境小镇街道
  10742. 出场道具:酒杯-高脚杯
  10743. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  10744. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  10745. 配音台词:
  10746. 背景音效:
  10747. 分镜2
  10748. 出场角色:刀疤脸
  10749. 场景:悦来酒馆
  10750. 出场道具:酒杯-高脚杯
  10751. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  10752. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  10753. 配音台词:
  10754. 背景音效:
  10755. 分镜3
  10756. 出场角色:刀疤脸
  10757. 场景:悦来酒馆
  10758. 出场道具:酒杯-高脚杯
  10759. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  10760. 运镜:从中景推向令牌特写。
  10761. 配音台词:
  10762. 背景音效:
  10763. 分镜4
  10764. 出场角色:刀疤脸
  10765. 场景:悦来酒馆
  10766. 出场道具:酒杯-高脚杯
  10767. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  10768. 运镜:极速推向酒水溅起的瞬间。
  10769. 配音台词:
  10770. 背景音效:
  10771. 分镜5
  10772. 出场角色:刀疤脸
  10773. 场景:悦来酒馆
  10774. 出场道具:酒杯-高脚杯
  10775. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  10776. 运镜:固定机位,利用倾斜构图制造压迫感。
  10777. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  10778. 背景音效:";
  10779. // 获取模型配置
  10780. $model = getProp($data, 'model');
  10781. if (!$model) {
  10782. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  10783. }
  10784. // 验证模型是否在可用模型表中
  10785. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10786. $model = 'deepseek-v4-pro';
  10787. }
  10788. // 模型兼容性处理
  10789. $thinkingMode = 'disabled';
  10790. $reasoningEffort = 'high';
  10791. if ($model === 'deepseek-chat') {
  10792. $model = 'deepseek-v4-flash';
  10793. $thinkingMode = 'disabled';
  10794. } elseif ($model === 'deepseek-reasoner') {
  10795. $model = 'deepseek-v4-flash';
  10796. $thinkingMode = 'enabled';
  10797. }
  10798. // 构建消息
  10799. $messages = [
  10800. [
  10801. 'role' => 'system',
  10802. 'content' => $system_prompt
  10803. ],
  10804. [
  10805. 'role' => 'user',
  10806. 'content' => $user_prompt
  10807. ]
  10808. ];
  10809. // dd($messages);
  10810. // 构建请求参数
  10811. $post_data = [
  10812. 'model' => $model,
  10813. 'messages' => $messages,
  10814. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  10815. 'frequency_penalty' => 0,
  10816. 'presence_penalty' => 0,
  10817. 'response_format' => ['type' => 'text'],
  10818. 'thinking' => ['type' => $thinkingMode],
  10819. 'stream' => false // 非流式输出
  10820. ];
  10821. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  10822. // 调用AI生成新的分段剧本
  10823. try {
  10824. $fullContent = '';
  10825. $usage = [];
  10826. // 根据模型类型选择调用方法
  10827. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10828. // DeepSeek 官方模型使用 DeepSeek API
  10829. $chatResult = $this->chatOnly($post_data);
  10830. } else if (in_array($model, $this->gpt_text_models)) {
  10831. // GPT 模型使用 TokenRouter API
  10832. $chatResult = $this->gpt54ChatOnly($post_data);
  10833. } else {
  10834. // 其他模型使用火山引擎API
  10835. $chatResult = $this->volcEngineChatCompletion($post_data);
  10836. }
  10837. if (is_array($chatResult)) {
  10838. $fullContent = $chatResult['fullContent'] ?? '';
  10839. $usage = $chatResult['usage'] ?? [];
  10840. }
  10841. $generated_content = $fullContent;
  10842. if (empty($generated_content)) {
  10843. Utils::throwError('20003:AI生成内容为空,请重试');
  10844. }
  10845. // 解析生成的内容 - 按片段分割
  10846. $parsed_segments = [];
  10847. // 先在开头添加换行符,确保第1片段也能被正确分割
  10848. $normalizedText = "\n" . $generated_content;
  10849. $parts = preg_split('/\n\s*##/', $normalizedText);
  10850. foreach ($parts as $part) {
  10851. $part = trim($part);
  10852. if (empty($part)) continue;
  10853. // 匹配"片段X"格式
  10854. if (!preg_match('/^片段\d+/', $part)) {
  10855. continue;
  10856. }
  10857. // 分离标题和内容
  10858. $lines = explode("\n", $part, 2);
  10859. $actTitle = trim($lines[0]);
  10860. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  10861. // 解析标题,提取序号
  10862. $actNumber = 0;
  10863. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  10864. $actNumber = intval($segmentTitleMatch[1]);
  10865. } else {
  10866. $actNumber = count($parsed_segments) + 1;
  10867. }
  10868. // 提取时长(仅保留数字)
  10869. $actDuration = 0;
  10870. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  10871. $actDurationStr = trim($actDurationMatch[1]);
  10872. // 提取数字部分(支持整数和小数)
  10873. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  10874. $actDuration = (float)$numMatch[1];
  10875. }
  10876. }
  10877. // 清理act_content:去除时长、旁白音色等非分镜内容行
  10878. // 只保留分镜内容,并确保分镜标记使用【】格式
  10879. $cleaned_content = '';
  10880. $content_lines = explode("\n", $actContent);
  10881. $is_capturing = false; // 标记是否开始捕获分镜内容
  10882. $count = 0;
  10883. foreach ($content_lines as $line) {
  10884. $trimmed_line = trim($line);
  10885. // 跳过时长和旁白音色行
  10886. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  10887. continue;
  10888. }
  10889. // 检测是否是分镜开始
  10890. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  10891. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  10892. $count++;
  10893. $is_capturing = true;
  10894. // 如果没有【】,则添加
  10895. if (!preg_match('/^【/u', $trimmed_line)) {
  10896. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  10897. }
  10898. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  10899. }
  10900. // 如果已经开始捕获,则添加该行
  10901. if ($is_capturing && !empty($trimmed_line)) {
  10902. $cleaned_content .= $trimmed_line."\n";
  10903. }
  10904. }
  10905. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  10906. $parsed_segments[] = [
  10907. 'act_number' => $actNumber,
  10908. 'act_title' => $actTitle,
  10909. 'act_duration' => $actDuration,
  10910. 'act_content' => $cleaned_content,
  10911. ];
  10912. }
  10913. if (empty($parsed_segments)) {
  10914. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  10915. }
  10916. // 收集所有资产名称(角色、场景、道具)
  10917. $product_names = [];
  10918. // 收集角色名称
  10919. if (!empty($roles) && is_array($roles)) {
  10920. foreach ($roles as $role) {
  10921. $role_name = getProp($role, 'role', '');
  10922. if (!empty($role_name)) {
  10923. $product_names[] = $role_name;
  10924. }
  10925. }
  10926. }
  10927. // 收集场景名称
  10928. if (!empty($scenes) && is_array($scenes)) {
  10929. foreach ($scenes as $scene) {
  10930. $scene_name = getProp($scene, 'scene', '');
  10931. if (!empty($scene_name)) {
  10932. $product_names[] = $scene_name;
  10933. }
  10934. }
  10935. }
  10936. // 收集道具名称
  10937. if (!empty($props) && is_array($props)) {
  10938. foreach ($props as $prop) {
  10939. $prop_name = getProp($prop, 'prop', '');
  10940. if (!empty($prop_name)) {
  10941. $product_names[] = $prop_name;
  10942. }
  10943. }
  10944. }
  10945. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  10946. $product_names = array_unique($product_names);
  10947. usort($product_names, function($a, $b) {
  10948. return mb_strlen($b) - mb_strlen($a);
  10949. });
  10950. // 处理每个片段的 act_show_content
  10951. foreach ($parsed_segments as &$segment) {
  10952. $act_content = getProp($segment, 'act_content', '');
  10953. if (empty($act_content)) {
  10954. $segment['act_show_content'] = '';
  10955. continue;
  10956. }
  10957. $processed_content = $act_content;
  10958. // 统一替换所有资产名称为 {资产名} 格式
  10959. // 使用占位符避免嵌套替换问题
  10960. $placeholder_map = [];
  10961. $placeholder_index = 0;
  10962. foreach ($product_names as $product_name) {
  10963. // 转义特殊字符
  10964. $escaped_product = preg_quote($product_name, '/');
  10965. // 检查是否匹配且未被 {} 包裹
  10966. $processed_content = preg_replace_callback(
  10967. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  10968. function($matches) use (&$placeholder_map, &$placeholder_index) {
  10969. // 使用唯一占位符
  10970. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  10971. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  10972. $placeholder_index++;
  10973. return $placeholder;
  10974. },
  10975. $processed_content
  10976. );
  10977. }
  10978. // 将所有占位符替换回实际内容
  10979. foreach ($placeholder_map as $placeholder => $replacement) {
  10980. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  10981. }
  10982. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  10983. $shot_counter = 0;
  10984. $processed_content = preg_replace_callback(
  10985. '/【(?:镜头|分镜)(\d+)】/u',
  10986. function($matches) use (&$shot_counter) {
  10987. $shot_counter++;
  10988. return '【镜头' . $shot_counter . '】';
  10989. },
  10990. $processed_content
  10991. );
  10992. $segment['act_show_content'] = $processed_content;
  10993. }
  10994. unset($segment); // 解除引用
  10995. // 保存到数据库
  10996. $now = date('Y-m-d H:i:s');
  10997. $saved_acts = []; // 用于记录保存后的片段信息
  10998. if ($act_id > 0) {
  10999. // 单个片段模式:更新单条记录
  11000. if (count($parsed_segments) > 0) {
  11001. $new_segment = $parsed_segments[0];
  11002. $update_data = [
  11003. 'act_content' => getProp($new_segment, 'act_content', ''),
  11004. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  11005. 'act_title' => getProp($new_segment, 'act_title', ''),
  11006. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  11007. 'updated_at' => $now,
  11008. ];
  11009. DB::table('mp_episode_segments')
  11010. ->where('id', $act_id)
  11011. ->update($update_data);
  11012. // 获取更新后的记录
  11013. $updated_act = DB::table('mp_episode_segments')
  11014. ->where('id', $act_id)
  11015. ->first();
  11016. if ($updated_act) {
  11017. $saved_acts[] = [
  11018. 'act_id' => $updated_act->id,
  11019. 'act_number' => $updated_act->act_number,
  11020. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  11021. 'act_content' => $updated_act->act_content,
  11022. 'act_show_content' => $updated_act->act_show_content,
  11023. 'video_url' => $updated_act->video_url ?? '',
  11024. 'video_duration' => $updated_act->video_duration ?? 0,
  11025. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  11026. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  11027. ];
  11028. }
  11029. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  11030. }
  11031. } else {
  11032. // 整个剧集模式:删除原有记录并批量保存新记录
  11033. DB::beginTransaction();
  11034. try {
  11035. // 删除原有的所有片段记录
  11036. DB::table('mp_episode_segments')
  11037. ->where('episode_id', $target_episode_id)
  11038. ->delete();
  11039. // 批量插入新的片段记录
  11040. $segments_to_insert = [];
  11041. foreach ($parsed_segments as $index => $segment) {
  11042. $act_number = $index + 1;
  11043. $segments_to_insert[] = [
  11044. 'anime_id' => $target_anime_id,
  11045. 'episode_id' => $target_episode_id,
  11046. 'episode_number' => $target_episode_number,
  11047. 'act_number' => $act_number,
  11048. 'act_title' => getProp($segment, 'act_title', ''),
  11049. 'act_duration' => getProp($segment, 'act_duration', 0),
  11050. 'act_content' => getProp($segment, 'act_content', ''),
  11051. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  11052. 'created_at' => $now,
  11053. 'updated_at' => $now,
  11054. ];
  11055. }
  11056. if (!empty($segments_to_insert)) {
  11057. DB::table('mp_episode_segments')->insert($segments_to_insert);
  11058. }
  11059. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  11060. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  11061. 'anime_id' => $target_anime_id,
  11062. 'episode_id' => $target_episode_id,
  11063. 'model' => $model,
  11064. 'source' => 'regenerateSegmentScript',
  11065. ]);
  11066. DB::commit();
  11067. // 查询保存后的所有片段记录
  11068. $saved_segments = DB::table('mp_episode_segments')
  11069. ->where('episode_id', $target_episode_id)
  11070. ->orderBy('act_number')
  11071. ->get();
  11072. foreach ($saved_segments as $saved_segment) {
  11073. $saved_acts[] = [
  11074. 'act_id' => $saved_segment->id,
  11075. 'act_number' => $saved_segment->act_number,
  11076. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  11077. 'act_content' => $saved_segment->act_content,
  11078. 'act_show_content' => $saved_segment->act_show_content,
  11079. 'video_url' => $saved_segment->video_url ?? '',
  11080. 'video_duration' => $saved_segment->video_duration ?? 0,
  11081. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  11082. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  11083. ];
  11084. }
  11085. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  11086. 'episode_id' => $target_episode_id,
  11087. 'segments_count' => count($segments_to_insert)
  11088. ]);
  11089. } catch (\Exception $e) {
  11090. DB::rollBack();
  11091. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  11092. Utils::throwError('20003:保存失败,请重试');
  11093. }
  11094. }
  11095. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  11096. return [
  11097. 'anime_id' => $target_anime_id,
  11098. 'episode_id' => $target_episode_id,
  11099. 'title' => getProp($episode, 'title', ''),
  11100. 'episode_number' => $target_episode_number,
  11101. 'is_generated' => getProp($episode, 'is_generated', 0),
  11102. 'acts' => $saved_acts,
  11103. ];
  11104. } catch (\Exception $e) {
  11105. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  11106. throw $e;
  11107. }
  11108. }
  11109. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  11110. {
  11111. $episode_arr = [
  11112. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  11113. 'intro' => getProp($script_arr, 'intro'),
  11114. 'art_style' => getProp($script_arr, 'art_style'),
  11115. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  11116. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  11117. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  11118. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  11119. ];
  11120. if (empty($episode_arr['acts'])) {
  11121. $fallback_episode_arr = handleEpisodeContent($fullContent);
  11122. if (!empty($fallback_episode_arr['acts'])) {
  11123. $episode_arr = array_merge($fallback_episode_arr, [
  11124. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  11125. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  11126. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  11127. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  11128. ]);
  11129. }
  11130. }
  11131. // if (!getProp($episode_arr, 'episode_title')) {
  11132. // $episode_title = '';
  11133. // $episodes = getProp($script_arr, 'episodes', []);
  11134. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  11135. // $episode_title = '第1集:' . $episodes[0]['title'];
  11136. // }
  11137. // if (!$episode_title) {
  11138. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  11139. // }
  11140. // $episode_arr['episode_title'] = $episode_title;
  11141. // }
  11142. return $episode_arr;
  11143. }
  11144. private function saveEpisodeVersionData(
  11145. int $anime_id,
  11146. int $episode_number,
  11147. array $episode_arr,
  11148. array $existing_roles,
  11149. array $existing_scenes,
  11150. array $existing_props,
  11151. $current_episode,
  11152. $base_episode,
  11153. bool $is_regenerate_version,
  11154. string $content,
  11155. string $now,
  11156. array $ref_products = []
  11157. ): array {
  11158. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  11159. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  11160. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  11161. // 过滤掉关键字段为空的条目
  11162. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  11163. return !empty($item['role'] ?? null);
  11164. }));
  11165. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  11166. return !empty($item['scene'] ?? null);
  11167. }));
  11168. $merged_props = array_values(array_filter($generated_props, function ($item) {
  11169. return !empty($item['prop'] ?? null);
  11170. }));
  11171. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  11172. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  11173. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  11174. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  11175. $ace_mode = getProp($anime, 'ace_mode');
  11176. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  11177. $global_roles = json_decode(getProp($anime, 'roles'), true);
  11178. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  11179. $global_roles = is_array($global_roles) ? $global_roles : [];
  11180. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  11181. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  11182. $art_style_type = getProp($anime, 'art_style_type');
  11183. // 检查并创建 roles 的图片生成任务
  11184. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  11185. // 检查并创建 scenes 的图片生成任务
  11186. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  11187. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  11188. if ($arr && is_array($arr)) {
  11189. $merged_roles = $arr['roles'];
  11190. $merged_scenes = $arr['scenes'];
  11191. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  11192. }
  11193. // 确保数据是数组类型
  11194. if (!is_array($merged_roles)) {
  11195. dLog('deepseek')->error('merged_roles不是数组类型', [
  11196. 'type' => gettype($merged_roles),
  11197. 'value' => $merged_roles
  11198. ]);
  11199. $merged_roles = [];
  11200. }
  11201. if (!is_array($merged_scenes)) {
  11202. dLog('deepseek')->error('merged_scenes不是数组类型', [
  11203. 'type' => gettype($merged_scenes),
  11204. 'value' => $merged_scenes
  11205. ]);
  11206. $merged_scenes = [];
  11207. }
  11208. if (!is_array($merged_props)) {
  11209. dLog('deepseek')->error('merged_props不是数组类型', [
  11210. 'type' => gettype($merged_props),
  11211. 'value' => $merged_props
  11212. ]);
  11213. $merged_props = [];
  11214. }
  11215. // 同步新出现的主体和场景到全局
  11216. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  11217. $role_arr = [];
  11218. foreach ($merged_roles as $item) {
  11219. $role_arr[$item['role']] = $item;
  11220. }
  11221. $version_count = DB::table('mp_anime_episodes')
  11222. ->where('anime_id', $anime_id)
  11223. ->where('episode_number', $episode_number)
  11224. ->count('id');
  11225. $episode = [
  11226. 'anime_id' => $anime_id,
  11227. 'episode_number' => $episode_number,
  11228. 'title' => getProp($episode_arr, 'episode_title'),
  11229. 'content' => $content,
  11230. 'intro' => getProp($episode_arr, 'intro'),
  11231. 'art_style' => getProp($episode_arr, 'art_style'),
  11232. 'roles' => json_encode($merged_roles, 256),
  11233. 'scenes' => json_encode($merged_scenes, 256),
  11234. 'props' => json_encode($merged_props, 256),
  11235. 'generate_status' => '待执行',
  11236. 'generate_at' => $now,
  11237. 'is_default' => 1,
  11238. 'updated_at' => $now,
  11239. ];
  11240. $del_flag = false;
  11241. if ($is_regenerate_version) {
  11242. DB::table('mp_anime_episodes')
  11243. ->where('anime_id', $anime_id)
  11244. ->where('episode_number', $episode_number)
  11245. ->update(['is_default' => 0, 'updated_at' => $now]);
  11246. $episode['sequence'] = $version_count + 1;
  11247. $episode['created_at'] = $now;
  11248. $episode['cpid'] = Site::getCpid();
  11249. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  11250. if (!$episode_id) {
  11251. Utils::throwError('20003:创建剧集版本失败');
  11252. }
  11253. } else {
  11254. $target_episode = $current_episode ?: $base_episode;
  11255. if ($target_episode) {
  11256. $episode_id = getProp($target_episode, 'id');
  11257. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  11258. DB::table('mp_anime_episodes')
  11259. ->where('anime_id', $anime_id)
  11260. ->where('episode_number', $episode_number)
  11261. ->where('id', '<>', $episode_id)
  11262. ->update(['is_default' => 0, 'updated_at' => $now]);
  11263. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  11264. if ($boolen === false) {
  11265. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  11266. Utils::throwError('20003:分集内容保存失败');
  11267. }
  11268. $del_flag = true;
  11269. } else {
  11270. DB::table('mp_anime_episodes')
  11271. ->where('anime_id', $anime_id)
  11272. ->where('episode_number', $episode_number)
  11273. ->update(['is_default' => 0, 'updated_at' => $now]);
  11274. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  11275. $episode['created_at'] = $now;
  11276. $episode['cpid'] = Site::getCpid();
  11277. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  11278. if (!$episode_id) {
  11279. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  11280. Utils::throwError('20003:分集内容保存失败');
  11281. }
  11282. }
  11283. }
  11284. $segments = [];
  11285. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  11286. // 如果是第2集及以后,获取上一集的主体音色数据
  11287. $previous_roles_voice = [];
  11288. if ($episode_number >= 2) {
  11289. $previous_episode = DB::table('mp_anime_episodes')
  11290. ->where('anime_id', $anime_id)
  11291. ->where('episode_number', $episode_number - 1)
  11292. ->where('is_default', 1)
  11293. ->first();
  11294. if ($previous_episode) {
  11295. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  11296. if (is_array($previous_roles)) {
  11297. foreach ($previous_roles as $prev_role) {
  11298. $role_name = getProp($prev_role, 'role');
  11299. if ($role_name) {
  11300. $previous_roles_voice[$role_name] = [
  11301. 'voice_name' => getProp($prev_role, 'voice_name'),
  11302. 'voice_type' => getProp($prev_role, 'voice_type'),
  11303. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  11304. ];
  11305. $voice_prompt = getProp($prev_role, 'voice_prompt');
  11306. if ($voice_prompt) {
  11307. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  11308. }
  11309. }
  11310. }
  11311. }
  11312. }
  11313. }
  11314. // 将继承的音色数据同步到当前集的主体列表
  11315. if (!empty($previous_roles_voice)) {
  11316. foreach ($merged_roles as &$role) {
  11317. $role_name = getProp($role, 'role');
  11318. if ($role_name && isset($previous_roles_voice[$role_name])) {
  11319. // 强制继承上一集的音色数据
  11320. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  11321. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  11322. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  11323. // 如果上一集有 voice_prompt 则继承,否则跳过
  11324. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  11325. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  11326. }
  11327. }
  11328. }
  11329. unset($role); // 解除引用
  11330. // 更新 role_arr 以便后续使用
  11331. $role_arr = [];
  11332. foreach ($merged_roles as $item) {
  11333. $role_arr[$item['role']] = $item;
  11334. }
  11335. }
  11336. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  11337. $emotion_list = array_flip($emotion_list);
  11338. foreach ($acts as $act) {
  11339. $act_segments = getProp($act, 'segments', []);
  11340. if (!is_array($act_segments)) {
  11341. continue;
  11342. }
  11343. if ((int)$ace_mode === 1) {
  11344. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  11345. $merged_parts = [];
  11346. foreach ($act_segments as $seg) {
  11347. $seg_num = getProp($seg, 'segment_number');
  11348. $seg_content = getProp($seg, 'segment_content');
  11349. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  11350. }
  11351. $act_content = implode("\n", $merged_parts);
  11352. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  11353. $segments[] = [
  11354. 'anime_id' => $anime_id,
  11355. 'episode_id' => $episode_id,
  11356. 'episode_number' => $episode_number,
  11357. 'act_number' => getProp($act, 'act_number'),
  11358. 'act_title' => getProp($act, 'act_title'),
  11359. 'act_duration' => getProp($act, 'act_duration'),
  11360. 'act_content' => $act_content,
  11361. 'created_at' => $now,
  11362. 'updated_at' => $now
  11363. ];
  11364. } else {
  11365. foreach ($act_segments as $segment) {
  11366. $voice_actor = getProp($segment, 'voice_actor');
  11367. // 优先从上一集继承音色数据
  11368. $timbre_info = [];
  11369. if (isset($previous_roles_voice[$voice_actor])) {
  11370. // 从上一集继承音色数据
  11371. $timbre_info = $previous_roles_voice[$voice_actor];
  11372. } elseif (isset($role_arr[$voice_actor])) {
  11373. // 使用当前集的主体音色数据
  11374. $timbre_info = $role_arr[$voice_actor];
  11375. }
  11376. $voice_type = getProp($timbre_info, 'voice_type');
  11377. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  11378. if ($timbre_emotion) {
  11379. $timbre_emotion = explode(',', $timbre_emotion);
  11380. } else {
  11381. $timbre_emotion = [];
  11382. }
  11383. $emotion = getProp($segment, 'emotion', '中性');
  11384. if (!in_array($emotion, $timbre_emotion)) {
  11385. $emotion = '中性';
  11386. }
  11387. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  11388. $segments[] = [
  11389. 'anime_id' => $anime_id,
  11390. 'episode_id' => $episode_id,
  11391. 'episode_number' => $episode_number,
  11392. 'act_number' => getProp($act, 'act_number'),
  11393. 'act_title' => getProp($act, 'act_title'),
  11394. 'act_duration' => getProp($act, 'act_duration'),
  11395. 'segment_id' => getProp($segment, 'segment_id'),
  11396. 'segment_number' => getProp($segment, 'segment_number'),
  11397. 'segment_content' => getProp($segment, 'segment_content'),
  11398. 'description' => getProp($segment, 'description'),
  11399. 'composition' => getProp($segment, 'composition'),
  11400. 'camera_movement' => getProp($segment, 'camera_movement'),
  11401. 'voice_actor' => $voice_actor,
  11402. 'dialogue' => getProp($segment, 'dialogue'),
  11403. 'frame_type' => getProp($segment, 'frame_type'),
  11404. 'scene' => getProp($segment, 'scene'),
  11405. 'characters' => getProp($segment, 'characters'),
  11406. 'tail_frame' => getProp($segment, 'tail_frame'),
  11407. 'voice_name' => getProp($timbre_info, 'voice_name'),
  11408. 'voice_type' => $voice_type,
  11409. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  11410. 'emotion' => $emotion,
  11411. 'emotion_type' => $emotion_type,
  11412. 'gender' => getProp($segment, 'gender', '0'),
  11413. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  11414. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  11415. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  11416. 'pitch' => getProp($segment, 'pitch', 0),
  11417. 'created_at' => $now,
  11418. 'updated_at' => $now
  11419. ];
  11420. }
  11421. }
  11422. }
  11423. if ($segments) {
  11424. if ($del_flag) {
  11425. DB::table('mp_episode_segments')
  11426. ->where('anime_id', $anime_id)
  11427. ->where('episode_id', $episode_id)
  11428. ->delete();
  11429. }
  11430. $boolen = DB::table('mp_episode_segments')->insert($segments);
  11431. if (!$boolen) {
  11432. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  11433. Utils::throwError('20003:分镜内容保存失败');
  11434. }
  11435. }
  11436. dLog('deepseek')->info('segments', $segments);
  11437. // ace_mode=1: acts 返回值按合并格式调整
  11438. if ((int)$ace_mode === 1) {
  11439. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  11440. $act_map = [];
  11441. foreach ($table_act_data as $item) {
  11442. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  11443. }
  11444. $restructured_acts = [];
  11445. foreach ($acts as $act) {
  11446. $act_segments = getProp($act, 'segments', []);
  11447. if (!is_array($act_segments)) {
  11448. continue;
  11449. }
  11450. $merged_parts = [];
  11451. foreach ($act_segments as $seg) {
  11452. $seg_num = getProp($seg, 'segment_number');
  11453. $seg_content = getProp($seg, 'segment_content');
  11454. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  11455. }
  11456. $act_content = implode("\n", $merged_parts);
  11457. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  11458. $restructured_acts[] = [
  11459. 'anime_id' => $anime_id,
  11460. 'episode_id' => $episode_id,
  11461. 'episode_number' => $episode_number,
  11462. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  11463. 'act_number' => getProp($act, 'act_number'),
  11464. 'act_title' => getProp($act, 'act_title'),
  11465. 'act_duration' => getProp($act, 'act_duration'),
  11466. 'act_content' => $act_content,
  11467. 'created_at' => $now,
  11468. 'updated_at' => $now,
  11469. ];
  11470. }
  11471. $acts = $restructured_acts;
  11472. }
  11473. $episode['episode_id'] = $episode_id;
  11474. $episode['roles'] = $merged_roles;
  11475. $episode['scenes'] = $merged_scenes;
  11476. $episode['props'] = $merged_props;
  11477. $episode['acts'] = $acts;
  11478. return [
  11479. 'episode' => $episode,
  11480. 'episode_id' => $episode_id,
  11481. 'merged_roles' => $merged_roles,
  11482. 'merged_scenes' => $merged_scenes,
  11483. 'merged_props' => $merged_props,
  11484. ];
  11485. }
  11486. private function buildEpisodeItemContent(array $items, string $nameKey): string
  11487. {
  11488. $content = '';
  11489. foreach ($items as $item) {
  11490. $name = trim((string)getProp($item, $nameKey));
  11491. if ($name === '' || $name === '旁白') {
  11492. continue;
  11493. }
  11494. $description = trim((string)getProp($item, 'description'));
  11495. $content .= $name . ': ' . $description;
  11496. if ($nameKey == 'role') {
  11497. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  11498. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11499. $voice_name = trim(getProp($item, 'voice_name'));
  11500. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  11501. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  11502. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  11503. }else {
  11504. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  11505. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11506. }
  11507. $content .= "\n";
  11508. }
  11509. return trim($content);
  11510. }
  11511. private function getEpisodeChatContent($animeId, $sequence, $content) {
  11512. if ((int)$sequence <= 0) {
  11513. return [];
  11514. }
  11515. $origin_content = '';
  11516. if ($content) {
  11517. $origin_content = '本集剧情内容:'.$content;
  11518. }else {
  11519. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  11520. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  11521. }
  11522. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  11523. // 获取分集信息
  11524. $episode = DB::table('mp_anime_episodes')
  11525. ->where('anime_id', $animeId)
  11526. ->where('episode_number', $sequence)
  11527. ->where('is_default', 1)
  11528. ->first();
  11529. if (!$episode) {
  11530. return [];
  11531. }
  11532. $episode_id = getProp($episode, 'id');
  11533. $episode_number = getProp($episode, 'episode_number');
  11534. $title = getProp($episode, 'title');
  11535. $intro = getProp($episode, 'intro');
  11536. $art_style = getProp($episode, 'art_style');
  11537. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  11538. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  11539. // 组装纯文本内容
  11540. $content = '';
  11541. // 添加分集标题和梗概
  11542. $content .= "###第{$episode_number}集:{$title}\n\n";
  11543. $content .= "###故事梗概\n";
  11544. $content .= trim($intro) . "\n\n";
  11545. // 添加美术风格
  11546. $content .= "###美术风格\n";
  11547. $content .= trim($art_style) . "\n\n";
  11548. // 添加主体列表
  11549. $content .= "###主体列表\n";
  11550. $pangbai_voice_prompt = "";
  11551. foreach ($roles as $role) {
  11552. $name = getProp($role, 'role');
  11553. $description = getProp($role, 'description');
  11554. $pic_prompt = getProp($role, 'pic_prompt');
  11555. $voice_prompt = getProp($role, 'voice_prompt');
  11556. $voice_name = getProp($role, 'voice_name');
  11557. $content .= "{$name}: {$description}";
  11558. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11559. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  11560. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  11561. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  11562. $content .= "\n";
  11563. }
  11564. $content .= "\n";
  11565. // 添加场景列表
  11566. $content .= "###场景列表\n";
  11567. foreach ($scenes as $scene) {
  11568. $name = getProp($scene, 'scene');
  11569. $description = getProp($scene, 'description');
  11570. $pic_prompt = getProp($scene, 'pic_prompt');
  11571. $content .= "{$name}: {$description}";
  11572. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  11573. $content .= "\n";
  11574. }
  11575. $content .= "\n";
  11576. // 获取分镜信息
  11577. $segments = DB::table('mp_episode_segments')
  11578. ->where('anime_id', $animeId)
  11579. ->where('episode_id', $episode_id)
  11580. ->orderBy('segment_number')
  11581. ->get();
  11582. if ($segments && count($segments) > 0) {
  11583. if ((int)$ace_mode === 1) {
  11584. $content .= "###分段剧本\n";
  11585. // 获取片段数量
  11586. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  11587. $content .= "片段数量:{$act_count}\n";
  11588. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  11589. $content .= "\n";
  11590. }else {
  11591. $content .= "###分镜剧本\n";
  11592. }
  11593. // 按幕分组
  11594. $currentAct = null;
  11595. foreach ($segments as $segment) {
  11596. $act_number = getProp($segment, 'act_number');
  11597. $act_title = getProp($segment, 'act_title');
  11598. $act_duration = getProp($segment, 'act_duration');
  11599. $segment_number = getProp($segment, 'segment_number');
  11600. $segment_content = getProp($segment, 'segment_content');
  11601. $scene_description = getProp($segment, 'scene_description');
  11602. $scene_name = getProp($segment, 'scene_name');
  11603. $composition = getProp($segment, 'composition');
  11604. $camera_movement = getProp($segment, 'camera_movement');
  11605. $voice_type = getProp($segment, 'voice_type');
  11606. $characters = getProp($segment, 'characters');
  11607. $dialogue = getProp($segment, 'dialogue');
  11608. $frame_type = getProp($segment, 'frame_type');
  11609. $tail_frame_description = getProp($segment, 'tail_frame_description');
  11610. // 判断是否是全能模式
  11611. if ((int)$ace_mode === 1) { // 全能模式
  11612. // 如果是新的分段,添加分段标题
  11613. if ($act_number !== $currentAct) {
  11614. $currentAct = $act_number;
  11615. $content .= "##{$act_title}\n";
  11616. $content .= "时长:{$act_duration}s\n";
  11617. }
  11618. }else {
  11619. // 如果是新的幕,添加幕标题
  11620. if ($act_number !== $currentAct) {
  11621. $currentAct = $act_number;
  11622. $content .= "##第{$act_number}幕:{$scene_name}\n";
  11623. }
  11624. }
  11625. // 添加分镜信息
  11626. $content .= "分镜{$segment_number}\n";
  11627. $content .= "分镜内容:\n{$segment_content}\n";
  11628. // $content .= "画面描述:{$scene_description}\n";
  11629. // $content .= "场景:{$scene_name}\n";
  11630. // $content .= "构图设计:{$composition}\n";
  11631. // $content .= "运镜调度:{$camera_movement}\n";
  11632. // if (!empty($voice_type)) {
  11633. // $content .= "配音角色:{$voice_type}\n";
  11634. // }
  11635. // if (!empty($characters)) {
  11636. // $content .= "出镜角色:{$characters}\n";
  11637. // }
  11638. // if (!empty($dialogue)) {
  11639. // $content .= "台词内容:\"{$dialogue}\"\n";
  11640. // }
  11641. // $content .= "画面类型:{$frame_type}\n";
  11642. // $content .= "尾帧描述:{$tail_frame_description}\n";
  11643. $content .= "\n";
  11644. }
  11645. }
  11646. $content = trim($content);
  11647. if($content) $content = "上集剧本内容:\n{$content}";
  11648. return [
  11649. [
  11650. 'role' => 'user',
  11651. 'content' => $origin_content
  11652. ],
  11653. [
  11654. 'role' => 'assistant',
  11655. 'content' => $content
  11656. ]
  11657. ];
  11658. }
  11659. private function getEpisodeChatMessages($animeId, $sequence): array
  11660. {
  11661. if ((int)$sequence <= 0) {
  11662. return [];
  11663. }
  11664. return DB::table('mp_anime_records')
  11665. ->where('anime_id', $animeId)
  11666. ->where('sequence', $sequence)
  11667. ->where('episode_id', '>', 0)
  11668. ->select('role', 'content')
  11669. ->orderBy('created_at')
  11670. ->orderBy('id')
  11671. ->get()
  11672. ->map(function ($value) {
  11673. return (array)$value;
  11674. })
  11675. ->toArray();
  11676. }
  11677. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  11678. {
  11679. $existingMap = [];
  11680. foreach ($existingItems as $item) {
  11681. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  11682. if ($itemKey === '') {
  11683. continue;
  11684. }
  11685. $existingMap[$itemKey] = $item;
  11686. }
  11687. if (!$generatedItems) {
  11688. return array_values($existingItems);
  11689. }
  11690. $merged = [];
  11691. foreach ($generatedItems as $item) {
  11692. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  11693. if ($itemKey === '') {
  11694. continue;
  11695. }
  11696. if (isset($existingMap[$itemKey])) {
  11697. if (trim((string)getProp($item, 'description')) === '') {
  11698. $merged[] = $existingMap[$itemKey];
  11699. continue;
  11700. }
  11701. // 检查内容是否发生变化
  11702. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  11703. if (!$isChanged) {
  11704. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  11705. $mergedItem = [
  11706. $nameKey => trim((string)getProp($item, $nameKey)),
  11707. 'description' => trim((string)getProp($item, 'description')),
  11708. ];
  11709. // 如果有 pic_prompt,添加到合并项中
  11710. $picPrompt = getProp($item, 'pic_prompt');
  11711. if (!empty($picPrompt)) {
  11712. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  11713. }
  11714. // 继承现有项的 URL
  11715. $existingUrl = getProp($existingMap[$itemKey], 'url');
  11716. if (!empty($existingUrl)) {
  11717. $mergedItem['url'] = $existingUrl;
  11718. }
  11719. // 继承现有项的 task_id
  11720. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  11721. if (!empty($existingTaskId)) {
  11722. $mergedItem['task_id'] = $existingTaskId;
  11723. }
  11724. // 继承现有项的 task_status
  11725. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  11726. if (!empty($existingTaskStatus)) {
  11727. $mergedItem['task_status'] = $existingTaskStatus;
  11728. }
  11729. // 保留生成项的音色字段
  11730. $voiceName = getProp($item, 'voice_name');
  11731. if (!empty($voiceName)) {
  11732. $mergedItem['voice_name'] = $voiceName;
  11733. }
  11734. $voiceType = getProp($item, 'voice_type');
  11735. if (!empty($voiceType)) {
  11736. $mergedItem['voice_type'] = $voiceType;
  11737. }
  11738. $audioUrl = getProp($item, 'voice_audio_url');
  11739. if (!empty($audioUrl)) {
  11740. $mergedItem['voice_audio_url'] = $audioUrl;
  11741. }
  11742. $merged[] = $mergedItem;
  11743. } else {
  11744. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  11745. $mergedItem = [
  11746. $nameKey => trim((string)getProp($item, $nameKey)),
  11747. 'description' => trim((string)getProp($item, 'description')),
  11748. ];
  11749. // 如果有 pic_prompt,添加到合并项中
  11750. $picPrompt = getProp($item, 'pic_prompt');
  11751. if (!empty($picPrompt)) {
  11752. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  11753. }
  11754. // 保留生成项的音色字段
  11755. $voiceName = getProp($item, 'voice_name');
  11756. if (!empty($voiceName)) {
  11757. $mergedItem['voice_name'] = $voiceName;
  11758. }
  11759. $voiceType = getProp($item, 'voice_type');
  11760. if (!empty($voiceType)) {
  11761. $mergedItem['voice_type'] = $voiceType;
  11762. }
  11763. $audioUrl = getProp($item, 'voice_audio_url');
  11764. if (!empty($audioUrl)) {
  11765. $mergedItem['voice_audio_url'] = $audioUrl;
  11766. }
  11767. // 不继承 URL、task_id 和 task_status(重置状态)
  11768. $merged[] = $mergedItem;
  11769. }
  11770. } else {
  11771. // 新增项,保留生成项的所有字段
  11772. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  11773. }
  11774. }
  11775. return $merged ?: array_values($existingItems);
  11776. }
  11777. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  11778. {
  11779. $resetItem = [
  11780. $nameKey => trim((string)getProp($item, $nameKey)),
  11781. 'description' => trim((string)getProp($item, 'description')),
  11782. ];
  11783. // 保留指定的字段
  11784. foreach ($preserveFields as $field) {
  11785. $value = getProp($item, $field);
  11786. if (!empty($value)) {
  11787. $resetItem[$field] = $value;
  11788. }
  11789. }
  11790. return $resetItem;
  11791. }
  11792. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  11793. {
  11794. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  11795. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  11796. if ($existingKey !== $generatedKey) {
  11797. return true;
  11798. }
  11799. // 比较 description 是否变化
  11800. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  11801. return true;
  11802. }
  11803. // 比较 pic_prompt 是否变化
  11804. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  11805. }
  11806. private function normalizeEpisodeResourceKey($value): string
  11807. {
  11808. $value = trim((string)$value);
  11809. if ($value === '') {
  11810. return '';
  11811. }
  11812. return strtolower((string)preg_replace('/\s+/u', '', $value));
  11813. }
  11814. // 生成全局角色图片
  11815. private function batchSetGlobalRoleImg($data, $is_force=false) {
  11816. $anime_id = getProp($data, 'anime_id');
  11817. if (!$anime_id) Utils::throwError('1002:请选择对话');
  11818. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11819. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11820. $art_style = getProp($anime, 'art_style');
  11821. $update_flag = false;
  11822. foreach ($roles as &$role) {
  11823. $role_name = getProp($role, 'role');
  11824. if ($role_name == '旁白') continue;
  11825. // 优先使用 pic_prompt,如果没有则使用 description
  11826. $pic_prompt = getProp($role, 'pic_prompt');
  11827. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  11828. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  11829. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  11830. // 参考图地址
  11831. $ref_img_url = getProp($role, 'url');
  11832. if (!$is_force && $ref_img_url) continue;
  11833. $update_flag = true;
  11834. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  11835. try {
  11836. $params = [
  11837. 'prompt' => $description,
  11838. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  11839. 'ref_img_urls' => []
  11840. ];
  11841. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11842. $task_id = $task->id;
  11843. if (!$task_id) {
  11844. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  11845. }
  11846. $role['task_id'] = $task_id;
  11847. $role['task_status'] = 'processing';
  11848. } catch (\Exception $e) {
  11849. Utils::throwError("20003:" . $e->getMessage());
  11850. }
  11851. }
  11852. if (!$update_flag) return true;
  11853. // 保存角色信息
  11854. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  11855. 'roles' => json_encode($roles, 256),
  11856. 'generate_status' => '执行中',
  11857. 'generate_at' => date('Y-m-d H:i:s'),
  11858. 'updated_at' => date('Y-m-d H:i:s')
  11859. ]);
  11860. if (!$boolen) {
  11861. Utils::throwError('20003:保存角色信息失败');
  11862. }
  11863. return $boolen;
  11864. }
  11865. // 生成全局场景图片
  11866. private function batchSetGlobalSceneImg($data, $is_force=false) {
  11867. $anime_id = getProp($data, 'anime_id');
  11868. if (!$anime_id) Utils::throwError('1002:请选择对话');
  11869. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11870. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11871. $art_style = getProp($anime, 'art_style');
  11872. $update_flag = false;
  11873. foreach ($scenes as &$scene) {
  11874. $scene_name = getProp($scene, 'scene');
  11875. // 优先使用 pic_prompt,如果没有则使用 description
  11876. $pic_prompt = getProp($scene, 'pic_prompt');
  11877. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  11878. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  11879. // 参考图地址
  11880. $ref_img_url = getProp($scene, 'url');
  11881. if (!$is_force && $ref_img_url) continue;
  11882. $update_flag = true;
  11883. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  11884. try {
  11885. $params = [
  11886. 'prompt' => $description,
  11887. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  11888. 'ref_img_urls' => []
  11889. ];
  11890. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11891. $task_id = $task->id;
  11892. if (!$task_id) {
  11893. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  11894. }
  11895. $scene['task_id'] = $task_id;
  11896. $scene['task_status'] = 'processing';
  11897. } catch (\Exception $e) {
  11898. Utils::throwError("20003:" . $e->getMessage());
  11899. }
  11900. }
  11901. if (!$update_flag) return true;
  11902. // 保存角色信息
  11903. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  11904. 'scenes' => json_encode($scenes, 256),
  11905. 'generate_status' => '执行中',
  11906. 'generate_at' => date('Y-m-d H:i:s'),
  11907. 'updated_at' => date('Y-m-d H:i:s')
  11908. ]);
  11909. if (!$boolen) {
  11910. Utils::throwError('20003:保存角色信息失败');
  11911. }
  11912. return $boolen;
  11913. }
  11914. // 生成分镜主体、场景和道具图片
  11915. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  11916. $character_prefix = '';
  11917. $scene_prefix = '';
  11918. $prop_prefix = '';
  11919. if ($art_style_type) {
  11920. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  11921. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  11922. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  11923. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  11924. }
  11925. $update_flag = false;
  11926. // 获取上一集的roles、scenes和props数据
  11927. $prev_roles = [];
  11928. $prev_scenes = [];
  11929. $prev_props = [];
  11930. if ($episode_number > 1) {
  11931. $prev_episode = DB::table('mp_anime_episodes')
  11932. ->where('anime_id', $anime_id)
  11933. ->where('episode_number', $episode_number - 1)
  11934. ->where('is_default', 1)
  11935. ->first();
  11936. if ($prev_episode) {
  11937. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  11938. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  11939. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  11940. dLog('deepseek')->info("获取上一集数据成功", [
  11941. 'anime_id' => $anime_id,
  11942. 'prev_episode_number' => $episode_number - 1,
  11943. 'prev_roles_count' => count($prev_roles),
  11944. 'prev_scenes_count' => count($prev_scenes),
  11945. 'prev_props_count' => count($prev_props)
  11946. ]);
  11947. }
  11948. }
  11949. // 处理角色图片生成
  11950. foreach ($roles as &$role) {
  11951. $role_name = getProp($role, 'role');
  11952. if ($role_name == '旁白') continue;
  11953. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  11954. if (isset($ref_products[$role_name])) {
  11955. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  11956. if ($role['url']) continue;
  11957. }
  11958. $role_description = getProp($role, 'description');
  11959. $role_pic_prompt = getProp($role, 'pic_prompt');
  11960. $role_url = getProp($role, 'url');
  11961. // 检查是否可以从上一集继承
  11962. $inherited = false;
  11963. if (!$is_force && !empty($prev_roles)) {
  11964. foreach ($prev_roles as $prev_role) {
  11965. $prev_role_name = getProp($prev_role, 'role');
  11966. $prev_description = getProp($prev_role, 'description');
  11967. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  11968. $prev_url = getProp($prev_role, 'url');
  11969. $prev_task_id = getProp($prev_role, 'task_id');
  11970. $prev_task_status = getProp($prev_role, 'task_status');
  11971. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  11972. if ($role_name == $prev_role_name
  11973. && $role_description == $prev_description
  11974. && $role_pic_prompt == $prev_pic_prompt
  11975. && !empty($prev_url)) {
  11976. $role['task_id'] = $prev_task_id;
  11977. $role['task_status'] = $prev_task_status;
  11978. $role['url'] = $prev_url;
  11979. $inherited = true;
  11980. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  11981. 'anime_id' => $anime_id,
  11982. 'episode_number' => $episode_number,
  11983. 'task_id' => $prev_task_id,
  11984. 'url' => $prev_url
  11985. ]);
  11986. break;
  11987. }
  11988. }
  11989. }
  11990. // 如果已继承或已有url,跳过生成
  11991. if ($inherited || (!$is_force && $role_url)) {
  11992. continue;
  11993. }
  11994. // 优先使用 pic_prompt,如果没有则使用 description
  11995. $pic_prompt = getProp($role, 'pic_prompt');
  11996. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  11997. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11998. $update_flag = true;
  11999. // 调用AIImageGenerationService的生成图片任务接口
  12000. try {
  12001. $params = [
  12002. 'prompt' => $description,
  12003. 'ref_img_urls' => []
  12004. ];
  12005. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12006. $task_id = $task->id;
  12007. if (!$task_id) {
  12008. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  12009. continue; // 不中断,继续处理其他角色
  12010. }
  12011. $role['task_id'] = $task_id;
  12012. $role['task_status'] = 'processing';
  12013. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  12014. 'anime_id' => $anime_id,
  12015. 'episode_number' => $episode_number,
  12016. 'task_id' => $task_id
  12017. ]);
  12018. } catch (\Exception $e) {
  12019. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  12020. // 不抛出异常,继续处理其他角色
  12021. }
  12022. }
  12023. // 处理场景图片生成
  12024. foreach ($scenes as &$scene) {
  12025. $scene_name = getProp($scene, 'scene');
  12026. $scene_description = getProp($scene, 'description');
  12027. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  12028. $scene_url = getProp($scene, 'url');
  12029. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  12030. if (isset($ref_products[$scene_name])) {
  12031. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  12032. if ($scene['url']) continue;
  12033. }
  12034. // 检查是否可以从上一集继承
  12035. $inherited = false;
  12036. if (!$is_force && !empty($prev_scenes)) {
  12037. foreach ($prev_scenes as $prev_scene) {
  12038. $prev_scene_name = getProp($prev_scene, 'scene');
  12039. $prev_description = getProp($prev_scene, 'description');
  12040. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  12041. $prev_url = getProp($prev_scene, 'url');
  12042. $prev_task_id = getProp($prev_scene, 'task_id');
  12043. $prev_task_status = getProp($prev_scene, 'task_status');
  12044. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  12045. if ($scene_name == $prev_scene_name
  12046. && $scene_description == $prev_description
  12047. && $scene_pic_prompt == $prev_pic_prompt
  12048. && !empty($prev_url)) {
  12049. $scene['task_id'] = $prev_task_id;
  12050. $scene['task_status'] = $prev_task_status;
  12051. $scene['url'] = $prev_url;
  12052. $inherited = true;
  12053. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  12054. 'anime_id' => $anime_id,
  12055. 'episode_number' => $episode_number,
  12056. 'task_id' => $prev_task_id,
  12057. 'url' => $prev_url
  12058. ]);
  12059. break;
  12060. }
  12061. }
  12062. }
  12063. // 如果已继承或已有url,跳过生成
  12064. if ($inherited || (!$is_force && $scene_url)) {
  12065. continue;
  12066. }
  12067. // 优先使用 pic_prompt,如果没有则使用 description
  12068. $pic_prompt = getProp($scene, 'pic_prompt');
  12069. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  12070. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  12071. $update_flag = true;
  12072. // 调用AIImageGenerationService的生成图片任务接口
  12073. try {
  12074. $params = [
  12075. 'prompt' => $description,
  12076. 'ref_img_urls' => []
  12077. ];
  12078. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12079. $task_id = $task->id;
  12080. if (!$task_id) {
  12081. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  12082. continue; // 不中断,继续处理其他场景
  12083. }
  12084. $scene['task_id'] = $task_id;
  12085. $scene['task_status'] = 'processing';
  12086. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  12087. 'anime_id' => $anime_id,
  12088. 'episode_number' => $episode_number,
  12089. 'task_id' => $task_id
  12090. ]);
  12091. } catch (\Exception $e) {
  12092. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  12093. // 不抛出异常,继续处理其他场景
  12094. }
  12095. }
  12096. // 处理道具图片生成(逻辑与场景一致)
  12097. foreach ($props as &$prop) {
  12098. $prop_name = getProp($prop, 'prop');
  12099. $prop_description = getProp($prop, 'description');
  12100. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  12101. $prop_url = getProp($prop, 'url');
  12102. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  12103. if (isset($ref_products[$prop_name])) {
  12104. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  12105. if ($prop['url']) continue;
  12106. }
  12107. // 检查是否可以从上一集继承
  12108. $inherited = false;
  12109. if (!$is_force && !empty($prev_props)) {
  12110. foreach ($prev_props as $prev_prop) {
  12111. $prev_prop_name = getProp($prev_prop, 'prop');
  12112. $prev_description = getProp($prev_prop, 'description');
  12113. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  12114. $prev_url = getProp($prev_prop, 'url');
  12115. $prev_task_id = getProp($prev_prop, 'task_id');
  12116. $prev_task_status = getProp($prev_prop, 'task_status');
  12117. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  12118. if ($prop_name == $prev_prop_name
  12119. && $prop_description == $prev_description
  12120. && $prop_pic_prompt == $prev_pic_prompt
  12121. && !empty($prev_url)) {
  12122. $prop['task_id'] = $prev_task_id;
  12123. $prop['task_status'] = $prev_task_status;
  12124. $prop['url'] = $prev_url;
  12125. $inherited = true;
  12126. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  12127. 'anime_id' => $anime_id,
  12128. 'episode_number' => $episode_number,
  12129. 'task_id' => $prev_task_id,
  12130. 'url' => $prev_url
  12131. ]);
  12132. break;
  12133. }
  12134. }
  12135. }
  12136. // 如果已继承或已有url,跳过生成
  12137. if ($inherited || (!$is_force && $prop_url)) {
  12138. continue;
  12139. }
  12140. // 优先使用 pic_prompt,如果没有则使用 description
  12141. $pic_prompt = getProp($prop, 'pic_prompt');
  12142. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  12143. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  12144. $update_flag = true;
  12145. // 调用AIImageGenerationService的生成图片任务接口
  12146. try {
  12147. $params = [
  12148. 'prompt' => $description,
  12149. 'ref_img_urls' => []
  12150. ];
  12151. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12152. $task_id = $task->id;
  12153. if (!$task_id) {
  12154. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  12155. continue; // 不中断,继续处理其他道具
  12156. }
  12157. $prop['task_id'] = $task_id;
  12158. $prop['task_status'] = 'processing';
  12159. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  12160. 'anime_id' => $anime_id,
  12161. 'episode_number' => $episode_number,
  12162. 'task_id' => $task_id
  12163. ]);
  12164. } catch (\Exception $e) {
  12165. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  12166. // 不抛出异常,继续处理其他道具
  12167. }
  12168. }
  12169. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  12170. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  12171. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  12172. // // 保存剧集的角色和场景信息
  12173. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  12174. // 'roles' => json_encode($roles, 256),
  12175. // 'scenes' => json_encode($scenes, 256),
  12176. // 'generate_status' => '执行中',
  12177. // 'generate_at' => date('Y-m-d H:i:s'),
  12178. // 'updated_at' => date('Y-m-d H:i:s')
  12179. // ]);
  12180. // if (!$boolen) {
  12181. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  12182. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  12183. // }
  12184. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  12185. // 'episode_id' => $episode_id,
  12186. 'roles_count' => count($roles),
  12187. 'scenes_count' => count($scenes),
  12188. 'props_count' => count($props)
  12189. ]);
  12190. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  12191. }
  12192. /**
  12193. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  12194. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  12195. *
  12196. * @param int $anime_id 动漫对话ID
  12197. * @param array $episode_roles 剧集角色数据
  12198. * @param array $episode_scenes 剧集场景数据
  12199. * @param array $episode_props 剧集道具数据
  12200. * @return bool
  12201. */
  12202. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  12203. // 获取全局数据
  12204. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12205. if (!$anime) {
  12206. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  12207. return false;
  12208. }
  12209. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  12210. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  12211. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  12212. $roles_added = false;
  12213. $roles_updated = false;
  12214. $scenes_added = false;
  12215. $props_added = false;
  12216. // 处理角色同步
  12217. foreach ($episode_roles as $episode_role) {
  12218. $episode_role_name = getProp($episode_role, 'role');
  12219. $episode_description = getProp($episode_role, 'description');
  12220. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  12221. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  12222. // 跳过旁白
  12223. if ($episode_role_name == '旁白') {
  12224. continue;
  12225. }
  12226. // 检查全局中是否已存在相同的角色
  12227. $exists = false;
  12228. $global_role_index = -1;
  12229. foreach ($global_roles as $index => $global_role) {
  12230. $global_role_name = getProp($global_role, 'role');
  12231. $global_description = getProp($global_role, 'description');
  12232. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  12233. // 如果role、description、pic_prompt三项都一致,则认为已存在
  12234. if ($episode_role_name == $global_role_name
  12235. && $episode_description == $global_description
  12236. && $episode_pic_prompt == $global_pic_prompt) {
  12237. $exists = true;
  12238. $global_role_index = $index;
  12239. break;
  12240. }
  12241. }
  12242. // 如果不存在,则添加到全局
  12243. if (!$exists) {
  12244. $global_roles[] = $episode_role;
  12245. $roles_added = true;
  12246. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  12247. 'anime_id' => $anime_id,
  12248. 'role' => $episode_role_name
  12249. ]);
  12250. } else {
  12251. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  12252. if (!empty($episode_voice_prompt)) {
  12253. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  12254. // 如果全局没有voice_prompt或与剧集不一致,则更新
  12255. if ($global_voice_prompt !== $episode_voice_prompt) {
  12256. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  12257. $roles_updated = true;
  12258. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  12259. 'anime_id' => $anime_id,
  12260. 'role' => $episode_role_name,
  12261. 'voice_prompt' => $episode_voice_prompt
  12262. ]);
  12263. }
  12264. }
  12265. }
  12266. }
  12267. // 处理场景同步
  12268. foreach ($episode_scenes as $episode_scene) {
  12269. $episode_scene_name = getProp($episode_scene, 'scene');
  12270. $episode_description = getProp($episode_scene, 'description');
  12271. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  12272. // 检查全局中是否已存在相同的场景
  12273. $exists = false;
  12274. foreach ($global_scenes as $global_scene) {
  12275. $global_scene_name = getProp($global_scene, 'scene');
  12276. $global_description = getProp($global_scene, 'description');
  12277. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  12278. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  12279. if ($episode_scene_name == $global_scene_name
  12280. && $episode_description == $global_description
  12281. && $episode_pic_prompt == $global_pic_prompt) {
  12282. $exists = true;
  12283. break;
  12284. }
  12285. }
  12286. // 如果不存在,则添加到全局
  12287. if (!$exists) {
  12288. $global_scenes[] = $episode_scene;
  12289. $scenes_added = true;
  12290. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  12291. 'anime_id' => $anime_id,
  12292. 'scene' => $episode_scene_name
  12293. ]);
  12294. }
  12295. }
  12296. // 处理道具同步(逻辑与场景一致)
  12297. foreach ($episode_props as $episode_prop) {
  12298. $episode_prop_name = getProp($episode_prop, 'prop');
  12299. $episode_description = getProp($episode_prop, 'description');
  12300. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  12301. // 检查全局中是否已存在相同的道具
  12302. $exists = false;
  12303. foreach ($global_props as $global_prop) {
  12304. $global_prop_name = getProp($global_prop, 'prop');
  12305. $global_description = getProp($global_prop, 'description');
  12306. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  12307. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  12308. if ($episode_prop_name == $global_prop_name
  12309. && $episode_description == $global_description
  12310. && $episode_pic_prompt == $global_pic_prompt) {
  12311. $exists = true;
  12312. break;
  12313. }
  12314. }
  12315. // 如果不存在,则添加到全局
  12316. if (!$exists) {
  12317. $global_props[] = $episode_prop;
  12318. $props_added = true;
  12319. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  12320. 'anime_id' => $anime_id,
  12321. 'prop' => $episode_prop_name
  12322. ]);
  12323. }
  12324. }
  12325. // 如果有新增或更新,则更新全局数据
  12326. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  12327. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  12328. if ($roles_added || $roles_updated) {
  12329. $update_data['roles'] = json_encode($global_roles, 256);
  12330. }
  12331. if ($scenes_added) {
  12332. $update_data['scenes'] = json_encode($global_scenes, 256);
  12333. }
  12334. if ($props_added) {
  12335. $update_data['props'] = json_encode($global_props, 256);
  12336. }
  12337. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  12338. dLog('deepseek')->info('剧集数据同步到全局完成', [
  12339. 'anime_id' => $anime_id,
  12340. 'roles_added' => $roles_added,
  12341. 'roles_updated' => $roles_updated,
  12342. 'scenes_added' => $scenes_added,
  12343. 'props_added' => $props_added,
  12344. 'global_roles_count' => count($global_roles),
  12345. 'global_scenes_count' => count($global_scenes),
  12346. 'global_props_count' => count($global_props)
  12347. ]);
  12348. }
  12349. return true;
  12350. }
  12351. /**
  12352. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  12353. *
  12354. * @param int $anime_id 动漫对话ID
  12355. * @param int $episode_id 分集ID
  12356. * @return bool
  12357. */
  12358. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  12359. // 获取全局角色和场景数据
  12360. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  12361. if (!$anime) {
  12362. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  12363. return false;
  12364. }
  12365. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  12366. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  12367. // 获取指定的分集
  12368. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  12369. if (!$episode) {
  12370. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  12371. return false;
  12372. }
  12373. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  12374. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  12375. $roles_updated = false;
  12376. $scenes_updated = false;
  12377. // 继承角色的task_id、task_status和url
  12378. foreach ($episode_roles as &$episode_role) {
  12379. $episode_role_name = getProp($episode_role, 'role');
  12380. $episode_description = getProp($episode_role, 'description');
  12381. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  12382. $episode_url = getProp($episode_role, 'url');
  12383. // 跳过旁白角色
  12384. if ($episode_role_name == '旁白') {
  12385. continue;
  12386. }
  12387. // 如果剧集中已有URL,跳过
  12388. if (!empty($episode_url)) {
  12389. continue;
  12390. }
  12391. // 遍历全局角色数据,查找匹配的角色
  12392. foreach ($global_roles as $global_role) {
  12393. $global_role_name = getProp($global_role, 'role');
  12394. $global_description = getProp($global_role, 'description');
  12395. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  12396. $global_url = getProp($global_role, 'url');
  12397. $global_task_id = getProp($global_role, 'task_id');
  12398. $global_task_status = getProp($global_role, 'task_status');
  12399. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  12400. if ($episode_role_name == $global_role_name
  12401. && $episode_description == $global_description
  12402. && $episode_pic_prompt == $global_pic_prompt) {
  12403. // 继承 task_id、task_status 和 url
  12404. if (!empty($global_task_id)) {
  12405. $episode_role['task_id'] = $global_task_id;
  12406. $episode_role['task_status'] = $global_task_status;
  12407. $roles_updated = true;
  12408. dLog('deepseek')->info('剧集角色继承全局task_id', [
  12409. 'episode_id' => $episode_id,
  12410. 'role' => $episode_role_name,
  12411. 'task_id' => $global_task_id,
  12412. 'task_status' => $global_task_status
  12413. ]);
  12414. }
  12415. if (!empty($global_url)) {
  12416. $episode_role['url'] = $global_url;
  12417. $roles_updated = true;
  12418. dLog('deepseek')->info('剧集角色继承全局url', [
  12419. 'episode_id' => $episode_id,
  12420. 'role' => $episode_role_name,
  12421. 'url' => $global_url
  12422. ]);
  12423. }
  12424. break;
  12425. }
  12426. }
  12427. }
  12428. // 继承场景的task_id、task_status和url
  12429. foreach ($episode_scenes as &$episode_scene) {
  12430. $episode_scene_name = getProp($episode_scene, 'scene');
  12431. $episode_description = getProp($episode_scene, 'description');
  12432. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  12433. $episode_url = getProp($episode_scene, 'url');
  12434. // 如果剧集中已有URL,跳过
  12435. if (!empty($episode_url)) {
  12436. continue;
  12437. }
  12438. // 遍历全局场景数据,查找匹配的场景
  12439. foreach ($global_scenes as $global_scene) {
  12440. $global_scene_name = getProp($global_scene, 'scene');
  12441. $global_description = getProp($global_scene, 'description');
  12442. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  12443. $global_url = getProp($global_scene, 'url');
  12444. $global_task_id = getProp($global_scene, 'task_id');
  12445. $global_task_status = getProp($global_scene, 'task_status');
  12446. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  12447. if ($episode_scene_name == $global_scene_name
  12448. && $episode_description == $global_description
  12449. && $episode_pic_prompt == $global_pic_prompt) {
  12450. // 继承 task_id、task_status 和 url
  12451. if (!empty($global_task_id)) {
  12452. $episode_scene['task_id'] = $global_task_id;
  12453. $episode_scene['task_status'] = $global_task_status;
  12454. $scenes_updated = true;
  12455. dLog('deepseek')->info('剧集场景继承全局task_id', [
  12456. 'episode_id' => $episode_id,
  12457. 'scene' => $episode_scene_name,
  12458. 'task_id' => $global_task_id,
  12459. 'task_status' => $global_task_status
  12460. ]);
  12461. }
  12462. if (!empty($global_url)) {
  12463. $episode_scene['url'] = $global_url;
  12464. $scenes_updated = true;
  12465. dLog('deepseek')->info('剧集场景继承全局url', [
  12466. 'episode_id' => $episode_id,
  12467. 'scene' => $episode_scene_name,
  12468. 'url' => $global_url
  12469. ]);
  12470. }
  12471. break;
  12472. }
  12473. }
  12474. }
  12475. // 如果有更新,则保存到数据库
  12476. if ($roles_updated || $scenes_updated) {
  12477. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  12478. if ($roles_updated) {
  12479. $update_data['roles'] = json_encode($episode_roles, 256);
  12480. }
  12481. if ($scenes_updated) {
  12482. $update_data['scenes'] = json_encode($episode_scenes, 256);
  12483. }
  12484. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  12485. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  12486. 'episode_id' => $episode_id,
  12487. 'roles_updated' => $roles_updated,
  12488. 'scenes_updated' => $scenes_updated
  12489. ]);
  12490. }
  12491. return true;
  12492. }
  12493. public function chatChangeImg($data) {
  12494. $segment = getProp($data, 'segment');
  12495. $segment_content = getProp($segment, 'segment_content');
  12496. $prompt = getProp($data, 'prompt');
  12497. $ref_img = getProp($data, 'ref_img');
  12498. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  12499. // 处理文本模型
  12500. $model = getProp($data, 'model');
  12501. if (!$model) {
  12502. // 用户没有输入,从anime表获取
  12503. $segment_id = getProp($segment, 'segment_id');
  12504. if ($segment_id) {
  12505. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  12506. if ($episode_id) {
  12507. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  12508. if ($anime_id) {
  12509. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  12510. }
  12511. }
  12512. }
  12513. if (!$model) {
  12514. // anime表也没有,使用默认值
  12515. $model = 'doubao-seed-2-0-mini-260215';
  12516. }
  12517. }
  12518. // 验证模型是否在可用模型表中
  12519. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  12520. $model = 'doubao-seed-2-0-mini-260215';
  12521. }
  12522. $messages[] =
  12523. [
  12524. 'role' => 'user',
  12525. 'content' => $question
  12526. ];
  12527. $post_data = [
  12528. 'model' => $model,
  12529. 'messages' => $messages,
  12530. // 'max_tokens' => 8192,
  12531. 'temperature' => 0.7,
  12532. 'frequency_penalty' => 0,
  12533. 'presence_penalty' => 0,
  12534. 'response_format' => ['type' => 'text'],
  12535. 'stream' => false // 是否启用流式输出
  12536. ];
  12537. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  12538. // DeepSeek 官方模型使用 DeepSeek API
  12539. $chatResult = $this->chatOnly($post_data);
  12540. } else if (in_array($model, $this->gpt_text_models)) {
  12541. // GPT-5.4 模型使用 TokenRouter API
  12542. $chatResult = $this->gpt54ChatOnly($post_data);
  12543. } else {
  12544. // 其他模型使用火山引擎API
  12545. $chatResult = $this->volcEngineChatCompletion($post_data);
  12546. }
  12547. if (is_array($chatResult)) {
  12548. extract($chatResult);
  12549. }else {
  12550. Utils::throwError('20003: 接口调用失败!');
  12551. }
  12552. // 仅记录 token 使用明细(不扣积分)
  12553. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  12554. 'model' => $model,
  12555. 'source' => 'chatChangeImg',
  12556. ], $model);
  12557. return [
  12558. 'type' => 'done',
  12559. // 'episode' => $episode,
  12560. 'answer' => $fullContent,
  12561. 'reasoning' => $fullReasoningContent,
  12562. 'usage' => $usage
  12563. ];
  12564. }
  12565. /**
  12566. * 仅调用 deepseek 对话接口(非流式)
  12567. *
  12568. * @param array $post_data
  12569. * @param int $timeout
  12570. * @return array
  12571. */
  12572. private function chatOnly($post_data, $timeout = 1800) {
  12573. $post_data['max_tokens'] = 300000;
  12574. $client = new Client(['timeout' => $timeout, 'verify' => false]);
  12575. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  12576. $response = $result->getBody()->getContents();
  12577. $response_arr = json_decode($response, true);
  12578. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  12579. $fullContent = '';
  12580. $fullReasoningContent = [];
  12581. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  12582. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  12583. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  12584. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  12585. }
  12586. return [
  12587. 'fullContent' => $fullContent,
  12588. 'fullReasoningContent' => $fullReasoningContent,
  12589. 'usage' => $usage
  12590. ];
  12591. }
  12592. /**
  12593. * 用 deepseek-v4-flash 非流式分析报错,返回不超过50字的用户友好提示
  12594. *
  12595. * @param string $errorMessage
  12596. * @return string|null
  12597. */
  12598. public function analyzeErrorMessage($errorMessage)
  12599. {
  12600. try {
  12601. $post_data = [
  12602. 'model' => 'deepseek-v4-flash',
  12603. 'messages' => [
  12604. [
  12605. 'role' => 'system',
  12606. 'content' => '你是视频生成任务的报错分析助手。请根据用户给出的原始报错,用一句中文提示告诉用户问题原因和下一步怎么做,不超过50个字,直接输出提示内容,不要解释、不要输出代码。',
  12607. ],
  12608. [
  12609. 'role' => 'user',
  12610. 'content' => (string)$errorMessage,
  12611. ],
  12612. ],
  12613. 'temperature' => 0.3,
  12614. 'frequency_penalty' => 0,
  12615. 'presence_penalty' => 0,
  12616. 'response_format' => ['type' => 'text'],
  12617. 'stream' => false,
  12618. ];
  12619. $result = $this->chatOnly($post_data, 8);
  12620. // 调用成功即记录 token 使用明细(不扣积分),保证错误分析这类隐性 AI 调用进入统计口径
  12621. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($result['usage'] ?? []), [
  12622. 'model' => 'deepseek-v4-flash',
  12623. 'source' => 'analyzeErrorMessage',
  12624. ], 'deepseek-v4-flash');
  12625. $content = trim((string)($result['fullContent'] ?? ''));
  12626. if ($content === '') {
  12627. return null;
  12628. }
  12629. return mb_substr($content, 0, 50);
  12630. } catch (\Exception $e) {
  12631. dLog('deepseek')->error('视频任务报错分析失败: ' . $e->getMessage(), [
  12632. 'error_message' => $errorMessage
  12633. ]);
  12634. return null;
  12635. }
  12636. }
  12637. // 仅调用 GPT-5.4 对话接口(非流式)
  12638. private function gpt54ChatOnly($post_data) {
  12639. // 按模型取 Key:gpt-5.6-luna 使用 GPT_56_LUNA_API_KEY,其余使用 GPT_54_API_KEY
  12640. $modelName = (string)getProp($post_data, 'model', 'gpt-5.4');
  12641. $lunaApiKey = env('GPT_56_LUNA_API_KEY');
  12642. $apiKey = $modelName === 'gpt-5.6-luna' ? $lunaApiKey : env('GPT_54_API_KEY');
  12643. $usedLunaFallback = false;
  12644. if (empty($apiKey)) {
  12645. Utils::throwError('20003:GPT-5.4 API Key未配置');
  12646. }
  12647. // 先探活,服务不可用时自动重试
  12648. $this->ensureGptServiceAvailable($apiKey);
  12649. $client = new Client(['timeout' => 1800, 'verify' => false]);
  12650. // 移除 thinking 参数,GPT-5.4 不支持
  12651. if (isset($post_data['thinking'])) {
  12652. unset($post_data['thinking']);
  12653. }
  12654. if (isset($post_data['reasoning_effort'])) {
  12655. unset($post_data['reasoning_effort']);
  12656. }
  12657. $post_data['max_completion_tokens'] = 100000;
  12658. // 确保 stream 为 false
  12659. $post_data['stream'] = false;
  12660. $maxRetries = $this->gptRetryTimes();
  12661. $interval = $this->gptRetryInterval();
  12662. $attempt = 0;
  12663. while (true) {
  12664. try {
  12665. $headers = [
  12666. 'Authorization' => 'Bearer ' . $apiKey,
  12667. 'Content-Type' => 'application/json'
  12668. ];
  12669. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  12670. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  12671. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  12672. 'json' => $post_data,
  12673. 'headers' => $headers
  12674. ]);
  12675. $response = $result->getBody()->getContents();
  12676. $response_arr = json_decode($response, true);
  12677. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  12678. $fullContent = '';
  12679. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  12680. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  12681. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  12682. }
  12683. return [
  12684. 'fullContent' => $fullContent,
  12685. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  12686. 'usage' => $usage
  12687. ];
  12688. } catch (\Exception $e) {
  12689. // 报错或超时时,切到 GPT_56_LUNA_API_KEY 重试一次(收费更高,慎用;仅原本未用 luna key 时触发)
  12690. if (!$usedLunaFallback && !empty($lunaApiKey) && $apiKey !== $lunaApiKey) {
  12691. $usedLunaFallback = true;
  12692. $apiKey = $lunaApiKey;
  12693. dLog('deepseek')->warning('GPT-5.4 请求异常,切换 GPT_56_LUNA_API_KEY 重试', ['error' => $e->getMessage()]);
  12694. continue;
  12695. }
  12696. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  12697. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  12698. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  12699. throw $e;
  12700. }
  12701. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  12702. 'retry' => $attempt + 1,
  12703. 'max_retries' => $maxRetries,
  12704. 'error' => $e->getMessage()
  12705. ]);
  12706. sleep($interval);
  12707. $attempt++;
  12708. }
  12709. }
  12710. }
  12711. private function splitContent($content) {
  12712. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  12713. $chapters = [];
  12714. // 匹配章节标题格式:
  12715. // 1. 标题可能独占一行,也可能在正文末尾或中间
  12716. // 2. 格式支持:
  12717. // - **第一集**
  12718. // - 第一集:
  12719. // - ###第1章 重生
  12720. // - ##第2章 相救
  12721. // - 第三章 共处一室
  12722. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  12723. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  12724. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  12725. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  12726. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  12727. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  12728. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  12729. // 先在每个标题前插入换行符(如果前面不是换行的话)
  12730. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  12731. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  12732. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  12733. // 用正则找出所有章节标题的位置
  12734. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  12735. $titleCount = count($matches[0]);
  12736. for ($i = 0; $i < $titleCount; $i++) {
  12737. // 获取当前章节标题
  12738. $titleLine = trim($matches[0][$i][0]);
  12739. // 去除标题开头的特殊符号
  12740. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/u', '', $titleLine);
  12741. // 去除标题结尾的冒号和特殊符号
  12742. $cleanTitle = preg_replace('/[#*·::\s]+$/u', '', $cleanTitle);
  12743. $cleanTitle = trim($cleanTitle);
  12744. // 获取当前标题的结束位置
  12745. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  12746. // 获取下一个章节标题的开始位置(如果存在)
  12747. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  12748. // 提取章节内容(从标题结束到下一个标题开始)
  12749. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  12750. // 清理内容:去除前后空白和分隔线
  12751. $chapterContent = trim($chapterContent);
  12752. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  12753. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  12754. if (!empty($cleanTitle) && !empty($chapterContent)) {
  12755. $chapters[] = [
  12756. 'title' => $cleanTitle,
  12757. 'content' => $chapterContent
  12758. ];
  12759. }
  12760. }
  12761. } else {
  12762. // 如果没有匹配到章节,返回整个内容
  12763. $chapters[] = [
  12764. 'title' => '',
  12765. 'content' => $content
  12766. ];
  12767. }
  12768. return $chapters;
  12769. }
  12770. public function getContentByBid($bid) {
  12771. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  12772. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  12773. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  12774. $content = '';
  12775. foreach ($chapters as $chapter) {
  12776. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  12777. }
  12778. return $content;
  12779. }
  12780. public function getContentByScriptId($script_id) {
  12781. $content = '';
  12782. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  12783. if ($contents) {
  12784. $content = implode(PHP_EOL, $contents);
  12785. }else {
  12786. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  12787. }
  12788. return $content;
  12789. }
  12790. /**
  12791. * 根据文件类型提取文本内容
  12792. *
  12793. * @param mixed $file 文件对象或文件路径
  12794. * @return string
  12795. */
  12796. public function extractFileContent($file) {
  12797. // 获取文件路径和扩展名
  12798. if (is_string($file)) {
  12799. $filePath = $file;
  12800. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  12801. } else {
  12802. // Laravel UploadedFile 对象
  12803. $filePath = $file->getRealPath();
  12804. $extension = strtolower($file->getClientOriginalExtension());
  12805. }
  12806. $content = '';
  12807. switch ($extension) {
  12808. case 'txt':
  12809. $content = $this->extractTxtContent($filePath);
  12810. break;
  12811. case 'pdf':
  12812. $content = $this->extractPdfContent($filePath);
  12813. break;
  12814. case 'doc':
  12815. case 'docx':
  12816. $content = $this->extractWordContent($filePath);
  12817. break;
  12818. // case 'jpg':
  12819. // case 'jpeg':
  12820. // case 'png':
  12821. // case 'gif':
  12822. // case 'bmp':
  12823. // case 'webp':
  12824. // $content = $this->extractImageContent($filePath);
  12825. // break;
  12826. default:
  12827. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  12828. }
  12829. // 移除非法 UTF-8 字节,避免后续 JSON 编码或正则解析异常
  12830. if (!mb_check_encoding($content, 'UTF-8')) {
  12831. $cleaned = @iconv('UTF-8', 'UTF-8//IGNORE', $content);
  12832. $content = $cleaned === false ? $content : $cleaned;
  12833. }
  12834. return $content;
  12835. }
  12836. /**
  12837. * 提取 TXT 文件内容
  12838. */
  12839. private function extractTxtContent($filePath) {
  12840. if (!file_exists($filePath)) {
  12841. Utils::throwError('20003:文件不存在');
  12842. }
  12843. $content = file_get_contents($filePath);
  12844. // 尝试检测并转换编码
  12845. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  12846. if ($encoding && $encoding !== 'UTF-8') {
  12847. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  12848. }
  12849. return trim($content);
  12850. }
  12851. /**
  12852. * 提取 PDF 文件内容
  12853. */
  12854. private function extractPdfContent($filePath) {
  12855. if (!file_exists($filePath)) {
  12856. Utils::throwError('20003:文件不存在');
  12857. }
  12858. try {
  12859. $parser = new PdfParser();
  12860. $pdf = $parser->parseFile($filePath);
  12861. $content = $pdf->getText();
  12862. return trim($content);
  12863. } catch (\Exception $e) {
  12864. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  12865. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  12866. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  12867. }
  12868. }
  12869. /**
  12870. * 提取 Word 文件内容(支持 doc 和 docx)
  12871. */
  12872. private function extractWordContent($filePath) {
  12873. if (!file_exists($filePath)) {
  12874. Utils::throwError('20003:文件不存在');
  12875. }
  12876. try {
  12877. $phpWord = WordIOFactory::load($filePath);
  12878. $content = '';
  12879. foreach ($phpWord->getSections() as $section) {
  12880. foreach ($section->getElements() as $element) {
  12881. $content .= $this->extractWordElementText($element);
  12882. }
  12883. }
  12884. return trim($content);
  12885. } catch (\Exception $e) {
  12886. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  12887. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  12888. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  12889. }
  12890. }
  12891. /**
  12892. * 递归提取 Word 元素中的文本
  12893. */
  12894. private function extractWordElementText($element) {
  12895. $text = '';
  12896. if (method_exists($element, 'getText')) {
  12897. $text .= $element->getText() . "\n";
  12898. } elseif (method_exists($element, 'getElements')) {
  12899. foreach ($element->getElements() as $childElement) {
  12900. $text .= $this->extractWordElementText($childElement);
  12901. }
  12902. }
  12903. return $text;
  12904. }
  12905. /**
  12906. * 提取图片内容(使用火山引擎 OCR)
  12907. */
  12908. private function extractImageContent($filePath) {
  12909. if (!file_exists($filePath)) {
  12910. Utils::throwError('20003:文件不存在');
  12911. }
  12912. try {
  12913. // 读取图片并转换为 base64
  12914. $imageData = file_get_contents($filePath);
  12915. $base64Image = base64_encode($imageData);
  12916. // 调用火山引擎 OCR 服务
  12917. $content = $this->callVolcEngineOCR($base64Image);
  12918. return trim($content);
  12919. } catch (\Exception $e) {
  12920. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  12921. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  12922. Utils::throwError('20003:图片识别失败');
  12923. }
  12924. }
  12925. /**
  12926. * 调用火山引擎 OCR 服务识别图片文字
  12927. *
  12928. * @param string $base64Image base64 编码的图片数据
  12929. * @return string 识别的文字内容
  12930. */
  12931. private function callVolcEngineOCR($base64Image) {
  12932. $method = 'POST';
  12933. $service = 'cv';
  12934. $host = 'visual.volcengineapi.com';
  12935. $region = env('VOLC_REGION', 'cn-north-1');
  12936. $access_key = env('VOLC_AK');
  12937. $secret_key = env('VOLC_SK');
  12938. $action = 'OCRNormal';
  12939. $version = '2020-08-26';
  12940. if (!$access_key || !$secret_key) {
  12941. Utils::throwError('20003:请配置火山引擎 AK/SK');
  12942. }
  12943. // 请求体
  12944. $body = json_encode([
  12945. 'image_base64' => $base64Image
  12946. ]);
  12947. // 生成签名
  12948. $headers = $this->getVolcEngineSignHeaders(
  12949. $method, $service, $host, $region,
  12950. "Action={$action}&Version={$version}",
  12951. $access_key, $secret_key, $body
  12952. );
  12953. $client = new Client(['timeout' => 1800, 'verify' => false]);
  12954. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  12955. 'headers' => $headers,
  12956. 'body' => $body
  12957. ]);
  12958. $response_arr = json_decode($response->getBody()->getContents(), true);
  12959. // 提取识别的文字
  12960. $textLines = [];
  12961. if (isset($response_arr['data']['line_texts'])) {
  12962. $textLines = $response_arr['data']['line_texts'];
  12963. } elseif (isset($response_arr['data']['ocr_infos'])) {
  12964. foreach ($response_arr['data']['ocr_infos'] as $info) {
  12965. if (isset($info['text'])) {
  12966. $textLines[] = $info['text'];
  12967. }
  12968. }
  12969. }
  12970. if (empty($textLines)) {
  12971. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  12972. return '';
  12973. }
  12974. return implode("\n", $textLines);
  12975. }
  12976. /**
  12977. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  12978. */
  12979. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  12980. $contentType = 'application/json';
  12981. $accept = 'application/json';
  12982. // 获取当前UTC时间
  12983. $t = new DateTime('now', new DateTimeZone('UTC'));
  12984. $xDate = $t->format('Ymd\THis\Z');
  12985. $dateStamp = $t->format('Ymd');
  12986. // 计算 body 的 sha256 哈希
  12987. $payloadHash = hash('sha256', $body);
  12988. // 1. 拼接规范请求串
  12989. $canonicalUri = '/';
  12990. $canonicalQueryString = $queryString;
  12991. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  12992. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  12993. $canonicalRequest = implode("\n", [
  12994. $method,
  12995. $canonicalUri,
  12996. $canonicalQueryString,
  12997. $canonicalHeaders,
  12998. $signedHeaders,
  12999. $payloadHash
  13000. ]);
  13001. // 2. 拼接待签名字符串
  13002. $algorithm = 'HMAC-SHA256';
  13003. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  13004. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  13005. $stringToSign = implode("\n", [
  13006. $algorithm,
  13007. $xDate,
  13008. $credentialScope,
  13009. $hashedCanonicalRequest
  13010. ]);
  13011. // 3. 计算签名
  13012. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  13013. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  13014. // 4. 添加签名到请求头
  13015. $authorizationHeader = sprintf(
  13016. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  13017. $algorithm,
  13018. $access_key,
  13019. $credentialScope,
  13020. $signedHeaders,
  13021. $signature
  13022. );
  13023. return [
  13024. 'Accept' => $accept,
  13025. 'Content-Type' => $contentType,
  13026. 'Host' => $host,
  13027. 'X-Date' => $xDate,
  13028. 'X-Content-Sha256'=> $payloadHash,
  13029. 'Authorization' => $authorizationHeader
  13030. ];
  13031. }
  13032. public function generateScriptWords($cid, $model = 'r1') {
  13033. ini_set('max_execution_time', 0);
  13034. if (!$cid) Utils::throwError('20003: 请选择章节!');
  13035. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  13036. // 模型兼容性处理和思考模式设置
  13037. $thinkingMode = 'disabled';
  13038. $reasoningEffort = 'high';
  13039. if ($model == 'r1') {
  13040. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  13041. $thinkingMode = 'enabled';
  13042. } else {
  13043. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  13044. $thinkingMode = 'disabled';
  13045. }
  13046. $messages = [
  13047. [
  13048. 'role' => 'system',
  13049. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  13050. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  13051. 2.非对话部分请全部用旁白角色代替
  13052. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  13053. ],
  13054. [
  13055. 'role' => 'user',
  13056. 'content' => $content
  13057. ]
  13058. ];
  13059. $post_data = [
  13060. 'model' => $model,
  13061. 'messages' => $messages,
  13062. // 'max_tokens' => 8192,
  13063. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  13064. 'frequency_penalty' => 0,
  13065. 'presence_penalty' => 0,
  13066. 'thinking' => ['type' => $thinkingMode],
  13067. 'response_format' => [
  13068. 'type' => 'text'
  13069. ],
  13070. 'stream' => false
  13071. ];
  13072. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  13073. // 根据模型类型选择调用方法
  13074. $fullContent = '';
  13075. $usage = [];
  13076. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  13077. // DeepSeek 官方模型使用 DeepSeek API
  13078. $chatResult = $this->chatOnly($post_data);
  13079. } else if (in_array($model, $this->gpt_text_models)) {
  13080. // GPT-5.4 模型使用 TokenRouter API
  13081. $chatResult = $this->gpt54ChatOnly($post_data);
  13082. } else {
  13083. // 其他模型使用火山引擎API
  13084. $chatResult = $this->volcEngineChatCompletion($post_data);
  13085. }
  13086. if (is_array($chatResult)) {
  13087. $fullContent = $chatResult['fullContent'];
  13088. $usage = $chatResult['usage'] ?? [];
  13089. }
  13090. // 仅记录 token 使用明细(不扣积分)
  13091. $this->recordTextTokenOnly($this->getCurrentUid(), $this->pointsService->getTokensFromUsage($usage), [
  13092. 'model' => $model,
  13093. 'cid' => $cid,
  13094. 'source' => 'generateScriptWords',
  13095. ], $model);
  13096. return $fullContent;
  13097. }
  13098. /**
  13099. * 智能化解析集数信息
  13100. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  13101. *
  13102. * @param string $prompt 用户输入的提示词
  13103. * @return int|null 解析出的集数,如果没有找到则返回null
  13104. */
  13105. private function extractEpisodeNumber($prompt)
  13106. {
  13107. if (empty($prompt)) {
  13108. return null;
  13109. }
  13110. // 定义各种可能的表达模式
  13111. $patterns = [
  13112. // 基本模式:改成N集、调整成N集、修改成N集
  13113. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  13114. // 扩展模式:分成N集、拆分成N集、分割成N集
  13115. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  13116. // 数量模式:N集、共N集、总共N集
  13117. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  13118. // 制作模式:制作N集、生成N集、创建N集
  13119. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  13120. // 计划模式:计划N集、预计N集、打算N集
  13121. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  13122. // 需要模式:需要N集、要N集
  13123. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  13124. // 中文数字模式:改成三集、调整成五集等
  13125. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  13126. // 英文数字模式
  13127. '/(?: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',
  13128. ];
  13129. // 中文数字转阿拉伯数字的映射
  13130. $chineseNumbers = [
  13131. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  13132. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  13133. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  13134. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  13135. ];
  13136. // 逐个尝试匹配模式
  13137. foreach ($patterns as $pattern) {
  13138. if (preg_match($pattern, $prompt, $matches)) {
  13139. $number = trim($matches[1]);
  13140. // 如果是中文数字,转换为阿拉伯数字
  13141. if (isset($chineseNumbers[$number])) {
  13142. return $chineseNumbers[$number];
  13143. }
  13144. // 如果是阿拉伯数字,直接返回
  13145. if (is_numeric($number)) {
  13146. $episodeNum = intval($number);
  13147. // 合理性检查:集数应该在1-100之间
  13148. if ($episodeNum >= 1 && $episodeNum <= 100) {
  13149. return $episodeNum;
  13150. }
  13151. }
  13152. }
  13153. }
  13154. return null;
  13155. }
  13156. /**
  13157. * 调用火山引擎对话(Chat) API
  13158. *
  13159. * @param array $params 包含以下参数:
  13160. * - model: 模型ID(必填)
  13161. * - messages: 消息列表(必填)
  13162. * - stream: 是否流式输出(可选,默认false)
  13163. * - max_tokens: 最大输出token数(可选)
  13164. * - temperature: 采样温度(可选,默认1)
  13165. * - top_p: 核采样概率(可选,默认0.7)
  13166. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  13167. * - presence_penalty: 存在惩罚系数(可选,默认0)
  13168. * - stop: 停止词(可选)
  13169. * - tools: 工具列表(可选)
  13170. * @return array|Generator 非流式返回数组,流式返回生成器
  13171. */
  13172. public function volcEngineChatCompletion(array $params)
  13173. {
  13174. $apiKey = env('VOLC_AI_API_KEY');
  13175. if (empty($apiKey)) {
  13176. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  13177. }
  13178. // 构建请求参数
  13179. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  13180. $requestData = [
  13181. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  13182. 'messages' => $params['messages'] ?? [],
  13183. ];
  13184. if (!in_array($originalModel, $this->valid_text_models)) {
  13185. Utils::throwError('20003:该模型不支持!');
  13186. }
  13187. // 添加可选参数
  13188. if (isset($params['stream'])) {
  13189. $requestData['stream'] = $params['stream'];
  13190. }
  13191. if (isset($params['stream_options'])) {
  13192. $requestData['stream_options'] = $params['stream_options'];
  13193. }
  13194. if (isset($params['max_tokens'])) {
  13195. $requestData['max_tokens'] = $params['max_tokens'];
  13196. }else if (isset($params['max_completion_tokens'])) {
  13197. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  13198. }else {
  13199. $requestData['max_completion_tokens'] = 100000;
  13200. }
  13201. if (isset($params['temperature'])) {
  13202. $requestData['temperature'] = $params['temperature'];
  13203. }
  13204. if (isset($params['top_p'])) {
  13205. $requestData['top_p'] = $params['top_p'];
  13206. }
  13207. if (isset($params['frequency_penalty'])) {
  13208. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  13209. }
  13210. if (isset($params['presence_penalty'])) {
  13211. $requestData['presence_penalty'] = $params['presence_penalty'];
  13212. }
  13213. if (isset($params['stop'])) {
  13214. $requestData['stop'] = $params['stop'];
  13215. }
  13216. if (isset($params['tools'])) {
  13217. $requestData['tools'] = $params['tools'];
  13218. }
  13219. if (isset($params['tool_choice'])) {
  13220. $requestData['tool_choice'] = $params['tool_choice'];
  13221. }
  13222. if (isset($params['response_format'])) {
  13223. $requestData['response_format'] = $params['response_format'];
  13224. }
  13225. if (isset($params['thinking'])) {
  13226. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  13227. if (is_array($params['thinking'])) {
  13228. $requestData['thinking'] = $params['thinking'];
  13229. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  13230. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  13231. }
  13232. } else {
  13233. $requestData['thinking'] = ['type' => $params['thinking']];
  13234. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  13235. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  13236. }
  13237. }
  13238. } else {
  13239. $requestData['thinking'] = ['type' => 'disabled'];
  13240. }
  13241. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  13242. $client = new Client(['verify' => false, 'timeout' => 1800]);
  13243. try {
  13244. // 判断是否为流式输出
  13245. $isStream = isset($params['stream']) && $params['stream'] === true;
  13246. if ($isStream) {
  13247. // 流式输出
  13248. // 流式请求默认声明返回 usage(未显式传参时)
  13249. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  13250. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  13251. } else {
  13252. // 非流式输出
  13253. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  13254. 'headers' => [
  13255. 'Authorization' => 'Bearer ' . $apiKey,
  13256. 'Content-Type' => 'application/json',
  13257. ],
  13258. 'json' => $requestData
  13259. ]);
  13260. $responseData = json_decode($response->getBody(), true);
  13261. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  13262. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  13263. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  13264. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  13265. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  13266. }
  13267. return [
  13268. 'fullContent' => $fullContent,
  13269. 'fullReasoningContent' => $fullReasoningContent,
  13270. 'usage' => $usage
  13271. ];
  13272. }
  13273. } catch (\Exception $e) {
  13274. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  13275. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  13276. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  13277. }
  13278. }
  13279. /**
  13280. * 火山引擎对话API流式输出
  13281. *
  13282. * @param Client $client HTTP客户端
  13283. * @param string $apiKey API密钥
  13284. * @param array $requestData 请求数据
  13285. * @return Generator
  13286. */
  13287. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  13288. {
  13289. try {
  13290. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  13291. 'headers' => [
  13292. 'Authorization' => 'Bearer ' . $apiKey,
  13293. 'Content-Type' => 'application/json',
  13294. ],
  13295. 'json' => $requestData,
  13296. 'stream' => true
  13297. ]);
  13298. $body = $response->getBody();
  13299. $buffer = '';
  13300. $fullContent = '';
  13301. $fullReasoningContent = '';
  13302. $usage = [];
  13303. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  13304. // 逐行读取流式响应
  13305. while (!$body->eof()) {
  13306. $chunk = $body->read(1024);
  13307. $buffer .= $chunk;
  13308. // 按行分割
  13309. $lines = explode("\n", $buffer);
  13310. $buffer = array_pop($lines);
  13311. foreach ($lines as $line) {
  13312. $line = trim($line);
  13313. if (empty($line)) {
  13314. continue;
  13315. }
  13316. // 检查是否是SSE数据行
  13317. if (strpos($line, 'data: ') !== 0) {
  13318. continue;
  13319. }
  13320. $data = substr($line, 6);
  13321. if ($data === '[DONE]') {
  13322. dLog('deepseek')->info('收到结束标记');
  13323. break 2;
  13324. }
  13325. try {
  13326. $json = json_decode($data, true);
  13327. if (json_last_error() !== JSON_ERROR_NONE) {
  13328. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  13329. continue;
  13330. }
  13331. if (isset($json['choices'][0]['delta'])) {
  13332. $delta = $json['choices'][0]['delta'];
  13333. // 处理思维链内容
  13334. if (isset($delta['reasoning_content'])) {
  13335. $fullReasoningContent .= $delta['reasoning_content'];
  13336. yield [
  13337. 'type' => 'reasoning',
  13338. 'content' => $delta['reasoning_content'],
  13339. 'full_reasoning' => $fullReasoningContent
  13340. ];
  13341. }
  13342. // 处理回答内容
  13343. if (isset($delta['content'])) {
  13344. $fullContent .= $delta['content'];
  13345. yield [
  13346. 'type' => 'content',
  13347. 'content' => $delta['content'],
  13348. ];
  13349. }
  13350. }
  13351. // 获取使用统计信息
  13352. if (isset($json['usage'])) {
  13353. $usage = $json['usage'];
  13354. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  13355. }
  13356. } catch (\Exception $e) {
  13357. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  13358. continue;
  13359. }
  13360. }
  13361. }
  13362. dLog('deepseek')->info('流式读取完成', [
  13363. 'content_length' => strlen($fullContent),
  13364. 'reasoning_length' => strlen($fullReasoningContent)
  13365. ]);
  13366. yield [
  13367. 'type' => 'done',
  13368. 'full_content' => $fullContent,
  13369. 'full_reasoning' => $fullReasoningContent,
  13370. 'usage' => $usage
  13371. ];
  13372. } catch (\Exception $e) {
  13373. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  13374. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  13375. throw $e;
  13376. }
  13377. }
  13378. /**
  13379. * 检查并创建图片生成任务
  13380. *
  13381. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  13382. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  13383. * @param string $nameKey 资源名称字段('role' 或 'scene')
  13384. * @param string $art_style 美术风格
  13385. * @return array 更新后的资源列表
  13386. */
  13387. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  13388. {
  13389. // 确保参数为数组
  13390. $merged_items = is_array($merged_items) ? $merged_items : [];
  13391. $global_items = is_array($global_items) ? $global_items : [];
  13392. // 构建全局资源映射表,用于快速查找
  13393. $global_map = [];
  13394. foreach ($global_items as $item) {
  13395. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  13396. if ($itemKey === '') {
  13397. continue;
  13398. }
  13399. $global_map[$itemKey] = $item;
  13400. }
  13401. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  13402. foreach ($merged_items as &$item) {
  13403. $item_name = getProp($item, $nameKey);
  13404. $item_description = getProp($item, 'description');
  13405. // $item_url = getProp($item, 'url');
  13406. // // 如果已有图片URL,跳过
  13407. // if (!empty($item_url)) {
  13408. // continue;
  13409. // }
  13410. // 如果是旁白角色,跳过
  13411. if ($nameKey === 'role' && $item_name === '旁白') {
  13412. continue;
  13413. }
  13414. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  13415. if ($itemKey === '') {
  13416. continue;
  13417. }
  13418. $need_create_task = false;
  13419. // 条件1:在全局资源中找不到匹配的名称
  13420. if (!isset($global_map[$itemKey])) {
  13421. $need_create_task = true;
  13422. } else {
  13423. // 条件2:名称匹配但描述或 pic_prompt 不一致
  13424. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  13425. $current_description = trim((string)$item_description);
  13426. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  13427. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  13428. // 如果 description 或 pic_prompt 有变化,需要重新生成
  13429. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  13430. $need_create_task = true;
  13431. }
  13432. }
  13433. // 如果需要创建任务,调用图片生成服务
  13434. if ($need_create_task) {
  13435. try {
  13436. // 优先使用 pic_prompt,如果没有则使用 description
  13437. $pic_prompt = getProp($item, 'pic_prompt');
  13438. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  13439. // 添加美术风格前缀
  13440. if ($art_style) {
  13441. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  13442. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  13443. $description = "{$prefix}:{$description}";
  13444. }
  13445. $params = [
  13446. 'prompt' => $description,
  13447. 'ref_img_urls' => []
  13448. ];
  13449. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  13450. $task_id = $task->id;
  13451. if ($task_id) {
  13452. $item['task_id'] = $task_id;
  13453. $item['task_status'] = 'processing';
  13454. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  13455. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  13456. }
  13457. } catch (\Exception $e) {
  13458. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  13459. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  13460. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  13461. // 不抛出异常,继续处理其他资源
  13462. }
  13463. }
  13464. }
  13465. return $merged_items;
  13466. }
  13467. /**
  13468. * 同步新出现的主体和场景到全局
  13469. *
  13470. * @param int $anime_id 动漫ID
  13471. * @param array $merged_roles 合并后的角色列表
  13472. * @param array $merged_scenes 合并后的场景列表
  13473. * @param array $global_roles 全局角色列表
  13474. * @param array $global_scenes 全局场景列表
  13475. * @return void
  13476. */
  13477. private function syncNewResourcesToGlobal(
  13478. int $anime_id,
  13479. array $merged_roles,
  13480. array $merged_scenes,
  13481. array $global_roles,
  13482. array $global_scenes
  13483. ): void {
  13484. // 构建全局角色映射表
  13485. $global_role_map = [];
  13486. foreach ($global_roles as $role) {
  13487. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  13488. if ($roleKey !== '') {
  13489. $global_role_map[$roleKey] = $role;
  13490. }
  13491. }
  13492. // 构建全局场景映射表
  13493. $global_scene_map = [];
  13494. foreach ($global_scenes as $scene) {
  13495. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  13496. if ($sceneKey !== '') {
  13497. $global_scene_map[$sceneKey] = $scene;
  13498. }
  13499. }
  13500. $need_update = false;
  13501. $new_global_roles = $global_roles;
  13502. $new_global_scenes = $global_scenes;
  13503. // 检查并添加新角色到全局
  13504. foreach ($merged_roles as $role) {
  13505. $role_name = getProp($role, 'role');
  13506. // 跳过旁白
  13507. if ($role_name === '旁白') {
  13508. continue;
  13509. }
  13510. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  13511. if ($roleKey === '') {
  13512. continue;
  13513. }
  13514. // 如果全局中不存在该角色,添加到全局
  13515. if (!isset($global_role_map[$roleKey])) {
  13516. $new_global_roles[] = [
  13517. 'role' => $role_name,
  13518. 'description' => getProp($role, 'description', ''),
  13519. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  13520. 'voice_name' => getProp($role, 'voice_name', ''),
  13521. 'voice_type' => getProp($role, 'voice_type', ''),
  13522. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  13523. 'url' => getProp($role, 'url', ''),
  13524. 'task_id' => getProp($role, 'task_id', ''),
  13525. 'task_status' => getProp($role, 'task_status', ''),
  13526. ];
  13527. $global_role_map[$roleKey] = true; // 标记已添加
  13528. $need_update = true;
  13529. dLog('deepseek')->info("新角色同步到全局", [
  13530. 'anime_id' => $anime_id,
  13531. 'role' => $role_name,
  13532. 'task_id' => getProp($role, 'task_id', ''),
  13533. ]);
  13534. }
  13535. // else {
  13536. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  13537. // $global_role = $global_role_map[$roleKey];
  13538. // if (is_array($global_role)) {
  13539. // $updated = false;
  13540. // $update_fields = [];
  13541. // // 检查描述是否更新
  13542. // $current_description = trim((string)getProp($role, 'description'));
  13543. // $global_description = trim((string)getProp($global_role, 'description'));
  13544. // if ($current_description !== '' && $current_description !== $global_description) {
  13545. // $updated = true;
  13546. // $update_fields[] = 'description';
  13547. // }
  13548. // // 检查pic_prompt是否更新
  13549. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  13550. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  13551. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  13552. // $updated = true;
  13553. // $update_fields[] = 'pic_prompt';
  13554. // }
  13555. // // 检查图片任务信息是否更新
  13556. // $current_task_id = getProp($role, 'task_id');
  13557. // $global_task_id = getProp($global_role, 'task_id');
  13558. // if ($current_task_id && $current_task_id !== $global_task_id) {
  13559. // $updated = true;
  13560. // $update_fields[] = 'task_id';
  13561. // }
  13562. // // 如果有更新,同步到全局
  13563. // if ($updated) {
  13564. // foreach ($new_global_roles as &$global_role_item) {
  13565. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  13566. // if ($global_role_key === $roleKey) {
  13567. // if (in_array('description', $update_fields)) {
  13568. // $global_role_item['description'] = $current_description;
  13569. // }
  13570. // if (in_array('pic_prompt', $update_fields)) {
  13571. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  13572. // }
  13573. // if (in_array('task_id', $update_fields)) {
  13574. // $global_role_item['task_id'] = $current_task_id;
  13575. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  13576. // $global_role_item['url'] = getProp($role, 'url', '');
  13577. // }
  13578. // break;
  13579. // }
  13580. // }
  13581. // $need_update = true;
  13582. // dLog('deepseek')->info("角色信息更新到全局", [
  13583. // 'anime_id' => $anime_id,
  13584. // 'role' => $role_name,
  13585. // 'update_fields' => implode(',', $update_fields),
  13586. // ]);
  13587. // }
  13588. // }
  13589. // }
  13590. }
  13591. // 检查并添加新场景到全局
  13592. foreach ($merged_scenes as $scene) {
  13593. $scene_name = getProp($scene, 'scene');
  13594. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  13595. if ($sceneKey === '') {
  13596. continue;
  13597. }
  13598. // 如果全局中不存在该场景,添加到全局
  13599. if (!isset($global_scene_map[$sceneKey])) {
  13600. $new_global_scenes[] = [
  13601. 'scene' => $scene_name,
  13602. 'description' => getProp($scene, 'description', ''),
  13603. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  13604. 'url' => getProp($scene, 'url', ''),
  13605. 'task_id' => getProp($scene, 'task_id', ''),
  13606. 'task_status' => getProp($scene, 'task_status', ''),
  13607. ];
  13608. $global_scene_map[$sceneKey] = true; // 标记已添加
  13609. $need_update = true;
  13610. dLog('deepseek')->info("新场景同步到全局", [
  13611. 'anime_id' => $anime_id,
  13612. 'scene' => $scene_name,
  13613. 'task_id' => getProp($scene, 'task_id', ''),
  13614. ]);
  13615. }
  13616. // else {
  13617. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  13618. // $global_scene = $global_scene_map[$sceneKey];
  13619. // if (is_array($global_scene)) {
  13620. // $updated = false;
  13621. // $update_fields = [];
  13622. // // 检查描述是否更新
  13623. // $current_description = trim((string)getProp($scene, 'description'));
  13624. // $global_description = trim((string)getProp($global_scene, 'description'));
  13625. // if ($current_description !== '' && $current_description !== $global_description) {
  13626. // $updated = true;
  13627. // $update_fields[] = 'description';
  13628. // }
  13629. // // 检查pic_prompt是否更新
  13630. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  13631. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  13632. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  13633. // $updated = true;
  13634. // $update_fields[] = 'pic_prompt';
  13635. // }
  13636. // // 检查图片任务信息是否更新
  13637. // $current_task_id = getProp($scene, 'task_id');
  13638. // $global_task_id = getProp($global_scene, 'task_id');
  13639. // if ($current_task_id && $current_task_id !== $global_task_id) {
  13640. // $updated = true;
  13641. // $update_fields[] = 'task_id';
  13642. // }
  13643. // // 如果有更新,同步到全局
  13644. // if ($updated) {
  13645. // foreach ($new_global_scenes as &$global_scene_item) {
  13646. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  13647. // if ($global_scene_key === $sceneKey) {
  13648. // if (in_array('description', $update_fields)) {
  13649. // $global_scene_item['description'] = $current_description;
  13650. // }
  13651. // if (in_array('pic_prompt', $update_fields)) {
  13652. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  13653. // }
  13654. // if (in_array('task_id', $update_fields)) {
  13655. // $global_scene_item['task_id'] = $current_task_id;
  13656. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  13657. // $global_scene_item['url'] = getProp($scene, 'url', '');
  13658. // }
  13659. // break;
  13660. // }
  13661. // }
  13662. // $need_update = true;
  13663. // dLog('deepseek')->info("场景信息更新到全局", [
  13664. // 'anime_id' => $anime_id,
  13665. // 'scene' => $scene_name,
  13666. // 'update_fields' => implode(',', $update_fields),
  13667. // ]);
  13668. // }
  13669. // }
  13670. // }
  13671. }
  13672. // 如果有新增或更新,更新数据库
  13673. if ($need_update) {
  13674. $update_data = [
  13675. 'roles' => json_encode($new_global_roles, 256),
  13676. 'scenes' => json_encode($new_global_scenes, 256),
  13677. 'updated_at' => date('Y-m-d H:i:s'),
  13678. ];
  13679. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  13680. if ($result !== false) {
  13681. dLog('deepseek')->info("全局角色和场景更新成功", [
  13682. 'anime_id' => $anime_id,
  13683. 'roles_count' => count($new_global_roles),
  13684. 'scenes_count' => count($new_global_scenes),
  13685. ]);
  13686. } else {
  13687. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  13688. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  13689. }
  13690. }
  13691. }
  13692. }