DeepSeekService.php 654 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715
  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\Services\AIGeneration\AIImageGenerationService;
  11. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Log;
  13. use Illuminate\Support\Facades\Redis;
  14. use OSS\Core\OssException;
  15. use OSS\OssClient;
  16. use Smalot\PdfParser\Parser as PdfParser;
  17. use TCPDF;
  18. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  19. use Predis\Command\Traits\Get\Get;
  20. class DeepSeekService
  21. {
  22. private $url;
  23. private $api_key;
  24. private $sys_message;
  25. private $headers;
  26. private $valid_text_models;
  27. private $gpt_text_models;
  28. protected $aiImageGenerationService;
  29. public function __construct(AIImageGenerationService $aiImageGenerationService) {
  30. $this->aiImageGenerationService = $aiImageGenerationService;
  31. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  32. $this->api_key = env('DEEPSEEK_API_KEY');
  33. $this->headers = [
  34. 'Authorization' => 'Bearer '.$this->api_key,
  35. 'Content-Type' => 'application/json; charset=UTF-8'
  36. ];
  37. // 火山引擎模型列表
  38. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  39. // GPT文本模型列表
  40. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  41. $this->sys_message = [
  42. 'role' => 'system',
  43. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  44. 强制要求:\n
  45. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  46. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  47. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  48. 普通要求:\n
  49. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  50. 2.<分集剧本>的要求如下:
  51.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  52.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  53.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  54.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  55. \n\n
  56. 示例如下:\n
  57. ###剧本名:西昆仑
  58. ###故事梗概
  59. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  60. ###剧本亮点
  61. 亮点1:绝境奇药,生死一线
  62. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  63. 亮点2:结拜兄妹,化解尴尬
  64. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  65. 亮点3:纤发夺命,情愫暗涌
  66. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  67. ###人物关系
  68. 阿雪与梁萧之间存在兄妹之情。
  69. ###核心矛盾
  70. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  71. ###主体列表
  72. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  73. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  74. 阴阳球:天地异宝,能化生精气,救人于危难。
  75. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  76. ###美术风格
  77. 基础画风风格词:厚涂古风
  78. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  79. ###场景列表
  80. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  81. ###分集剧本
  82. ##分集01
  83. 第1集: 第一集的标题
  84. 场景描述:地点、时间、场景
  85. 运镜:固定近距离
  86. 出场角色:男主、女主
  87. 台词内容:
  88. 女主: 女主对话
  89. 男主:男主对话
  90. 女主: 女主对话
  91. 男主: 男主对话
  92. ##分集02
  93. 第2集: 第二集的标题
  94. 场景描述:地点、时间、场景
  95. 运镜:固定近距离
  96. 出场角色:男主、女主
  97. 台词内容:
  98. 女主: 女主对话
  99. 男主:男主对话
  100. 女主: 女主对话
  101. 男主: 男主对话"
  102. ];
  103. }
  104. /**
  105. * 通用文生文方法 - 支持多模型流式输出和图片输入
  106. *
  107. * @param array $data 请求参数
  108. * @return \Generator 返回生成器,用于流式输出
  109. */
  110. public function generateText($data) {
  111. // 获取请求参数
  112. $model = getProp($data, 'model', 'deepseek-v3-2-251201'); // 默认使用deepseek-v3
  113. $messages = getProp($data, 'messages', []);
  114. $systemPrompt = getProp($data, 'system_prompt', '');
  115. $prompt = getProp($data, 'prompt', '');
  116. $images = getProp($data, 'images', []); // 支持多张图片
  117. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  118. // 如果没有提供messages,则根据system_prompt、content和images构建
  119. if (empty($messages)) {
  120. $messages = [];
  121. // 添加系统提示词
  122. if (!empty($systemPrompt)) {
  123. $messages[] = [
  124. 'role' => 'system',
  125. 'content' => $systemPrompt
  126. ];
  127. }
  128. // 构建用户消息内容(支持文本+图片)
  129. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  130. $userMessage = [
  131. 'role' => 'user',
  132. 'content' => []
  133. ];
  134. // 添加文本内容
  135. if (!empty($prompt)) {
  136. $userMessage['content'][] = [
  137. 'type' => 'text',
  138. 'text' => $prompt
  139. ];
  140. }
  141. // 处理上传的图片文件
  142. if (!empty($images)) {
  143. if (!is_array($images)) {
  144. $images = [$images];
  145. }
  146. foreach ($images as $image) {
  147. $imageBase64 = $this->processImageToBase64($image);
  148. if ($imageBase64) {
  149. $userMessage['content'][] = [
  150. 'type' => 'image_url',
  151. 'image_url' => [
  152. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  153. ]
  154. ];
  155. }
  156. }
  157. }
  158. // 处理图片URL
  159. if (!empty($imageUrls)) {
  160. if (!is_array($imageUrls)) {
  161. $imageUrls = [$imageUrls];
  162. }
  163. foreach ($imageUrls as $url) {
  164. if (!empty($url)) {
  165. $userMessage['content'][] = [
  166. 'type' => 'image_url',
  167. 'image_url' => [
  168. 'url' => $url
  169. ]
  170. ];
  171. }
  172. }
  173. }
  174. // 如果只有文本内容,简化为字符串格式
  175. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  176. $userMessage['content'] = $userMessage['content'][0]['text'];
  177. }
  178. $messages[] = $userMessage;
  179. }
  180. }
  181. // 验证messages不为空
  182. if (empty($messages)) {
  183. Utils::throwError('20003:请提供有效的对话内容');
  184. }
  185. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  186. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  187. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  188. if ($model === 'deepseek-chat') {
  189. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  190. $model = 'deepseek-v4-flash';
  191. $thinkingMode = 'disabled';
  192. } elseif ($model === 'deepseek-reasoner') {
  193. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  194. $model = 'deepseek-v4-flash';
  195. $thinkingMode = 'enabled';
  196. }
  197. // 构建请求参数
  198. $post_data = [
  199. 'model' => $model,
  200. 'messages' => $messages,
  201. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  202. 'temperature' => getProp($data, 'temperature', 1),
  203. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  204. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  205. 'thinking' => ['type' => $thinkingMode],
  206. 'stream' => true // 启用流式输出
  207. ];
  208. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  209. // 添加可选参数
  210. if (isset($data['top_p'])) {
  211. $post_data['top_p'] = $data['top_p'];
  212. }
  213. if (isset($data['response_format'])) {
  214. $post_data['response_format'] = $data['response_format'];
  215. }
  216. // 根据模型类型选择调用方法
  217. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  218. // DeepSeek 官方模型使用 DeepSeek API
  219. return $this->deepSeekStreamResponse($post_data);
  220. } else if (in_array($model, $this->gpt_text_models)) {
  221. // GPT 模型使用 TokenRouter API
  222. return $this->gpt54StreamResponse($post_data);
  223. } else if (in_array($model, $this->valid_text_models)) {
  224. // 火山引擎支持的模型使用火山引擎 API
  225. return $this->volcEngineChatCompletion($post_data);
  226. } else {
  227. Utils::throwError('20003:不支持的模型: ' . $model);
  228. }
  229. }
  230. public function createGenerateText($data) {
  231. $file = getProp($data, 'file');
  232. $uid = Site::getUid();
  233. $cpid = Site::getCpid();
  234. if (!$file) {
  235. Utils::throwError('20003:请上传文件');
  236. }
  237. // 提取文件内容
  238. $content = $this->extractFileContent($file);
  239. if (!$content) {
  240. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  241. }
  242. // 获取原始文件名(不含扩展名)作为script_name
  243. $originalName = $file->getClientOriginalName();
  244. $script_name = pathinfo($originalName, PATHINFO_FILENAME);
  245. if (!$script_name) {
  246. $script_name = '剧本_' . date('YmdHis');
  247. }
  248. // 如果剧本名称已存在,添加时间戳后缀
  249. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('is_deleted', 0)->exists()) {
  250. $script_name .= '_' . date('YmdHis');
  251. }
  252. // 插入数据到mp_scripts表
  253. $script_id = DB::table('mp_scripts')->insertGetId([
  254. 'script_name' => $script_name,
  255. 'user_id' => $uid,
  256. 'cpid' => $cpid,
  257. 'content' => $content,
  258. 'created_at' => date('Y-m-d H:i:s'),
  259. 'updated_at' => date('Y-m-d H:i:s')
  260. ]);
  261. return [
  262. 'script_id' => $script_id,
  263. 'script_name' => $script_name
  264. ];
  265. }
  266. /**
  267. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  268. *
  269. * @param array $data 请求参数
  270. * @return array 返回结果数组
  271. */
  272. public function newGenerateText($data) {
  273. // 获取请求参数
  274. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  275. $messages = getProp($data, 'messages', []);
  276. $systemPrompt = getProp($data, 'system_prompt', '');
  277. $prompt = getProp($data, 'prompt', '');
  278. $images = getProp($data, 'images', []); // 支持多张图片
  279. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  280. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  281. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  282. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  283. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  284. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  285. $originalContent = '';
  286. if ($script_id > 0) {
  287. $script = DB::table('mp_scripts')
  288. ->where('id', $script_id)
  289. ->where('is_deleted', 0)
  290. ->first();
  291. if (!$script) {
  292. Utils::throwError('20003:剧本不存在或已删除');
  293. }
  294. $originalContent = $script->content ?? '';
  295. if (empty($originalContent)) {
  296. Utils::throwError('20003:剧本内容为空');
  297. }
  298. // 将剧本内容添加到提示词前面
  299. if (!empty($originalContent)) {
  300. if (!empty($prompt)) {
  301. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  302. } else {
  303. $prompt = "原文内容:\n" . $originalContent;
  304. }
  305. }
  306. }
  307. // 新增: 如果提供了template_id,从数据库获取template_prompt
  308. if ($templateId > 0) {
  309. $template = DB::table('mp_prompt_templates')
  310. ->where('id', $templateId)
  311. ->where('is_deleted', 0)
  312. ->first();
  313. if (!$template) {
  314. Utils::throwError('20003:模板不存在或已删除');
  315. }
  316. $templatePrompt = $template->template_prompt ?? '';
  317. // 将模板提示词和用户输入的prompt组合
  318. // 模板为准,用户输入作为补充要求
  319. if (!empty($templatePrompt)) {
  320. if (!empty($prompt)) {
  321. $prompt = $templatePrompt . "\n\n" . $prompt;
  322. } else {
  323. $prompt = $templatePrompt;
  324. }
  325. }
  326. }
  327. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  328. if (empty($messages)) {
  329. $messages = [];
  330. // 添加系统提示词
  331. if (!empty($systemPrompt)) {
  332. $messages[] = [
  333. 'role' => 'system',
  334. 'content' => $systemPrompt
  335. ];
  336. }
  337. // 构建用户消息内容(支持文本+图片)
  338. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  339. $userMessage = [
  340. 'role' => 'user',
  341. 'content' => []
  342. ];
  343. // 添加文本内容
  344. if (!empty($prompt)) {
  345. $userMessage['content'][] = [
  346. 'type' => 'text',
  347. 'text' => $prompt
  348. ];
  349. }
  350. // 处理上传的图片文件
  351. if (!empty($images)) {
  352. if (!is_array($images)) {
  353. $images = [$images];
  354. }
  355. foreach ($images as $image) {
  356. $imageBase64 = $this->processImageToBase64($image);
  357. if ($imageBase64) {
  358. $userMessage['content'][] = [
  359. 'type' => 'image_url',
  360. 'image_url' => [
  361. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  362. ]
  363. ];
  364. }
  365. }
  366. }
  367. // 处理图片URL
  368. if (!empty($imageUrls)) {
  369. if (!is_array($imageUrls)) {
  370. $imageUrls = [$imageUrls];
  371. }
  372. foreach ($imageUrls as $url) {
  373. if (!empty($url)) {
  374. $userMessage['content'][] = [
  375. 'type' => 'image_url',
  376. 'image_url' => [
  377. 'url' => $url
  378. ]
  379. ];
  380. }
  381. }
  382. }
  383. // 如果只有文本内容,简化为字符串格式
  384. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  385. $userMessage['content'] = $userMessage['content'][0]['text'];
  386. }
  387. $messages[] = $userMessage;
  388. }
  389. }
  390. // 验证messages不为空
  391. if (empty($messages)) {
  392. Utils::throwError('20003:请提供有效的对话内容');
  393. }
  394. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  395. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  396. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  397. if ($model === 'deepseek-chat') {
  398. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  399. $model = 'deepseek-v4-flash';
  400. $thinkingMode = 'disabled';
  401. } elseif ($model === 'deepseek-reasoner') {
  402. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  403. $model = 'deepseek-v4-flash';
  404. $thinkingMode = 'enabled';
  405. }
  406. // 构建请求参数(非流式)
  407. $post_data = [
  408. 'model' => $model,
  409. 'messages' => $messages,
  410. 'temperature' => getProp($data, 'temperature', 1),
  411. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  412. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  413. 'thinking' => ['type' => $thinkingMode],
  414. 'stream' => false // 非流式输出
  415. ];
  416. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  417. // 添加可选参数
  418. if (isset($data['top_p'])) {
  419. $post_data['top_p'] = $data['top_p'];
  420. }
  421. // 新增: 根据response_format设置响应格式
  422. if ($responseFormat === 'json') {
  423. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  424. $hasJsonKeyword = false;
  425. foreach ($post_data['messages'] as $message) {
  426. if (isset($message['content'])) {
  427. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  428. if (stripos($content, 'json') !== false) {
  429. $hasJsonKeyword = true;
  430. break;
  431. }
  432. }
  433. }
  434. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  435. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  436. if (!$hasJsonKeyword) {
  437. $lastMessageIndex = count($post_data['messages']) - 1;
  438. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  439. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  440. // 如果content是字符串,直接追加
  441. if (is_string($lastContent)) {
  442. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  443. }
  444. // 如果content是数组(包含文本和图片),在文本部分追加
  445. else if (is_array($lastContent)) {
  446. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  447. if ($contentPart['type'] === 'text') {
  448. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  449. break;
  450. }
  451. }
  452. }
  453. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  454. }
  455. }
  456. // 设置response_format参数(所有支持的模型)
  457. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  458. // DeepSeek模型
  459. $post_data['response_format'] = ['type' => 'json_object'];
  460. } else if (in_array($model, $this->gpt_text_models)) {
  461. // GPT模型
  462. $post_data['response_format'] = ['type' => 'json_object'];
  463. } else if (in_array($model, $this->valid_text_models)) {
  464. // 火山引擎模型
  465. $post_data['response_format'] = ['type' => 'json_object'];
  466. }
  467. }
  468. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  469. $aiResult = null;
  470. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  471. // DeepSeek 官方模型使用现有的 chatOnly 方法
  472. $result = $this->chatOnly($post_data);
  473. // 记录实际使用的模型
  474. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  475. $aiResult = [
  476. 'content' => $result['fullContent'],
  477. 'reasoning_content' => $result['fullReasoningContent'],
  478. 'usage' => $result['usage'],
  479. 'model' => $model,
  480. 'finish_reason' => 'stop'
  481. ];
  482. } else if (in_array($model, $this->gpt_text_models)) {
  483. // GPT 模型使用现有的 gpt54ChatOnly 方法
  484. $result = $this->gpt54ChatOnly($post_data);
  485. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  486. $aiResult = [
  487. 'content' => $result['fullContent'],
  488. 'reasoning_content' => '',
  489. 'usage' => $result['usage'],
  490. 'model' => $model,
  491. 'finish_reason' => 'stop'
  492. ];
  493. } else if (in_array($model, $this->valid_text_models)) {
  494. // 火山引擎支持的模型使用火山引擎 API(非流式)
  495. $post_data['stream'] = false;
  496. $result = $this->volcEngineChatCompletion($post_data);
  497. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  498. 'requested_model' => $model,
  499. 'result_keys' => array_keys($result),
  500. 'has_fullContent' => isset($result['fullContent']),
  501. 'has_content' => isset($result['content'])
  502. ]);
  503. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  504. $aiResult = [
  505. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  506. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  507. 'usage' => $result['usage'] ?? [],
  508. 'model' => $model,
  509. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  510. ];
  511. } else {
  512. Utils::throwError('20003:不支持的模型: ' . $model);
  513. }
  514. // 新增: 如果提供了script_id,保存对话记录
  515. if ($script_id > 0 && $aiResult) {
  516. try {
  517. $uid = Site::getUid();
  518. $now = now();
  519. // 获取用户原始的prompt(不包含剧本内容)
  520. $originalPrompt = getProp($data, 'prompt', '');
  521. $recordsToInsert = [
  522. [
  523. 'uid' => $uid,
  524. 'script_id' => $script_id,
  525. 'sequence' => $sequence,
  526. 'role' => 'user',
  527. 'content' => $originalPrompt,
  528. 'created_at' => $now,
  529. 'updated_at' => $now,
  530. ],
  531. [
  532. 'uid' => $uid,
  533. 'script_id' => $script_id,
  534. 'sequence' => $sequence,
  535. 'role' => 'assistant',
  536. 'content' => $aiResult['content'],
  537. 'created_at' => $now,
  538. 'updated_at' => $now,
  539. ]
  540. ];
  541. DB::table('mp_script_records')->insert($recordsToInsert);
  542. // 获取刚插入的记录ID(假设按插入顺序返回)
  543. $insertedRecords = DB::table('mp_script_records')
  544. ->where('uid', $uid)
  545. ->where('script_id', $script_id)
  546. ->where('sequence', $sequence)
  547. ->orderBy('id', 'desc')
  548. ->limit(2)
  549. ->get()
  550. ->map(function ($record) {
  551. return [
  552. 'rid' => $record->id,
  553. 'script_id' => $record->script_id,
  554. 'sequence' => $record->sequence,
  555. 'role' => $record->role,
  556. 'content' => $record->content,
  557. 'created_at' => $record->created_at,
  558. ];
  559. })
  560. ->reverse()
  561. ->values()
  562. ->toArray();
  563. // 将记录信息添加到返回结果中
  564. $aiResult['records'] = $insertedRecords;
  565. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  566. } catch (\Exception $e) {
  567. // 记录错误但不影响主流程
  568. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  569. }
  570. }
  571. return $aiResult;
  572. }
  573. public function saveScriptChatHistory($data) {
  574. $uid = Site::getUid();
  575. $rid = getProp($data, 'rid');
  576. $script_id = getProp($data, 'script_id');
  577. $sequence = getProp($data, 'sequence', 0);
  578. $content = getProp($data, 'content');
  579. if (!$rid) {
  580. Utils::throwError('20003:请选择对话记录ID');
  581. }
  582. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  583. if (!$record) {
  584. Utils::throwError('20003:对话记录不存在');
  585. }
  586. if (!$script_id) {
  587. Utils::throwError('20003:请选择剧本');
  588. }
  589. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  590. if (!$script) {
  591. Utils::throwError('20003:剧本不存在');
  592. }
  593. // 批量插入数据
  594. return DB::table('mp_script_records')->where('id', $rid)->update([
  595. 'content' => $content,
  596. 'updated_at' => date('Y-m-d H:i:s')
  597. ]);
  598. }
  599. /**
  600. * 获取剧本的历史对话记录
  601. *
  602. * @param array $data 请求参数
  603. * @return array 返回历史记录数组
  604. */
  605. public function getScriptChatHistory($data) {
  606. $uid = Site::getUid();
  607. $script_id = getProp($data, 'script_id');
  608. $rid = getProp($data, 'rid');
  609. $sequence = getProp($data, 'sequence', null);
  610. if (!$script_id) {
  611. Utils::throwError('20003:请提供剧本ID');
  612. }
  613. // 验证剧本是否存在
  614. $script = DB::table('mp_scripts')
  615. ->where('id', $script_id)
  616. ->where('is_deleted', 0)
  617. ->first();
  618. if (!$script) {
  619. Utils::throwError('20003:剧本不存在');
  620. }
  621. // 构建查询
  622. $query = DB::table('mp_script_records')
  623. ->where('script_id', $script_id);
  624. // ->where('uid', $uid);
  625. // 如果提供了 sequence,则过滤指定剧集
  626. if ($sequence !== null) {
  627. $query->where('sequence', $sequence);
  628. }
  629. // 记录ID筛选
  630. if ($rid) {
  631. $query->where('id', $rid);
  632. }
  633. // 查询记录并按 id 正序排序
  634. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  635. ->orderBy('created_at', 'asc')
  636. ->orderBy('id', 'asc')
  637. ->get()
  638. ->map(function ($record) {
  639. return [
  640. 'rid' => $record->id,
  641. 'script_id' => $record->script_id,
  642. 'sequence' => $record->sequence,
  643. 'role' => $record->role,
  644. 'content' => $record->content,
  645. 'products' => $record->products ? json_decode($record->products) : [],
  646. 'created_at' => $record->created_at,
  647. ];
  648. })
  649. ->toArray();
  650. return $records;
  651. }
  652. /**
  653. * 处理图片转换为base64
  654. *
  655. * @param mixed $image 图片文件对象或文件路径
  656. * @return string|null base64编码的图片数据
  657. */
  658. private function processImageToBase64($image) {
  659. try {
  660. // 获取文件路径
  661. if (is_string($image)) {
  662. $filePath = $image;
  663. } else {
  664. // Laravel UploadedFile 对象
  665. $filePath = $image->getRealPath();
  666. }
  667. if (!file_exists($filePath)) {
  668. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  669. return null;
  670. }
  671. // 验证是否为图片文件
  672. $imageInfo = @getimagesize($filePath);
  673. if ($imageInfo === false) {
  674. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  675. return null;
  676. }
  677. // 读取图片并转换为base64
  678. $imageData = file_get_contents($filePath);
  679. $base64Image = base64_encode($imageData);
  680. dLog('deepseek')->info('图片转换成功', [
  681. 'size' => strlen($imageData),
  682. 'type' => $imageInfo['mime']
  683. ]);
  684. return $base64Image;
  685. } catch (\Exception $e) {
  686. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  687. return null;
  688. }
  689. }
  690. private function getArtStylePromptMappings($art_style='')
  691. {
  692. $arr = [
  693. '唯美真人风格' => [
  694. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  695. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  696. ],
  697. '真人古风风格' => [
  698. 'aliases' => ['真人古风风格', '真人古风'],
  699. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  700. ],
  701. '日系动漫风格' => [
  702. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  703. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  704. ],
  705. '国漫风格' => [
  706. 'aliases' => ['国漫风格', '国漫'],
  707. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  708. ],
  709. 'Q版卡通风格' => [
  710. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  711. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  712. ],
  713. '简约扁平风格' => [
  714. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  715. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  716. ],
  717. '武侠风格' => [
  718. 'aliases' => ['武侠风格', '武侠'],
  719. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  720. ],
  721. '古风仙侠风格' => [
  722. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  723. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  724. ],
  725. '新中式水墨风格' => [
  726. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  727. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  728. ],
  729. '写实插画风格' => [
  730. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  731. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  732. ],
  733. '3D卡通风格' => [
  734. 'aliases' => ['3D卡通风格', '3D卡通'],
  735. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  736. ],
  737. '条漫风格' => [
  738. 'aliases' => ['条漫风格', '条漫'],
  739. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  740. ],
  741. '赛博朋克风格' => [
  742. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  743. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  744. ],
  745. '暗黑悬疑风格' => [
  746. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  747. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  748. ],
  749. '治愈清新风格' => [
  750. 'aliases' => ['治愈清新风格', '治愈清新'],
  751. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  752. ],
  753. ];
  754. if($art_style) {
  755. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  756. }
  757. return $arr;
  758. $arr = [
  759. '唯美真人风格' => [
  760. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  761. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  762. 2. 色彩色调
  763. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  764. 3. 画质精度
  765. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  766. 4. 画面观感
  767. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  768. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  769. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  770. ],
  771. '真人古风风格' => [
  772. 'aliases' => ['真人古风风格', '真人古风'],
  773. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  774. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  775. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  776. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  777. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  778. ],
  779. '日系动漫风格' => [
  780. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  781. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  782. 正向提示词(中文)
  783. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  784. 必须遵守规则
  785. • 全程保持日系动漫风格,不混入其他画风
  786. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  787. • 画面适配所选画面比例,构图居中,主体突出
  788. • 线条干净、色彩统一,不杂乱、不突兀
  789. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  790. ],
  791. '国漫风格' => [
  792. 'aliases' => ['国漫风格', '国漫'],
  793. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  794. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  795. 必须遵守规则
  796. • 严格保持国漫画风,不串风格、不混画风
  797. • 角色形象统一,不随意改变五官、身材、服饰
  798. • 画面构图稳定,适合漫剧叙事展示
  799. • 色调统一,不出现脏色、杂色
  800. 禁止/避免词汇
  801. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  802. ],
  803. 'Q版卡通风格' => [
  804. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  805. 'prompt' => "风格说明
  806. 头大身小,造型可爱圆润,简约干净
  807. 正向提示词(中文)
  808. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  809. 必须遵守规则
  810. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  811. • 角色造型统一,表情可爱,不诡异
  812. • 画面简洁清爽,无多余复杂元素
  813. • 色彩明亮柔和,不刺眼
  814. 禁止/避免词汇
  815. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  816. ],
  817. '简约扁平风格' => [
  818. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  819. 'prompt' => "风格说明
  820. 色块简洁、无复杂渐变,现代极简风
  821. 正向提示词(中文)
  822. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  823. 必须遵守规则
  824. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  825. • 构图简洁,主体突出,无多余装饰
  826. • 色彩统一、干净,不杂乱
  827. 禁止/避免词汇
  828. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  829. ],
  830. '武侠风格' => [
  831. 'aliases' => ['武侠风格', '武侠'],
  832. 'prompt' => "风格说明
  833. 江湖气息,线条硬朗,动作感强
  834. 正向提示词(中文)
  835. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  836. 必须遵守规则
  837. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  838. • 角色形象、服饰、身材比例统一
  839. • 画面动作自然,不扭曲、不畸形
  840. 禁止/避免词汇
  841. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  842. ],
  843. '古风仙侠风格' => [
  844. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  845. 'prompt' => "风格说明
  846. 飘逸汉服、云雾仙气、唯美空灵
  847. 正向提示词(中文)
  848. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  849. 必须遵守规则
  850. • 保持古风仙侠统一画风,不混入现代、科幻元素
  851. • 角色服饰、发型、形象前后一致
  852. • 场景仙气飘逸,色调清雅统一
  853. • 画面唯美柔和,不阴暗、不诡异
  854. 禁止/避免词汇
  855. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  856. ],
  857. '新中式水墨风格' => [
  858. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  859. 'prompt' => "风格说明
  860. 淡墨渲染,毛笔笔触,留白意境
  861. 正向提示词(中文)
  862. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  863. 必须遵守规则
  864. • 严格保持水墨质感,不混入厚涂、写实、卡通
  865. • 色调淡雅统一,不浓艳杂乱
  866. • 画面干净有意境,不堆砌元素
  867. 禁止/避免词汇
  868. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  869. ],
  870. '写实插画风格' => [
  871. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  872. 'prompt' => "风格说明
  873. 接近真人比例,光影真实,质感细腻
  874. 正向提示词(中文)
  875. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  876. 必须遵守规则
  877. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  878. • 角色五官、身材、服饰高度统一
  879. • 画面清晰、光影自然、不扭曲
  880. 禁止/避免词汇
  881. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  882. ],
  883. '3D卡通风格' => [
  884. 'aliases' => ['3D卡通风格', '3D卡通'],
  885. 'prompt' => "风格说明
  886. 3D建模质感,柔和渲染,圆润可爱
  887. 正向提示词(中文)
  888. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  889. 必须遵守规则
  890. • 保持3D卡通统一质感,不出现2D杂乱线条
  891. • 角色模型、比例、形象前后一致
  892. • 画面干净,不模糊、不穿模
  893. 禁止/避免词汇
  894. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  895. ],
  896. '条漫风格' => [
  897. 'aliases' => ['条漫风格', '条漫'],
  898. 'prompt' => "风格说明
  899. 纵向分镜,上下滑动阅读,轻量化
  900. 正向提示词(中文)
  901. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  902. 必须遵守规则
  903. • 保持条漫纵向阅读逻辑,构图简洁
  904. • 画风统一,不混写实、3D、水墨
  905. • 画面干净,不杂乱
  906. 禁止/避免词汇
  907. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  908. ],
  909. '赛博朋克风格' => [
  910. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  911. 'prompt' => "风格说明
  912. 霓虹灯光、未来都市、暗色调、科技机械
  913. 正向提示词(中文)
  914. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  915. 必须遵守规则
  916. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  917. • 色调以暗调+霓虹为主,色彩统一
  918. • 画面科技感强,不杂乱
  919. 禁止/避免词汇
  920. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  921. ],
  922. '暗黑悬疑风格' => [
  923. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  924. 'prompt' => "风格说明
  925. 低饱和、冷色调、阴影重、神秘压抑
  926. 正向提示词(中文)
  927. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  928. 必须遵守规则
  929. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  930. • 画面氛围压抑神秘,但不低俗、不血腥
  931. • 角色形象统一,不崩坏
  932. 禁止/避免词汇
  933. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  934. ],
  935. '治愈清新风格' => [
  936. 'aliases' => ['治愈清新风格', '治愈清新'],
  937. 'prompt' => "风格说明
  938. 马卡龙色系、柔光、温暖干净
  939. 正向提示词(中文)
  940. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  941. 必须遵守规则
  942. • 保持治愈清新统一色调,不阴暗、不诡异
  943. • 画面柔和干净,无杂乱元素
  944. • 角色形象柔和可爱,不狰狞
  945. 禁止/避免词汇
  946. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  947. ],
  948. ];
  949. return $arr;
  950. }
  951. public function getArtStylePromptByInput($inputArtStyle): string
  952. {
  953. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  954. if ($normalizedInput === '') {
  955. return '';
  956. }
  957. return $this->getArtStylePromptMappings($normalizedInput);
  958. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  959. // foreach ($mapping['aliases'] as $alias) {
  960. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  961. // if ($normalizedAlias === '') {
  962. // continue;
  963. // }
  964. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  965. // return $mapping['prompt'];
  966. // }
  967. // }
  968. // }
  969. return '';
  970. }
  971. public function getArtStyleShortPromptByInput($inputArtStyle) {
  972. $stylePrefixes = [
  973. '唯美真人风格' => [
  974. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  975. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  976. ],
  977. '真人古风风格' => [
  978. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  979. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  980. ],
  981. '日系动漫风格' => [
  982. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  983. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  984. ],
  985. '国漫风格' => [
  986. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  987. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  988. ],
  989. 'Q版卡通风格' => [
  990. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  991. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  992. ],
  993. '简约扁平风格' => [
  994. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  995. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  996. ],
  997. '武侠风格' => [
  998. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  999. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  1000. ],
  1001. '古风仙侠风格' => [
  1002. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  1003. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  1004. ],
  1005. '新中式水墨风格' => [
  1006. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  1007. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  1008. ],
  1009. '写实插画风格' => [
  1010. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  1011. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  1012. ],
  1013. '3D卡通风格' => [
  1014. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  1015. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  1016. ],
  1017. '条漫风格' => [
  1018. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  1019. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  1020. ],
  1021. '赛博朋克风格' => [
  1022. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  1023. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  1024. ],
  1025. '暗黑悬疑风格' => [
  1026. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  1027. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  1028. ],
  1029. '治愈清新风格' => [
  1030. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  1031. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  1032. ]
  1033. ];
  1034. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  1035. }
  1036. private function normalizeArtStyleInput($value): string
  1037. {
  1038. $value = trim((string)$value);
  1039. if ($value === '') {
  1040. return '';
  1041. }
  1042. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  1043. return mb_strtolower($value, 'UTF-8');
  1044. }
  1045. private function replaceArtStyleSection(string $content, string $artStyle): string
  1046. {
  1047. if ($content === '' || $artStyle === '') {
  1048. return $content;
  1049. }
  1050. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  1051. if (!preg_match($pattern, $content)) {
  1052. return $content;
  1053. }
  1054. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  1055. }
  1056. /**
  1057. * DeepSeek流式输出处理方法
  1058. *
  1059. * @param array $post_data DeepSeek API请求参数
  1060. * @return \Generator 返回生成器,用于流式输出
  1061. */
  1062. private function deepSeekStreamResponse($post_data) {
  1063. // 设置最大输出tokens
  1064. $post_data['max_tokens'] = 300000;
  1065. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1066. $response = $client->post($this->url, [
  1067. 'json' => $post_data,
  1068. 'headers' => $this->headers,
  1069. 'stream' => true // 启用流式响应
  1070. ]);
  1071. $body = $response->getBody();
  1072. $fullContent = '';
  1073. $fullReasoningContent = '';
  1074. $usage = [];
  1075. $buffer = '';
  1076. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1077. // 逐行读取流式响应
  1078. while (!$body->eof()) {
  1079. $chunk = $body->read(1024); // 每次读取 1KB
  1080. $buffer .= $chunk;
  1081. // 按行分割
  1082. $lines = explode("\n", $buffer);
  1083. // 保留最后一个不完整的行
  1084. $buffer = array_pop($lines);
  1085. foreach ($lines as $line) {
  1086. $line = trim($line);
  1087. // 跳过空行
  1088. if (empty($line)) {
  1089. continue;
  1090. }
  1091. // 检查是否是 SSE 数据行
  1092. if (strpos($line, 'data: ') !== 0) {
  1093. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1094. continue;
  1095. }
  1096. $data = substr($line, 6); // 移除 "data: " 前缀
  1097. if ($data === '[DONE]') {
  1098. dLog('deepseek')->info('收到结束标记');
  1099. break 2; // 跳出两层循环
  1100. }
  1101. try {
  1102. $json = json_decode($data, true);
  1103. if (json_last_error() !== JSON_ERROR_NONE) {
  1104. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1105. continue;
  1106. }
  1107. if (isset($json['choices'][0]['delta'])) {
  1108. $delta = $json['choices'][0]['delta'];
  1109. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1110. if (isset($delta['reasoning_content'])) {
  1111. $fullReasoningContent .= $delta['reasoning_content'];
  1112. yield [
  1113. 'type' => 'reasoning',
  1114. 'content' => $delta['reasoning_content'],
  1115. 'full_reasoning' => $fullReasoningContent
  1116. ];
  1117. }
  1118. // 处理最终回答内容
  1119. if (isset($delta['content'])) {
  1120. $fullContent .= $delta['content'];
  1121. yield [
  1122. 'type' => 'content',
  1123. 'content' => $delta['content'],
  1124. ];
  1125. }
  1126. }
  1127. // 获取使用统计信息
  1128. if (isset($json['usage'])) {
  1129. $usage = $json['usage'];
  1130. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1131. }
  1132. } catch (\Exception $e) {
  1133. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1134. continue;
  1135. }
  1136. }
  1137. }
  1138. dLog('deepseek')->info('流式读取完成', [
  1139. 'content_length' => strlen($fullContent),
  1140. 'reasoning_length' => strlen($fullReasoningContent)
  1141. ]);
  1142. yield [
  1143. 'type' => 'done',
  1144. 'full_content' => $fullContent,
  1145. 'full_reasoning' => $fullReasoningContent,
  1146. 'usage' => $usage
  1147. ];
  1148. }
  1149. /**
  1150. * GPT 流式输出处理方法
  1151. *
  1152. * @param array $post_data GPT API请求参数
  1153. * @return \Generator 返回生成器,用于流式输出
  1154. */
  1155. private function gpt54StreamResponse($post_data) {
  1156. $apiKey = env('GPT_54_API_KEY');
  1157. if (empty($apiKey)) {
  1158. Utils::throwError('20003:GPT API Key未配置');
  1159. }
  1160. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1161. $headers = [
  1162. 'Authorization' => 'Bearer ' . $apiKey,
  1163. 'Content-Type' => 'application/json'
  1164. ];
  1165. // 移除 thinking 参数,GPT-5.4 不支持
  1166. if (isset($post_data['thinking'])) {
  1167. unset($post_data['thinking']);
  1168. }
  1169. if (isset($post_data['reasoning_effort'])) {
  1170. unset($post_data['reasoning_effort']);
  1171. }
  1172. $post_data['max_completion_tokens'] = 100000;
  1173. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  1174. $response = $client->post('https://api.nonelinear.com/v1/chat/completions', [
  1175. 'json' => $post_data,
  1176. 'headers' => $headers
  1177. ]);
  1178. $body = $response->getBody();
  1179. $fullContent = '';
  1180. $usage = [];
  1181. $buffer = '';
  1182. dLog('deepseek')->info('开始读取 GPT 流式响应');
  1183. // 逐行读取流式响应
  1184. while (!$body->eof()) {
  1185. $chunk = $body->read(1024); // 每次读取 1KB
  1186. $buffer .= $chunk;
  1187. // 按行分割
  1188. $lines = explode("\n", $buffer);
  1189. // 保留最后一个不完整的行
  1190. $buffer = array_pop($lines);
  1191. foreach ($lines as $line) {
  1192. $line = trim($line);
  1193. // 跳过空行
  1194. if (empty($line)) {
  1195. continue;
  1196. }
  1197. // 检查是否是 SSE 数据行
  1198. if (strpos($line, 'data: ') !== 0) {
  1199. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1200. continue;
  1201. }
  1202. $data = substr($line, 6); // 移除 "data: " 前缀
  1203. if ($data === '[DONE]') {
  1204. dLog('deepseek')->info('收到结束标记');
  1205. break 2; // 跳出两层循环
  1206. }
  1207. try {
  1208. $json = json_decode($data, true);
  1209. if (json_last_error() !== JSON_ERROR_NONE) {
  1210. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1211. continue;
  1212. }
  1213. if (isset($json['choices'][0]['delta'])) {
  1214. $delta = $json['choices'][0]['delta'];
  1215. // 处理回答内容
  1216. if (isset($delta['content'])) {
  1217. $fullContent .= $delta['content'];
  1218. yield [
  1219. 'type' => 'content',
  1220. 'content' => $delta['content'],
  1221. ];
  1222. }
  1223. }
  1224. // 获取使用统计信息
  1225. if (isset($json['usage'])) {
  1226. $usage = $json['usage'];
  1227. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1228. }
  1229. } catch (\Exception $e) {
  1230. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1231. continue;
  1232. }
  1233. }
  1234. }
  1235. dLog('deepseek')->info('流式读取完成', [
  1236. 'content_length' => strlen($fullContent)
  1237. ]);
  1238. yield [
  1239. 'type' => 'done',
  1240. 'full_content' => $fullContent,
  1241. 'full_reasoning' => '',
  1242. 'usage' => $usage
  1243. ];
  1244. }
  1245. // 与推理模型对话
  1246. public function chatWithReasoner($data) {
  1247. $content = getProp($data, 'content');
  1248. $model = getProp($data, 'model', 'r1');
  1249. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1250. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1251. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1252. if ($model == 'r1') {
  1253. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  1254. $thinkingMode = 'disabled';
  1255. } else {
  1256. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  1257. $thinkingMode = 'disabled';
  1258. }
  1259. // 获取可选情感(根据音色可支持情感选)
  1260. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  1261. $emotion_list = [];
  1262. foreach ($timbre_emotion as $emotion) {
  1263. $tmp = explode(',', $emotion);
  1264. $emotion_list = array_merge($emotion_list, $tmp);
  1265. }
  1266. $emotion_list = array_unique($emotion_list);
  1267. $emotion_str = implode('、', $emotion_list);
  1268. // // 获取可选情感
  1269. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  1270. // $emotion_str = implode('、', $emotion_list);
  1271. // 是否启用情感
  1272. $enable_emotion = getProp($data, 'enable_emotion', 0);
  1273. if ($enable_emotion) {
  1274. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  1275. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1276. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  1277. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  1278. }else {
  1279. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  1280. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1281. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  1282. }
  1283. $messages = [
  1284. [
  1285. 'role' => 'system',
  1286. 'content' => $sys_content
  1287. ],
  1288. [
  1289. 'role' => 'user',
  1290. 'content' => $content
  1291. ]
  1292. ];
  1293. $post_data = [
  1294. 'model' => $model,
  1295. 'messages' => $messages,
  1296. // 'max_tokens' => 8192,
  1297. 'temperature' => 1,
  1298. 'frequency_penalty' => 0,
  1299. 'presence_penalty' => 0,
  1300. 'thinking' => ['type' => $thinkingMode],
  1301. 'response_format' => [
  1302. 'type' => 'text'
  1303. ],
  1304. 'stream' => false
  1305. ];
  1306. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1307. // 根据模型类型选择调用方法
  1308. $fullContent = '';
  1309. $usage = [];
  1310. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1311. // DeepSeek 官方模型使用 DeepSeek API
  1312. $chatResult = $this->chatOnly($post_data);
  1313. } else if (in_array($model, $this->gpt_text_models)) {
  1314. // GPT-5.4 模型使用 TokenRouter API
  1315. $chatResult = $this->gpt54ChatOnly($post_data);
  1316. } else {
  1317. // 其他模型使用火山引擎API
  1318. $chatResult = $this->volcEngineChatCompletion($post_data);
  1319. }
  1320. if (is_array($chatResult)) {
  1321. $fullContent = $chatResult['fullContent'];
  1322. $usage = $chatResult['usage'];
  1323. }
  1324. // 处理获取到的剧本数据
  1325. $script_content = handleScriptWords($fullContent, $enable_emotion);
  1326. $result = [
  1327. 'origin_content' => $fullContent,
  1328. 'roles' => getProp($script_content, 'roles'),
  1329. 'words' => getProp($script_content, 'words'),
  1330. ];
  1331. return $result;
  1332. }
  1333. public function resetParagraphAudio($data) {
  1334. $bid = getProp($data, 'bid');
  1335. $cid = getProp($data, 'cid');
  1336. $version_id = getProp($data, 'version_id');
  1337. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  1338. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  1339. 'generate_status' => '待制作',
  1340. 'updated_at' => date('Y-m-d H:i:s')
  1341. ]);
  1342. }
  1343. public function saveParagraphAudio($data) {
  1344. $bid = getProp($data, 'bid');
  1345. $cid = getProp($data, 'cid');
  1346. $version_id = getProp($data, 'version_id');
  1347. $sequence = getProp($data, 'sequence');
  1348. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  1349. // 获取所有情感
  1350. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1351. $emotion_list = array_flip($emotion_list);
  1352. // 获取音色支持情感
  1353. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  1354. $timbre_emotion = explode(',', $timbre_emotion);
  1355. $emotion = getProp($data, 'emotion');
  1356. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  1357. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  1358. $list = [
  1359. 'bid' => $bid,
  1360. 'cid' => $cid,
  1361. 'version_id' => $version_id,
  1362. 'sequence' => $sequence,
  1363. 'role' => getProp($data, 'role'),
  1364. 'gender' => getProp($data, 'gender'),
  1365. 'text' => trim(getProp($data, 'text')),
  1366. 'emotion' => $emotion,
  1367. 'emotion_type' => $emotion_type,
  1368. 'voice_type' => getProp($data, 'voice_type'),
  1369. 'voice_name' => getProp($data, 'voice_name'),
  1370. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  1371. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  1372. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  1373. 'pitch' => getProp($data, 'pitch', 0),
  1374. // 'paragraph_audio_url' => '',
  1375. 'generate_status' => '制作中',
  1376. 'error_msg' => '',
  1377. 'updated_at' => date('Y-m-d H:i:s')
  1378. ];
  1379. $continue = false;
  1380. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  1381. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  1382. $list['generate_status'] = '制作成功';
  1383. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1384. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  1385. $continue = true;
  1386. }
  1387. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  1388. if ($id) {
  1389. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  1390. }else {
  1391. $list['created_at'] = date('Y-m-d H:i:s');
  1392. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  1393. $boolen = $id ? true : false;
  1394. }
  1395. // 如果更新成功则加入查询队列
  1396. if ($boolen) {
  1397. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  1398. Redis::sadd($redis_key, $id);
  1399. }
  1400. if ($boolen && !$continue) {
  1401. $boolen = false;
  1402. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1403. // 根据ID通过API通知合成音频
  1404. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  1405. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  1406. $response = $result->getBody()->getContents();
  1407. $response_arr = json_decode($response, true);
  1408. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1409. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1410. Log::info('通知火山生成段落音频失败: '.$error_msg);
  1411. Utils::throwError('20003:通知火山生成段落音频失败');
  1412. }
  1413. $boolen = true;
  1414. }
  1415. return $boolen;
  1416. }
  1417. public function insertAudioEffect($data) {
  1418. $audio_id = getProp($data, 'audio_id');
  1419. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1420. $bid = getProp($chapter_audio, 'bid');
  1421. $version_id = getProp($chapter_audio, 'version_id');
  1422. $cid = getProp($chapter_audio, 'cid');
  1423. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1424. $audio_effect_json = getProp($data, 'audio_effect_json');
  1425. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  1426. try {
  1427. DB::beginTransaction();
  1428. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1429. if (!$count) {
  1430. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1431. }else {
  1432. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1433. }
  1434. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1435. 'audio_effect_status' => '添加中',
  1436. 'audio_effect_json' => $audio_effect_json,
  1437. 'updated_at' => date('Y-m-d H:i:s')
  1438. ]);
  1439. if (!$boolen1) {
  1440. DB::rollBack();
  1441. Utils::throwError('20003:更新生成数据失败');
  1442. }
  1443. $id = DB::table('mp_audio_tasks')->insertGetId([
  1444. 'audio_id' => $audio_id,
  1445. 'generate_status' => '执行中',
  1446. 'generate_json' => json_encode([], 256),
  1447. 'bid' => $bid,
  1448. 'book_name' => getProp($chapter_audio, 'book_name'),
  1449. 'version_id' => $version_id,
  1450. 'version_name' => getProp($chapter_audio, 'version_name'),
  1451. 'cid' => $cid,
  1452. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1453. 'task_name' => $task_name,
  1454. 'created_at' => date('Y-m-d H:i:s'),
  1455. 'updated_at' => date('Y-m-d H:i:s')
  1456. ]);
  1457. if (!$id) {
  1458. DB::rollBack();
  1459. Utils::throwError('20003:创建任务失败');
  1460. }
  1461. }catch (\Exception $e) {
  1462. DB::rollBack();
  1463. Utils::throwError('20003:'.$e->getMessage());
  1464. }
  1465. DB::commit();
  1466. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1467. // 根据ID通过API通知合成音频
  1468. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1469. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1470. $response = $result->getBody()->getContents();
  1471. $response_arr = json_decode($response, true);
  1472. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1473. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1474. Log::info('通知火山插入音效失败: '.$error_msg);
  1475. Utils::throwError('20003:通知火山插入音效失败');
  1476. }
  1477. return true;
  1478. }
  1479. public function insertBgm($data) {
  1480. $audio_id = getProp($data, 'audio_id');
  1481. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1482. $bid = getProp($chapter_audio, 'bid');
  1483. $version_id = getProp($chapter_audio, 'version_id');
  1484. $cid = getProp($chapter_audio, 'cid');
  1485. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1486. $bgm_json = getProp($data, 'bgm_json');
  1487. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1488. if (!$bgm_json) {
  1489. $bgm_json = getProp($data, 'audio_effect_json');
  1490. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1491. }
  1492. try {
  1493. DB::beginTransaction();
  1494. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1495. if (!$count) {
  1496. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1497. }else {
  1498. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1499. }
  1500. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1501. 'bgm_status' => '添加中',
  1502. 'bgm_json' => $bgm_json,
  1503. 'updated_at' => date('Y-m-d H:i:s')
  1504. ]);
  1505. if (!$boolen1) {
  1506. DB::rollBack();
  1507. Utils::throwError('20003:更新生成数据失败');
  1508. }
  1509. $id = DB::table('mp_audio_tasks')->insertGetId([
  1510. 'audio_id' => $audio_id,
  1511. 'generate_status' => '执行中',
  1512. 'generate_json' => json_encode([], 256),
  1513. 'bid' => $bid,
  1514. 'book_name' => getProp($chapter_audio, 'book_name'),
  1515. 'version_id' => $version_id,
  1516. 'version_name' => getProp($chapter_audio, 'version_name'),
  1517. 'cid' => $cid,
  1518. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1519. 'task_name' => $task_name,
  1520. 'created_at' => date('Y-m-d H:i:s'),
  1521. 'updated_at' => date('Y-m-d H:i:s')
  1522. ]);
  1523. if (!$id) {
  1524. DB::rollBack();
  1525. Utils::throwError('20003:创建任务失败');
  1526. }
  1527. }catch (\Exception $e) {
  1528. DB::rollBack();
  1529. Utils::throwError('20003:'.$e->getMessage());
  1530. }
  1531. DB::commit();
  1532. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1533. // 根据ID通过API通知合成音频
  1534. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1535. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1536. $response = $result->getBody()->getContents();
  1537. $response_arr = json_decode($response, true);
  1538. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1539. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1540. Log::info('通知火山插入bgm失败: '.$error_msg);
  1541. Utils::throwError('20003:通知火山插入bgm失败');
  1542. }
  1543. return true;
  1544. }
  1545. public function getParagraphAudios($data) {
  1546. $bid = getProp($data, 'bid');
  1547. $cid = getProp($data, 'cid');
  1548. $version_id = getProp($data, 'version_id');
  1549. $sequence = getProp($data, 'sequence');
  1550. // 获取已生成的音频
  1551. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  1552. if ($sequence) $query->where('sequence', $sequence);
  1553. $paragraph_audios = $query->orderBy('sequence')->get();
  1554. $result = [];
  1555. foreach($paragraph_audios as $item) {
  1556. $result[] = [
  1557. 'sequence' => getProp($item, 'sequence'),
  1558. 'role' => getProp($item, 'role'),
  1559. 'gender' => getProp($item, 'gender'),
  1560. 'text' => trim(getProp($item, 'text')),
  1561. 'emotion' => getProp($item, 'emotion'),
  1562. 'emotion_type' => getProp($item, 'emotion_type'),
  1563. 'voice_type' => getProp($item, 'voice_type'),
  1564. 'voice_name' => getProp($item, 'voice_name'),
  1565. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1566. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1567. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1568. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1569. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  1570. ];
  1571. }
  1572. return $result;
  1573. }
  1574. // 新增合成任务
  1575. public function addGenerateTask($data) {
  1576. $bid = getProp($data, 'bid');
  1577. $cid = getProp($data, 'cid');
  1578. $version_id = getProp($data, 'version_id');
  1579. $generate_json = getProp($data, 'generate_json');
  1580. // 获取已生成的音频
  1581. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  1582. $paragraph_list = [];
  1583. foreach($paragraph_audios as $item) {
  1584. $paragraph_list[getProp($item, 'sequence')] = [
  1585. 'role' => getProp($item, 'role'),
  1586. 'gender' => getProp($item, 'gender'),
  1587. 'text' => trim(getProp($item, 'text')),
  1588. 'emotion' => getProp($item, 'emotion'),
  1589. 'emotion_type' => getProp($item, 'emotion_type'),
  1590. 'voice_type' => getProp($item, 'voice_type'),
  1591. 'voice_name' => getProp($item, 'voice_name'),
  1592. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1593. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1594. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1595. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1596. ];
  1597. }
  1598. // 更新角色-音色信息
  1599. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  1600. $existed_role_info = json_decode($existed_role_info, true);
  1601. if (!$existed_role_info) $existed_role_info = [];
  1602. // 获取情感信息
  1603. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1604. $emotion_list = array_flip($emotion_list);
  1605. // 获取音色对应情感组
  1606. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  1607. $timbre_emotion_list = [];
  1608. foreach($timbre_emotions as $item) {
  1609. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  1610. }
  1611. // 构造生成音频的json
  1612. $words = json_decode($generate_json, true);
  1613. // 最终合成前的参数组
  1614. $mp_chapter_paragraph_audios = [];
  1615. $sequence = 1;
  1616. $complete_paragraph_sequences = [];
  1617. foreach($words as &$word) {
  1618. 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:参数格式有误');
  1619. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  1620. $role = getProp($word, 'role');
  1621. $word['gender'] = (int)$word['gender'];
  1622. // 判断音色对应情感是否支持,不支持则调整为中性
  1623. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  1624. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  1625. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  1626. if (isset($emotion_list[getProp($word, 'emotion')])) {
  1627. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  1628. }else {
  1629. $word['emotion'] = '中性';
  1630. $word['emotion_type'] = 'neutral';
  1631. }
  1632. $existed_role_info[$role] = [
  1633. 'timbre_type' => $word['voice_type'],
  1634. 'timbre_name' => $word['voice_name'],
  1635. 'emotion' => $word['emotion'],
  1636. 'emotion_type' => $word['emotion_type'],
  1637. 'speed_ratio' => $word['speed_ratio'],
  1638. 'loudness_ratio'=> $word['loudness_ratio'],
  1639. 'emotion_scale' => $word['emotion_scale'],
  1640. 'pitch' => $word['pitch']
  1641. ];
  1642. $word['paragraph_audio_url'] = '';
  1643. // 判断生成参数是否相同,相同则直接使用已生成的音频
  1644. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  1645. // 如果音频存在并且参数都未改变则使用已生成的音频
  1646. if (getProp($paragraph, 'paragraph_audio_url')) {
  1647. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  1648. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  1649. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  1650. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  1651. // {
  1652. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1653. // }
  1654. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1655. }
  1656. $tmp = $word;
  1657. // 组装章节分句音频数据
  1658. // $tmp['sequence'] = getProp($word, 'sequence');
  1659. // $tmp['text'] = getProp($word, 'text');
  1660. // $tmp['emotion'] = getProp($word, 'emotion');
  1661. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  1662. // $tmp['voice_name'] = getProp($word, 'voice_name');
  1663. // $tmp['voice_type'] = getProp($word, 'voice_type');
  1664. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  1665. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  1666. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  1667. $tmp['bid'] = $bid;
  1668. $tmp['version_id'] = $version_id;
  1669. $tmp['cid'] = $cid;
  1670. $tmp['sequence'] = $sequence;
  1671. $tmp['created_at'] = date('Y-m-d H:i:s');
  1672. $tmp['updated_at'] = date('Y-m-d H:i:s');
  1673. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  1674. $mp_chapter_paragraph_audios[] = $tmp;
  1675. $complete_paragraph_sequences[] = $sequence;
  1676. $sequence++;
  1677. }
  1678. $generate_json = json_encode($words, 256);
  1679. // 判断是否有未生成字幕的段落
  1680. $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();
  1681. if ($no_subtitle_sequences) {
  1682. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  1683. }
  1684. try {
  1685. DB::beginTransaction();
  1686. $role_info = json_encode($existed_role_info, 256);
  1687. $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')]);
  1688. if (!$boolen) {
  1689. DB::rollBack();
  1690. Utils::throwError('20003:更新角色信息失败');
  1691. }
  1692. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  1693. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  1694. if (!$count) {
  1695. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1696. }else {
  1697. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1698. }
  1699. $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')]);
  1700. if (!$boolen1) {
  1701. DB::rollBack();
  1702. Utils::throwError('20003:更新生成数据失败');
  1703. }
  1704. $id = DB::table('mp_audio_tasks')->insertGetId([
  1705. 'audio_id' => getProp($chapter_audio, 'id'),
  1706. 'generate_status' => '执行中',
  1707. 'generate_json' => $generate_json,
  1708. 'bid' => $bid,
  1709. 'book_name' => getProp($chapter_audio, 'book_name'),
  1710. 'version_id' => $version_id,
  1711. 'version_name' => getProp($chapter_audio, 'version_name'),
  1712. 'cid' => $cid,
  1713. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1714. 'task_name' => $task_name,
  1715. 'created_at' => date('Y-m-d H:i:s'),
  1716. 'updated_at' => date('Y-m-d H:i:s')
  1717. ]);
  1718. if (!$id) {
  1719. DB::rollBack();
  1720. Utils::throwError('20003:创建任务失败');
  1721. }
  1722. // 删除不在段落序号范围内的其他数据
  1723. if ($complete_paragraph_sequences) {
  1724. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  1725. }
  1726. // // 删除章节分句音频数据并重新插入
  1727. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  1728. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  1729. // if (!$boolen3) {
  1730. // DB::rollBack();
  1731. // Utils::throwError('20003:更新章节分句音频失败');
  1732. // }
  1733. } catch (\Exception $e) {
  1734. DB::rollBack();
  1735. Utils::throwError('20003:'.$e->getMessage());
  1736. }
  1737. DB::commit();
  1738. // 通知火山生成音频
  1739. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1740. // 根据ID通过API通知合成音频
  1741. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  1742. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  1743. $response = $result->getBody()->getContents();
  1744. $response_arr = json_decode($response, true);
  1745. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1746. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1747. Log::info('通知火山生成音频失败: '.$error_msg);
  1748. Utils::throwError('20003:通知火山生成音频失败');
  1749. }
  1750. return true;
  1751. }
  1752. public function timbreList($data) {
  1753. $gender = getProp($data, 'gender');
  1754. $timbre_name = getProp($data, 'voice_name');
  1755. $category_id = getProp($data, 'category_id');
  1756. $age_stage = getProp($data, 'age_stage');
  1757. $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');
  1758. if ($gender) {
  1759. $query->where('gender', $gender);
  1760. }
  1761. if ($timbre_name) {
  1762. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  1763. }
  1764. if ($category_id) {
  1765. $query->where(function ($query) use ($category_id) {
  1766. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  1767. });
  1768. }
  1769. if ($age_stage) {
  1770. $query->where('age_stage', $age_stage);
  1771. }
  1772. $list = $query->get()->map(function ($value) {
  1773. $value = (array)$value;
  1774. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  1775. return $value;
  1776. })->toArray();
  1777. return $list;
  1778. }
  1779. // 生成火山临时token
  1780. public function setStsToken() {
  1781. // ************* 配置参数 *************
  1782. $method = 'GET';
  1783. $service = 'sts';
  1784. $host = 'open.volcengineapi.com';
  1785. $region = env('VOLC_REGION');
  1786. $endpoint = 'https://open.volcengineapi.com';
  1787. // $endpoint = 'https://tos-cn-beijing.volces.com';
  1788. $access_key = env('VOLC_AK');
  1789. $secret_key = env('VOLC_SK');
  1790. // 获取缓存中的token,如果没有则请求接口
  1791. $token = Redis::get('volc_sts_token');
  1792. if (!$token) {
  1793. // 查询参数
  1794. $query_parameters = [
  1795. 'Action' => 'AssumeRole',
  1796. 'RoleSessionName' => 'user@zw',
  1797. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  1798. 'Version' => '2018-01-01'
  1799. ];
  1800. // 生成URL编码的查询字符串
  1801. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  1802. // 获取签名头信息
  1803. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  1804. // 构建完整URL
  1805. $request_url = $endpoint . '?' . $request_parameters;
  1806. $client = new Client(['verify' => false]);
  1807. $response = $client->get($request_url, ['headers' => $headers]);
  1808. $response_arr = json_decode($response->getBody()->getContents(), true);
  1809. $result = [
  1810. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  1811. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  1812. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  1813. 'Region' => env('VOLC_REGION'),
  1814. 'Endpoint' => env('VOLC_END_POINT'),
  1815. 'Bucket' => env('VOLC_BUCKET'),
  1816. ];
  1817. // 缓存token
  1818. Redis::setex('volc_sts_token', 3000, json_encode($result));
  1819. return $result;
  1820. } else {
  1821. return json_decode($token, true);
  1822. }
  1823. // $response = $response['Response'];
  1824. // $access_key = $response['Credentials']['AccessKeyId'];
  1825. // $secret_key = $response['Credentials']['AccessKeySecret'];
  1826. // $security_token = $response['Credentials']['SecurityToken'];
  1827. // $expiration = $response['Credentials']['Expiration'];
  1828. // dd($response_arr);
  1829. }
  1830. public function emotionGroups($data) {
  1831. $id = getProp($data, 'group_id');
  1832. $group_name = getProp($data, 'group_name');
  1833. $voice_type = getProp($data, 'voice_type');
  1834. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  1835. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  1836. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  1837. if ($group_name) {
  1838. $query->where('group_name', 'like', "%{$group_name}%");
  1839. }
  1840. if ($id) {
  1841. $query->where('id', $id);
  1842. }
  1843. if ($voice_type) {
  1844. $query->where('voice_type', $voice_type);
  1845. }
  1846. return $query->orderBy('id')->get()->map(function ($value) {
  1847. return (array)$value;
  1848. })->toArray();
  1849. }
  1850. private function sign($key, $msg) {
  1851. return hash_hmac('sha256', $msg, $key, true);
  1852. }
  1853. // 生成签名密钥
  1854. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  1855. $kDate = $this->sign($key, $dateStamp);
  1856. $kRegion = $this->sign($kDate, $regionName);
  1857. $kService = $this->sign($kRegion, $serviceName);
  1858. $kSigning = $this->sign($kService, 'request');
  1859. return $kSigning;
  1860. }
  1861. // 获取签名头信息
  1862. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  1863. $contenttype = 'application/x-www-form-urlencoded';
  1864. $accept = 'application/json';
  1865. // 获取当前UTC时间
  1866. $t = new DateTime('now', new DateTimeZone('UTC'));
  1867. $xdate = $t->format('Ymd\THis\Z');
  1868. $datestamp = $t->format('Ymd');
  1869. // 1. 拼接规范请求串
  1870. $canonical_uri = '/';
  1871. $canonical_querystring = $request_parameters;
  1872. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  1873. $signed_headers = 'content-type;host;x-date';
  1874. // 空请求体的SHA256哈希
  1875. $payload_hash = hash('sha256', '');
  1876. $canonical_request = implode("\n", [
  1877. $method,
  1878. $canonical_uri,
  1879. $canonical_querystring,
  1880. $canonical_headers,
  1881. $signed_headers,
  1882. $payload_hash
  1883. ]);
  1884. // 2. 拼接待签名字符串
  1885. $algorithm = 'HMAC-SHA256';
  1886. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  1887. $hashed_canonical_request = hash('sha256', $canonical_request);
  1888. $string_to_sign = implode("\n", [
  1889. $algorithm,
  1890. $xdate,
  1891. $credential_scope,
  1892. $hashed_canonical_request
  1893. ]);
  1894. // 3. 计算签名
  1895. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  1896. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  1897. // 4. 添加签名到请求头
  1898. $authorization_header = sprintf(
  1899. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  1900. $algorithm,
  1901. $access_key,
  1902. $credential_scope,
  1903. $signed_headers,
  1904. $signature
  1905. );
  1906. return [
  1907. 'Accept' => $accept,
  1908. 'Content-Type' => $contenttype,
  1909. 'X-Date' => $xdate,
  1910. 'Authorization' => $authorization_header
  1911. ];
  1912. }
  1913. // 文字合成语音(火山引擎)
  1914. public function tts($data) {
  1915. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  1916. $headers = [
  1917. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  1918. 'Content-Type' => 'application/json; charset=UTF-8'
  1919. ];
  1920. $post_data = [
  1921. 'app' => [
  1922. 'appid' => env('VOLC_APPID'),
  1923. 'token' => env('VOLC_TOKEN'),
  1924. 'cluster' => 'volcano_tts'
  1925. ],
  1926. 'user' => [
  1927. 'uid' => 'mp_audio'
  1928. ],
  1929. // 'audio' => [
  1930. // 'voice_type' =>
  1931. // ],
  1932. ];
  1933. }
  1934. public function scriptList($data) {
  1935. $uid = Site::getUid();
  1936. $script_id = getProp($data, 'script_id');
  1937. $script_name = getProp($data, 'script_name');
  1938. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  1939. if ($script_id) {
  1940. $query->where('id', $script_id);
  1941. }
  1942. if ($script_name) {
  1943. $query->where('script_name', 'like', "%{$script_name}%");
  1944. }
  1945. return $query->orderBy('created_at', 'desc')->paginate(12);
  1946. }
  1947. public function scripts($data) {
  1948. $uid = Site::getUid();
  1949. $script_id = getProp($data, 'script_id');
  1950. $script_name = getProp($data, 'script_name');
  1951. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  1952. if ($script_id) {
  1953. $query->where('id', $script_id);
  1954. }
  1955. if ($script_name) {
  1956. $query->where('script_name', 'like', "%{$script_name}%");
  1957. }
  1958. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  1959. return (array)$value;
  1960. })->toArray();
  1961. }
  1962. public function scriptInfo($data) {
  1963. $uid = Site::getUid();
  1964. $script_id = getProp($data, 'script_id');
  1965. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  1966. // ->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();
  1967. ->selectRaw('id as script_id, script_name')->first();
  1968. if (!$script) Utils::throwError('20003:该剧本不存在!');
  1969. $script = (array)$script;
  1970. // 获取分集组信息
  1971. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  1972. ->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')
  1973. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  1974. $value = (array)$value;
  1975. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  1976. return (array)$value;
  1977. })->toArray();
  1978. $script['group'] = $groups;
  1979. return $script;
  1980. }
  1981. public function createScript($data) {
  1982. $script_name = getProp($data, 'script_name');
  1983. $uid = Site::getUid(); // 获取当前用户ID
  1984. $cpid = Site::getCpid(); // 获取当前公司组ID
  1985. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  1986. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  1987. $script_name .= '_'.date('YmdHis');
  1988. }
  1989. return DB::table('mp_scripts')->insertGetId([
  1990. 'script_name' => $script_name,
  1991. 'user_id' => $uid,
  1992. 'cpid' => $cpid,
  1993. 'created_at' => date('Y-m-d H:i:s'),
  1994. 'updated_at' => date('Y-m-d H:i:s')
  1995. ]);
  1996. }
  1997. public function editScript($data) {
  1998. $script_id = getProp($data, 'script_id');
  1999. $script_name = getProp($data, 'script_name');
  2000. $uid = Site::getUid(); // 获取当前用户ID
  2001. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  2002. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  2003. if ($id && (int)$id !== (int)$script_id) {
  2004. $script_name .= '_'.date('YmdHis');
  2005. }
  2006. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2007. 'script_name' => $script_name,
  2008. 'updated_at' => date('Y-m-d H:i:s')
  2009. ]);
  2010. }
  2011. public function delScript($data) {
  2012. $script_id = getProp($data, 'script_id');
  2013. $uid = Site::getUid(); // 获取当前用户ID
  2014. if (!$script_id) Utils::throwError('20003:请选择剧本');
  2015. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2016. 'is_deleted' => 1,
  2017. 'updated_at' => date('Y-m-d H:i:s')
  2018. ]);
  2019. }
  2020. public function createEpisode($data) {
  2021. $script_id = getProp($data, 'script_id');
  2022. $group_name = getProp($data, 'group_name');
  2023. $remark = getProp($data, 'remark');
  2024. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  2025. $uid = Site::getUid(); // 获取当前用户ID
  2026. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  2027. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  2028. $group_name .= '_'.date('YmdHis');
  2029. }
  2030. return DB::table('mp_script_episode_group')->insertGetId([
  2031. 'script_id' => $script_id,
  2032. 'group_name' => $group_name,
  2033. 'user_id' => $uid,
  2034. 'remark' => $remark,
  2035. 'created_at' => date('Y-m-d H:i:s'),
  2036. 'updated_at' => date('Y-m-d H:i:s')
  2037. ]);
  2038. }
  2039. public function editEpisode($data) {
  2040. $group_id = getProp($data, 'group_id');
  2041. $start_episode_number = getProp($data, 'start_episode_number');
  2042. $end_episode_number = getProp($data, 'end_episode_number');
  2043. $group_name = getProp($data, 'group_name');
  2044. $uid = Site::getUid(); // 获取当前用户ID
  2045. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  2046. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  2047. if ($id && (int)$id !== (int)$group_id) {
  2048. $group_name .= '_'.date('YmdHis');
  2049. }
  2050. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2051. 'group_name' => $group_name,
  2052. 'start_episode_number' => $start_episode_number,
  2053. 'end_episode_number' => $end_episode_number,
  2054. 'updated_at' => date('Y-m-d H:i:s')
  2055. ]);
  2056. }
  2057. public function delEpisode($data) {
  2058. $group_id = getProp($data, 'group_id');
  2059. $uid = Site::getUid(); // 获取当前用户ID
  2060. if (!$group_id) Utils::throwError('20003:请选择分集');
  2061. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2062. 'is_deleted' => 1,
  2063. 'updated_at' => date('Y-m-d H:i:s')
  2064. ]);
  2065. }
  2066. /**
  2067. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2068. *
  2069. * @param array $data 包含以下参数:
  2070. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2071. * - question: 用户问题(可选)
  2072. * - model: 使用的模型(r1 或 v3,默认 v3)
  2073. * @return \Generator 返回生成器,用于流式输出
  2074. */
  2075. public function generateEpisodes($data) {
  2076. $script_id = getProp($data, 'script_id');
  2077. $group_id = getProp($data, 'group_id');
  2078. // $file = getProp($data, 'file');
  2079. $file = '';
  2080. $content = getProp($data, 'content', '');
  2081. // $bid = getProp($data, 'bid', 0);
  2082. $bid = 0;
  2083. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2084. if (!$group) {
  2085. Utils::throwError('20003:剧本分集不存在');
  2086. }
  2087. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  2088. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  2089. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  2090. $prompt = getProp($data, 'prompt');
  2091. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  2092. $model = getProp($data, 'model');
  2093. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2094. Utils::throwError('20003:该模型不存在!');
  2095. }
  2096. // 检查是否存在重叠的剧集序号范围
  2097. $exists_groups = DB::table('mp_script_episode_group')
  2098. ->where('script_id', $script_id)
  2099. ->where('id', '<>', $group_id) // 排除当前组
  2100. ->where('is_deleted', 0)
  2101. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2102. // 检查新范围是否与现有范围重叠
  2103. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2104. // 新范围的开始在现有范围内
  2105. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2106. ->where('end_episode_number', '>=', $start_episode_sequence);
  2107. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2108. // 新范围的结束在现有范围内
  2109. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2110. ->where('end_episode_number', '>=', $end_episode_sequence);
  2111. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2112. // 新范围完全包含现有范围
  2113. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2114. ->where('end_episode_number', '<=', $end_episode_sequence);
  2115. });
  2116. })
  2117. ->select('start_episode_number', 'end_episode_number')
  2118. ->get();
  2119. if ($exists_groups->isNotEmpty()) {
  2120. $conflict_ranges = [];
  2121. foreach ($exists_groups as $group) {
  2122. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2123. }
  2124. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2125. }
  2126. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2127. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2128. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2129. if ($model === 'deepseek-chat') {
  2130. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2131. $model = 'deepseek-v4-flash';
  2132. $thinkingMode = 'disabled';
  2133. } elseif ($model === 'deepseek-reasoner') {
  2134. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2135. $model = 'deepseek-v4-flash';
  2136. $thinkingMode = 'enabled';
  2137. }
  2138. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2139. if (!$script) {
  2140. Utils::throwError('20003:剧本不存在');
  2141. }
  2142. $content = getProp($group, 'content');
  2143. if (!$file && !$content && !$bid) {
  2144. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2145. }
  2146. // 提取文件内容
  2147. if ($file) {
  2148. $content = $this->extractFileContent($file);
  2149. if (!$content) {
  2150. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2151. }
  2152. } elseif ($bid) {
  2153. $content = $this->getContentByBid($bid);
  2154. if (!$content) {
  2155. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2156. }
  2157. } elseif ($content) {
  2158. $content = filterContent($content);
  2159. } elseif ($prompt) {
  2160. $content = filterContent($prompt);
  2161. } else {
  2162. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2163. }
  2164. // 构建消息
  2165. $messages = [
  2166. $this->sys_message,
  2167. [
  2168. 'role' => 'user',
  2169. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2170. ]
  2171. ];
  2172. $post_data = [
  2173. 'model' => $model,
  2174. 'messages' => $messages,
  2175. // 'max_tokens' => 8192,
  2176. 'temperature' => 0.7,
  2177. 'frequency_penalty' => 0,
  2178. 'presence_penalty' => 0,
  2179. 'thinking' => ['type' => $thinkingMode],
  2180. 'response_format' => ['type' => 'text'],
  2181. 'stream' => true
  2182. ];
  2183. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2184. // 根据模型类型选择调用方法
  2185. $fullContent = '';
  2186. $fullReasoningContent = '';
  2187. $usage = [];
  2188. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2189. // DeepSeek 官方模型使用 DeepSeek API
  2190. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2191. } else if (in_array($model, $this->gpt_text_models)) {
  2192. // GPT-5.4 模型使用 TokenRouter API
  2193. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2194. } else {
  2195. // 其他模型使用火山引擎API
  2196. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2197. }
  2198. // 处理流式输出
  2199. foreach ($streamGenerator as $chunk) {
  2200. if (isset($chunk['type'])) {
  2201. if ($chunk['type'] === 'done') {
  2202. // 最终结果
  2203. $fullContent = $chunk['full_content'];
  2204. $fullReasoningContent = $chunk['full_reasoning'];
  2205. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2206. } else {
  2207. // 逐块yield数据
  2208. yield $chunk;
  2209. }
  2210. }
  2211. }
  2212. dLog('deepseek')->info('完整内容: '.$fullContent);
  2213. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2214. // 处理完整内容并返回最终结果
  2215. $script_arr = [];
  2216. if ($fullContent) {
  2217. $script_arr = extractScriptContent($fullContent);
  2218. }
  2219. logDB('deepseek', 'info', '解析内容', $script_arr);
  2220. if (!$script_arr['episodes']) {
  2221. Utils::throwError('20003:未生成剧本相关信息');
  2222. // yield [
  2223. // 'type' => 'done',
  2224. // 'script' => $script_arr,
  2225. // 'msg' => '未生成剧本相关信息',
  2226. // 'answer' => $fullContent,
  2227. // 'reasoning' => $fullReasoningContent,
  2228. // 'usage' => $usage
  2229. // ];
  2230. // return ;
  2231. }
  2232. try {
  2233. DB::beginTransaction();
  2234. // // 返回前保存剧本内容
  2235. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2236. // 'content' => $content,
  2237. // 'updated_at' => date('Y-m-d H:i:s')
  2238. // ]);
  2239. // if (!$boolen) {
  2240. // Utils::throwError('20003:保存剧本内容失败');
  2241. // }
  2242. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2243. // 'start_episode_number' => $start_episode_sequence,
  2244. // 'end_episode_number' => $end_episode_sequence,
  2245. // 'updated_at' => date('Y-m-d H:i:s')
  2246. // ]);
  2247. // if (!$boolen1) {
  2248. // Utils::throwError('20003:保存分集失败');
  2249. // }
  2250. $episode_content = '';
  2251. $episodes = [];
  2252. foreach ($script_arr['episodes'] as $item) {
  2253. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  2254. // $episodes[] = [
  2255. // 'script_id' => $script_id,
  2256. // 'episode_number' => $item['episode_number'],
  2257. // 'episode_name' => $item['episode_name'],
  2258. // 'episode_content' => $item['episode_content'],
  2259. // 'created_at' => date('Y-m-d H:i:s'),
  2260. // 'updated_at' => date('Y-m-d H:i:s'),
  2261. // ];
  2262. }
  2263. if ($episode_content) {
  2264. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2265. 'episode_content' => $episode_content,
  2266. 'updated_at' => date('Y-m-d H:i:s')
  2267. ]);
  2268. if (!$boolen2) {
  2269. Utils::throwError('20003:保存分集内容失败');
  2270. }
  2271. }else {
  2272. Utils::throwError('20003:分集剧本解析失败');
  2273. }
  2274. }catch (\Exception $e) {
  2275. DB::rollBack();
  2276. Utils::throwError('20003:'.$e->getMessage());
  2277. }
  2278. DB::commit();
  2279. yield [
  2280. 'type' => 'done',
  2281. 'script' => $script_arr,
  2282. 'episode_content' => $episode_content,
  2283. 'answer' => $fullContent,
  2284. 'reasoning' => $fullReasoningContent,
  2285. 'usage' => $usage
  2286. ];
  2287. }
  2288. public function chatWithFileStream($data) {
  2289. $script_id = getProp($data, 'script_id');
  2290. $group_id = getProp($data, 'group_id');
  2291. $file = getProp($data, 'file');
  2292. $content = getProp($data, 'content', '');
  2293. $bid = getProp($data, 'bid', 0);
  2294. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2295. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2296. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  2297. $prompt = getProp($data, 'prompt');
  2298. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2299. if (!empty($prompt)) {
  2300. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2301. }
  2302. $question = getProp($data, 'question', $baseQuestion);
  2303. $model = getProp($data, 'model');
  2304. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2305. Utils::throwError('20003:该模型不存在!');
  2306. }
  2307. // 检查是否存在重叠的剧集序号范围
  2308. $exists_groups = DB::table('mp_script_episode_group')
  2309. ->where('script_id', $script_id)
  2310. ->where('id', '<>', $group_id)
  2311. ->where('is_deleted', 0)
  2312. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2313. // 检查新范围是否与现有范围重叠
  2314. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2315. // 新范围的开始在现有范围内
  2316. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2317. ->where('end_episode_number', '>=', $start_episode_sequence);
  2318. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2319. // 新范围的结束在现有范围内
  2320. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2321. ->where('end_episode_number', '>=', $end_episode_sequence);
  2322. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2323. // 新范围完全包含现有范围
  2324. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2325. ->where('end_episode_number', '<=', $end_episode_sequence);
  2326. });
  2327. })
  2328. ->select('start_episode_number', 'end_episode_number')
  2329. ->get();
  2330. if ($exists_groups->isNotEmpty()) {
  2331. $conflict_ranges = [];
  2332. foreach ($exists_groups as $group) {
  2333. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2334. }
  2335. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2336. }
  2337. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2338. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2339. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2340. if ($model === 'deepseek-chat') {
  2341. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2342. $model = 'deepseek-v4-flash';
  2343. $thinkingMode = 'disabled';
  2344. } elseif ($model === 'deepseek-reasoner') {
  2345. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2346. $model = 'deepseek-v4-flash';
  2347. $thinkingMode = 'enabled';
  2348. }
  2349. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2350. if (!$script) {
  2351. Utils::throwError('20003:剧本不存在');
  2352. }
  2353. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2354. if (!$group) {
  2355. Utils::throwError('20003:剧本分集不存在');
  2356. }
  2357. if (!$file && !$content && !$bid) {
  2358. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2359. }
  2360. // 提取文件内容
  2361. if ($file) {
  2362. $content = $this->extractFileContent($file);
  2363. if (!$content) {
  2364. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2365. }
  2366. } elseif ($bid) {
  2367. $content = $this->getContentByBid($bid);
  2368. if (!$content) {
  2369. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2370. }
  2371. } elseif ($content) {
  2372. $content = filterContent($content);
  2373. } elseif ($prompt) {
  2374. $content = filterContent($prompt);
  2375. } else {
  2376. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2377. }
  2378. // 构建消息
  2379. $messages = [
  2380. [
  2381. 'role' => 'system',
  2382. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  2383. 强制要求:\n
  2384. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2385. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  2386. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  2387. 普通要求:\n
  2388. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  2389. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  2390. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  2391. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  2392. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  2393. 示例如下:\n
  2394. ###剧本名:西昆仑
  2395. ###故事梗概
  2396. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2397. ###剧本亮点
  2398. 亮点1:绝境奇药,生死一线
  2399. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2400. 亮点2:结拜兄妹,化解尴尬
  2401. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2402. 亮点3:纤发夺命,情愫暗涌
  2403. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2404. ###人物关系
  2405. 阿雪与梁萧之间存在兄妹之情。
  2406. ###核心矛盾
  2407. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2408. ###主体列表
  2409. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2410. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2411. 阴阳球:天地异宝,能化生精气,救人于危难。
  2412. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2413. ###美术风格
  2414. 基础画风风格词:厚涂古风
  2415. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2416. ###场景列表
  2417. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  2418. [
  2419. 'role' => 'user',
  2420. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2421. ]
  2422. ];
  2423. $post_data = [
  2424. 'model' => $model,
  2425. 'messages' => $messages,
  2426. // 'max_tokens' => 8192,
  2427. 'temperature' => 0.7,
  2428. 'frequency_penalty' => 0,
  2429. 'presence_penalty' => 0,
  2430. 'thinking' => ['type' => $thinkingMode],
  2431. 'response_format' => ['type' => 'text'],
  2432. 'stream' => true
  2433. ];
  2434. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2435. // 根据模型类型选择调用方法
  2436. $fullContent = '';
  2437. $fullReasoningContent = '';
  2438. $usage = [];
  2439. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2440. // DeepSeek 官方模型使用 DeepSeek API
  2441. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2442. } else if (in_array($model, $this->gpt_text_models)) {
  2443. // GPT-5.4 模型使用 TokenRouter API
  2444. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2445. } else {
  2446. // 其他模型使用火山引擎API
  2447. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2448. }
  2449. // 处理流式输出
  2450. foreach ($streamGenerator as $chunk) {
  2451. if (isset($chunk['type'])) {
  2452. if ($chunk['type'] === 'done') {
  2453. // 最终结果
  2454. $fullContent = $chunk['full_content'];
  2455. $fullReasoningContent = $chunk['full_reasoning'];
  2456. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2457. } else {
  2458. // 逐块yield数据
  2459. yield $chunk;
  2460. }
  2461. }
  2462. }
  2463. dLog('deepseek')->info('完整内容: '.$fullContent);
  2464. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2465. // 处理完整内容并返回最终结果
  2466. $script_arr = [];
  2467. if ($fullContent) {
  2468. $script_arr = extractScriptContent($fullContent);
  2469. }
  2470. logDB('deepseek', 'info', '解析内容', $script_arr);
  2471. if (!$script_arr['roles']) {
  2472. Utils::throwError('20003:未生成剧本相关信息');
  2473. // yield [
  2474. // 'type' => 'done',
  2475. // 'script' => $script_arr,
  2476. // 'msg' => '未生成剧本相关信息',
  2477. // 'answer' => $fullContent,
  2478. // 'reasoning' => $fullReasoningContent,
  2479. // 'usage' => $usage
  2480. // ];
  2481. }
  2482. try {
  2483. DB::beginTransaction();
  2484. // // 返回前保存剧本内容
  2485. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2486. // 'content' => $content,
  2487. // 'status' => '解析完成',
  2488. // 'updated_at' => date('Y-m-d H:i:s')
  2489. // ]);
  2490. // if (!$boolen) {
  2491. // Utils::throwError('20003:保存剧本内容失败');
  2492. // }
  2493. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2494. 'start_episode_number' => $start_episode_sequence,
  2495. 'end_episode_number' => $end_episode_sequence,
  2496. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2497. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2498. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2499. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2500. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2501. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2502. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2503. 'status' => '解析完成',
  2504. 'content' => $content,
  2505. 'updated_at' => date('Y-m-d H:i:s')
  2506. ]);
  2507. if (!$boolen1) {
  2508. Utils::throwError('20003:保存分集失败');
  2509. }
  2510. // $episodes = [];
  2511. // foreach ($script_arr['episodes'] as $item) {
  2512. // $episodes[] = [
  2513. // 'script_id' => $script_id,
  2514. // 'episode_number' => $item['episode_number'],
  2515. // 'episode_name' => $item['episode_name'],
  2516. // 'episode_content' => $item['episode_content'],
  2517. // 'created_at' => date('Y-m-d H:i:s'),
  2518. // 'updated_at' => date('Y-m-d H:i:s'),
  2519. // ];
  2520. // }
  2521. // if ($episodes) {
  2522. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2523. // if (!$boolen2) {
  2524. // Utils::throwError('20003:保存分集内容失败');
  2525. // }
  2526. // }else {
  2527. // Utils::throwError('20003:分集剧本解析失败');
  2528. // }
  2529. }catch (\Exception $e) {
  2530. DB::rollBack();
  2531. Utils::throwError('20003:'.$e->getMessage());
  2532. }
  2533. DB::commit();
  2534. yield [
  2535. 'type' => 'done',
  2536. 'script' => $script_arr,
  2537. 'answer' => $fullContent,
  2538. 'reasoning' => $fullReasoningContent,
  2539. 'usage' => $usage
  2540. ];
  2541. }
  2542. /**
  2543. * 上传文件识别文字内容并与 DeepSeek 进行对话
  2544. *
  2545. * @param array $data 包含以下参数:
  2546. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2547. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  2548. * - model: 使用的模型(r1 或 v3,默认 v3)
  2549. * @return array
  2550. */
  2551. public function chatWithFile($data) {
  2552. $script_id = getProp($data, 'script_id');
  2553. $file = getProp($data, 'file');
  2554. $content = getProp($data, 'content', '');
  2555. $bid = getProp($data, 'bid', 0);
  2556. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2557. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2558. $prompt = getProp($data, 'prompt');
  2559. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2560. if (!empty($prompt)) {
  2561. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2562. }
  2563. $question = getProp($data, 'question', $baseQuestion);
  2564. // 处理文本模型
  2565. $model = getProp($data, 'model');
  2566. if (!$model) {
  2567. // 用户没有输入,使用默认值
  2568. $model = 'doubao-seed-2-0-mini-260215';
  2569. }
  2570. // 验证模型是否在可用模型表中
  2571. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2572. $model = 'doubao-seed-2-0-mini-260215';
  2573. }
  2574. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2575. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2576. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2577. if ($model === 'deepseek-chat') {
  2578. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2579. $model = 'deepseek-v4-flash';
  2580. $thinkingMode = 'disabled';
  2581. } elseif ($model === 'deepseek-reasoner') {
  2582. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2583. $model = 'deepseek-v4-flash';
  2584. $thinkingMode = 'enabled';
  2585. }
  2586. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2587. if (!$script) {
  2588. Utils::throwError('20003:剧本不存在');
  2589. }
  2590. if (!$file && !$content && !$bid) {
  2591. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2592. }
  2593. // 提取文件内容
  2594. if ($file) {
  2595. $content = $this->extractFileContent($file);
  2596. if (!$content) {
  2597. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2598. }
  2599. } elseif ($bid) {
  2600. $content = $this->getContentByBid($bid);
  2601. if (!$content) {
  2602. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2603. }
  2604. } elseif ($content) {
  2605. $content = filterContent($content);
  2606. } elseif ($prompt) {
  2607. $content = filterContent($prompt);
  2608. } else {
  2609. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2610. }
  2611. // 构建消息
  2612. $messages = [
  2613. $this->sys_message,
  2614. [
  2615. 'role' => 'user',
  2616. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2617. ]
  2618. ];
  2619. $post_data = [
  2620. 'model' => $model,
  2621. 'messages' => $messages,
  2622. // 'max_tokens' => 8192,
  2623. 'temperature' => 0.7,
  2624. 'frequency_penalty' => 0,
  2625. 'presence_penalty' => 0,
  2626. 'thinking' => ['type' => $thinkingMode],
  2627. 'response_format' => ['type' => 'text'],
  2628. 'stream' => false
  2629. ];
  2630. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2631. // 根据模型类型选择调用方法
  2632. $fullContent = '';
  2633. $usage = [];
  2634. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2635. // DeepSeek 官方模型使用 DeepSeek API
  2636. $chatResult = $this->chatOnly($post_data);
  2637. } else if (in_array($model, $this->gpt_text_models)) {
  2638. // GPT-5.4 模型使用 TokenRouter API
  2639. $chatResult = $this->gpt54ChatOnly($post_data);
  2640. } else {
  2641. // 其他模型使用火山引擎API
  2642. $chatResult = $this->volcEngineChatCompletion($post_data);
  2643. }
  2644. if (is_array($chatResult)) {
  2645. $fullContent = $chatResult['fullContent'];
  2646. $usage = $chatResult['usage'];
  2647. }
  2648. $script_arr = [];
  2649. // 处理结果
  2650. if ($fullContent) {
  2651. $script_arr = extractScriptContent($fullContent);
  2652. }
  2653. // 返回前保存剧本内容
  2654. DB::table('mp_scripts')->where('id', $script_id)->update([
  2655. 'content' => $content,
  2656. 'updated_at' => date('Y-m-d H:i:s')
  2657. ]);
  2658. return [
  2659. 'script' => $script_arr,
  2660. 'answer' => $fullContent,
  2661. 'usage' => $usage
  2662. ];
  2663. }
  2664. public function getEpisodeContent($data) {
  2665. $group_id = getProp($data, 'group_id');
  2666. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  2667. }
  2668. public function saveEpisodeContent($data) {
  2669. $script_id = getProp($data, 'script_id');
  2670. $group_id = getProp($data, 'group_id');
  2671. $start_episode_sequence = getProp($data, 'start_episode_number');
  2672. $end_episode_sequence = getProp($data, 'end_episode_number');
  2673. // 检查是否存在重叠的剧集序号范围
  2674. $exists_groups = DB::table('mp_script_episode_group')
  2675. ->where('script_id', $script_id)
  2676. ->where('id', '<>', $group_id) // 排除当前组
  2677. ->where('is_deleted', 0)
  2678. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2679. // 检查新范围是否与现有范围重叠
  2680. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2681. // 新范围的开始在现有范围内
  2682. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2683. ->where('end_episode_number', '>=', $start_episode_sequence);
  2684. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2685. // 新范围的结束在现有范围内
  2686. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2687. ->where('end_episode_number', '>=', $end_episode_sequence);
  2688. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2689. // 新范围完全包含现有范围
  2690. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2691. ->where('end_episode_number', '<=', $end_episode_sequence);
  2692. });
  2693. })
  2694. ->select('start_episode_number', 'end_episode_number')
  2695. ->get();
  2696. if ($exists_groups->isNotEmpty()) {
  2697. $conflict_ranges = [];
  2698. foreach ($exists_groups as $group) {
  2699. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2700. }
  2701. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2702. }
  2703. $episode_content = getProp($data, 'episode_content');
  2704. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  2705. 'content' => $episode_content,
  2706. 'start_episode_number' => $start_episode_sequence,
  2707. 'end_episode_number' => $end_episode_sequence,
  2708. 'updated_at' => date('Y-m-d H:i:s')
  2709. ]);
  2710. $script_arr =getProp($data, 'script', []);
  2711. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  2712. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2713. $script_id = getProp($data, 'script_id');
  2714. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  2715. try {
  2716. DB::beginTransaction();
  2717. $update_data = [
  2718. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2719. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2720. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2721. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2722. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2723. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2724. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2725. 'status' => 3,
  2726. 'start_episode_sequence' => $start_episode_sequence,
  2727. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  2728. 'episode_num' => count($script_arr['episodes']),
  2729. 'updated_at' => date('Y-m-d H:i:s')
  2730. ];
  2731. // 保存剧本内容
  2732. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  2733. if (!$boolen) {
  2734. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  2735. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  2736. Utils::throwError('20003:剧本内容保存失败');
  2737. }
  2738. // 保存分集内容
  2739. // 删除历史分集内容
  2740. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  2741. $episodes = [];
  2742. $sequence = 1;
  2743. foreach ($script_arr['episodes'] as $episode) {
  2744. $segment_number = 1;
  2745. foreach($episode['segments'] as $segment) {
  2746. $episodes[] = [
  2747. 'script_id' => $script_id,
  2748. 'episode_number' => $episode['episode_number'],
  2749. 'title' => $episode['title'],
  2750. // 'content' => $episode['content'],
  2751. 'content' => '',
  2752. 'segment_number' => $segment_number,
  2753. 'segment_content' => $segment['segment_content'],
  2754. 'sequence' => $sequence,
  2755. 'created_at' => date('Y-m-d H:i:s'),
  2756. 'updated_at' => date('Y-m-d H:i:s')
  2757. ];
  2758. $sequence++;
  2759. $segment_number++;
  2760. }
  2761. }
  2762. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2763. if (!$boolen2) {
  2764. dLog('deepseek')->info('分集内容保存失败', $episodes);
  2765. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  2766. Utils::throwError('20003:分集内容保存失败');
  2767. }
  2768. } catch (\Exception $e) {
  2769. DB::rollBack();
  2770. Utils::throwError('20003:'.$e->getMessage());
  2771. }
  2772. DB::commit();
  2773. return true;
  2774. }
  2775. public function getBookContent($data) {
  2776. $bid = getProp($data, 'bid');
  2777. $start_sequence = getProp($data, 'start_sequence');
  2778. $end_sequence = getProp($data, 'end_sequence');
  2779. $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])
  2780. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  2781. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  2782. return $return_content;
  2783. }
  2784. public function exportScript($data) {
  2785. $filename = getProp($data, 'filename');
  2786. $script_id = getProp($data, 'script_id');
  2787. $group_id = getProp($data, 'group_id');
  2788. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  2789. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  2790. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2791. $script = (array)$script;
  2792. // 获取分集组信息
  2793. if ($group_id) {
  2794. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2795. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2796. ->get()->map(function($value) {
  2797. return (array)$value;
  2798. })->toArray();
  2799. }else {
  2800. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2801. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2802. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  2803. return (array)$value;
  2804. })->toArray();
  2805. }
  2806. if (!$groups) Utils::throwError('20003:分集不存在');
  2807. $script['group'] = $groups;
  2808. $export_type = getProp($data, 'export_type', 'txt');
  2809. // 生成文件名
  2810. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  2811. // 根据导出类型生成不同格式的文件
  2812. switch ($export_type) {
  2813. case 'txt':
  2814. return $this->exportScriptAsTxt($script, $filename);
  2815. case 'pdf':
  2816. return $this->exportScriptAsPdf($script, $filename);
  2817. default:
  2818. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  2819. }
  2820. }
  2821. /**
  2822. * 导出剧本为TXT格式
  2823. */
  2824. private function exportScriptAsTxt($script, $filename) {
  2825. // 构建TXT内容
  2826. $content = $this->buildScriptContent($script);
  2827. // 设置响应头,直接下载
  2828. header('Content-Type: text/plain; charset=utf-8');
  2829. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  2830. header('Content-Length: ' . strlen($content));
  2831. // 输出内容并结束
  2832. echo $content;
  2833. exit();
  2834. }
  2835. /**
  2836. * 导出剧本为PDF格式
  2837. */
  2838. private function exportScriptAsPdf($script, $filename) {
  2839. // 使用HTML转PDF的方式来更好地支持中文
  2840. $htmlContent = $this->buildScriptHtmlForPdf($script);
  2841. // 创建PDF实例
  2842. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  2843. // 设置文档信息
  2844. $pdf->SetCreator('剧本导出系统');
  2845. $pdf->SetAuthor('系统');
  2846. $pdf->SetTitle($script['script_name']);
  2847. $pdf->SetSubject('剧本导出');
  2848. // 设置边距
  2849. $pdf->SetMargins(15, 15, 15);
  2850. $pdf->SetAutoPageBreak(TRUE, 15);
  2851. // 添加页面
  2852. $pdf->AddPage();
  2853. // 注册并使用 simsun.ttf 字体
  2854. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  2855. // 使用HTML内容生成PDF
  2856. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  2857. // 直接输出PDF文件供下载
  2858. header('Content-Type: application/pdf');
  2859. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  2860. // 直接输出PDF内容
  2861. $pdf->Output($filename . '.pdf', 'D');
  2862. exit();
  2863. }
  2864. /**
  2865. * 构建用于PDF的HTML内容
  2866. */
  2867. private function buildScriptHtmlForPdf($script) {
  2868. $html = '<style>
  2869. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  2870. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  2871. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  2872. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  2873. .info { margin-bottom: 8px; }
  2874. .group { margin-bottom: 30px; page-break-inside: avoid; }
  2875. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  2876. .segment { margin-bottom: 10px; margin-left: 20px; }
  2877. .episode-content { white-space: pre-wrap; }
  2878. </style>';
  2879. // 标题
  2880. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  2881. // 处理分组数据
  2882. if (!empty($script['group']) && is_array($script['group'])) {
  2883. $groups = (array)$script['group'];
  2884. foreach ($groups as $group) {
  2885. $html .= '<div class="group">';
  2886. // 分组标题
  2887. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  2888. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  2889. // 故事梗概
  2890. if (!empty($group['intro'])) {
  2891. $html .= '<h3>故事梗概</h3>';
  2892. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  2893. }
  2894. // 剧本亮点
  2895. if (!empty($group['highlights'])) {
  2896. $html .= '<h3>剧本亮点</h3>';
  2897. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  2898. }
  2899. // 人物关系
  2900. if (!empty($group['role_relationship'])) {
  2901. $html .= '<h3>人物关系</h3>';
  2902. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  2903. }
  2904. // 核心矛盾
  2905. if (!empty($group['core_contradiction'])) {
  2906. $html .= '<h3>核心矛盾</h3>';
  2907. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  2908. }
  2909. // 主体列表
  2910. if (!empty($group['roles']) && is_array($group['roles'])) {
  2911. $html .= '<h3>主体列表</h3>';
  2912. $html .= '<ul>';
  2913. foreach ($group['roles'] as $role) {
  2914. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  2915. }
  2916. $html .= '</ul>';
  2917. }
  2918. // 美术风格
  2919. if (!empty($group['art_style'])) {
  2920. $html .= '<h3>美术风格</h3>';
  2921. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  2922. }
  2923. // 场景列表
  2924. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  2925. $html .= '<h3>场景列表</h3>';
  2926. $html .= '<ul>';
  2927. foreach ($group['scenes'] as $scene) {
  2928. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  2929. }
  2930. $html .= '</ul>';
  2931. }
  2932. // 分集剧本
  2933. if (!empty($group['episode_content'])) {
  2934. $html .= '<h3>分集剧本</h3>';
  2935. // 去除零宽字符和其他不可见字符
  2936. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  2937. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  2938. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  2939. }
  2940. $html .= '</div>';
  2941. }
  2942. }
  2943. return $html;
  2944. }
  2945. /**
  2946. * 构建PDF内容
  2947. */
  2948. private function buildPdfContent($pdf, $script) {
  2949. // 标题
  2950. $pdf->SetFont('dejavusans', 'B', 18);
  2951. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  2952. $pdf->Ln(5);
  2953. // 基本信息
  2954. $pdf->SetFont('dejavusans', '', 12);
  2955. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  2956. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  2957. $pdf->Ln(5);
  2958. // 剧本简介
  2959. if (!empty($script['intro'])) {
  2960. $pdf->SetFont('dejavusans', 'B', 14);
  2961. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  2962. $pdf->SetFont('dejavusans', '', 12);
  2963. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  2964. $pdf->Ln(3);
  2965. }
  2966. // 亮点
  2967. if (!empty($script['highlights'])) {
  2968. $pdf->SetFont('dejavusans', 'B', 14);
  2969. $pdf->Cell(0, 10, '亮点', 0, 1);
  2970. $pdf->SetFont('dejavusans', '', 12);
  2971. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  2972. $pdf->Ln(3);
  2973. }
  2974. // 核心矛盾
  2975. if (!empty($script['core_contradiction'])) {
  2976. $pdf->SetFont('dejavusans', 'B', 14);
  2977. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  2978. $pdf->SetFont('dejavusans', '', 12);
  2979. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  2980. $pdf->Ln(3);
  2981. }
  2982. // 艺术风格
  2983. if (!empty($script['art_style'])) {
  2984. $pdf->SetFont('dejavusans', 'B', 14);
  2985. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  2986. $pdf->SetFont('dejavusans', '', 12);
  2987. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  2988. $pdf->Ln(3);
  2989. }
  2990. // 备注
  2991. if (!empty($script['remark'])) {
  2992. $pdf->SetFont('dejavusans', 'B', 14);
  2993. $pdf->Cell(0, 10, '备注', 0, 1);
  2994. $pdf->SetFont('dejavusans', '', 12);
  2995. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  2996. $pdf->Ln(3);
  2997. }
  2998. // 角色列表
  2999. if (!empty($script['roles']) && is_array($script['roles'])) {
  3000. $pdf->SetFont('dejavusans', 'B', 14);
  3001. $pdf->Cell(0, 10, '角色列表', 0, 1);
  3002. $pdf->SetFont('dejavusans', '', 12);
  3003. foreach ($script['roles'] as $index => $role) {
  3004. if (is_array($role) || is_object($role)) {
  3005. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  3006. } else {
  3007. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  3008. }
  3009. }
  3010. $pdf->Ln(3);
  3011. }
  3012. // 角色关系
  3013. if (!empty($script['role_relationship'])) {
  3014. $pdf->SetFont('dejavusans', 'B', 14);
  3015. $pdf->Cell(0, 10, '角色关系', 0, 1);
  3016. $pdf->SetFont('dejavusans', '', 12);
  3017. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  3018. $pdf->Ln(3);
  3019. }
  3020. // 场景列表
  3021. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  3022. $pdf->SetFont('dejavusans', 'B', 14);
  3023. $pdf->Cell(0, 10, '场景列表', 0, 1);
  3024. $pdf->SetFont('dejavusans', '', 12);
  3025. foreach ($script['scenes'] as $index => $scene) {
  3026. if (is_array($scene) || is_object($scene)) {
  3027. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  3028. } else {
  3029. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  3030. }
  3031. }
  3032. $pdf->Ln(5);
  3033. }
  3034. // 分集内容
  3035. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  3036. $pdf->SetFont('dejavusans', 'B', 16);
  3037. $pdf->Cell(0, 12, '分集内容', 0, 1);
  3038. $pdf->Ln(3);
  3039. foreach ($script['episodes'] as $episode) {
  3040. // 检查是否需要新页面
  3041. if ($pdf->GetY() > 250) {
  3042. $pdf->AddPage();
  3043. }
  3044. $pdf->SetFont('dejavusans', 'B', 14);
  3045. $episodeTitle = '第' . $episode['episode_number'] . '集';
  3046. if (!empty($episode['title'])) {
  3047. $episodeTitle .= ':' . $episode['title'];
  3048. }
  3049. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  3050. // 处理分段内容
  3051. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  3052. $pdf->SetFont('dejavusans', '', 12);
  3053. foreach ($episode['segments'] as $segment) {
  3054. if (!empty($segment['segment_content'])) {
  3055. // 如果有分段编号,显示分段标题
  3056. if (!empty($segment['segment_number'])) {
  3057. $pdf->SetFont('dejavusans', 'B', 12);
  3058. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  3059. $pdf->SetFont('dejavusans', '', 12);
  3060. }
  3061. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  3062. $pdf->Ln(2);
  3063. }
  3064. }
  3065. }
  3066. $pdf->Ln(5);
  3067. }
  3068. }
  3069. }
  3070. /**
  3071. * 构建剧本文本内容
  3072. */
  3073. private function buildScriptContent($script) {
  3074. $content = '';
  3075. $groups = $script['group'];
  3076. $groups = (array)$groups;
  3077. foreach ($groups as $group) {
  3078. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  3079. // 剧本基本信息
  3080. if (!empty($group['intro'])) {
  3081. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  3082. }
  3083. if (!empty($group['highlights'])) {
  3084. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  3085. }
  3086. if (!empty($group['role_relationship'])) {
  3087. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  3088. }
  3089. if (!empty($group['core_contradiction'])) {
  3090. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  3091. }
  3092. if (!empty($group['roles']) && is_array($group['roles'])) {
  3093. $content .= "###主体列表\n";
  3094. foreach ($group['roles'] as $role) {
  3095. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  3096. }
  3097. $content .= "\n\n";
  3098. }
  3099. if (!empty($group['art_style'])) {
  3100. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  3101. }
  3102. // 场景信息
  3103. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3104. $content .= "###场景列表\n";
  3105. foreach ($group['scenes'] as $scene) {
  3106. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  3107. }
  3108. $content .= "\n\n";
  3109. }
  3110. // 分集内容
  3111. if (!empty($group['episode_content'])) {
  3112. $content .= "###分集剧本\n";
  3113. $content .= $group['episode_content'];
  3114. // foreach ($script['episodes'] as $episode) {
  3115. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  3116. // // if (!empty($episode['episode_name'])) {
  3117. // // $content .= ":" . $episode['episode_name'];
  3118. // // }
  3119. // // $content .= "\n";
  3120. // $content .= $episode['episode_content'] . "\n\n";
  3121. // }
  3122. }
  3123. }
  3124. return $content;
  3125. }
  3126. /**
  3127. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3128. *
  3129. * @param array $data 包含以下参数:
  3130. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3131. * - question: 用户问题(可选)
  3132. * - model: 使用的模型(r1 或 v3,默认 v3)
  3133. * @return \Generator 返回生成器,用于流式输出
  3134. */
  3135. public function addChat($data) {
  3136. $uid = Site::getUid();
  3137. $anime_id = getProp($data, 'anime_id');
  3138. if (!$anime_id) Utils::throwError('20003:请选择对话');
  3139. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3140. if (!$anime) Utils::throwError('20003:对话不存在');
  3141. $file = getProp($data, 'file');
  3142. $content = getProp($data, 'content', '');
  3143. $bid = getProp($data, 'bid', 0);
  3144. $script_id = getProp($data, 'script_id', 0);
  3145. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  3146. $prompt = getProp($data, 'prompt');
  3147. $user_anime_name = getProp($anime, 'anime_name');
  3148. // 处理文本模型
  3149. $model = getProp($data, 'model');
  3150. if (!$model) {
  3151. // 用户没有输入,从anime表获取
  3152. $model = getProp($anime, 'model');
  3153. if (!$model) {
  3154. // anime表也没有,使用默认值
  3155. $model = 'doubao-seed-2-0-mini-260215';
  3156. }
  3157. }
  3158. // 验证模型是否在可用模型表中
  3159. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3160. $model = 'doubao-seed-2-0-mini-260215';
  3161. }
  3162. $is_multi = getProp($anime, 'is_multi');
  3163. $is_single = (int)$is_multi !== 1;
  3164. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3165. if ($prompt) {
  3166. $question .= "本次修改要求如下:\n{$prompt}";
  3167. }
  3168. // if (!$file && !$content && !$bid) {
  3169. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3170. // }
  3171. // 提取文件内容
  3172. if ($file) {
  3173. $content = $this->extractFileContent($file);
  3174. if (!$content) {
  3175. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3176. }
  3177. } elseif ($script_id) {
  3178. $content = $this->getContentByScriptId($script_id);
  3179. if (!$content) {
  3180. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3181. }
  3182. } elseif ($bid) {
  3183. $content = $this->getContentByBid($bid);
  3184. if (!$content) {
  3185. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3186. }
  3187. } elseif ($content) {
  3188. $content = filterContent($content);
  3189. } else {
  3190. $content = getProp($anime, 'content');
  3191. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3192. $need_generate_content = true;
  3193. }
  3194. }
  3195. // 美术风格
  3196. $input_art_style = getProp($data, 'art_style');
  3197. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3198. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3199. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3200. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3201. 中年女:邻居阿姨
  3202. 老年男:幽默大爷
  3203. 老年女:婆婆
  3204. 萌娃:奶气萌娃";
  3205. // 判断是否需要生成原文内容
  3206. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3207. // 如果需要生成原文内容,添加额外的要求
  3208. $content_generation_requirement = $need_generate_content
  3209. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3210. : "";
  3211. // 美术风格
  3212. if (!$mappedArtStyle) {
  3213. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3214. }else {
  3215. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3216. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3217. }else {
  3218. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3219. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3220. }
  3221. }
  3222. $systemPrompt = $is_single
  3223. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3224. 强制要求:
  3225. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3226. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3227. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3228. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3229. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3230. 普通要求:
  3231. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3232. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3233. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  3234. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3235. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3236. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3237. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3238. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3239. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3240. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3241. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3242. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3243. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3244. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3245. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3246. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3247. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3248. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3249. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3250. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3251. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3252. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3253. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3254. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3255. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3256. 5.{$mappedArtStyle_prompt}\n\n
  3257. 示例如下:\n
  3258. ###剧本名:西昆仑
  3259. ###故事梗概
  3260. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3261. ###剧本亮点
  3262. 亮点1:绝境奇药,生死一线
  3263. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3264. 亮点2:结拜兄妹,化解尴尬
  3265. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3266. 亮点3:纤发夺命,情愫暗涌
  3267. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3268. ###人物关系
  3269. 阿雪与梁萧之间存在兄妹之情。
  3270. ###核心矛盾
  3271. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3272. ###主体列表
  3273. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3274. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3275. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3276. 姿态:站立。}{{甜心小美}}
  3277. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3278. 全景,正面拍摄,青年女性,亚洲人。
  3279. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3280. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3281. 姿态:站立。}{{阳光青年}}
  3282. ###美术风格
  3283. 基础画风风格词:厚涂古风
  3284. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3285. ###场景列表
  3286. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3287. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3288. 无人物。}
  3289. ###分镜剧本
  3290. ##第1幕:徐家老旧厨房 白天 室内
  3291. 分镜1
  3292. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3293. 场景:徐家老旧厨房
  3294. 构图设计:全景,低角度仰视
  3295. 运镜调度:手持拍摄
  3296. 配音角色:旁白
  3297. 出镜角色:许芸-校服装、徐母
  3298. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3299. 画面类型:普通画面
  3300. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3301. 分镜2
  3302. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3303. 场景:徐家老旧厨房
  3304. 构图设计:近景,徐母面部特写
  3305. 运镜调度:固定镜头
  3306. 配音角色:徐母
  3307. 出镜角色:徐母
  3308. 台词内容:问我夜不归宿死哪儿去了。
  3309. 画面类型:对口型
  3310. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3311. ##第2幕:徐家简陋客厅 黄昏 室内
  3312. 分镜3
  3313. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3314. 场景:徐家简陋客厅
  3315. 构图设计:全景,景深虚化
  3316. 运镜调度:固定镜头
  3317. 配音角色:旁白
  3318. 出镜角色:无
  3319. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3320. 画面类型:普通画面
  3321. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3322. 分镜4
  3323. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3324. 场景:徐家简陋客厅
  3325. 构图设计:特写,火车票
  3326. 运镜调度:固定镜头
  3327. 配音角色:旁白
  3328. 出镜角色:无
  3329. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3330. 画面类型:普通画面
  3331. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  3332. "
  3333. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3334. 强制要求:\n
  3335. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3336. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3337. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3338. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3339. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3340. 普通要求:\n
  3341. 1.剧本名(必须生成)必须与文档内容高度相关
  3342. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3343. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3344. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3345. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3346. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3347. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3348. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3349. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3350. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3351. 4.{$mappedArtStyle_prompt}\n\n
  3352. 示例如下:\n
  3353. ###剧本名:西昆仑
  3354. ###故事梗概
  3355. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3356. ###剧本亮点
  3357. 亮点1:绝境奇药,生死一线
  3358. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3359. 亮点2:结拜兄妹,化解尴尬
  3360. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3361. 亮点3:纤发夺命,情愫暗涌
  3362. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3363. ###人物关系
  3364. 阿雪与梁萧之间存在兄妹之情。
  3365. ###核心矛盾
  3366. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3367. ###主体列表
  3368. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3369. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3370. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3371. 姿态:站立。}{{甜心小美}}
  3372. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3373. 全景,正面拍摄,青年女性,亚洲人。
  3374. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3375. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3376. 姿态:站立。}{{阳光青年}}
  3377. ###美术风格
  3378. 基础画风风格词:厚涂古风
  3379. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3380. ###场景列表
  3381. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3382. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3383. 无人物。}";
  3384. // 构建消息
  3385. $messages = [
  3386. [
  3387. 'role' => 'system',
  3388. 'content' => $systemPrompt
  3389. ],
  3390. [
  3391. 'role' => 'user',
  3392. 'content' => "以下是文档内容:
  3393. {$content}
  3394. 用户问题:
  3395. {$question}"
  3396. ]
  3397. ];
  3398. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3399. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3400. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3401. if ($model === 'deepseek-chat') {
  3402. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3403. $model = 'deepseek-v4-flash';
  3404. $thinkingMode = 'disabled';
  3405. } elseif ($model === 'deepseek-reasoner') {
  3406. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3407. $model = 'deepseek-v4-flash';
  3408. $thinkingMode = 'enabled';
  3409. }
  3410. $post_data = [
  3411. 'model' => $model,
  3412. 'messages' => $messages,
  3413. // 'max_tokens' => 8192,
  3414. 'temperature' => 0.7,
  3415. 'frequency_penalty' => 0,
  3416. 'presence_penalty' => 0,
  3417. 'response_format' => ['type' => 'text'],
  3418. 'thinking' => ['type'=>$thinkingMode],
  3419. 'stream' => true // 启用流式输出
  3420. ];
  3421. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3422. // 根据模型类型选择调用方法
  3423. $fullContent = '';
  3424. $fullReasoningContent = '';
  3425. $usage = [];
  3426. try {
  3427. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3428. // DeepSeek 官方模型使用 DeepSeek API
  3429. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3430. } else if (in_array($model, $this->gpt_text_models)) {
  3431. // GPT-5.4 模型使用 TokenRouter API
  3432. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3433. } else {
  3434. // 其他模型使用火山引擎API
  3435. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3436. }
  3437. // 验证返回值类型
  3438. if (!is_iterable($streamGenerator)) {
  3439. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  3440. dLog('deepseek')->error('addChat流式生成器无效', [
  3441. 'generator_type' => $errorType,
  3442. 'model' => $model,
  3443. 'anime_id' => $anime_id
  3444. ]);
  3445. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  3446. 'type' => $errorType,
  3447. 'model' => $model
  3448. ]);
  3449. yield [
  3450. 'type' => 'error',
  3451. 'script' => [],
  3452. 'episode' => [],
  3453. 'answer' => '',
  3454. 'reasoning' => '',
  3455. 'usage' => [],
  3456. 'error' => '接口返回数据异常,请重新请求'
  3457. ];
  3458. return;
  3459. }
  3460. // 处理流式输出
  3461. foreach ($streamGenerator as $chunk) {
  3462. if (isset($chunk['type'])) {
  3463. if ($chunk['type'] === 'done') {
  3464. // 最终结果
  3465. $fullContent = $chunk['full_content'];
  3466. $fullReasoningContent = $chunk['full_reasoning'];
  3467. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3468. } else {
  3469. // 逐块yield数据
  3470. yield $chunk;
  3471. }
  3472. }
  3473. }
  3474. } catch (\Exception $e) {
  3475. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  3476. 'model' => $model,
  3477. 'anime_id' => $anime_id,
  3478. 'trace' => $e->getTraceAsString()
  3479. ]);
  3480. logDB('deepseek', 'error', 'addChat流式处理失败', [
  3481. 'error' => $e->getMessage(),
  3482. 'model' => $model
  3483. ]);
  3484. yield [
  3485. 'type' => 'error',
  3486. 'script' => [],
  3487. 'episode' => [],
  3488. 'answer' => '',
  3489. 'reasoning' => '',
  3490. 'usage' => [],
  3491. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  3492. ];
  3493. return;
  3494. }
  3495. dLog('deepseek')->info('完整内容: '.$fullContent);
  3496. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3497. // 处理完整内容并返回最终结果
  3498. $script_arr = [];
  3499. if ($fullContent) {
  3500. $script_arr = handleScriptContent($fullContent);
  3501. dLog('deepseek')->info('解析内容', $script_arr);
  3502. logDB('deepseek', 'info', '解析内容', $script_arr);
  3503. }
  3504. if (empty($script_arr['roles'])) {
  3505. // 未生成剧本相关内容,保存对话记录并返回提示
  3506. dLog('deepseek')->info('未生成剧本相关的内容');
  3507. try {
  3508. DB::beginTransaction();
  3509. $now = date('Y-m-d H:i:s');
  3510. // 保存对话记录
  3511. $records = [
  3512. [
  3513. 'uid' => $uid,
  3514. 'anime_id' => $anime_id,
  3515. 'sequence' => 0,
  3516. 'role' => 'user',
  3517. 'content' => $prompt,
  3518. 'created_at' => $now,
  3519. 'updated_at' => $now
  3520. ],
  3521. [
  3522. 'uid' => $uid,
  3523. 'anime_id' => $anime_id,
  3524. 'sequence' => 0,
  3525. 'role' => 'assistant',
  3526. // 'content' => $fullContent,
  3527. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  3528. 'created_at' => $now,
  3529. 'updated_at' => $now
  3530. ]
  3531. ];
  3532. DB::table('mp_anime_records')->insert($records);
  3533. DB::commit();
  3534. } catch (\Exception $e) {
  3535. DB::rollBack();
  3536. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3537. }
  3538. yield [
  3539. 'type' => 'done',
  3540. 'script' => [],
  3541. 'episode' => [],
  3542. 'answer' => $fullContent,
  3543. 'reasoning' => $fullReasoningContent,
  3544. 'usage' => $usage,
  3545. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  3546. ];
  3547. return;
  3548. }
  3549. // 如果需要生成原文内容,从script_arr中提取
  3550. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  3551. $content = $script_arr['content'];
  3552. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  3553. if (!$content) {
  3554. yield [
  3555. 'type' => 'done',
  3556. 'script' => [],
  3557. 'episode' => [],
  3558. 'answer' => $fullContent,
  3559. 'reasoning' => $fullReasoningContent,
  3560. 'usage' => $usage,
  3561. 'error' => '未生成剧本内容,请调整提示词再试'
  3562. ];
  3563. return;
  3564. }
  3565. }
  3566. // 替换美术风格
  3567. if ($mappedArtStyle !== '') {
  3568. $script_arr['art_style'] = $mappedArtStyle;
  3569. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  3570. }
  3571. // 新建动漫
  3572. if ($user_anime_name == '新剧本策划') {
  3573. $anime_name = getProp($script_arr, 'script_name');
  3574. // if (!$anime_name) {
  3575. // // 未识别到剧本名,保存对话记录并返回提示
  3576. // dLog('deepseek')->info('未能识别到剧本名称');
  3577. // try {
  3578. // DB::beginTransaction();
  3579. // $now = date('Y-m-d H:i:s');
  3580. // // 保存对话记录
  3581. // $records = [
  3582. // [
  3583. // 'uid' => $uid,
  3584. // 'anime_id' => $anime_id,
  3585. // 'sequence' => 0,
  3586. // 'role' => 'user',
  3587. // 'content' => $prompt,
  3588. // 'created_at' => $now,
  3589. // 'updated_at' => $now
  3590. // ],
  3591. // [
  3592. // 'uid' => $uid,
  3593. // 'anime_id' => $anime_id,
  3594. // 'sequence' => 0,
  3595. // 'role' => 'assistant',
  3596. // 'content' => '未能生成剧本名称,请重试',
  3597. // 'created_at' => $now,
  3598. // 'updated_at' => $now
  3599. // ]
  3600. // ];
  3601. // DB::table('mp_anime_records')->insert($records);
  3602. // DB::commit();
  3603. // } catch (\Exception $e) {
  3604. // DB::rollBack();
  3605. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3606. // }
  3607. // yield [
  3608. // 'type' => 'done',
  3609. // 'script' => [],
  3610. // 'episode' => [],
  3611. // 'answer' => $fullContent,
  3612. // 'reasoning' => $fullReasoningContent,
  3613. // 'usage' => $usage,
  3614. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  3615. // ];
  3616. // return;
  3617. // }
  3618. // 确认对话名称唯一性
  3619. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  3620. $anime_name = $anime_name . '_' . date('YmdHis');
  3621. }
  3622. }else {
  3623. $anime_name = $user_anime_name;
  3624. }
  3625. $table_data = [
  3626. 'user_id' => $uid,
  3627. 'anime_name' => $anime_name,
  3628. 'model' => $model,
  3629. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3630. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3631. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3632. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3633. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3634. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3635. 'art_style_type' => $input_art_style,
  3636. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3637. 'status' => '解析完成',
  3638. 'content' => $content,
  3639. 'is_multi' => $is_multi,
  3640. 'ace_mode' => $ace_mode,
  3641. 'generate_status' => '待执行',
  3642. 'updated_at' => date('Y-m-d H:i:s')
  3643. ];
  3644. if ($table_data['content']) {
  3645. $chapters = $this->splitContent($table_data['content']);
  3646. $chapter_count = count($chapters);
  3647. if ($chapter_count > 0) {
  3648. $table_data['start_episode_sequence'] = 1;
  3649. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  3650. }
  3651. }
  3652. // 如果有剧本ID则进行绑定
  3653. if ($script_id) {
  3654. $table_data['script_id'] = $script_id;
  3655. }
  3656. $single_episode = [];
  3657. try {
  3658. DB::beginTransaction();
  3659. $now = date('Y-m-d H:i:s');
  3660. // 更新动漫大纲
  3661. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3662. if (!$boolen) {
  3663. dLog('deepseek')->info('动漫保存失败', $table_data);
  3664. Utils::throwError('20003:动漫保存失败');
  3665. }
  3666. // 保存对话记录
  3667. $records = [
  3668. [
  3669. 'uid' => $uid,
  3670. 'anime_id' => $anime_id,
  3671. 'sequence' => 0,
  3672. 'role' => 'user',
  3673. 'content' => $prompt,
  3674. 'created_at' => date('Y-m-d H:i:s'),
  3675. 'updated_at' => date('Y-m-d H:i:s')
  3676. ],
  3677. [
  3678. 'uid' => $uid,
  3679. 'anime_id' => $anime_id,
  3680. 'sequence' => 0,
  3681. 'role' => 'assistant',
  3682. 'content' => $fullContent,
  3683. 'created_at' => date('Y-m-d H:i:s'),
  3684. 'updated_at' => date('Y-m-d H:i:s')
  3685. ]
  3686. ];
  3687. // 保存对话记录
  3688. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3689. if (!$boolen3) {
  3690. Utils::throwError('20003:对话记录保存失败');
  3691. }
  3692. if ($is_single) {
  3693. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3694. if (empty($episode_arr['acts'])) {
  3695. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3696. }
  3697. $saveResult = $this->saveEpisodeVersionData(
  3698. $anime_id,
  3699. 1,
  3700. $episode_arr,
  3701. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3702. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3703. null,
  3704. null,
  3705. false,
  3706. $content,
  3707. $now
  3708. );
  3709. $single_episode = $saveResult['episode'];
  3710. $episode_id = $saveResult['episode_id'];
  3711. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3712. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3713. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3714. 'updated_at' => $now
  3715. ]);
  3716. if ($boolen5 === false) {
  3717. Utils::throwError('20003:单剧集主表资源同步失败');
  3718. }
  3719. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3720. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3721. $episode_record_content = '确认分镜大纲';
  3722. if ($content !== '') {
  3723. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  3724. }
  3725. $episode_records = [
  3726. [
  3727. 'uid' => $uid,
  3728. 'anime_id' => $anime_id,
  3729. 'role' => 'user',
  3730. 'content' => $episode_record_content,
  3731. 'sequence' => 1,
  3732. 'episode_id' => $episode_id,
  3733. 'created_at' => $now,
  3734. 'updated_at' => $now
  3735. ],
  3736. [
  3737. 'uid' => $uid,
  3738. 'anime_id' => $anime_id,
  3739. 'role' => 'assistant',
  3740. 'content' => $fullContent,
  3741. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3742. 'sequence' => 1,
  3743. 'episode_id' => $episode_id,
  3744. 'created_at' => $now,
  3745. 'updated_at' => $now
  3746. ]
  3747. ];
  3748. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3749. if (!$boolen4) {
  3750. Utils::throwError('20003:单剧集分镜记录保存失败');
  3751. }
  3752. }
  3753. }catch (\Exception $e) {
  3754. DB::rollBack();
  3755. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  3756. yield [
  3757. 'type' => 'done',
  3758. 'answer' => $fullContent,
  3759. 'reasoning' => $fullReasoningContent,
  3760. 'usage' => $usage,
  3761. 'error' => $e->getMessage(),
  3762. ];
  3763. return;
  3764. }
  3765. DB::commit();
  3766. dLog('deepseek')->info('保存完毕');
  3767. if ($is_single && !empty($single_episode)) {
  3768. // $this->batchSetGlobalRoleImg([
  3769. // 'anime_id' => $anime_id,
  3770. // ]);
  3771. // $this->batchSetGlobalSceneImg([
  3772. // 'anime_id' => $anime_id,
  3773. // ]);
  3774. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  3775. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  3776. }
  3777. $table_data['anime_id'] = $anime_id;
  3778. $table_data['roles'] = json_decode($table_data['roles'], true);
  3779. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  3780. // $table_data['episodes'] = $script_arr['episodes'];
  3781. unset($table_data['created_at']);
  3782. unset($table_data['updated_at']);
  3783. unset($table_data['status']);
  3784. dLog('deepseek')->info('开始返回');
  3785. yield [
  3786. 'type' => 'done',
  3787. 'script' => $table_data,
  3788. 'episode' => $single_episode,
  3789. 'answer' => $fullContent,
  3790. 'reasoning' => $fullReasoningContent,
  3791. 'usage' => $usage
  3792. ];
  3793. }
  3794. public function reGenerateAnime($data) {
  3795. $uid = Site::getUid();
  3796. $file = getProp($data, 'file');
  3797. $content = getProp($data, 'content', '');
  3798. $bid = getProp($data, 'bid', 0);
  3799. $script_id = getProp($data, 'script_id', 0);
  3800. $anime_id = getProp($data, 'anime_id');
  3801. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3802. if (!$anime) {
  3803. Utils::throwError('20003:该对话不存在');
  3804. }
  3805. $user_anime_name = getProp($anime, 'anime_name');
  3806. $prompt = getProp($data, 'prompt');
  3807. // 处理文本模型
  3808. $model = getProp($data, 'model');
  3809. if (!$model) {
  3810. // 用户没有输入,从anime表获取
  3811. $model = getProp($anime, 'model');
  3812. if (!$model) {
  3813. // anime表也没有,使用默认值
  3814. $model = 'doubao-seed-2-0-mini-260215';
  3815. }
  3816. }
  3817. // 验证模型是否在可用模型表中
  3818. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3819. $model = 'doubao-seed-2-0-mini-260215';
  3820. }
  3821. $is_multi = getProp($anime, 'is_multi', 1);
  3822. $is_single = (int)$is_multi !== 1;
  3823. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  3824. if ($is_single) {
  3825. $episode_exists = DB::table('mp_anime_episodes')
  3826. ->where('anime_id', $anime_id)
  3827. ->where('sequence', 1)
  3828. ->exists();
  3829. if ($episode_exists) {
  3830. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  3831. }
  3832. }
  3833. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3834. if ($prompt) {
  3835. $question .= "本次修改要求如下:\n{$prompt}";
  3836. }
  3837. // 提取文件内容
  3838. if ($file) {
  3839. $content = $this->extractFileContent($file);
  3840. if (!$content) {
  3841. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3842. }
  3843. } elseif ($script_id) {
  3844. $content = $this->getContentByScriptId($script_id);
  3845. if (!$content) {
  3846. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3847. }
  3848. } elseif ($bid) {
  3849. $content = $this->getContentByBid($bid);
  3850. if (!$content) {
  3851. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3852. }
  3853. } elseif ($content) {
  3854. $content = filterContent($content);
  3855. }else {
  3856. $content = filterContent(getProp($anime, 'content'));
  3857. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3858. $need_generate_content = true;
  3859. }
  3860. }
  3861. // 判断是否需要生成原文内容
  3862. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3863. // 如果需要生成原文内容,添加额外的要求
  3864. $content_generation_requirement = $need_generate_content
  3865. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3866. : "";
  3867. // 美术风格
  3868. $input_art_style = getProp($anime, 'art_style');
  3869. if (!$input_art_style) {
  3870. $input_art_style = getProp($data, 'art_style');
  3871. }
  3872. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3873. // 美术风格
  3874. if (!$mappedArtStyle) {
  3875. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3876. }else {
  3877. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3878. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3879. }else {
  3880. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3881. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3882. }
  3883. }
  3884. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3885. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3886. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3887. 中年女:邻居阿姨
  3888. 老年男:幽默大爷
  3889. 老年女:婆婆
  3890. 萌娃:奶气萌娃";
  3891. $system_message = ['role'=>'system', 'content'=>$is_single
  3892. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3893. 强制要求:
  3894. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3895. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3896. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3897. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3898. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3899. 普通要求:
  3900. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3901. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3902. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3903. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3904. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3905. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3906. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3907. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3908. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3909. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3910. 3.$mappedArtStyle_prompt\n\n
  3911. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3912. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3913. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3914. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3915. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3916. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3917. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3918. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3919. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3920. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3921. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3922. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3923. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3924. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3925. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3926. 示例如下:\n
  3927. ###剧本名:西昆仑
  3928. ###故事梗概
  3929. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3930. ###剧本亮点
  3931. 亮点1:绝境奇药,生死一线
  3932. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3933. 亮点2:结拜兄妹,化解尴尬
  3934. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3935. 亮点3:纤发夺命,情愫暗涌
  3936. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3937. ###人物关系
  3938. 阿雪与梁萧之间存在兄妹之情。
  3939. ###核心矛盾
  3940. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3941. ###主体列表
  3942. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3943. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3944. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3945. 姿态:站立。}{{甜心小美}}
  3946. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3947. 全景,正面拍摄,青年女性,亚洲人。
  3948. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3949. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3950. 姿态:站立。}{{阳光青年}}
  3951. ###美术风格
  3952. 基础画风风格词:厚涂古风
  3953. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3954. ###场景列表
  3955. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3956. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3957. 无人物。}
  3958. ###分镜剧本
  3959. ##第1幕:徐家老旧厨房 白天 室内
  3960. 分镜1
  3961. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3962. 场景:徐家老旧厨房
  3963. 构图设计:全景,低角度仰视
  3964. 运镜调度:手持拍摄
  3965. 配音角色:旁白
  3966. 出镜角色:许芸-校服装、徐母
  3967. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3968. 画面类型:普通画面
  3969. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3970. 分镜2
  3971. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3972. 场景:徐家老旧厨房
  3973. 构图设计:近景,徐母面部特写
  3974. 运镜调度:固定镜头
  3975. 配音角色:徐母
  3976. 出镜角色:徐母
  3977. 台词内容:问我夜不归宿死哪儿去了。
  3978. 画面类型:对口型
  3979. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3980. ##第2幕:徐家简陋客厅 黄昏 室内
  3981. 分镜3
  3982. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3983. 场景:徐家简陋客厅
  3984. 构图设计:全景,景深虚化
  3985. 运镜调度:固定镜头
  3986. 配音角色:旁白
  3987. 出镜角色:无
  3988. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3989. 画面类型:普通画面
  3990. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3991. 分镜4
  3992. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3993. 场景:徐家简陋客厅
  3994. 构图设计:特写,火车票
  3995. 运镜调度:固定镜头
  3996. 配音角色:旁白
  3997. 出镜角色:无
  3998. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3999. 画面类型:普通画面
  4000. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4001. "
  4002. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4003. 强制要求:\n
  4004. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4005. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4006. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4007. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4008. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4009. 普通要求:\n
  4010. 1.剧本名(必须生成)必须与文档内容高度相关
  4011. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4012. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4013. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4014. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4015. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4016. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4017. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4018. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4019. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4020. 4.$mappedArtStyle_prompt\n\n
  4021. 示例如下:\n
  4022. ###剧本名:西昆仑
  4023. ###故事梗概
  4024. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4025. ###剧本亮点
  4026. 亮点1:绝境奇药,生死一线
  4027. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4028. 亮点2:结拜兄妹,化解尴尬
  4029. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4030. 亮点3:纤发夺命,情愫暗涌
  4031. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4032. ###人物关系
  4033. 阿雪与梁萧之间存在兄妹之情。
  4034. ###核心矛盾
  4035. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4036. ###主体列表
  4037. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4038. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4039. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4040. 姿态:站立。}{{甜心小美}}
  4041. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4042. 全景,正面拍摄,青年女性,亚洲人。
  4043. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4044. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4045. 姿态:站立。}{{阳光青年}}
  4046. ###美术风格
  4047. 基础画风风格词:厚涂古风
  4048. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4049. ###场景列表
  4050. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4051. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4052. 无人物。}"];
  4053. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  4054. $episode_count = $this->extractEpisodeNumber($prompt);
  4055. if ((int)getProp($anime, 'is_multi') !== 1) {
  4056. yield [
  4057. 'type' => 'done',
  4058. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  4059. 'reasoning' => '',
  4060. 'usage' => []
  4061. ];
  4062. return;
  4063. }
  4064. if ($episode_count) {
  4065. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  4066. $system_message = [
  4067. 'role' => 'system',
  4068. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4069. 强制要求:\n
  4070. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4071. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4072. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4073. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4074. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4075. 普通要求:\n
  4076. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4077. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4078. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4079. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4080. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4081. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4082. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4083. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4084. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4085. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  4086. 示例如下:\n
  4087. ###剧本名:西昆仑
  4088. ###故事梗概
  4089. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4090. ###剧本亮点
  4091. 亮点1:绝境奇药,生死一线
  4092. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4093. 亮点2:结拜兄妹,化解尴尬
  4094. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4095. 亮点3:纤发夺命,情愫暗涌
  4096. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4097. ###人物关系
  4098. 阿雪与梁萧之间存在兄妹之情。
  4099. ###核心矛盾
  4100. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4101. ###主体列表
  4102. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4103. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4104. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4105. 姿态:站立。}{{甜心小美}}
  4106. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4107. 全景,正面拍摄,青年女性,亚洲人。
  4108. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4109. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4110. 姿态:站立。}{{阳光青年}}
  4111. ###美术风格
  4112. 基础画风风格词:厚涂古风
  4113. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4114. ###场景列表
  4115. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4116. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4117. 无人物。}
  4118. ###分集详细内容
  4119. ##第1章 重生
  4120. 我重生了。
  4121. 源于一个男人偏执的暗恋。
  4122. ##第2章 相救
  4123. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  4124. 我眼睛扫向站在锅炉后的卞大伟。"
  4125. ];
  4126. // 构建消息
  4127. $messages = [
  4128. $system_message,
  4129. [
  4130. 'role' => 'user',
  4131. 'content' => "以下是文档内容:
  4132. {$content}
  4133. 用户问题:
  4134. {$question}"
  4135. ]
  4136. ];
  4137. }else {
  4138. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  4139. // 构建消息
  4140. $messages = [
  4141. $system_message,
  4142. [
  4143. 'role' => 'user',
  4144. 'content' => "以下是文档内容:
  4145. {$content}
  4146. 用户问题:
  4147. {$question}"
  4148. ]
  4149. ];
  4150. }else {
  4151. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  4152. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  4153. return (array)$value;
  4154. })->toArray();
  4155. array_unshift($messages, $system_message);
  4156. $messages[] = [
  4157. 'role' => 'user',
  4158. 'content' => $prompt
  4159. ];
  4160. }
  4161. }
  4162. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4163. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4164. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4165. if ($model === 'deepseek-chat') {
  4166. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4167. $model = 'deepseek-v4-flash';
  4168. $thinkingMode = 'disabled';
  4169. } elseif ($model === 'deepseek-reasoner') {
  4170. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4171. $model = 'deepseek-v4-flash';
  4172. $thinkingMode = 'enabled';
  4173. }
  4174. $post_data = [
  4175. 'model' => $model,
  4176. 'messages' => $messages,
  4177. // 'max_tokens' => 8192,
  4178. 'temperature' => 0.7,
  4179. 'frequency_penalty' => 0,
  4180. 'presence_penalty' => 0,
  4181. 'response_format' => ['type' => 'text'],
  4182. 'thinking' => ['type' => $thinkingMode],
  4183. 'stream' => true // 启用流式输出
  4184. ];
  4185. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4186. // 根据模型类型选择调用方法
  4187. $fullContent = '';
  4188. $fullReasoningContent = '';
  4189. $usage = [];
  4190. // dd($post_data);
  4191. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  4192. try {
  4193. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4194. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4195. } else if (in_array($model, $this->gpt_text_models)) {
  4196. // GPT-5.4 模型使用 TokenRouter API
  4197. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4198. } else {
  4199. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4200. }
  4201. // 验证返回值类型
  4202. if (!is_iterable($streamGenerator)) {
  4203. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4204. dLog('deepseek')->error('方法名流式生成器无效', [
  4205. 'generator_type' => $errorType,
  4206. 'model' => $model,
  4207. // 添加其他上下文信息
  4208. ]);
  4209. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  4210. 'type' => $errorType,
  4211. 'model' => $model
  4212. ]);
  4213. yield [
  4214. 'type' => 'error',
  4215. // 根据方法返回相应的空数据结构
  4216. 'answer' => '',
  4217. 'reasoning' => '',
  4218. 'usage' => [],
  4219. 'error' => '接口返回数据异常,请重新请求'
  4220. ];
  4221. return;
  4222. }
  4223. // 处理流式输出
  4224. foreach ($streamGenerator as $chunk) {
  4225. if (isset($chunk['type'])) {
  4226. if ($chunk['type'] === 'done') {
  4227. $fullContent = $chunk['full_content'];
  4228. $fullReasoningContent = $chunk['full_reasoning'];
  4229. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4230. } else {
  4231. yield $chunk;
  4232. }
  4233. }
  4234. }
  4235. } catch (\Exception $e) {
  4236. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  4237. 'model' => $model,
  4238. 'trace' => $e->getTraceAsString()
  4239. ]);
  4240. logDB('deepseek', 'error', '方法名流式处理失败', [
  4241. 'error' => $e->getMessage(),
  4242. 'model' => $model
  4243. ]);
  4244. yield [
  4245. 'type' => 'error',
  4246. // 根据方法返回相应的空数据结构
  4247. 'answer' => '',
  4248. 'reasoning' => '',
  4249. 'usage' => [],
  4250. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4251. ];
  4252. return;
  4253. }
  4254. dLog('deepseek')->info('完整内容: '.$fullContent);
  4255. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4256. // 处理完整内容并返回最终结果
  4257. $script_arr = [];
  4258. if ($fullContent) {
  4259. $script_arr = handleScriptContent($fullContent);
  4260. dLog('deepseek')->info('解析内容', $script_arr);
  4261. logDB('deepseek', 'info', '解析内容', $script_arr);
  4262. }
  4263. if (empty($script_arr['roles'])) {
  4264. // 未生成剧本相关内容,保存对话记录并返回提示
  4265. dLog('deepseek')->info('未生成剧本相关的内容');
  4266. try {
  4267. $now = date('Y-m-d H:i:s');
  4268. // 保存对话记录
  4269. $records = [
  4270. [
  4271. 'uid' => $uid,
  4272. 'anime_id' => $anime_id,
  4273. 'sequence' => 0,
  4274. 'role' => 'user',
  4275. 'content' => $prompt,
  4276. 'created_at' => $now,
  4277. 'updated_at' => $now
  4278. ],
  4279. [
  4280. 'uid' => $uid,
  4281. 'anime_id' => $anime_id,
  4282. 'sequence' => 0,
  4283. 'role' => 'assistant',
  4284. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  4285. 'created_at' => $now,
  4286. 'updated_at' => $now
  4287. ]
  4288. ];
  4289. DB::table('mp_anime_records')->insert($records);
  4290. } catch (\Exception $e) {
  4291. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4292. }
  4293. yield [
  4294. 'type' => 'done',
  4295. 'script' => [],
  4296. 'episode' => [],
  4297. 'answer' => $fullContent,
  4298. 'reasoning' => $fullReasoningContent,
  4299. 'usage' => $usage,
  4300. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4301. ];
  4302. return;
  4303. }
  4304. // 替换美术风格
  4305. if ($mappedArtStyle !== '') {
  4306. $script_arr['art_style'] = $mappedArtStyle;
  4307. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4308. }
  4309. if ($user_anime_name != '新剧本策划') {
  4310. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  4311. // 确认对话名称唯一性
  4312. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4313. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  4314. }
  4315. }else {
  4316. $anime_name = $user_anime_name;
  4317. }
  4318. $table_data = [
  4319. 'user_id' => $uid,
  4320. 'model' => $model,
  4321. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4322. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4323. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4324. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4325. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4326. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4327. 'art_style_type' => $input_art_style,
  4328. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4329. 'status' => '解析完成',
  4330. 'generate_status' => '待执行',
  4331. 'updated_at' => date('Y-m-d H:i:s')
  4332. ];
  4333. if ($anime_name) $table_data['anime_name'] = $anime_name;
  4334. // 如果是修改集数,则将content内容更新(会改变原文)
  4335. if (isset($episode_count) && $episode_count > 0) {
  4336. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  4337. $table_data['start_episode_sequence'] = 1;
  4338. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  4339. }else {
  4340. // 如果需要生成原文内容,从script_arr中提取
  4341. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4342. $table_data['content'] = $script_arr['content'];
  4343. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  4344. if (!$table_data['content']) {
  4345. yield [
  4346. 'type' => 'done',
  4347. 'script' => [],
  4348. 'episode' => [],
  4349. 'answer' => $fullContent,
  4350. 'reasoning' => $fullReasoningContent,
  4351. 'usage' => $usage,
  4352. 'error' => '未生成剧本内容,请调整提示词再试'
  4353. ];
  4354. return;
  4355. }
  4356. }
  4357. if (isset($table_data['content']) && $table_data['content']) {
  4358. $chapters = $this->splitContent($table_data['content']);
  4359. $chapter_count = count($chapters);
  4360. if ($chapter_count > 0) {
  4361. $table_data['start_episode_sequence'] = 1;
  4362. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4363. }
  4364. }
  4365. }
  4366. $single_episode = [];
  4367. try {
  4368. DB::beginTransaction();
  4369. $now = date('Y-m-d H:i:s');
  4370. // 更新动漫大纲
  4371. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4372. if (!$boolen) {
  4373. dLog('deepseek')->info('对话修改失败', $table_data);
  4374. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  4375. Utils::throwError('20003:对话修改失败');
  4376. }
  4377. // 保存对话记录
  4378. $records = [
  4379. [
  4380. 'uid' => $uid,
  4381. 'anime_id' => $anime_id,
  4382. 'sequence' => 0,
  4383. 'role' => 'user',
  4384. 'content' => $prompt,
  4385. 'created_at' => $now,
  4386. 'updated_at' => $now
  4387. ],
  4388. [
  4389. 'uid' => $uid,
  4390. 'anime_id' => $anime_id,
  4391. 'sequence' => 0,
  4392. 'role' => 'assistant',
  4393. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4394. 'content' => $fullContent,
  4395. 'created_at' => $now,
  4396. 'updated_at' => $now
  4397. ]
  4398. ];
  4399. // 保存对话记录
  4400. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4401. if (!$boolen3) {
  4402. Utils::throwError('20003:对话记录保存失败');
  4403. }
  4404. // 单剧集模式:生成并保存剧集信息
  4405. if ($is_single) {
  4406. $anime_name = getProp($anime, 'anime_name', '未命名');
  4407. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4408. if (empty($episode_arr['acts'])) {
  4409. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4410. }
  4411. $saveResult = $this->saveEpisodeVersionData(
  4412. $anime_id,
  4413. 1,
  4414. $episode_arr,
  4415. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4416. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4417. null,
  4418. null,
  4419. false,
  4420. $content,
  4421. $now
  4422. );
  4423. $single_episode = $saveResult['episode'];
  4424. $episode_id = $saveResult['episode_id'];
  4425. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4426. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4427. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4428. 'updated_at' => $now
  4429. ]);
  4430. if ($boolen5 === false) {
  4431. Utils::throwError('20003:单剧集主表资源同步失败');
  4432. }
  4433. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4434. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4435. $episode_record_content = '确认分镜大纲';
  4436. if ($content !== '') {
  4437. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4438. }
  4439. $episode_records = [
  4440. [
  4441. 'uid' => $uid,
  4442. 'anime_id' => $anime_id,
  4443. 'role' => 'user',
  4444. 'content' => $episode_record_content,
  4445. 'sequence' => 1,
  4446. 'episode_id' => $episode_id,
  4447. 'created_at' => $now,
  4448. 'updated_at' => $now
  4449. ],
  4450. [
  4451. 'uid' => $uid,
  4452. 'anime_id' => $anime_id,
  4453. 'role' => 'assistant',
  4454. 'content' => $fullContent,
  4455. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4456. 'sequence' => 1,
  4457. 'episode_id' => $episode_id,
  4458. 'created_at' => $now,
  4459. 'updated_at' => $now
  4460. ]
  4461. ];
  4462. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4463. if (!$boolen4) {
  4464. Utils::throwError('20003:单剧集分镜记录保存失败');
  4465. }
  4466. }
  4467. }catch (\Exception $e) {
  4468. DB::rollBack();
  4469. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  4470. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  4471. yield [
  4472. 'type' => 'done',
  4473. 'answer' => $fullContent,
  4474. 'reasoning' => $fullReasoningContent,
  4475. 'usage' => $usage,
  4476. 'error' => $e->getMessage(),
  4477. ];
  4478. return;
  4479. }
  4480. DB::commit();
  4481. dLog('deepseek')->info('保存完毕');
  4482. if ($is_single && !empty($single_episode)) {
  4483. // $this->batchSetGlobalRoleImg([
  4484. // 'anime_id' => $anime_id,
  4485. // ]);
  4486. // $this->batchSetGlobalSceneImg([
  4487. // 'anime_id' => $anime_id,
  4488. // ]);
  4489. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4490. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4491. }
  4492. $table_data['anime_id'] = $anime_id;
  4493. $table_data['roles'] = json_decode($table_data['roles'], true);
  4494. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4495. unset($table_data['updated_at']);
  4496. unset($table_data['status']);
  4497. yield [
  4498. 'type' => 'done',
  4499. 'script' => $table_data,
  4500. 'episode' => $single_episode,
  4501. 'answer' => $fullContent,
  4502. 'reasoning' => $fullReasoningContent,
  4503. 'usage' => $usage
  4504. ];
  4505. }
  4506. public function chat($data) {
  4507. $uid = Site::getUid();
  4508. $anime_id = getProp($data, 'anime_id');
  4509. $file = getProp($data, 'file');
  4510. $content = getProp($data, 'content', '');
  4511. $bid = getProp($data, 'bid', 0);
  4512. $script_id = getProp($data, 'script_id', 0);
  4513. $episode_number = getProp($data, 'episode_number', 1);
  4514. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4515. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4516. if (!$anime) Utils::throwError('20003:该对话不存在!');
  4517. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  4518. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  4519. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  4520. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  4521. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  4522. $roles = is_array($roles) ? $roles : [];
  4523. $scenes = is_array($scenes) ? $scenes : [];
  4524. // 获取最后一集序号
  4525. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  4526. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  4527. // 转换主体列表和场景列表的格式
  4528. // 获取参考主体或场景
  4529. if ((int)$episode_number === 1) {
  4530. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  4531. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  4532. }else {
  4533. $prev_episode_number = $episode_number - 1;
  4534. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  4535. }
  4536. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  4537. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  4538. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  4539. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  4540. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4541. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4542. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4543. 中年女:邻居阿姨
  4544. 老年男:幽默大爷
  4545. 老年女:婆婆
  4546. 萌娃:奶气萌娃";
  4547. if ($roles_content) {
  4548. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  4549. 主体范围:\n {$roles_content}\n
  4550. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  4551. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4552. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4553. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4554. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4555. }else {
  4556. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4557. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4558. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4559. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4560. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4561. }
  4562. if ($scenes_content) {
  4563. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  4564. 场景范围:\n {$scenes_content}\n
  4565. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  4566. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4567. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4568. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4569. }else {
  4570. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4571. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4572. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4573. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4574. }
  4575. // 提取文件内容
  4576. if ($file) {
  4577. $uploaded_content = $this->extractFileContent($file);
  4578. if (!$uploaded_content) {
  4579. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4580. }
  4581. } elseif ($script_id) {
  4582. $uploaded_content = $this->getContentByScriptId($script_id);
  4583. if (!$uploaded_content) {
  4584. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4585. }
  4586. } elseif ($bid) {
  4587. $uploaded_content = $this->getContentByBid($bid);
  4588. if (!$uploaded_content) {
  4589. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4590. }
  4591. } elseif ($content) {
  4592. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  4593. }
  4594. // elseif ($prompt) {
  4595. // $uploaded_content = filterContent($prompt);
  4596. // }
  4597. else {
  4598. $uploaded_content = '';
  4599. }
  4600. $input_art_style = getProp($anime, 'art_style');
  4601. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4602. // 美术风格
  4603. if (!$mappedArtStyle) {
  4604. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4605. }else {
  4606. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4607. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4608. }else {
  4609. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4610. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4611. }
  4612. }
  4613. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4614. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4615. // 强制要求:
  4616. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4617. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4618. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4619. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4620. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  4621. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  4622. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  4623. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  4624. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  4625. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  4626. // - 分镜要和场景列表、人物主体保持一致\n
  4627. // 普通要求:
  4628. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4629. // {$role_demo}
  4630. // {$scene_demo}
  4631. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4632. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4633. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4634. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4635. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4636. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4637. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4638. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4639. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4640. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4641. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4642. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4643. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4644. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4645. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4646. // 5.$mappedArtStyle_prompt\n\n
  4647. // 示例格式:\n
  4648. // 第1集:隐形的守护者
  4649. // ###故事梗概
  4650. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4651. // ###美术风格
  4652. // 基础画风风格词:韩漫二次元
  4653. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4654. // ###主体列表
  4655. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4656. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4657. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4658. // ###场景列表
  4659. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4660. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4661. // 无人物。}
  4662. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4663. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4664. // 无人物。}
  4665. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4666. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4667. // 无人物。}
  4668. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4669. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4670. // 无人物。}
  4671. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4672. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4673. // 无人物。}
  4674. // ###分镜剧本
  4675. // ##第1幕:徐家老旧厨房 白天 室内
  4676. // 分镜1
  4677. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4678. // 场景:徐家老旧厨房
  4679. // 构图设计:全景,低角度仰视
  4680. // 运镜调度:手持拍摄
  4681. // 配音角色:旁白
  4682. // 出镜角色:许芸-校服装、徐母
  4683. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4684. // 画面类型:普通画面
  4685. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4686. // 分镜2
  4687. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4688. // 场景:徐家老旧厨房
  4689. // 构图设计:近景,徐母面部特写
  4690. // 运镜调度:固定镜头
  4691. // 配音角色:徐母
  4692. // 出镜角色:徐母
  4693. // 台词内容:问我夜不归宿死哪儿去了。
  4694. // 画面类型:对口型
  4695. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4696. // ##第2幕:徐家简陋客厅 黄昏 室内
  4697. // 分镜3
  4698. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4699. // 场景:徐家简陋客厅
  4700. // 构图设计:全景,景深虚化
  4701. // 运镜调度:固定镜头
  4702. // 配音角色:旁白
  4703. // 出镜角色:无
  4704. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4705. // 画面类型:普通画面
  4706. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4707. // 分镜4
  4708. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4709. // 场景:徐家简陋客厅
  4710. // 构图设计:特写,火车票
  4711. // 运镜调度:固定镜头
  4712. // 配音角色:旁白
  4713. // 出镜角色:无
  4714. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4715. // 画面类型:普通画面
  4716. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4717. // \n\n";
  4718. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  4719. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  4720. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  4721. 普通要求:
  4722. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4723. {$role_demo}
  4724. {$scene_demo}
  4725. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4726. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4727. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4728. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  4729. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4730. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4731. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4732. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4733. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4734. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4735. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4736. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4737. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4738. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4739. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4740. 5.$mappedArtStyle_prompt
  4741. 6.《情绪-视听语言映射表》:
  4742. 6.1 场景空间与时间心理学 (Scene & Temporality)
  4743. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4744. -----|---------|------------|----------------
  4745. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  4746. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  4747. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  4748. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  4749. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  4750. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4751. -----|---------|------------|----------------
  4752. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  4753. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  4754. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  4755. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  4756. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  4757. --------|---------|--------------|-------------
  4758. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  4759. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  4760. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  4761. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  4762. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  4763. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  4764. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  4765. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  4766. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  4767. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  4768. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  4769. -----|---------|------------|------------
  4770. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  4771. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  4772. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  4773. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  4774. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  4775. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  4776. --------|---------|--------------|----------
  4777. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  4778. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  4779. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  4780. 6.6 声音设计与潜意识影响 (Soundscape)
  4781. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  4782. -----|---------|------------|------------------
  4783. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  4784. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  4785. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  4786. 理论基石:
  4787. - The Five C's of Cinematography by Joseph V. Mascelli
  4788. - Film Art: An Introduction by David Bordwell
  4789. - Sight, Sound, Motion by Herbert Zettl
  4790. - Notes on the Cinematograph by Robert Bresson
  4791. \n\n
  4792. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  4793. 示例格式:\n
  4794. 第1集:隐形的守护者
  4795. ###故事梗概
  4796. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4797. ###美术风格
  4798. 基础画风风格词:韩漫二次元
  4799. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4800. ###主体列表
  4801. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4802. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4803. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4804. ###场景列表
  4805. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4806. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4807. 无人物。}
  4808. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4809. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4810. 无人物。}
  4811. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4812. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4813. 无人物。}
  4814. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4815. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4816. 无人物。}
  4817. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4818. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4819. 无人物。}
  4820. ###分镜剧本
  4821. ##第1幕:徐家老旧厨房 白天 室内
  4822. 分镜1
  4823. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4824. 场景:徐家老旧厨房
  4825. 构图设计:全景,低角度仰视
  4826. 运镜调度:手持拍摄
  4827. 配音角色:旁白
  4828. 出镜角色:许芸-校服装、徐母
  4829. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4830. 画面类型:普通画面
  4831. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4832. 分镜2
  4833. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4834. 场景:徐家老旧厨房
  4835. 构图设计:近景,徐母面部特写
  4836. 运镜调度:固定镜头
  4837. 配音角色:徐母
  4838. 出镜角色:徐母
  4839. 台词内容:问我夜不归宿死哪儿去了。
  4840. 画面类型:对口型
  4841. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4842. ##第2幕:徐家简陋客厅 黄昏 室内
  4843. 分镜3
  4844. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4845. 场景:徐家简陋客厅
  4846. 构图设计:全景,景深虚化
  4847. 运镜调度:固定镜头
  4848. 配音角色:旁白
  4849. 出镜角色:无
  4850. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4851. 画面类型:普通画面
  4852. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4853. 分镜4
  4854. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4855. 场景:徐家简陋客厅
  4856. 构图设计:特写,火车票
  4857. 运镜调度:固定镜头
  4858. 配音角色:旁白
  4859. 出镜角色:无
  4860. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4861. 画面类型:普通画面
  4862. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4863. \n\n";
  4864. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4865. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  4866. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  4867. $prompt = $origin_prompt;
  4868. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  4869. // 获取章节内容
  4870. $full_content = getProp($anime, 'content');
  4871. if ($uploaded_content) {
  4872. $full_content = $uploaded_content;
  4873. }
  4874. // 根据章节内容拆分章节
  4875. $chapters = $this->splitContent($full_content);
  4876. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  4877. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  4878. $messages = [];
  4879. if ($prompt == '确认分镜大纲') {
  4880. // 暂时保留
  4881. $content = $chapter_content;
  4882. if ($is_single) $content = $full_content; // 单剧集使用全文
  4883. if (!$content) {
  4884. Utils::throwError('20003:章节内容无法获取,请确认');
  4885. }
  4886. $question = $is_single
  4887. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  4888. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  4889. // 构建消息
  4890. $messages[] =
  4891. [
  4892. 'role' => 'user',
  4893. 'content' => $question
  4894. ];
  4895. }else if ($prompt == '继续策划下一集') {
  4896. if ($is_single) {
  4897. Utils::throwError('20003:单剧集不支持继续策划下一集');
  4898. }
  4899. $content = $chapter_content;
  4900. if (!$content) {
  4901. Utils::throwError('20003:章节内容无法获取,请确认');
  4902. }
  4903. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  4904. // 获取上一集最后记录
  4905. $prev_sequence = $episode_number - 1;
  4906. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  4907. // 构建消息
  4908. $messages[] =
  4909. [
  4910. 'role' => 'user',
  4911. 'content' => $question
  4912. ];
  4913. }else {
  4914. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  4915. if (!$content) {
  4916. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  4917. }
  4918. if (!$content) {
  4919. Utils::throwError('20003:章节内容无法获取,请确认');
  4920. }
  4921. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  4922. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  4923. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  4924. if ($origin_prompt) {
  4925. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  4926. }
  4927. $messages[] =
  4928. [
  4929. 'role' => 'user',
  4930. 'content' => $question
  4931. ];
  4932. }
  4933. // 处理文本模型
  4934. $model = getProp($data, 'model');
  4935. if (!$model) {
  4936. // 用户没有输入,从anime表获取
  4937. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4938. $model = getProp($anime, 'model');
  4939. if (!$model) {
  4940. // anime表也没有,使用默认值
  4941. $model = 'doubao-seed-2-0-mini-260215';
  4942. }
  4943. }
  4944. // 验证模型是否在可用模型表中
  4945. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4946. $model = 'doubao-seed-2-0-mini-260215';
  4947. }
  4948. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4949. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4950. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4951. if ($model === 'deepseek-chat') {
  4952. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4953. $model = 'deepseek-v4-flash';
  4954. $thinkingMode = 'disabled';
  4955. } elseif ($model === 'deepseek-reasoner') {
  4956. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4957. $model = 'deepseek-v4-flash';
  4958. $thinkingMode = 'enabled';
  4959. }
  4960. $post_data = [
  4961. 'model' => $model,
  4962. 'messages' => $messages,
  4963. // 'max_tokens' => 8192,
  4964. 'temperature' => 0.2,
  4965. 'frequency_penalty' => 0,
  4966. 'presence_penalty' => 0,
  4967. 'response_format' => ['type' => 'text'],
  4968. 'thinking' => ['type' => $thinkingMode],
  4969. 'stream' => true // 启用流式输出
  4970. ];
  4971. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4972. // 根据模型类型选择调用方法
  4973. $fullContent = '';
  4974. $fullReasoningContent = '';
  4975. $usage = [];
  4976. try {
  4977. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4978. // DeepSeek 官方模型使用 DeepSeek API
  4979. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4980. } else if (in_array($model, $this->gpt_text_models)) {
  4981. // GPT-5.4 模型使用 TokenRouter API
  4982. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4983. } else {
  4984. // 其他模型使用火山引擎API
  4985. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4986. }
  4987. // 验证返回值类型
  4988. if (!is_iterable($streamGenerator)) {
  4989. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4990. dLog('deepseek')->error('chat流式生成器无效', [
  4991. 'generator_type' => $errorType,
  4992. 'model' => $model,
  4993. 'anime_id' => $anime_id,
  4994. 'episode_number' => $episode_number
  4995. ]);
  4996. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  4997. 'type' => $errorType,
  4998. 'model' => $model
  4999. ]);
  5000. yield [
  5001. 'type' => 'error',
  5002. 'episode' => [],
  5003. 'answer' => '',
  5004. 'reasoning' => '',
  5005. 'usage' => [],
  5006. 'error' => '接口返回数据异常,请重新请求'
  5007. ];
  5008. return;
  5009. }
  5010. // 处理流式输出
  5011. foreach ($streamGenerator as $chunk) {
  5012. if (isset($chunk['type'])) {
  5013. if ($chunk['type'] === 'done') {
  5014. // 最终结果
  5015. $fullContent = $chunk['full_content'];
  5016. $fullReasoningContent = $chunk['full_reasoning'];
  5017. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5018. } else {
  5019. // 逐块yield数据
  5020. yield $chunk;
  5021. }
  5022. }
  5023. }
  5024. } catch (\Exception $e) {
  5025. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  5026. 'model' => $model,
  5027. 'anime_id' => $anime_id,
  5028. 'episode_number' => $episode_number,
  5029. 'trace' => $e->getTraceAsString()
  5030. ]);
  5031. logDB('deepseek', 'error', 'chat流式处理失败', [
  5032. 'error' => $e->getMessage(),
  5033. 'model' => $model
  5034. ]);
  5035. yield [
  5036. 'type' => 'error',
  5037. 'episode' => [],
  5038. 'answer' => '',
  5039. 'reasoning' => '',
  5040. 'usage' => [],
  5041. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5042. ];
  5043. return;
  5044. }
  5045. dLog('deepseek')->info('完整内容: '.$fullContent);
  5046. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5047. // 处理完整内容并返回最终结果
  5048. $episode_arr = handleEpisodeContent($fullContent);
  5049. logDB('deepseek', 'info', '解析内容', $episode_arr);
  5050. if (empty($episode_arr['acts'])) {
  5051. // 未生成剧本相关内容,保存对话记录并返回提示
  5052. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  5053. try {
  5054. $now = date('Y-m-d H:i:s');
  5055. // 保存对话记录
  5056. $records = [
  5057. [
  5058. 'uid' => $uid,
  5059. 'anime_id' => $anime_id,
  5060. 'sequence' => $episode_number,
  5061. 'role' => 'user',
  5062. 'content' => $prompt,
  5063. 'created_at' => $now,
  5064. 'updated_at' => $now
  5065. ],
  5066. [
  5067. 'uid' => $uid,
  5068. 'anime_id' => $anime_id,
  5069. 'sequence' => $episode_number,
  5070. 'role' => 'assistant',
  5071. 'content' => $fullContent,
  5072. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5073. 'created_at' => $now,
  5074. 'updated_at' => $now
  5075. ]
  5076. ];
  5077. DB::table('mp_anime_records')->insert($records);
  5078. } catch (\Exception $e) {
  5079. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5080. }
  5081. yield [
  5082. 'type' => 'done',
  5083. 'episode' => [],
  5084. 'answer' => $fullContent,
  5085. 'reasoning' => $fullReasoningContent,
  5086. 'usage' => $usage,
  5087. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  5088. ];
  5089. return;
  5090. }
  5091. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  5092. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  5093. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  5094. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  5095. $now = date('Y-m-d H:i:s');
  5096. try {
  5097. DB::beginTransaction();
  5098. $saveResult = $this->saveEpisodeVersionData(
  5099. $anime_id,
  5100. $episode_number,
  5101. $episode_arr,
  5102. $existing_roles,
  5103. $existing_scenes,
  5104. $current_episode,
  5105. $base_episode,
  5106. $is_regenerate_version,
  5107. $content,
  5108. $now
  5109. );
  5110. $episode = $saveResult['episode'];
  5111. $episode_id = $saveResult['episode_id'];
  5112. $merged_roles = $saveResult['merged_roles'];
  5113. $merged_scenes = $saveResult['merged_scenes'];
  5114. $record_content = $origin_prompt;
  5115. if ($uploaded_content !== '') {
  5116. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  5117. }
  5118. $records = [
  5119. [
  5120. 'uid' => $uid,
  5121. 'anime_id' => $anime_id,
  5122. 'role' => 'user',
  5123. 'content' => $record_content,
  5124. 'sequence' => $episode_number,
  5125. 'episode_id' => $episode_id,
  5126. 'created_at' => $now,
  5127. 'updated_at' => $now
  5128. ],
  5129. [
  5130. 'uid' => $uid,
  5131. 'anime_id' => $anime_id,
  5132. 'role' => 'assistant',
  5133. 'content' => $fullContent,
  5134. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5135. 'sequence' => $episode_number,
  5136. 'episode_id' => $episode_id,
  5137. 'created_at' => $now,
  5138. 'updated_at' => $now
  5139. ]
  5140. ];
  5141. $boolen4 = DB::table('mp_anime_records')->insert($records);
  5142. if (!$boolen4) {
  5143. Utils::throwError('20003:对话记录保存失败');
  5144. }
  5145. // 保存模型和内容到anime表
  5146. $update_anime_data = [
  5147. 'model' => $model,
  5148. 'updated_at' => $now
  5149. ];
  5150. if ($uploaded_content) {
  5151. $update_anime_data['content'] = $uploaded_content;
  5152. }
  5153. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  5154. }catch (\Exception $e) {
  5155. DB::rollBack();
  5156. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5157. yield [
  5158. 'type' => 'done',
  5159. 'answer' => $fullContent,
  5160. 'reasoning' => $fullReasoningContent,
  5161. 'usage' => $usage,
  5162. 'error' => $e->getMessage(),
  5163. ];
  5164. return;
  5165. }
  5166. DB::commit();
  5167. if ($is_global_generate_pics) {
  5168. // // 批量生成全局角色图片
  5169. // $this->batchSetGlobalRoleImg([
  5170. // 'anime_id' => $anime_id,
  5171. // ], true);
  5172. // // 批量生成全局场景图片
  5173. // $this->batchSetGlobalSceneImg([
  5174. // 'anime_id' => $anime_id,
  5175. // ], true);
  5176. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5177. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5178. }
  5179. $episode['episode_id'] = $episode_id;
  5180. $episode['roles'] = $merged_roles;
  5181. $episode['scenes'] = $merged_scenes;
  5182. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  5183. yield [
  5184. 'type' => 'done',
  5185. 'episode' => $episode,
  5186. 'answer' => $fullContent,
  5187. 'reasoning' => $fullReasoningContent,
  5188. 'usage' => $usage
  5189. ];
  5190. }
  5191. public function addChatForAce($data) {
  5192. $uid = Site::getUid();
  5193. $anime_id = getProp($data, 'anime_id');
  5194. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5195. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5196. if (!$anime) Utils::throwError('20003:对话不存在');
  5197. $file = getProp($data, 'file');
  5198. $content = getProp($data, 'content', '');
  5199. $bid = getProp($data, 'bid', 0);
  5200. $script_id = getProp($data, 'script_id', 0);
  5201. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5202. $prompt = getProp($data, 'prompt');
  5203. $extra_products = getProp($data, 'products', []);
  5204. if (!$extra_products) {
  5205. $extra_products = getProp($anime, 'extra_products');
  5206. if ($extra_products) {
  5207. $extra_products = json_decode($extra_products, true);
  5208. }else {
  5209. $extra_products = [];
  5210. }
  5211. }else {
  5212. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  5213. }
  5214. $user_anime_name = getProp($anime, 'anime_name');
  5215. // 处理提示词
  5216. if ($prompt && $extra_products) {
  5217. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  5218. foreach($extra_products as $item) {
  5219. $product_name = getProp($item, 'product_name');
  5220. if ($product_name) {
  5221. // 替换 {product_name} 为 product_name
  5222. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  5223. }
  5224. }
  5225. }
  5226. // 处理文本模型
  5227. $model = getProp($data, 'model');
  5228. if (!$model) {
  5229. // 用户没有输入,从anime表获取
  5230. $model = getProp($anime, 'model');
  5231. if (!$model) {
  5232. // anime表也没有,使用默认值
  5233. $model = 'doubao-seed-2-0-mini-260215';
  5234. }
  5235. }
  5236. // 验证模型是否在可用模型表中
  5237. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5238. $model = 'doubao-seed-2-0-mini-260215';
  5239. }
  5240. $is_multi = getProp($anime, 'is_multi');
  5241. $is_single = (int)$is_multi !== 1;
  5242. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  5243. if ($prompt) {
  5244. $question .= "本次修改要求如下:\n{$prompt}";
  5245. }
  5246. // if (!$file && !$content && !$bid) {
  5247. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5248. // }
  5249. // 提取文件内容
  5250. if ($file) {
  5251. $content = $this->extractFileContent($file);
  5252. if (!$content) {
  5253. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5254. }
  5255. } elseif ($script_id) {
  5256. $content = $this->getContentByScriptId($script_id);
  5257. if (!$content) {
  5258. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5259. }
  5260. } elseif ($bid) {
  5261. $content = $this->getContentByBid($bid);
  5262. if (!$content) {
  5263. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5264. }
  5265. } elseif ($content) {
  5266. $content = filterContent($content);
  5267. } else {
  5268. $content = getProp($anime, 'content');
  5269. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5270. $need_generate_content = true;
  5271. }
  5272. }
  5273. // 美术风格
  5274. $input_art_style = getProp($data, 'art_style');
  5275. if (!$input_art_style) {
  5276. $mappedArtStyle = getProp($anime, 'art_style');
  5277. }else {
  5278. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5279. }
  5280. // 判断是否需要生成原文内容
  5281. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5282. // 如果需要生成原文内容,添加额外的要求
  5283. $content_generation_requirement = $need_generate_content
  5284. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5285. : "";
  5286. // 美术风格
  5287. if (!$mappedArtStyle) {
  5288. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5289. }else {
  5290. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5291. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5292. }else {
  5293. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5294. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5295. }
  5296. }
  5297. // 构建主体和场景提示词
  5298. $extra_role_prompt = "\n";
  5299. $extra_scene_prompt = "\n";
  5300. $ref_products = []; // 参考资产
  5301. if ($extra_products) {
  5302. foreach($extra_products as $item) {
  5303. $product = getProp($item, 'product');
  5304. $product_name = getProp($item, 'product_name');
  5305. if ($product_name == '旁白') continue;
  5306. $ref_products[$product_name] = $item;
  5307. $pic_prompt = getProp($item, 'pic_prompt');
  5308. if ((int)$product === 1) {
  5309. // 拼接角色信息
  5310. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5311. } elseif ((int)$product === 2) {
  5312. // 拼接场景信息
  5313. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5314. }
  5315. }
  5316. // 优化提示词,融入剧本
  5317. if (!empty(trim($extra_role_prompt))) {
  5318. $extra_role_prompt = "\n2.5【强制主体设定-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  5319. }
  5320. if (!empty(trim($extra_scene_prompt))) {
  5321. $extra_scene_prompt = "\n3.4【强制场景设定-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  5322. }
  5323. }
  5324. $systemPrompt = $is_single
  5325. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5326. 强制要求:
  5327. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5328. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5329. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5330. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5331. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5332. 普通要求:
  5333. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5334. 3.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5335. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5336. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5337. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5338. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5339. {$extra_role_prompt}
  5340. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5341. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5342. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5343. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5344. {$extra_scene_prompt}
  5345. 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  5346. 4.1片段分割逻辑(优先级从高到低):
  5347. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  5348. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  5349. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  5350. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  5351. 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  5352. - 片段数量格式为: 片段数量:8
  5353. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5354. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  5355. 4.3分镜结构:每个分镜包含以下字段:
  5356. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  5357. - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  5358. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  5359. - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  5360. - 运镜:场景+画面描述+运镜
  5361. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  5362. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  5363. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  5364. 5.{$mappedArtStyle_prompt}\n\n
  5365. 示例如下:\n
  5366. ###剧本名:西昆仑
  5367. ###故事梗概
  5368. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5369. ###剧本亮点
  5370. 亮点1:绝境奇药,生死一线
  5371. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5372. 亮点2:结拜兄妹,化解尴尬
  5373. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5374. 亮点3:纤发夺命,情愫暗涌
  5375. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5376. ###人物关系
  5377. 阿雪与梁萧之间存在兄妹之情。
  5378. ###核心矛盾
  5379. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5380. ###主体列表
  5381. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5382. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5383. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5384. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5385. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5386. 全景,正面拍摄,青年女性,亚洲人。
  5387. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5388. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5389. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5390. ###美术风格
  5391. 基础画风风格词:厚涂古风
  5392. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5393. ###场景列表
  5394. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5395. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5396. 无人物。}
  5397. ###分段剧本
  5398. 片段数量:8
  5399. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  5400. ##片段1
  5401. 时长:12s
  5402. 分镜1
  5403. 场景:边境小镇街道
  5404. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  5405. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  5406. 配音台词:
  5407. 背景音效:
  5408. 分镜2
  5409. 场景:悦来酒馆
  5410. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  5411. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  5412. 配音台词:
  5413. 背景音效:
  5414. 分镜3
  5415. 场景:悦来酒馆
  5416. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  5417. 运镜:从中景推向令牌特写。
  5418. 配音台词:
  5419. 背景音效:
  5420. 分镜4
  5421. 场景:悦来酒馆
  5422. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  5423. 运镜:极速推向酒水溅起的瞬间。
  5424. 配音台词:
  5425. 背景音效:
  5426. 分镜5
  5427. 镜头描述
  5428. 场景:悦来酒馆
  5429. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  5430. 运镜:固定机位,利用倾斜构图制造压迫感。
  5431. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  5432. 背景音效:
  5433. \n\n"
  5434. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5435. 强制要求:\n
  5436. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5437. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5438. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5439. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5440. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5441. 普通要求:\n
  5442. 1.剧本名(必须生成)必须与文档内容高度相关
  5443. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5444. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5445. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5446. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5447. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5448. {$extra_role_prompt}
  5449. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5450. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5451. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5452. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5453. {$extra_scene_prompt}
  5454. 4.{$mappedArtStyle_prompt}\n\n
  5455. 示例如下:\n
  5456. ###剧本名:西昆仑
  5457. ###故事梗概
  5458. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5459. ###剧本亮点
  5460. 亮点1:绝境奇药,生死一线
  5461. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5462. 亮点2:结拜兄妹,化解尴尬
  5463. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5464. 亮点3:纤发夺命,情愫暗涌
  5465. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5466. ###人物关系
  5467. 阿雪与梁萧之间存在兄妹之情。
  5468. ###核心矛盾
  5469. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5470. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5471. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  5472. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  5473. ###主体列表
  5474. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5475. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5476. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5477. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5478. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5479. 全景,正面拍摄,青年女性,亚洲人。
  5480. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5481. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5482. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5483. ###美术风格
  5484. 基础画风风格词:厚涂古风
  5485. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5486. ###场景列表
  5487. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5488. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5489. 无人物。}";
  5490. // 构建消息
  5491. $messages = [
  5492. [
  5493. 'role' => 'system',
  5494. 'content' => $systemPrompt
  5495. ],
  5496. [
  5497. 'role' => 'user',
  5498. 'content' => "以下是文档内容:
  5499. {$content}
  5500. 用户问题:
  5501. {$question}"
  5502. ]
  5503. ];
  5504. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5505. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5506. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5507. if ($model === 'deepseek-chat') {
  5508. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5509. $model = 'deepseek-v4-flash';
  5510. $thinkingMode = 'disabled';
  5511. } elseif ($model === 'deepseek-reasoner') {
  5512. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5513. $model = 'deepseek-v4-flash';
  5514. $thinkingMode = 'enabled';
  5515. }
  5516. $post_data = [
  5517. 'model' => $model,
  5518. 'messages' => $messages,
  5519. // 'max_tokens' => 8192,
  5520. 'temperature' => 0.7,
  5521. 'frequency_penalty' => 0,
  5522. 'presence_penalty' => 0,
  5523. 'response_format' => ['type' => 'text'],
  5524. 'thinking' => ['type'=>$thinkingMode],
  5525. 'stream' => true // 启用流式输出
  5526. ];
  5527. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5528. // 根据模型类型选择调用方法
  5529. $fullContent = '';
  5530. $fullReasoningContent = '';
  5531. $usage = [];
  5532. try {
  5533. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5534. // DeepSeek 官方模型使用 DeepSeek API
  5535. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5536. } else if (in_array($model, $this->gpt_text_models)) {
  5537. // GPT-5.4 模型使用 TokenRouter API
  5538. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5539. } else {
  5540. // 其他模型使用火山引擎API
  5541. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5542. }
  5543. // 验证返回值类型
  5544. if (!is_iterable($streamGenerator)) {
  5545. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5546. dLog('deepseek')->error('addChat流式生成器无效', [
  5547. 'generator_type' => $errorType,
  5548. 'model' => $model,
  5549. 'anime_id' => $anime_id
  5550. ]);
  5551. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5552. 'type' => $errorType,
  5553. 'model' => $model
  5554. ]);
  5555. yield [
  5556. 'type' => 'error',
  5557. 'script' => [],
  5558. 'episode' => [],
  5559. 'answer' => '',
  5560. 'reasoning' => '',
  5561. 'usage' => [],
  5562. 'error' => '接口返回数据异常,请重新请求'
  5563. ];
  5564. return;
  5565. }
  5566. // 处理流式输出
  5567. foreach ($streamGenerator as $chunk) {
  5568. if (isset($chunk['type'])) {
  5569. if ($chunk['type'] === 'done') {
  5570. // 最终结果
  5571. $fullContent = $chunk['full_content'];
  5572. $fullReasoningContent = $chunk['full_reasoning'];
  5573. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5574. } else {
  5575. // 逐块yield数据
  5576. yield $chunk;
  5577. }
  5578. }
  5579. }
  5580. } catch (\Exception $e) {
  5581. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5582. 'model' => $model,
  5583. 'anime_id' => $anime_id,
  5584. 'trace' => $e->getTraceAsString()
  5585. ]);
  5586. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5587. 'error' => $e->getMessage(),
  5588. 'model' => $model
  5589. ]);
  5590. yield [
  5591. 'type' => 'error',
  5592. 'script' => [],
  5593. 'episode' => [],
  5594. 'answer' => '',
  5595. 'reasoning' => '',
  5596. 'usage' => [],
  5597. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5598. ];
  5599. return;
  5600. }
  5601. dLog('deepseek')->info('完整内容: '.$fullContent);
  5602. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5603. // 处理完整内容并返回最终结果
  5604. $script_arr = [];
  5605. if ($fullContent) {
  5606. $script_arr = handleScriptContentForAce($fullContent);
  5607. dLog('deepseek')->info('解析内容', $script_arr);
  5608. logDB('deepseek', 'info', '解析内容', $script_arr);
  5609. }
  5610. if (empty($script_arr['roles'])) {
  5611. // 未生成剧本相关内容,保存对话记录并返回提示
  5612. dLog('deepseek')->info('未生成剧本相关的内容');
  5613. try {
  5614. DB::beginTransaction();
  5615. $now = date('Y-m-d H:i:s');
  5616. // 保存对话记录
  5617. $records = [
  5618. [
  5619. 'uid' => $uid,
  5620. 'anime_id' => $anime_id,
  5621. 'sequence' => 0,
  5622. 'role' => 'user',
  5623. 'content' => $prompt,
  5624. 'created_at' => $now,
  5625. 'updated_at' => $now
  5626. ],
  5627. [
  5628. 'uid' => $uid,
  5629. 'anime_id' => $anime_id,
  5630. 'sequence' => 0,
  5631. 'role' => 'assistant',
  5632. // 'content' => $fullContent,
  5633. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5634. 'created_at' => $now,
  5635. 'updated_at' => $now
  5636. ]
  5637. ];
  5638. DB::table('mp_anime_records')->insert($records);
  5639. DB::commit();
  5640. } catch (\Exception $e) {
  5641. DB::rollBack();
  5642. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5643. }
  5644. yield [
  5645. 'type' => 'done',
  5646. 'script' => [],
  5647. 'episode' => [],
  5648. 'answer' => $fullContent,
  5649. 'reasoning' => $fullReasoningContent,
  5650. 'usage' => $usage,
  5651. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5652. ];
  5653. return;
  5654. }
  5655. // 如果需要生成原文内容,从script_arr中提取
  5656. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5657. $content = $script_arr['content'];
  5658. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5659. if (!$content) {
  5660. yield [
  5661. 'type' => 'done',
  5662. 'script' => [],
  5663. 'episode' => [],
  5664. 'answer' => $fullContent,
  5665. 'reasoning' => $fullReasoningContent,
  5666. 'usage' => $usage,
  5667. 'error' => '未生成剧本内容,请调整提示词再试'
  5668. ];
  5669. return;
  5670. }
  5671. }
  5672. // 替换美术风格
  5673. if ($mappedArtStyle !== '') {
  5674. $script_arr['art_style'] = $mappedArtStyle;
  5675. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5676. }
  5677. // 新建动漫
  5678. if ($user_anime_name == '新剧本策划') {
  5679. $anime_name = getProp($script_arr, 'script_name');
  5680. // if (!$anime_name) {
  5681. // // 未识别到剧本名,保存对话记录并返回提示
  5682. // dLog('deepseek')->info('未能识别到剧本名称');
  5683. // try {
  5684. // DB::beginTransaction();
  5685. // $now = date('Y-m-d H:i:s');
  5686. // // 保存对话记录
  5687. // $records = [
  5688. // [
  5689. // 'uid' => $uid,
  5690. // 'anime_id' => $anime_id,
  5691. // 'sequence' => 0,
  5692. // 'role' => 'user',
  5693. // 'content' => $prompt,
  5694. // 'created_at' => $now,
  5695. // 'updated_at' => $now
  5696. // ],
  5697. // [
  5698. // 'uid' => $uid,
  5699. // 'anime_id' => $anime_id,
  5700. // 'sequence' => 0,
  5701. // 'role' => 'assistant',
  5702. // 'content' => '未能生成剧本名称,请重试',
  5703. // 'created_at' => $now,
  5704. // 'updated_at' => $now
  5705. // ]
  5706. // ];
  5707. // DB::table('mp_anime_records')->insert($records);
  5708. // DB::commit();
  5709. // } catch (\Exception $e) {
  5710. // DB::rollBack();
  5711. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5712. // }
  5713. // yield [
  5714. // 'type' => 'done',
  5715. // 'script' => [],
  5716. // 'episode' => [],
  5717. // 'answer' => $fullContent,
  5718. // 'reasoning' => $fullReasoningContent,
  5719. // 'usage' => $usage,
  5720. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  5721. // ];
  5722. // return;
  5723. // }
  5724. // 确认对话名称唯一性
  5725. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5726. $anime_name = $anime_name . '_' . date('YmdHis');
  5727. }
  5728. }else {
  5729. $anime_name = $user_anime_name;
  5730. }
  5731. $table_data = [
  5732. 'user_id' => $uid,
  5733. 'anime_name' => $anime_name,
  5734. 'model' => $model,
  5735. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5736. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5737. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5738. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5739. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5740. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5741. 'art_style_type' => $input_art_style,
  5742. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5743. 'status' => '解析完成',
  5744. 'content' => $content,
  5745. 'is_multi' => $is_multi,
  5746. 'ace_mode' => $ace_mode,
  5747. 'generate_status' => '待执行',
  5748. 'updated_at' => date('Y-m-d H:i:s')
  5749. ];
  5750. if ($table_data['content']) {
  5751. $chapters = $this->splitContent($table_data['content']);
  5752. $chapter_count = count($chapters);
  5753. if ($chapter_count > 0) {
  5754. $table_data['start_episode_sequence'] = 1;
  5755. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5756. }
  5757. }
  5758. if ($extra_products) {
  5759. $table_data['extra_products'] = json_encode($extra_products, 256);
  5760. }
  5761. // 如果有剧本ID则进行绑定
  5762. if ($script_id) {
  5763. $table_data['script_id'] = $script_id;
  5764. }
  5765. $single_episode = [];
  5766. try {
  5767. DB::beginTransaction();
  5768. $now = date('Y-m-d H:i:s');
  5769. // 更新动漫大纲
  5770. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5771. if (!$boolen) {
  5772. dLog('deepseek')->info('动漫保存失败', $table_data);
  5773. Utils::throwError('20003:动漫保存失败');
  5774. }
  5775. // 保存对话记录
  5776. $records = [
  5777. [
  5778. 'uid' => $uid,
  5779. 'anime_id' => $anime_id,
  5780. 'sequence' => 0,
  5781. 'role' => 'user',
  5782. 'content' => $prompt,
  5783. 'created_at' => date('Y-m-d H:i:s'),
  5784. 'updated_at' => date('Y-m-d H:i:s')
  5785. ],
  5786. [
  5787. 'uid' => $uid,
  5788. 'anime_id' => $anime_id,
  5789. 'sequence' => 0,
  5790. 'role' => 'assistant',
  5791. 'content' => $fullContent,
  5792. 'created_at' => date('Y-m-d H:i:s'),
  5793. 'updated_at' => date('Y-m-d H:i:s')
  5794. ]
  5795. ];
  5796. // 保存对话记录
  5797. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5798. if (!$boolen3) {
  5799. Utils::throwError('20003:对话记录保存失败');
  5800. }
  5801. if ($is_single) {
  5802. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5803. if (empty($episode_arr['acts'])) {
  5804. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5805. }
  5806. $saveResult = $this->saveEpisodeVersionData(
  5807. $anime_id,
  5808. 1,
  5809. $episode_arr,
  5810. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5811. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5812. null,
  5813. null,
  5814. false,
  5815. $content,
  5816. $now,
  5817. $ref_products
  5818. );
  5819. $single_episode = $saveResult['episode'];
  5820. $episode_id = $saveResult['episode_id'];
  5821. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5822. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5823. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5824. 'updated_at' => $now
  5825. ]);
  5826. if ($boolen5 === false) {
  5827. Utils::throwError('20003:单剧集主表资源同步失败');
  5828. }
  5829. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5830. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5831. $episode_record_content = '确认分镜大纲';
  5832. if ($content !== '') {
  5833. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5834. }
  5835. $episode_records = [
  5836. [
  5837. 'uid' => $uid,
  5838. 'anime_id' => $anime_id,
  5839. 'role' => 'user',
  5840. 'content' => $episode_record_content,
  5841. 'sequence' => 1,
  5842. 'episode_id' => $episode_id,
  5843. 'created_at' => $now,
  5844. 'updated_at' => $now
  5845. ],
  5846. [
  5847. 'uid' => $uid,
  5848. 'anime_id' => $anime_id,
  5849. 'role' => 'assistant',
  5850. 'content' => $fullContent,
  5851. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5852. 'sequence' => 1,
  5853. 'episode_id' => $episode_id,
  5854. 'created_at' => $now,
  5855. 'updated_at' => $now
  5856. ]
  5857. ];
  5858. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5859. if (!$boolen4) {
  5860. Utils::throwError('20003:单剧集分镜记录保存失败');
  5861. }
  5862. }
  5863. }catch (\Exception $e) {
  5864. DB::rollBack();
  5865. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5866. yield [
  5867. 'type' => 'done',
  5868. 'answer' => $fullContent,
  5869. 'reasoning' => $fullReasoningContent,
  5870. 'usage' => $usage,
  5871. 'error' => $e->getMessage(),
  5872. ];
  5873. return;
  5874. }
  5875. DB::commit();
  5876. dLog('deepseek')->info('保存完毕');
  5877. if ($is_single && !empty($single_episode)) {
  5878. // $this->batchSetGlobalRoleImg([
  5879. // 'anime_id' => $anime_id,
  5880. // ]);
  5881. // $this->batchSetGlobalSceneImg([
  5882. // 'anime_id' => $anime_id,
  5883. // ]);
  5884. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5885. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5886. }
  5887. $table_data['anime_id'] = $anime_id;
  5888. $table_data['roles'] = json_decode($table_data['roles'], true);
  5889. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5890. // $table_data['episodes'] = $script_arr['episodes'];
  5891. unset($table_data['created_at']);
  5892. unset($table_data['updated_at']);
  5893. unset($table_data['status']);
  5894. dLog('deepseek')->info('开始返回');
  5895. yield [
  5896. 'type' => 'done',
  5897. 'script' => $table_data,
  5898. 'episode' => $single_episode,
  5899. 'answer' => $fullContent,
  5900. 'reasoning' => $fullReasoningContent,
  5901. 'usage' => $usage
  5902. ];
  5903. }
  5904. public function reGenerateAnimeForAce($data) {
  5905. $uid = Site::getUid();
  5906. $file = getProp($data, 'file');
  5907. $content = getProp($data, 'content', '');
  5908. $bid = getProp($data, 'bid', 0);
  5909. $script_id = getProp($data, 'script_id', 0);
  5910. $anime_id = getProp($data, 'anime_id');
  5911. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5912. if (!$anime) {
  5913. Utils::throwError('20003:该对话不存在');
  5914. }
  5915. $extra_products = getProp($data, 'products', []);
  5916. if (!$extra_products) {
  5917. $extra_products = getProp($anime, 'extra_products');
  5918. if ($extra_products) {
  5919. $extra_products = json_decode($extra_products, true);
  5920. }else {
  5921. $extra_products = [];
  5922. }
  5923. }else {
  5924. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  5925. }
  5926. $user_anime_name = getProp($anime, 'anime_name');
  5927. $prompt = getProp($data, 'prompt');
  5928. // 处理提示词
  5929. if ($prompt && $extra_products) {
  5930. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  5931. foreach($extra_products as $item) {
  5932. $product_name = getProp($item, 'product_name');
  5933. if ($product_name) {
  5934. // 替换 {product_name} 为 product_name
  5935. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  5936. }
  5937. }
  5938. }
  5939. // 处理文本模型
  5940. $model = getProp($data, 'model');
  5941. if (!$model) {
  5942. // 用户没有输入,从anime表获取
  5943. $model = getProp($anime, 'model');
  5944. if (!$model) {
  5945. // anime表也没有,使用默认值
  5946. $model = 'doubao-seed-2-0-mini-260215';
  5947. }
  5948. }
  5949. // 验证模型是否在可用模型表中
  5950. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5951. $model = 'doubao-seed-2-0-mini-260215';
  5952. }
  5953. $is_multi = getProp($anime, 'is_multi', 1);
  5954. $is_single = (int)$is_multi !== 1;
  5955. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  5956. if ($is_single) {
  5957. $episode_exists = DB::table('mp_anime_episodes')
  5958. ->where('anime_id', $anime_id)
  5959. ->where('sequence', 1)
  5960. ->exists();
  5961. if ($episode_exists) {
  5962. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  5963. }
  5964. }
  5965. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  5966. if ($prompt) {
  5967. $question .= "本次修改要求如下:\n{$prompt}";
  5968. }
  5969. // 提取文件内容
  5970. if ($file) {
  5971. $content = $this->extractFileContent($file);
  5972. if (!$content) {
  5973. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5974. }
  5975. } elseif ($script_id) {
  5976. $content = $this->getContentByScriptId($script_id);
  5977. if (!$content) {
  5978. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5979. }
  5980. } elseif ($bid) {
  5981. $content = $this->getContentByBid($bid);
  5982. if (!$content) {
  5983. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5984. }
  5985. } elseif ($content) {
  5986. $content = filterContent($content);
  5987. }else {
  5988. $content = filterContent(getProp($anime, 'content'));
  5989. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5990. $need_generate_content = true;
  5991. }
  5992. }
  5993. // 判断是否需要生成原文内容
  5994. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5995. // 如果需要生成原文内容,添加额外的要求
  5996. $content_generation_requirement = $need_generate_content
  5997. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5998. : "";
  5999. // 美术风格
  6000. $input_art_style = getProp($data, 'art_style');
  6001. if (!$input_art_style) {
  6002. $mappedArtStyle = getProp($anime, 'art_style');
  6003. }else {
  6004. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6005. }
  6006. if (!$mappedArtStyle) {
  6007. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6008. }else {
  6009. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6010. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6011. }else {
  6012. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6013. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6014. }
  6015. }
  6016. // 构建主体和场景提示词
  6017. $extra_role_prompt = "\n";
  6018. $extra_scene_prompt = "\n";
  6019. $ref_products = []; // 参考资产
  6020. if ($extra_products) {
  6021. foreach($extra_products as $item) {
  6022. $product = getProp($item, 'product');
  6023. $product_name = getProp($item, 'product_name');
  6024. if ($product_name == '旁白') continue;
  6025. $ref_products[$product_name] = $item;
  6026. $pic_prompt = getProp($item, 'pic_prompt');
  6027. if ((int)$product === 1) {
  6028. // 拼接角色信息
  6029. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6030. } elseif ((int)$product === 2) {
  6031. // 拼接场景信息
  6032. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6033. }
  6034. }
  6035. // 优化提示词,融入剧本
  6036. if (!empty(trim($extra_role_prompt))) {
  6037. $extra_role_prompt = "\n2.5【强制主体设定-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6038. }
  6039. if (!empty(trim($extra_scene_prompt))) {
  6040. $extra_scene_prompt = "\n3.4【强制场景设定-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6041. }
  6042. }
  6043. $system_message = ['role'=>'system', 'content'=>$is_single
  6044. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6045. 强制要求:
  6046. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6047. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6048. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6049. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6050. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6051. 普通要求:
  6052. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6053. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6054. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6055. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6056. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6057. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6058. {$extra_role_prompt}
  6059. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6060. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6061. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6062. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6063. {$extra_scene_prompt}
  6064. 3.$mappedArtStyle_prompt\n\n
  6065. 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6066. 4.1片段分割逻辑(优先级从高到低):
  6067. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6068. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6069. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6070. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6071. 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6072. - 片段数量格式为: 片段数量:8
  6073. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6074. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6075. 4.3分镜结构:每个分镜包含以下字段:
  6076. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  6077. - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  6078. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6079. - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  6080. - 运镜:场景+画面描述+运镜
  6081. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  6082. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6083. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6084. 示例如下:\n
  6085. ###剧本名:西昆仑
  6086. ###故事梗概
  6087. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6088. ###剧本亮点
  6089. 亮点1:绝境奇药,生死一线
  6090. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6091. 亮点2:结拜兄妹,化解尴尬
  6092. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6093. 亮点3:纤发夺命,情愫暗涌
  6094. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6095. ###人物关系
  6096. 阿雪与梁萧之间存在兄妹之情。
  6097. ###核心矛盾
  6098. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6099. ###主体列表
  6100. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6101. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6102. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6103. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6104. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6105. 全景,正面拍摄,青年女性,亚洲人。
  6106. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6107. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6108. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6109. ###美术风格
  6110. 基础画风风格词:厚涂古风
  6111. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6112. ###场景列表
  6113. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6114. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6115. 无人物。}
  6116. ###分段剧本
  6117. 片段数量:8
  6118. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6119. ##片段1
  6120. 时长:12s
  6121. 分镜1
  6122. 场景:边境小镇街道
  6123. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6124. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6125. 配音台词:
  6126. 背景音效:
  6127. 分镜2
  6128. 场景:悦来酒馆
  6129. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6130. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6131. 配音台词:
  6132. 背景音效:
  6133. 分镜3
  6134. 场景:悦来酒馆
  6135. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6136. 运镜:从中景推向令牌特写。
  6137. 配音台词:
  6138. 背景音效:
  6139. 分镜4
  6140. 场景:悦来酒馆
  6141. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6142. 运镜:极速推向酒水溅起的瞬间。
  6143. 配音台词:
  6144. 背景音效:
  6145. 分镜5
  6146. 镜头描述
  6147. 场景:悦来酒馆
  6148. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6149. 运镜:固定机位,利用倾斜构图制造压迫感。
  6150. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6151. 背景音效:
  6152. \n\n"
  6153. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6154. 强制要求:\n
  6155. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6156. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6157. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6158. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6159. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6160. 普通要求:\n
  6161. 1.剧本名(必须生成)必须与文档内容高度相关
  6162. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6163. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6164. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6165. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6166. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6167. {$extra_role_prompt}
  6168. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6169. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6170. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6171. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6172. {$extra_scene_prompt}
  6173. 4.$mappedArtStyle_prompt\n\n
  6174. 示例如下:\n
  6175. ###剧本名:西昆仑
  6176. ###故事梗概
  6177. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6178. ###剧本亮点
  6179. 亮点1:绝境奇药,生死一线
  6180. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6181. 亮点2:结拜兄妹,化解尴尬
  6182. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6183. 亮点3:纤发夺命,情愫暗涌
  6184. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6185. ###人物关系
  6186. 阿雪与梁萧之间存在兄妹之情。
  6187. ###核心矛盾
  6188. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6189. ###主体列表
  6190. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6191. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6192. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6193. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6194. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6195. 全景,正面拍摄,青年女性,亚洲人。
  6196. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6197. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6198. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6199. ###美术风格
  6200. 基础画风风格词:厚涂古风
  6201. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6202. ###场景列表
  6203. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6204. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6205. 无人物。}"];
  6206. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6207. $episode_count = $this->extractEpisodeNumber($prompt);
  6208. if ((int)getProp($anime, 'is_multi') !== 1) {
  6209. yield [
  6210. 'type' => 'done',
  6211. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6212. 'reasoning' => '',
  6213. 'usage' => []
  6214. ];
  6215. return;
  6216. }
  6217. if ($episode_count) {
  6218. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6219. $system_message = [
  6220. 'role' => 'system',
  6221. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6222. 强制要求:\n
  6223. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6224. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6225. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6226. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6227. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6228. 普通要求:\n
  6229. 1.<故事梗概>控制在200-300字左右
  6230. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6231. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6232. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6233. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6234. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6235. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6236. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6237. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6238. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6239. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6240. 示例如下:\n
  6241. ###剧本名:西昆仑
  6242. ###故事梗概
  6243. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6244. ###剧本亮点
  6245. 亮点1:绝境奇药,生死一线
  6246. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6247. 亮点2:结拜兄妹,化解尴尬
  6248. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6249. 亮点3:纤发夺命,情愫暗涌
  6250. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6251. ###人物关系
  6252. 阿雪与梁萧之间存在兄妹之情。
  6253. ###核心矛盾
  6254. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6255. ###主体列表
  6256. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6257. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6258. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6259. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6260. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6261. 全景,正面拍摄,青年女性,亚洲人。
  6262. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6263. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6264. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6265. ###美术风格
  6266. 基础画风风格词:厚涂古风
  6267. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6268. ###场景列表
  6269. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6270. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6271. 无人物。}
  6272. ###分集详细内容
  6273. ##第1章 重生
  6274. 我重生了。
  6275. 源于一个男人偏执的暗恋。
  6276. ##第2章 相救
  6277. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6278. 我眼睛扫向站在锅炉后的卞大伟。"
  6279. ];
  6280. // 构建消息
  6281. $messages = [
  6282. $system_message,
  6283. [
  6284. 'role' => 'user',
  6285. 'content' => "以下是文档内容:
  6286. {$content}
  6287. 用户问题:
  6288. {$question}"
  6289. ]
  6290. ];
  6291. }else {
  6292. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6293. // 构建消息
  6294. $messages = [
  6295. $system_message,
  6296. [
  6297. 'role' => 'user',
  6298. 'content' => "以下是文档内容:
  6299. {$content}
  6300. 用户问题:
  6301. {$question}"
  6302. ]
  6303. ];
  6304. }else {
  6305. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6306. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6307. return (array)$value;
  6308. })->toArray();
  6309. array_unshift($messages, $system_message);
  6310. $messages[] = [
  6311. 'role' => 'user',
  6312. 'content' => $prompt
  6313. ];
  6314. }
  6315. }
  6316. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6317. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6318. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6319. if ($model === 'deepseek-chat') {
  6320. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6321. $model = 'deepseek-v4-flash';
  6322. $thinkingMode = 'disabled';
  6323. } elseif ($model === 'deepseek-reasoner') {
  6324. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6325. $model = 'deepseek-v4-flash';
  6326. $thinkingMode = 'enabled';
  6327. }
  6328. $post_data = [
  6329. 'model' => $model,
  6330. 'messages' => $messages,
  6331. // 'max_tokens' => 8192,
  6332. 'temperature' => 0.7,
  6333. 'frequency_penalty' => 0,
  6334. 'presence_penalty' => 0,
  6335. 'response_format' => ['type' => 'text'],
  6336. 'thinking' => ['type' => $thinkingMode],
  6337. 'stream' => true // 启用流式输出
  6338. ];
  6339. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6340. // 根据模型类型选择调用方法
  6341. $fullContent = '';
  6342. $fullReasoningContent = '';
  6343. $usage = [];
  6344. // dd($post_data);
  6345. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6346. try {
  6347. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6348. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6349. } else if (in_array($model, $this->gpt_text_models)) {
  6350. // GPT-5.4 模型使用 TokenRouter API
  6351. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6352. } else {
  6353. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6354. }
  6355. // 验证返回值类型
  6356. if (!is_iterable($streamGenerator)) {
  6357. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6358. dLog('deepseek')->error('方法名流式生成器无效', [
  6359. 'generator_type' => $errorType,
  6360. 'model' => $model,
  6361. // 添加其他上下文信息
  6362. ]);
  6363. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6364. 'type' => $errorType,
  6365. 'model' => $model
  6366. ]);
  6367. yield [
  6368. 'type' => 'error',
  6369. // 根据方法返回相应的空数据结构
  6370. 'answer' => '',
  6371. 'reasoning' => '',
  6372. 'usage' => [],
  6373. 'error' => '接口返回数据异常,请重新请求'
  6374. ];
  6375. return;
  6376. }
  6377. // 处理流式输出
  6378. foreach ($streamGenerator as $chunk) {
  6379. if (isset($chunk['type'])) {
  6380. if ($chunk['type'] === 'done') {
  6381. $fullContent = $chunk['full_content'];
  6382. $fullReasoningContent = $chunk['full_reasoning'];
  6383. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6384. } else {
  6385. yield $chunk;
  6386. }
  6387. }
  6388. }
  6389. } catch (\Exception $e) {
  6390. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6391. 'model' => $model,
  6392. 'trace' => $e->getTraceAsString()
  6393. ]);
  6394. logDB('deepseek', 'error', '方法名流式处理失败', [
  6395. 'error' => $e->getMessage(),
  6396. 'model' => $model
  6397. ]);
  6398. yield [
  6399. 'type' => 'error',
  6400. // 根据方法返回相应的空数据结构
  6401. 'answer' => '',
  6402. 'reasoning' => '',
  6403. 'usage' => [],
  6404. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6405. ];
  6406. return;
  6407. }
  6408. dLog('deepseek')->info('完整内容: '.$fullContent);
  6409. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6410. // 处理完整内容并返回最终结果
  6411. $script_arr = [];
  6412. if ($fullContent) {
  6413. $script_arr = handleScriptContentForAce($fullContent);
  6414. dLog('deepseek')->info('解析内容', $script_arr);
  6415. logDB('deepseek', 'info', '解析内容', $script_arr);
  6416. }
  6417. if (empty($script_arr['roles'])) {
  6418. // 未生成剧本相关内容,保存对话记录并返回提示
  6419. dLog('deepseek')->info('未生成剧本相关的内容');
  6420. try {
  6421. $now = date('Y-m-d H:i:s');
  6422. // 保存对话记录
  6423. $records = [
  6424. [
  6425. 'uid' => $uid,
  6426. 'anime_id' => $anime_id,
  6427. 'sequence' => 0,
  6428. 'role' => 'user',
  6429. 'content' => $prompt,
  6430. 'created_at' => $now,
  6431. 'updated_at' => $now
  6432. ],
  6433. [
  6434. 'uid' => $uid,
  6435. 'anime_id' => $anime_id,
  6436. 'sequence' => 0,
  6437. 'role' => 'assistant',
  6438. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6439. 'created_at' => $now,
  6440. 'updated_at' => $now
  6441. ]
  6442. ];
  6443. DB::table('mp_anime_records')->insert($records);
  6444. } catch (\Exception $e) {
  6445. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6446. }
  6447. yield [
  6448. 'type' => 'done',
  6449. 'script' => [],
  6450. 'episode' => [],
  6451. 'answer' => $fullContent,
  6452. 'reasoning' => $fullReasoningContent,
  6453. 'usage' => $usage,
  6454. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6455. ];
  6456. return;
  6457. }
  6458. // 替换美术风格
  6459. if ($mappedArtStyle !== '') {
  6460. $script_arr['art_style'] = $mappedArtStyle;
  6461. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6462. }
  6463. if ($user_anime_name != '新剧本策划') {
  6464. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  6465. // 确认对话名称唯一性
  6466. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6467. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6468. }
  6469. }else {
  6470. $anime_name = $user_anime_name;
  6471. }
  6472. $table_data = [
  6473. 'user_id' => $uid,
  6474. 'model' => $model,
  6475. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6476. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6477. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6478. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6479. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6480. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6481. 'art_style_type' => $input_art_style,
  6482. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6483. 'status' => '解析完成',
  6484. 'generate_status' => '待执行',
  6485. 'updated_at' => date('Y-m-d H:i:s')
  6486. ];
  6487. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6488. // 如果是修改集数,则将content内容更新(会改变原文)
  6489. if (isset($episode_count) && $episode_count > 0) {
  6490. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6491. $table_data['start_episode_sequence'] = 1;
  6492. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6493. }else {
  6494. // 如果需要生成原文内容,从script_arr中提取
  6495. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6496. $table_data['content'] = $script_arr['content'];
  6497. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6498. if (!$table_data['content']) {
  6499. yield [
  6500. 'type' => 'done',
  6501. 'script' => [],
  6502. 'episode' => [],
  6503. 'answer' => $fullContent,
  6504. 'reasoning' => $fullReasoningContent,
  6505. 'usage' => $usage,
  6506. 'error' => '未生成剧本内容,请调整提示词再试'
  6507. ];
  6508. return;
  6509. }
  6510. }
  6511. if (isset($table_data['content']) && $table_data['content']) {
  6512. $chapters = $this->splitContent($table_data['content']);
  6513. $chapter_count = count($chapters);
  6514. if ($chapter_count > 0) {
  6515. $table_data['start_episode_sequence'] = 1;
  6516. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6517. }
  6518. }
  6519. }
  6520. if ($extra_products) {
  6521. $table_data['extra_products'] = json_encode($extra_products, 256);
  6522. }
  6523. $single_episode = [];
  6524. try {
  6525. DB::beginTransaction();
  6526. $now = date('Y-m-d H:i:s');
  6527. // 更新动漫大纲
  6528. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6529. if (!$boolen) {
  6530. dLog('deepseek')->info('对话修改失败', $table_data);
  6531. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6532. Utils::throwError('20003:对话修改失败');
  6533. }
  6534. // 保存对话记录
  6535. $records = [
  6536. [
  6537. 'uid' => $uid,
  6538. 'anime_id' => $anime_id,
  6539. 'sequence' => 0,
  6540. 'role' => 'user',
  6541. 'content' => $prompt,
  6542. 'created_at' => $now,
  6543. 'updated_at' => $now
  6544. ],
  6545. [
  6546. 'uid' => $uid,
  6547. 'anime_id' => $anime_id,
  6548. 'sequence' => 0,
  6549. 'role' => 'assistant',
  6550. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6551. 'content' => $fullContent,
  6552. 'created_at' => $now,
  6553. 'updated_at' => $now
  6554. ]
  6555. ];
  6556. // 保存对话记录
  6557. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6558. if (!$boolen3) {
  6559. Utils::throwError('20003:对话记录保存失败');
  6560. }
  6561. // 单剧集模式:生成并保存剧集信息
  6562. if ($is_single) {
  6563. $anime_name = getProp($anime, 'anime_name', '未命名');
  6564. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6565. if (empty($episode_arr['acts'])) {
  6566. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6567. }
  6568. $saveResult = $this->saveEpisodeVersionData(
  6569. $anime_id,
  6570. 1,
  6571. $episode_arr,
  6572. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6573. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6574. null,
  6575. null,
  6576. false,
  6577. $content,
  6578. $now,
  6579. $ref_products
  6580. );
  6581. $single_episode = $saveResult['episode'];
  6582. $episode_id = $saveResult['episode_id'];
  6583. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6584. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6585. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6586. 'updated_at' => $now
  6587. ]);
  6588. if ($boolen5 === false) {
  6589. Utils::throwError('20003:单剧集主表资源同步失败');
  6590. }
  6591. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6592. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6593. $episode_record_content = '确认分镜大纲';
  6594. if ($content !== '') {
  6595. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6596. }
  6597. $episode_records = [
  6598. [
  6599. 'uid' => $uid,
  6600. 'anime_id' => $anime_id,
  6601. 'role' => 'user',
  6602. 'content' => $episode_record_content,
  6603. 'sequence' => 1,
  6604. 'episode_id' => $episode_id,
  6605. 'created_at' => $now,
  6606. 'updated_at' => $now
  6607. ],
  6608. [
  6609. 'uid' => $uid,
  6610. 'anime_id' => $anime_id,
  6611. 'role' => 'assistant',
  6612. 'content' => $fullContent,
  6613. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6614. 'sequence' => 1,
  6615. 'episode_id' => $episode_id,
  6616. 'created_at' => $now,
  6617. 'updated_at' => $now
  6618. ]
  6619. ];
  6620. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6621. if (!$boolen4) {
  6622. Utils::throwError('20003:单剧集分镜记录保存失败');
  6623. }
  6624. }
  6625. }catch (\Exception $e) {
  6626. DB::rollBack();
  6627. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  6628. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  6629. yield [
  6630. 'type' => 'done',
  6631. 'answer' => $fullContent,
  6632. 'reasoning' => $fullReasoningContent,
  6633. 'usage' => $usage,
  6634. 'error' => $e->getMessage(),
  6635. ];
  6636. return;
  6637. }
  6638. DB::commit();
  6639. dLog('deepseek')->info('保存完毕');
  6640. if ($is_single && !empty($single_episode)) {
  6641. // $this->batchSetGlobalRoleImg([
  6642. // 'anime_id' => $anime_id,
  6643. // ]);
  6644. // $this->batchSetGlobalSceneImg([
  6645. // 'anime_id' => $anime_id,
  6646. // ]);
  6647. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6648. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6649. }
  6650. $table_data['anime_id'] = $anime_id;
  6651. $table_data['roles'] = json_decode($table_data['roles'], true);
  6652. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6653. unset($table_data['updated_at']);
  6654. unset($table_data['status']);
  6655. yield [
  6656. 'type' => 'done',
  6657. 'script' => $table_data,
  6658. 'episode' => $single_episode,
  6659. 'answer' => $fullContent,
  6660. 'reasoning' => $fullReasoningContent,
  6661. 'usage' => $usage
  6662. ];
  6663. }
  6664. public function chatForAce($data) {
  6665. $uid = Site::getUid();
  6666. $anime_id = getProp($data, 'anime_id');
  6667. $file = getProp($data, 'file');
  6668. $content = getProp($data, 'content', '');
  6669. $bid = getProp($data, 'bid', 0);
  6670. $script_id = getProp($data, 'script_id', 0);
  6671. $episode_number = getProp($data, 'episode_number', 1);
  6672. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6673. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6674. if (!$anime) Utils::throwError('20003:该对话不存在!');
  6675. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  6676. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  6677. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  6678. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  6679. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  6680. $roles = is_array($roles) ? $roles : [];
  6681. $scenes = is_array($scenes) ? $scenes : [];
  6682. $extra_products = getProp($data, 'products', []);
  6683. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6684. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6685. $anime_script_id = getProp($anime, 'script_id');
  6686. if ($anime_script_id) {
  6687. $cpid = Site::getCpid();
  6688. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6689. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6690. ->where('mapping.script_id', $anime_script_id)
  6691. ->where('product.cpid', $cpid)
  6692. ->where('product.is_deleted', 0);
  6693. // 如果提供了 episode_number,则过滤指定集数
  6694. if ($episode_number !== null && $episode_number !== '') {
  6695. $script_products_mappings->where('mapping.episode_number', $episode_number);
  6696. }
  6697. $mappings = $script_products_mappings->select(
  6698. 'mapping.product_id',
  6699. 'mapping.episode_number',
  6700. 'product.product_name',
  6701. 'product.type',
  6702. 'product.product',
  6703. 'product.pic_prompt',
  6704. 'product.url',
  6705. 'product.pic_task_id',
  6706. 'product.pic_task_status',
  6707. 'product.three_view_image_url'
  6708. )
  6709. ->get();
  6710. // 按 product_id 分组,合并 episode_number
  6711. $productMap = [];
  6712. foreach ($mappings as $item) {
  6713. $product_id = $item->product_id;
  6714. $product_name = $item->product_name;
  6715. // 处理product_name两边的符号
  6716. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6717. if (!isset($productMap[$product_id])) {
  6718. $productMap[$product_id] = [
  6719. 'product_id' => $product_id,
  6720. 'product_name' => $product_name,
  6721. 'type' => (int)$item->type,
  6722. 'product' => (int)$item->product,
  6723. 'pic_prompt' => $item->pic_prompt,
  6724. 'url' => $item->url,
  6725. 'pic_task_id' => $item->pic_task_id,
  6726. 'pic_task_status' => $item->pic_task_status,
  6727. 'episode_numbers' => [],
  6728. ];
  6729. }
  6730. // 添加 episode_number(去重)
  6731. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6732. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6733. }
  6734. }
  6735. // 将查询到的剧本资产合并到extra_products中
  6736. // 先构建extra_products的索引(以product_id+episode_number为key)
  6737. $extraProductsMap = [];
  6738. foreach ($extra_products as $item) {
  6739. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  6740. $extraProductsMap[$key] = $item;
  6741. }
  6742. // 合并剧本资产(去重:product_id+episode_number)
  6743. foreach ($productMap as $product) {
  6744. foreach ($product['episode_numbers'] as $ep_num) {
  6745. $key = $product['product_id'] . '_' . $ep_num;
  6746. // 如果不存在则添加
  6747. if (!isset($extraProductsMap[$key])) {
  6748. $extraProductsMap[$key] = [
  6749. 'product_id' => $product['product_id'],
  6750. 'product_name' => $product['product_name'],
  6751. 'type' => $product['type'],
  6752. 'product' => $product['product'],
  6753. 'pic_prompt' => $product['pic_prompt'],
  6754. 'url' => $product['url'],
  6755. 'pic_task_id' => $product['pic_task_id'],
  6756. 'pic_task_status' => $product['pic_task_status'],
  6757. 'episode_number' => $ep_num,
  6758. ];
  6759. }
  6760. }
  6761. }
  6762. // 重新赋值给extra_products
  6763. $extra_products = array_values($extraProductsMap);
  6764. }
  6765. // 处理提示词
  6766. if ($prompt && $extra_products) {
  6767. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6768. foreach($extra_products as $item) {
  6769. $product_name = getProp($item, 'product_name');
  6770. if ($product_name) {
  6771. // 替换 {product_name} 为 product_name
  6772. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6773. }
  6774. }
  6775. }
  6776. // 获取最后一集序号
  6777. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  6778. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  6779. // 转换主体列表和场景列表的格式
  6780. // 获取参考主体或场景
  6781. if ((int)$episode_number === 1) {
  6782. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  6783. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  6784. }else {
  6785. $prev_episode_number = $episode_number - 1;
  6786. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  6787. }
  6788. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  6789. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  6790. // 合并anime_products和extra_products(extra_products优先,去重)
  6791. $anime_products = getProp($anime, 'extra_products');
  6792. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  6793. $ref_products = [];
  6794. foreach($anime_products as $item) {
  6795. $product_name = getProp($item, 'product_name');
  6796. $ref_products[$product_name] = $item;
  6797. }
  6798. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  6799. $extra_roles = []; // 从extra_products中提取的角色
  6800. $extra_scenes = []; // 从extra_products中提取的场景
  6801. if ($extra_products && is_array($extra_products)) {
  6802. foreach($extra_products as $item) {
  6803. $product = (int)getProp($item, 'product');
  6804. $product_name = getProp($item, 'product_name');
  6805. if ($product_name == '旁白') continue;
  6806. $pic_prompt = getProp($item, 'pic_prompt');
  6807. $ref_products[$product_name] = $item;
  6808. if ($product === 1) {
  6809. // 角色
  6810. $extra_roles[$product_name] = [
  6811. 'role' => $product_name,
  6812. 'pic_prompt' => $pic_prompt,
  6813. 'url' => getProp($item, 'url', ''),
  6814. ];
  6815. } elseif ($product === 2) {
  6816. // 场景
  6817. $extra_scenes[$product_name] = [
  6818. 'scene' => $product_name,
  6819. 'pic_prompt' => $pic_prompt,
  6820. 'url' => getProp($item, 'url', ''),
  6821. ];
  6822. }
  6823. }
  6824. }
  6825. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  6826. $merged_roles = [];
  6827. foreach($ref_roles as $role) {
  6828. $role_name = getProp($role, 'role');
  6829. if (!isset($extra_roles[$role_name])) {
  6830. $merged_roles[$role_name] = $role;
  6831. }
  6832. }
  6833. // 添加extra_roles
  6834. foreach($extra_roles as $role_name => $role) {
  6835. $merged_roles[$role_name] = $role;
  6836. }
  6837. $ref_roles = array_values($merged_roles);
  6838. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  6839. $merged_scenes = [];
  6840. foreach($ref_scenes as $scene) {
  6841. $scene_name = getProp($scene, 'scene');
  6842. if (!isset($extra_scenes[$scene_name])) {
  6843. $merged_scenes[$scene_name] = $scene;
  6844. }
  6845. }
  6846. // 添加extra_scenes
  6847. foreach($extra_scenes as $scene_name => $scene) {
  6848. $merged_scenes[$scene_name] = $scene;
  6849. }
  6850. $ref_scenes = array_values($merged_scenes);
  6851. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  6852. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  6853. // 构建强制主体和场景提示词
  6854. $forced_roles_prompt = "";
  6855. $forced_scenes_prompt = "";
  6856. if (!empty($extra_roles)) {
  6857. $forced_roles_list = "";
  6858. foreach($extra_roles as $role_name => $role) {
  6859. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  6860. }
  6861. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6862. }
  6863. if (!empty($extra_scenes)) {
  6864. $forced_scenes_list = "";
  6865. foreach($extra_scenes as $scene_name => $scene) {
  6866. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  6867. }
  6868. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6869. }
  6870. if ($anime_script_id) {
  6871. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  6872. }else if ($roles_content) {
  6873. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  6874. 主体范围:\n {$roles_content}\n
  6875. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  6876. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6877. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6878. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6879. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  6880. }else {
  6881. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6882. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6883. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6884. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6885. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  6886. }
  6887. if ($anime_script_id) {
  6888. $scene_demo = "3.<场景列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  6889. }else if ($scenes_content) {
  6890. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  6891. 场景范围:\n {$scenes_content}\n
  6892. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  6893. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  6894. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6895. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  6896. }else {
  6897. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6898. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6899. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6900. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  6901. }
  6902. // 提取文件内容
  6903. if ($file) {
  6904. $uploaded_content = $this->extractFileContent($file);
  6905. if (!$uploaded_content) {
  6906. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6907. }
  6908. } elseif ($script_id) {
  6909. $uploaded_content = $this->getContentByScriptId($script_id);
  6910. if (!$uploaded_content) {
  6911. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6912. }
  6913. } elseif ($bid) {
  6914. $uploaded_content = $this->getContentByBid($bid);
  6915. if (!$uploaded_content) {
  6916. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6917. }
  6918. } elseif ($content) {
  6919. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  6920. }
  6921. // elseif ($prompt) {
  6922. // $uploaded_content = filterContent($prompt);
  6923. // }
  6924. else {
  6925. $uploaded_content = '';
  6926. }
  6927. // 美术风格
  6928. $input_art_style = getProp($data, 'art_style');
  6929. if (!$input_art_style) {
  6930. $mappedArtStyle = getProp($anime, 'art_style');
  6931. }else {
  6932. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6933. }
  6934. if (!$mappedArtStyle) {
  6935. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6936. }else {
  6937. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6938. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6939. }else {
  6940. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6941. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6942. }
  6943. }
  6944. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6945. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6946. // 强制要求:
  6947. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6948. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6949. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6950. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  6951. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  6952. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  6953. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  6954. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  6955. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  6956. // 10.分镜要和场景列表、人物主体保持一致\n
  6957. // 普通要求:
  6958. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6959. // {$role_demo}
  6960. // {$scene_demo}
  6961. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6962. // 4.1片段分割逻辑(优先级从高到低):
  6963. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6964. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6965. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6966. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6967. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6968. // - 片段数量格式为: 片段数量:8
  6969. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6970. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6971. // 4.3分镜结构:每个分镜包含以下字段:
  6972. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  6973. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  6974. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6975. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  6976. // - 运镜:场景+画面描述+运镜
  6977. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  6978. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6979. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  6980. // 5.$mappedArtStyle_prompt\n\n
  6981. // 示例格式:\n
  6982. // 第1集:隐形的守护者
  6983. // ###故事梗概
  6984. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6985. // ###美术风格
  6986. // 基础画风风格词:胡金铨武侠
  6987. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  6988. // ###主体列表
  6989. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6990. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  6991. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  6992. // ###场景列表
  6993. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  6994. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  6995. // ###分段剧本
  6996. // 片段数量:8
  6997. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6998. // ##片段1
  6999. // 时长:12s
  7000. // 分镜1
  7001. // 场景:边境小镇街道
  7002. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7003. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7004. // 配音台词:
  7005. // 背景音效:
  7006. // 分镜2
  7007. // 场景:悦来酒馆
  7008. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7009. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7010. // 配音台词:
  7011. // 背景音效:
  7012. // 分镜3
  7013. // 场景:悦来酒馆
  7014. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7015. // 运镜:从中景推向令牌特写。
  7016. // 配音台词:
  7017. // 背景音效:
  7018. // 分镜4
  7019. // 场景:悦来酒馆
  7020. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7021. // 运镜:极速推向酒水溅起的瞬间。
  7022. // 配音台词:
  7023. // 背景音效:
  7024. // 分镜5
  7025. // 镜头描述
  7026. // 场景:悦来酒馆
  7027. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7028. // 运镜:固定机位,利用倾斜构图制造压迫感。
  7029. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7030. // 背景音效:
  7031. // \n\n";
  7032. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7033. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7034. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  7035. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  7036. 普通要求:
  7037. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7038. {$role_demo}
  7039. {$scene_demo}
  7040. 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7041. 4.1片段分割逻辑(优先级从高到低):
  7042. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7043. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7044. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7045. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7046. 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7047. - 片段数量格式为: 片段数量:8
  7048. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7049. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7050. 4.3分镜结构:每个分镜包含以下字段:
  7051. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7052. - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  7053. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7054. - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  7055. - 运镜:场景+画面描述+运镜
  7056. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用[林启明-黑色大衣七爷造型]而不是[林启明])
  7057. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7058. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7059. 5.{$mappedArtStyle_prompt}
  7060. 6.《情绪-视听语言映射表》:
  7061. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7062. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7063. -----|---------|------------|----------------
  7064. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7065. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7066. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7067. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7068. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7069. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7070. -----|---------|------------|----------------
  7071. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7072. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7073. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7074. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7075. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7076. --------|---------|--------------|-------------
  7077. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7078. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7079. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7080. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7081. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7082. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7083. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7084. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7085. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7086. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7087. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7088. -----|---------|------------|------------
  7089. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7090. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7091. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7092. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7093. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7094. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7095. --------|---------|--------------|----------
  7096. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7097. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7098. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7099. 6.6 声音设计与潜意识影响 (Soundscape)
  7100. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7101. -----|---------|------------|------------------
  7102. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7103. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7104. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7105. 理论基石:
  7106. - The Five C's of Cinematography by Joseph V. Mascelli
  7107. - Film Art: An Introduction by David Bordwell
  7108. - Sight, Sound, Motion by Herbert Zettl
  7109. - Notes on the Cinematograph by Robert Bresson
  7110. \n\n
  7111. 示例格式:\n
  7112. 第1集:隐形的守护者
  7113. ###故事梗概
  7114. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7115. ###美术风格
  7116. 基础画风风格词:胡金铨武侠
  7117. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7118. ###主体列表
  7119. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7120. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7121. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7122. ###场景列表
  7123. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7124. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7125. ###分段剧本
  7126. 片段数量:8
  7127. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7128. ##片段1
  7129. 时长:12s
  7130. 分镜1
  7131. 场景:边境小镇街道
  7132. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7133. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7134. 配音台词:
  7135. 背景音效:
  7136. 分镜2
  7137. 场景:悦来酒馆
  7138. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7139. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7140. 配音台词:
  7141. 背景音效:
  7142. 分镜3
  7143. 场景:悦来酒馆
  7144. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7145. 运镜:从中景推向令牌特写。
  7146. 配音台词:
  7147. 背景音效:
  7148. 分镜4
  7149. 场景:悦来酒馆
  7150. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7151. 运镜:极速推向酒水溅起的瞬间。
  7152. 配音台词:
  7153. 背景音效:
  7154. 分镜5
  7155. 镜头描述
  7156. 场景:悦来酒馆
  7157. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7158. 运镜:固定机位,利用倾斜构图制造压迫感。
  7159. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7160. 背景音效:
  7161. \n\n";
  7162. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7163. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  7164. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7165. $prompt = $origin_prompt;
  7166. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7167. // 获取章节内容
  7168. $full_content = getProp($anime, 'content');
  7169. if ($uploaded_content) {
  7170. $full_content = $uploaded_content;
  7171. }
  7172. // 根据章节内容拆分章节
  7173. $chapters = $this->splitContent($full_content);
  7174. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7175. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7176. $messages = [];
  7177. if ($prompt == '确认分镜大纲') {
  7178. // 暂时保留
  7179. $content = $chapter_content;
  7180. if ($is_single) $content = $full_content; // 单剧集使用全文
  7181. if (!$content) {
  7182. Utils::throwError('20003:章节内容无法获取,请确认');
  7183. }
  7184. $question = $is_single
  7185. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7186. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7187. // 构建消息
  7188. $messages[] =
  7189. [
  7190. 'role' => 'user',
  7191. 'content' => $question
  7192. ];
  7193. }else if ($prompt == '继续策划下一集') {
  7194. if ($is_single) {
  7195. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7196. }
  7197. $content = $chapter_content;
  7198. if (!$content) {
  7199. Utils::throwError('20003:章节内容无法获取,请确认');
  7200. }
  7201. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7202. // 获取上一集最后记录
  7203. $prev_sequence = $episode_number - 1;
  7204. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7205. // 构建消息
  7206. $messages[] =
  7207. [
  7208. 'role' => 'user',
  7209. 'content' => $question
  7210. ];
  7211. // dd($messages);
  7212. }else {
  7213. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7214. if (!$content) {
  7215. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7216. }
  7217. if (!$content) {
  7218. Utils::throwError('20003:章节内容无法获取,请确认');
  7219. }
  7220. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7221. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7222. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7223. if ($origin_prompt) {
  7224. $question .= "本次修改要求如下:\n{$origin_prompt}";
  7225. }
  7226. $messages[] =
  7227. [
  7228. 'role' => 'user',
  7229. 'content' => $question
  7230. ];
  7231. }
  7232. // 处理文本模型
  7233. $model = getProp($data, 'model');
  7234. if (!$model) {
  7235. // 用户没有输入,从anime表获取
  7236. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7237. $model = getProp($anime, 'model');
  7238. if (!$model) {
  7239. // anime表也没有,使用默认值
  7240. $model = 'doubao-seed-2-0-mini-260215';
  7241. }
  7242. }
  7243. // 验证模型是否在可用模型表中
  7244. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7245. $model = 'doubao-seed-2-0-mini-260215';
  7246. }
  7247. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7248. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7249. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7250. if ($model === 'deepseek-chat') {
  7251. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7252. $model = 'deepseek-v4-flash';
  7253. $thinkingMode = 'disabled';
  7254. } elseif ($model === 'deepseek-reasoner') {
  7255. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7256. $model = 'deepseek-v4-flash';
  7257. $thinkingMode = 'enabled';
  7258. }
  7259. $post_data = [
  7260. 'model' => $model,
  7261. 'messages' => $messages,
  7262. // 'max_tokens' => 8192,
  7263. 'temperature' => 0.7,
  7264. 'frequency_penalty' => 0,
  7265. 'presence_penalty' => 0,
  7266. 'response_format' => ['type' => 'text'],
  7267. 'thinking' => ['type' => $thinkingMode],
  7268. 'stream' => true // 启用流式输出
  7269. ];
  7270. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7271. // 根据模型类型选择调用方法
  7272. $fullContent = '';
  7273. $fullReasoningContent = '';
  7274. $usage = [];
  7275. try {
  7276. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7277. // DeepSeek 官方模型使用 DeepSeek API
  7278. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7279. } else if (in_array($model, $this->gpt_text_models)) {
  7280. // GPT-5.4 模型使用 TokenRouter API
  7281. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7282. } else {
  7283. // 其他模型使用火山引擎API
  7284. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7285. }
  7286. // 验证返回值类型
  7287. if (!is_iterable($streamGenerator)) {
  7288. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7289. dLog('deepseek')->error('chat流式生成器无效', [
  7290. 'generator_type' => $errorType,
  7291. 'model' => $model,
  7292. 'anime_id' => $anime_id,
  7293. 'episode_number' => $episode_number
  7294. ]);
  7295. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7296. 'type' => $errorType,
  7297. 'model' => $model
  7298. ]);
  7299. yield [
  7300. 'type' => 'error',
  7301. 'episode' => [],
  7302. 'answer' => '',
  7303. 'reasoning' => '',
  7304. 'usage' => [],
  7305. 'error' => '接口返回数据异常,请重新请求'
  7306. ];
  7307. return;
  7308. }
  7309. // 处理流式输出
  7310. foreach ($streamGenerator as $chunk) {
  7311. if (isset($chunk['type'])) {
  7312. if ($chunk['type'] === 'done') {
  7313. // 最终结果
  7314. $fullContent = $chunk['full_content'];
  7315. $fullReasoningContent = $chunk['full_reasoning'];
  7316. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7317. } else {
  7318. // 逐块yield数据
  7319. yield $chunk;
  7320. }
  7321. }
  7322. }
  7323. } catch (\Exception $e) {
  7324. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7325. 'model' => $model,
  7326. 'anime_id' => $anime_id,
  7327. 'episode_number' => $episode_number,
  7328. 'trace' => $e->getTraceAsString()
  7329. ]);
  7330. logDB('deepseek', 'error', 'chat流式处理失败', [
  7331. 'error' => $e->getMessage(),
  7332. 'model' => $model
  7333. ]);
  7334. yield [
  7335. 'type' => 'error',
  7336. 'episode' => [],
  7337. 'answer' => '',
  7338. 'reasoning' => '',
  7339. 'usage' => [],
  7340. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7341. ];
  7342. return;
  7343. }
  7344. dLog('deepseek')->info('完整内容: '.$fullContent);
  7345. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7346. // 处理完整内容并返回最终结果
  7347. $episode_arr = handleEpisodeContentForAce($fullContent);
  7348. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7349. if (empty($episode_arr['acts'])) {
  7350. // 未生成剧本相关内容,保存对话记录并返回提示
  7351. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  7352. try {
  7353. $now = date('Y-m-d H:i:s');
  7354. // 保存对话记录
  7355. $records = [
  7356. [
  7357. 'uid' => $uid,
  7358. 'anime_id' => $anime_id,
  7359. 'sequence' => $episode_number,
  7360. 'role' => 'user',
  7361. 'content' => $prompt,
  7362. 'created_at' => $now,
  7363. 'updated_at' => $now
  7364. ],
  7365. [
  7366. 'uid' => $uid,
  7367. 'anime_id' => $anime_id,
  7368. 'sequence' => $episode_number,
  7369. 'role' => 'assistant',
  7370. 'content' => $fullContent,
  7371. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7372. 'created_at' => $now,
  7373. 'updated_at' => $now
  7374. ]
  7375. ];
  7376. DB::table('mp_anime_records')->insert($records);
  7377. } catch (\Exception $e) {
  7378. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7379. }
  7380. yield [
  7381. 'type' => 'done',
  7382. 'episode' => [],
  7383. 'answer' => $fullContent,
  7384. 'reasoning' => $fullReasoningContent,
  7385. 'usage' => $usage,
  7386. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  7387. ];
  7388. return;
  7389. }
  7390. // 老逻辑
  7391. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  7392. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  7393. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  7394. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  7395. $now = date('Y-m-d H:i:s');
  7396. try {
  7397. DB::beginTransaction();
  7398. $saveResult = $this->saveEpisodeVersionData(
  7399. $anime_id,
  7400. $episode_number,
  7401. $episode_arr,
  7402. $existing_roles,
  7403. $existing_scenes,
  7404. $current_episode,
  7405. $base_episode,
  7406. $is_regenerate_version,
  7407. $content,
  7408. $now,
  7409. $ref_products
  7410. );
  7411. $episode = $saveResult['episode'];
  7412. $episode_id = $saveResult['episode_id'];
  7413. $merged_roles = $saveResult['merged_roles'];
  7414. $merged_scenes = $saveResult['merged_scenes'];
  7415. $record_content = $origin_prompt;
  7416. if ($uploaded_content !== '') {
  7417. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  7418. }
  7419. $records = [
  7420. [
  7421. 'uid' => $uid,
  7422. 'anime_id' => $anime_id,
  7423. 'role' => 'user',
  7424. 'content' => $record_content,
  7425. 'sequence' => $episode_number,
  7426. 'episode_id' => $episode_id,
  7427. 'created_at' => $now,
  7428. 'updated_at' => $now
  7429. ],
  7430. [
  7431. 'uid' => $uid,
  7432. 'anime_id' => $anime_id,
  7433. 'role' => 'assistant',
  7434. 'content' => $fullContent,
  7435. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7436. 'sequence' => $episode_number,
  7437. 'episode_id' => $episode_id,
  7438. 'created_at' => $now,
  7439. 'updated_at' => $now
  7440. ]
  7441. ];
  7442. $boolen4 = DB::table('mp_anime_records')->insert($records);
  7443. if (!$boolen4) {
  7444. Utils::throwError('20003:对话记录保存失败');
  7445. }
  7446. // 保存模型到anime表
  7447. $update_anime_data = [
  7448. 'model' => $model,
  7449. 'updated_at' => $now
  7450. ];
  7451. if ($uploaded_content) {
  7452. $update_anime_data['content'] = $uploaded_content;
  7453. }
  7454. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  7455. }catch (\Exception $e) {
  7456. DB::rollBack();
  7457. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7458. yield [
  7459. 'type' => 'done',
  7460. 'answer' => $fullContent,
  7461. 'reasoning' => $fullReasoningContent,
  7462. 'usage' => $usage,
  7463. 'error' => $e->getMessage(),
  7464. ];
  7465. return;
  7466. }
  7467. DB::commit();
  7468. if ($is_global_generate_pics) {
  7469. // // 批量生成全局角色图片
  7470. // $this->batchSetGlobalRoleImg([
  7471. // 'anime_id' => $anime_id,
  7472. // ], true);
  7473. // // 批量生成全局场景图片
  7474. // $this->batchSetGlobalSceneImg([
  7475. // 'anime_id' => $anime_id,
  7476. // ], true);
  7477. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7478. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7479. }
  7480. $episode['episode_id'] = $episode_id;
  7481. $episode['roles'] = $merged_roles;
  7482. $episode['scenes'] = $merged_scenes;
  7483. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  7484. yield [
  7485. 'type' => 'done',
  7486. 'episode' => $episode,
  7487. 'answer' => $fullContent,
  7488. 'reasoning' => $fullReasoningContent,
  7489. 'usage' => $usage
  7490. ];
  7491. }
  7492. /**
  7493. * 重新生成分段剧本
  7494. * @param array $data 包含以下字段:
  7495. * - prompt: string|null 用户修改要求(可选)
  7496. * - template_id: int|null 提示词模板ID(可选)
  7497. * - act_id: int|null 单个片段ID(与episode_id二选一)
  7498. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  7499. * @return array 返回生成结果
  7500. */
  7501. public function regenerateSegmentScript($data) {
  7502. $uid = Site::getUid();
  7503. $prompt = trim((string)getProp($data, 'prompt', ''));
  7504. $template_id = getProp($data, 'template_id', 0);
  7505. $act_id = getProp($data, 'act_id', 0);
  7506. $episode_id = getProp($data, 'episode_id', 0);
  7507. // 验证:prompt和template_id至少提供一个
  7508. if (empty($prompt) && empty($template_id)) {
  7509. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  7510. }
  7511. // 验证:act_id和episode_id二选一
  7512. if (empty($act_id) && empty($episode_id)) {
  7513. Utils::throwError('20003:请提供片段ID或剧集ID');
  7514. }
  7515. if (!empty($act_id) && !empty($episode_id)) {
  7516. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  7517. }
  7518. // 如果提供了template_id,获取模板提示词
  7519. $template_prompt = '';
  7520. if ($template_id > 0) {
  7521. $template = DB::table('mp_prompt_templates')
  7522. ->where('id', $template_id)
  7523. ->where('is_deleted', 0)
  7524. ->first();
  7525. if (!$template) {
  7526. Utils::throwError('20003:提示词模板不存在或已删除');
  7527. }
  7528. $template_prompt = $template->template_prompt ?? '';
  7529. }
  7530. // 合并用户提示词和模板提示词
  7531. $final_prompt = '';
  7532. if (!empty($template_prompt)) {
  7533. $final_prompt = $template_prompt;
  7534. if (!empty($prompt)) {
  7535. $final_prompt .= "\n\n补充要求:" . $prompt;
  7536. }
  7537. } else {
  7538. $final_prompt = $prompt;
  7539. }
  7540. // 获取需要重新生成的内容参考
  7541. $reference_content = '';
  7542. $target_episode_id = 0;
  7543. $target_anime_id = 0;
  7544. $target_episode_number = 0;
  7545. if ($act_id > 0) {
  7546. // 单个片段模式:获取该片段的内容
  7547. $segment = DB::table('mp_episode_segments')
  7548. ->where('id', $act_id)
  7549. ->first();
  7550. if (!$segment) {
  7551. Utils::throwError('20003:片段不存在');
  7552. }
  7553. $target_episode_id = $segment->episode_id;
  7554. $target_anime_id = $segment->anime_id;
  7555. $target_episode_number = $segment->episode_number;
  7556. $reference_content = $segment->act_content ?? '';
  7557. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  7558. } else {
  7559. // 整个剧集模式:获取所有片段的内容
  7560. $segments = DB::table('mp_episode_segments')
  7561. ->where('episode_id', $episode_id)
  7562. ->orderBy('act_number')
  7563. ->get();
  7564. if ($segments->isEmpty()) {
  7565. Utils::throwError('20003:该剧集没有片段数据');
  7566. }
  7567. $target_episode_id = $episode_id;
  7568. $target_anime_id = $segments[0]->anime_id;
  7569. $target_episode_number = $segments[0]->episode_number;
  7570. // 拼接所有片段内容,保留格式用于AI理解
  7571. $act_contents = [];
  7572. foreach ($segments as $seg) {
  7573. $act_number = $seg->act_number;
  7574. $act_content = $seg->act_content ?? '';
  7575. if (!empty($act_content)) {
  7576. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  7577. }
  7578. }
  7579. $reference_content = implode("\n\n", $act_contents);
  7580. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  7581. if ($episode_content) {
  7582. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  7583. }else {
  7584. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  7585. }
  7586. }
  7587. if (empty($reference_content)) {
  7588. Utils::throwError('20003:没有可参考的片段内容');
  7589. }
  7590. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  7591. $episode = DB::table('mp_anime_episodes')
  7592. ->where('id', $target_episode_id)
  7593. ->first();
  7594. if (!$episode) {
  7595. Utils::throwError('20003:剧集不存在');
  7596. }
  7597. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  7598. $anime_script_id = getProp($anime, 'script_id');
  7599. $intro = $episode->intro ?? '';
  7600. $art_style = $episode->art_style ?? '';
  7601. $roles = json_decode($episode->roles ?? '[]', true);
  7602. $scenes = json_decode($episode->scenes ?? '[]', true);
  7603. // 构建提示词中的主体列表和场景列表参考
  7604. $roles_ref = '';
  7605. if (!empty($roles) && is_array($roles)) {
  7606. $roles_list = [];
  7607. foreach ($roles as $role) {
  7608. $role_name = getProp($role, 'role', '');
  7609. $role_desc = getProp($role, 'description', '');
  7610. $pic_prompt = getProp($role, 'pic_prompt', '');
  7611. $voice_prompt = getProp($role, 'voice_prompt', '');
  7612. if (!empty($role_name)) {
  7613. $role_line = $role_name;
  7614. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  7615. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  7616. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  7617. $roles_list[] = $role_line;
  7618. }
  7619. }
  7620. if (!empty($roles_list)) {
  7621. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  7622. }
  7623. }
  7624. $scenes_ref = '';
  7625. if (!empty($scenes) && is_array($scenes)) {
  7626. $scenes_list = [];
  7627. foreach ($scenes as $scene) {
  7628. $scene_name = getProp($scene, 'scene', '');
  7629. $scene_desc = getProp($scene, 'description', '');
  7630. $pic_prompt = getProp($scene, 'pic_prompt', '');
  7631. if (!empty($scene_name)) {
  7632. $scene_line = $scene_name;
  7633. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  7634. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  7635. $scenes_list[] = $scene_line;
  7636. }
  7637. }
  7638. if (!empty($scenes_list)) {
  7639. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  7640. }
  7641. }
  7642. // 构建美术风格参考
  7643. $art_style_ref = '';
  7644. if (!empty($art_style)) {
  7645. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  7646. }
  7647. // 构建内容简介参考
  7648. $intro_ref = '';
  7649. if (!empty($intro)) {
  7650. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  7651. }
  7652. // 构建完整的AI提示词
  7653. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  7654. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  7655. $user_prompt .= $intro_ref;
  7656. $user_prompt .= $art_style_ref;
  7657. $user_prompt .= $reference_content;
  7658. // $user_prompt .= $roles_ref;
  7659. // $user_prompt .= $scenes_ref;
  7660. $system_prompt = "\n\n【强制要求】\n";
  7661. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  7662. $system_prompt .= "- 每个分镜包含:分镜序号、场景、画面、运镜、配音台词、背景音效\n";
  7663. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”后面“:”前面的任何内容,不能自创){$scenes_ref}\n";
  7664. $system_prompt .= "- 出场角色必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”后面“:”前面的任何内容,不能自创){$roles_ref}\n";
  7665. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  7666. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  7667. ###分段剧本
  7668. 片段数量:8
  7669. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7670. ##片段1
  7671. 时长:12s
  7672. 分镜1
  7673. 场景:边境小镇街道
  7674. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7675. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7676. 配音台词:
  7677. 背景音效:
  7678. 分镜2
  7679. 场景:悦来酒馆
  7680. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7681. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7682. 配音台词:
  7683. 背景音效:
  7684. 分镜3
  7685. 场景:悦来酒馆
  7686. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7687. 运镜:从中景推向令牌特写。
  7688. 配音台词:
  7689. 背景音效:
  7690. 分镜4
  7691. 场景:悦来酒馆
  7692. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7693. 运镜:极速推向酒水溅起的瞬间。
  7694. 配音台词:
  7695. 背景音效:
  7696. 分镜5
  7697. 镜头描述
  7698. 场景:悦来酒馆
  7699. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7700. 运镜:固定机位,利用倾斜构图制造压迫感。
  7701. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7702. 背景音效:";
  7703. // 获取模型配置
  7704. $model = getProp($data, 'model');
  7705. if (!$model) {
  7706. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  7707. }
  7708. // 验证模型是否在可用模型表中
  7709. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7710. $model = 'deepseek-v4-pro';
  7711. }
  7712. // 模型兼容性处理
  7713. $thinkingMode = 'disabled';
  7714. $reasoningEffort = 'high';
  7715. if ($model === 'deepseek-chat') {
  7716. $model = 'deepseek-v4-flash';
  7717. $thinkingMode = 'disabled';
  7718. } elseif ($model === 'deepseek-reasoner') {
  7719. $model = 'deepseek-v4-flash';
  7720. $thinkingMode = 'enabled';
  7721. }
  7722. // 构建消息
  7723. $messages = [
  7724. [
  7725. 'role' => 'system',
  7726. 'content' => $system_prompt
  7727. ],
  7728. [
  7729. 'role' => 'user',
  7730. 'content' => $user_prompt
  7731. ]
  7732. ];
  7733. // dd($messages);
  7734. // 构建请求参数
  7735. $post_data = [
  7736. 'model' => $model,
  7737. 'messages' => $messages,
  7738. 'temperature' => 0.7,
  7739. 'frequency_penalty' => 0,
  7740. 'presence_penalty' => 0,
  7741. 'response_format' => ['type' => 'text'],
  7742. 'thinking' => ['type' => $thinkingMode],
  7743. 'stream' => false // 非流式输出
  7744. ];
  7745. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7746. // 调用AI生成新的分段剧本
  7747. try {
  7748. $fullContent = '';
  7749. $usage = [];
  7750. // 根据模型类型选择调用方法
  7751. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7752. // DeepSeek 官方模型使用 DeepSeek API
  7753. $chatResult = $this->chatOnly($post_data);
  7754. } else if (in_array($model, $this->gpt_text_models)) {
  7755. // GPT 模型使用 TokenRouter API
  7756. $chatResult = $this->gpt54ChatOnly($post_data);
  7757. } else {
  7758. // 其他模型使用火山引擎API
  7759. $chatResult = $this->volcEngineChatCompletion($post_data);
  7760. }
  7761. if (is_array($chatResult)) {
  7762. $fullContent = $chatResult['fullContent'] ?? '';
  7763. $usage = $chatResult['usage'] ?? [];
  7764. }
  7765. $generated_content = $fullContent;
  7766. if (empty($generated_content)) {
  7767. Utils::throwError('20003:AI生成内容为空,请重试');
  7768. }
  7769. // 解析生成的内容 - 按片段分割
  7770. $parsed_segments = [];
  7771. // 先在开头添加换行符,确保第1片段也能被正确分割
  7772. $normalizedText = "\n" . $generated_content;
  7773. $parts = preg_split('/\n\s*##/', $normalizedText);
  7774. foreach ($parts as $part) {
  7775. $part = trim($part);
  7776. if (empty($part)) continue;
  7777. // 匹配"片段X"格式
  7778. if (!preg_match('/^片段\d+/', $part)) {
  7779. continue;
  7780. }
  7781. // 分离标题和内容
  7782. $lines = explode("\n", $part, 2);
  7783. $actTitle = trim($lines[0]);
  7784. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  7785. // 解析标题,提取序号
  7786. $actNumber = 0;
  7787. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  7788. $actNumber = intval($segmentTitleMatch[1]);
  7789. } else {
  7790. $actNumber = count($parsed_segments) + 1;
  7791. }
  7792. // 提取时长(仅保留数字)
  7793. $actDuration = 0;
  7794. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  7795. $actDurationStr = trim($actDurationMatch[1]);
  7796. // 提取数字部分(支持整数和小数)
  7797. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  7798. $actDuration = (float)$numMatch[1];
  7799. }
  7800. }
  7801. // 清理act_content:去除时长、旁白音色等非分镜内容行
  7802. // 只保留分镜内容,并确保分镜标记使用【】格式
  7803. $cleaned_content = '';
  7804. $content_lines = explode("\n", $actContent);
  7805. $is_capturing = false; // 标记是否开始捕获分镜内容
  7806. $count = 0;
  7807. foreach ($content_lines as $line) {
  7808. $trimmed_line = trim($line);
  7809. // 跳过时长和旁白音色行
  7810. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  7811. continue;
  7812. }
  7813. // 检测是否是分镜开始
  7814. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  7815. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  7816. $count++;
  7817. $is_capturing = true;
  7818. // 如果没有【】,则添加
  7819. if (!preg_match('/^【/u', $trimmed_line)) {
  7820. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  7821. }
  7822. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  7823. }
  7824. // 如果已经开始捕获,则添加该行
  7825. if ($is_capturing && !empty($trimmed_line)) {
  7826. $cleaned_content .= $trimmed_line."\n";
  7827. }
  7828. }
  7829. $parsed_segments[] = [
  7830. 'act_number' => $actNumber,
  7831. 'act_title' => $actTitle,
  7832. 'act_duration' => $actDuration,
  7833. 'act_content' => $cleaned_content,
  7834. ];
  7835. }
  7836. if (empty($parsed_segments)) {
  7837. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  7838. }
  7839. // 获取角色和场景名称用于标记
  7840. $role_names = [];
  7841. $scene_names = [];
  7842. if (!empty($roles) && is_array($roles)) {
  7843. foreach ($roles as $role) {
  7844. $role_name = getProp($role, 'role', '');
  7845. if (!empty($role_name)) {
  7846. $role_names[] = $role_name;
  7847. }
  7848. }
  7849. }
  7850. if (!empty($scenes) && is_array($scenes)) {
  7851. foreach ($scenes as $scene) {
  7852. $scene_name = getProp($scene, 'scene', '');
  7853. if (!empty($scene_name)) {
  7854. $scene_names[] = $scene_name;
  7855. }
  7856. }
  7857. }
  7858. // 处理每个片段的 act_show_content
  7859. foreach ($parsed_segments as &$segment) {
  7860. $act_content = getProp($segment, 'act_content', '');
  7861. if (empty($act_content)) {
  7862. $segment['act_show_content'] = '';
  7863. continue;
  7864. }
  7865. $processed_content = $act_content;
  7866. // 先匹配场景(在"场景:"后面)
  7867. foreach ($scene_names as $scene_name) {
  7868. // 转义特殊字符
  7869. $escaped_scene = preg_quote($scene_name, '/');
  7870. // 匹配场景:后面的场景名称(可能换行,也可能不换行)
  7871. $pattern = '/(场景:[\s\r\n]*)(' . $escaped_scene . ')/u';
  7872. $processed_content = preg_replace_callback($pattern, function($matches) {
  7873. $prefix = $matches[1];
  7874. $scene_name = $matches[2];
  7875. // 检查是否已经被标记
  7876. if (strpos($scene_name, '{') === false && strpos($scene_name, '}') === false) {
  7877. return $prefix . '{' . $scene_name . '}';
  7878. }
  7879. return $matches[0];
  7880. }, $processed_content);
  7881. }
  7882. // 再匹配角色名称(只在"画面:"部分)
  7883. foreach ($role_names as $role_name) {
  7884. // 转义特殊字符
  7885. $escaped_role = preg_quote($role_name, '/');
  7886. // 只匹配"画面:"开始到换行之前的内容
  7887. $pattern = '/(画面:[^\n]*)/u';
  7888. $processed_content = preg_replace_callback($pattern, function($matches) use ($escaped_role) {
  7889. $line = $matches[1]; // 整行"画面:xxxxx"
  7890. // 在这一行中匹配所有角色名(避免重复标记)
  7891. $new_line = preg_replace(
  7892. '/(?<![{])(' . $escaped_role . ')(?![}])/u',
  7893. '{$1}',
  7894. $line
  7895. );
  7896. return $new_line;
  7897. }, $processed_content);
  7898. }
  7899. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  7900. $shot_counter = 0;
  7901. $processed_content = preg_replace_callback(
  7902. '/【(?:镜头|分镜)(\d+)】/u',
  7903. function($matches) use (&$shot_counter) {
  7904. $shot_counter++;
  7905. return '【镜头' . $shot_counter . '】';
  7906. },
  7907. $processed_content
  7908. );
  7909. $segment['act_show_content'] = $processed_content;
  7910. }
  7911. unset($segment); // 解除引用
  7912. // 保存到数据库
  7913. $now = date('Y-m-d H:i:s');
  7914. $saved_acts = []; // 用于记录保存后的片段信息
  7915. if ($act_id > 0) {
  7916. // 单个片段模式:更新单条记录
  7917. if (count($parsed_segments) > 0) {
  7918. $new_segment = $parsed_segments[0];
  7919. $update_data = [
  7920. 'act_content' => getProp($new_segment, 'act_content', ''),
  7921. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  7922. 'act_title' => getProp($new_segment, 'act_title', ''),
  7923. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  7924. 'updated_at' => $now,
  7925. ];
  7926. DB::table('mp_episode_segments')
  7927. ->where('id', $act_id)
  7928. ->update($update_data);
  7929. // 获取更新后的记录
  7930. $updated_act = DB::table('mp_episode_segments')
  7931. ->where('id', $act_id)
  7932. ->first();
  7933. if ($updated_act) {
  7934. $saved_acts[] = [
  7935. 'act_id' => $updated_act->id,
  7936. 'act_number' => $updated_act->act_number,
  7937. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  7938. 'act_content' => $updated_act->act_content,
  7939. 'act_show_content' => $updated_act->act_show_content,
  7940. 'video_url' => $updated_act->video_url ?? '',
  7941. 'video_duration' => $updated_act->video_duration ?? 0,
  7942. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  7943. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  7944. ];
  7945. }
  7946. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  7947. }
  7948. } else {
  7949. // 整个剧集模式:删除原有记录并批量保存新记录
  7950. DB::beginTransaction();
  7951. try {
  7952. // 删除原有的所有片段记录
  7953. DB::table('mp_episode_segments')
  7954. ->where('episode_id', $target_episode_id)
  7955. ->delete();
  7956. // 批量插入新的片段记录
  7957. $segments_to_insert = [];
  7958. foreach ($parsed_segments as $index => $segment) {
  7959. $act_number = $index + 1;
  7960. $segments_to_insert[] = [
  7961. 'anime_id' => $target_anime_id,
  7962. 'episode_id' => $target_episode_id,
  7963. 'episode_number' => $target_episode_number,
  7964. 'act_number' => $act_number,
  7965. 'act_title' => getProp($segment, 'act_title', ''),
  7966. 'act_duration' => getProp($segment, 'act_duration', 0),
  7967. 'act_content' => getProp($segment, 'act_content', ''),
  7968. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  7969. 'created_at' => $now,
  7970. 'updated_at' => $now,
  7971. ];
  7972. }
  7973. if (!empty($segments_to_insert)) {
  7974. DB::table('mp_episode_segments')->insert($segments_to_insert);
  7975. }
  7976. DB::commit();
  7977. // 查询保存后的所有片段记录
  7978. $saved_segments = DB::table('mp_episode_segments')
  7979. ->where('episode_id', $target_episode_id)
  7980. ->orderBy('act_number')
  7981. ->get();
  7982. foreach ($saved_segments as $saved_segment) {
  7983. $saved_acts[] = [
  7984. 'act_id' => $saved_segment->id,
  7985. 'act_number' => $saved_segment->act_number,
  7986. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  7987. 'act_content' => $saved_segment->act_content,
  7988. 'act_show_content' => $saved_segment->act_show_content,
  7989. 'video_url' => $saved_segment->video_url ?? '',
  7990. 'video_duration' => $saved_segment->video_duration ?? 0,
  7991. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  7992. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  7993. ];
  7994. }
  7995. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  7996. 'episode_id' => $target_episode_id,
  7997. 'segments_count' => count($segments_to_insert)
  7998. ]);
  7999. } catch (\Exception $e) {
  8000. DB::rollBack();
  8001. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  8002. Utils::throwError('20003:保存失败,请重试');
  8003. }
  8004. }
  8005. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  8006. return [
  8007. 'anime_id' => $target_anime_id,
  8008. 'episode_id' => $target_episode_id,
  8009. 'title' => getProp($episode, 'title', ''),
  8010. 'episode_number' => $target_episode_number,
  8011. 'is_generated' => getProp($episode, 'is_generated', 0),
  8012. 'acts' => $saved_acts,
  8013. ];
  8014. } catch (\Exception $e) {
  8015. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  8016. throw $e;
  8017. }
  8018. }
  8019. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  8020. {
  8021. $episode_arr = [
  8022. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  8023. 'intro' => getProp($script_arr, 'intro'),
  8024. 'art_style' => getProp($script_arr, 'art_style'),
  8025. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8026. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8027. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  8028. ];
  8029. if (empty($episode_arr['acts'])) {
  8030. $fallback_episode_arr = handleEpisodeContent($fullContent);
  8031. if (!empty($fallback_episode_arr['acts'])) {
  8032. $episode_arr = array_merge($fallback_episode_arr, [
  8033. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  8034. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  8035. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  8036. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  8037. ]);
  8038. }
  8039. }
  8040. // if (!getProp($episode_arr, 'episode_title')) {
  8041. // $episode_title = '';
  8042. // $episodes = getProp($script_arr, 'episodes', []);
  8043. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  8044. // $episode_title = '第1集:' . $episodes[0]['title'];
  8045. // }
  8046. // if (!$episode_title) {
  8047. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  8048. // }
  8049. // $episode_arr['episode_title'] = $episode_title;
  8050. // }
  8051. return $episode_arr;
  8052. }
  8053. private function saveEpisodeVersionData(
  8054. int $anime_id,
  8055. int $episode_number,
  8056. array $episode_arr,
  8057. array $existing_roles,
  8058. array $existing_scenes,
  8059. $current_episode,
  8060. $base_episode,
  8061. bool $is_regenerate_version,
  8062. string $content,
  8063. string $now,
  8064. array $ref_products = []
  8065. ): array {
  8066. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  8067. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  8068. $merged_roles = $generated_roles;
  8069. $merged_scenes = $generated_scenes;
  8070. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  8071. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  8072. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  8073. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8074. $ace_mode = getProp($anime, 'ace_mode');
  8075. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  8076. $global_roles = json_decode(getProp($anime, 'roles'), true);
  8077. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  8078. $global_roles = is_array($global_roles) ? $global_roles : [];
  8079. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  8080. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  8081. $art_style_type = getProp($anime, 'art_style_type');
  8082. // 检查并创建 roles 的图片生成任务
  8083. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  8084. // 检查并创建 scenes 的图片生成任务
  8085. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  8086. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $ref_products, $art_style_type);
  8087. if ($arr && is_array($arr)) {
  8088. $merged_roles = $arr['roles'];
  8089. $merged_scenes = $arr['scenes'];
  8090. }
  8091. // 确保数据是数组类型
  8092. if (!is_array($merged_roles)) {
  8093. dLog('deepseek')->error('merged_roles不是数组类型', [
  8094. 'type' => gettype($merged_roles),
  8095. 'value' => $merged_roles
  8096. ]);
  8097. $merged_roles = [];
  8098. }
  8099. if (!is_array($merged_scenes)) {
  8100. dLog('deepseek')->error('merged_scenes不是数组类型', [
  8101. 'type' => gettype($merged_scenes),
  8102. 'value' => $merged_scenes
  8103. ]);
  8104. $merged_scenes = [];
  8105. }
  8106. // 同步新出现的主体和场景到全局
  8107. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  8108. $role_arr = [];
  8109. foreach ($merged_roles as $item) {
  8110. $role_arr[$item['role']] = $item;
  8111. }
  8112. $version_count = DB::table('mp_anime_episodes')
  8113. ->where('anime_id', $anime_id)
  8114. ->where('episode_number', $episode_number)
  8115. ->count('id');
  8116. $episode = [
  8117. 'anime_id' => $anime_id,
  8118. 'episode_number' => $episode_number,
  8119. 'title' => getProp($episode_arr, 'episode_title'),
  8120. 'content' => $content,
  8121. 'intro' => getProp($episode_arr, 'intro'),
  8122. 'art_style' => getProp($episode_arr, 'art_style'),
  8123. 'roles' => json_encode($merged_roles, 256),
  8124. 'scenes' => json_encode($merged_scenes, 256),
  8125. 'generate_status' => '待执行',
  8126. 'generate_at' => $now,
  8127. 'is_default' => 1,
  8128. 'updated_at' => $now,
  8129. ];
  8130. $del_flag = false;
  8131. if ($is_regenerate_version) {
  8132. DB::table('mp_anime_episodes')
  8133. ->where('anime_id', $anime_id)
  8134. ->where('episode_number', $episode_number)
  8135. ->update(['is_default' => 0, 'updated_at' => $now]);
  8136. $episode['sequence'] = $version_count + 1;
  8137. $episode['created_at'] = $now;
  8138. $episode['cpid'] = Site::getCpid();
  8139. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  8140. if (!$episode_id) {
  8141. Utils::throwError('20003:创建剧集版本失败');
  8142. }
  8143. } else {
  8144. $target_episode = $current_episode ?: $base_episode;
  8145. if ($target_episode) {
  8146. $episode_id = getProp($target_episode, 'id');
  8147. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  8148. DB::table('mp_anime_episodes')
  8149. ->where('anime_id', $anime_id)
  8150. ->where('episode_number', $episode_number)
  8151. ->where('id', '<>', $episode_id)
  8152. ->update(['is_default' => 0, 'updated_at' => $now]);
  8153. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  8154. if ($boolen === false) {
  8155. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  8156. Utils::throwError('20003:分集内容保存失败');
  8157. }
  8158. $del_flag = true;
  8159. } else {
  8160. DB::table('mp_anime_episodes')
  8161. ->where('anime_id', $anime_id)
  8162. ->where('episode_number', $episode_number)
  8163. ->update(['is_default' => 0, 'updated_at' => $now]);
  8164. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  8165. $episode['created_at'] = $now;
  8166. $episode['cpid'] = Site::getCpid();
  8167. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  8168. if (!$episode_id) {
  8169. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  8170. Utils::throwError('20003:分集内容保存失败');
  8171. }
  8172. }
  8173. }
  8174. $segments = [];
  8175. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  8176. // 如果是第2集及以后,获取上一集的主体音色数据
  8177. $previous_roles_voice = [];
  8178. if ($episode_number >= 2) {
  8179. $previous_episode = DB::table('mp_anime_episodes')
  8180. ->where('anime_id', $anime_id)
  8181. ->where('episode_number', $episode_number - 1)
  8182. ->where('is_default', 1)
  8183. ->first();
  8184. if ($previous_episode) {
  8185. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  8186. if (is_array($previous_roles)) {
  8187. foreach ($previous_roles as $prev_role) {
  8188. $role_name = getProp($prev_role, 'role');
  8189. if ($role_name) {
  8190. $previous_roles_voice[$role_name] = [
  8191. 'voice_name' => getProp($prev_role, 'voice_name'),
  8192. 'voice_type' => getProp($prev_role, 'voice_type'),
  8193. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  8194. ];
  8195. $voice_prompt = getProp($prev_role, 'voice_prompt');
  8196. if ($voice_prompt) {
  8197. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  8198. }
  8199. }
  8200. }
  8201. }
  8202. }
  8203. }
  8204. // 将继承的音色数据同步到当前集的主体列表
  8205. if (!empty($previous_roles_voice)) {
  8206. foreach ($merged_roles as &$role) {
  8207. $role_name = getProp($role, 'role');
  8208. if ($role_name && isset($previous_roles_voice[$role_name])) {
  8209. // 强制继承上一集的音色数据
  8210. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  8211. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  8212. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  8213. // 如果上一集有 voice_prompt 则继承,否则跳过
  8214. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  8215. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  8216. }
  8217. }
  8218. }
  8219. unset($role); // 解除引用
  8220. // 更新 role_arr 以便后续使用
  8221. $role_arr = [];
  8222. foreach ($merged_roles as $item) {
  8223. $role_arr[$item['role']] = $item;
  8224. }
  8225. }
  8226. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  8227. $emotion_list = array_flip($emotion_list);
  8228. foreach ($acts as $act) {
  8229. $act_segments = getProp($act, 'segments', []);
  8230. if (!is_array($act_segments)) {
  8231. continue;
  8232. }
  8233. if ((int)$ace_mode === 1) {
  8234. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  8235. $merged_parts = [];
  8236. foreach ($act_segments as $seg) {
  8237. $seg_num = getProp($seg, 'segment_number');
  8238. $seg_content = getProp($seg, 'segment_content');
  8239. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  8240. }
  8241. $act_content = implode("\n", $merged_parts);
  8242. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  8243. $segments[] = [
  8244. 'anime_id' => $anime_id,
  8245. 'episode_id' => $episode_id,
  8246. 'episode_number' => $episode_number,
  8247. 'act_number' => getProp($act, 'act_number'),
  8248. 'act_title' => getProp($act, 'act_title'),
  8249. 'act_duration' => getProp($act, 'act_duration'),
  8250. 'act_content' => $act_content,
  8251. 'created_at' => $now,
  8252. 'updated_at' => $now
  8253. ];
  8254. } else {
  8255. foreach ($act_segments as $segment) {
  8256. $voice_actor = getProp($segment, 'voice_actor');
  8257. // 优先从上一集继承音色数据
  8258. $timbre_info = [];
  8259. if (isset($previous_roles_voice[$voice_actor])) {
  8260. // 从上一集继承音色数据
  8261. $timbre_info = $previous_roles_voice[$voice_actor];
  8262. } elseif (isset($role_arr[$voice_actor])) {
  8263. // 使用当前集的主体音色数据
  8264. $timbre_info = $role_arr[$voice_actor];
  8265. }
  8266. $voice_type = getProp($timbre_info, 'voice_type');
  8267. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  8268. if ($timbre_emotion) {
  8269. $timbre_emotion = explode(',', $timbre_emotion);
  8270. } else {
  8271. $timbre_emotion = [];
  8272. }
  8273. $emotion = getProp($segment, 'emotion', '中性');
  8274. if (!in_array($emotion, $timbre_emotion)) {
  8275. $emotion = '中性';
  8276. }
  8277. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  8278. $segments[] = [
  8279. 'anime_id' => $anime_id,
  8280. 'episode_id' => $episode_id,
  8281. 'episode_number' => $episode_number,
  8282. 'act_number' => getProp($act, 'act_number'),
  8283. 'act_title' => getProp($act, 'act_title'),
  8284. 'act_duration' => getProp($act, 'act_duration'),
  8285. 'segment_id' => getProp($segment, 'segment_id'),
  8286. 'segment_number' => getProp($segment, 'segment_number'),
  8287. 'segment_content' => getProp($segment, 'segment_content'),
  8288. 'description' => getProp($segment, 'description'),
  8289. 'composition' => getProp($segment, 'composition'),
  8290. 'camera_movement' => getProp($segment, 'camera_movement'),
  8291. 'voice_actor' => $voice_actor,
  8292. 'dialogue' => getProp($segment, 'dialogue'),
  8293. 'frame_type' => getProp($segment, 'frame_type'),
  8294. 'scene' => getProp($segment, 'scene'),
  8295. 'characters' => getProp($segment, 'characters'),
  8296. 'tail_frame' => getProp($segment, 'tail_frame'),
  8297. 'voice_name' => getProp($timbre_info, 'voice_name'),
  8298. 'voice_type' => $voice_type,
  8299. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  8300. 'emotion' => $emotion,
  8301. 'emotion_type' => $emotion_type,
  8302. 'gender' => getProp($segment, 'gender', '0'),
  8303. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  8304. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  8305. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  8306. 'pitch' => getProp($segment, 'pitch', 0),
  8307. 'created_at' => $now,
  8308. 'updated_at' => $now
  8309. ];
  8310. }
  8311. }
  8312. }
  8313. if ($segments) {
  8314. if ($del_flag) {
  8315. DB::table('mp_episode_segments')
  8316. ->where('anime_id', $anime_id)
  8317. ->where('episode_id', $episode_id)
  8318. ->delete();
  8319. }
  8320. $boolen = DB::table('mp_episode_segments')->insert($segments);
  8321. if (!$boolen) {
  8322. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  8323. Utils::throwError('20003:分镜内容保存失败');
  8324. }
  8325. }
  8326. dLog('deepseek')->info('segments', $segments);
  8327. // ace_mode=1: acts 返回值按合并格式调整
  8328. if ((int)$ace_mode === 1) {
  8329. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  8330. $act_map = [];
  8331. foreach ($table_act_data as $item) {
  8332. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  8333. }
  8334. $restructured_acts = [];
  8335. foreach ($acts as $act) {
  8336. $act_segments = getProp($act, 'segments', []);
  8337. if (!is_array($act_segments)) {
  8338. continue;
  8339. }
  8340. $merged_parts = [];
  8341. foreach ($act_segments as $seg) {
  8342. $seg_num = getProp($seg, 'segment_number');
  8343. $seg_content = getProp($seg, 'segment_content');
  8344. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  8345. }
  8346. $act_content = implode("\n", $merged_parts);
  8347. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  8348. $restructured_acts[] = [
  8349. 'anime_id' => $anime_id,
  8350. 'episode_id' => $episode_id,
  8351. 'episode_number' => $episode_number,
  8352. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  8353. 'act_number' => getProp($act, 'act_number'),
  8354. 'act_title' => getProp($act, 'act_title'),
  8355. 'act_duration' => getProp($act, 'act_duration'),
  8356. 'act_content' => $act_content,
  8357. 'created_at' => $now,
  8358. 'updated_at' => $now,
  8359. ];
  8360. }
  8361. $acts = $restructured_acts;
  8362. }
  8363. $episode['episode_id'] = $episode_id;
  8364. $episode['roles'] = $merged_roles;
  8365. $episode['scenes'] = $merged_scenes;
  8366. $episode['acts'] = $acts;
  8367. return [
  8368. 'episode' => $episode,
  8369. 'episode_id' => $episode_id,
  8370. 'merged_roles' => $merged_roles,
  8371. 'merged_scenes' => $merged_scenes,
  8372. ];
  8373. }
  8374. private function buildEpisodeItemContent(array $items, string $nameKey): string
  8375. {
  8376. $content = '';
  8377. foreach ($items as $item) {
  8378. $name = trim((string)getProp($item, $nameKey));
  8379. if ($name === '' || $name === '旁白') {
  8380. continue;
  8381. }
  8382. $description = trim((string)getProp($item, 'description'));
  8383. $content .= $name . ': ' . $description;
  8384. if ($nameKey == 'role') {
  8385. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  8386. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  8387. $voice_name = trim(getProp($item, 'voice_name'));
  8388. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  8389. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  8390. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  8391. }else {
  8392. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  8393. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  8394. }
  8395. $content .= "\n";
  8396. }
  8397. return trim($content);
  8398. }
  8399. private function getEpisodeChatContent($animeId, $sequence, $content) {
  8400. if ((int)$sequence <= 0) {
  8401. return [];
  8402. }
  8403. $origin_content = '';
  8404. if ($content) {
  8405. $origin_content = '本集剧情内容:'.$content;
  8406. }else {
  8407. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  8408. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  8409. }
  8410. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  8411. // 获取分集信息
  8412. $episode = DB::table('mp_anime_episodes')
  8413. ->where('anime_id', $animeId)
  8414. ->where('episode_number', $sequence)
  8415. ->where('is_default', 1)
  8416. ->first();
  8417. if (!$episode) {
  8418. return [];
  8419. }
  8420. $episode_id = getProp($episode, 'id');
  8421. $episode_number = getProp($episode, 'episode_number');
  8422. $title = getProp($episode, 'title');
  8423. $intro = getProp($episode, 'intro');
  8424. $art_style = getProp($episode, 'art_style');
  8425. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  8426. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  8427. // 组装纯文本内容
  8428. $content = '';
  8429. // 添加分集标题和梗概
  8430. $content .= "###第{$episode_number}集:{$title}\n\n";
  8431. $content .= "###故事梗概\n";
  8432. $content .= trim($intro) . "\n\n";
  8433. // 添加美术风格
  8434. $content .= "###美术风格\n";
  8435. $content .= trim($art_style) . "\n\n";
  8436. // 添加主体列表
  8437. $content .= "###主体列表\n";
  8438. $pangbai_voice_prompt = "";
  8439. foreach ($roles as $role) {
  8440. $name = getProp($role, 'role');
  8441. $description = getProp($role, 'description');
  8442. $pic_prompt = getProp($role, 'pic_prompt');
  8443. $voice_prompt = getProp($role, 'voice_prompt');
  8444. $voice_name = getProp($role, 'voice_name');
  8445. $content .= "{$name}: {$description}";
  8446. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  8447. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  8448. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  8449. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  8450. $content .= "\n";
  8451. }
  8452. $content .= "\n";
  8453. // 添加场景列表
  8454. $content .= "###场景列表\n";
  8455. foreach ($scenes as $scene) {
  8456. $name = getProp($scene, 'scene');
  8457. $description = getProp($scene, 'description');
  8458. $pic_prompt = getProp($scene, 'pic_prompt');
  8459. $content .= "{$name}: {$description}";
  8460. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  8461. $content .= "\n";
  8462. }
  8463. $content .= "\n";
  8464. // 获取分镜信息
  8465. $segments = DB::table('mp_episode_segments')
  8466. ->where('anime_id', $animeId)
  8467. ->where('episode_id', $episode_id)
  8468. ->orderBy('segment_number')
  8469. ->get();
  8470. if ($segments && count($segments) > 0) {
  8471. if ((int)$ace_mode === 1) {
  8472. $content .= "###分段剧本\n";
  8473. // 获取片段数量
  8474. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  8475. $content .= "片段数量:{$act_count}\n";
  8476. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  8477. $content .= "\n";
  8478. }else {
  8479. $content .= "###分镜剧本\n";
  8480. }
  8481. // 按幕分组
  8482. $currentAct = null;
  8483. foreach ($segments as $segment) {
  8484. $act_number = getProp($segment, 'act_number');
  8485. $act_title = getProp($segment, 'act_title');
  8486. $act_duration = getProp($segment, 'act_duration');
  8487. $segment_number = getProp($segment, 'segment_number');
  8488. $segment_content = getProp($segment, 'segment_content');
  8489. $scene_description = getProp($segment, 'scene_description');
  8490. $scene_name = getProp($segment, 'scene_name');
  8491. $composition = getProp($segment, 'composition');
  8492. $camera_movement = getProp($segment, 'camera_movement');
  8493. $voice_type = getProp($segment, 'voice_type');
  8494. $characters = getProp($segment, 'characters');
  8495. $dialogue = getProp($segment, 'dialogue');
  8496. $frame_type = getProp($segment, 'frame_type');
  8497. $tail_frame_description = getProp($segment, 'tail_frame_description');
  8498. // 判断是否是全能模式
  8499. if ((int)$ace_mode === 1) { // 全能模式
  8500. // 如果是新的分段,添加分段标题
  8501. if ($act_number !== $currentAct) {
  8502. $currentAct = $act_number;
  8503. $content .= "##{$act_title}\n";
  8504. $content .= "时长:{$act_duration}s\n";
  8505. }
  8506. }else {
  8507. // 如果是新的幕,添加幕标题
  8508. if ($act_number !== $currentAct) {
  8509. $currentAct = $act_number;
  8510. $content .= "##第{$act_number}幕:{$scene_name}\n";
  8511. }
  8512. }
  8513. // 添加分镜信息
  8514. $content .= "分镜{$segment_number}\n";
  8515. $content .= "分镜内容:\n{$segment_content}\n";
  8516. // $content .= "画面描述:{$scene_description}\n";
  8517. // $content .= "场景:{$scene_name}\n";
  8518. // $content .= "构图设计:{$composition}\n";
  8519. // $content .= "运镜调度:{$camera_movement}\n";
  8520. // if (!empty($voice_type)) {
  8521. // $content .= "配音角色:{$voice_type}\n";
  8522. // }
  8523. // if (!empty($characters)) {
  8524. // $content .= "出镜角色:{$characters}\n";
  8525. // }
  8526. // if (!empty($dialogue)) {
  8527. // $content .= "台词内容:\"{$dialogue}\"\n";
  8528. // }
  8529. // $content .= "画面类型:{$frame_type}\n";
  8530. // $content .= "尾帧描述:{$tail_frame_description}\n";
  8531. $content .= "\n";
  8532. }
  8533. }
  8534. $content = trim($content);
  8535. if($content) $content = "上集剧本内容:\n{$content}";
  8536. return [
  8537. [
  8538. 'role' => 'user',
  8539. 'content' => $origin_content
  8540. ],
  8541. [
  8542. 'role' => 'assistant',
  8543. 'content' => $content
  8544. ]
  8545. ];
  8546. }
  8547. private function getEpisodeChatMessages($animeId, $sequence): array
  8548. {
  8549. if ((int)$sequence <= 0) {
  8550. return [];
  8551. }
  8552. return DB::table('mp_anime_records')
  8553. ->where('anime_id', $animeId)
  8554. ->where('sequence', $sequence)
  8555. ->where('episode_id', '>', 0)
  8556. ->select('role', 'content')
  8557. ->orderBy('created_at')
  8558. ->orderBy('id')
  8559. ->get()
  8560. ->map(function ($value) {
  8561. return (array)$value;
  8562. })
  8563. ->toArray();
  8564. }
  8565. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  8566. {
  8567. $existingMap = [];
  8568. foreach ($existingItems as $item) {
  8569. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  8570. if ($itemKey === '') {
  8571. continue;
  8572. }
  8573. $existingMap[$itemKey] = $item;
  8574. }
  8575. if (!$generatedItems) {
  8576. return array_values($existingItems);
  8577. }
  8578. $merged = [];
  8579. foreach ($generatedItems as $item) {
  8580. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  8581. if ($itemKey === '') {
  8582. continue;
  8583. }
  8584. if (isset($existingMap[$itemKey])) {
  8585. if (trim((string)getProp($item, 'description')) === '') {
  8586. $merged[] = $existingMap[$itemKey];
  8587. continue;
  8588. }
  8589. // 检查内容是否发生变化
  8590. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  8591. if (!$isChanged) {
  8592. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  8593. $mergedItem = [
  8594. $nameKey => trim((string)getProp($item, $nameKey)),
  8595. 'description' => trim((string)getProp($item, 'description')),
  8596. ];
  8597. // 如果有 pic_prompt,添加到合并项中
  8598. $picPrompt = getProp($item, 'pic_prompt');
  8599. if (!empty($picPrompt)) {
  8600. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  8601. }
  8602. // 继承现有项的 URL
  8603. $existingUrl = getProp($existingMap[$itemKey], 'url');
  8604. if (!empty($existingUrl)) {
  8605. $mergedItem['url'] = $existingUrl;
  8606. }
  8607. // 继承现有项的 task_id
  8608. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  8609. if (!empty($existingTaskId)) {
  8610. $mergedItem['task_id'] = $existingTaskId;
  8611. }
  8612. // 继承现有项的 task_status
  8613. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  8614. if (!empty($existingTaskStatus)) {
  8615. $mergedItem['task_status'] = $existingTaskStatus;
  8616. }
  8617. // 保留生成项的音色字段
  8618. $voiceName = getProp($item, 'voice_name');
  8619. if (!empty($voiceName)) {
  8620. $mergedItem['voice_name'] = $voiceName;
  8621. }
  8622. $voiceType = getProp($item, 'voice_type');
  8623. if (!empty($voiceType)) {
  8624. $mergedItem['voice_type'] = $voiceType;
  8625. }
  8626. $audioUrl = getProp($item, 'voice_audio_url');
  8627. if (!empty($audioUrl)) {
  8628. $mergedItem['voice_audio_url'] = $audioUrl;
  8629. }
  8630. $merged[] = $mergedItem;
  8631. } else {
  8632. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  8633. $mergedItem = [
  8634. $nameKey => trim((string)getProp($item, $nameKey)),
  8635. 'description' => trim((string)getProp($item, 'description')),
  8636. ];
  8637. // 如果有 pic_prompt,添加到合并项中
  8638. $picPrompt = getProp($item, 'pic_prompt');
  8639. if (!empty($picPrompt)) {
  8640. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  8641. }
  8642. // 保留生成项的音色字段
  8643. $voiceName = getProp($item, 'voice_name');
  8644. if (!empty($voiceName)) {
  8645. $mergedItem['voice_name'] = $voiceName;
  8646. }
  8647. $voiceType = getProp($item, 'voice_type');
  8648. if (!empty($voiceType)) {
  8649. $mergedItem['voice_type'] = $voiceType;
  8650. }
  8651. $audioUrl = getProp($item, 'voice_audio_url');
  8652. if (!empty($audioUrl)) {
  8653. $mergedItem['voice_audio_url'] = $audioUrl;
  8654. }
  8655. // 不继承 URL、task_id 和 task_status(重置状态)
  8656. $merged[] = $mergedItem;
  8657. }
  8658. } else {
  8659. // 新增项,保留生成项的所有字段
  8660. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  8661. }
  8662. }
  8663. return $merged ?: array_values($existingItems);
  8664. }
  8665. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  8666. {
  8667. $resetItem = [
  8668. $nameKey => trim((string)getProp($item, $nameKey)),
  8669. 'description' => trim((string)getProp($item, 'description')),
  8670. ];
  8671. // 保留指定的字段
  8672. foreach ($preserveFields as $field) {
  8673. $value = getProp($item, $field);
  8674. if (!empty($value)) {
  8675. $resetItem[$field] = $value;
  8676. }
  8677. }
  8678. return $resetItem;
  8679. }
  8680. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  8681. {
  8682. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  8683. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  8684. if ($existingKey !== $generatedKey) {
  8685. return true;
  8686. }
  8687. // 比较 description 是否变化
  8688. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  8689. return true;
  8690. }
  8691. // 比较 pic_prompt 是否变化
  8692. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  8693. }
  8694. private function normalizeEpisodeResourceKey($value): string
  8695. {
  8696. $value = trim((string)$value);
  8697. if ($value === '') {
  8698. return '';
  8699. }
  8700. return strtolower((string)preg_replace('/\s+/u', '', $value));
  8701. }
  8702. // 生成全局角色图片
  8703. private function batchSetGlobalRoleImg($data, $is_force=false) {
  8704. $anime_id = getProp($data, 'anime_id');
  8705. if (!$anime_id) Utils::throwError('1002:请选择对话');
  8706. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  8707. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  8708. $art_style = getProp($anime, 'art_style');
  8709. $update_flag = false;
  8710. foreach ($roles as &$role) {
  8711. $role_name = getProp($role, 'role');
  8712. if ($role_name == '旁白') continue;
  8713. // 优先使用 pic_prompt,如果没有则使用 description
  8714. $pic_prompt = getProp($role, 'pic_prompt');
  8715. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  8716. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  8717. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  8718. // 参考图地址
  8719. $ref_img_url = getProp($role, 'url');
  8720. if (!$is_force && $ref_img_url) continue;
  8721. $update_flag = true;
  8722. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  8723. try {
  8724. $params = [
  8725. 'prompt' => $description,
  8726. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  8727. 'ref_img_urls' => []
  8728. ];
  8729. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8730. $task_id = $task->id;
  8731. if (!$task_id) {
  8732. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  8733. }
  8734. $role['task_id'] = $task_id;
  8735. $role['task_status'] = 'processing';
  8736. } catch (\Exception $e) {
  8737. Utils::throwError("20003:" . $e->getMessage());
  8738. }
  8739. }
  8740. if (!$update_flag) return true;
  8741. // 保存角色信息
  8742. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  8743. 'roles' => json_encode($roles, 256),
  8744. 'generate_status' => '执行中',
  8745. 'generate_at' => date('Y-m-d H:i:s'),
  8746. 'updated_at' => date('Y-m-d H:i:s')
  8747. ]);
  8748. if (!$boolen) {
  8749. Utils::throwError('20003:保存角色信息失败');
  8750. }
  8751. return $boolen;
  8752. }
  8753. // 生成全局场景图片
  8754. private function batchSetGlobalSceneImg($data, $is_force=false) {
  8755. $anime_id = getProp($data, 'anime_id');
  8756. if (!$anime_id) Utils::throwError('1002:请选择对话');
  8757. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  8758. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  8759. $art_style = getProp($anime, 'art_style');
  8760. $update_flag = false;
  8761. foreach ($scenes as &$scene) {
  8762. $scene_name = getProp($scene, 'scene');
  8763. // 优先使用 pic_prompt,如果没有则使用 description
  8764. $pic_prompt = getProp($scene, 'pic_prompt');
  8765. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  8766. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  8767. // 参考图地址
  8768. $ref_img_url = getProp($scene, 'url');
  8769. if (!$is_force && $ref_img_url) continue;
  8770. $update_flag = true;
  8771. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  8772. try {
  8773. $params = [
  8774. 'prompt' => $description,
  8775. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  8776. 'ref_img_urls' => []
  8777. ];
  8778. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8779. $task_id = $task->id;
  8780. if (!$task_id) {
  8781. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  8782. }
  8783. $scene['task_id'] = $task_id;
  8784. $scene['task_status'] = 'processing';
  8785. } catch (\Exception $e) {
  8786. Utils::throwError("20003:" . $e->getMessage());
  8787. }
  8788. }
  8789. if (!$update_flag) return true;
  8790. // 保存角色信息
  8791. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  8792. 'scenes' => json_encode($scenes, 256),
  8793. 'generate_status' => '执行中',
  8794. 'generate_at' => date('Y-m-d H:i:s'),
  8795. 'updated_at' => date('Y-m-d H:i:s')
  8796. ]);
  8797. if (!$boolen) {
  8798. Utils::throwError('20003:保存角色信息失败');
  8799. }
  8800. return $boolen;
  8801. }
  8802. // 生成分镜主体和场景图片
  8803. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $ref_products=[], $art_style_type='', $is_force=false) {
  8804. $character_prefix = '';
  8805. $scene_prefix = '';
  8806. if ($art_style_type) {
  8807. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  8808. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  8809. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  8810. }
  8811. $update_flag = false;
  8812. // 获取上一集的roles和scenes数据
  8813. $prev_roles = [];
  8814. $prev_scenes = [];
  8815. if ($episode_number > 1) {
  8816. $prev_episode = DB::table('mp_anime_episodes')
  8817. ->where('anime_id', $anime_id)
  8818. ->where('episode_number', $episode_number - 1)
  8819. ->where('is_default', 1)
  8820. ->first();
  8821. if ($prev_episode) {
  8822. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  8823. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  8824. dLog('deepseek')->info("获取上一集数据成功", [
  8825. 'anime_id' => $anime_id,
  8826. 'prev_episode_number' => $episode_number - 1,
  8827. 'prev_roles_count' => count($prev_roles),
  8828. 'prev_scenes_count' => count($prev_scenes)
  8829. ]);
  8830. }
  8831. }
  8832. // 处理角色图片生成
  8833. foreach ($roles as &$role) {
  8834. $role_name = getProp($role, 'role');
  8835. if ($role_name == '旁白') continue;
  8836. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  8837. if (isset($ref_products[$role_name])) {
  8838. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  8839. if ($role['url']) continue;
  8840. }
  8841. $role_description = getProp($role, 'description');
  8842. $role_pic_prompt = getProp($role, 'pic_prompt');
  8843. $role_url = getProp($role, 'url');
  8844. // 检查是否可以从上一集继承
  8845. $inherited = false;
  8846. if (!$is_force && !empty($prev_roles)) {
  8847. foreach ($prev_roles as $prev_role) {
  8848. $prev_role_name = getProp($prev_role, 'role');
  8849. $prev_description = getProp($prev_role, 'description');
  8850. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  8851. $prev_url = getProp($prev_role, 'url');
  8852. $prev_task_id = getProp($prev_role, 'task_id');
  8853. $prev_task_status = getProp($prev_role, 'task_status');
  8854. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  8855. if ($role_name == $prev_role_name
  8856. && $role_description == $prev_description
  8857. && $role_pic_prompt == $prev_pic_prompt
  8858. && !empty($prev_url)) {
  8859. $role['task_id'] = $prev_task_id;
  8860. $role['task_status'] = $prev_task_status;
  8861. $role['url'] = $prev_url;
  8862. $inherited = true;
  8863. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  8864. 'anime_id' => $anime_id,
  8865. 'episode_number' => $episode_number,
  8866. 'task_id' => $prev_task_id,
  8867. 'url' => $prev_url
  8868. ]);
  8869. break;
  8870. }
  8871. }
  8872. }
  8873. // 如果已继承或已有url,跳过生成
  8874. if ($inherited || (!$is_force && $role_url)) {
  8875. continue;
  8876. }
  8877. // 优先使用 pic_prompt,如果没有则使用 description
  8878. $pic_prompt = getProp($role, 'pic_prompt');
  8879. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  8880. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  8881. $update_flag = true;
  8882. // 调用AIImageGenerationService的生成图片任务接口
  8883. try {
  8884. $params = [
  8885. 'prompt' => $description,
  8886. 'ref_img_urls' => []
  8887. ];
  8888. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8889. $task_id = $task->id;
  8890. if (!$task_id) {
  8891. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  8892. continue; // 不中断,继续处理其他角色
  8893. }
  8894. $role['task_id'] = $task_id;
  8895. $role['task_status'] = 'processing';
  8896. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  8897. 'anime_id' => $anime_id,
  8898. 'episode_number' => $episode_number,
  8899. 'task_id' => $task_id
  8900. ]);
  8901. } catch (\Exception $e) {
  8902. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  8903. // 不抛出异常,继续处理其他角色
  8904. }
  8905. }
  8906. // 处理场景图片生成
  8907. foreach ($scenes as &$scene) {
  8908. $scene_name = getProp($scene, 'scene');
  8909. $scene_description = getProp($scene, 'description');
  8910. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  8911. $scene_url = getProp($scene, 'url');
  8912. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  8913. if (isset($ref_products[$scene_name])) {
  8914. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  8915. if ($scene['url']) continue;
  8916. }
  8917. // 检查是否可以从上一集继承
  8918. $inherited = false;
  8919. if (!$is_force && !empty($prev_scenes)) {
  8920. foreach ($prev_scenes as $prev_scene) {
  8921. $prev_scene_name = getProp($prev_scene, 'scene');
  8922. $prev_description = getProp($prev_scene, 'description');
  8923. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  8924. $prev_url = getProp($prev_scene, 'url');
  8925. $prev_task_id = getProp($prev_scene, 'task_id');
  8926. $prev_task_status = getProp($prev_scene, 'task_status');
  8927. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  8928. if ($scene_name == $prev_scene_name
  8929. && $scene_description == $prev_description
  8930. && $scene_pic_prompt == $prev_pic_prompt
  8931. && !empty($prev_url)) {
  8932. $scene['task_id'] = $prev_task_id;
  8933. $scene['task_status'] = $prev_task_status;
  8934. $scene['url'] = $prev_url;
  8935. $inherited = true;
  8936. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  8937. 'anime_id' => $anime_id,
  8938. 'episode_number' => $episode_number,
  8939. 'task_id' => $prev_task_id,
  8940. 'url' => $prev_url
  8941. ]);
  8942. break;
  8943. }
  8944. }
  8945. }
  8946. // 如果已继承或已有url,跳过生成
  8947. if ($inherited || (!$is_force && $scene_url)) {
  8948. continue;
  8949. }
  8950. // 优先使用 pic_prompt,如果没有则使用 description
  8951. $pic_prompt = getProp($scene, 'pic_prompt');
  8952. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  8953. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  8954. $update_flag = true;
  8955. // 调用AIImageGenerationService的生成图片任务接口
  8956. try {
  8957. $params = [
  8958. 'prompt' => $description,
  8959. 'ref_img_urls' => []
  8960. ];
  8961. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8962. $task_id = $task->id;
  8963. if (!$task_id) {
  8964. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  8965. continue; // 不中断,继续处理其他场景
  8966. }
  8967. $scene['task_id'] = $task_id;
  8968. $scene['task_status'] = 'processing';
  8969. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  8970. 'anime_id' => $anime_id,
  8971. 'episode_number' => $episode_number,
  8972. 'task_id' => $task_id
  8973. ]);
  8974. } catch (\Exception $e) {
  8975. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  8976. // 不抛出异常,继续处理其他场景
  8977. }
  8978. }
  8979. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes];
  8980. // 将处理完毕的roles和scenes与全局(mp_animes)数据对比并合并
  8981. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes);
  8982. // // 保存剧集的角色和场景信息
  8983. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8984. // 'roles' => json_encode($roles, 256),
  8985. // 'scenes' => json_encode($scenes, 256),
  8986. // 'generate_status' => '执行中',
  8987. // 'generate_at' => date('Y-m-d H:i:s'),
  8988. // 'updated_at' => date('Y-m-d H:i:s')
  8989. // ]);
  8990. // if (!$boolen) {
  8991. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  8992. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  8993. // }
  8994. dLog('deepseek')->info('剧集角色和场景图片任务创建完成', [
  8995. // 'episode_id' => $episode_id,
  8996. 'roles_count' => count($roles),
  8997. 'scenes_count' => count($scenes)
  8998. ]);
  8999. return ['roles' => $roles, 'scenes' => $scenes];
  9000. }
  9001. /**
  9002. * 将剧集的roles和scenes同步到全局(mp_animes)
  9003. * 如果全局中不存在相同的role/scene(role、description、pic_prompt三项一致),则添加到全局
  9004. *
  9005. * @param int $anime_id 动漫对话ID
  9006. * @param array $episode_roles 剧集角色数据
  9007. * @param array $episode_scenes 剧集场景数据
  9008. * @return bool
  9009. */
  9010. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes) {
  9011. // 获取全局数据
  9012. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9013. if (!$anime) {
  9014. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  9015. return false;
  9016. }
  9017. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9018. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  9019. $roles_added = false;
  9020. $roles_updated = false;
  9021. $scenes_added = false;
  9022. // 处理角色同步
  9023. foreach ($episode_roles as $episode_role) {
  9024. $episode_role_name = getProp($episode_role, 'role');
  9025. $episode_description = getProp($episode_role, 'description');
  9026. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  9027. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  9028. // 跳过旁白
  9029. if ($episode_role_name == '旁白') {
  9030. continue;
  9031. }
  9032. // 检查全局中是否已存在相同的角色
  9033. $exists = false;
  9034. $global_role_index = -1;
  9035. foreach ($global_roles as $index => $global_role) {
  9036. $global_role_name = getProp($global_role, 'role');
  9037. $global_description = getProp($global_role, 'description');
  9038. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  9039. // 如果role、description、pic_prompt三项都一致,则认为已存在
  9040. if ($episode_role_name == $global_role_name
  9041. && $episode_description == $global_description
  9042. && $episode_pic_prompt == $global_pic_prompt) {
  9043. $exists = true;
  9044. $global_role_index = $index;
  9045. break;
  9046. }
  9047. }
  9048. // 如果不存在,则添加到全局
  9049. if (!$exists) {
  9050. $global_roles[] = $episode_role;
  9051. $roles_added = true;
  9052. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  9053. 'anime_id' => $anime_id,
  9054. 'role' => $episode_role_name
  9055. ]);
  9056. } else {
  9057. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  9058. if (!empty($episode_voice_prompt)) {
  9059. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  9060. // 如果全局没有voice_prompt或与剧集不一致,则更新
  9061. if ($global_voice_prompt !== $episode_voice_prompt) {
  9062. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  9063. $roles_updated = true;
  9064. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  9065. 'anime_id' => $anime_id,
  9066. 'role' => $episode_role_name,
  9067. 'voice_prompt' => $episode_voice_prompt
  9068. ]);
  9069. }
  9070. }
  9071. }
  9072. }
  9073. // 处理场景同步
  9074. foreach ($episode_scenes as $episode_scene) {
  9075. $episode_scene_name = getProp($episode_scene, 'scene');
  9076. $episode_description = getProp($episode_scene, 'description');
  9077. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  9078. // 检查全局中是否已存在相同的场景
  9079. $exists = false;
  9080. foreach ($global_scenes as $global_scene) {
  9081. $global_scene_name = getProp($global_scene, 'scene');
  9082. $global_description = getProp($global_scene, 'description');
  9083. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  9084. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  9085. if ($episode_scene_name == $global_scene_name
  9086. && $episode_description == $global_description
  9087. && $episode_pic_prompt == $global_pic_prompt) {
  9088. $exists = true;
  9089. break;
  9090. }
  9091. }
  9092. // 如果不存在,则添加到全局
  9093. if (!$exists) {
  9094. $global_scenes[] = $episode_scene;
  9095. $scenes_added = true;
  9096. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  9097. 'anime_id' => $anime_id,
  9098. 'scene' => $episode_scene_name
  9099. ]);
  9100. }
  9101. }
  9102. // 如果有新增或更新,则更新全局数据
  9103. if ($roles_added || $roles_updated || $scenes_added) {
  9104. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  9105. if ($roles_added || $roles_updated) {
  9106. $update_data['roles'] = json_encode($global_roles, 256);
  9107. }
  9108. if ($scenes_added) {
  9109. $update_data['scenes'] = json_encode($global_scenes, 256);
  9110. }
  9111. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  9112. dLog('deepseek')->info('剧集数据同步到全局完成', [
  9113. 'anime_id' => $anime_id,
  9114. 'roles_added' => $roles_added,
  9115. 'roles_updated' => $roles_updated,
  9116. 'scenes_added' => $scenes_added,
  9117. 'global_roles_count' => count($global_roles),
  9118. 'global_scenes_count' => count($global_scenes)
  9119. ]);
  9120. }
  9121. return true;
  9122. }
  9123. /**
  9124. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  9125. *
  9126. * @param int $anime_id 动漫对话ID
  9127. * @param int $episode_id 分集ID
  9128. * @return bool
  9129. */
  9130. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  9131. // 获取全局角色和场景数据
  9132. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9133. if (!$anime) {
  9134. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  9135. return false;
  9136. }
  9137. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9138. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  9139. // 获取指定的分集
  9140. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  9141. if (!$episode) {
  9142. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  9143. return false;
  9144. }
  9145. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9146. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9147. $roles_updated = false;
  9148. $scenes_updated = false;
  9149. // 继承角色的task_id、task_status和url
  9150. foreach ($episode_roles as &$episode_role) {
  9151. $episode_role_name = getProp($episode_role, 'role');
  9152. $episode_description = getProp($episode_role, 'description');
  9153. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  9154. $episode_url = getProp($episode_role, 'url');
  9155. // 跳过旁白角色
  9156. if ($episode_role_name == '旁白') {
  9157. continue;
  9158. }
  9159. // 如果剧集中已有URL,跳过
  9160. if (!empty($episode_url)) {
  9161. continue;
  9162. }
  9163. // 遍历全局角色数据,查找匹配的角色
  9164. foreach ($global_roles as $global_role) {
  9165. $global_role_name = getProp($global_role, 'role');
  9166. $global_description = getProp($global_role, 'description');
  9167. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  9168. $global_url = getProp($global_role, 'url');
  9169. $global_task_id = getProp($global_role, 'task_id');
  9170. $global_task_status = getProp($global_role, 'task_status');
  9171. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  9172. if ($episode_role_name == $global_role_name
  9173. && $episode_description == $global_description
  9174. && $episode_pic_prompt == $global_pic_prompt) {
  9175. // 继承 task_id、task_status 和 url
  9176. if (!empty($global_task_id)) {
  9177. $episode_role['task_id'] = $global_task_id;
  9178. $episode_role['task_status'] = $global_task_status;
  9179. $roles_updated = true;
  9180. dLog('deepseek')->info('剧集角色继承全局task_id', [
  9181. 'episode_id' => $episode_id,
  9182. 'role' => $episode_role_name,
  9183. 'task_id' => $global_task_id,
  9184. 'task_status' => $global_task_status
  9185. ]);
  9186. }
  9187. if (!empty($global_url)) {
  9188. $episode_role['url'] = $global_url;
  9189. $roles_updated = true;
  9190. dLog('deepseek')->info('剧集角色继承全局url', [
  9191. 'episode_id' => $episode_id,
  9192. 'role' => $episode_role_name,
  9193. 'url' => $global_url
  9194. ]);
  9195. }
  9196. break;
  9197. }
  9198. }
  9199. }
  9200. // 继承场景的task_id、task_status和url
  9201. foreach ($episode_scenes as &$episode_scene) {
  9202. $episode_scene_name = getProp($episode_scene, 'scene');
  9203. $episode_description = getProp($episode_scene, 'description');
  9204. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  9205. $episode_url = getProp($episode_scene, 'url');
  9206. // 如果剧集中已有URL,跳过
  9207. if (!empty($episode_url)) {
  9208. continue;
  9209. }
  9210. // 遍历全局场景数据,查找匹配的场景
  9211. foreach ($global_scenes as $global_scene) {
  9212. $global_scene_name = getProp($global_scene, 'scene');
  9213. $global_description = getProp($global_scene, 'description');
  9214. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  9215. $global_url = getProp($global_scene, 'url');
  9216. $global_task_id = getProp($global_scene, 'task_id');
  9217. $global_task_status = getProp($global_scene, 'task_status');
  9218. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  9219. if ($episode_scene_name == $global_scene_name
  9220. && $episode_description == $global_description
  9221. && $episode_pic_prompt == $global_pic_prompt) {
  9222. // 继承 task_id、task_status 和 url
  9223. if (!empty($global_task_id)) {
  9224. $episode_scene['task_id'] = $global_task_id;
  9225. $episode_scene['task_status'] = $global_task_status;
  9226. $scenes_updated = true;
  9227. dLog('deepseek')->info('剧集场景继承全局task_id', [
  9228. 'episode_id' => $episode_id,
  9229. 'scene' => $episode_scene_name,
  9230. 'task_id' => $global_task_id,
  9231. 'task_status' => $global_task_status
  9232. ]);
  9233. }
  9234. if (!empty($global_url)) {
  9235. $episode_scene['url'] = $global_url;
  9236. $scenes_updated = true;
  9237. dLog('deepseek')->info('剧集场景继承全局url', [
  9238. 'episode_id' => $episode_id,
  9239. 'scene' => $episode_scene_name,
  9240. 'url' => $global_url
  9241. ]);
  9242. }
  9243. break;
  9244. }
  9245. }
  9246. }
  9247. // 如果有更新,则保存到数据库
  9248. if ($roles_updated || $scenes_updated) {
  9249. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  9250. if ($roles_updated) {
  9251. $update_data['roles'] = json_encode($episode_roles, 256);
  9252. }
  9253. if ($scenes_updated) {
  9254. $update_data['scenes'] = json_encode($episode_scenes, 256);
  9255. }
  9256. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  9257. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  9258. 'episode_id' => $episode_id,
  9259. 'roles_updated' => $roles_updated,
  9260. 'scenes_updated' => $scenes_updated
  9261. ]);
  9262. }
  9263. return true;
  9264. }
  9265. public function chatChangeImg($data) {
  9266. $segment = getProp($data, 'segment');
  9267. $segment_content = getProp($segment, 'segment_content');
  9268. $prompt = getProp($data, 'prompt');
  9269. $ref_img = getProp($data, 'ref_img');
  9270. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  9271. // 处理文本模型
  9272. $model = getProp($data, 'model');
  9273. if (!$model) {
  9274. // 用户没有输入,从anime表获取
  9275. $segment_id = getProp($segment, 'segment_id');
  9276. if ($segment_id) {
  9277. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  9278. if ($episode_id) {
  9279. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  9280. if ($anime_id) {
  9281. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  9282. }
  9283. }
  9284. }
  9285. if (!$model) {
  9286. // anime表也没有,使用默认值
  9287. $model = 'doubao-seed-2-0-mini-260215';
  9288. }
  9289. }
  9290. // 验证模型是否在可用模型表中
  9291. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9292. $model = 'doubao-seed-2-0-mini-260215';
  9293. }
  9294. $messages[] =
  9295. [
  9296. 'role' => 'user',
  9297. 'content' => $question
  9298. ];
  9299. $post_data = [
  9300. 'model' => $model,
  9301. 'messages' => $messages,
  9302. // 'max_tokens' => 8192,
  9303. 'temperature' => 0.7,
  9304. 'frequency_penalty' => 0,
  9305. 'presence_penalty' => 0,
  9306. 'response_format' => ['type' => 'text'],
  9307. 'stream' => false // 是否启用流式输出
  9308. ];
  9309. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9310. // DeepSeek 官方模型使用 DeepSeek API
  9311. $chatResult = $this->chatOnly($post_data);
  9312. } else if (in_array($model, $this->gpt_text_models)) {
  9313. // GPT-5.4 模型使用 TokenRouter API
  9314. $chatResult = $this->gpt54ChatOnly($post_data);
  9315. } else {
  9316. // 其他模型使用火山引擎API
  9317. $chatResult = $this->volcEngineChatCompletion($post_data);
  9318. }
  9319. if (is_array($chatResult)) {
  9320. extract($chatResult);
  9321. }else {
  9322. Utils::throwError('20003: 接口调用失败!');
  9323. }
  9324. return [
  9325. 'type' => 'done',
  9326. // 'episode' => $episode,
  9327. 'answer' => $fullContent,
  9328. 'reasoning' => $fullReasoningContent,
  9329. 'usage' => $usage
  9330. ];
  9331. }
  9332. // 仅调用deepseek对话接口
  9333. private function chatOnly($post_data) {
  9334. $post_data['max_tokens'] = 300000;
  9335. $client = new Client(['timeout' => 1800, 'verify' => false]);
  9336. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  9337. $response = $result->getBody()->getContents();
  9338. $response_arr = json_decode($response, true);
  9339. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  9340. $fullContent = '';
  9341. $fullReasoningContent = [];
  9342. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  9343. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  9344. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  9345. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  9346. }
  9347. return [
  9348. 'fullContent' => $fullContent,
  9349. 'fullReasoningContent' => $fullReasoningContent,
  9350. 'usage' => $usage
  9351. ];
  9352. }
  9353. // 仅调用 GPT-5.4 对话接口(非流式)
  9354. private function gpt54ChatOnly($post_data) {
  9355. $apiKey = env('GPT_54_API_KEY');
  9356. if (empty($apiKey)) {
  9357. Utils::throwError('20003:GPT-5.4 API Key未配置');
  9358. }
  9359. $client = new Client(['timeout' => 1800, 'verify' => false]);
  9360. $headers = [
  9361. 'Authorization' => 'Bearer ' . $apiKey,
  9362. 'Content-Type' => 'application/json'
  9363. ];
  9364. // 移除 thinking 参数,GPT-5.4 不支持
  9365. if (isset($post_data['thinking'])) {
  9366. unset($post_data['thinking']);
  9367. }
  9368. if (isset($post_data['reasoning_effort'])) {
  9369. unset($post_data['reasoning_effort']);
  9370. }
  9371. $post_data['max_completion_tokens'] = 100000;
  9372. // 确保 stream 为 false
  9373. $post_data['stream'] = false;
  9374. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  9375. $result = $client->post('https://api.nonelinear.com/v1/chat/completions', [
  9376. 'json' => $post_data,
  9377. 'headers' => $headers
  9378. ]);
  9379. $response = $result->getBody()->getContents();
  9380. $response_arr = json_decode($response, true);
  9381. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  9382. $fullContent = '';
  9383. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  9384. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  9385. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  9386. }
  9387. return [
  9388. 'fullContent' => $fullContent,
  9389. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  9390. 'usage' => $usage
  9391. ];
  9392. }
  9393. private function splitContent($content) {
  9394. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  9395. $chapters = [];
  9396. // 匹配章节标题格式:
  9397. // 1. 标题独占一行
  9398. // 2. 格式支持:
  9399. // - **第一集**
  9400. // - 第一集:
  9401. // - ###第1章 重生
  9402. // - ##第2章 相救
  9403. // - 第三章 共处一室
  9404. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  9405. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  9406. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  9407. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  9408. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  9409. // 先用正则找出所有章节标题的位置
  9410. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  9411. $titleCount = count($matches[0]);
  9412. for ($i = 0; $i < $titleCount; $i++) {
  9413. // 获取当前章节标题
  9414. $titleLine = trim($matches[0][$i][0]);
  9415. // 去除标题开头的特殊符号
  9416. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  9417. // 去除标题结尾的冒号
  9418. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  9419. $cleanTitle = trim($cleanTitle);
  9420. // 获取当前标题的结束位置
  9421. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  9422. // 获取下一个章节标题的开始位置(如果存在)
  9423. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  9424. // 提取章节内容(从标题结束到下一个标题开始)
  9425. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  9426. // 清理内容:去除前后空白和分隔线
  9427. $chapterContent = trim($chapterContent);
  9428. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  9429. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  9430. if (!empty($cleanTitle) && !empty($chapterContent)) {
  9431. $chapters[] = [
  9432. 'title' => $cleanTitle,
  9433. 'content' => $chapterContent
  9434. ];
  9435. }
  9436. }
  9437. } else {
  9438. // 如果没有匹配到章节,返回整个内容
  9439. $chapters[] = [
  9440. 'title' => '',
  9441. 'content' => $content
  9442. ];
  9443. }
  9444. return $chapters;
  9445. }
  9446. public function getContentByBid($bid) {
  9447. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  9448. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  9449. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  9450. $content = '';
  9451. foreach ($chapters as $chapter) {
  9452. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  9453. }
  9454. return $content;
  9455. }
  9456. public function getContentByScriptId($script_id) {
  9457. $content = '';
  9458. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  9459. if ($contents) {
  9460. $content = implode(PHP_EOL, $contents);
  9461. }else {
  9462. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  9463. }
  9464. return $content;
  9465. }
  9466. /**
  9467. * 根据文件类型提取文本内容
  9468. *
  9469. * @param mixed $file 文件对象或文件路径
  9470. * @return string
  9471. */
  9472. public function extractFileContent($file) {
  9473. // 获取文件路径和扩展名
  9474. if (is_string($file)) {
  9475. $filePath = $file;
  9476. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  9477. } else {
  9478. // Laravel UploadedFile 对象
  9479. $filePath = $file->getRealPath();
  9480. $extension = strtolower($file->getClientOriginalExtension());
  9481. }
  9482. $content = '';
  9483. switch ($extension) {
  9484. case 'txt':
  9485. $content = $this->extractTxtContent($filePath);
  9486. break;
  9487. case 'pdf':
  9488. $content = $this->extractPdfContent($filePath);
  9489. break;
  9490. case 'doc':
  9491. case 'docx':
  9492. $content = $this->extractWordContent($filePath);
  9493. break;
  9494. // case 'jpg':
  9495. // case 'jpeg':
  9496. // case 'png':
  9497. // case 'gif':
  9498. // case 'bmp':
  9499. // case 'webp':
  9500. // $content = $this->extractImageContent($filePath);
  9501. // break;
  9502. default:
  9503. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  9504. }
  9505. return $content;
  9506. }
  9507. /**
  9508. * 提取 TXT 文件内容
  9509. */
  9510. private function extractTxtContent($filePath) {
  9511. if (!file_exists($filePath)) {
  9512. Utils::throwError('20003:文件不存在');
  9513. }
  9514. $content = file_get_contents($filePath);
  9515. // 尝试检测并转换编码
  9516. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  9517. if ($encoding && $encoding !== 'UTF-8') {
  9518. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  9519. }
  9520. return trim($content);
  9521. }
  9522. /**
  9523. * 提取 PDF 文件内容
  9524. */
  9525. private function extractPdfContent($filePath) {
  9526. if (!file_exists($filePath)) {
  9527. Utils::throwError('20003:文件不存在');
  9528. }
  9529. try {
  9530. $parser = new PdfParser();
  9531. $pdf = $parser->parseFile($filePath);
  9532. $content = $pdf->getText();
  9533. return trim($content);
  9534. } catch (\Exception $e) {
  9535. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  9536. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  9537. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  9538. }
  9539. }
  9540. /**
  9541. * 提取 Word 文件内容(支持 doc 和 docx)
  9542. */
  9543. private function extractWordContent($filePath) {
  9544. if (!file_exists($filePath)) {
  9545. Utils::throwError('20003:文件不存在');
  9546. }
  9547. try {
  9548. $phpWord = WordIOFactory::load($filePath);
  9549. $content = '';
  9550. foreach ($phpWord->getSections() as $section) {
  9551. foreach ($section->getElements() as $element) {
  9552. $content .= $this->extractWordElementText($element);
  9553. }
  9554. }
  9555. return trim($content);
  9556. } catch (\Exception $e) {
  9557. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  9558. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  9559. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  9560. }
  9561. }
  9562. /**
  9563. * 递归提取 Word 元素中的文本
  9564. */
  9565. private function extractWordElementText($element) {
  9566. $text = '';
  9567. if (method_exists($element, 'getText')) {
  9568. $text .= $element->getText() . "\n";
  9569. } elseif (method_exists($element, 'getElements')) {
  9570. foreach ($element->getElements() as $childElement) {
  9571. $text .= $this->extractWordElementText($childElement);
  9572. }
  9573. }
  9574. return $text;
  9575. }
  9576. /**
  9577. * 提取图片内容(使用火山引擎 OCR)
  9578. */
  9579. private function extractImageContent($filePath) {
  9580. if (!file_exists($filePath)) {
  9581. Utils::throwError('20003:文件不存在');
  9582. }
  9583. try {
  9584. // 读取图片并转换为 base64
  9585. $imageData = file_get_contents($filePath);
  9586. $base64Image = base64_encode($imageData);
  9587. // 调用火山引擎 OCR 服务
  9588. $content = $this->callVolcEngineOCR($base64Image);
  9589. return trim($content);
  9590. } catch (\Exception $e) {
  9591. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  9592. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  9593. Utils::throwError('20003:图片识别失败');
  9594. }
  9595. }
  9596. /**
  9597. * 调用火山引擎 OCR 服务识别图片文字
  9598. *
  9599. * @param string $base64Image base64 编码的图片数据
  9600. * @return string 识别的文字内容
  9601. */
  9602. private function callVolcEngineOCR($base64Image) {
  9603. $method = 'POST';
  9604. $service = 'cv';
  9605. $host = 'visual.volcengineapi.com';
  9606. $region = env('VOLC_REGION', 'cn-north-1');
  9607. $access_key = env('VOLC_AK');
  9608. $secret_key = env('VOLC_SK');
  9609. $action = 'OCRNormal';
  9610. $version = '2020-08-26';
  9611. if (!$access_key || !$secret_key) {
  9612. Utils::throwError('20003:请配置火山引擎 AK/SK');
  9613. }
  9614. // 请求体
  9615. $body = json_encode([
  9616. 'image_base64' => $base64Image
  9617. ]);
  9618. // 生成签名
  9619. $headers = $this->getVolcEngineSignHeaders(
  9620. $method, $service, $host, $region,
  9621. "Action={$action}&Version={$version}",
  9622. $access_key, $secret_key, $body
  9623. );
  9624. $client = new Client(['timeout' => 1800, 'verify' => false]);
  9625. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  9626. 'headers' => $headers,
  9627. 'body' => $body
  9628. ]);
  9629. $response_arr = json_decode($response->getBody()->getContents(), true);
  9630. // 提取识别的文字
  9631. $textLines = [];
  9632. if (isset($response_arr['data']['line_texts'])) {
  9633. $textLines = $response_arr['data']['line_texts'];
  9634. } elseif (isset($response_arr['data']['ocr_infos'])) {
  9635. foreach ($response_arr['data']['ocr_infos'] as $info) {
  9636. if (isset($info['text'])) {
  9637. $textLines[] = $info['text'];
  9638. }
  9639. }
  9640. }
  9641. if (empty($textLines)) {
  9642. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  9643. return '';
  9644. }
  9645. return implode("\n", $textLines);
  9646. }
  9647. /**
  9648. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  9649. */
  9650. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  9651. $contentType = 'application/json';
  9652. $accept = 'application/json';
  9653. // 获取当前UTC时间
  9654. $t = new DateTime('now', new DateTimeZone('UTC'));
  9655. $xDate = $t->format('Ymd\THis\Z');
  9656. $dateStamp = $t->format('Ymd');
  9657. // 计算 body 的 sha256 哈希
  9658. $payloadHash = hash('sha256', $body);
  9659. // 1. 拼接规范请求串
  9660. $canonicalUri = '/';
  9661. $canonicalQueryString = $queryString;
  9662. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  9663. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  9664. $canonicalRequest = implode("\n", [
  9665. $method,
  9666. $canonicalUri,
  9667. $canonicalQueryString,
  9668. $canonicalHeaders,
  9669. $signedHeaders,
  9670. $payloadHash
  9671. ]);
  9672. // 2. 拼接待签名字符串
  9673. $algorithm = 'HMAC-SHA256';
  9674. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  9675. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  9676. $stringToSign = implode("\n", [
  9677. $algorithm,
  9678. $xDate,
  9679. $credentialScope,
  9680. $hashedCanonicalRequest
  9681. ]);
  9682. // 3. 计算签名
  9683. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  9684. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  9685. // 4. 添加签名到请求头
  9686. $authorizationHeader = sprintf(
  9687. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  9688. $algorithm,
  9689. $access_key,
  9690. $credentialScope,
  9691. $signedHeaders,
  9692. $signature
  9693. );
  9694. return [
  9695. 'Accept' => $accept,
  9696. 'Content-Type' => $contentType,
  9697. 'Host' => $host,
  9698. 'X-Date' => $xDate,
  9699. 'X-Content-Sha256'=> $payloadHash,
  9700. 'Authorization' => $authorizationHeader
  9701. ];
  9702. }
  9703. public function generateScriptWords($cid, $model = 'r1') {
  9704. ini_set('max_execution_time', 0);
  9705. if (!$cid) Utils::throwError('20003: 请选择章节!');
  9706. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  9707. // 模型兼容性处理和思考模式设置
  9708. $thinkingMode = 'disabled';
  9709. $reasoningEffort = 'high';
  9710. if ($model == 'r1') {
  9711. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  9712. $thinkingMode = 'enabled';
  9713. } else {
  9714. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  9715. $thinkingMode = 'disabled';
  9716. }
  9717. $messages = [
  9718. [
  9719. 'role' => 'system',
  9720. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  9721. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  9722. 2.非对话部分请全部用旁白角色代替
  9723. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  9724. ],
  9725. [
  9726. 'role' => 'user',
  9727. 'content' => $content
  9728. ]
  9729. ];
  9730. $post_data = [
  9731. 'model' => $model,
  9732. 'messages' => $messages,
  9733. // 'max_tokens' => 8192,
  9734. 'temperature' => 1,
  9735. 'frequency_penalty' => 0,
  9736. 'presence_penalty' => 0,
  9737. 'thinking' => ['type' => $thinkingMode],
  9738. 'response_format' => [
  9739. 'type' => 'text'
  9740. ],
  9741. 'stream' => false
  9742. ];
  9743. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9744. // 根据模型类型选择调用方法
  9745. $fullContent = '';
  9746. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9747. // DeepSeek 官方模型使用 DeepSeek API
  9748. $chatResult = $this->chatOnly($post_data);
  9749. } else if (in_array($model, $this->gpt_text_models)) {
  9750. // GPT-5.4 模型使用 TokenRouter API
  9751. $chatResult = $this->gpt54ChatOnly($post_data);
  9752. } else {
  9753. // 其他模型使用火山引擎API
  9754. $chatResult = $this->volcEngineChatCompletion($post_data);
  9755. }
  9756. if (is_array($chatResult)) {
  9757. $fullContent = $chatResult['fullContent'];
  9758. }
  9759. return $fullContent;
  9760. }
  9761. /**
  9762. * 智能化解析集数信息
  9763. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  9764. *
  9765. * @param string $prompt 用户输入的提示词
  9766. * @return int|null 解析出的集数,如果没有找到则返回null
  9767. */
  9768. private function extractEpisodeNumber($prompt)
  9769. {
  9770. if (empty($prompt)) {
  9771. return null;
  9772. }
  9773. // 定义各种可能的表达模式
  9774. $patterns = [
  9775. // 基本模式:改成N集、调整成N集、修改成N集
  9776. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  9777. // 扩展模式:分成N集、拆分成N集、分割成N集
  9778. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  9779. // 数量模式:N集、共N集、总共N集
  9780. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  9781. // 制作模式:制作N集、生成N集、创建N集
  9782. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  9783. // 计划模式:计划N集、预计N集、打算N集
  9784. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  9785. // 需要模式:需要N集、要N集
  9786. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  9787. // 中文数字模式:改成三集、调整成五集等
  9788. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  9789. // 英文数字模式
  9790. '/(?: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',
  9791. ];
  9792. // 中文数字转阿拉伯数字的映射
  9793. $chineseNumbers = [
  9794. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  9795. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  9796. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  9797. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  9798. ];
  9799. // 逐个尝试匹配模式
  9800. foreach ($patterns as $pattern) {
  9801. if (preg_match($pattern, $prompt, $matches)) {
  9802. $number = trim($matches[1]);
  9803. // 如果是中文数字,转换为阿拉伯数字
  9804. if (isset($chineseNumbers[$number])) {
  9805. return $chineseNumbers[$number];
  9806. }
  9807. // 如果是阿拉伯数字,直接返回
  9808. if (is_numeric($number)) {
  9809. $episodeNum = intval($number);
  9810. // 合理性检查:集数应该在1-100之间
  9811. if ($episodeNum >= 1 && $episodeNum <= 100) {
  9812. return $episodeNum;
  9813. }
  9814. }
  9815. }
  9816. }
  9817. return null;
  9818. }
  9819. /**
  9820. * 调用火山引擎对话(Chat) API
  9821. *
  9822. * @param array $params 包含以下参数:
  9823. * - model: 模型ID(必填)
  9824. * - messages: 消息列表(必填)
  9825. * - stream: 是否流式输出(可选,默认false)
  9826. * - max_tokens: 最大输出token数(可选)
  9827. * - temperature: 采样温度(可选,默认1)
  9828. * - top_p: 核采样概率(可选,默认0.7)
  9829. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  9830. * - presence_penalty: 存在惩罚系数(可选,默认0)
  9831. * - stop: 停止词(可选)
  9832. * - tools: 工具列表(可选)
  9833. * @return array|Generator 非流式返回数组,流式返回生成器
  9834. */
  9835. public function volcEngineChatCompletion(array $params)
  9836. {
  9837. $apiKey = env('VOLC_AI_API_KEY');
  9838. if (empty($apiKey)) {
  9839. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  9840. }
  9841. // 构建请求参数
  9842. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  9843. $requestData = [
  9844. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  9845. 'messages' => $params['messages'] ?? [],
  9846. ];
  9847. if (!in_array($originalModel, $this->valid_text_models)) {
  9848. Utils::throwError('20003:该模型不支持!');
  9849. }
  9850. // 添加可选参数
  9851. if (isset($params['stream'])) {
  9852. $requestData['stream'] = $params['stream'];
  9853. }
  9854. if (isset($params['stream_options'])) {
  9855. $requestData['stream_options'] = $params['stream_options'];
  9856. }
  9857. if (isset($params['max_tokens'])) {
  9858. $requestData['max_tokens'] = $params['max_tokens'];
  9859. }else if (isset($params['max_completion_tokens'])) {
  9860. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  9861. }else {
  9862. $requestData['max_completion_tokens'] = 100000;
  9863. }
  9864. if (isset($params['temperature'])) {
  9865. $requestData['temperature'] = $params['temperature'];
  9866. }
  9867. if (isset($params['top_p'])) {
  9868. $requestData['top_p'] = $params['top_p'];
  9869. }
  9870. if (isset($params['frequency_penalty'])) {
  9871. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  9872. }
  9873. if (isset($params['presence_penalty'])) {
  9874. $requestData['presence_penalty'] = $params['presence_penalty'];
  9875. }
  9876. if (isset($params['stop'])) {
  9877. $requestData['stop'] = $params['stop'];
  9878. }
  9879. if (isset($params['tools'])) {
  9880. $requestData['tools'] = $params['tools'];
  9881. }
  9882. if (isset($params['tool_choice'])) {
  9883. $requestData['tool_choice'] = $params['tool_choice'];
  9884. }
  9885. if (isset($params['response_format'])) {
  9886. $requestData['response_format'] = $params['response_format'];
  9887. }
  9888. if (isset($params['thinking'])) {
  9889. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  9890. if (is_array($params['thinking'])) {
  9891. $requestData['thinking'] = $params['thinking'];
  9892. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  9893. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  9894. }
  9895. } else {
  9896. $requestData['thinking'] = ['type' => $params['thinking']];
  9897. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  9898. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  9899. }
  9900. }
  9901. } else {
  9902. $requestData['thinking'] = ['type' => 'disabled'];
  9903. }
  9904. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  9905. $client = new Client(['verify' => false, 'timeout' => 1800]);
  9906. try {
  9907. // 判断是否为流式输出
  9908. $isStream = isset($params['stream']) && $params['stream'] === true;
  9909. if ($isStream) {
  9910. // 流式输出
  9911. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  9912. } else {
  9913. // 非流式输出
  9914. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  9915. 'headers' => [
  9916. 'Authorization' => 'Bearer ' . $apiKey,
  9917. 'Content-Type' => 'application/json',
  9918. ],
  9919. 'json' => $requestData
  9920. ]);
  9921. $responseData = json_decode($response->getBody(), true);
  9922. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  9923. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  9924. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  9925. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  9926. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  9927. }
  9928. return [
  9929. 'fullContent' => $fullContent,
  9930. 'fullReasoningContent' => $fullReasoningContent,
  9931. 'usage' => $usage
  9932. ];
  9933. }
  9934. } catch (\Exception $e) {
  9935. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  9936. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  9937. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  9938. }
  9939. }
  9940. /**
  9941. * 火山引擎对话API流式输出
  9942. *
  9943. * @param Client $client HTTP客户端
  9944. * @param string $apiKey API密钥
  9945. * @param array $requestData 请求数据
  9946. * @return Generator
  9947. */
  9948. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  9949. {
  9950. try {
  9951. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  9952. 'headers' => [
  9953. 'Authorization' => 'Bearer ' . $apiKey,
  9954. 'Content-Type' => 'application/json',
  9955. ],
  9956. 'json' => $requestData,
  9957. 'stream' => true
  9958. ]);
  9959. $body = $response->getBody();
  9960. $buffer = '';
  9961. $fullContent = '';
  9962. $fullReasoningContent = '';
  9963. $usage = [];
  9964. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  9965. // 逐行读取流式响应
  9966. while (!$body->eof()) {
  9967. $chunk = $body->read(1024);
  9968. $buffer .= $chunk;
  9969. // 按行分割
  9970. $lines = explode("\n", $buffer);
  9971. $buffer = array_pop($lines);
  9972. foreach ($lines as $line) {
  9973. $line = trim($line);
  9974. if (empty($line)) {
  9975. continue;
  9976. }
  9977. // 检查是否是SSE数据行
  9978. if (strpos($line, 'data: ') !== 0) {
  9979. continue;
  9980. }
  9981. $data = substr($line, 6);
  9982. if ($data === '[DONE]') {
  9983. dLog('deepseek')->info('收到结束标记');
  9984. break 2;
  9985. }
  9986. try {
  9987. $json = json_decode($data, true);
  9988. if (json_last_error() !== JSON_ERROR_NONE) {
  9989. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  9990. continue;
  9991. }
  9992. if (isset($json['choices'][0]['delta'])) {
  9993. $delta = $json['choices'][0]['delta'];
  9994. // 处理思维链内容
  9995. if (isset($delta['reasoning_content'])) {
  9996. $fullReasoningContent .= $delta['reasoning_content'];
  9997. yield [
  9998. 'type' => 'reasoning',
  9999. 'content' => $delta['reasoning_content'],
  10000. 'full_reasoning' => $fullReasoningContent
  10001. ];
  10002. }
  10003. // 处理回答内容
  10004. if (isset($delta['content'])) {
  10005. $fullContent .= $delta['content'];
  10006. yield [
  10007. 'type' => 'content',
  10008. 'content' => $delta['content'],
  10009. ];
  10010. }
  10011. }
  10012. // 获取使用统计信息
  10013. if (isset($json['usage'])) {
  10014. $usage = $json['usage'];
  10015. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  10016. }
  10017. } catch (\Exception $e) {
  10018. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  10019. continue;
  10020. }
  10021. }
  10022. }
  10023. dLog('deepseek')->info('流式读取完成', [
  10024. 'content_length' => strlen($fullContent),
  10025. 'reasoning_length' => strlen($fullReasoningContent)
  10026. ]);
  10027. yield [
  10028. 'type' => 'done',
  10029. 'full_content' => $fullContent,
  10030. 'full_reasoning' => $fullReasoningContent,
  10031. 'usage' => $usage
  10032. ];
  10033. } catch (\Exception $e) {
  10034. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  10035. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  10036. throw $e;
  10037. }
  10038. }
  10039. /**
  10040. * 检查并创建图片生成任务
  10041. *
  10042. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  10043. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  10044. * @param string $nameKey 资源名称字段('role' 或 'scene')
  10045. * @param string $art_style 美术风格
  10046. * @return array 更新后的资源列表
  10047. */
  10048. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  10049. {
  10050. // 确保参数为数组
  10051. $merged_items = is_array($merged_items) ? $merged_items : [];
  10052. $global_items = is_array($global_items) ? $global_items : [];
  10053. // 构建全局资源映射表,用于快速查找
  10054. $global_map = [];
  10055. foreach ($global_items as $item) {
  10056. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  10057. if ($itemKey === '') {
  10058. continue;
  10059. }
  10060. $global_map[$itemKey] = $item;
  10061. }
  10062. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  10063. foreach ($merged_items as &$item) {
  10064. $item_name = getProp($item, $nameKey);
  10065. $item_description = getProp($item, 'description');
  10066. // $item_url = getProp($item, 'url');
  10067. // // 如果已有图片URL,跳过
  10068. // if (!empty($item_url)) {
  10069. // continue;
  10070. // }
  10071. // 如果是旁白角色,跳过
  10072. if ($nameKey === 'role' && $item_name === '旁白') {
  10073. continue;
  10074. }
  10075. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  10076. if ($itemKey === '') {
  10077. continue;
  10078. }
  10079. $need_create_task = false;
  10080. // 条件1:在全局资源中找不到匹配的名称
  10081. if (!isset($global_map[$itemKey])) {
  10082. $need_create_task = true;
  10083. } else {
  10084. // 条件2:名称匹配但描述或 pic_prompt 不一致
  10085. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  10086. $current_description = trim((string)$item_description);
  10087. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  10088. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  10089. // 如果 description 或 pic_prompt 有变化,需要重新生成
  10090. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  10091. $need_create_task = true;
  10092. }
  10093. }
  10094. // 如果需要创建任务,调用图片生成服务
  10095. if ($need_create_task) {
  10096. try {
  10097. // 优先使用 pic_prompt,如果没有则使用 description
  10098. $pic_prompt = getProp($item, 'pic_prompt');
  10099. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  10100. // 添加美术风格前缀
  10101. if ($art_style) {
  10102. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  10103. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  10104. $description = "{$prefix}:{$description}";
  10105. }
  10106. $params = [
  10107. 'prompt' => $description,
  10108. 'ref_img_urls' => []
  10109. ];
  10110. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10111. $task_id = $task->id;
  10112. if ($task_id) {
  10113. $item['task_id'] = $task_id;
  10114. $item['task_status'] = 'processing';
  10115. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  10116. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  10117. }
  10118. } catch (\Exception $e) {
  10119. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  10120. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  10121. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  10122. // 不抛出异常,继续处理其他资源
  10123. }
  10124. }
  10125. }
  10126. return $merged_items;
  10127. }
  10128. /**
  10129. * 同步新出现的主体和场景到全局
  10130. *
  10131. * @param int $anime_id 动漫ID
  10132. * @param array $merged_roles 合并后的角色列表
  10133. * @param array $merged_scenes 合并后的场景列表
  10134. * @param array $global_roles 全局角色列表
  10135. * @param array $global_scenes 全局场景列表
  10136. * @return void
  10137. */
  10138. private function syncNewResourcesToGlobal(
  10139. int $anime_id,
  10140. array $merged_roles,
  10141. array $merged_scenes,
  10142. array $global_roles,
  10143. array $global_scenes
  10144. ): void {
  10145. // 构建全局角色映射表
  10146. $global_role_map = [];
  10147. foreach ($global_roles as $role) {
  10148. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  10149. if ($roleKey !== '') {
  10150. $global_role_map[$roleKey] = $role;
  10151. }
  10152. }
  10153. // 构建全局场景映射表
  10154. $global_scene_map = [];
  10155. foreach ($global_scenes as $scene) {
  10156. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  10157. if ($sceneKey !== '') {
  10158. $global_scene_map[$sceneKey] = $scene;
  10159. }
  10160. }
  10161. $need_update = false;
  10162. $new_global_roles = $global_roles;
  10163. $new_global_scenes = $global_scenes;
  10164. // 检查并添加新角色到全局
  10165. foreach ($merged_roles as $role) {
  10166. $role_name = getProp($role, 'role');
  10167. // 跳过旁白
  10168. if ($role_name === '旁白') {
  10169. continue;
  10170. }
  10171. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  10172. if ($roleKey === '') {
  10173. continue;
  10174. }
  10175. // 如果全局中不存在该角色,添加到全局
  10176. if (!isset($global_role_map[$roleKey])) {
  10177. $new_global_roles[] = [
  10178. 'role' => $role_name,
  10179. 'description' => getProp($role, 'description', ''),
  10180. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  10181. 'voice_name' => getProp($role, 'voice_name', ''),
  10182. 'voice_type' => getProp($role, 'voice_type', ''),
  10183. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  10184. 'url' => getProp($role, 'url', ''),
  10185. 'task_id' => getProp($role, 'task_id', ''),
  10186. 'task_status' => getProp($role, 'task_status', ''),
  10187. ];
  10188. $global_role_map[$roleKey] = true; // 标记已添加
  10189. $need_update = true;
  10190. dLog('deepseek')->info("新角色同步到全局", [
  10191. 'anime_id' => $anime_id,
  10192. 'role' => $role_name,
  10193. 'task_id' => getProp($role, 'task_id', ''),
  10194. ]);
  10195. }
  10196. // else {
  10197. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  10198. // $global_role = $global_role_map[$roleKey];
  10199. // if (is_array($global_role)) {
  10200. // $updated = false;
  10201. // $update_fields = [];
  10202. // // 检查描述是否更新
  10203. // $current_description = trim((string)getProp($role, 'description'));
  10204. // $global_description = trim((string)getProp($global_role, 'description'));
  10205. // if ($current_description !== '' && $current_description !== $global_description) {
  10206. // $updated = true;
  10207. // $update_fields[] = 'description';
  10208. // }
  10209. // // 检查pic_prompt是否更新
  10210. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  10211. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  10212. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  10213. // $updated = true;
  10214. // $update_fields[] = 'pic_prompt';
  10215. // }
  10216. // // 检查图片任务信息是否更新
  10217. // $current_task_id = getProp($role, 'task_id');
  10218. // $global_task_id = getProp($global_role, 'task_id');
  10219. // if ($current_task_id && $current_task_id !== $global_task_id) {
  10220. // $updated = true;
  10221. // $update_fields[] = 'task_id';
  10222. // }
  10223. // // 如果有更新,同步到全局
  10224. // if ($updated) {
  10225. // foreach ($new_global_roles as &$global_role_item) {
  10226. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  10227. // if ($global_role_key === $roleKey) {
  10228. // if (in_array('description', $update_fields)) {
  10229. // $global_role_item['description'] = $current_description;
  10230. // }
  10231. // if (in_array('pic_prompt', $update_fields)) {
  10232. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  10233. // }
  10234. // if (in_array('task_id', $update_fields)) {
  10235. // $global_role_item['task_id'] = $current_task_id;
  10236. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  10237. // $global_role_item['url'] = getProp($role, 'url', '');
  10238. // }
  10239. // break;
  10240. // }
  10241. // }
  10242. // $need_update = true;
  10243. // dLog('deepseek')->info("角色信息更新到全局", [
  10244. // 'anime_id' => $anime_id,
  10245. // 'role' => $role_name,
  10246. // 'update_fields' => implode(',', $update_fields),
  10247. // ]);
  10248. // }
  10249. // }
  10250. // }
  10251. }
  10252. // 检查并添加新场景到全局
  10253. foreach ($merged_scenes as $scene) {
  10254. $scene_name = getProp($scene, 'scene');
  10255. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  10256. if ($sceneKey === '') {
  10257. continue;
  10258. }
  10259. // 如果全局中不存在该场景,添加到全局
  10260. if (!isset($global_scene_map[$sceneKey])) {
  10261. $new_global_scenes[] = [
  10262. 'scene' => $scene_name,
  10263. 'description' => getProp($scene, 'description', ''),
  10264. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  10265. 'url' => getProp($scene, 'url', ''),
  10266. 'task_id' => getProp($scene, 'task_id', ''),
  10267. 'task_status' => getProp($scene, 'task_status', ''),
  10268. ];
  10269. $global_scene_map[$sceneKey] = true; // 标记已添加
  10270. $need_update = true;
  10271. dLog('deepseek')->info("新场景同步到全局", [
  10272. 'anime_id' => $anime_id,
  10273. 'scene' => $scene_name,
  10274. 'task_id' => getProp($scene, 'task_id', ''),
  10275. ]);
  10276. }
  10277. // else {
  10278. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  10279. // $global_scene = $global_scene_map[$sceneKey];
  10280. // if (is_array($global_scene)) {
  10281. // $updated = false;
  10282. // $update_fields = [];
  10283. // // 检查描述是否更新
  10284. // $current_description = trim((string)getProp($scene, 'description'));
  10285. // $global_description = trim((string)getProp($global_scene, 'description'));
  10286. // if ($current_description !== '' && $current_description !== $global_description) {
  10287. // $updated = true;
  10288. // $update_fields[] = 'description';
  10289. // }
  10290. // // 检查pic_prompt是否更新
  10291. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  10292. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  10293. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  10294. // $updated = true;
  10295. // $update_fields[] = 'pic_prompt';
  10296. // }
  10297. // // 检查图片任务信息是否更新
  10298. // $current_task_id = getProp($scene, 'task_id');
  10299. // $global_task_id = getProp($global_scene, 'task_id');
  10300. // if ($current_task_id && $current_task_id !== $global_task_id) {
  10301. // $updated = true;
  10302. // $update_fields[] = 'task_id';
  10303. // }
  10304. // // 如果有更新,同步到全局
  10305. // if ($updated) {
  10306. // foreach ($new_global_scenes as &$global_scene_item) {
  10307. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  10308. // if ($global_scene_key === $sceneKey) {
  10309. // if (in_array('description', $update_fields)) {
  10310. // $global_scene_item['description'] = $current_description;
  10311. // }
  10312. // if (in_array('pic_prompt', $update_fields)) {
  10313. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  10314. // }
  10315. // if (in_array('task_id', $update_fields)) {
  10316. // $global_scene_item['task_id'] = $current_task_id;
  10317. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  10318. // $global_scene_item['url'] = getProp($scene, 'url', '');
  10319. // }
  10320. // break;
  10321. // }
  10322. // }
  10323. // $need_update = true;
  10324. // dLog('deepseek')->info("场景信息更新到全局", [
  10325. // 'anime_id' => $anime_id,
  10326. // 'scene' => $scene_name,
  10327. // 'update_fields' => implode(',', $update_fields),
  10328. // ]);
  10329. // }
  10330. // }
  10331. // }
  10332. }
  10333. // 如果有新增或更新,更新数据库
  10334. if ($need_update) {
  10335. $update_data = [
  10336. 'roles' => json_encode($new_global_roles, 256),
  10337. 'scenes' => json_encode($new_global_scenes, 256),
  10338. 'updated_at' => date('Y-m-d H:i:s'),
  10339. ];
  10340. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  10341. if ($result !== false) {
  10342. dLog('deepseek')->info("全局角色和场景更新成功", [
  10343. 'anime_id' => $anime_id,
  10344. 'roles_count' => count($new_global_roles),
  10345. 'scenes_count' => count($new_global_scenes),
  10346. ]);
  10347. } else {
  10348. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  10349. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  10350. }
  10351. }
  10352. }
  10353. }