DeepSeekService.php 777 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280
  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. private $gemini_text_models;
  29. protected $aiImageGenerationService;
  30. public function __construct(AIImageGenerationService $aiImageGenerationService) {
  31. $this->aiImageGenerationService = $aiImageGenerationService;
  32. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  33. $this->api_key = env('DEEPSEEK_API_KEY');
  34. $this->headers = [
  35. 'Authorization' => 'Bearer '.$this->api_key,
  36. 'Content-Type' => 'application/json; charset=UTF-8'
  37. ];
  38. // 火山引擎模型列表
  39. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  40. // GPT文本模型列表
  41. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  42. // Gemini文本模型列表
  43. $this->gemini_text_models = BaseConst::GEMINI_TEXT_MODELS;
  44. $this->sys_message = [
  45. 'role' => 'system',
  46. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  47. 强制要求:\n
  48. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  49. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  50. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  51. 普通要求:\n
  52. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  53. 2.<分集剧本>的要求如下:
  54.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  55.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  56.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  57.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  58. \n\n
  59. 示例如下:\n
  60. ###剧本名:西昆仑
  61. ###故事梗概
  62. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  63. ###剧本亮点
  64. 亮点1:绝境奇药,生死一线
  65. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  66. 亮点2:结拜兄妹,化解尴尬
  67. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  68. 亮点3:纤发夺命,情愫暗涌
  69. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  70. ###人物关系
  71. 阿雪与梁萧之间存在兄妹之情。
  72. ###核心矛盾
  73. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  74. ###主体列表
  75. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  76. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  77. 阴阳球:天地异宝,能化生精气,救人于危难。
  78. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  79. ###美术风格
  80. 基础画风风格词:厚涂古风
  81. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  82. ###场景列表
  83. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  84. ###分集剧本
  85. ##分集01
  86. 第1集: 第一集的标题
  87. 场景描述:地点、时间、场景
  88. 运镜:固定近距离
  89. 出场角色:男主、女主
  90. 台词内容:
  91. 女主: 女主对话
  92. 男主:男主对话
  93. 女主: 女主对话
  94. 男主: 男主对话
  95. ##分集02
  96. 第2集: 第二集的标题
  97. 场景描述:地点、时间、场景
  98. 运镜:固定近距离
  99. 出场角色:男主、女主
  100. 台词内容:
  101. 女主: 女主对话
  102. 男主:男主对话
  103. 女主: 女主对话
  104. 男主: 男主对话"
  105. ];
  106. }
  107. /**
  108. * 通用文生文方法 - 支持多模型流式输出、图片输入;视频输入仅 Gemini 模型支持
  109. *
  110. * @param array $data 请求参数
  111. * @return \Generator 返回生成器,用于流式输出
  112. */
  113. public function generateText($data) {
  114. // 获取请求参数
  115. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  116. $messages = getProp($data, 'messages', []);
  117. $systemPrompt = getProp($data, 'system_prompt', '');
  118. $prompt = getProp($data, 'prompt', '');
  119. $images = getProp($data, 'images', []); // 支持多张图片
  120. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  121. $videos = getProp($data, 'videos', []); // Gemini 支持视频文件
  122. $videoUrls = getProp($data, 'video_urls', []); // Gemini 支持视频URL
  123. $isGeminiModel = in_array($model, $this->gemini_text_models);
  124. if ((!empty($videos) || !empty($videoUrls)) && !$isGeminiModel) {
  125. Utils::throwError('20003:仅Gemini模型支持视频输入');
  126. }
  127. // 如果没有提供messages,则根据system_prompt、content和images构建
  128. if (empty($messages)) {
  129. $messages = [];
  130. // 添加系统提示词
  131. if (!empty($systemPrompt)) {
  132. $messages[] = [
  133. 'role' => 'system',
  134. 'content' => $systemPrompt
  135. ];
  136. }
  137. // 构建用户消息内容(支持文本+图片)
  138. if (!empty($prompt) || !empty($images) || !empty($imageUrls) || !empty($videos) || !empty($videoUrls)) {
  139. $userMessage = [
  140. 'role' => 'user',
  141. 'content' => []
  142. ];
  143. // 添加文本内容
  144. if (!empty($prompt)) {
  145. $userMessage['content'][] = [
  146. 'type' => 'text',
  147. 'text' => $prompt
  148. ];
  149. }
  150. // 处理上传的图片文件
  151. if (!empty($images)) {
  152. if (!is_array($images)) {
  153. $images = [$images];
  154. }
  155. foreach ($images as $image) {
  156. $imageBase64 = $this->processImageToBase64($image);
  157. if ($imageBase64) {
  158. $userMessage['content'][] = [
  159. 'type' => 'image_url',
  160. 'image_url' => [
  161. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  162. ]
  163. ];
  164. }
  165. }
  166. }
  167. // 处理图片URL
  168. if (!empty($imageUrls)) {
  169. if (!is_array($imageUrls)) {
  170. $imageUrls = [$imageUrls];
  171. }
  172. foreach ($imageUrls as $url) {
  173. if (!empty($url)) {
  174. $userMessage['content'][] = [
  175. 'type' => 'image_url',
  176. 'image_url' => [
  177. 'url' => $url
  178. ]
  179. ];
  180. }
  181. }
  182. }
  183. // 处理上传的视频文件(仅 Gemini)
  184. if (!empty($videos) && $isGeminiModel) {
  185. if (!is_array($videos)) {
  186. $videos = [$videos];
  187. }
  188. foreach ($videos as $video) {
  189. $inlineData = $this->processMediaToInlineData($video);
  190. if ($inlineData) {
  191. $userMessage['content'][] = [
  192. 'type' => 'video',
  193. 'inline_data' => $inlineData
  194. ];
  195. }
  196. }
  197. }
  198. // 处理视频URL(仅 Gemini)
  199. if (!empty($videoUrls) && $isGeminiModel) {
  200. if (!is_array($videoUrls)) {
  201. $videoUrls = [$videoUrls];
  202. }
  203. foreach ($videoUrls as $url) {
  204. if (!empty($url)) {
  205. $userMessage['content'][] = [
  206. 'type' => 'video_url',
  207. 'video_url' => ['url' => $url]
  208. ];
  209. }
  210. }
  211. }
  212. // 如果只有文本内容,简化为字符串格式
  213. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  214. $userMessage['content'] = $userMessage['content'][0]['text'];
  215. }
  216. $messages[] = $userMessage;
  217. }
  218. }
  219. // 验证messages不为空
  220. if (empty($messages)) {
  221. Utils::throwError('20003:请提供有效的对话内容');
  222. }
  223. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  224. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  225. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  226. if ($model === 'deepseek-chat') {
  227. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  228. $model = 'deepseek-v4-flash';
  229. $thinkingMode = 'disabled';
  230. } elseif ($model === 'deepseek-reasoner') {
  231. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  232. $model = 'deepseek-v4-flash';
  233. $thinkingMode = 'enabled';
  234. }
  235. // 构建请求参数
  236. $post_data = [
  237. 'model' => $model,
  238. 'messages' => $messages,
  239. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  240. 'temperature' => getProp($data, 'temperature', 1),
  241. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  242. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  243. 'thinking' => ['type' => $thinkingMode],
  244. 'stream' => true // 启用流式输出
  245. ];
  246. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  247. // 添加可选参数
  248. if (isset($data['top_p'])) {
  249. $post_data['top_p'] = $data['top_p'];
  250. }
  251. if (isset($data['response_format'])) {
  252. $post_data['response_format'] = $data['response_format'];
  253. }
  254. // 根据模型类型选择调用方法
  255. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  256. // DeepSeek 官方模型使用 DeepSeek API
  257. return $this->deepSeekStreamResponse($post_data);
  258. } else if (in_array($model, $this->gpt_text_models)) {
  259. // GPT 模型使用 TokenRouter API
  260. return $this->gpt54StreamResponse($post_data);
  261. } else if (in_array($model, $this->gemini_text_models)) {
  262. // Gemini 模型使用 Gemini API
  263. return $this->geminiStreamResponse($post_data, $model);
  264. } else if (in_array($model, $this->valid_text_models)) {
  265. // 火山引擎支持的模型使用火山引擎 API
  266. return $this->volcEngineChatCompletion($post_data);
  267. } else {
  268. Utils::throwError('20003:不支持的模型: ' . $model);
  269. }
  270. }
  271. public function createGenerateText($data) {
  272. $file = getProp($data, 'file');
  273. $uid = Site::getUid();
  274. $cpid = Site::getCpid();
  275. if (!$file) {
  276. Utils::throwError('20003:请上传文件');
  277. }
  278. // 提取文件内容
  279. $content = $this->extractFileContent($file);
  280. if (!$content) {
  281. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  282. }
  283. // 获取原始文件名(不含扩展名)作为script_name
  284. // 注意:不能用pathinfo()取FILENAME,PHP在部分Linux环境下对中文等
  285. // 多字节文件名会解析为空(PHP Bug #47954 / #30014),这里改为按扩展名
  286. // 字节安全剥离,不依赖服务器locale设置
  287. $originalName = $file->getClientOriginalName();
  288. $extension = $file->getClientOriginalExtension();
  289. $script_name = $extension !== '' && substr($originalName, -strlen($extension) - 1) === '.' . $extension
  290. ? substr($originalName, 0, -strlen($extension) - 1)
  291. : $originalName;
  292. if ($script_name === '') {
  293. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  294. }
  295. // 如果同一用户的剧本名存在则提示
  296. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  297. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  298. }
  299. // 插入数据到mp_scripts表
  300. $script_id = DB::table('mp_scripts')->insertGetId([
  301. 'script_name' => $script_name,
  302. 'user_id' => $uid,
  303. 'cpid' => $cpid,
  304. 'content' => $content,
  305. 'created_at' => date('Y-m-d H:i:s'),
  306. 'updated_at' => date('Y-m-d H:i:s')
  307. ]);
  308. return [
  309. 'script_id' => $script_id,
  310. 'script_name' => $script_name
  311. ];
  312. }
  313. /**
  314. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  315. *
  316. * @param array $data 请求参数
  317. * @return array 返回结果数组
  318. */
  319. public function newGenerateText($data) {
  320. // 获取请求参数
  321. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  322. $messages = getProp($data, 'messages', []);
  323. $systemPrompt = getProp($data, 'system_prompt', '');
  324. $prompt = getProp($data, 'prompt', '');
  325. $images = getProp($data, 'images', []); // 支持多张图片
  326. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  327. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  328. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  329. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  330. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  331. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  332. $generateTaskId = 0;
  333. if ($script_id > 0) {
  334. $uid = Site::getUid();
  335. $existingTask = DB::table('mp_script_generate_tasks')
  336. ->where('uid', $uid)
  337. ->where('script_id', $script_id)
  338. ->orderByDesc('id')
  339. ->first();
  340. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  341. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  342. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  343. }
  344. }
  345. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  346. $originalContent = '';
  347. if ($script_id > 0) {
  348. $script = DB::table('mp_scripts')
  349. ->where('id', $script_id)
  350. ->where('is_deleted', 0)
  351. ->first();
  352. if (!$script) {
  353. Utils::throwError('20003:剧本不存在或已删除');
  354. }
  355. $originalContent = $script->content ?? '';
  356. if (empty($originalContent)) {
  357. Utils::throwError('20003:剧本内容为空');
  358. }
  359. // 将剧本内容添加到提示词前面
  360. if (!empty($originalContent)) {
  361. if (!empty($prompt)) {
  362. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  363. } else {
  364. $prompt = "原文内容:\n" . $originalContent;
  365. }
  366. }
  367. }
  368. // 新增: 如果提供了template_id,从数据库获取template_prompt
  369. if ($templateId > 0) {
  370. $template = DB::table('mp_prompt_templates')
  371. ->where('id', $templateId)
  372. ->where('is_deleted', 0)
  373. ->first();
  374. if (!$template) {
  375. Utils::throwError('20003:模板不存在或已删除');
  376. }
  377. $templatePrompt = $template->template_prompt ?? '';
  378. // 将模板提示词和用户输入的prompt组合
  379. // 模板为准,用户输入作为补充要求
  380. if (!empty($templatePrompt)) {
  381. if (!empty($prompt)) {
  382. $prompt = $templatePrompt . "\n\n" . $prompt;
  383. } else {
  384. $prompt = $templatePrompt;
  385. }
  386. }
  387. }
  388. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  389. if (empty($messages)) {
  390. $messages = [];
  391. // 添加系统提示词
  392. if (!empty($systemPrompt)) {
  393. $messages[] = [
  394. 'role' => 'system',
  395. 'content' => $systemPrompt
  396. ];
  397. }
  398. // 构建用户消息内容(支持文本+图片)
  399. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  400. $userMessage = [
  401. 'role' => 'user',
  402. 'content' => []
  403. ];
  404. // 添加文本内容
  405. if (!empty($prompt)) {
  406. $userMessage['content'][] = [
  407. 'type' => 'text',
  408. 'text' => $prompt
  409. ];
  410. }
  411. // 处理上传的图片文件
  412. if (!empty($images)) {
  413. if (!is_array($images)) {
  414. $images = [$images];
  415. }
  416. foreach ($images as $image) {
  417. $imageBase64 = $this->processImageToBase64($image);
  418. if ($imageBase64) {
  419. $userMessage['content'][] = [
  420. 'type' => 'image_url',
  421. 'image_url' => [
  422. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  423. ]
  424. ];
  425. }
  426. }
  427. }
  428. // 处理图片URL
  429. if (!empty($imageUrls)) {
  430. if (!is_array($imageUrls)) {
  431. $imageUrls = [$imageUrls];
  432. }
  433. foreach ($imageUrls as $url) {
  434. if (!empty($url)) {
  435. $userMessage['content'][] = [
  436. 'type' => 'image_url',
  437. 'image_url' => [
  438. 'url' => $url
  439. ]
  440. ];
  441. }
  442. }
  443. }
  444. // 如果只有文本内容,简化为字符串格式
  445. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  446. $userMessage['content'] = $userMessage['content'][0]['text'];
  447. }
  448. $messages[] = $userMessage;
  449. }
  450. }
  451. // 验证messages不为空
  452. if (empty($messages)) {
  453. Utils::throwError('20003:请提供有效的对话内容');
  454. }
  455. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  456. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  457. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  458. if ($model === 'deepseek-chat') {
  459. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  460. $model = 'deepseek-v4-flash';
  461. $thinkingMode = 'disabled';
  462. } elseif ($model === 'deepseek-reasoner') {
  463. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  464. $model = 'deepseek-v4-flash';
  465. $thinkingMode = 'enabled';
  466. }
  467. // 构建请求参数(非流式)
  468. $post_data = [
  469. 'model' => $model,
  470. 'messages' => $messages,
  471. 'temperature' => getProp($data, 'temperature', 1),
  472. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  473. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  474. 'thinking' => ['type' => $thinkingMode],
  475. 'stream' => false // 非流式输出
  476. ];
  477. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  478. // 添加可选参数
  479. if (isset($data['top_p'])) {
  480. $post_data['top_p'] = $data['top_p'];
  481. }
  482. // 新增: 根据response_format设置响应格式
  483. if ($responseFormat === 'json') {
  484. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  485. $hasJsonKeyword = false;
  486. foreach ($post_data['messages'] as $message) {
  487. if (isset($message['content'])) {
  488. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  489. if (stripos($content, 'json') !== false) {
  490. $hasJsonKeyword = true;
  491. break;
  492. }
  493. }
  494. }
  495. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  496. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  497. if (!$hasJsonKeyword) {
  498. $lastMessageIndex = count($post_data['messages']) - 1;
  499. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  500. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  501. // 如果content是字符串,直接追加
  502. if (is_string($lastContent)) {
  503. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  504. }
  505. // 如果content是数组(包含文本和图片),在文本部分追加
  506. else if (is_array($lastContent)) {
  507. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  508. if ($contentPart['type'] === 'text') {
  509. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  510. break;
  511. }
  512. }
  513. }
  514. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  515. }
  516. }
  517. // 设置response_format参数(所有支持的模型)
  518. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  519. // DeepSeek模型
  520. $post_data['response_format'] = ['type' => 'json_object'];
  521. } else if (in_array($model, $this->gpt_text_models)) {
  522. // GPT模型
  523. $post_data['response_format'] = ['type' => 'json_object'];
  524. } else if (in_array($model, $this->valid_text_models)) {
  525. // 火山引擎模型
  526. $post_data['response_format'] = ['type' => 'json_object'];
  527. }
  528. }
  529. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  530. if ($script_id > 0) {
  531. $uid = Site::getUid();
  532. // 创建新的生成任务
  533. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  534. 'uid' => $uid,
  535. 'script_id' => $script_id,
  536. 'sequence' => $sequence,
  537. 'status' => 'processing',
  538. 'prompt' => getProp($data, 'prompt', ''),
  539. 'started_at' => date('Y-m-d H:i:s'),
  540. 'created_at' => date('Y-m-d H:i:s'),
  541. 'updated_at' => date('Y-m-d H:i:s')
  542. ]);
  543. }
  544. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  545. try {
  546. $aiResult = null;
  547. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  548. // DeepSeek 官方模型使用现有的 chatOnly 方法
  549. $result = $this->chatOnly($post_data);
  550. // 记录实际使用的模型
  551. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  552. $aiResult = [
  553. 'content' => $result['fullContent'],
  554. 'reasoning_content' => $result['fullReasoningContent'],
  555. 'usage' => $result['usage'],
  556. 'model' => $model,
  557. 'finish_reason' => 'stop'
  558. ];
  559. } else if (in_array($model, $this->gpt_text_models)) {
  560. // GPT 模型使用现有的 gpt54ChatOnly 方法
  561. $result = $this->gpt54ChatOnly($post_data);
  562. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  563. $aiResult = [
  564. 'content' => $result['fullContent'],
  565. 'reasoning_content' => '',
  566. 'usage' => $result['usage'],
  567. 'model' => $model,
  568. 'finish_reason' => 'stop'
  569. ];
  570. } else if (in_array($model, $this->gemini_text_models)) {
  571. // Gemini 模型使用 Gemini API(非流式)
  572. $result = $this->geminiChatOnly($post_data, $model);
  573. dLog('deepseek')->info('newGenerateText使用Gemini模型', ['requested_model' => $model]);
  574. $aiResult = [
  575. 'content' => $result['fullContent'],
  576. 'reasoning_content' => $result['fullReasoningContent'] ?? '',
  577. 'usage' => $result['usage'],
  578. 'model' => $model,
  579. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  580. ];
  581. } else if (in_array($model, $this->valid_text_models)) {
  582. // 火山引擎支持的模型使用火山引擎 API(非流式)
  583. $post_data['stream'] = false;
  584. $result = $this->volcEngineChatCompletion($post_data);
  585. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  586. 'requested_model' => $model,
  587. 'result_keys' => array_keys($result),
  588. 'has_fullContent' => isset($result['fullContent']),
  589. 'has_content' => isset($result['content'])
  590. ]);
  591. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  592. $aiResult = [
  593. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  594. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  595. 'usage' => $result['usage'] ?? [],
  596. 'model' => $model,
  597. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  598. ];
  599. } else {
  600. Utils::throwError('20003:不支持的模型: ' . $model);
  601. }
  602. } catch (\Exception $e) {
  603. // 生成失败,更新任务状态
  604. if ($generateTaskId) {
  605. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  606. 'status' => 'failed',
  607. 'error_message' => $e->getMessage(),
  608. 'completed_at' => date('Y-m-d H:i:s'),
  609. 'updated_at' => date('Y-m-d H:i:s')
  610. ]);
  611. }
  612. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  613. }
  614. // 生成成功,更新任务状态
  615. if ($generateTaskId && $aiResult) {
  616. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  617. 'status' => 'success',
  618. 'result' => getProp($aiResult, 'content', ''),
  619. 'completed_at' => date('Y-m-d H:i:s'),
  620. 'updated_at' => date('Y-m-d H:i:s')
  621. ]);
  622. $aiResult['generate_task_id'] = $generateTaskId;
  623. }
  624. // 新增: 如果提供了script_id,保存对话记录
  625. if ($script_id > 0 && $aiResult) {
  626. try {
  627. $uid = Site::getUid();
  628. $now = now();
  629. // 获取用户原始的prompt(不包含剧本内容)
  630. $originalPrompt = getProp($data, 'prompt', '');
  631. $recordsToInsert = [
  632. [
  633. 'uid' => $uid,
  634. 'script_id' => $script_id,
  635. 'sequence' => $sequence,
  636. 'role' => 'user',
  637. 'content' => $originalPrompt,
  638. 'created_at' => $now,
  639. 'updated_at' => $now,
  640. ],
  641. [
  642. 'uid' => $uid,
  643. 'script_id' => $script_id,
  644. 'sequence' => $sequence,
  645. 'role' => 'assistant',
  646. 'content' => $aiResult['content'],
  647. 'created_at' => $now,
  648. 'updated_at' => $now,
  649. ]
  650. ];
  651. DB::table('mp_script_records')->insert($recordsToInsert);
  652. // 获取刚插入的记录ID(假设按插入顺序返回)
  653. $insertedRecords = DB::table('mp_script_records')
  654. ->where('uid', $uid)
  655. ->where('script_id', $script_id)
  656. ->where('sequence', $sequence)
  657. ->orderBy('id', 'desc')
  658. ->limit(2)
  659. ->get()
  660. ->map(function ($record) {
  661. return [
  662. 'rid' => $record->id,
  663. 'script_id' => $record->script_id,
  664. 'sequence' => $record->sequence,
  665. 'role' => $record->role,
  666. 'content' => $record->content,
  667. 'created_at' => $record->created_at,
  668. ];
  669. })
  670. ->reverse()
  671. ->values()
  672. ->toArray();
  673. // 将记录信息添加到返回结果中
  674. $aiResult['records'] = $insertedRecords;
  675. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  676. } catch (\Exception $e) {
  677. // 记录错误但不影响主流程
  678. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  679. }
  680. }
  681. return $aiResult;
  682. }
  683. /**
  684. * 通用 Gemini 文生文方法(支持流式和非流式)
  685. *
  686. * 与 chatWithFileStream / newGenerateText 相同的入参格式:
  687. * model 模型ID(gemini-3-flash-preview 等,默认 gemini-3-flash-preview)
  688. * messages OpenAI 风格消息数组(可选,与 system_prompt/prompt 二选一)
  689. * system_prompt 系统提示词(可选)
  690. * prompt 用户提示词(可选)
  691. * images 上传的图片/视频文件列表(可选,自动转 inlineData,超限自动用 ffmpeg 压缩)
  692. * image_urls 图片/视频URL列表(可选,同上)
  693. * temperature 温度(可选,默认 1)
  694. * top_p 核采样(可选)
  695. * max_tokens 最大输出 token(可选,默认 8192)
  696. * response_format text/json(可选)
  697. * thinking enabled/disabled(可选,pro 系列默认 enabled)
  698. * thinking_budget 思考预算(可选,默认 20)
  699. * stream 是否流式(可选,默认 false)
  700. *
  701. * @param array $data 请求参数
  702. * @return array|\Generator 非流式返回数组;流式返回生成器(yield type=content/reasoning/done)
  703. */
  704. public function geminiGenerateText($data) {
  705. $model = getProp($data, 'model', 'gemini-3-flash-preview');
  706. $isStream = (bool)getProp($data, 'stream', false);
  707. if (!in_array($model, $this->gemini_text_models)) {
  708. Utils::throwError('20003:不支持的Gemini模型: ' . $model);
  709. }
  710. $requestData = $this->buildGeminiRequestBody($data, $model);
  711. dLog('deepseek')->info('Gemini请求参数', ['model' => $model, 'stream' => $isStream]);
  712. if ($isStream) {
  713. // 流式返回生成器
  714. return $this->geminiStreamResponse($requestData, $model);
  715. }
  716. // 非流式
  717. return $this->geminiChatOnly($requestData, $model);
  718. }
  719. /**
  720. * Gemini 多媒体文件大小上限(原始字节,base64 后约 19MB,留出 20MB 请求体余量)
  721. */
  722. private function geminiMediaMaxBytes() {
  723. return 14 * 1024 * 1024;
  724. }
  725. /**
  726. * 构建 Gemini 请求体(将 OpenAI 风格消息转换为 Gemini contents 格式)
  727. */
  728. private function buildGeminiRequestBody($data, $model) {
  729. $messages = getProp($data, 'messages', []);
  730. // 如果没有提供 messages,则根据 system_prompt、prompt 和 images 构建
  731. if (empty($messages)) {
  732. $systemPrompt = getProp($data, 'system_prompt', '');
  733. $prompt = getProp($data, 'prompt', '');
  734. $images = getProp($data, 'images', []);
  735. $imageUrls = getProp($data, 'image_urls', []);
  736. $messages = [];
  737. if (!empty($systemPrompt)) {
  738. $messages[] = [
  739. 'role' => 'system',
  740. 'content' => $systemPrompt
  741. ];
  742. }
  743. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  744. $userMessage = ['role' => 'user', 'content' => []];
  745. if (!empty($prompt)) {
  746. $userMessage['content'][] = ['type' => 'text', 'text' => $prompt];
  747. }
  748. if (!empty($images)) {
  749. if (!is_array($images)) {
  750. $images = [$images];
  751. }
  752. foreach ($images as $image) {
  753. $inlineData = $this->processMediaToInlineData($image);
  754. if ($inlineData) {
  755. $userMessage['content'][] = [
  756. 'type' => 'image',
  757. 'inline_data' => $inlineData
  758. ];
  759. }
  760. }
  761. }
  762. if (!empty($imageUrls)) {
  763. if (!is_array($imageUrls)) {
  764. $imageUrls = [$imageUrls];
  765. }
  766. foreach ($imageUrls as $url) {
  767. if (!empty($url)) {
  768. $inlineData = $this->processMediaToInlineData($url);
  769. if ($inlineData) {
  770. $userMessage['content'][] = [
  771. 'type' => 'image',
  772. 'inline_data' => $inlineData
  773. ];
  774. }
  775. }
  776. }
  777. }
  778. if (count($userMessage['content']) === 1 && isset($userMessage['content'][0]['type']) && $userMessage['content'][0]['type'] === 'text') {
  779. $userMessage['content'] = $userMessage['content'][0]['text'];
  780. }
  781. $messages[] = $userMessage;
  782. }
  783. }
  784. if (empty($messages)) {
  785. Utils::throwError('20003:请提供有效的对话内容');
  786. }
  787. // 转换为 Gemini contents 格式
  788. $systemInstruction = '';
  789. $contents = [];
  790. foreach ($messages as $message) {
  791. $role = getProp($message, 'role', 'user');
  792. $content = getProp($message, 'content', '');
  793. if ($role === 'system') {
  794. if (is_array($content)) {
  795. $systemInstruction = $this->extractGeminiTextFromParts($content);
  796. } else {
  797. $systemInstruction = (string)$content;
  798. }
  799. continue;
  800. }
  801. $geminiRole = $role === 'assistant' ? 'model' : 'user';
  802. $parts = [];
  803. if (is_array($content)) {
  804. foreach ($content as $part) {
  805. $partType = getProp($part, 'type', 'text');
  806. if ($partType === 'text') {
  807. $text = (string)getProp($part, 'text', '');
  808. if ($text !== '') {
  809. $parts[] = ['text' => $text];
  810. }
  811. } elseif (in_array($partType, ['image_url', 'image', 'video_url', 'video'])) {
  812. if (in_array($partType, ['image_url', 'video_url'])) {
  813. $mediaPart = getProp($part, $partType === 'image_url' ? 'image_url' : 'video_url', []);
  814. $url = is_array($mediaPart) ? (string)getProp($mediaPart, 'url', '') : (string)$mediaPart;
  815. } elseif (isset($part['inline_data'])) {
  816. // 已处理过的 inline_data 直接使用
  817. $parts[] = ['inline_data' => $part['inline_data']];
  818. continue;
  819. } else {
  820. $url = '';
  821. }
  822. $inlineData = $this->processMediaToInlineData($url);
  823. if ($inlineData) {
  824. $parts[] = ['inline_data' => $inlineData];
  825. }
  826. }
  827. }
  828. } else {
  829. $text = (string)$content;
  830. if ($text !== '') {
  831. $parts[] = ['text' => $text];
  832. }
  833. }
  834. if (!empty($parts)) {
  835. $contents[] = ['role' => $geminiRole, 'parts' => $parts];
  836. }
  837. }
  838. if (empty($contents)) {
  839. Utils::throwError('20003:请提供有效的对话内容');
  840. }
  841. // 构建生成配置
  842. $generationConfig = [];
  843. if (getProp($data, 'temperature', null) !== null) {
  844. $generationConfig['temperature'] = (float)getProp($data, 'temperature');
  845. }
  846. if (getProp($data, 'top_p', null) !== null) {
  847. $generationConfig['topP'] = (float)getProp($data, 'top_p');
  848. }
  849. if (getProp($data, 'frequency_penalty', null) !== null) {
  850. $generationConfig['frequencyPenalty'] = (float)getProp($data, 'frequency_penalty');
  851. }
  852. if (getProp($data, 'presence_penalty', null) !== null) {
  853. $generationConfig['presencePenalty'] = (float)getProp($data, 'presence_penalty');
  854. }
  855. $maxOutputTokens = (int)getProp($data, 'max_tokens', 8192);
  856. if ($maxOutputTokens <= 0) {
  857. $maxOutputTokens = 8192;
  858. }
  859. // gemini-3 pro 中转站实测最大输出上限为 32768,超限会返回 400
  860. if (in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']) && $maxOutputTokens > 32768) {
  861. $maxOutputTokens = 32768;
  862. }
  863. $generationConfig['maxOutputTokens'] = $maxOutputTokens;
  864. // response_format 映射:text -> text/plain,json -> application/json
  865. $responseFormat = getProp($data, 'response_format', 'text');
  866. if (is_array($responseFormat)) {
  867. $responseFormat = getProp($responseFormat, 'type', 'text');
  868. }
  869. if (in_array($responseFormat, ['json', 'json_object'])) {
  870. $generationConfig['responseMimeType'] = 'application/json';
  871. } else {
  872. $generationConfig['responseMimeType'] = 'text/plain';
  873. }
  874. $requestData = [
  875. 'contents' => $contents,
  876. 'generationConfig' => $generationConfig,
  877. ];
  878. if ($systemInstruction !== '') {
  879. $requestData['systemInstruction'] = ['parts' => [['text' => $systemInstruction]]];
  880. }
  881. // thinking 配置(Gemini 通过 thinkingConfig.thinkingBudget 控制,0 表示关闭)
  882. $thinkingMode = getProp($data, 'thinking', null);
  883. if (is_array($thinkingMode)) {
  884. $thinkingMode = getProp($thinkingMode, 'type', 'disabled');
  885. }
  886. $defaultThinking = in_array($model, ['gemini-3-pro-preview', 'gemini-3.1-pro-preview']);
  887. if ($thinkingMode === null) {
  888. $thinkingMode = $defaultThinking ? 'enabled' : 'disabled';
  889. }
  890. if ($thinkingMode === 'enabled') {
  891. $thinkingBudget = (int)getProp($data, 'thinking_budget', 20);
  892. if ($thinkingBudget <= 0) {
  893. $thinkingBudget = 20;
  894. }
  895. $requestData['generationConfig']['thinkingConfig'] = [
  896. 'thinkingBudget' => $thinkingBudget
  897. ];
  898. } elseif ($defaultThinking) {
  899. // 该模型仅支持思考模式,传 0 会返回 400
  900. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 20];
  901. } else {
  902. $requestData['generationConfig']['thinkingConfig'] = ['thinkingBudget' => 0];
  903. }
  904. return $requestData;
  905. }
  906. /**
  907. * 获取指定 Gemini 模型对应的 API Key(env 配置,优先取模型专属 Key,缺失时回退 GEMINI_API_KEY)
  908. *
  909. * 模型名 -> env 变量名映射:
  910. * gemini-3-pro-preview => GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW
  911. * gemini-3-flash-preview => GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW
  912. * gemini-3.1-pro-preview => GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW
  913. * gemini-3.1-flash-image-preview-t => GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T
  914. * gemini-3.6-flash => GEMINI_API_KEY_GEMINI_3_6_FLASH
  915. */
  916. private function getGeminiApiKey($model) {
  917. $map = [
  918. 'gemini-3-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_PRO_PREVIEW',
  919. 'gemini-3-flash-preview' => 'GEMINI_API_KEY_GEMINI_3_FLASH_PREVIEW',
  920. 'gemini-3.1-pro-preview' => 'GEMINI_API_KEY_GEMINI_3_1_PRO_PREVIEW',
  921. 'gemini-3.1-flash-image-preview-t' => 'GEMINI_API_KEY_GEMINI_3_1_FLASH_IMAGE_PREVIEW_T',
  922. 'gemini-3.6-flash' => 'GEMINI_API_KEY_GEMINI_3_6_FLASH',
  923. ];
  924. if (isset($map[$model])) {
  925. $key = env($map[$model]);
  926. if (!empty($key)) {
  927. return $key;
  928. }
  929. }
  930. return env('GEMINI_API_KEY', '');
  931. }
  932. /**
  933. * Gemini 非流式对话(返回与 chatOnly 一致的结构)
  934. */
  935. private function geminiChatOnly($requestData, $model) {
  936. $apiKey = $this->getGeminiApiKey($model);
  937. if (empty($apiKey)) {
  938. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  939. }
  940. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  941. if (isset($requestData['messages'])) {
  942. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  943. }
  944. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  945. . '/models/' . $model . ':generateContent';
  946. $client = new Client(['timeout' => 1800, 'verify' => false]);
  947. $headers = [
  948. 'Authorization' => 'Bearer ' . $apiKey,
  949. 'Content-Type' => 'application/json'
  950. ];
  951. $maxRetries = $this->gptRetryTimes();
  952. $interval = $this->gptRetryInterval();
  953. $attempt = 0;
  954. while (true) {
  955. try {
  956. $response = $client->post($url, [
  957. 'json' => $requestData,
  958. 'headers' => $headers
  959. ]);
  960. $responseArr = json_decode($response->getBody()->getContents(), true);
  961. dLog('deepseek')->info('Gemini请求完成', ['model' => $model, 'response' => $responseArr]);
  962. $fullContent = $this->extractGeminiContent($responseArr);
  963. $fullReasoningContent = $this->extractGeminiReasoningContent($responseArr);
  964. $usage = isset($responseArr['usageMetadata']) ? $responseArr['usageMetadata'] : [];
  965. $finishReason = isset($responseArr['candidates'][0]['finishReason'])
  966. ? $responseArr['candidates'][0]['finishReason']
  967. : '';
  968. return [
  969. 'fullContent' => $fullContent,
  970. 'fullReasoningContent' => $fullReasoningContent,
  971. 'usage' => $usage,
  972. 'finish_reason' => $finishReason
  973. ];
  974. } catch (\Exception $e) {
  975. $retryable = true;
  976. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  977. $status = $e->getResponse()->getStatusCode();
  978. $retryable = $status >= 500 || $status == 429;
  979. }
  980. if (!$retryable || $attempt >= $maxRetries) {
  981. dLog('deepseek')->error('Gemini请求失败: ' . $e->getMessage());
  982. logDB('deepseek', 'error', 'Gemini请求失败', ['error' => $e->getMessage(), 'model' => $model]);
  983. Utils::throwError('20003:Gemini请求失败: ' . $e->getMessage());
  984. }
  985. dLog('deepseek')->warning('Gemini请求失败,准备重试', [
  986. 'retry' => $attempt + 1,
  987. 'max_retries' => $maxRetries,
  988. 'error' => $e->getMessage()
  989. ]);
  990. sleep($interval);
  991. $attempt++;
  992. }
  993. }
  994. }
  995. /**
  996. * Gemini 流式对话(SSE 输出,格式与 deepSeekStreamResponse 一致)
  997. */
  998. private function geminiStreamResponse($requestData, $model) {
  999. $apiKey = $this->getGeminiApiKey($model);
  1000. if (empty($apiKey)) {
  1001. Utils::throwError('20003:Gemini API Key未配置: ' . $model);
  1002. }
  1003. // 兼容 OpenAI 风格 post_data(包含 messages 字段)
  1004. if (isset($requestData['messages'])) {
  1005. $requestData = $this->buildGeminiRequestBody($requestData, $model);
  1006. }
  1007. $url = rtrim(env('GEMINI_API_BASE_URL', 'https://ai-api.kkidc.com/v1beta'), '/')
  1008. . '/models/' . $model . ':generateContent?alt=sse';
  1009. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1010. $headers = [
  1011. 'Authorization' => 'Bearer ' . $apiKey,
  1012. 'Content-Type' => 'application/json'
  1013. ];
  1014. try {
  1015. $response = $client->post($url, [
  1016. 'json' => $requestData,
  1017. 'headers' => $headers,
  1018. 'stream' => true
  1019. ]);
  1020. $body = $response->getBody();
  1021. $fullContent = '';
  1022. $fullReasoningContent = '';
  1023. $usage = [];
  1024. $buffer = '';
  1025. dLog('deepseek')->info('开始读取 Gemini 流式响应');
  1026. while (!$body->eof()) {
  1027. $chunk = $body->read(1024);
  1028. $buffer .= $chunk;
  1029. $lines = explode("\n", $buffer);
  1030. $buffer = array_pop($lines);
  1031. foreach ($lines as $line) {
  1032. $line = trim($line);
  1033. if (empty($line) || strpos($line, 'data: ') !== 0) {
  1034. continue;
  1035. }
  1036. $data = substr($line, 6);
  1037. if ($data === '[DONE]') {
  1038. break 2;
  1039. }
  1040. try {
  1041. $json = json_decode($data, true);
  1042. if (json_last_error() !== JSON_ERROR_NONE) {
  1043. dLog('deepseek')->warning('Gemini JSON解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1044. continue;
  1045. }
  1046. // 思考内容(thoughts)
  1047. $thoughts = $this->extractGeminiThoughts($json);
  1048. if ($thoughts !== '') {
  1049. $fullReasoningContent .= $thoughts;
  1050. yield [
  1051. 'type' => 'reasoning',
  1052. 'content' => $thoughts,
  1053. 'full_reasoning' => $fullReasoningContent
  1054. ];
  1055. }
  1056. // 回答内容
  1057. $partText = $this->extractGeminiContent($json);
  1058. if ($partText !== '') {
  1059. $fullContent .= $partText;
  1060. yield [
  1061. 'type' => 'content',
  1062. 'content' => $partText,
  1063. ];
  1064. }
  1065. // 使用统计
  1066. if (isset($json['usageMetadata'])) {
  1067. $usage = $json['usageMetadata'];
  1068. dLog('deepseek')->info('Gemini收到使用统计', ['usage' => $usage]);
  1069. }
  1070. } catch (\Exception $e) {
  1071. dLog('deepseek')->error('Gemini解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1072. continue;
  1073. }
  1074. }
  1075. }
  1076. dLog('deepseek')->info('Gemini流式读取完成', [
  1077. 'content_length' => strlen($fullContent),
  1078. 'reasoning_length' => strlen($fullReasoningContent)
  1079. ]);
  1080. yield [
  1081. 'type' => 'done',
  1082. 'full_content' => $fullContent,
  1083. 'full_reasoning' => $fullReasoningContent,
  1084. 'usage' => $usage
  1085. ];
  1086. } catch (\Exception $e) {
  1087. dLog('deepseek')->error('Gemini流式请求失败: ' . $e->getMessage());
  1088. yield [
  1089. 'type' => 'error',
  1090. 'msg' => $e->getMessage(),
  1091. 'code' => $e->getCode()
  1092. ];
  1093. }
  1094. }
  1095. /**
  1096. * 从 Gemini 响应中提取回答文本
  1097. */
  1098. private function extractGeminiContent($responseArr) {
  1099. $text = '';
  1100. if (isset($responseArr['candidates'][0]['content']['parts']) && is_array($responseArr['candidates'][0]['content']['parts'])) {
  1101. foreach ($responseArr['candidates'][0]['content']['parts'] as $part) {
  1102. if (isset($part['text'])) {
  1103. $text .= $part['text'];
  1104. }
  1105. }
  1106. }
  1107. return $text;
  1108. }
  1109. /**
  1110. * 从 Gemini 响应中提取思考内容
  1111. */
  1112. private function extractGeminiReasoningContent($responseArr) {
  1113. $reasoning = '';
  1114. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1115. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1116. if (isset($thought['text'])) {
  1117. $reasoning .= $thought['text'];
  1118. }
  1119. }
  1120. }
  1121. return $reasoning;
  1122. }
  1123. /**
  1124. * 从 Gemini 流式响应中提取本次增量思考内容
  1125. */
  1126. private function extractGeminiThoughts($responseArr) {
  1127. $thoughts = '';
  1128. if (isset($responseArr['candidates'][0]['thoughts']) && is_array($responseArr['candidates'][0]['thoughts'])) {
  1129. foreach ($responseArr['candidates'][0]['thoughts'] as $thought) {
  1130. if (isset($thought['text'])) {
  1131. $thoughts .= $thought['text'];
  1132. }
  1133. }
  1134. }
  1135. return $thoughts;
  1136. }
  1137. /**
  1138. * 提取消息数组中的纯文本
  1139. */
  1140. private function extractGeminiTextFromParts($parts) {
  1141. $text = '';
  1142. if (is_array($parts)) {
  1143. foreach ($parts as $part) {
  1144. if (is_array($part) && getProp($part, 'type', 'text') === 'text') {
  1145. $text .= (string)getProp($part, 'text', '');
  1146. }
  1147. }
  1148. }
  1149. return $text;
  1150. }
  1151. /**
  1152. * 将多媒体文件(上传文件路径或 http(s) URL)转换为 Gemini inline_data 格式
  1153. *
  1154. * 限制:中转站请求体最大 20MB,base64 体积膨胀约 1.37 倍,
  1155. * 因此压缩目标为原始文件 <= 14MB(base64 后约 19.2MB,留有余量);
  1156. * 视频时长超过 5 分钟时通过加速压缩到 5 分钟以内。
  1157. *
  1158. * @param mixed $media 文件路径 / UploadedFile / http(s) URL / data URI
  1159. * @return array|null ['mime_type' => string, 'data' => string]
  1160. */
  1161. private function processMediaToInlineData($media) {
  1162. if (empty($media)) {
  1163. return null;
  1164. }
  1165. $localPath = null;
  1166. $isTempFile = false;
  1167. try {
  1168. // 1. data URI:直接解析使用(无法压缩,体积本身已受限)
  1169. if (is_string($media) && strpos($media, 'data:') === 0) {
  1170. if (preg_match('/^data:([^;,]+);base64,(.+)$/s', $media, $matches)) {
  1171. return [
  1172. 'mime_type' => $matches[1],
  1173. 'data' => $matches[2]
  1174. ];
  1175. }
  1176. return null;
  1177. }
  1178. // 2. 获取本地文件路径
  1179. if (is_string($media) && preg_match('#^https?://#i', $media)) {
  1180. $localPath = $this->downloadMediaToTemp($media);
  1181. $isTempFile = true;
  1182. } elseif (is_string($media)) {
  1183. $localPath = $media;
  1184. } else {
  1185. // Laravel UploadedFile 对象
  1186. $localPath = $media->getRealPath();
  1187. }
  1188. if (!$localPath || !file_exists($localPath)) {
  1189. dLog('deepseek')->warning('Gemini多媒体文件不存在', ['path' => $localPath]);
  1190. return null;
  1191. }
  1192. $fileSize = filesize($localPath);
  1193. $maxBytes = $this->geminiMediaMaxBytes();
  1194. // 3. 判断是否需要压缩(超过大小上限或视频时长超过5分钟)
  1195. $mimeType = $this->detectMediaMime($localPath);
  1196. $isVideo = strpos($mimeType, 'video/') === 0;
  1197. $needCompress = $fileSize > $maxBytes;
  1198. $duration = 0;
  1199. if ($isVideo) {
  1200. $duration = $this->getMediaDuration($localPath);
  1201. if ($duration > 300) {
  1202. $needCompress = true;
  1203. }
  1204. }
  1205. $finalPath = $localPath;
  1206. $compressedPath = null;
  1207. if ($needCompress && $this->ffmpegAvailable()) {
  1208. $compressed = $this->compressMediaFile($localPath, $isVideo, $duration);
  1209. if ($compressed && file_exists($compressed)) {
  1210. $compressedPath = $compressed;
  1211. if (filesize($compressed) < $fileSize || $isVideo) {
  1212. $finalPath = $compressed;
  1213. $mimeType = $isVideo ? 'video/mp4' : $this->detectMediaMime($compressed);
  1214. } else {
  1215. @unlink($compressed);
  1216. $compressedPath = null;
  1217. }
  1218. }
  1219. }
  1220. // 兜底校验:压缩后(或未压缩)仍超过大小上限,直接报错,不静默发送
  1221. $finalSize = filesize($finalPath);
  1222. if ($finalSize > $maxBytes) {
  1223. dLog('deepseek')->error('Gemini多媒体文件压缩后仍超过大小上限', [
  1224. 'path' => $localPath,
  1225. 'size_mb' => round($finalSize / 1024 / 1024, 2),
  1226. 'limit_mb' => 14
  1227. ]);
  1228. Utils::throwError('20003:多媒体文件过大(' . round($finalSize / 1024 / 1024, 2) . 'MB),压缩后仍超过14MB限制,请先自行压缩后重试');
  1229. }
  1230. // 兜底校验:视频时长超过5分钟且未能压缩成功
  1231. if ($isVideo && $duration > 300 && $finalPath === $localPath && !$this->ffmpegAvailable()) {
  1232. Utils::throwError('20003:视频时长超过5分钟(' . round($duration, 1) . '秒),且服务器ffmpeg不可用,无法压缩,请先自行处理视频后重试');
  1233. }
  1234. $data = base64_encode(file_get_contents($finalPath));
  1235. return [
  1236. 'mime_type' => $mimeType,
  1237. 'data' => $data
  1238. ];
  1239. } catch (\App\Exceptions\ApiException $e) {
  1240. // 业务错误(如文件过大)原样抛出,让前端看到明确提示
  1241. throw $e;
  1242. } catch (\Exception $e) {
  1243. dLog('deepseek')->error('Gemini多媒体处理失败: ' . $e->getMessage());
  1244. return null;
  1245. } finally {
  1246. if (!empty($compressedPath) && $compressedPath !== $localPath && file_exists($compressedPath)) {
  1247. @unlink($compressedPath);
  1248. }
  1249. if ($isTempFile && $localPath && file_exists($localPath)) {
  1250. @unlink($localPath);
  1251. }
  1252. }
  1253. }
  1254. /**
  1255. * 下载远程多媒体到临时目录
  1256. *
  1257. * @return string|null 本地临时文件路径
  1258. */
  1259. private function downloadMediaToTemp($url) {
  1260. try {
  1261. $tempDir = storage_path('app/temp/gemini');
  1262. if (!is_dir($tempDir)) {
  1263. mkdir($tempDir, 0775, true);
  1264. }
  1265. $extension = 'tmp';
  1266. $pathInfo = parse_url($url, PHP_URL_PATH);
  1267. if ($pathInfo) {
  1268. $ext = pathinfo($pathInfo, PATHINFO_EXTENSION);
  1269. if ($ext && strlen($ext) <= 10) {
  1270. $extension = strtolower($ext);
  1271. }
  1272. }
  1273. $tmpFile = $tempDir . '/' . uniqid('gemini_media_') . '.' . $extension;
  1274. $client = new Client(['timeout' => 300, 'verify' => false]);
  1275. $response = $client->get($url, ['sink' => $tmpFile]);
  1276. if (!file_exists($tmpFile) || filesize($tmpFile) <= 0) {
  1277. @unlink($tmpFile);
  1278. return null;
  1279. }
  1280. return $tmpFile;
  1281. } catch (\Exception $e) {
  1282. dLog('deepseek')->warning('Gemini多媒体下载失败: ' . $e->getMessage(), ['url' => $url]);
  1283. return null;
  1284. }
  1285. }
  1286. /**
  1287. * 检测多媒体文件 MIME 类型
  1288. */
  1289. private function detectMediaMime($filePath) {
  1290. $imageInfo = @getimagesize($filePath);
  1291. if ($imageInfo !== false && isset($imageInfo['mime'])) {
  1292. return $imageInfo['mime'];
  1293. }
  1294. // 视频按扩展名粗略判断
  1295. $ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
  1296. $videoExts = ['mp4' => 'video/mp4', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo',
  1297. 'mkv' => 'video/x-matroska', 'webm' => 'video/webm', 'm4v' => 'video/x-m4v',
  1298. 'flv' => 'video/x-flv', 'wmv' => 'video/x-ms-wmv', 'ts' => 'video/mp2t'];
  1299. if (isset($videoExts[$ext])) {
  1300. return $videoExts[$ext];
  1301. }
  1302. $imageExts = ['jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png',
  1303. 'gif' => 'image/gif', 'webp' => 'image/webp', 'bmp' => 'image/bmp'];
  1304. if (isset($imageExts[$ext])) {
  1305. return $imageExts[$ext];
  1306. }
  1307. return 'application/octet-stream';
  1308. }
  1309. /**
  1310. * 获取多媒体时长(秒),非视频或失败返回 0
  1311. */
  1312. private function getMediaDuration($filePath) {
  1313. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  1314. $cmd = '"' . $ffprobePath . '" -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "' . $filePath . '" 2>&1';
  1315. $output = trim((string)shell_exec($cmd));
  1316. $duration = (float)$output;
  1317. return $duration > 0 ? $duration : 0;
  1318. }
  1319. /**
  1320. * 检查 ffmpeg 是否可用
  1321. */
  1322. private function ffmpegAvailable() {
  1323. static $available = null;
  1324. if ($available !== null) {
  1325. return $available;
  1326. }
  1327. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1328. if (strtoupper((string)env('APP_ENV', 'production')) === 'LOCAL') {
  1329. // 本地环境不执行 ffmpeg 压缩(与现有图片超分逻辑保持一致)
  1330. $available = false;
  1331. return $available;
  1332. }
  1333. $cmd = '"' . $ffmpegPath . '" -version 2>&1';
  1334. $output = shell_exec($cmd);
  1335. $available = is_string($output) && stripos($output, 'ffmpeg') !== false;
  1336. return $available;
  1337. }
  1338. /**
  1339. * 使用 ffmpeg 压缩多媒体文件
  1340. *
  1341. * @param string $inputFile 输入文件路径
  1342. * @param bool $isVideo 是否为视频
  1343. * @param float $duration 视频时长(秒),非视频传 0
  1344. * @return string|null 压缩后的文件路径,失败返回 null
  1345. */
  1346. private function compressMediaFile($inputFile, $isVideo, $duration = 0) {
  1347. try {
  1348. $tempDir = storage_path('app/temp/gemini');
  1349. if (!is_dir($tempDir)) {
  1350. mkdir($tempDir, 0775, true);
  1351. }
  1352. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1353. $uniqueId = uniqid('gemini_cmp_') . bin2hex(random_bytes(4));
  1354. $outputFile = $tempDir . '/' . $uniqueId . ($isVideo ? '.mp4' : '.jpg');
  1355. if ($isVideo) {
  1356. // 视频:时长超过5分钟则加速压缩到5分钟以内
  1357. $speedFactor = 1.0;
  1358. if ($duration > 300) {
  1359. $speedFactor = $duration / 300;
  1360. }
  1361. // 目标文件大小:14MB,按加速后时长估算码率(不高于 6000kbps,不低于 300kbps)
  1362. $finalDuration = $duration / max(1.0, $speedFactor);
  1363. $targetBitrate = (int)((14 * 1024 * 8) / max(1, $finalDuration));
  1364. $targetBitrate = max(300, min(6000, $targetBitrate));
  1365. $filters = [];
  1366. $filters[] = 'scale=min(1280,iw):-2';
  1367. $filters[] = 'fps=24';
  1368. if ($speedFactor > 1.0) {
  1369. $filters[] = 'setpts=' . number_format(1 / $speedFactor, 6, '.', '') . '*PTS';
  1370. // 用多个 atempo 级联实现加速:前 n-1 个为 2.0,最后一个补足剩余倍数
  1371. $fullCount = (int)ceil($speedFactor / 2.0);
  1372. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1373. if ($lastTempo < 0.5) {
  1374. $fullCount++;
  1375. $lastTempo = $speedFactor / pow(2.0, $fullCount - 1);
  1376. }
  1377. for ($i = 0; $i < $fullCount; $i++) {
  1378. $tempoValue = $i === $fullCount - 1 ? $lastTempo : 2.0;
  1379. $filters[] = 'atempo=' . number_format($tempoValue, 6, '.', '');
  1380. }
  1381. }
  1382. $filterStr = implode(',', $filters);
  1383. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile . '" -vf "' . $filterStr
  1384. . '" -c:v libx264 -b:v ' . $targetBitrate . 'k -preset medium'
  1385. . ' -c:a aac -b:a 96k -movflags +faststart -y "' . $outputFile . '" 2>&1';
  1386. } else {
  1387. // 图片:缩放至最长边2048px(保持纵横比),JPEG质量压缩
  1388. $imageInfo = @getimagesize($inputFile);
  1389. $scaleW = 2048;
  1390. $scaleH = 2048;
  1391. if ($imageInfo !== false && $imageInfo[0] > 0 && $imageInfo[1] > 0) {
  1392. if ($imageInfo[0] >= $imageInfo[1]) {
  1393. $scaleH = (int)round($imageInfo[1] * 2048 / $imageInfo[0]);
  1394. $scaleW = 2048;
  1395. } else {
  1396. $scaleW = (int)round($imageInfo[0] * 2048 / $imageInfo[1]);
  1397. $scaleH = 2048;
  1398. }
  1399. }
  1400. $cmd = '"' . $ffmpegPath . '" -i "' . $inputFile
  1401. . '" -vf "scale=' . $scaleW . ':' . $scaleH . '"'
  1402. . ' -q:v 3 -y "' . $outputFile . '" 2>&1';
  1403. }
  1404. dLog('deepseek')->info('Gemini开始压缩多媒体', ['command' => $cmd]);
  1405. $output = shell_exec($cmd);
  1406. if (!file_exists($outputFile) || filesize($outputFile) <= 0) {
  1407. dLog('deepseek')->error('Gemini多媒体压缩失败', [
  1408. 'input' => $inputFile,
  1409. 'output' => $output
  1410. ]);
  1411. @unlink($outputFile);
  1412. return null;
  1413. }
  1414. dLog('deepseek')->info('Gemini多媒体压缩成功', [
  1415. 'input_size' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB',
  1416. 'output_size' => round(filesize($outputFile) / 1024 / 1024, 2) . 'MB'
  1417. ]);
  1418. return $outputFile;
  1419. } catch (\Exception $e) {
  1420. dLog('deepseek')->error('Gemini多媒体压缩异常: ' . $e->getMessage());
  1421. return null;
  1422. }
  1423. }
  1424. /**
  1425. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  1426. *
  1427. * @param array $data
  1428. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  1429. */
  1430. public function getScriptGenerateTasks($data) {
  1431. $uid = Site::getUid();
  1432. return DB::table('mp_script_generate_tasks as t')
  1433. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  1434. ->where('t.uid', $uid)
  1435. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  1436. ->orderByDesc('t.id')
  1437. ->paginate(15);
  1438. }
  1439. public function saveScriptChatHistory($data) {
  1440. $uid = Site::getUid();
  1441. $rid = getProp($data, 'rid');
  1442. $script_id = getProp($data, 'script_id');
  1443. $sequence = getProp($data, 'sequence', 0);
  1444. $content = getProp($data, 'content');
  1445. if (!$rid) {
  1446. Utils::throwError('20003:请选择对话记录ID');
  1447. }
  1448. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  1449. if (!$record) {
  1450. Utils::throwError('20003:对话记录不存在');
  1451. }
  1452. if (!$script_id) {
  1453. Utils::throwError('20003:请选择剧本');
  1454. }
  1455. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  1456. if (!$script) {
  1457. Utils::throwError('20003:剧本不存在');
  1458. }
  1459. // 批量插入数据
  1460. return DB::table('mp_script_records')->where('id', $rid)->update([
  1461. 'content' => $content,
  1462. 'updated_at' => date('Y-m-d H:i:s')
  1463. ]);
  1464. }
  1465. /**
  1466. * 获取剧本的历史对话记录
  1467. *
  1468. * @param array $data 请求参数
  1469. * @return array 返回历史记录数组
  1470. */
  1471. public function getScriptChatHistory($data) {
  1472. $uid = Site::getUid();
  1473. $script_id = getProp($data, 'script_id');
  1474. $rid = getProp($data, 'rid');
  1475. $sequence = getProp($data, 'sequence', null);
  1476. if (!$script_id) {
  1477. Utils::throwError('20003:请提供剧本ID');
  1478. }
  1479. // 验证剧本是否存在
  1480. $script = DB::table('mp_scripts')
  1481. ->where('id', $script_id)
  1482. ->where('is_deleted', 0)
  1483. ->first();
  1484. if (!$script) {
  1485. Utils::throwError('20003:剧本不存在');
  1486. }
  1487. // 构建查询
  1488. $query = DB::table('mp_script_records')
  1489. ->where('script_id', $script_id);
  1490. // ->where('uid', $uid);
  1491. // 如果提供了 sequence,则过滤指定剧集
  1492. if ($sequence !== null) {
  1493. $query->where('sequence', $sequence);
  1494. }
  1495. // 记录ID筛选
  1496. if ($rid) {
  1497. $query->where('id', $rid);
  1498. }
  1499. // 查询记录并按 id 正序排序
  1500. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  1501. ->orderBy('created_at', 'asc')
  1502. ->orderBy('id', 'asc')
  1503. ->get()
  1504. ->map(function ($record) {
  1505. return [
  1506. 'rid' => $record->id,
  1507. 'script_id' => $record->script_id,
  1508. 'sequence' => $record->sequence,
  1509. 'role' => $record->role,
  1510. 'content' => $record->content,
  1511. 'products' => $record->products ? json_decode($record->products) : [],
  1512. 'created_at' => $record->created_at,
  1513. ];
  1514. })
  1515. ->toArray();
  1516. return $records;
  1517. }
  1518. /**
  1519. * 处理图片转换为base64
  1520. *
  1521. * @param mixed $image 图片文件对象或文件路径
  1522. * @return string|null base64编码的图片数据
  1523. */
  1524. private function processImageToBase64($image) {
  1525. try {
  1526. // 获取文件路径
  1527. if (is_string($image)) {
  1528. $filePath = $image;
  1529. } else {
  1530. // Laravel UploadedFile 对象
  1531. $filePath = $image->getRealPath();
  1532. }
  1533. if (!file_exists($filePath)) {
  1534. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  1535. return null;
  1536. }
  1537. // 验证是否为图片文件
  1538. $imageInfo = @getimagesize($filePath);
  1539. if ($imageInfo === false) {
  1540. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  1541. return null;
  1542. }
  1543. // 读取图片并转换为base64
  1544. $imageData = file_get_contents($filePath);
  1545. $base64Image = base64_encode($imageData);
  1546. dLog('deepseek')->info('图片转换成功', [
  1547. 'size' => strlen($imageData),
  1548. 'type' => $imageInfo['mime']
  1549. ]);
  1550. return $base64Image;
  1551. } catch (\Exception $e) {
  1552. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  1553. return null;
  1554. }
  1555. }
  1556. private function getArtStylePromptMappings($art_style='')
  1557. {
  1558. $arr = [
  1559. '唯美真人风格' => [
  1560. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  1561. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  1562. ],
  1563. '真人古风风格' => [
  1564. 'aliases' => ['真人古风风格', '真人古风'],
  1565. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  1566. ],
  1567. '日系动漫风格' => [
  1568. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  1569. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  1570. ],
  1571. '国漫风格' => [
  1572. 'aliases' => ['国漫风格', '国漫'],
  1573. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  1574. ],
  1575. 'Q版卡通风格' => [
  1576. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  1577. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  1578. ],
  1579. '简约扁平风格' => [
  1580. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  1581. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  1582. ],
  1583. '武侠风格' => [
  1584. 'aliases' => ['武侠风格', '武侠'],
  1585. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  1586. ],
  1587. '古风仙侠风格' => [
  1588. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  1589. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  1590. ],
  1591. '新中式水墨风格' => [
  1592. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  1593. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  1594. ],
  1595. '写实插画风格' => [
  1596. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  1597. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  1598. ],
  1599. '3D卡通风格' => [
  1600. 'aliases' => ['3D卡通风格', '3D卡通'],
  1601. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  1602. ],
  1603. '条漫风格' => [
  1604. 'aliases' => ['条漫风格', '条漫'],
  1605. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  1606. ],
  1607. '赛博朋克风格' => [
  1608. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  1609. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  1610. ],
  1611. '暗黑悬疑风格' => [
  1612. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  1613. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  1614. ],
  1615. '治愈清新风格' => [
  1616. 'aliases' => ['治愈清新风格', '治愈清新'],
  1617. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  1618. ],
  1619. '3D真人风格' => [
  1620. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  1621. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  1622. ],
  1623. ];
  1624. if($art_style) {
  1625. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  1626. }
  1627. return $arr;
  1628. $arr = [
  1629. '唯美真人风格' => [
  1630. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  1631. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  1632. 2. 色彩色调
  1633. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  1634. 3. 画质精度
  1635. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  1636. 4. 画面观感
  1637. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  1638. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  1639. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  1640. ],
  1641. '真人古风风格' => [
  1642. 'aliases' => ['真人古风风格', '真人古风'],
  1643. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  1644. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  1645. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  1646. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  1647. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  1648. ],
  1649. '日系动漫风格' => [
  1650. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  1651. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  1652. 正向提示词(中文)
  1653. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  1654. 必须遵守规则
  1655. • 全程保持日系动漫风格,不混入其他画风
  1656. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  1657. • 画面适配所选画面比例,构图居中,主体突出
  1658. • 线条干净、色彩统一,不杂乱、不突兀
  1659. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  1660. ],
  1661. '国漫风格' => [
  1662. 'aliases' => ['国漫风格', '国漫'],
  1663. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  1664. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  1665. 必须遵守规则
  1666. • 严格保持国漫画风,不串风格、不混画风
  1667. • 角色形象统一,不随意改变五官、身材、服饰
  1668. • 画面构图稳定,适合漫剧叙事展示
  1669. • 色调统一,不出现脏色、杂色
  1670. 禁止/避免词汇
  1671. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  1672. ],
  1673. 'Q版卡通风格' => [
  1674. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  1675. 'prompt' => "风格说明
  1676. 头大身小,造型可爱圆润,简约干净
  1677. 正向提示词(中文)
  1678. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  1679. 必须遵守规则
  1680. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  1681. • 角色造型统一,表情可爱,不诡异
  1682. • 画面简洁清爽,无多余复杂元素
  1683. • 色彩明亮柔和,不刺眼
  1684. 禁止/避免词汇
  1685. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  1686. ],
  1687. '简约扁平风格' => [
  1688. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  1689. 'prompt' => "风格说明
  1690. 色块简洁、无复杂渐变,现代极简风
  1691. 正向提示词(中文)
  1692. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  1693. 必须遵守规则
  1694. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  1695. • 构图简洁,主体突出,无多余装饰
  1696. • 色彩统一、干净,不杂乱
  1697. 禁止/避免词汇
  1698. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  1699. ],
  1700. '武侠风格' => [
  1701. 'aliases' => ['武侠风格', '武侠'],
  1702. 'prompt' => "风格说明
  1703. 江湖气息,线条硬朗,动作感强
  1704. 正向提示词(中文)
  1705. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  1706. 必须遵守规则
  1707. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  1708. • 角色形象、服饰、身材比例统一
  1709. • 画面动作自然,不扭曲、不畸形
  1710. 禁止/避免词汇
  1711. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  1712. ],
  1713. '古风仙侠风格' => [
  1714. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  1715. 'prompt' => "风格说明
  1716. 飘逸汉服、云雾仙气、唯美空灵
  1717. 正向提示词(中文)
  1718. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  1719. 必须遵守规则
  1720. • 保持古风仙侠统一画风,不混入现代、科幻元素
  1721. • 角色服饰、发型、形象前后一致
  1722. • 场景仙气飘逸,色调清雅统一
  1723. • 画面唯美柔和,不阴暗、不诡异
  1724. 禁止/避免词汇
  1725. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  1726. ],
  1727. '新中式水墨风格' => [
  1728. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  1729. 'prompt' => "风格说明
  1730. 淡墨渲染,毛笔笔触,留白意境
  1731. 正向提示词(中文)
  1732. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  1733. 必须遵守规则
  1734. • 严格保持水墨质感,不混入厚涂、写实、卡通
  1735. • 色调淡雅统一,不浓艳杂乱
  1736. • 画面干净有意境,不堆砌元素
  1737. 禁止/避免词汇
  1738. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  1739. ],
  1740. '写实插画风格' => [
  1741. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  1742. 'prompt' => "风格说明
  1743. 接近真人比例,光影真实,质感细腻
  1744. 正向提示词(中文)
  1745. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  1746. 必须遵守规则
  1747. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  1748. • 角色五官、身材、服饰高度统一
  1749. • 画面清晰、光影自然、不扭曲
  1750. 禁止/避免词汇
  1751. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  1752. ],
  1753. '3D卡通风格' => [
  1754. 'aliases' => ['3D卡通风格', '3D卡通'],
  1755. 'prompt' => "风格说明
  1756. 3D建模质感,柔和渲染,圆润可爱
  1757. 正向提示词(中文)
  1758. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  1759. 必须遵守规则
  1760. • 保持3D卡通统一质感,不出现2D杂乱线条
  1761. • 角色模型、比例、形象前后一致
  1762. • 画面干净,不模糊、不穿模
  1763. 禁止/避免词汇
  1764. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  1765. ],
  1766. '条漫风格' => [
  1767. 'aliases' => ['条漫风格', '条漫'],
  1768. 'prompt' => "风格说明
  1769. 纵向分镜,上下滑动阅读,轻量化
  1770. 正向提示词(中文)
  1771. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  1772. 必须遵守规则
  1773. • 保持条漫纵向阅读逻辑,构图简洁
  1774. • 画风统一,不混写实、3D、水墨
  1775. • 画面干净,不杂乱
  1776. 禁止/避免词汇
  1777. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  1778. ],
  1779. '赛博朋克风格' => [
  1780. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  1781. 'prompt' => "风格说明
  1782. 霓虹灯光、未来都市、暗色调、科技机械
  1783. 正向提示词(中文)
  1784. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  1785. 必须遵守规则
  1786. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  1787. • 色调以暗调+霓虹为主,色彩统一
  1788. • 画面科技感强,不杂乱
  1789. 禁止/避免词汇
  1790. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  1791. ],
  1792. '暗黑悬疑风格' => [
  1793. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  1794. 'prompt' => "风格说明
  1795. 低饱和、冷色调、阴影重、神秘压抑
  1796. 正向提示词(中文)
  1797. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  1798. 必须遵守规则
  1799. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  1800. • 画面氛围压抑神秘,但不低俗、不血腥
  1801. • 角色形象统一,不崩坏
  1802. 禁止/避免词汇
  1803. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  1804. ],
  1805. '治愈清新风格' => [
  1806. 'aliases' => ['治愈清新风格', '治愈清新'],
  1807. 'prompt' => "风格说明
  1808. 马卡龙色系、柔光、温暖干净
  1809. 正向提示词(中文)
  1810. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  1811. 必须遵守规则
  1812. • 保持治愈清新统一色调,不阴暗、不诡异
  1813. • 画面柔和干净,无杂乱元素
  1814. • 角色形象柔和可爱,不狰狞
  1815. 禁止/避免词汇
  1816. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  1817. ],
  1818. ];
  1819. return $arr;
  1820. }
  1821. public function getArtStylePromptByInput($inputArtStyle): string
  1822. {
  1823. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  1824. if ($normalizedInput === '') {
  1825. return '';
  1826. }
  1827. return $this->getArtStylePromptMappings($normalizedInput);
  1828. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  1829. // foreach ($mapping['aliases'] as $alias) {
  1830. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  1831. // if ($normalizedAlias === '') {
  1832. // continue;
  1833. // }
  1834. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  1835. // return $mapping['prompt'];
  1836. // }
  1837. // }
  1838. // }
  1839. return '';
  1840. }
  1841. public function getArtStyleShortPromptByInput($inputArtStyle) {
  1842. $stylePrefixes = [
  1843. '唯美真人风格' => [
  1844. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  1845. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  1846. ],
  1847. '真人古风风格' => [
  1848. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  1849. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  1850. ],
  1851. '日系动漫风格' => [
  1852. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  1853. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  1854. ],
  1855. '国漫风格' => [
  1856. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  1857. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  1858. ],
  1859. 'Q版卡通风格' => [
  1860. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  1861. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  1862. ],
  1863. '简约扁平风格' => [
  1864. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  1865. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  1866. ],
  1867. '武侠风格' => [
  1868. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  1869. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  1870. ],
  1871. '古风仙侠风格' => [
  1872. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  1873. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  1874. ],
  1875. '新中式水墨风格' => [
  1876. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  1877. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  1878. ],
  1879. '写实插画风格' => [
  1880. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  1881. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  1882. ],
  1883. '3D卡通风格' => [
  1884. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  1885. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  1886. ],
  1887. '条漫风格' => [
  1888. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  1889. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  1890. ],
  1891. '赛博朋克风格' => [
  1892. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  1893. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  1894. ],
  1895. '暗黑悬疑风格' => [
  1896. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  1897. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  1898. ],
  1899. '治愈清新风格' => [
  1900. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  1901. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  1902. ]
  1903. ];
  1904. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  1905. }
  1906. private function normalizeArtStyleInput($value): string
  1907. {
  1908. $value = trim((string)$value);
  1909. if ($value === '') {
  1910. return '';
  1911. }
  1912. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  1913. return mb_strtolower($value, 'UTF-8');
  1914. }
  1915. private function replaceArtStyleSection(string $content, string $artStyle): string
  1916. {
  1917. if ($content === '' || $artStyle === '') {
  1918. return $content;
  1919. }
  1920. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  1921. if (!preg_match($pattern, $content)) {
  1922. return $content;
  1923. }
  1924. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  1925. }
  1926. /**
  1927. * DeepSeek流式输出处理方法
  1928. *
  1929. * @param array $post_data DeepSeek API请求参数
  1930. * @return \Generator 返回生成器,用于流式输出
  1931. */
  1932. private function unwrapJsonWrappedContent($content) {
  1933. $trimmed = ltrim((string)$content);
  1934. if ($trimmed === '' || ($trimmed[0] !== '{' && $trimmed[0] !== '[')) {
  1935. return $content;
  1936. }
  1937. $decoded = json_decode($trimmed, true);
  1938. if (!is_array($decoded)) {
  1939. return $content;
  1940. }
  1941. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  1942. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  1943. return $decoded[$key];
  1944. }
  1945. }
  1946. return $content;
  1947. }
  1948. private function deepSeekStreamResponse($post_data) {
  1949. // 设置最大输出tokens
  1950. $post_data['max_tokens'] = 300000;
  1951. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1952. $response = $client->post($this->url, [
  1953. 'json' => $post_data,
  1954. 'headers' => $this->headers,
  1955. 'stream' => true // 启用流式响应
  1956. ]);
  1957. $body = $response->getBody();
  1958. $fullContent = '';
  1959. $fullReasoningContent = '';
  1960. $usage = [];
  1961. $buffer = '';
  1962. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1963. // 逐行读取流式响应
  1964. while (!$body->eof()) {
  1965. $chunk = $body->read(1024); // 每次读取 1KB
  1966. $buffer .= $chunk;
  1967. // 按行分割
  1968. $lines = explode("\n", $buffer);
  1969. // 保留最后一个不完整的行
  1970. $buffer = array_pop($lines);
  1971. foreach ($lines as $line) {
  1972. $line = trim($line);
  1973. // 跳过空行
  1974. if (empty($line)) {
  1975. continue;
  1976. }
  1977. // 检查是否是 SSE 数据行
  1978. if (strpos($line, 'data: ') !== 0) {
  1979. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1980. continue;
  1981. }
  1982. $data = substr($line, 6); // 移除 "data: " 前缀
  1983. if ($data === '[DONE]') {
  1984. dLog('deepseek')->info('收到结束标记');
  1985. break 2; // 跳出两层循环
  1986. }
  1987. try {
  1988. $json = json_decode($data, true);
  1989. if (json_last_error() !== JSON_ERROR_NONE) {
  1990. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1991. continue;
  1992. }
  1993. if (isset($json['choices'][0]['delta'])) {
  1994. $delta = $json['choices'][0]['delta'];
  1995. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1996. if (isset($delta['reasoning_content'])) {
  1997. $fullReasoningContent .= $delta['reasoning_content'];
  1998. yield [
  1999. 'type' => 'reasoning',
  2000. 'content' => $delta['reasoning_content'],
  2001. 'full_reasoning' => $fullReasoningContent
  2002. ];
  2003. }
  2004. // 处理最终回答内容
  2005. if (isset($delta['content'])) {
  2006. $fullContent .= $delta['content'];
  2007. yield [
  2008. 'type' => 'content',
  2009. 'content' => $delta['content'],
  2010. ];
  2011. }
  2012. }
  2013. // 获取使用统计信息
  2014. if (isset($json['usage'])) {
  2015. $usage = $json['usage'];
  2016. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2017. }
  2018. } catch (\Exception $e) {
  2019. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2020. continue;
  2021. }
  2022. }
  2023. }
  2024. dLog('deepseek')->info('流式读取完成', [
  2025. 'content_length' => strlen($fullContent),
  2026. 'reasoning_length' => strlen($fullReasoningContent)
  2027. ]);
  2028. yield [
  2029. 'type' => 'done',
  2030. 'full_content' => $fullContent,
  2031. 'full_reasoning' => $fullReasoningContent,
  2032. 'usage' => $usage
  2033. ];
  2034. }
  2035. /**
  2036. * GPT 重试次数(env 可配置,默认 5 次)
  2037. */
  2038. private function gptRetryTimes()
  2039. {
  2040. return (int)env('GPT_RETRY_TIMES', 5);
  2041. }
  2042. /**
  2043. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  2044. */
  2045. private function gptRetryInterval()
  2046. {
  2047. return (int)env('GPT_RETRY_INTERVAL', 10);
  2048. }
  2049. /**
  2050. * 判断 GPT 请求异常是否可重试
  2051. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  2052. */
  2053. private function isGptRetryableException(\Exception $e)
  2054. {
  2055. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  2056. return false;
  2057. }
  2058. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  2059. $status = $e->getResponse()->getStatusCode();
  2060. return $status >= 500 || $status == 429;
  2061. }
  2062. return true;
  2063. }
  2064. /**
  2065. * GPT 中转站探活:GET /v1/models,5 秒短超时
  2066. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  2067. */
  2068. private function checkGptServiceAvailable()
  2069. {
  2070. $apiKey = env('GPT_54_API_KEY');
  2071. if (empty($apiKey)) {
  2072. return false;
  2073. }
  2074. try {
  2075. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  2076. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  2077. 'headers' => [
  2078. 'Authorization' => 'Bearer ' . $apiKey,
  2079. 'Content-Type' => 'application/json'
  2080. ]
  2081. ]);
  2082. $status = $response->getStatusCode();
  2083. return $status < 500 && $status != 429;
  2084. } catch (\Exception $e) {
  2085. return false;
  2086. }
  2087. }
  2088. /**
  2089. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  2090. * 全部失败抛出友好错误
  2091. */
  2092. private function ensureGptServiceAvailable()
  2093. {
  2094. $maxRetries = $this->gptRetryTimes();
  2095. $interval = $this->gptRetryInterval();
  2096. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  2097. if ($this->checkGptServiceAvailable()) {
  2098. return;
  2099. }
  2100. if ($attempt < $maxRetries) {
  2101. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  2102. 'retry' => $attempt + 1,
  2103. 'max_retries' => $maxRetries
  2104. ]);
  2105. sleep($interval);
  2106. }
  2107. }
  2108. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  2109. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  2110. 'max_retries' => $maxRetries,
  2111. 'interval' => $interval
  2112. ]);
  2113. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  2114. }
  2115. /**
  2116. * GPT 流式输出处理方法
  2117. *
  2118. * @param array $post_data GPT API请求参数
  2119. * @return \Generator 返回生成器,用于流式输出
  2120. */
  2121. private function gpt54StreamResponse($post_data) {
  2122. $apiKey = env('GPT_54_API_KEY');
  2123. if (empty($apiKey)) {
  2124. Utils::throwError('20003:GPT API Key未配置');
  2125. }
  2126. // 先探活,服务不可用时自动重试
  2127. $this->ensureGptServiceAvailable();
  2128. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2129. $headers = [
  2130. 'Authorization' => 'Bearer ' . $apiKey,
  2131. 'Content-Type' => 'application/json',
  2132. 'Accept' => 'text/event-stream'
  2133. ];
  2134. // 移除 thinking 参数,GPT-5.4 不支持
  2135. if (isset($post_data['thinking'])) {
  2136. unset($post_data['thinking']);
  2137. }
  2138. if (isset($post_data['reasoning_effort'])) {
  2139. unset($post_data['reasoning_effort']);
  2140. }
  2141. // 中转站不识别 response_format,可能被误转成 JSON 输出模式
  2142. if (isset($post_data['response_format'])) {
  2143. unset($post_data['response_format']);
  2144. }
  2145. $post_data['max_completion_tokens'] = 100000;
  2146. $maxRetries = $this->gptRetryTimes();
  2147. $interval = $this->gptRetryInterval();
  2148. $attempt = 0;
  2149. while (true) {
  2150. $fullContent = '';
  2151. $usage = [];
  2152. $buffer = '';
  2153. $suspectJsonWrap = false;
  2154. $pendingContent = '';
  2155. try {
  2156. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  2157. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  2158. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  2159. 'json' => $post_data,
  2160. 'headers' => $headers,
  2161. 'stream' => true // 启用流式响应
  2162. ]);
  2163. $body = $response->getBody();
  2164. dLog('deepseek')->info('开始读取 GPT 流式响应');
  2165. // 逐行读取流式响应
  2166. while (!$body->eof()) {
  2167. $chunk = $body->read(1024); // 每次读取 1KB
  2168. $buffer .= $chunk;
  2169. // 按行分割
  2170. $lines = explode("\n", $buffer);
  2171. // 保留最后一个不完整的行
  2172. $buffer = array_pop($lines);
  2173. foreach ($lines as $line) {
  2174. $line = trim($line);
  2175. // 跳过空行
  2176. if (empty($line)) {
  2177. continue;
  2178. }
  2179. // 检查是否是 SSE 数据行
  2180. if (strpos($line, 'data: ') !== 0) {
  2181. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2182. continue;
  2183. }
  2184. $data = substr($line, 6); // 移除 "data: " 前缀
  2185. if ($data === '[DONE]') {
  2186. dLog('deepseek')->info('收到结束标记');
  2187. break 2; // 跳出 foreach 和流读取循环
  2188. }
  2189. try {
  2190. $json = json_decode($data, true);
  2191. if (json_last_error() !== JSON_ERROR_NONE) {
  2192. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2193. continue;
  2194. }
  2195. if (isset($json['choices'][0]['delta'])) {
  2196. $delta = $json['choices'][0]['delta'];
  2197. // 处理回答内容
  2198. if (isset($delta['content'])) {
  2199. $fullContent .= $delta['content'];
  2200. $trimmed = ltrim($fullContent);
  2201. if (!$suspectJsonWrap && $trimmed !== '' && ($trimmed[0] === '{' || $trimmed[0] === '[')) {
  2202. // 可能模型把整段正文包成了 JSON 字符串,先暂缓输出
  2203. $suspectJsonWrap = true;
  2204. }
  2205. if (!$suspectJsonWrap) {
  2206. // 中转可能一次返回大段内容,按小块输出保持流式节奏
  2207. $chunkSize = 256;
  2208. $chunkLength = mb_strlen($delta['content']);
  2209. for ($offset = 0; $offset < $chunkLength; $offset += $chunkSize) {
  2210. yield [
  2211. 'type' => 'content',
  2212. 'content' => mb_substr($delta['content'], $offset, $chunkSize),
  2213. ];
  2214. }
  2215. } else {
  2216. $pendingContent .= $delta['content'];
  2217. }
  2218. }
  2219. }
  2220. // 获取使用统计信息
  2221. if (isset($json['usage'])) {
  2222. $usage = $json['usage'];
  2223. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2224. }
  2225. } catch (\Exception $e) {
  2226. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2227. continue;
  2228. }
  2229. }
  2230. }
  2231. dLog('deepseek')->info('流式读取完成', [
  2232. 'content_length' => strlen($fullContent)
  2233. ]);
  2234. // 兼容模型偶发把整段正文包裹成 JSON 字符串返回
  2235. if ($suspectJsonWrap) {
  2236. $decoded = json_decode(trim($fullContent), true);
  2237. $unwrapped = null;
  2238. if (is_array($decoded)) {
  2239. foreach (['result', 'content', 'text', 'output', 'data'] as $key) {
  2240. if (isset($decoded[$key]) && is_string($decoded[$key]) && $decoded[$key] !== '') {
  2241. $unwrapped = $decoded[$key];
  2242. break;
  2243. }
  2244. }
  2245. }
  2246. if ($unwrapped !== null) {
  2247. $fullContent = $unwrapped;
  2248. $chunkSize = 256;
  2249. $contentLength = mb_strlen($fullContent);
  2250. for ($offset = 0; $offset < $contentLength; $offset += $chunkSize) {
  2251. yield [
  2252. 'type' => 'content',
  2253. 'content' => mb_substr($fullContent, $offset, $chunkSize),
  2254. ];
  2255. }
  2256. } elseif ($pendingContent !== '') {
  2257. // 误判:补发暂缓内容,避免内容丢失
  2258. yield [
  2259. 'type' => 'content',
  2260. 'content' => $pendingContent,
  2261. ];
  2262. }
  2263. }
  2264. yield [
  2265. 'type' => 'done',
  2266. 'full_content' => $fullContent,
  2267. 'full_reasoning' => '',
  2268. 'usage' => $usage
  2269. ];
  2270. return;
  2271. } catch (\Exception $e) {
  2272. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  2273. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  2274. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  2275. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  2276. throw $e;
  2277. }
  2278. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  2279. 'retry' => $attempt + 1,
  2280. 'max_retries' => $maxRetries,
  2281. 'error' => $e->getMessage()
  2282. ]);
  2283. sleep($interval);
  2284. $attempt++;
  2285. }
  2286. }
  2287. }
  2288. // 与推理模型对话
  2289. public function chatWithReasoner($data) {
  2290. $content = getProp($data, 'content');
  2291. $model = getProp($data, 'model', 'r1');
  2292. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2293. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2294. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2295. if ($model == 'r1') {
  2296. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  2297. $thinkingMode = 'disabled';
  2298. } else {
  2299. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  2300. $thinkingMode = 'disabled';
  2301. }
  2302. // 获取可选情感(根据音色可支持情感选)
  2303. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  2304. $emotion_list = [];
  2305. foreach ($timbre_emotion as $emotion) {
  2306. $tmp = explode(',', $emotion);
  2307. $emotion_list = array_merge($emotion_list, $tmp);
  2308. }
  2309. $emotion_list = array_unique($emotion_list);
  2310. $emotion_str = implode('、', $emotion_list);
  2311. // // 获取可选情感
  2312. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  2313. // $emotion_str = implode('、', $emotion_list);
  2314. // 是否启用情感
  2315. $enable_emotion = getProp($data, 'enable_emotion', 0);
  2316. if ($enable_emotion) {
  2317. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  2318. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2319. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  2320. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  2321. }else {
  2322. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  2323. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  2324. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  2325. }
  2326. $messages = [
  2327. [
  2328. 'role' => 'system',
  2329. 'content' => $sys_content
  2330. ],
  2331. [
  2332. 'role' => 'user',
  2333. 'content' => $content
  2334. ]
  2335. ];
  2336. $post_data = [
  2337. 'model' => $model,
  2338. 'messages' => $messages,
  2339. // 'max_tokens' => 8192,
  2340. 'temperature' => 1,
  2341. 'frequency_penalty' => 0,
  2342. 'presence_penalty' => 0,
  2343. 'thinking' => ['type' => $thinkingMode],
  2344. 'response_format' => [
  2345. 'type' => 'text'
  2346. ],
  2347. 'stream' => false
  2348. ];
  2349. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2350. // 根据模型类型选择调用方法
  2351. $fullContent = '';
  2352. $usage = [];
  2353. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2354. // DeepSeek 官方模型使用 DeepSeek API
  2355. $chatResult = $this->chatOnly($post_data);
  2356. } else if (in_array($model, $this->gpt_text_models)) {
  2357. // GPT-5.4 模型使用 TokenRouter API
  2358. $chatResult = $this->gpt54ChatOnly($post_data);
  2359. } else {
  2360. // 其他模型使用火山引擎API
  2361. $chatResult = $this->volcEngineChatCompletion($post_data);
  2362. }
  2363. if (is_array($chatResult)) {
  2364. $fullContent = $chatResult['fullContent'];
  2365. $usage = $chatResult['usage'];
  2366. }
  2367. // 处理获取到的剧本数据
  2368. $script_content = handleScriptWords($fullContent, $enable_emotion);
  2369. $result = [
  2370. 'origin_content' => $fullContent,
  2371. 'roles' => getProp($script_content, 'roles'),
  2372. 'words' => getProp($script_content, 'words'),
  2373. ];
  2374. return $result;
  2375. }
  2376. public function resetParagraphAudio($data) {
  2377. $bid = getProp($data, 'bid');
  2378. $cid = getProp($data, 'cid');
  2379. $version_id = getProp($data, 'version_id');
  2380. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  2381. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  2382. 'generate_status' => '待制作',
  2383. 'updated_at' => date('Y-m-d H:i:s')
  2384. ]);
  2385. }
  2386. public function saveParagraphAudio($data) {
  2387. $bid = getProp($data, 'bid');
  2388. $cid = getProp($data, 'cid');
  2389. $version_id = getProp($data, 'version_id');
  2390. $sequence = getProp($data, 'sequence');
  2391. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  2392. // 获取所有情感
  2393. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  2394. $emotion_list = array_flip($emotion_list);
  2395. // 获取音色支持情感
  2396. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  2397. $timbre_emotion = explode(',', $timbre_emotion);
  2398. $emotion = getProp($data, 'emotion');
  2399. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  2400. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  2401. $list = [
  2402. 'bid' => $bid,
  2403. 'cid' => $cid,
  2404. 'version_id' => $version_id,
  2405. 'sequence' => $sequence,
  2406. 'role' => getProp($data, 'role'),
  2407. 'gender' => getProp($data, 'gender'),
  2408. 'text' => trim(getProp($data, 'text')),
  2409. 'emotion' => $emotion,
  2410. 'emotion_type' => $emotion_type,
  2411. 'voice_type' => getProp($data, 'voice_type'),
  2412. 'voice_name' => getProp($data, 'voice_name'),
  2413. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  2414. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  2415. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  2416. 'pitch' => getProp($data, 'pitch', 0),
  2417. // 'paragraph_audio_url' => '',
  2418. 'generate_status' => '制作中',
  2419. 'error_msg' => '',
  2420. 'updated_at' => date('Y-m-d H:i:s')
  2421. ];
  2422. $continue = false;
  2423. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  2424. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  2425. $list['generate_status'] = '制作成功';
  2426. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  2427. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  2428. $continue = true;
  2429. }
  2430. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  2431. if ($id) {
  2432. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  2433. }else {
  2434. $list['created_at'] = date('Y-m-d H:i:s');
  2435. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  2436. $boolen = $id ? true : false;
  2437. }
  2438. // 如果更新成功则加入查询队列
  2439. if ($boolen) {
  2440. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  2441. Redis::sadd($redis_key, $id);
  2442. }
  2443. if ($boolen && !$continue) {
  2444. $boolen = false;
  2445. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2446. // 根据ID通过API通知合成音频
  2447. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  2448. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  2449. $response = $result->getBody()->getContents();
  2450. $response_arr = json_decode($response, true);
  2451. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2452. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2453. Log::info('通知火山生成段落音频失败: '.$error_msg);
  2454. Utils::throwError('20003:通知火山生成段落音频失败');
  2455. }
  2456. $boolen = true;
  2457. }
  2458. return $boolen;
  2459. }
  2460. public function insertAudioEffect($data) {
  2461. $audio_id = getProp($data, 'audio_id');
  2462. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2463. $bid = getProp($chapter_audio, 'bid');
  2464. $version_id = getProp($chapter_audio, 'version_id');
  2465. $cid = getProp($chapter_audio, 'cid');
  2466. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2467. $audio_effect_json = getProp($data, 'audio_effect_json');
  2468. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  2469. try {
  2470. DB::beginTransaction();
  2471. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2472. if (!$count) {
  2473. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2474. }else {
  2475. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2476. }
  2477. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2478. 'audio_effect_status' => '添加中',
  2479. 'audio_effect_json' => $audio_effect_json,
  2480. 'updated_at' => date('Y-m-d H:i:s')
  2481. ]);
  2482. if (!$boolen1) {
  2483. DB::rollBack();
  2484. Utils::throwError('20003:更新生成数据失败');
  2485. }
  2486. $id = DB::table('mp_audio_tasks')->insertGetId([
  2487. 'audio_id' => $audio_id,
  2488. 'generate_status' => '执行中',
  2489. 'generate_json' => json_encode([], 256),
  2490. 'bid' => $bid,
  2491. 'book_name' => getProp($chapter_audio, 'book_name'),
  2492. 'version_id' => $version_id,
  2493. 'version_name' => getProp($chapter_audio, 'version_name'),
  2494. 'cid' => $cid,
  2495. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2496. 'task_name' => $task_name,
  2497. 'created_at' => date('Y-m-d H:i:s'),
  2498. 'updated_at' => date('Y-m-d H:i:s')
  2499. ]);
  2500. if (!$id) {
  2501. DB::rollBack();
  2502. Utils::throwError('20003:创建任务失败');
  2503. }
  2504. }catch (\Exception $e) {
  2505. DB::rollBack();
  2506. Utils::throwError('20003:'.$e->getMessage());
  2507. }
  2508. DB::commit();
  2509. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2510. // 根据ID通过API通知合成音频
  2511. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2512. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2513. $response = $result->getBody()->getContents();
  2514. $response_arr = json_decode($response, true);
  2515. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2516. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2517. Log::info('通知火山插入音效失败: '.$error_msg);
  2518. Utils::throwError('20003:通知火山插入音效失败');
  2519. }
  2520. return true;
  2521. }
  2522. public function insertBgm($data) {
  2523. $audio_id = getProp($data, 'audio_id');
  2524. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  2525. $bid = getProp($chapter_audio, 'bid');
  2526. $version_id = getProp($chapter_audio, 'version_id');
  2527. $cid = getProp($chapter_audio, 'cid');
  2528. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  2529. $bgm_json = getProp($data, 'bgm_json');
  2530. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2531. if (!$bgm_json) {
  2532. $bgm_json = getProp($data, 'audio_effect_json');
  2533. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  2534. }
  2535. try {
  2536. DB::beginTransaction();
  2537. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  2538. if (!$count) {
  2539. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2540. }else {
  2541. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2542. }
  2543. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  2544. 'bgm_status' => '添加中',
  2545. 'bgm_json' => $bgm_json,
  2546. 'updated_at' => date('Y-m-d H:i:s')
  2547. ]);
  2548. if (!$boolen1) {
  2549. DB::rollBack();
  2550. Utils::throwError('20003:更新生成数据失败');
  2551. }
  2552. $id = DB::table('mp_audio_tasks')->insertGetId([
  2553. 'audio_id' => $audio_id,
  2554. 'generate_status' => '执行中',
  2555. 'generate_json' => json_encode([], 256),
  2556. 'bid' => $bid,
  2557. 'book_name' => getProp($chapter_audio, 'book_name'),
  2558. 'version_id' => $version_id,
  2559. 'version_name' => getProp($chapter_audio, 'version_name'),
  2560. 'cid' => $cid,
  2561. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2562. 'task_name' => $task_name,
  2563. 'created_at' => date('Y-m-d H:i:s'),
  2564. 'updated_at' => date('Y-m-d H:i:s')
  2565. ]);
  2566. if (!$id) {
  2567. DB::rollBack();
  2568. Utils::throwError('20003:创建任务失败');
  2569. }
  2570. }catch (\Exception $e) {
  2571. DB::rollBack();
  2572. Utils::throwError('20003:'.$e->getMessage());
  2573. }
  2574. DB::commit();
  2575. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2576. // 根据ID通过API通知合成音频
  2577. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  2578. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  2579. $response = $result->getBody()->getContents();
  2580. $response_arr = json_decode($response, true);
  2581. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2582. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2583. Log::info('通知火山插入bgm失败: '.$error_msg);
  2584. Utils::throwError('20003:通知火山插入bgm失败');
  2585. }
  2586. return true;
  2587. }
  2588. public function getParagraphAudios($data) {
  2589. $bid = getProp($data, 'bid');
  2590. $cid = getProp($data, 'cid');
  2591. $version_id = getProp($data, 'version_id');
  2592. $sequence = getProp($data, 'sequence');
  2593. // 获取已生成的音频
  2594. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  2595. if ($sequence) $query->where('sequence', $sequence);
  2596. $paragraph_audios = $query->orderBy('sequence')->get();
  2597. $result = [];
  2598. foreach($paragraph_audios as $item) {
  2599. $result[] = [
  2600. 'sequence' => getProp($item, 'sequence'),
  2601. 'role' => getProp($item, 'role'),
  2602. 'gender' => getProp($item, 'gender'),
  2603. 'text' => trim(getProp($item, 'text')),
  2604. 'emotion' => getProp($item, 'emotion'),
  2605. 'emotion_type' => getProp($item, 'emotion_type'),
  2606. 'voice_type' => getProp($item, 'voice_type'),
  2607. 'voice_name' => getProp($item, 'voice_name'),
  2608. 'speed_ratio' => getProp($item, 'speed_ratio'),
  2609. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  2610. 'emotion_scale' => getProp($item, 'emotion_scale'),
  2611. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  2612. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  2613. ];
  2614. }
  2615. return $result;
  2616. }
  2617. // 新增合成任务
  2618. public function addGenerateTask($data) {
  2619. $bid = getProp($data, 'bid');
  2620. $cid = getProp($data, 'cid');
  2621. $version_id = getProp($data, 'version_id');
  2622. $generate_json = getProp($data, 'generate_json');
  2623. // 获取已生成的音频
  2624. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  2625. $paragraph_list = [];
  2626. foreach($paragraph_audios as $item) {
  2627. $paragraph_list[getProp($item, 'sequence')] = [
  2628. 'role' => getProp($item, 'role'),
  2629. 'gender' => getProp($item, 'gender'),
  2630. 'text' => trim(getProp($item, 'text')),
  2631. 'emotion' => getProp($item, 'emotion'),
  2632. 'emotion_type' => getProp($item, 'emotion_type'),
  2633. 'voice_type' => getProp($item, 'voice_type'),
  2634. 'voice_name' => getProp($item, 'voice_name'),
  2635. 'speed_ratio' => getProp($item, 'speed_ratio'),
  2636. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  2637. 'emotion_scale' => getProp($item, 'emotion_scale'),
  2638. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  2639. ];
  2640. }
  2641. // 更新角色-音色信息
  2642. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  2643. $existed_role_info = json_decode($existed_role_info, true);
  2644. if (!$existed_role_info) $existed_role_info = [];
  2645. // 获取情感信息
  2646. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  2647. $emotion_list = array_flip($emotion_list);
  2648. // 获取音色对应情感组
  2649. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  2650. $timbre_emotion_list = [];
  2651. foreach($timbre_emotions as $item) {
  2652. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  2653. }
  2654. // 构造生成音频的json
  2655. $words = json_decode($generate_json, true);
  2656. // 最终合成前的参数组
  2657. $mp_chapter_paragraph_audios = [];
  2658. $sequence = 1;
  2659. $complete_paragraph_sequences = [];
  2660. foreach($words as &$word) {
  2661. 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:参数格式有误');
  2662. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  2663. $role = getProp($word, 'role');
  2664. $word['gender'] = (int)$word['gender'];
  2665. // 判断音色对应情感是否支持,不支持则调整为中性
  2666. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  2667. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  2668. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  2669. if (isset($emotion_list[getProp($word, 'emotion')])) {
  2670. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  2671. }else {
  2672. $word['emotion'] = '中性';
  2673. $word['emotion_type'] = 'neutral';
  2674. }
  2675. $existed_role_info[$role] = [
  2676. 'timbre_type' => $word['voice_type'],
  2677. 'timbre_name' => $word['voice_name'],
  2678. 'emotion' => $word['emotion'],
  2679. 'emotion_type' => $word['emotion_type'],
  2680. 'speed_ratio' => $word['speed_ratio'],
  2681. 'loudness_ratio'=> $word['loudness_ratio'],
  2682. 'emotion_scale' => $word['emotion_scale'],
  2683. 'pitch' => $word['pitch']
  2684. ];
  2685. $word['paragraph_audio_url'] = '';
  2686. // 判断生成参数是否相同,相同则直接使用已生成的音频
  2687. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  2688. // 如果音频存在并且参数都未改变则使用已生成的音频
  2689. if (getProp($paragraph, 'paragraph_audio_url')) {
  2690. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  2691. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  2692. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  2693. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  2694. // {
  2695. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  2696. // }
  2697. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  2698. }
  2699. $tmp = $word;
  2700. // 组装章节分句音频数据
  2701. // $tmp['sequence'] = getProp($word, 'sequence');
  2702. // $tmp['text'] = getProp($word, 'text');
  2703. // $tmp['emotion'] = getProp($word, 'emotion');
  2704. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  2705. // $tmp['voice_name'] = getProp($word, 'voice_name');
  2706. // $tmp['voice_type'] = getProp($word, 'voice_type');
  2707. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  2708. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  2709. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  2710. $tmp['bid'] = $bid;
  2711. $tmp['version_id'] = $version_id;
  2712. $tmp['cid'] = $cid;
  2713. $tmp['sequence'] = $sequence;
  2714. $tmp['created_at'] = date('Y-m-d H:i:s');
  2715. $tmp['updated_at'] = date('Y-m-d H:i:s');
  2716. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  2717. $mp_chapter_paragraph_audios[] = $tmp;
  2718. $complete_paragraph_sequences[] = $sequence;
  2719. $sequence++;
  2720. }
  2721. $generate_json = json_encode($words, 256);
  2722. // 判断是否有未生成字幕的段落
  2723. $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();
  2724. if ($no_subtitle_sequences) {
  2725. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  2726. }
  2727. try {
  2728. DB::beginTransaction();
  2729. $role_info = json_encode($existed_role_info, 256);
  2730. $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')]);
  2731. if (!$boolen) {
  2732. DB::rollBack();
  2733. Utils::throwError('20003:更新角色信息失败');
  2734. }
  2735. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  2736. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  2737. if (!$count) {
  2738. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  2739. }else {
  2740. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  2741. }
  2742. $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')]);
  2743. if (!$boolen1) {
  2744. DB::rollBack();
  2745. Utils::throwError('20003:更新生成数据失败');
  2746. }
  2747. $id = DB::table('mp_audio_tasks')->insertGetId([
  2748. 'audio_id' => getProp($chapter_audio, 'id'),
  2749. 'generate_status' => '执行中',
  2750. 'generate_json' => $generate_json,
  2751. 'bid' => $bid,
  2752. 'book_name' => getProp($chapter_audio, 'book_name'),
  2753. 'version_id' => $version_id,
  2754. 'version_name' => getProp($chapter_audio, 'version_name'),
  2755. 'cid' => $cid,
  2756. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  2757. 'task_name' => $task_name,
  2758. 'created_at' => date('Y-m-d H:i:s'),
  2759. 'updated_at' => date('Y-m-d H:i:s')
  2760. ]);
  2761. if (!$id) {
  2762. DB::rollBack();
  2763. Utils::throwError('20003:创建任务失败');
  2764. }
  2765. // 删除不在段落序号范围内的其他数据
  2766. if ($complete_paragraph_sequences) {
  2767. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  2768. }
  2769. // // 删除章节分句音频数据并重新插入
  2770. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  2771. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  2772. // if (!$boolen3) {
  2773. // DB::rollBack();
  2774. // Utils::throwError('20003:更新章节分句音频失败');
  2775. // }
  2776. } catch (\Exception $e) {
  2777. DB::rollBack();
  2778. Utils::throwError('20003:'.$e->getMessage());
  2779. }
  2780. DB::commit();
  2781. // 通知火山生成音频
  2782. $client = new Client(['timeout' => 1800, 'verify' => false]);
  2783. // 根据ID通过API通知合成音频
  2784. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  2785. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  2786. $response = $result->getBody()->getContents();
  2787. $response_arr = json_decode($response, true);
  2788. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  2789. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  2790. Log::info('通知火山生成音频失败: '.$error_msg);
  2791. Utils::throwError('20003:通知火山生成音频失败');
  2792. }
  2793. return true;
  2794. }
  2795. public function timbreList($data) {
  2796. $gender = getProp($data, 'gender');
  2797. $timbre_name = getProp($data, 'voice_name');
  2798. $category_id = getProp($data, 'category_id');
  2799. $age_stage = getProp($data, 'age_stage');
  2800. $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');
  2801. if ($gender) {
  2802. $query->where('gender', $gender);
  2803. }
  2804. if ($timbre_name) {
  2805. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  2806. }
  2807. if ($category_id) {
  2808. $query->where(function ($query) use ($category_id) {
  2809. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  2810. });
  2811. }
  2812. if ($age_stage) {
  2813. $query->where('age_stage', $age_stage);
  2814. }
  2815. $list = $query->get()->map(function ($value) {
  2816. $value = (array)$value;
  2817. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  2818. return $value;
  2819. })->toArray();
  2820. return $list;
  2821. }
  2822. // 生成火山临时token
  2823. public function setStsToken() {
  2824. // ************* 配置参数 *************
  2825. $method = 'GET';
  2826. $service = 'sts';
  2827. $host = 'open.volcengineapi.com';
  2828. $region = env('VOLC_REGION');
  2829. $endpoint = 'https://open.volcengineapi.com';
  2830. // $endpoint = 'https://tos-cn-beijing.volces.com';
  2831. $access_key = env('VOLC_AK');
  2832. $secret_key = env('VOLC_SK');
  2833. // 获取缓存中的token,如果没有则请求接口
  2834. $token = Redis::get('volc_sts_token');
  2835. if (!$token) {
  2836. // 查询参数
  2837. $query_parameters = [
  2838. 'Action' => 'AssumeRole',
  2839. 'RoleSessionName' => 'user@zw',
  2840. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  2841. 'Version' => '2018-01-01'
  2842. ];
  2843. // 生成URL编码的查询字符串
  2844. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  2845. // 获取签名头信息
  2846. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  2847. // 构建完整URL
  2848. $request_url = $endpoint . '?' . $request_parameters;
  2849. $client = new Client(['verify' => false]);
  2850. $response = $client->get($request_url, ['headers' => $headers]);
  2851. $response_arr = json_decode($response->getBody()->getContents(), true);
  2852. $result = [
  2853. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  2854. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  2855. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  2856. 'Region' => env('VOLC_REGION'),
  2857. 'Endpoint' => env('VOLC_END_POINT'),
  2858. 'Bucket' => env('VOLC_BUCKET'),
  2859. ];
  2860. // 缓存token
  2861. Redis::setex('volc_sts_token', 3000, json_encode($result));
  2862. return $result;
  2863. } else {
  2864. return json_decode($token, true);
  2865. }
  2866. // $response = $response['Response'];
  2867. // $access_key = $response['Credentials']['AccessKeyId'];
  2868. // $secret_key = $response['Credentials']['AccessKeySecret'];
  2869. // $security_token = $response['Credentials']['SecurityToken'];
  2870. // $expiration = $response['Credentials']['Expiration'];
  2871. // dd($response_arr);
  2872. }
  2873. public function emotionGroups($data) {
  2874. $id = getProp($data, 'group_id');
  2875. $group_name = getProp($data, 'group_name');
  2876. $voice_type = getProp($data, 'voice_type');
  2877. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  2878. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  2879. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  2880. if ($group_name) {
  2881. $query->where('group_name', 'like', "%{$group_name}%");
  2882. }
  2883. if ($id) {
  2884. $query->where('id', $id);
  2885. }
  2886. if ($voice_type) {
  2887. $query->where('voice_type', $voice_type);
  2888. }
  2889. return $query->orderBy('id')->get()->map(function ($value) {
  2890. return (array)$value;
  2891. })->toArray();
  2892. }
  2893. private function sign($key, $msg) {
  2894. return hash_hmac('sha256', $msg, $key, true);
  2895. }
  2896. // 生成签名密钥
  2897. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  2898. $kDate = $this->sign($key, $dateStamp);
  2899. $kRegion = $this->sign($kDate, $regionName);
  2900. $kService = $this->sign($kRegion, $serviceName);
  2901. $kSigning = $this->sign($kService, 'request');
  2902. return $kSigning;
  2903. }
  2904. // 获取签名头信息
  2905. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  2906. $contenttype = 'application/x-www-form-urlencoded';
  2907. $accept = 'application/json';
  2908. // 获取当前UTC时间
  2909. $t = new DateTime('now', new DateTimeZone('UTC'));
  2910. $xdate = $t->format('Ymd\THis\Z');
  2911. $datestamp = $t->format('Ymd');
  2912. // 1. 拼接规范请求串
  2913. $canonical_uri = '/';
  2914. $canonical_querystring = $request_parameters;
  2915. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  2916. $signed_headers = 'content-type;host;x-date';
  2917. // 空请求体的SHA256哈希
  2918. $payload_hash = hash('sha256', '');
  2919. $canonical_request = implode("\n", [
  2920. $method,
  2921. $canonical_uri,
  2922. $canonical_querystring,
  2923. $canonical_headers,
  2924. $signed_headers,
  2925. $payload_hash
  2926. ]);
  2927. // 2. 拼接待签名字符串
  2928. $algorithm = 'HMAC-SHA256';
  2929. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  2930. $hashed_canonical_request = hash('sha256', $canonical_request);
  2931. $string_to_sign = implode("\n", [
  2932. $algorithm,
  2933. $xdate,
  2934. $credential_scope,
  2935. $hashed_canonical_request
  2936. ]);
  2937. // 3. 计算签名
  2938. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  2939. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  2940. // 4. 添加签名到请求头
  2941. $authorization_header = sprintf(
  2942. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  2943. $algorithm,
  2944. $access_key,
  2945. $credential_scope,
  2946. $signed_headers,
  2947. $signature
  2948. );
  2949. return [
  2950. 'Accept' => $accept,
  2951. 'Content-Type' => $contenttype,
  2952. 'X-Date' => $xdate,
  2953. 'Authorization' => $authorization_header
  2954. ];
  2955. }
  2956. // 文字合成语音(火山引擎)
  2957. public function tts($data) {
  2958. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  2959. $headers = [
  2960. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  2961. 'Content-Type' => 'application/json; charset=UTF-8'
  2962. ];
  2963. $post_data = [
  2964. 'app' => [
  2965. 'appid' => env('VOLC_APPID'),
  2966. 'token' => env('VOLC_TOKEN'),
  2967. 'cluster' => 'volcano_tts'
  2968. ],
  2969. 'user' => [
  2970. 'uid' => 'mp_audio'
  2971. ],
  2972. // 'audio' => [
  2973. // 'voice_type' =>
  2974. // ],
  2975. ];
  2976. }
  2977. public function scriptList($data) {
  2978. $uid = Site::getUid();
  2979. $script_id = getProp($data, 'script_id');
  2980. $script_name = getProp($data, 'script_name');
  2981. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  2982. if ($script_id) {
  2983. $query->where('id', $script_id);
  2984. }
  2985. if ($script_name) {
  2986. $query->where('script_name', 'like', "%{$script_name}%");
  2987. }
  2988. return $query->orderBy('created_at', 'desc')->paginate(12);
  2989. }
  2990. public function scripts($data) {
  2991. $uid = Site::getUid();
  2992. $script_id = getProp($data, 'script_id');
  2993. $script_name = getProp($data, 'script_name');
  2994. $is_products = getProp($data, 'is_products');
  2995. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  2996. if ($script_id) {
  2997. $query->where('id', $script_id);
  2998. }
  2999. if ($is_products !== '') {
  3000. $query->where('is_products', $is_products);
  3001. }
  3002. if ($script_name) {
  3003. $query->where('script_name', 'like', "%{$script_name}%");
  3004. }
  3005. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  3006. return (array)$value;
  3007. })->toArray();
  3008. }
  3009. public function scriptInfo($data) {
  3010. $uid = Site::getUid();
  3011. $script_id = getProp($data, 'script_id');
  3012. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  3013. // ->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();
  3014. ->selectRaw('id as script_id, script_name')->first();
  3015. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3016. $script = (array)$script;
  3017. // 获取分集组信息
  3018. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  3019. ->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')
  3020. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  3021. $value = (array)$value;
  3022. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  3023. return (array)$value;
  3024. })->toArray();
  3025. $script['group'] = $groups;
  3026. return $script;
  3027. }
  3028. public function createScript($data) {
  3029. $script_name = getProp($data, 'script_name');
  3030. $uid = Site::getUid(); // 获取当前用户ID
  3031. $cpid = Site::getCpid(); // 获取当前公司组ID
  3032. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  3033. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  3034. $script_name .= '_'.date('YmdHis');
  3035. }
  3036. return DB::table('mp_scripts')->insertGetId([
  3037. 'script_name' => $script_name,
  3038. 'user_id' => $uid,
  3039. 'cpid' => $cpid,
  3040. 'created_at' => date('Y-m-d H:i:s'),
  3041. 'updated_at' => date('Y-m-d H:i:s')
  3042. ]);
  3043. }
  3044. public function editScript($data) {
  3045. $script_id = getProp($data, 'script_id');
  3046. $script_name = getProp($data, 'script_name');
  3047. $uid = Site::getUid(); // 获取当前用户ID
  3048. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  3049. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  3050. if ($id && (int)$id !== (int)$script_id) {
  3051. $script_name .= '_'.date('YmdHis');
  3052. }
  3053. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3054. 'script_name' => $script_name,
  3055. 'updated_at' => date('Y-m-d H:i:s')
  3056. ]);
  3057. }
  3058. public function delScript($data) {
  3059. $script_id = getProp($data, 'script_id');
  3060. $uid = Site::getUid(); // 获取当前用户ID
  3061. if (!$script_id) Utils::throwError('20003:请选择剧本');
  3062. return DB::table('mp_scripts')->where('id', $script_id)->update([
  3063. 'is_deleted' => 1,
  3064. 'updated_at' => date('Y-m-d H:i:s')
  3065. ]);
  3066. }
  3067. public function createEpisode($data) {
  3068. $script_id = getProp($data, 'script_id');
  3069. $group_name = getProp($data, 'group_name');
  3070. $remark = getProp($data, 'remark');
  3071. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  3072. $uid = Site::getUid(); // 获取当前用户ID
  3073. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  3074. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  3075. $group_name .= '_'.date('YmdHis');
  3076. }
  3077. return DB::table('mp_script_episode_group')->insertGetId([
  3078. 'script_id' => $script_id,
  3079. 'group_name' => $group_name,
  3080. 'user_id' => $uid,
  3081. 'remark' => $remark,
  3082. 'created_at' => date('Y-m-d H:i:s'),
  3083. 'updated_at' => date('Y-m-d H:i:s')
  3084. ]);
  3085. }
  3086. public function editEpisode($data) {
  3087. $group_id = getProp($data, 'group_id');
  3088. $start_episode_number = getProp($data, 'start_episode_number');
  3089. $end_episode_number = getProp($data, 'end_episode_number');
  3090. $group_name = getProp($data, 'group_name');
  3091. $uid = Site::getUid(); // 获取当前用户ID
  3092. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  3093. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  3094. if ($id && (int)$id !== (int)$group_id) {
  3095. $group_name .= '_'.date('YmdHis');
  3096. }
  3097. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3098. 'group_name' => $group_name,
  3099. 'start_episode_number' => $start_episode_number,
  3100. 'end_episode_number' => $end_episode_number,
  3101. 'updated_at' => date('Y-m-d H:i:s')
  3102. ]);
  3103. }
  3104. public function delEpisode($data) {
  3105. $group_id = getProp($data, 'group_id');
  3106. $uid = Site::getUid(); // 获取当前用户ID
  3107. if (!$group_id) Utils::throwError('20003:请选择分集');
  3108. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3109. 'is_deleted' => 1,
  3110. 'updated_at' => date('Y-m-d H:i:s')
  3111. ]);
  3112. }
  3113. /**
  3114. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3115. *
  3116. * @param array $data 包含以下参数:
  3117. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3118. * - question: 用户问题(可选)
  3119. * - model: 使用的模型(r1 或 v3,默认 v3)
  3120. * @return \Generator 返回生成器,用于流式输出
  3121. */
  3122. public function generateEpisodes($data) {
  3123. $script_id = getProp($data, 'script_id');
  3124. $group_id = getProp($data, 'group_id');
  3125. // $file = getProp($data, 'file');
  3126. $file = '';
  3127. $content = getProp($data, 'content', '');
  3128. // $bid = getProp($data, 'bid', 0);
  3129. $bid = 0;
  3130. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3131. if (!$group) {
  3132. Utils::throwError('20003:剧本分集不存在');
  3133. }
  3134. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  3135. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  3136. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  3137. $prompt = getProp($data, 'prompt');
  3138. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  3139. $model = getProp($data, 'model');
  3140. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3141. Utils::throwError('20003:该模型不存在!');
  3142. }
  3143. // 检查是否存在重叠的剧集序号范围
  3144. $exists_groups = DB::table('mp_script_episode_group')
  3145. ->where('script_id', $script_id)
  3146. ->where('id', '<>', $group_id) // 排除当前组
  3147. ->where('is_deleted', 0)
  3148. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3149. // 检查新范围是否与现有范围重叠
  3150. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3151. // 新范围的开始在现有范围内
  3152. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3153. ->where('end_episode_number', '>=', $start_episode_sequence);
  3154. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3155. // 新范围的结束在现有范围内
  3156. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3157. ->where('end_episode_number', '>=', $end_episode_sequence);
  3158. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3159. // 新范围完全包含现有范围
  3160. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3161. ->where('end_episode_number', '<=', $end_episode_sequence);
  3162. });
  3163. })
  3164. ->select('start_episode_number', 'end_episode_number')
  3165. ->get();
  3166. if ($exists_groups->isNotEmpty()) {
  3167. $conflict_ranges = [];
  3168. foreach ($exists_groups as $group) {
  3169. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3170. }
  3171. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3172. }
  3173. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3174. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3175. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3176. if ($model === 'deepseek-chat') {
  3177. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3178. $model = 'deepseek-v4-flash';
  3179. $thinkingMode = 'disabled';
  3180. } elseif ($model === 'deepseek-reasoner') {
  3181. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3182. $model = 'deepseek-v4-flash';
  3183. $thinkingMode = 'enabled';
  3184. }
  3185. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3186. if (!$script) {
  3187. Utils::throwError('20003:剧本不存在');
  3188. }
  3189. $content = getProp($group, 'content');
  3190. if (!$file && !$content && !$bid) {
  3191. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3192. }
  3193. // 提取文件内容
  3194. if ($file) {
  3195. $content = $this->extractFileContent($file);
  3196. if (!$content) {
  3197. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3198. }
  3199. } elseif ($bid) {
  3200. $content = $this->getContentByBid($bid);
  3201. if (!$content) {
  3202. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3203. }
  3204. } elseif ($content) {
  3205. $content = filterContent($content);
  3206. } elseif ($prompt) {
  3207. $content = filterContent($prompt);
  3208. } else {
  3209. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3210. }
  3211. // 构建消息
  3212. $messages = [
  3213. $this->sys_message,
  3214. [
  3215. 'role' => 'user',
  3216. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3217. ]
  3218. ];
  3219. $post_data = [
  3220. 'model' => $model,
  3221. 'messages' => $messages,
  3222. // 'max_tokens' => 8192,
  3223. 'temperature' => 0.7,
  3224. 'frequency_penalty' => 0,
  3225. 'presence_penalty' => 0,
  3226. 'thinking' => ['type' => $thinkingMode],
  3227. 'response_format' => ['type' => 'text'],
  3228. 'stream' => true
  3229. ];
  3230. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3231. // 根据模型类型选择调用方法
  3232. $fullContent = '';
  3233. $fullReasoningContent = '';
  3234. $usage = [];
  3235. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3236. // DeepSeek 官方模型使用 DeepSeek API
  3237. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3238. } else if (in_array($model, $this->gpt_text_models)) {
  3239. // GPT-5.4 模型使用 TokenRouter API
  3240. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3241. } else if (in_array($model, $this->gemini_text_models)) {
  3242. // Gemini 模型使用 Gemini API
  3243. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3244. } else {
  3245. // 其他模型使用火山引擎API
  3246. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3247. }
  3248. // 处理流式输出
  3249. foreach ($streamGenerator as $chunk) {
  3250. if (isset($chunk['type'])) {
  3251. if ($chunk['type'] === 'done') {
  3252. // 最终结果
  3253. $fullContent = $chunk['full_content'];
  3254. $fullReasoningContent = $chunk['full_reasoning'];
  3255. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3256. } else {
  3257. // 逐块yield数据
  3258. yield $chunk;
  3259. }
  3260. }
  3261. }
  3262. dLog('deepseek')->info('完整内容: '.$fullContent);
  3263. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3264. // 处理完整内容并返回最终结果
  3265. $script_arr = [];
  3266. if ($fullContent) {
  3267. $script_arr = extractScriptContent($fullContent);
  3268. }
  3269. logDB('deepseek', 'info', '解析内容', $script_arr);
  3270. if (!$script_arr['episodes']) {
  3271. Utils::throwError('20003:未生成剧本相关信息');
  3272. // yield [
  3273. // 'type' => 'done',
  3274. // 'script' => $script_arr,
  3275. // 'msg' => '未生成剧本相关信息',
  3276. // 'answer' => $fullContent,
  3277. // 'reasoning' => $fullReasoningContent,
  3278. // 'usage' => $usage
  3279. // ];
  3280. // return ;
  3281. }
  3282. try {
  3283. DB::beginTransaction();
  3284. // // 返回前保存剧本内容
  3285. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3286. // 'content' => $content,
  3287. // 'updated_at' => date('Y-m-d H:i:s')
  3288. // ]);
  3289. // if (!$boolen) {
  3290. // Utils::throwError('20003:保存剧本内容失败');
  3291. // }
  3292. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3293. // 'start_episode_number' => $start_episode_sequence,
  3294. // 'end_episode_number' => $end_episode_sequence,
  3295. // 'updated_at' => date('Y-m-d H:i:s')
  3296. // ]);
  3297. // if (!$boolen1) {
  3298. // Utils::throwError('20003:保存分集失败');
  3299. // }
  3300. $episode_content = '';
  3301. $episodes = [];
  3302. foreach ($script_arr['episodes'] as $item) {
  3303. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  3304. // $episodes[] = [
  3305. // 'script_id' => $script_id,
  3306. // 'episode_number' => $item['episode_number'],
  3307. // 'episode_name' => $item['episode_name'],
  3308. // 'episode_content' => $item['episode_content'],
  3309. // 'created_at' => date('Y-m-d H:i:s'),
  3310. // 'updated_at' => date('Y-m-d H:i:s'),
  3311. // ];
  3312. }
  3313. if ($episode_content) {
  3314. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3315. 'episode_content' => $episode_content,
  3316. 'updated_at' => date('Y-m-d H:i:s')
  3317. ]);
  3318. if (!$boolen2) {
  3319. Utils::throwError('20003:保存分集内容失败');
  3320. }
  3321. }else {
  3322. Utils::throwError('20003:分集剧本解析失败');
  3323. }
  3324. }catch (\Exception $e) {
  3325. DB::rollBack();
  3326. Utils::throwError('20003:'.$e->getMessage());
  3327. }
  3328. DB::commit();
  3329. yield [
  3330. 'type' => 'done',
  3331. 'script' => $script_arr,
  3332. 'episode_content' => $episode_content,
  3333. 'answer' => $fullContent,
  3334. 'reasoning' => $fullReasoningContent,
  3335. 'usage' => $usage
  3336. ];
  3337. }
  3338. public function chatWithFileStream($data) {
  3339. $script_id = getProp($data, 'script_id');
  3340. $group_id = getProp($data, 'group_id');
  3341. $file = getProp($data, 'file');
  3342. $content = getProp($data, 'content', '');
  3343. $bid = getProp($data, 'bid', 0);
  3344. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3345. $total_episode_num = getProp($data, 'total_episode_num', 30);
  3346. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  3347. $prompt = getProp($data, 'prompt');
  3348. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  3349. if (!empty($prompt)) {
  3350. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  3351. }
  3352. $question = getProp($data, 'question', $baseQuestion);
  3353. $model = getProp($data, 'model');
  3354. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  3355. Utils::throwError('20003:该模型不存在!');
  3356. }
  3357. // 检查是否存在重叠的剧集序号范围
  3358. $exists_groups = DB::table('mp_script_episode_group')
  3359. ->where('script_id', $script_id)
  3360. ->where('id', '<>', $group_id)
  3361. ->where('is_deleted', 0)
  3362. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3363. // 检查新范围是否与现有范围重叠
  3364. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3365. // 新范围的开始在现有范围内
  3366. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3367. ->where('end_episode_number', '>=', $start_episode_sequence);
  3368. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3369. // 新范围的结束在现有范围内
  3370. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3371. ->where('end_episode_number', '>=', $end_episode_sequence);
  3372. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3373. // 新范围完全包含现有范围
  3374. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3375. ->where('end_episode_number', '<=', $end_episode_sequence);
  3376. });
  3377. })
  3378. ->select('start_episode_number', 'end_episode_number')
  3379. ->get();
  3380. if ($exists_groups->isNotEmpty()) {
  3381. $conflict_ranges = [];
  3382. foreach ($exists_groups as $group) {
  3383. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3384. }
  3385. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3386. }
  3387. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3388. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3389. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3390. if ($model === 'deepseek-chat') {
  3391. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3392. $model = 'deepseek-v4-flash';
  3393. $thinkingMode = 'disabled';
  3394. } elseif ($model === 'deepseek-reasoner') {
  3395. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3396. $model = 'deepseek-v4-flash';
  3397. $thinkingMode = 'enabled';
  3398. }
  3399. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3400. if (!$script) {
  3401. Utils::throwError('20003:剧本不存在');
  3402. }
  3403. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  3404. if (!$group) {
  3405. Utils::throwError('20003:剧本分集不存在');
  3406. }
  3407. if (!$file && !$content && !$bid) {
  3408. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3409. }
  3410. // 提取文件内容
  3411. if ($file) {
  3412. $content = $this->extractFileContent($file);
  3413. if (!$content) {
  3414. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3415. }
  3416. } elseif ($bid) {
  3417. $content = $this->getContentByBid($bid);
  3418. if (!$content) {
  3419. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3420. }
  3421. } elseif ($content) {
  3422. $content = filterContent($content);
  3423. } elseif ($prompt) {
  3424. $content = filterContent($prompt);
  3425. } else {
  3426. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3427. }
  3428. // 构建消息
  3429. $messages = [
  3430. [
  3431. 'role' => 'system',
  3432. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3433. 强制要求:\n
  3434. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3435. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  3436. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  3437. 普通要求:\n
  3438. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  3439. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  3440. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  3441. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  3442. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  3443. 示例如下:\n
  3444. ###剧本名:西昆仑
  3445. ###故事梗概
  3446. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3447. ###剧本亮点
  3448. 亮点1:绝境奇药,生死一线
  3449. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3450. 亮点2:结拜兄妹,化解尴尬
  3451. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3452. 亮点3:纤发夺命,情愫暗涌
  3453. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3454. ###人物关系
  3455. 阿雪与梁萧之间存在兄妹之情。
  3456. ###核心矛盾
  3457. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3458. ###主体列表
  3459. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  3460. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  3461. 阴阳球:天地异宝,能化生精气,救人于危难。
  3462. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  3463. ###美术风格
  3464. 基础画风风格词:厚涂古风
  3465. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3466. ###场景列表
  3467. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  3468. [
  3469. 'role' => 'user',
  3470. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3471. ]
  3472. ];
  3473. $post_data = [
  3474. 'model' => $model,
  3475. 'messages' => $messages,
  3476. // 'max_tokens' => 8192,
  3477. 'temperature' => 0.7,
  3478. 'frequency_penalty' => 0,
  3479. 'presence_penalty' => 0,
  3480. 'thinking' => ['type' => $thinkingMode],
  3481. 'response_format' => ['type' => 'text'],
  3482. 'stream' => true
  3483. ];
  3484. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3485. // 根据模型类型选择调用方法
  3486. $fullContent = '';
  3487. $fullReasoningContent = '';
  3488. $usage = [];
  3489. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3490. // DeepSeek 官方模型使用 DeepSeek API
  3491. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3492. } else if (in_array($model, $this->gpt_text_models)) {
  3493. // GPT-5.4 模型使用 TokenRouter API
  3494. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3495. } else if (in_array($model, $this->gemini_text_models)) {
  3496. // Gemini 模型使用 Gemini API
  3497. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  3498. } else {
  3499. // 其他模型使用火山引擎API
  3500. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3501. }
  3502. // 处理流式输出
  3503. foreach ($streamGenerator as $chunk) {
  3504. if (isset($chunk['type'])) {
  3505. if ($chunk['type'] === 'done') {
  3506. // 最终结果
  3507. $fullContent = $chunk['full_content'];
  3508. $fullReasoningContent = $chunk['full_reasoning'];
  3509. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3510. } else {
  3511. // 逐块yield数据
  3512. yield $chunk;
  3513. }
  3514. }
  3515. }
  3516. dLog('deepseek')->info('完整内容: '.$fullContent);
  3517. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  3518. // 处理完整内容并返回最终结果
  3519. $script_arr = [];
  3520. if ($fullContent) {
  3521. $script_arr = extractScriptContent($fullContent);
  3522. }
  3523. logDB('deepseek', 'info', '解析内容', $script_arr);
  3524. if (!$script_arr['roles']) {
  3525. Utils::throwError('20003:未生成剧本相关信息');
  3526. // yield [
  3527. // 'type' => 'done',
  3528. // 'script' => $script_arr,
  3529. // 'msg' => '未生成剧本相关信息',
  3530. // 'answer' => $fullContent,
  3531. // 'reasoning' => $fullReasoningContent,
  3532. // 'usage' => $usage
  3533. // ];
  3534. }
  3535. try {
  3536. DB::beginTransaction();
  3537. // // 返回前保存剧本内容
  3538. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  3539. // 'content' => $content,
  3540. // 'status' => '解析完成',
  3541. // 'updated_at' => date('Y-m-d H:i:s')
  3542. // ]);
  3543. // if (!$boolen) {
  3544. // Utils::throwError('20003:保存剧本内容失败');
  3545. // }
  3546. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  3547. 'start_episode_number' => $start_episode_sequence,
  3548. 'end_episode_number' => $end_episode_sequence,
  3549. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3550. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3551. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3552. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3553. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3554. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3555. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3556. 'status' => '解析完成',
  3557. 'content' => $content,
  3558. 'updated_at' => date('Y-m-d H:i:s')
  3559. ]);
  3560. if (!$boolen1) {
  3561. Utils::throwError('20003:保存分集失败');
  3562. }
  3563. // $episodes = [];
  3564. // foreach ($script_arr['episodes'] as $item) {
  3565. // $episodes[] = [
  3566. // 'script_id' => $script_id,
  3567. // 'episode_number' => $item['episode_number'],
  3568. // 'episode_name' => $item['episode_name'],
  3569. // 'episode_content' => $item['episode_content'],
  3570. // 'created_at' => date('Y-m-d H:i:s'),
  3571. // 'updated_at' => date('Y-m-d H:i:s'),
  3572. // ];
  3573. // }
  3574. // if ($episodes) {
  3575. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  3576. // if (!$boolen2) {
  3577. // Utils::throwError('20003:保存分集内容失败');
  3578. // }
  3579. // }else {
  3580. // Utils::throwError('20003:分集剧本解析失败');
  3581. // }
  3582. }catch (\Exception $e) {
  3583. DB::rollBack();
  3584. Utils::throwError('20003:'.$e->getMessage());
  3585. }
  3586. DB::commit();
  3587. yield [
  3588. 'type' => 'done',
  3589. 'script' => $script_arr,
  3590. 'answer' => $fullContent,
  3591. 'reasoning' => $fullReasoningContent,
  3592. 'usage' => $usage
  3593. ];
  3594. }
  3595. /**
  3596. * 上传文件识别文字内容并与 DeepSeek 进行对话
  3597. *
  3598. * @param array $data 包含以下参数:
  3599. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3600. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  3601. * - model: 使用的模型(r1 或 v3,默认 v3)
  3602. * @return array
  3603. */
  3604. public function chatWithFile($data) {
  3605. $script_id = getProp($data, 'script_id');
  3606. $file = getProp($data, 'file');
  3607. $content = getProp($data, 'content', '');
  3608. $bid = getProp($data, 'bid', 0);
  3609. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3610. $total_episode_num = getProp($data, 'total_episode_num', 30);
  3611. $prompt = getProp($data, 'prompt');
  3612. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  3613. if (!empty($prompt)) {
  3614. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  3615. }
  3616. $question = getProp($data, 'question', $baseQuestion);
  3617. // 处理文本模型
  3618. $model = getProp($data, 'model');
  3619. if (!$model) {
  3620. // 用户没有输入,使用默认值
  3621. $model = 'doubao-seed-2-0-mini-260215';
  3622. }
  3623. // 验证模型是否在可用模型表中
  3624. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3625. $model = 'doubao-seed-2-0-mini-260215';
  3626. }
  3627. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3628. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3629. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3630. if ($model === 'deepseek-chat') {
  3631. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3632. $model = 'deepseek-v4-flash';
  3633. $thinkingMode = 'disabled';
  3634. } elseif ($model === 'deepseek-reasoner') {
  3635. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3636. $model = 'deepseek-v4-flash';
  3637. $thinkingMode = 'enabled';
  3638. }
  3639. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  3640. if (!$script) {
  3641. Utils::throwError('20003:剧本不存在');
  3642. }
  3643. if (!$file && !$content && !$bid) {
  3644. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3645. }
  3646. // 提取文件内容
  3647. if ($file) {
  3648. $content = $this->extractFileContent($file);
  3649. if (!$content) {
  3650. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3651. }
  3652. } elseif ($bid) {
  3653. $content = $this->getContentByBid($bid);
  3654. if (!$content) {
  3655. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3656. }
  3657. } elseif ($content) {
  3658. $content = filterContent($content);
  3659. } elseif ($prompt) {
  3660. $content = filterContent($prompt);
  3661. } else {
  3662. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3663. }
  3664. // 构建消息
  3665. $messages = [
  3666. $this->sys_message,
  3667. [
  3668. 'role' => 'user',
  3669. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  3670. ]
  3671. ];
  3672. $post_data = [
  3673. 'model' => $model,
  3674. 'messages' => $messages,
  3675. // 'max_tokens' => 8192,
  3676. 'temperature' => 0.7,
  3677. 'frequency_penalty' => 0,
  3678. 'presence_penalty' => 0,
  3679. 'thinking' => ['type' => $thinkingMode],
  3680. 'response_format' => ['type' => 'text'],
  3681. 'stream' => false
  3682. ];
  3683. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3684. // 根据模型类型选择调用方法
  3685. $fullContent = '';
  3686. $usage = [];
  3687. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3688. // DeepSeek 官方模型使用 DeepSeek API
  3689. $chatResult = $this->chatOnly($post_data);
  3690. } else if (in_array($model, $this->gpt_text_models)) {
  3691. // GPT-5.4 模型使用 TokenRouter API
  3692. $chatResult = $this->gpt54ChatOnly($post_data);
  3693. } else {
  3694. // 其他模型使用火山引擎API
  3695. $chatResult = $this->volcEngineChatCompletion($post_data);
  3696. }
  3697. if (is_array($chatResult)) {
  3698. $fullContent = $chatResult['fullContent'];
  3699. $usage = $chatResult['usage'];
  3700. }
  3701. $script_arr = [];
  3702. // 处理结果
  3703. if ($fullContent) {
  3704. $script_arr = extractScriptContent($fullContent);
  3705. }
  3706. // 返回前保存剧本内容
  3707. DB::table('mp_scripts')->where('id', $script_id)->update([
  3708. 'content' => $content,
  3709. 'updated_at' => date('Y-m-d H:i:s')
  3710. ]);
  3711. return [
  3712. 'script' => $script_arr,
  3713. 'answer' => $fullContent,
  3714. 'usage' => $usage
  3715. ];
  3716. }
  3717. public function getEpisodeContent($data) {
  3718. $group_id = getProp($data, 'group_id');
  3719. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  3720. }
  3721. public function saveEpisodeContent($data) {
  3722. $script_id = getProp($data, 'script_id');
  3723. $group_id = getProp($data, 'group_id');
  3724. $start_episode_sequence = getProp($data, 'start_episode_number');
  3725. $end_episode_sequence = getProp($data, 'end_episode_number');
  3726. // 检查是否存在重叠的剧集序号范围
  3727. $exists_groups = DB::table('mp_script_episode_group')
  3728. ->where('script_id', $script_id)
  3729. ->where('id', '<>', $group_id) // 排除当前组
  3730. ->where('is_deleted', 0)
  3731. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  3732. // 检查新范围是否与现有范围重叠
  3733. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3734. // 新范围的开始在现有范围内
  3735. $q->where('start_episode_number', '<=', $start_episode_sequence)
  3736. ->where('end_episode_number', '>=', $start_episode_sequence);
  3737. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3738. // 新范围的结束在现有范围内
  3739. $q->where('start_episode_number', '<=', $end_episode_sequence)
  3740. ->where('end_episode_number', '>=', $end_episode_sequence);
  3741. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  3742. // 新范围完全包含现有范围
  3743. $q->where('start_episode_number', '>=', $start_episode_sequence)
  3744. ->where('end_episode_number', '<=', $end_episode_sequence);
  3745. });
  3746. })
  3747. ->select('start_episode_number', 'end_episode_number')
  3748. ->get();
  3749. if ($exists_groups->isNotEmpty()) {
  3750. $conflict_ranges = [];
  3751. foreach ($exists_groups as $group) {
  3752. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  3753. }
  3754. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  3755. }
  3756. $episode_content = getProp($data, 'episode_content');
  3757. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  3758. 'content' => $episode_content,
  3759. 'start_episode_number' => $start_episode_sequence,
  3760. 'end_episode_number' => $end_episode_sequence,
  3761. 'updated_at' => date('Y-m-d H:i:s')
  3762. ]);
  3763. $script_arr =getProp($data, 'script', []);
  3764. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  3765. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  3766. $script_id = getProp($data, 'script_id');
  3767. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  3768. try {
  3769. DB::beginTransaction();
  3770. $update_data = [
  3771. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3772. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3773. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3774. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3775. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3776. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3777. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3778. 'status' => 3,
  3779. 'start_episode_sequence' => $start_episode_sequence,
  3780. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  3781. 'episode_num' => count($script_arr['episodes']),
  3782. 'updated_at' => date('Y-m-d H:i:s')
  3783. ];
  3784. // 保存剧本内容
  3785. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  3786. if (!$boolen) {
  3787. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  3788. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  3789. Utils::throwError('20003:剧本内容保存失败');
  3790. }
  3791. // 保存分集内容
  3792. // 删除历史分集内容
  3793. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  3794. $episodes = [];
  3795. $sequence = 1;
  3796. foreach ($script_arr['episodes'] as $episode) {
  3797. $segment_number = 1;
  3798. foreach($episode['segments'] as $segment) {
  3799. $episodes[] = [
  3800. 'script_id' => $script_id,
  3801. 'episode_number' => $episode['episode_number'],
  3802. 'title' => $episode['title'],
  3803. // 'content' => $episode['content'],
  3804. 'content' => '',
  3805. 'segment_number' => $segment_number,
  3806. 'segment_content' => $segment['segment_content'],
  3807. 'sequence' => $sequence,
  3808. 'created_at' => date('Y-m-d H:i:s'),
  3809. 'updated_at' => date('Y-m-d H:i:s')
  3810. ];
  3811. $sequence++;
  3812. $segment_number++;
  3813. }
  3814. }
  3815. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  3816. if (!$boolen2) {
  3817. dLog('deepseek')->info('分集内容保存失败', $episodes);
  3818. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  3819. Utils::throwError('20003:分集内容保存失败');
  3820. }
  3821. } catch (\Exception $e) {
  3822. DB::rollBack();
  3823. Utils::throwError('20003:'.$e->getMessage());
  3824. }
  3825. DB::commit();
  3826. return true;
  3827. }
  3828. public function getBookContent($data) {
  3829. $bid = getProp($data, 'bid');
  3830. $start_sequence = getProp($data, 'start_sequence');
  3831. $end_sequence = getProp($data, 'end_sequence');
  3832. $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])
  3833. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  3834. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  3835. return $return_content;
  3836. }
  3837. public function exportScript($data) {
  3838. $filename = getProp($data, 'filename');
  3839. $script_id = getProp($data, 'script_id');
  3840. $group_id = getProp($data, 'group_id');
  3841. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  3842. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  3843. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3844. $script = (array)$script;
  3845. // 获取分集组信息
  3846. if ($group_id) {
  3847. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  3848. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  3849. ->get()->map(function($value) {
  3850. return (array)$value;
  3851. })->toArray();
  3852. }else {
  3853. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  3854. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  3855. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  3856. return (array)$value;
  3857. })->toArray();
  3858. }
  3859. if (!$groups) Utils::throwError('20003:分集不存在');
  3860. $script['group'] = $groups;
  3861. $export_type = getProp($data, 'export_type', 'txt');
  3862. // 生成文件名
  3863. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  3864. // 根据导出类型生成不同格式的文件
  3865. switch ($export_type) {
  3866. case 'txt':
  3867. return $this->exportScriptAsTxt($script, $filename);
  3868. case 'pdf':
  3869. return $this->exportScriptAsPdf($script, $filename);
  3870. default:
  3871. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  3872. }
  3873. }
  3874. /**
  3875. * 导出剧本为TXT格式
  3876. */
  3877. private function exportScriptAsTxt($script, $filename) {
  3878. // 构建TXT内容
  3879. $content = $this->buildScriptContent($script);
  3880. // 设置响应头,直接下载
  3881. header('Content-Type: text/plain; charset=utf-8');
  3882. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  3883. header('Content-Length: ' . strlen($content));
  3884. // 输出内容并结束
  3885. echo $content;
  3886. exit();
  3887. }
  3888. /**
  3889. * 导出剧本为PDF格式
  3890. */
  3891. private function exportScriptAsPdf($script, $filename) {
  3892. // 使用HTML转PDF的方式来更好地支持中文
  3893. $htmlContent = $this->buildScriptHtmlForPdf($script);
  3894. // 创建PDF实例
  3895. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  3896. // 设置文档信息
  3897. $pdf->SetCreator('剧本导出系统');
  3898. $pdf->SetAuthor('系统');
  3899. $pdf->SetTitle($script['script_name']);
  3900. $pdf->SetSubject('剧本导出');
  3901. // 设置边距
  3902. $pdf->SetMargins(15, 15, 15);
  3903. $pdf->SetAutoPageBreak(TRUE, 15);
  3904. // 添加页面
  3905. $pdf->AddPage();
  3906. // 注册并使用 simsun.ttf 字体
  3907. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  3908. // 使用HTML内容生成PDF
  3909. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  3910. // 直接输出PDF文件供下载
  3911. header('Content-Type: application/pdf');
  3912. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  3913. // 直接输出PDF内容
  3914. $pdf->Output($filename . '.pdf', 'D');
  3915. exit();
  3916. }
  3917. /**
  3918. * 构建用于PDF的HTML内容
  3919. */
  3920. private function buildScriptHtmlForPdf($script) {
  3921. $html = '<style>
  3922. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  3923. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  3924. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  3925. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  3926. .info { margin-bottom: 8px; }
  3927. .group { margin-bottom: 30px; page-break-inside: avoid; }
  3928. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  3929. .segment { margin-bottom: 10px; margin-left: 20px; }
  3930. .episode-content { white-space: pre-wrap; }
  3931. </style>';
  3932. // 标题
  3933. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  3934. // 处理分组数据
  3935. if (!empty($script['group']) && is_array($script['group'])) {
  3936. $groups = (array)$script['group'];
  3937. foreach ($groups as $group) {
  3938. $html .= '<div class="group">';
  3939. // 分组标题
  3940. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  3941. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  3942. // 故事梗概
  3943. if (!empty($group['intro'])) {
  3944. $html .= '<h3>故事梗概</h3>';
  3945. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  3946. }
  3947. // 剧本亮点
  3948. if (!empty($group['highlights'])) {
  3949. $html .= '<h3>剧本亮点</h3>';
  3950. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  3951. }
  3952. // 人物关系
  3953. if (!empty($group['role_relationship'])) {
  3954. $html .= '<h3>人物关系</h3>';
  3955. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  3956. }
  3957. // 核心矛盾
  3958. if (!empty($group['core_contradiction'])) {
  3959. $html .= '<h3>核心矛盾</h3>';
  3960. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  3961. }
  3962. // 主体列表
  3963. if (!empty($group['roles']) && is_array($group['roles'])) {
  3964. $html .= '<h3>主体列表</h3>';
  3965. $html .= '<ul>';
  3966. foreach ($group['roles'] as $role) {
  3967. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  3968. }
  3969. $html .= '</ul>';
  3970. }
  3971. // 美术风格
  3972. if (!empty($group['art_style'])) {
  3973. $html .= '<h3>美术风格</h3>';
  3974. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  3975. }
  3976. // 场景列表
  3977. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3978. $html .= '<h3>场景列表</h3>';
  3979. $html .= '<ul>';
  3980. foreach ($group['scenes'] as $scene) {
  3981. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  3982. }
  3983. $html .= '</ul>';
  3984. }
  3985. // 分集剧本
  3986. if (!empty($group['episode_content'])) {
  3987. $html .= '<h3>分集剧本</h3>';
  3988. // 去除零宽字符和其他不可见字符
  3989. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  3990. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  3991. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  3992. }
  3993. $html .= '</div>';
  3994. }
  3995. }
  3996. return $html;
  3997. }
  3998. /**
  3999. * 构建PDF内容
  4000. */
  4001. private function buildPdfContent($pdf, $script) {
  4002. // 标题
  4003. $pdf->SetFont('dejavusans', 'B', 18);
  4004. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  4005. $pdf->Ln(5);
  4006. // 基本信息
  4007. $pdf->SetFont('dejavusans', '', 12);
  4008. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  4009. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  4010. $pdf->Ln(5);
  4011. // 剧本简介
  4012. if (!empty($script['intro'])) {
  4013. $pdf->SetFont('dejavusans', 'B', 14);
  4014. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  4015. $pdf->SetFont('dejavusans', '', 12);
  4016. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  4017. $pdf->Ln(3);
  4018. }
  4019. // 亮点
  4020. if (!empty($script['highlights'])) {
  4021. $pdf->SetFont('dejavusans', 'B', 14);
  4022. $pdf->Cell(0, 10, '亮点', 0, 1);
  4023. $pdf->SetFont('dejavusans', '', 12);
  4024. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  4025. $pdf->Ln(3);
  4026. }
  4027. // 核心矛盾
  4028. if (!empty($script['core_contradiction'])) {
  4029. $pdf->SetFont('dejavusans', 'B', 14);
  4030. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  4031. $pdf->SetFont('dejavusans', '', 12);
  4032. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  4033. $pdf->Ln(3);
  4034. }
  4035. // 艺术风格
  4036. if (!empty($script['art_style'])) {
  4037. $pdf->SetFont('dejavusans', 'B', 14);
  4038. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  4039. $pdf->SetFont('dejavusans', '', 12);
  4040. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  4041. $pdf->Ln(3);
  4042. }
  4043. // 备注
  4044. if (!empty($script['remark'])) {
  4045. $pdf->SetFont('dejavusans', 'B', 14);
  4046. $pdf->Cell(0, 10, '备注', 0, 1);
  4047. $pdf->SetFont('dejavusans', '', 12);
  4048. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  4049. $pdf->Ln(3);
  4050. }
  4051. // 角色列表
  4052. if (!empty($script['roles']) && is_array($script['roles'])) {
  4053. $pdf->SetFont('dejavusans', 'B', 14);
  4054. $pdf->Cell(0, 10, '角色列表', 0, 1);
  4055. $pdf->SetFont('dejavusans', '', 12);
  4056. foreach ($script['roles'] as $index => $role) {
  4057. if (is_array($role) || is_object($role)) {
  4058. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  4059. } else {
  4060. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  4061. }
  4062. }
  4063. $pdf->Ln(3);
  4064. }
  4065. // 角色关系
  4066. if (!empty($script['role_relationship'])) {
  4067. $pdf->SetFont('dejavusans', 'B', 14);
  4068. $pdf->Cell(0, 10, '角色关系', 0, 1);
  4069. $pdf->SetFont('dejavusans', '', 12);
  4070. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  4071. $pdf->Ln(3);
  4072. }
  4073. // 场景列表
  4074. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  4075. $pdf->SetFont('dejavusans', 'B', 14);
  4076. $pdf->Cell(0, 10, '场景列表', 0, 1);
  4077. $pdf->SetFont('dejavusans', '', 12);
  4078. foreach ($script['scenes'] as $index => $scene) {
  4079. if (is_array($scene) || is_object($scene)) {
  4080. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  4081. } else {
  4082. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  4083. }
  4084. }
  4085. $pdf->Ln(5);
  4086. }
  4087. // 分集内容
  4088. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  4089. $pdf->SetFont('dejavusans', 'B', 16);
  4090. $pdf->Cell(0, 12, '分集内容', 0, 1);
  4091. $pdf->Ln(3);
  4092. foreach ($script['episodes'] as $episode) {
  4093. // 检查是否需要新页面
  4094. if ($pdf->GetY() > 250) {
  4095. $pdf->AddPage();
  4096. }
  4097. $pdf->SetFont('dejavusans', 'B', 14);
  4098. $episodeTitle = '第' . $episode['episode_number'] . '集';
  4099. if (!empty($episode['title'])) {
  4100. $episodeTitle .= ':' . $episode['title'];
  4101. }
  4102. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  4103. // 处理分段内容
  4104. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  4105. $pdf->SetFont('dejavusans', '', 12);
  4106. foreach ($episode['segments'] as $segment) {
  4107. if (!empty($segment['segment_content'])) {
  4108. // 如果有分段编号,显示分段标题
  4109. if (!empty($segment['segment_number'])) {
  4110. $pdf->SetFont('dejavusans', 'B', 12);
  4111. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  4112. $pdf->SetFont('dejavusans', '', 12);
  4113. }
  4114. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  4115. $pdf->Ln(2);
  4116. }
  4117. }
  4118. }
  4119. $pdf->Ln(5);
  4120. }
  4121. }
  4122. }
  4123. /**
  4124. * 构建剧本文本内容
  4125. */
  4126. private function buildScriptContent($script) {
  4127. $content = '';
  4128. $groups = $script['group'];
  4129. $groups = (array)$groups;
  4130. foreach ($groups as $group) {
  4131. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  4132. // 剧本基本信息
  4133. if (!empty($group['intro'])) {
  4134. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  4135. }
  4136. if (!empty($group['highlights'])) {
  4137. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  4138. }
  4139. if (!empty($group['role_relationship'])) {
  4140. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  4141. }
  4142. if (!empty($group['core_contradiction'])) {
  4143. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  4144. }
  4145. if (!empty($group['roles']) && is_array($group['roles'])) {
  4146. $content .= "###主体列表\n";
  4147. foreach ($group['roles'] as $role) {
  4148. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  4149. }
  4150. $content .= "\n\n";
  4151. }
  4152. if (!empty($group['art_style'])) {
  4153. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  4154. }
  4155. // 场景信息
  4156. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  4157. $content .= "###场景列表\n";
  4158. foreach ($group['scenes'] as $scene) {
  4159. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  4160. }
  4161. $content .= "\n\n";
  4162. }
  4163. // 分集内容
  4164. if (!empty($group['episode_content'])) {
  4165. $content .= "###分集剧本\n";
  4166. $content .= $group['episode_content'];
  4167. // foreach ($script['episodes'] as $episode) {
  4168. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  4169. // // if (!empty($episode['episode_name'])) {
  4170. // // $content .= ":" . $episode['episode_name'];
  4171. // // }
  4172. // // $content .= "\n";
  4173. // $content .= $episode['episode_content'] . "\n\n";
  4174. // }
  4175. }
  4176. }
  4177. return $content;
  4178. }
  4179. /**
  4180. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  4181. *
  4182. * @param array $data 包含以下参数:
  4183. * - file: 上传的文件(UploadedFile 对象)或文件路径
  4184. * - question: 用户问题(可选)
  4185. * - model: 使用的模型(r1 或 v3,默认 v3)
  4186. * @return \Generator 返回生成器,用于流式输出
  4187. */
  4188. public function addChat($data) {
  4189. $uid = Site::getUid();
  4190. $anime_id = getProp($data, 'anime_id');
  4191. if (!$anime_id) Utils::throwError('20003:请选择对话');
  4192. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4193. if (!$anime) Utils::throwError('20003:对话不存在');
  4194. $file = getProp($data, 'file');
  4195. $content = getProp($data, 'content', '');
  4196. $bid = getProp($data, 'bid', 0);
  4197. $script_id = getProp($data, 'script_id', 0);
  4198. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  4199. $prompt = getProp($data, 'prompt');
  4200. $user_anime_name = getProp($anime, 'anime_name');
  4201. // 处理文本模型
  4202. $model = getProp($data, 'model');
  4203. if (!$model) {
  4204. // 用户没有输入,从anime表获取
  4205. $model = getProp($anime, 'model');
  4206. if (!$model) {
  4207. // anime表也没有,使用默认值
  4208. $model = 'doubao-seed-2-0-mini-260215';
  4209. }
  4210. }
  4211. // 验证模型是否在可用模型表中
  4212. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4213. $model = 'doubao-seed-2-0-mini-260215';
  4214. }
  4215. $is_multi = getProp($anime, 'is_multi');
  4216. $is_single = (int)$is_multi !== 1;
  4217. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4218. if ($prompt) {
  4219. $question .= "本次修改要求如下:\n{$prompt}";
  4220. }
  4221. // if (!$file && !$content && !$bid) {
  4222. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  4223. // }
  4224. // 提取文件内容
  4225. if ($file) {
  4226. $content = $this->extractFileContent($file);
  4227. if (!$content) {
  4228. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4229. }
  4230. } elseif ($script_id) {
  4231. $content = $this->getContentByScriptId($script_id);
  4232. if (!$content) {
  4233. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4234. }
  4235. } elseif ($bid) {
  4236. $content = $this->getContentByBid($bid);
  4237. if (!$content) {
  4238. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4239. }
  4240. } elseif ($content) {
  4241. $content = filterContent($content);
  4242. } else {
  4243. $content = getProp($anime, 'content');
  4244. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4245. $need_generate_content = true;
  4246. }
  4247. }
  4248. // 美术风格
  4249. $input_art_style = getProp($data, 'art_style');
  4250. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4251. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4252. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4253. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4254. 中年女:邻居阿姨
  4255. 老年男:幽默大爷
  4256. 老年女:婆婆
  4257. 萌娃:奶气萌娃";
  4258. // 判断是否需要生成原文内容
  4259. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4260. // 如果需要生成原文内容,添加额外的要求
  4261. $content_generation_requirement = $need_generate_content
  4262. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4263. : "";
  4264. // 美术风格
  4265. if (!$mappedArtStyle) {
  4266. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4267. }else {
  4268. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4269. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4270. }else {
  4271. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4272. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4273. }
  4274. }
  4275. $systemPrompt = $is_single
  4276. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4277. 强制要求:
  4278. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4279. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4280. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4281. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4282. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4283. 普通要求:
  4284. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4285. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4286. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  4287. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4288. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4289. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4290. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4291. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4292. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4293. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4294. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4295. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4296. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4297. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4298. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4299. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4300. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4301. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4302. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4303. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4304. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4305. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4306. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4307. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4308. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4309. 5.{$mappedArtStyle_prompt}\n\n
  4310. 示例如下:\n
  4311. ###剧本名:西昆仑
  4312. ###故事梗概
  4313. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4314. ###剧本亮点
  4315. 亮点1:绝境奇药,生死一线
  4316. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4317. 亮点2:结拜兄妹,化解尴尬
  4318. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4319. 亮点3:纤发夺命,情愫暗涌
  4320. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4321. ###人物关系
  4322. 阿雪与梁萧之间存在兄妹之情。
  4323. ###核心矛盾
  4324. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4325. ###主体列表
  4326. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4327. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4328. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4329. 姿态:站立。}{{甜心小美}}
  4330. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4331. 全景,正面拍摄,青年女性,亚洲人。
  4332. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4333. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4334. 姿态:站立。}{{阳光青年}}
  4335. ###美术风格
  4336. 基础画风风格词:厚涂古风
  4337. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4338. ###场景列表
  4339. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4340. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4341. 无人物。}
  4342. ###分镜剧本
  4343. ##第1幕:徐家老旧厨房 白天 室内
  4344. 分镜1
  4345. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4346. 场景:徐家老旧厨房
  4347. 构图设计:全景,低角度仰视
  4348. 运镜调度:手持拍摄
  4349. 配音角色:旁白
  4350. 出镜角色:许芸-校服装、徐母
  4351. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4352. 画面类型:普通画面
  4353. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4354. 分镜2
  4355. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4356. 场景:徐家老旧厨房
  4357. 构图设计:近景,徐母面部特写
  4358. 运镜调度:固定镜头
  4359. 配音角色:徐母
  4360. 出镜角色:徐母
  4361. 台词内容:问我夜不归宿死哪儿去了。
  4362. 画面类型:对口型
  4363. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4364. ##第2幕:徐家简陋客厅 黄昏 室内
  4365. 分镜3
  4366. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4367. 场景:徐家简陋客厅
  4368. 构图设计:全景,景深虚化
  4369. 运镜调度:固定镜头
  4370. 配音角色:旁白
  4371. 出镜角色:无
  4372. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4373. 画面类型:普通画面
  4374. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4375. 分镜4
  4376. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4377. 场景:徐家简陋客厅
  4378. 构图设计:特写,火车票
  4379. 运镜调度:固定镜头
  4380. 配音角色:旁白
  4381. 出镜角色:无
  4382. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4383. 画面类型:普通画面
  4384. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4385. "
  4386. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4387. 强制要求:\n
  4388. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4389. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4390. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4391. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4392. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4393. 普通要求:\n
  4394. 1.剧本名(必须生成)必须与文档内容高度相关
  4395. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4396. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4397. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4398. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4399. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4400. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4401. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4402. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4403. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4404. 4.{$mappedArtStyle_prompt}\n\n
  4405. 示例如下:\n
  4406. ###剧本名:西昆仑
  4407. ###故事梗概
  4408. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4409. ###剧本亮点
  4410. 亮点1:绝境奇药,生死一线
  4411. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4412. 亮点2:结拜兄妹,化解尴尬
  4413. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4414. 亮点3:纤发夺命,情愫暗涌
  4415. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4416. ###人物关系
  4417. 阿雪与梁萧之间存在兄妹之情。
  4418. ###核心矛盾
  4419. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4420. ###主体列表
  4421. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4422. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4423. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4424. 姿态:站立。}{{甜心小美}}
  4425. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4426. 全景,正面拍摄,青年女性,亚洲人。
  4427. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4428. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4429. 姿态:站立。}{{阳光青年}}
  4430. ###美术风格
  4431. 基础画风风格词:厚涂古风
  4432. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4433. ###场景列表
  4434. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4435. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4436. 无人物。}";
  4437. // 构建消息
  4438. $messages = [
  4439. [
  4440. 'role' => 'system',
  4441. 'content' => $systemPrompt
  4442. ],
  4443. [
  4444. 'role' => 'user',
  4445. 'content' => "以下是文档内容:
  4446. {$content}
  4447. 用户问题:
  4448. {$question}"
  4449. ]
  4450. ];
  4451. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4452. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4453. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4454. if ($model === 'deepseek-chat') {
  4455. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4456. $model = 'deepseek-v4-flash';
  4457. $thinkingMode = 'disabled';
  4458. } elseif ($model === 'deepseek-reasoner') {
  4459. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4460. $model = 'deepseek-v4-flash';
  4461. $thinkingMode = 'enabled';
  4462. }
  4463. $post_data = [
  4464. 'model' => $model,
  4465. 'messages' => $messages,
  4466. // 'max_tokens' => 8192,
  4467. 'temperature' => 0.7,
  4468. 'frequency_penalty' => 0,
  4469. 'presence_penalty' => 0,
  4470. 'response_format' => ['type' => 'text'],
  4471. 'thinking' => ['type'=>$thinkingMode],
  4472. 'stream' => true // 启用流式输出
  4473. ];
  4474. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4475. // 根据模型类型选择调用方法
  4476. $fullContent = '';
  4477. $fullReasoningContent = '';
  4478. $usage = [];
  4479. try {
  4480. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4481. // DeepSeek 官方模型使用 DeepSeek API
  4482. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4483. } else if (in_array($model, $this->gpt_text_models)) {
  4484. // GPT-5.4 模型使用 TokenRouter API
  4485. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4486. } else if (in_array($model, $this->gemini_text_models)) {
  4487. // Gemini 模型使用 Gemini API
  4488. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  4489. } else {
  4490. // 其他模型使用火山引擎API
  4491. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4492. }
  4493. // 验证返回值类型
  4494. if (!is_iterable($streamGenerator)) {
  4495. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4496. dLog('deepseek')->error('addChat流式生成器无效', [
  4497. 'generator_type' => $errorType,
  4498. 'model' => $model,
  4499. 'anime_id' => $anime_id
  4500. ]);
  4501. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  4502. 'type' => $errorType,
  4503. 'model' => $model
  4504. ]);
  4505. yield [
  4506. 'type' => 'error',
  4507. 'script' => [],
  4508. 'episode' => [],
  4509. 'answer' => '',
  4510. 'reasoning' => '',
  4511. 'usage' => [],
  4512. 'error' => '接口返回数据异常,请重新请求'
  4513. ];
  4514. return;
  4515. }
  4516. // 处理流式输出
  4517. foreach ($streamGenerator as $chunk) {
  4518. if (isset($chunk['type'])) {
  4519. if ($chunk['type'] === 'done') {
  4520. // 最终结果
  4521. $fullContent = $chunk['full_content'];
  4522. $fullReasoningContent = $chunk['full_reasoning'];
  4523. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4524. } else {
  4525. // 逐块yield数据
  4526. yield $chunk;
  4527. }
  4528. }
  4529. }
  4530. } catch (\Exception $e) {
  4531. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  4532. 'model' => $model,
  4533. 'anime_id' => $anime_id,
  4534. 'trace' => $e->getTraceAsString()
  4535. ]);
  4536. logDB('deepseek', 'error', 'addChat流式处理失败', [
  4537. 'error' => $e->getMessage(),
  4538. 'model' => $model
  4539. ]);
  4540. yield [
  4541. 'type' => 'error',
  4542. 'script' => [],
  4543. 'episode' => [],
  4544. 'answer' => '',
  4545. 'reasoning' => '',
  4546. 'usage' => [],
  4547. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4548. ];
  4549. return;
  4550. }
  4551. dLog('deepseek')->info('完整内容: '.$fullContent);
  4552. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4553. // 处理完整内容并返回最终结果
  4554. $script_arr = [];
  4555. if ($fullContent) {
  4556. $script_arr = handleScriptContent($fullContent);
  4557. dLog('deepseek')->info('解析内容', $script_arr);
  4558. logDB('deepseek', 'info', '解析内容', $script_arr);
  4559. }
  4560. if (empty($script_arr['roles'])) {
  4561. // 未生成剧本相关内容,保存对话记录并返回提示
  4562. dLog('deepseek')->info('未生成剧本相关的内容');
  4563. try {
  4564. DB::beginTransaction();
  4565. $now = date('Y-m-d H:i:s');
  4566. // 保存对话记录
  4567. $records = [
  4568. [
  4569. 'uid' => $uid,
  4570. 'anime_id' => $anime_id,
  4571. 'sequence' => 0,
  4572. 'role' => 'user',
  4573. 'content' => $prompt,
  4574. 'created_at' => $now,
  4575. 'updated_at' => $now
  4576. ],
  4577. [
  4578. 'uid' => $uid,
  4579. 'anime_id' => $anime_id,
  4580. 'sequence' => 0,
  4581. 'role' => 'assistant',
  4582. // 'content' => $fullContent,
  4583. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  4584. 'created_at' => $now,
  4585. 'updated_at' => $now
  4586. ]
  4587. ];
  4588. DB::table('mp_anime_records')->insert($records);
  4589. DB::commit();
  4590. } catch (\Exception $e) {
  4591. DB::rollBack();
  4592. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4593. }
  4594. yield [
  4595. 'type' => 'done',
  4596. 'script' => [],
  4597. 'episode' => [],
  4598. 'answer' => $fullContent,
  4599. 'reasoning' => $fullReasoningContent,
  4600. 'usage' => $usage,
  4601. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4602. ];
  4603. return;
  4604. }
  4605. // 如果需要生成原文内容,从script_arr中提取
  4606. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4607. $content = $script_arr['content'];
  4608. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  4609. if (!$content) {
  4610. yield [
  4611. 'type' => 'done',
  4612. 'script' => [],
  4613. 'episode' => [],
  4614. 'answer' => $fullContent,
  4615. 'reasoning' => $fullReasoningContent,
  4616. 'usage' => $usage,
  4617. 'error' => '未生成剧本内容,请调整提示词再试'
  4618. ];
  4619. return;
  4620. }
  4621. }
  4622. // 替换美术风格
  4623. if ($mappedArtStyle !== '') {
  4624. $script_arr['art_style'] = $mappedArtStyle;
  4625. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4626. }
  4627. // 新建动漫
  4628. if ($user_anime_name == '新剧本策划') {
  4629. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  4630. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  4631. // if (!$anime_name) {
  4632. // // 未识别到剧本名,保存对话记录并返回提示
  4633. // dLog('deepseek')->info('未能识别到剧本名称');
  4634. // try {
  4635. // DB::beginTransaction();
  4636. // $now = date('Y-m-d H:i:s');
  4637. // // 保存对话记录
  4638. // $records = [
  4639. // [
  4640. // 'uid' => $uid,
  4641. // 'anime_id' => $anime_id,
  4642. // 'sequence' => 0,
  4643. // 'role' => 'user',
  4644. // 'content' => $prompt,
  4645. // 'created_at' => $now,
  4646. // 'updated_at' => $now
  4647. // ],
  4648. // [
  4649. // 'uid' => $uid,
  4650. // 'anime_id' => $anime_id,
  4651. // 'sequence' => 0,
  4652. // 'role' => 'assistant',
  4653. // 'content' => '未能生成剧本名称,请重试',
  4654. // 'created_at' => $now,
  4655. // 'updated_at' => $now
  4656. // ]
  4657. // ];
  4658. // DB::table('mp_anime_records')->insert($records);
  4659. // DB::commit();
  4660. // } catch (\Exception $e) {
  4661. // DB::rollBack();
  4662. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4663. // }
  4664. // yield [
  4665. // 'type' => 'done',
  4666. // 'script' => [],
  4667. // 'episode' => [],
  4668. // 'answer' => $fullContent,
  4669. // 'reasoning' => $fullReasoningContent,
  4670. // 'usage' => $usage,
  4671. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  4672. // ];
  4673. // return;
  4674. // }
  4675. // 确认对话名称唯一性
  4676. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4677. $anime_name = $anime_name . '_' . date('YmdHis');
  4678. }
  4679. }else {
  4680. $anime_name = $user_anime_name;
  4681. }
  4682. $table_data = [
  4683. 'user_id' => $uid,
  4684. 'anime_name' => $anime_name,
  4685. 'model' => $model,
  4686. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4687. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4688. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4689. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4690. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4691. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4692. 'art_style_type' => $input_art_style,
  4693. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4694. 'status' => '解析完成',
  4695. 'content' => $content,
  4696. 'is_multi' => $is_multi,
  4697. 'ace_mode' => $ace_mode,
  4698. 'generate_status' => '待执行',
  4699. 'updated_at' => date('Y-m-d H:i:s')
  4700. ];
  4701. if ($table_data['content']) {
  4702. $chapters = splitContent($table_data['content']);
  4703. $chapter_count = count($chapters);
  4704. if ($chapter_count > 0) {
  4705. $table_data['start_episode_sequence'] = 1;
  4706. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4707. }
  4708. }
  4709. // 如果有剧本ID则进行绑定
  4710. if ($script_id) {
  4711. $table_data['script_id'] = $script_id;
  4712. }
  4713. $single_episode = [];
  4714. try {
  4715. DB::beginTransaction();
  4716. $now = date('Y-m-d H:i:s');
  4717. // 更新动漫大纲
  4718. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4719. if (!$boolen) {
  4720. dLog('deepseek')->info('动漫保存失败', $table_data);
  4721. Utils::throwError('20003:动漫保存失败');
  4722. }
  4723. // 保存对话记录
  4724. $records = [
  4725. [
  4726. 'uid' => $uid,
  4727. 'anime_id' => $anime_id,
  4728. 'sequence' => 0,
  4729. 'role' => 'user',
  4730. 'content' => $prompt,
  4731. 'created_at' => date('Y-m-d H:i:s'),
  4732. 'updated_at' => date('Y-m-d H:i:s')
  4733. ],
  4734. [
  4735. 'uid' => $uid,
  4736. 'anime_id' => $anime_id,
  4737. 'sequence' => 0,
  4738. 'role' => 'assistant',
  4739. 'content' => $fullContent,
  4740. 'created_at' => date('Y-m-d H:i:s'),
  4741. 'updated_at' => date('Y-m-d H:i:s')
  4742. ]
  4743. ];
  4744. // 保存对话记录
  4745. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4746. if (!$boolen3) {
  4747. Utils::throwError('20003:对话记录保存失败');
  4748. }
  4749. if ($is_single) {
  4750. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4751. if (empty($episode_arr['acts'])) {
  4752. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4753. }
  4754. $saveResult = $this->saveEpisodeVersionData(
  4755. $anime_id,
  4756. 1,
  4757. $episode_arr,
  4758. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4759. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4760. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  4761. null,
  4762. null,
  4763. false,
  4764. $content,
  4765. $now
  4766. );
  4767. $single_episode = $saveResult['episode'];
  4768. $episode_id = $saveResult['episode_id'];
  4769. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4770. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4771. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4772. 'props' => json_encode($saveResult['merged_props'], 256),
  4773. 'updated_at' => $now
  4774. ]);
  4775. if ($boolen5 === false) {
  4776. Utils::throwError('20003:单剧集主表资源同步失败');
  4777. }
  4778. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4779. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4780. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  4781. $episode_record_content = '确认分镜大纲';
  4782. if ($content !== '') {
  4783. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4784. }
  4785. $episode_records = [
  4786. [
  4787. 'uid' => $uid,
  4788. 'anime_id' => $anime_id,
  4789. 'role' => 'user',
  4790. 'content' => $episode_record_content,
  4791. 'sequence' => 1,
  4792. 'episode_id' => $episode_id,
  4793. 'created_at' => $now,
  4794. 'updated_at' => $now
  4795. ],
  4796. [
  4797. 'uid' => $uid,
  4798. 'anime_id' => $anime_id,
  4799. 'role' => 'assistant',
  4800. 'content' => $fullContent,
  4801. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4802. 'sequence' => 1,
  4803. 'episode_id' => $episode_id,
  4804. 'created_at' => $now,
  4805. 'updated_at' => $now
  4806. ]
  4807. ];
  4808. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4809. if (!$boolen4) {
  4810. Utils::throwError('20003:单剧集分镜记录保存失败');
  4811. }
  4812. }
  4813. }catch (\Exception $e) {
  4814. DB::rollBack();
  4815. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  4816. yield [
  4817. 'type' => 'done',
  4818. 'answer' => $fullContent,
  4819. 'reasoning' => $fullReasoningContent,
  4820. 'usage' => $usage,
  4821. 'error' => $e->getMessage(),
  4822. ];
  4823. return;
  4824. }
  4825. DB::commit();
  4826. dLog('deepseek')->info('保存完毕');
  4827. if ($is_single && !empty($single_episode)) {
  4828. // $this->batchSetGlobalRoleImg([
  4829. // 'anime_id' => $anime_id,
  4830. // ]);
  4831. // $this->batchSetGlobalSceneImg([
  4832. // 'anime_id' => $anime_id,
  4833. // ]);
  4834. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4835. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4836. }
  4837. $table_data['anime_id'] = $anime_id;
  4838. $table_data['roles'] = json_decode($table_data['roles'], true);
  4839. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4840. // $table_data['episodes'] = $script_arr['episodes'];
  4841. unset($table_data['created_at']);
  4842. unset($table_data['updated_at']);
  4843. unset($table_data['status']);
  4844. dLog('deepseek')->info('开始返回');
  4845. yield [
  4846. 'type' => 'done',
  4847. 'script' => $table_data,
  4848. 'episode' => $single_episode,
  4849. 'answer' => $fullContent,
  4850. 'reasoning' => $fullReasoningContent,
  4851. 'usage' => $usage
  4852. ];
  4853. }
  4854. public function reGenerateAnime($data) {
  4855. $uid = Site::getUid();
  4856. $file = getProp($data, 'file');
  4857. $content = getProp($data, 'content', '');
  4858. $bid = getProp($data, 'bid', 0);
  4859. $script_id = getProp($data, 'script_id', 0);
  4860. $anime_id = getProp($data, 'anime_id');
  4861. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4862. if (!$anime) {
  4863. Utils::throwError('20003:该对话不存在');
  4864. }
  4865. $user_anime_name = getProp($anime, 'anime_name');
  4866. $prompt = getProp($data, 'prompt');
  4867. // 处理文本模型
  4868. $model = getProp($data, 'model');
  4869. if (!$model) {
  4870. // 用户没有输入,从anime表获取
  4871. $model = getProp($anime, 'model');
  4872. if (!$model) {
  4873. // anime表也没有,使用默认值
  4874. $model = 'doubao-seed-2-0-mini-260215';
  4875. }
  4876. }
  4877. // 验证模型是否在可用模型表中
  4878. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4879. $model = 'doubao-seed-2-0-mini-260215';
  4880. }
  4881. $is_multi = getProp($anime, 'is_multi', 1);
  4882. $is_single = (int)$is_multi !== 1;
  4883. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  4884. if ($is_single) {
  4885. $episode_exists = DB::table('mp_anime_episodes')
  4886. ->where('anime_id', $anime_id)
  4887. ->where('sequence', 1)
  4888. ->exists();
  4889. if ($episode_exists) {
  4890. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  4891. }
  4892. }
  4893. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4894. if ($prompt) {
  4895. $question .= "本次修改要求如下:\n{$prompt}";
  4896. }
  4897. // 提取文件内容
  4898. if ($file) {
  4899. $content = $this->extractFileContent($file);
  4900. if (!$content) {
  4901. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4902. }
  4903. } elseif ($script_id) {
  4904. $content = $this->getContentByScriptId($script_id);
  4905. if (!$content) {
  4906. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4907. }
  4908. } elseif ($bid) {
  4909. $content = $this->getContentByBid($bid);
  4910. if (!$content) {
  4911. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4912. }
  4913. } elseif ($content) {
  4914. $content = filterContent($content);
  4915. }else {
  4916. $content = filterContent(getProp($anime, 'content'));
  4917. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4918. $need_generate_content = true;
  4919. }
  4920. }
  4921. // 判断是否需要生成原文内容
  4922. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4923. // 如果需要生成原文内容,添加额外的要求
  4924. $content_generation_requirement = $need_generate_content
  4925. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4926. : "";
  4927. // 美术风格
  4928. $input_art_style = getProp($anime, 'art_style');
  4929. if (!$input_art_style) {
  4930. $input_art_style = getProp($data, 'art_style');
  4931. }
  4932. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4933. // 美术风格
  4934. if (!$mappedArtStyle) {
  4935. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4936. }else {
  4937. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4938. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4939. }else {
  4940. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4941. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4942. }
  4943. }
  4944. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4945. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4946. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4947. 中年女:邻居阿姨
  4948. 老年男:幽默大爷
  4949. 老年女:婆婆
  4950. 萌娃:奶气萌娃";
  4951. $system_message = ['role'=>'system', 'content'=>$is_single
  4952. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4953. 强制要求:
  4954. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4955. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4956. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4957. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4958. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4959. 普通要求:
  4960. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4961. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4962. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4963. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4964. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4965. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4966. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4967. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4968. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4969. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4970. 3.$mappedArtStyle_prompt\n\n
  4971. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4972. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4973. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4974. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4975. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4976. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4977. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4978. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4979. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4980. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4981. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4982. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4983. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4984. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4985. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4986. 示例如下:\n
  4987. ###剧本名:西昆仑
  4988. ###故事梗概
  4989. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4990. ###剧本亮点
  4991. 亮点1:绝境奇药,生死一线
  4992. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4993. 亮点2:结拜兄妹,化解尴尬
  4994. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4995. 亮点3:纤发夺命,情愫暗涌
  4996. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4997. ###人物关系
  4998. 阿雪与梁萧之间存在兄妹之情。
  4999. ###核心矛盾
  5000. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5001. ###主体列表
  5002. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5003. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5004. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5005. 姿态:站立。}{{甜心小美}}
  5006. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5007. 全景,正面拍摄,青年女性,亚洲人。
  5008. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5009. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5010. 姿态:站立。}{{阳光青年}}
  5011. ###美术风格
  5012. 基础画风风格词:厚涂古风
  5013. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5014. ###场景列表
  5015. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5016. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5017. 无人物。}
  5018. ###分镜剧本
  5019. ##第1幕:徐家老旧厨房 白天 室内
  5020. 分镜1
  5021. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5022. 场景:徐家老旧厨房
  5023. 构图设计:全景,低角度仰视
  5024. 运镜调度:手持拍摄
  5025. 配音角色:旁白
  5026. 出镜角色:许芸-校服装、徐母
  5027. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5028. 画面类型:普通画面
  5029. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5030. 分镜2
  5031. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5032. 场景:徐家老旧厨房
  5033. 构图设计:近景,徐母面部特写
  5034. 运镜调度:固定镜头
  5035. 配音角色:徐母
  5036. 出镜角色:徐母
  5037. 台词内容:问我夜不归宿死哪儿去了。
  5038. 画面类型:对口型
  5039. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5040. ##第2幕:徐家简陋客厅 黄昏 室内
  5041. 分镜3
  5042. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5043. 场景:徐家简陋客厅
  5044. 构图设计:全景,景深虚化
  5045. 运镜调度:固定镜头
  5046. 配音角色:旁白
  5047. 出镜角色:无
  5048. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5049. 画面类型:普通画面
  5050. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5051. 分镜4
  5052. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5053. 场景:徐家简陋客厅
  5054. 构图设计:特写,火车票
  5055. 运镜调度:固定镜头
  5056. 配音角色:旁白
  5057. 出镜角色:无
  5058. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5059. 画面类型:普通画面
  5060. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  5061. "
  5062. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5063. 强制要求:\n
  5064. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5065. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5066. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5067. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5068. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5069. 普通要求:\n
  5070. 1.剧本名(必须生成)必须与文档内容高度相关
  5071. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5072. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5073. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5074. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5075. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5076. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5077. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5078. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5079. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5080. 4.$mappedArtStyle_prompt\n\n
  5081. 示例如下:\n
  5082. ###剧本名:西昆仑
  5083. ###故事梗概
  5084. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5085. ###剧本亮点
  5086. 亮点1:绝境奇药,生死一线
  5087. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5088. 亮点2:结拜兄妹,化解尴尬
  5089. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5090. 亮点3:纤发夺命,情愫暗涌
  5091. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5092. ###人物关系
  5093. 阿雪与梁萧之间存在兄妹之情。
  5094. ###核心矛盾
  5095. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5096. ###主体列表
  5097. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5098. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5099. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5100. 姿态:站立。}{{甜心小美}}
  5101. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5102. 全景,正面拍摄,青年女性,亚洲人。
  5103. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5104. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5105. 姿态:站立。}{{阳光青年}}
  5106. ###美术风格
  5107. 基础画风风格词:厚涂古风
  5108. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5109. ###场景列表
  5110. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5111. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5112. 无人物。}"];
  5113. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  5114. $episode_count = $this->extractEpisodeNumber($prompt);
  5115. if ((int)getProp($anime, 'is_multi') !== 1) {
  5116. yield [
  5117. 'type' => 'done',
  5118. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  5119. 'reasoning' => '',
  5120. 'usage' => []
  5121. ];
  5122. return;
  5123. }
  5124. if ($episode_count) {
  5125. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  5126. $system_message = [
  5127. 'role' => 'system',
  5128. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5129. 强制要求:\n
  5130. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5131. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5132. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5133. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5134. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5135. 普通要求:\n
  5136. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5137. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5138. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5139. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5140. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  5141. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5142. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5143. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5144. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5145. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  5146. 示例如下:\n
  5147. ###剧本名:西昆仑
  5148. ###故事梗概
  5149. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5150. ###剧本亮点
  5151. 亮点1:绝境奇药,生死一线
  5152. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5153. 亮点2:结拜兄妹,化解尴尬
  5154. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5155. 亮点3:纤发夺命,情愫暗涌
  5156. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5157. ###人物关系
  5158. 阿雪与梁萧之间存在兄妹之情。
  5159. ###核心矛盾
  5160. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5161. ###主体列表
  5162. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5163. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5164. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5165. 姿态:站立。}{{甜心小美}}
  5166. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5167. 全景,正面拍摄,青年女性,亚洲人。
  5168. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5169. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5170. 姿态:站立。}{{阳光青年}}
  5171. ###美术风格
  5172. 基础画风风格词:厚涂古风
  5173. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5174. ###场景列表
  5175. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5176. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5177. 无人物。}
  5178. ###分集详细内容
  5179. ##第1章 重生
  5180. 我重生了。
  5181. 源于一个男人偏执的暗恋。
  5182. ##第2章 相救
  5183. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  5184. 我眼睛扫向站在锅炉后的卞大伟。"
  5185. ];
  5186. // 构建消息
  5187. $messages = [
  5188. $system_message,
  5189. [
  5190. 'role' => 'user',
  5191. 'content' => "以下是文档内容:
  5192. {$content}
  5193. 用户问题:
  5194. {$question}"
  5195. ]
  5196. ];
  5197. }else {
  5198. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  5199. // 构建消息
  5200. $messages = [
  5201. $system_message,
  5202. [
  5203. 'role' => 'user',
  5204. 'content' => "以下是文档内容:
  5205. {$content}
  5206. 用户问题:
  5207. {$question}"
  5208. ]
  5209. ];
  5210. }else {
  5211. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  5212. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  5213. return (array)$value;
  5214. })->toArray();
  5215. array_unshift($messages, $system_message);
  5216. $messages[] = [
  5217. 'role' => 'user',
  5218. 'content' => $prompt
  5219. ];
  5220. }
  5221. }
  5222. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5223. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5224. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5225. if ($model === 'deepseek-chat') {
  5226. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5227. $model = 'deepseek-v4-flash';
  5228. $thinkingMode = 'disabled';
  5229. } elseif ($model === 'deepseek-reasoner') {
  5230. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5231. $model = 'deepseek-v4-flash';
  5232. $thinkingMode = 'enabled';
  5233. }
  5234. $post_data = [
  5235. 'model' => $model,
  5236. 'messages' => $messages,
  5237. // 'max_tokens' => 8192,
  5238. 'temperature' => 0.7,
  5239. 'frequency_penalty' => 0,
  5240. 'presence_penalty' => 0,
  5241. 'response_format' => ['type' => 'text'],
  5242. 'thinking' => ['type' => $thinkingMode],
  5243. 'stream' => true // 启用流式输出
  5244. ];
  5245. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5246. // 根据模型类型选择调用方法
  5247. $fullContent = '';
  5248. $fullReasoningContent = '';
  5249. $usage = [];
  5250. // dd($post_data);
  5251. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  5252. try {
  5253. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5254. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5255. } else if (in_array($model, $this->gpt_text_models)) {
  5256. // GPT-5.4 模型使用 TokenRouter API
  5257. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5258. } else if (in_array($model, $this->gemini_text_models)) {
  5259. // Gemini 模型使用 Gemini API
  5260. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  5261. } else {
  5262. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5263. }
  5264. // 验证返回值类型
  5265. if (!is_iterable($streamGenerator)) {
  5266. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5267. dLog('deepseek')->error('方法名流式生成器无效', [
  5268. 'generator_type' => $errorType,
  5269. 'model' => $model,
  5270. // 添加其他上下文信息
  5271. ]);
  5272. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  5273. 'type' => $errorType,
  5274. 'model' => $model
  5275. ]);
  5276. yield [
  5277. 'type' => 'error',
  5278. // 根据方法返回相应的空数据结构
  5279. 'answer' => '',
  5280. 'reasoning' => '',
  5281. 'usage' => [],
  5282. 'error' => '接口返回数据异常,请重新请求'
  5283. ];
  5284. return;
  5285. }
  5286. // 处理流式输出
  5287. foreach ($streamGenerator as $chunk) {
  5288. if (isset($chunk['type'])) {
  5289. if ($chunk['type'] === 'done') {
  5290. $fullContent = $chunk['full_content'];
  5291. $fullReasoningContent = $chunk['full_reasoning'];
  5292. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5293. } else {
  5294. yield $chunk;
  5295. }
  5296. }
  5297. }
  5298. } catch (\Exception $e) {
  5299. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  5300. 'model' => $model,
  5301. 'trace' => $e->getTraceAsString()
  5302. ]);
  5303. logDB('deepseek', 'error', '方法名流式处理失败', [
  5304. 'error' => $e->getMessage(),
  5305. 'model' => $model
  5306. ]);
  5307. yield [
  5308. 'type' => 'error',
  5309. // 根据方法返回相应的空数据结构
  5310. 'answer' => '',
  5311. 'reasoning' => '',
  5312. 'usage' => [],
  5313. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5314. ];
  5315. return;
  5316. }
  5317. dLog('deepseek')->info('完整内容: '.$fullContent);
  5318. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5319. // 处理完整内容并返回最终结果
  5320. $script_arr = [];
  5321. if ($fullContent) {
  5322. $script_arr = handleScriptContent($fullContent);
  5323. dLog('deepseek')->info('解析内容', $script_arr);
  5324. logDB('deepseek', 'info', '解析内容', $script_arr);
  5325. }
  5326. if (empty($script_arr['roles'])) {
  5327. // 未生成剧本相关内容,保存对话记录并返回提示
  5328. dLog('deepseek')->info('未生成剧本相关的内容');
  5329. try {
  5330. $now = date('Y-m-d H:i:s');
  5331. // 保存对话记录
  5332. $records = [
  5333. [
  5334. 'uid' => $uid,
  5335. 'anime_id' => $anime_id,
  5336. 'sequence' => 0,
  5337. 'role' => 'user',
  5338. 'content' => $prompt,
  5339. 'created_at' => $now,
  5340. 'updated_at' => $now
  5341. ],
  5342. [
  5343. 'uid' => $uid,
  5344. 'anime_id' => $anime_id,
  5345. 'sequence' => 0,
  5346. 'role' => 'assistant',
  5347. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  5348. 'created_at' => $now,
  5349. 'updated_at' => $now
  5350. ]
  5351. ];
  5352. DB::table('mp_anime_records')->insert($records);
  5353. } catch (\Exception $e) {
  5354. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5355. }
  5356. yield [
  5357. 'type' => 'done',
  5358. 'script' => [],
  5359. 'episode' => [],
  5360. 'answer' => $fullContent,
  5361. 'reasoning' => $fullReasoningContent,
  5362. 'usage' => $usage,
  5363. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5364. ];
  5365. return;
  5366. }
  5367. // 替换美术风格
  5368. if ($mappedArtStyle !== '') {
  5369. $script_arr['art_style'] = $mappedArtStyle;
  5370. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5371. }
  5372. if ($user_anime_name != '新剧本策划') {
  5373. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  5374. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  5375. // 确认对话名称唯一性
  5376. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5377. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  5378. }
  5379. }else {
  5380. $anime_name = $user_anime_name;
  5381. }
  5382. $table_data = [
  5383. 'user_id' => $uid,
  5384. 'model' => $model,
  5385. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5386. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5387. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5388. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5389. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5390. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5391. 'art_style_type' => $input_art_style,
  5392. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5393. 'status' => '解析完成',
  5394. 'generate_status' => '待执行',
  5395. 'updated_at' => date('Y-m-d H:i:s')
  5396. ];
  5397. if ($anime_name) $table_data['anime_name'] = $anime_name;
  5398. // 如果是修改集数,则将content内容更新(会改变原文)
  5399. if (isset($episode_count) && $episode_count > 0) {
  5400. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  5401. $table_data['start_episode_sequence'] = 1;
  5402. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  5403. }else {
  5404. // 如果需要生成原文内容,从script_arr中提取
  5405. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5406. $table_data['content'] = $script_arr['content'];
  5407. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  5408. if (!$table_data['content']) {
  5409. yield [
  5410. 'type' => 'done',
  5411. 'script' => [],
  5412. 'episode' => [],
  5413. 'answer' => $fullContent,
  5414. 'reasoning' => $fullReasoningContent,
  5415. 'usage' => $usage,
  5416. 'error' => '未生成剧本内容,请调整提示词再试'
  5417. ];
  5418. return;
  5419. }
  5420. }
  5421. if (isset($table_data['content']) && $table_data['content']) {
  5422. $chapters = splitContent($table_data['content']);
  5423. $chapter_count = count($chapters);
  5424. if ($chapter_count > 0) {
  5425. $table_data['start_episode_sequence'] = 1;
  5426. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5427. }
  5428. }
  5429. }
  5430. $single_episode = [];
  5431. try {
  5432. DB::beginTransaction();
  5433. $now = date('Y-m-d H:i:s');
  5434. // 更新动漫大纲
  5435. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5436. if (!$boolen) {
  5437. dLog('deepseek')->info('对话修改失败', $table_data);
  5438. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  5439. Utils::throwError('20003:对话修改失败');
  5440. }
  5441. // 保存对话记录
  5442. $records = [
  5443. [
  5444. 'uid' => $uid,
  5445. 'anime_id' => $anime_id,
  5446. 'sequence' => 0,
  5447. 'role' => 'user',
  5448. 'content' => $prompt,
  5449. 'created_at' => $now,
  5450. 'updated_at' => $now
  5451. ],
  5452. [
  5453. 'uid' => $uid,
  5454. 'anime_id' => $anime_id,
  5455. 'sequence' => 0,
  5456. 'role' => 'assistant',
  5457. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5458. 'content' => $fullContent,
  5459. 'created_at' => $now,
  5460. 'updated_at' => $now
  5461. ]
  5462. ];
  5463. // 保存对话记录
  5464. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5465. if (!$boolen3) {
  5466. Utils::throwError('20003:对话记录保存失败');
  5467. }
  5468. // 单剧集模式:生成并保存剧集信息
  5469. if ($is_single) {
  5470. $anime_name = getProp($anime, 'anime_name', '未命名');
  5471. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5472. if (empty($episode_arr['acts'])) {
  5473. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5474. }
  5475. $saveResult = $this->saveEpisodeVersionData(
  5476. $anime_id,
  5477. 1,
  5478. $episode_arr,
  5479. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5480. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5481. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5482. null,
  5483. null,
  5484. false,
  5485. $content,
  5486. $now
  5487. );
  5488. $single_episode = $saveResult['episode'];
  5489. $episode_id = $saveResult['episode_id'];
  5490. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5491. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5492. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5493. 'props' => json_encode($saveResult['merged_props'], 256),
  5494. 'updated_at' => $now
  5495. ]);
  5496. if ($boolen5 === false) {
  5497. Utils::throwError('20003:单剧集主表资源同步失败');
  5498. }
  5499. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5500. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5501. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  5502. $episode_record_content = '确认分镜大纲';
  5503. if ($content !== '') {
  5504. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5505. }
  5506. $episode_records = [
  5507. [
  5508. 'uid' => $uid,
  5509. 'anime_id' => $anime_id,
  5510. 'role' => 'user',
  5511. 'content' => $episode_record_content,
  5512. 'sequence' => 1,
  5513. 'episode_id' => $episode_id,
  5514. 'created_at' => $now,
  5515. 'updated_at' => $now
  5516. ],
  5517. [
  5518. 'uid' => $uid,
  5519. 'anime_id' => $anime_id,
  5520. 'role' => 'assistant',
  5521. 'content' => $fullContent,
  5522. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5523. 'sequence' => 1,
  5524. 'episode_id' => $episode_id,
  5525. 'created_at' => $now,
  5526. 'updated_at' => $now
  5527. ]
  5528. ];
  5529. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5530. if (!$boolen4) {
  5531. Utils::throwError('20003:单剧集分镜记录保存失败');
  5532. }
  5533. }
  5534. }catch (\Exception $e) {
  5535. DB::rollBack();
  5536. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  5537. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  5538. yield [
  5539. 'type' => 'done',
  5540. 'answer' => $fullContent,
  5541. 'reasoning' => $fullReasoningContent,
  5542. 'usage' => $usage,
  5543. 'error' => $e->getMessage(),
  5544. ];
  5545. return;
  5546. }
  5547. DB::commit();
  5548. dLog('deepseek')->info('保存完毕');
  5549. if ($is_single && !empty($single_episode)) {
  5550. // $this->batchSetGlobalRoleImg([
  5551. // 'anime_id' => $anime_id,
  5552. // ]);
  5553. // $this->batchSetGlobalSceneImg([
  5554. // 'anime_id' => $anime_id,
  5555. // ]);
  5556. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5557. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5558. }
  5559. $table_data['anime_id'] = $anime_id;
  5560. $table_data['roles'] = json_decode($table_data['roles'], true);
  5561. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5562. unset($table_data['updated_at']);
  5563. unset($table_data['status']);
  5564. yield [
  5565. 'type' => 'done',
  5566. 'script' => $table_data,
  5567. 'episode' => $single_episode,
  5568. 'answer' => $fullContent,
  5569. 'reasoning' => $fullReasoningContent,
  5570. 'usage' => $usage
  5571. ];
  5572. }
  5573. public function chat($data) {
  5574. $uid = Site::getUid();
  5575. $anime_id = getProp($data, 'anime_id');
  5576. $file = getProp($data, 'file');
  5577. $content = getProp($data, 'content', '');
  5578. $bid = getProp($data, 'bid', 0);
  5579. $script_id = getProp($data, 'script_id', 0);
  5580. $episode_number = getProp($data, 'episode_number', 1);
  5581. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5582. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5583. if (!$anime) Utils::throwError('20003:该对话不存在!');
  5584. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  5585. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  5586. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  5587. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  5588. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  5589. $roles = is_array($roles) ? $roles : [];
  5590. $scenes = is_array($scenes) ? $scenes : [];
  5591. // 获取最后一集序号
  5592. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  5593. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  5594. // 转换主体列表和场景列表的格式
  5595. // 获取参考主体或场景
  5596. if ((int)$episode_number === 1) {
  5597. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  5598. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  5599. }else {
  5600. $prev_episode_number = $episode_number - 1;
  5601. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  5602. }
  5603. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  5604. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  5605. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  5606. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  5607. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  5608. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  5609. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  5610. 中年女:邻居阿姨
  5611. 老年男:幽默大爷
  5612. 老年女:婆婆
  5613. 萌娃:奶气萌娃";
  5614. if ($roles_content) {
  5615. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  5616. 主体范围:\n {$roles_content}\n
  5617. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  5618. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5619. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  5620. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5621. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  5622. }else {
  5623. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5624. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  5625. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  5626. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5627. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  5628. }
  5629. if ($scenes_content) {
  5630. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  5631. 场景范围:\n {$scenes_content}\n
  5632. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  5633. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5634. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5635. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  5636. }else {
  5637. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5638. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  5639. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5640. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  5641. }
  5642. // 提取文件内容
  5643. if ($file) {
  5644. $uploaded_content = $this->extractFileContent($file);
  5645. if (!$uploaded_content) {
  5646. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5647. }
  5648. } elseif ($script_id) {
  5649. $uploaded_content = $this->getContentByScriptId($script_id);
  5650. if (!$uploaded_content) {
  5651. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5652. }
  5653. } elseif ($bid) {
  5654. $uploaded_content = $this->getContentByBid($bid);
  5655. if (!$uploaded_content) {
  5656. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5657. }
  5658. } elseif ($content) {
  5659. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  5660. }
  5661. // elseif ($prompt) {
  5662. // $uploaded_content = filterContent($prompt);
  5663. // }
  5664. else {
  5665. $uploaded_content = '';
  5666. }
  5667. $input_art_style = getProp($anime, 'art_style');
  5668. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5669. // 美术风格
  5670. if (!$mappedArtStyle) {
  5671. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5672. }else {
  5673. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5674. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5675. }else {
  5676. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5677. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5678. }
  5679. }
  5680. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5681. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5682. // 强制要求:
  5683. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5684. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5685. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5686. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  5687. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  5688. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  5689. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  5690. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  5691. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  5692. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  5693. // - 分镜要和场景列表、人物主体保持一致\n
  5694. // 普通要求:
  5695. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  5696. // {$role_demo}
  5697. // {$scene_demo}
  5698. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5699. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5700. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5701. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  5702. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  5703. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5704. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5705. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5706. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5707. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5708. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5709. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5710. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5711. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5712. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  5713. // 5.$mappedArtStyle_prompt\n\n
  5714. // 示例格式:\n
  5715. // 第1集:隐形的守护者
  5716. // ###故事梗概
  5717. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5718. // ###美术风格
  5719. // 基础画风风格词:韩漫二次元
  5720. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  5721. // ###主体列表
  5722. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  5723. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  5724. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  5725. // ###场景列表
  5726. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  5727. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5728. // 无人物。}
  5729. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  5730. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  5731. // 无人物。}
  5732. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  5733. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  5734. // 无人物。}
  5735. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  5736. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  5737. // 无人物。}
  5738. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  5739. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  5740. // 无人物。}
  5741. // ###分镜剧本
  5742. // ##第1幕:徐家老旧厨房 白天 室内
  5743. // 分镜1
  5744. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5745. // 场景:徐家老旧厨房
  5746. // 构图设计:全景,低角度仰视
  5747. // 运镜调度:手持拍摄
  5748. // 配音角色:旁白
  5749. // 出镜角色:许芸-校服装、徐母
  5750. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5751. // 画面类型:普通画面
  5752. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5753. // 分镜2
  5754. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5755. // 场景:徐家老旧厨房
  5756. // 构图设计:近景,徐母面部特写
  5757. // 运镜调度:固定镜头
  5758. // 配音角色:徐母
  5759. // 出镜角色:徐母
  5760. // 台词内容:问我夜不归宿死哪儿去了。
  5761. // 画面类型:对口型
  5762. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5763. // ##第2幕:徐家简陋客厅 黄昏 室内
  5764. // 分镜3
  5765. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5766. // 场景:徐家简陋客厅
  5767. // 构图设计:全景,景深虚化
  5768. // 运镜调度:固定镜头
  5769. // 配音角色:旁白
  5770. // 出镜角色:无
  5771. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5772. // 画面类型:普通画面
  5773. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5774. // 分镜4
  5775. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5776. // 场景:徐家简陋客厅
  5777. // 构图设计:特写,火车票
  5778. // 运镜调度:固定镜头
  5779. // 配音角色:旁白
  5780. // 出镜角色:无
  5781. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5782. // 画面类型:普通画面
  5783. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  5784. // \n\n";
  5785. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  5786. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  5787. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  5788. 普通要求:
  5789. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  5790. {$role_demo}
  5791. {$scene_demo}
  5792. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  5793. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  5794. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  5795. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  5796. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  5797. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  5798. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  5799. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  5800. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  5801. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  5802. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  5803. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  5804. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  5805. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  5806. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  5807. 5.$mappedArtStyle_prompt
  5808. 6.《情绪-视听语言映射表》:
  5809. 6.1 场景空间与时间心理学 (Scene & Temporality)
  5810. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  5811. -----|---------|------------|----------------
  5812. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  5813. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  5814. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  5815. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  5816. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  5817. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  5818. -----|---------|------------|----------------
  5819. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  5820. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  5821. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  5822. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  5823. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  5824. --------|---------|--------------|-------------
  5825. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  5826. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  5827. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  5828. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  5829. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  5830. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  5831. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  5832. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  5833. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  5834. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  5835. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  5836. -----|---------|------------|------------
  5837. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  5838. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  5839. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  5840. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  5841. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  5842. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  5843. --------|---------|--------------|----------
  5844. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  5845. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  5846. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  5847. 6.6 声音设计与潜意识影响 (Soundscape)
  5848. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  5849. -----|---------|------------|------------------
  5850. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  5851. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  5852. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  5853. 理论基石:
  5854. - The Five C's of Cinematography by Joseph V. Mascelli
  5855. - Film Art: An Introduction by David Bordwell
  5856. - Sight, Sound, Motion by Herbert Zettl
  5857. - Notes on the Cinematograph by Robert Bresson
  5858. \n\n
  5859. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  5860. 示例格式:\n
  5861. 第1集:隐形的守护者
  5862. ###故事梗概
  5863. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5864. ###美术风格
  5865. 基础画风风格词:韩漫二次元
  5866. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  5867. ###主体列表
  5868. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  5869. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  5870. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  5871. ###场景列表
  5872. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  5873. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5874. 无人物。}
  5875. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  5876. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  5877. 无人物。}
  5878. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  5879. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  5880. 无人物。}
  5881. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  5882. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  5883. 无人物。}
  5884. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  5885. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  5886. 无人物。}
  5887. ###分镜剧本
  5888. ##第1幕:徐家老旧厨房 白天 室内
  5889. 分镜1
  5890. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5891. 场景:徐家老旧厨房
  5892. 构图设计:全景,低角度仰视
  5893. 运镜调度:手持拍摄
  5894. 配音角色:旁白
  5895. 出镜角色:许芸-校服装、徐母
  5896. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5897. 画面类型:普通画面
  5898. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5899. 分镜2
  5900. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5901. 场景:徐家老旧厨房
  5902. 构图设计:近景,徐母面部特写
  5903. 运镜调度:固定镜头
  5904. 配音角色:徐母
  5905. 出镜角色:徐母
  5906. 台词内容:问我夜不归宿死哪儿去了。
  5907. 画面类型:对口型
  5908. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5909. ##第2幕:徐家简陋客厅 黄昏 室内
  5910. 分镜3
  5911. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5912. 场景:徐家简陋客厅
  5913. 构图设计:全景,景深虚化
  5914. 运镜调度:固定镜头
  5915. 配音角色:旁白
  5916. 出镜角色:无
  5917. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5918. 画面类型:普通画面
  5919. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5920. 分镜4
  5921. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5922. 场景:徐家简陋客厅
  5923. 构图设计:特写,火车票
  5924. 运镜调度:固定镜头
  5925. 配音角色:旁白
  5926. 出镜角色:无
  5927. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5928. 画面类型:普通画面
  5929. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  5930. \n\n";
  5931. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5932. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  5933. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  5934. $prompt = $origin_prompt;
  5935. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  5936. // 获取章节内容
  5937. $full_content = getProp($anime, 'content');
  5938. if ($uploaded_content) {
  5939. $full_content = $uploaded_content;
  5940. }
  5941. // 根据章节内容拆分章节
  5942. $chapters = splitContent($full_content);
  5943. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  5944. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  5945. $messages = [];
  5946. if ($prompt == '确认分镜大纲') {
  5947. // 暂时保留
  5948. $content = $chapter_content;
  5949. if ($is_single) $content = $full_content; // 单剧集使用全文
  5950. if (!$content) {
  5951. Utils::throwError('20003:章节内容无法获取,请确认');
  5952. }
  5953. $question = $is_single
  5954. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  5955. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  5956. // 构建消息
  5957. $messages[] =
  5958. [
  5959. 'role' => 'user',
  5960. 'content' => $question
  5961. ];
  5962. }else if ($prompt == '继续策划下一集') {
  5963. if ($is_single) {
  5964. Utils::throwError('20003:单剧集不支持继续策划下一集');
  5965. }
  5966. $content = $chapter_content;
  5967. if (!$content) {
  5968. Utils::throwError('20003:章节内容无法获取,请确认');
  5969. }
  5970. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  5971. // 获取上一集最后记录
  5972. $prev_sequence = $episode_number - 1;
  5973. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  5974. // 构建消息
  5975. $messages[] =
  5976. [
  5977. 'role' => 'user',
  5978. 'content' => $question
  5979. ];
  5980. }else {
  5981. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  5982. if (!$content) {
  5983. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  5984. }
  5985. if (!$content) {
  5986. Utils::throwError('20003:章节内容无法获取,请确认');
  5987. }
  5988. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  5989. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  5990. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  5991. if ($origin_prompt) {
  5992. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  5993. }
  5994. $messages[] =
  5995. [
  5996. 'role' => 'user',
  5997. 'content' => $question
  5998. ];
  5999. }
  6000. // 处理文本模型
  6001. $model = getProp($data, 'model');
  6002. if (!$model) {
  6003. // 用户没有输入,从anime表获取
  6004. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6005. $model = getProp($anime, 'model');
  6006. if (!$model) {
  6007. // anime表也没有,使用默认值
  6008. $model = 'doubao-seed-2-0-mini-260215';
  6009. }
  6010. }
  6011. // 验证模型是否在可用模型表中
  6012. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6013. $model = 'doubao-seed-2-0-mini-260215';
  6014. }
  6015. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6016. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6017. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6018. if ($model === 'deepseek-chat') {
  6019. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6020. $model = 'deepseek-v4-flash';
  6021. $thinkingMode = 'disabled';
  6022. } elseif ($model === 'deepseek-reasoner') {
  6023. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6024. $model = 'deepseek-v4-flash';
  6025. $thinkingMode = 'enabled';
  6026. }
  6027. $post_data = [
  6028. 'model' => $model,
  6029. 'messages' => $messages,
  6030. // 'max_tokens' => 8192,
  6031. 'temperature' => 0.2,
  6032. 'frequency_penalty' => 0,
  6033. 'presence_penalty' => 0,
  6034. 'response_format' => ['type' => 'text'],
  6035. 'thinking' => ['type' => $thinkingMode],
  6036. 'stream' => true // 启用流式输出
  6037. ];
  6038. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6039. // 根据模型类型选择调用方法
  6040. $fullContent = '';
  6041. $fullReasoningContent = '';
  6042. $usage = [];
  6043. try {
  6044. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6045. // DeepSeek 官方模型使用 DeepSeek API
  6046. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6047. } else if (in_array($model, $this->gpt_text_models)) {
  6048. // GPT-5.4 模型使用 TokenRouter API
  6049. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6050. } else if (in_array($model, $this->gemini_text_models)) {
  6051. // Gemini 模型使用 Gemini API
  6052. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6053. } else {
  6054. // 其他模型使用火山引擎API
  6055. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6056. }
  6057. // 验证返回值类型
  6058. if (!is_iterable($streamGenerator)) {
  6059. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6060. dLog('deepseek')->error('chat流式生成器无效', [
  6061. 'generator_type' => $errorType,
  6062. 'model' => $model,
  6063. 'anime_id' => $anime_id,
  6064. 'episode_number' => $episode_number
  6065. ]);
  6066. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  6067. 'type' => $errorType,
  6068. 'model' => $model
  6069. ]);
  6070. yield [
  6071. 'type' => 'error',
  6072. 'episode' => [],
  6073. 'answer' => '',
  6074. 'reasoning' => '',
  6075. 'usage' => [],
  6076. 'error' => '接口返回数据异常,请重新请求'
  6077. ];
  6078. return;
  6079. }
  6080. // 处理流式输出
  6081. foreach ($streamGenerator as $chunk) {
  6082. if (isset($chunk['type'])) {
  6083. if ($chunk['type'] === 'done') {
  6084. // 最终结果
  6085. $fullContent = $chunk['full_content'];
  6086. $fullReasoningContent = $chunk['full_reasoning'];
  6087. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6088. } else {
  6089. // 逐块yield数据
  6090. yield $chunk;
  6091. }
  6092. }
  6093. }
  6094. } catch (\Exception $e) {
  6095. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  6096. 'model' => $model,
  6097. 'anime_id' => $anime_id,
  6098. 'episode_number' => $episode_number,
  6099. 'trace' => $e->getTraceAsString()
  6100. ]);
  6101. logDB('deepseek', 'error', 'chat流式处理失败', [
  6102. 'error' => $e->getMessage(),
  6103. 'model' => $model
  6104. ]);
  6105. yield [
  6106. 'type' => 'error',
  6107. 'episode' => [],
  6108. 'answer' => '',
  6109. 'reasoning' => '',
  6110. 'usage' => [],
  6111. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6112. ];
  6113. return;
  6114. }
  6115. dLog('deepseek')->info('完整内容: '.$fullContent);
  6116. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6117. // 处理完整内容并返回最终结果
  6118. $episode_arr = handleEpisodeContent($fullContent);
  6119. logDB('deepseek', 'info', '解析内容', $episode_arr);
  6120. if (empty($episode_arr['acts'])) {
  6121. // 未生成剧本相关内容,保存对话记录并返回提示
  6122. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  6123. try {
  6124. $now = date('Y-m-d H:i:s');
  6125. // 保存对话记录
  6126. $records = [
  6127. [
  6128. 'uid' => $uid,
  6129. 'anime_id' => $anime_id,
  6130. 'sequence' => $episode_number,
  6131. 'role' => 'user',
  6132. 'content' => $prompt,
  6133. 'created_at' => $now,
  6134. 'updated_at' => $now
  6135. ],
  6136. [
  6137. 'uid' => $uid,
  6138. 'anime_id' => $anime_id,
  6139. 'sequence' => $episode_number,
  6140. 'role' => 'assistant',
  6141. 'content' => $fullContent,
  6142. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6143. 'created_at' => $now,
  6144. 'updated_at' => $now
  6145. ]
  6146. ];
  6147. DB::table('mp_anime_records')->insert($records);
  6148. } catch (\Exception $e) {
  6149. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6150. }
  6151. yield [
  6152. 'type' => 'done',
  6153. 'episode' => [],
  6154. 'answer' => $fullContent,
  6155. 'reasoning' => $fullReasoningContent,
  6156. 'usage' => $usage,
  6157. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  6158. ];
  6159. return;
  6160. }
  6161. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  6162. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  6163. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  6164. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  6165. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  6166. $existing_props = is_array($existing_props) ? $existing_props : [];
  6167. $now = date('Y-m-d H:i:s');
  6168. try {
  6169. DB::beginTransaction();
  6170. $saveResult = $this->saveEpisodeVersionData(
  6171. $anime_id,
  6172. $episode_number,
  6173. $episode_arr,
  6174. $existing_roles,
  6175. $existing_scenes,
  6176. $existing_props,
  6177. $current_episode,
  6178. $base_episode,
  6179. $is_regenerate_version,
  6180. $content,
  6181. $now
  6182. );
  6183. $episode = $saveResult['episode'];
  6184. $episode_id = $saveResult['episode_id'];
  6185. $merged_roles = $saveResult['merged_roles'];
  6186. $merged_scenes = $saveResult['merged_scenes'];
  6187. $merged_props = $saveResult['merged_props'];
  6188. $record_content = $origin_prompt;
  6189. if ($uploaded_content !== '') {
  6190. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  6191. }
  6192. $records = [
  6193. [
  6194. 'uid' => $uid,
  6195. 'anime_id' => $anime_id,
  6196. 'role' => 'user',
  6197. 'content' => $record_content,
  6198. 'sequence' => $episode_number,
  6199. 'episode_id' => $episode_id,
  6200. 'created_at' => $now,
  6201. 'updated_at' => $now
  6202. ],
  6203. [
  6204. 'uid' => $uid,
  6205. 'anime_id' => $anime_id,
  6206. 'role' => 'assistant',
  6207. 'content' => $fullContent,
  6208. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6209. 'sequence' => $episode_number,
  6210. 'episode_id' => $episode_id,
  6211. 'created_at' => $now,
  6212. 'updated_at' => $now
  6213. ]
  6214. ];
  6215. $boolen4 = DB::table('mp_anime_records')->insert($records);
  6216. if (!$boolen4) {
  6217. Utils::throwError('20003:对话记录保存失败');
  6218. }
  6219. // 保存模型和内容到anime表
  6220. $update_anime_data = [
  6221. 'model' => $model,
  6222. 'updated_at' => $now
  6223. ];
  6224. if ($uploaded_content) {
  6225. $update_anime_data['content'] = $uploaded_content;
  6226. }
  6227. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  6228. }catch (\Exception $e) {
  6229. DB::rollBack();
  6230. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6231. yield [
  6232. 'type' => 'done',
  6233. 'answer' => $fullContent,
  6234. 'reasoning' => $fullReasoningContent,
  6235. 'usage' => $usage,
  6236. 'error' => $e->getMessage(),
  6237. ];
  6238. return;
  6239. }
  6240. DB::commit();
  6241. if ($is_global_generate_pics) {
  6242. // // 批量生成全局角色图片
  6243. // $this->batchSetGlobalRoleImg([
  6244. // 'anime_id' => $anime_id,
  6245. // ], true);
  6246. // // 批量生成全局场景图片
  6247. // $this->batchSetGlobalSceneImg([
  6248. // 'anime_id' => $anime_id,
  6249. // ], true);
  6250. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6251. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6252. }
  6253. $episode['episode_id'] = $episode_id;
  6254. $episode['roles'] = $merged_roles;
  6255. $episode['scenes'] = $merged_scenes;
  6256. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  6257. yield [
  6258. 'type' => 'done',
  6259. 'episode' => $episode,
  6260. 'answer' => $fullContent,
  6261. 'reasoning' => $fullReasoningContent,
  6262. 'usage' => $usage
  6263. ];
  6264. }
  6265. public function addChatForAce($data) {
  6266. $uid = Site::getUid();
  6267. $anime_id = getProp($data, 'anime_id');
  6268. if (!$anime_id) Utils::throwError('20003:请选择对话');
  6269. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  6270. if (!$anime) Utils::throwError('20003:对话不存在');
  6271. $file = getProp($data, 'file');
  6272. $content = getProp($data, 'content', '');
  6273. $bid = getProp($data, 'bid', 0);
  6274. $script_id = getProp($data, 'script_id', 0);
  6275. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  6276. $prompt = getProp($data, 'prompt');
  6277. $is_multi = getProp($anime, 'is_multi');
  6278. $is_single = (int)$is_multi !== 1;
  6279. $extra_products = getProp($data, 'products', []);
  6280. if (!$extra_products) {
  6281. $extra_products = getProp($anime, 'extra_products');
  6282. if ($extra_products) {
  6283. $extra_products = json_decode($extra_products, true);
  6284. }else {
  6285. $extra_products = [];
  6286. }
  6287. }else {
  6288. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6289. }
  6290. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6291. $anime_script_id = getProp($anime, 'script_id');
  6292. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  6293. $cpid = Site::getCpid();
  6294. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6295. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6296. ->where('mapping.script_id', $anime_script_id)
  6297. ->where('product.cpid', $cpid)
  6298. ->where('product.is_deleted', 0);
  6299. $mappings = $script_products_mappings->select(
  6300. 'mapping.product_id',
  6301. 'mapping.episode_number',
  6302. 'product.product_name',
  6303. 'product.type',
  6304. 'product.product',
  6305. 'product.pic_prompt',
  6306. 'product.url',
  6307. 'product.pic_task_id',
  6308. 'product.pic_task_status',
  6309. 'product.three_view_image_url'
  6310. )
  6311. ->get();
  6312. // 按 product_id 分组,合并 episode_number
  6313. $productMap = [];
  6314. foreach ($mappings as $item) {
  6315. $product_id = $item->product_id;
  6316. $product_name = $item->product_name;
  6317. // 处理product_name两边的符号
  6318. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6319. if (!isset($productMap[$product_id])) {
  6320. $productMap[$product_id] = [
  6321. 'product_id' => $product_id,
  6322. 'product_name' => $product_name,
  6323. 'type' => (int)$item->type,
  6324. 'product' => (int)$item->product,
  6325. 'pic_prompt' => $item->pic_prompt,
  6326. 'url' => $item->url,
  6327. 'pic_task_id' => $item->pic_task_id,
  6328. 'pic_task_status' => $item->pic_task_status,
  6329. 'episode_numbers' => [],
  6330. ];
  6331. }
  6332. // 添加 episode_number(去重)
  6333. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6334. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6335. }
  6336. }
  6337. // 将查询到的剧本资产合并到extra_products中
  6338. // 先构建extra_products的索引(以product_id为key,用于去重)
  6339. $extraProductsMap = [];
  6340. foreach ($extra_products as $item) {
  6341. $key = getProp($item, 'product_id');
  6342. if ($key) {
  6343. $extraProductsMap[$key] = $item;
  6344. }
  6345. }
  6346. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6347. foreach ($productMap as $product) {
  6348. $product_id = $product['product_id'];
  6349. // 如果不存在则添加(不带episode_number信息)
  6350. if (!isset($extraProductsMap[$product_id])) {
  6351. $extraProductsMap[$product_id] = [
  6352. 'product_id' => $product['product_id'],
  6353. 'product_name' => $product['product_name'],
  6354. 'type' => $product['type'],
  6355. 'product' => $product['product'],
  6356. 'pic_prompt' => $product['pic_prompt'],
  6357. 'url' => $product['url'],
  6358. 'pic_task_id' => $product['pic_task_id'],
  6359. 'pic_task_status' => $product['pic_task_status'],
  6360. ];
  6361. }
  6362. }
  6363. // 重新赋值给extra_products
  6364. $extra_products = array_values($extraProductsMap);
  6365. }
  6366. $user_anime_name = getProp($anime, 'anime_name');
  6367. // 处理提示词
  6368. if ($prompt && $extra_products) {
  6369. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6370. foreach($extra_products as $item) {
  6371. $product_name = getProp($item, 'product_name');
  6372. if ($product_name) {
  6373. // 替换 {product_name} 为 product_name
  6374. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6375. }
  6376. }
  6377. }
  6378. // 处理文本模型
  6379. $model = getProp($data, 'model');
  6380. if (!$model) {
  6381. // 用户没有输入,从anime表获取
  6382. $model = getProp($anime, 'model');
  6383. if (!$model) {
  6384. // anime表也没有,使用默认值
  6385. $model = 'deepseek-v4-pro';
  6386. }
  6387. }
  6388. // 验证模型是否在可用模型表中
  6389. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6390. $model = 'deepseek-v4-pro';
  6391. }
  6392. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6393. if ($prompt) {
  6394. $question .= "本次修改要求如下:\n{$prompt}";
  6395. }
  6396. // if (!$file && !$content && !$bid) {
  6397. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  6398. // }
  6399. // 提取文件内容
  6400. if ($file) {
  6401. $content = $this->extractFileContent($file);
  6402. if (!$content) {
  6403. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6404. }
  6405. } elseif ($script_id) {
  6406. $content = $this->getContentByScriptId($script_id);
  6407. if (!$content) {
  6408. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6409. }
  6410. } elseif ($bid) {
  6411. $content = $this->getContentByBid($bid);
  6412. if (!$content) {
  6413. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6414. }
  6415. } elseif ($content) {
  6416. $content = filterContent($content);
  6417. } else {
  6418. $content = getProp($anime, 'content');
  6419. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6420. $need_generate_content = true;
  6421. }
  6422. }
  6423. // 美术风格
  6424. $input_art_style = getProp($data, 'art_style');
  6425. if (!$input_art_style) {
  6426. $mappedArtStyle = getProp($anime, 'art_style');
  6427. }else {
  6428. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6429. }
  6430. // 判断是否需要生成原文内容
  6431. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6432. // 如果需要生成原文内容,添加额外的要求
  6433. $content_generation_requirement = $need_generate_content
  6434. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6435. : "";
  6436. // 美术风格
  6437. if (!$mappedArtStyle) {
  6438. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6439. }else {
  6440. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6441. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6442. }else {
  6443. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6444. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6445. }
  6446. }
  6447. // 构建主体、场景和道具提示词
  6448. $extra_role_prompt = "\n";
  6449. $extra_scene_prompt = "\n";
  6450. $extra_prop_prompt = "\n";
  6451. $ref_products = []; // 参考资产
  6452. if ($extra_products) {
  6453. foreach($extra_products as $item) {
  6454. $product = getProp($item, 'product');
  6455. $product_name = getProp($item, 'product_name');
  6456. if ($product_name == '旁白') continue;
  6457. $ref_products[$product_name] = $item;
  6458. $pic_prompt = getProp($item, 'pic_prompt');
  6459. if ((int)$product === 1) {
  6460. // 拼接角色信息
  6461. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6462. } elseif ((int)$product === 2) {
  6463. // 拼接场景信息
  6464. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6465. } elseif ((int)$product === 3) {
  6466. // 拼接道具信息
  6467. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6468. }
  6469. }
  6470. // 优化提示词,融入剧本
  6471. if (!empty(trim($extra_role_prompt))) {
  6472. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6473. }
  6474. if (!empty(trim($extra_scene_prompt))) {
  6475. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6476. }
  6477. if (!empty(trim($extra_prop_prompt))) {
  6478. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6479. }
  6480. }
  6481. if ($anime_script_id && $is_single) {
  6482. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6483. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6484. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6485. }else {
  6486. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6487. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6488. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6489. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6490. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6491. {$extra_role_prompt}";
  6492. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6493. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6494. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6495. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6496. {$extra_scene_prompt}";
  6497. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6498. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6499. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6500. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6501. {$extra_prop_prompt}";
  6502. }
  6503. $systemPrompt = $is_single
  6504. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6505. 强制要求:
  6506. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6507. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6508. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6509. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6510. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6511. 普通要求:
  6512. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6513. $role_demo
  6514. $scene_demo
  6515. $prop_demo
  6516. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6517. 5.1片段分割逻辑(优先级从高到低):
  6518. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6519. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6520. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6521. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6522. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6523. - 片段数量格式为: 片段数量:8
  6524. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6525. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6526. 5.3分镜结构:每个分镜包含以下字段:
  6527. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6528. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6529. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6530. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6531. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6532. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6533. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6534. - 运镜:场景+画面描述+运镜
  6535. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  6536. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  6537. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6538. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6539. 6.{$mappedArtStyle_prompt}\n\n
  6540. 示例如下:\n
  6541. ###剧本名:西昆仑
  6542. ###故事梗概
  6543. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6544. ###剧本亮点
  6545. 亮点1:绝境奇药,生死一线
  6546. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6547. 亮点2:结拜兄妹,化解尴尬
  6548. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6549. 亮点3:纤发夺命,情愫暗涌
  6550. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6551. ###人物关系
  6552. 阿雪与梁萧之间存在兄妹之情。
  6553. ###核心矛盾
  6554. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6555. ###主体列表
  6556. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6557. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6558. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6559. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6560. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6561. 全景,正面拍摄,青年女性,亚洲人。
  6562. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6563. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6564. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6565. ###美术风格
  6566. 基础画风风格词:厚涂古风
  6567. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6568. ###场景列表
  6569. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6570. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6571. 无人物。}
  6572. ###分段剧本
  6573. 片段数量:8
  6574. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6575. ##片段1
  6576. 时长:12s
  6577. 分镜1
  6578. 出场角色:刀疤脸
  6579. 场景:边境小镇街道
  6580. 出场道具:酒杯-高脚杯
  6581. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6582. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6583. 配音台词:
  6584. 背景音效:
  6585. 分镜2
  6586. 出场角色:刀疤脸
  6587. 场景:悦来酒馆
  6588. 出场道具:酒杯-高脚杯
  6589. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6590. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6591. 配音台词:
  6592. 背景音效:
  6593. 分镜3
  6594. 出场角色:刀疤脸
  6595. 场景:悦来酒馆
  6596. 出场道具:酒杯-高脚杯
  6597. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6598. 运镜:从中景推向令牌特写。
  6599. 配音台词:
  6600. 背景音效:
  6601. 分镜4
  6602. 出场角色:刀疤脸
  6603. 场景:悦来酒馆
  6604. 出场道具:酒杯-高脚杯
  6605. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6606. 运镜:极速推向酒水溅起的瞬间。
  6607. 配音台词:
  6608. 背景音效:
  6609. 分镜5
  6610. 出场角色:刀疤脸
  6611. 场景:悦来酒馆
  6612. 出场道具:酒杯-高脚杯
  6613. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6614. 运镜:固定机位,利用倾斜构图制造压迫感。
  6615. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6616. 背景音效:
  6617. \n\n"
  6618. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6619. 强制要求:\n
  6620. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6621. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6622. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6623. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6624. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6625. 普通要求:\n
  6626. 1.剧本名(必须生成)必须与文档内容高度相关
  6627. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6628. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6629. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6630. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6631. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6632. {$extra_role_prompt}
  6633. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6634. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6635. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6636. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6637. {$extra_scene_prompt}
  6638. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6639. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6640. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6641. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6642. {$extra_prop_prompt}
  6643. 5.{$mappedArtStyle_prompt}\n\n
  6644. 示例如下:\n
  6645. ###剧本名:西昆仑
  6646. ###故事梗概
  6647. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6648. ###剧本亮点
  6649. 亮点1:绝境奇药,生死一线
  6650. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6651. 亮点2:结拜兄妹,化解尴尬
  6652. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6653. 亮点3:纤发夺命,情愫暗涌
  6654. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6655. ###人物关系
  6656. 阿雪与梁萧之间存在兄妹之情。
  6657. ###核心矛盾
  6658. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6659. ###主体列表
  6660. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6661. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6662. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6663. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6664. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6665. 全景,正面拍摄,青年女性,亚洲人。
  6666. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6667. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6668. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6669. ###美术风格
  6670. 基础画风风格词:厚涂古风
  6671. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6672. ###场景列表
  6673. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6674. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6675. 无人物。}
  6676. ###道具列表
  6677. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  6678. // 构建消息
  6679. $messages = [
  6680. [
  6681. 'role' => 'system',
  6682. 'content' => $systemPrompt
  6683. ],
  6684. [
  6685. 'role' => 'user',
  6686. 'content' => "以下是文档内容:
  6687. {$content}
  6688. 用户问题:
  6689. {$question}"
  6690. ]
  6691. ];
  6692. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6693. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6694. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6695. if ($model === 'deepseek-chat') {
  6696. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6697. $model = 'deepseek-v4-flash';
  6698. $thinkingMode = 'disabled';
  6699. } elseif ($model === 'deepseek-reasoner') {
  6700. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6701. $model = 'deepseek-v4-flash';
  6702. $thinkingMode = 'enabled';
  6703. }
  6704. $post_data = [
  6705. 'model' => $model,
  6706. 'messages' => $messages,
  6707. // 'max_tokens' => 8192,
  6708. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  6709. 'frequency_penalty' => 0,
  6710. 'presence_penalty' => 0,
  6711. 'response_format' => ['type' => 'text'],
  6712. 'thinking' => ['type'=>$thinkingMode],
  6713. 'stream' => true // 启用流式输出
  6714. ];
  6715. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6716. // 根据模型类型选择调用方法
  6717. $fullContent = '';
  6718. $fullReasoningContent = '';
  6719. $usage = [];
  6720. try {
  6721. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6722. // DeepSeek 官方模型使用 DeepSeek API
  6723. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6724. } else if (in_array($model, $this->gpt_text_models)) {
  6725. // GPT-5.4 模型使用 TokenRouter API
  6726. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6727. } else if (in_array($model, $this->gemini_text_models)) {
  6728. // Gemini 模型使用 Gemini API
  6729. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  6730. } else {
  6731. // 其他模型使用火山引擎API
  6732. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6733. }
  6734. // 验证返回值类型
  6735. if (!is_iterable($streamGenerator)) {
  6736. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6737. dLog('deepseek')->error('addChat流式生成器无效', [
  6738. 'generator_type' => $errorType,
  6739. 'model' => $model,
  6740. 'anime_id' => $anime_id
  6741. ]);
  6742. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  6743. 'type' => $errorType,
  6744. 'model' => $model
  6745. ]);
  6746. yield [
  6747. 'type' => 'error',
  6748. 'script' => [],
  6749. 'episode' => [],
  6750. 'answer' => '',
  6751. 'reasoning' => '',
  6752. 'usage' => [],
  6753. 'error' => '接口返回数据异常,请重新请求'
  6754. ];
  6755. return;
  6756. }
  6757. // 处理流式输出
  6758. foreach ($streamGenerator as $chunk) {
  6759. if (isset($chunk['type'])) {
  6760. if ($chunk['type'] === 'done') {
  6761. // 最终结果
  6762. $fullContent = $chunk['full_content'];
  6763. $fullReasoningContent = $chunk['full_reasoning'];
  6764. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6765. } else {
  6766. // 逐块yield数据
  6767. yield $chunk;
  6768. }
  6769. }
  6770. }
  6771. } catch (\Exception $e) {
  6772. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  6773. 'model' => $model,
  6774. 'anime_id' => $anime_id,
  6775. 'trace' => $e->getTraceAsString()
  6776. ]);
  6777. logDB('deepseek', 'error', 'addChat流式处理失败', [
  6778. 'error' => $e->getMessage(),
  6779. 'model' => $model
  6780. ]);
  6781. yield [
  6782. 'type' => 'error',
  6783. 'script' => [],
  6784. 'episode' => [],
  6785. 'answer' => '',
  6786. 'reasoning' => '',
  6787. 'usage' => [],
  6788. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6789. ];
  6790. return;
  6791. }
  6792. dLog('deepseek')->info('完整内容: '.$fullContent);
  6793. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6794. // 处理完整内容并返回最终结果
  6795. $script_arr = [];
  6796. if ($fullContent) {
  6797. $script_arr = handleScriptContentForAce($fullContent);
  6798. dLog('deepseek')->info('解析内容', $script_arr);
  6799. logDB('deepseek', 'info', '解析内容', $script_arr);
  6800. }
  6801. if (empty($script_arr['roles'])) {
  6802. // 未生成剧本相关内容,保存对话记录并返回提示
  6803. dLog('deepseek')->info('未生成剧本相关的内容');
  6804. try {
  6805. DB::beginTransaction();
  6806. $now = date('Y-m-d H:i:s');
  6807. // 保存对话记录
  6808. $records = [
  6809. [
  6810. 'uid' => $uid,
  6811. 'anime_id' => $anime_id,
  6812. 'sequence' => 0,
  6813. 'role' => 'user',
  6814. 'content' => $prompt,
  6815. 'created_at' => $now,
  6816. 'updated_at' => $now
  6817. ],
  6818. [
  6819. 'uid' => $uid,
  6820. 'anime_id' => $anime_id,
  6821. 'sequence' => 0,
  6822. 'role' => 'assistant',
  6823. // 'content' => $fullContent,
  6824. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  6825. 'created_at' => $now,
  6826. 'updated_at' => $now
  6827. ]
  6828. ];
  6829. DB::table('mp_anime_records')->insert($records);
  6830. DB::commit();
  6831. } catch (\Exception $e) {
  6832. DB::rollBack();
  6833. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6834. }
  6835. yield [
  6836. 'type' => 'done',
  6837. 'script' => [],
  6838. 'episode' => [],
  6839. 'answer' => $fullContent,
  6840. 'reasoning' => $fullReasoningContent,
  6841. 'usage' => $usage,
  6842. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6843. ];
  6844. return;
  6845. }
  6846. // 如果需要生成原文内容,从script_arr中提取
  6847. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6848. $content = $script_arr['content'];
  6849. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  6850. if (!$content) {
  6851. yield [
  6852. 'type' => 'done',
  6853. 'script' => [],
  6854. 'episode' => [],
  6855. 'answer' => $fullContent,
  6856. 'reasoning' => $fullReasoningContent,
  6857. 'usage' => $usage,
  6858. 'error' => '未生成剧本内容,请调整提示词再试'
  6859. ];
  6860. return;
  6861. }
  6862. }
  6863. // 替换美术风格
  6864. if ($mappedArtStyle !== '') {
  6865. $script_arr['art_style'] = $mappedArtStyle;
  6866. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6867. }
  6868. // 新建动漫
  6869. if ($user_anime_name == '新剧本策划') {
  6870. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  6871. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  6872. // if (!$anime_name) {
  6873. // // 未识别到剧本名,保存对话记录并返回提示
  6874. // dLog('deepseek')->info('未能识别到剧本名称');
  6875. // try {
  6876. // DB::beginTransaction();
  6877. // $now = date('Y-m-d H:i:s');
  6878. // // 保存对话记录
  6879. // $records = [
  6880. // [
  6881. // 'uid' => $uid,
  6882. // 'anime_id' => $anime_id,
  6883. // 'sequence' => 0,
  6884. // 'role' => 'user',
  6885. // 'content' => $prompt,
  6886. // 'created_at' => $now,
  6887. // 'updated_at' => $now
  6888. // ],
  6889. // [
  6890. // 'uid' => $uid,
  6891. // 'anime_id' => $anime_id,
  6892. // 'sequence' => 0,
  6893. // 'role' => 'assistant',
  6894. // 'content' => '未能生成剧本名称,请重试',
  6895. // 'created_at' => $now,
  6896. // 'updated_at' => $now
  6897. // ]
  6898. // ];
  6899. // DB::table('mp_anime_records')->insert($records);
  6900. // DB::commit();
  6901. // } catch (\Exception $e) {
  6902. // DB::rollBack();
  6903. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6904. // }
  6905. // yield [
  6906. // 'type' => 'done',
  6907. // 'script' => [],
  6908. // 'episode' => [],
  6909. // 'answer' => $fullContent,
  6910. // 'reasoning' => $fullReasoningContent,
  6911. // 'usage' => $usage,
  6912. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  6913. // ];
  6914. // return;
  6915. // }
  6916. // 确认对话名称唯一性
  6917. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6918. $anime_name = $anime_name . '_' . date('YmdHis');
  6919. }
  6920. }else {
  6921. $anime_name = $user_anime_name;
  6922. }
  6923. $table_data = [
  6924. 'user_id' => $uid,
  6925. 'anime_name' => $anime_name,
  6926. 'model' => $model,
  6927. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6928. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6929. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6930. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6931. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6932. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6933. 'art_style_type' => $input_art_style,
  6934. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6935. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6936. 'status' => '解析完成',
  6937. 'content' => $content,
  6938. 'is_multi' => $is_multi,
  6939. 'ace_mode' => $ace_mode,
  6940. 'generate_status' => '待执行',
  6941. 'updated_at' => date('Y-m-d H:i:s')
  6942. ];
  6943. if ($table_data['content']) {
  6944. $chapters = splitContent($table_data['content']);
  6945. $chapter_count = count($chapters);
  6946. if ($chapter_count > 0) {
  6947. $table_data['start_episode_sequence'] = 1;
  6948. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6949. }
  6950. }
  6951. if ($extra_products) {
  6952. $table_data['extra_products'] = json_encode($extra_products, 256);
  6953. }
  6954. // 如果有剧本ID则进行绑定
  6955. if ($script_id) {
  6956. $table_data['script_id'] = $script_id;
  6957. }
  6958. $single_episode = [];
  6959. try {
  6960. DB::beginTransaction();
  6961. $now = date('Y-m-d H:i:s');
  6962. // 更新动漫大纲
  6963. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6964. if (!$boolen) {
  6965. dLog('deepseek')->info('动漫保存失败', $table_data);
  6966. Utils::throwError('20003:动漫保存失败');
  6967. }
  6968. // 保存对话记录
  6969. $records = [
  6970. [
  6971. 'uid' => $uid,
  6972. 'anime_id' => $anime_id,
  6973. 'sequence' => 0,
  6974. 'role' => 'user',
  6975. 'content' => $prompt,
  6976. 'created_at' => date('Y-m-d H:i:s'),
  6977. 'updated_at' => date('Y-m-d H:i:s')
  6978. ],
  6979. [
  6980. 'uid' => $uid,
  6981. 'anime_id' => $anime_id,
  6982. 'sequence' => 0,
  6983. 'role' => 'assistant',
  6984. 'content' => $fullContent,
  6985. 'created_at' => date('Y-m-d H:i:s'),
  6986. 'updated_at' => date('Y-m-d H:i:s')
  6987. ]
  6988. ];
  6989. // 保存对话记录
  6990. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6991. if (!$boolen3) {
  6992. Utils::throwError('20003:对话记录保存失败');
  6993. }
  6994. if ($is_single) {
  6995. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6996. if (empty($episode_arr['acts'])) {
  6997. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6998. }
  6999. $saveResult = $this->saveEpisodeVersionData(
  7000. $anime_id,
  7001. 1,
  7002. $episode_arr,
  7003. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7004. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7005. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7006. null,
  7007. null,
  7008. false,
  7009. $content,
  7010. $now,
  7011. $ref_products
  7012. );
  7013. $single_episode = $saveResult['episode'];
  7014. $episode_id = $saveResult['episode_id'];
  7015. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7016. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7017. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7018. 'props' => json_encode($saveResult['merged_props'], 256),
  7019. 'updated_at' => $now
  7020. ]);
  7021. if ($boolen5 === false) {
  7022. Utils::throwError('20003:单剧集主表资源同步失败');
  7023. }
  7024. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7025. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7026. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7027. $episode_record_content = '确认分镜大纲';
  7028. if ($content !== '') {
  7029. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7030. }
  7031. $episode_records = [
  7032. [
  7033. 'uid' => $uid,
  7034. 'anime_id' => $anime_id,
  7035. 'role' => 'user',
  7036. 'content' => $episode_record_content,
  7037. 'sequence' => 1,
  7038. 'episode_id' => $episode_id,
  7039. 'created_at' => $now,
  7040. 'updated_at' => $now
  7041. ],
  7042. [
  7043. 'uid' => $uid,
  7044. 'anime_id' => $anime_id,
  7045. 'role' => 'assistant',
  7046. 'content' => $fullContent,
  7047. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7048. 'sequence' => 1,
  7049. 'episode_id' => $episode_id,
  7050. 'created_at' => $now,
  7051. 'updated_at' => $now
  7052. ]
  7053. ];
  7054. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7055. if (!$boolen4) {
  7056. Utils::throwError('20003:单剧集分镜记录保存失败');
  7057. }
  7058. }
  7059. }catch (\Exception $e) {
  7060. DB::rollBack();
  7061. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7062. yield [
  7063. 'type' => 'done',
  7064. 'answer' => $fullContent,
  7065. 'reasoning' => $fullReasoningContent,
  7066. 'usage' => $usage,
  7067. 'error' => $e->getMessage(),
  7068. ];
  7069. return;
  7070. }
  7071. DB::commit();
  7072. dLog('deepseek')->info('保存完毕');
  7073. if ($is_single && !empty($single_episode)) {
  7074. // $this->batchSetGlobalRoleImg([
  7075. // 'anime_id' => $anime_id,
  7076. // ]);
  7077. // $this->batchSetGlobalSceneImg([
  7078. // 'anime_id' => $anime_id,
  7079. // ]);
  7080. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7081. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7082. }
  7083. $table_data['anime_id'] = $anime_id;
  7084. $table_data['roles'] = json_decode($table_data['roles'], true);
  7085. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7086. // $table_data['episodes'] = $script_arr['episodes'];
  7087. unset($table_data['created_at']);
  7088. unset($table_data['updated_at']);
  7089. unset($table_data['status']);
  7090. dLog('deepseek')->info('开始返回');
  7091. yield [
  7092. 'type' => 'done',
  7093. 'script' => $table_data,
  7094. 'episode' => $single_episode,
  7095. 'answer' => $fullContent,
  7096. 'reasoning' => $fullReasoningContent,
  7097. 'usage' => $usage
  7098. ];
  7099. }
  7100. public function reGenerateAnimeForAce($data) {
  7101. $uid = Site::getUid();
  7102. $file = getProp($data, 'file');
  7103. $content = getProp($data, 'content', '');
  7104. $bid = getProp($data, 'bid', 0);
  7105. $script_id = getProp($data, 'script_id', 0);
  7106. $anime_id = getProp($data, 'anime_id');
  7107. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7108. if (!$anime) {
  7109. Utils::throwError('20003:该对话不存在');
  7110. }
  7111. $is_multi = getProp($anime, 'is_multi', 1);
  7112. $is_single = (int)$is_multi !== 1;
  7113. $extra_products = getProp($data, 'products', []);
  7114. if (!$extra_products) {
  7115. $extra_products = getProp($anime, 'extra_products');
  7116. if ($extra_products) {
  7117. $extra_products = json_decode($extra_products, true);
  7118. }else {
  7119. $extra_products = [];
  7120. }
  7121. }else {
  7122. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7123. }
  7124. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7125. $anime_script_id = getProp($anime, 'script_id');
  7126. if ($anime_script_id && $is_single) {
  7127. $cpid = Site::getCpid();
  7128. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7129. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7130. ->where('mapping.script_id', $anime_script_id)
  7131. ->where('product.cpid', $cpid)
  7132. ->where('product.is_deleted', 0);
  7133. $mappings = $script_products_mappings->select(
  7134. 'mapping.product_id',
  7135. 'mapping.episode_number',
  7136. 'product.product_name',
  7137. 'product.type',
  7138. 'product.product',
  7139. 'product.pic_prompt',
  7140. 'product.url',
  7141. 'product.pic_task_id',
  7142. 'product.pic_task_status',
  7143. 'product.three_view_image_url'
  7144. )
  7145. ->get();
  7146. // 按 product_id 分组,合并 episode_number
  7147. $productMap = [];
  7148. foreach ($mappings as $item) {
  7149. $product_id = $item->product_id;
  7150. $product_name = $item->product_name;
  7151. // 处理product_name两边的符号
  7152. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7153. if (!isset($productMap[$product_id])) {
  7154. $productMap[$product_id] = [
  7155. 'product_id' => $product_id,
  7156. 'product_name' => $product_name,
  7157. 'type' => (int)$item->type,
  7158. 'product' => (int)$item->product,
  7159. 'pic_prompt' => $item->pic_prompt,
  7160. 'url' => $item->url,
  7161. 'pic_task_id' => $item->pic_task_id,
  7162. 'pic_task_status' => $item->pic_task_status,
  7163. 'episode_numbers' => [],
  7164. ];
  7165. }
  7166. // 添加 episode_number(去重)
  7167. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7168. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7169. }
  7170. }
  7171. // 将查询到的剧本资产合并到extra_products中
  7172. // 先构建extra_products的索引(以product_id为key,用于去重)
  7173. $extraProductsMap = [];
  7174. foreach ($extra_products as $item) {
  7175. $key = getProp($item, 'product_id');
  7176. if ($key) {
  7177. $extraProductsMap[$key] = $item;
  7178. }
  7179. }
  7180. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  7181. foreach ($productMap as $product) {
  7182. $product_id = $product['product_id'];
  7183. // 如果不存在则添加(不带episode_number信息)
  7184. if (!isset($extraProductsMap[$product_id])) {
  7185. $extraProductsMap[$product_id] = [
  7186. 'product_id' => $product['product_id'],
  7187. 'product_name' => $product['product_name'],
  7188. 'type' => $product['type'],
  7189. 'product' => $product['product'],
  7190. 'pic_prompt' => $product['pic_prompt'],
  7191. 'url' => $product['url'],
  7192. 'pic_task_id' => $product['pic_task_id'],
  7193. 'pic_task_status' => $product['pic_task_status'],
  7194. ];
  7195. }
  7196. }
  7197. // 重新赋值给extra_products
  7198. $extra_products = array_values($extraProductsMap);
  7199. }
  7200. $user_anime_name = getProp($anime, 'anime_name');
  7201. $prompt = getProp($data, 'prompt');
  7202. // 处理提示词
  7203. if ($prompt && $extra_products) {
  7204. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7205. foreach($extra_products as $item) {
  7206. $product_name = getProp($item, 'product_name');
  7207. if ($product_name) {
  7208. // 替换 {product_name} 为 product_name
  7209. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7210. }
  7211. }
  7212. }
  7213. // 处理文本模型
  7214. $model = getProp($data, 'model');
  7215. if (!$model) {
  7216. // 用户没有输入,从anime表获取
  7217. $model = getProp($anime, 'model');
  7218. if (!$model) {
  7219. // anime表也没有,使用默认值
  7220. $model = 'deepseek-v4-pro';
  7221. }
  7222. }
  7223. // 验证模型是否在可用模型表中
  7224. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7225. $model = 'deepseek-v4-pro';
  7226. }
  7227. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  7228. if ($is_single) {
  7229. $episode_exists = DB::table('mp_anime_episodes')
  7230. ->where('anime_id', $anime_id)
  7231. ->where('sequence', 1)
  7232. ->exists();
  7233. if ($episode_exists) {
  7234. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  7235. }
  7236. }
  7237. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  7238. if ($prompt) {
  7239. $question .= "本次修改要求如下:\n{$prompt}";
  7240. }
  7241. // 提取文件内容
  7242. if ($file) {
  7243. $content = $this->extractFileContent($file);
  7244. if (!$content) {
  7245. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7246. }
  7247. } elseif ($script_id) {
  7248. $content = $this->getContentByScriptId($script_id);
  7249. if (!$content) {
  7250. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7251. }
  7252. } elseif ($bid) {
  7253. $content = $this->getContentByBid($bid);
  7254. if (!$content) {
  7255. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7256. }
  7257. } elseif ($content) {
  7258. $content = filterContent($content);
  7259. }else {
  7260. $content = filterContent(getProp($anime, 'content'));
  7261. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  7262. $need_generate_content = true;
  7263. }
  7264. }
  7265. // 判断是否需要生成原文内容
  7266. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  7267. // 如果需要生成原文内容,添加额外的要求
  7268. $content_generation_requirement = $need_generate_content
  7269. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  7270. : "";
  7271. // 美术风格
  7272. $input_art_style = getProp($data, 'art_style');
  7273. if (!$input_art_style) {
  7274. $mappedArtStyle = getProp($anime, 'art_style');
  7275. }else {
  7276. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7277. }
  7278. if (!$mappedArtStyle) {
  7279. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7280. }else {
  7281. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7282. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7283. }else {
  7284. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7285. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7286. }
  7287. }
  7288. // 构建主体、场景和道具提示词
  7289. $extra_role_prompt = "\n";
  7290. $extra_scene_prompt = "\n";
  7291. $extra_prop_prompt = "\n";
  7292. $ref_products = []; // 参考资产
  7293. if ($extra_products) {
  7294. foreach($extra_products as $item) {
  7295. $product = getProp($item, 'product');
  7296. $product_name = getProp($item, 'product_name');
  7297. if ($product_name == '旁白') continue;
  7298. $ref_products[$product_name] = $item;
  7299. $pic_prompt = getProp($item, 'pic_prompt');
  7300. if ((int)$product === 1) {
  7301. // 拼接角色信息
  7302. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7303. } elseif ((int)$product === 2) {
  7304. // 拼接场景信息
  7305. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7306. } elseif ((int)$product === 3) {
  7307. // 拼接道具信息
  7308. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  7309. }
  7310. }
  7311. // 优化提示词,融入剧本
  7312. if (!empty(trim($extra_role_prompt))) {
  7313. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7314. }
  7315. if (!empty(trim($extra_scene_prompt))) {
  7316. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7317. }
  7318. if (!empty(trim($extra_prop_prompt))) {
  7319. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7320. }
  7321. }
  7322. if ($anime_script_id && $is_single) {
  7323. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  7324. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  7325. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  7326. }else {
  7327. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7328. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7329. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7330. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7331. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7332. {$extra_role_prompt}";
  7333. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7334. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  7335. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7336. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7337. {$extra_scene_prompt}";
  7338. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7339. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  7340. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7341. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  7342. {$extra_prop_prompt}";
  7343. }
  7344. $system_message = ['role'=>'system', 'content'=>$is_single
  7345. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  7346. 强制要求:
  7347. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7348. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7349. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7350. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7351. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7352. 普通要求:
  7353. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  7354. $role_demo
  7355. $scene_demo
  7356. $prop_demo
  7357. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7358. 5.1片段分割逻辑(优先级从高到低):
  7359. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7360. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7361. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7362. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7363. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7364. - 片段数量格式为: 片段数量:8
  7365. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7366. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7367. 5.3分镜结构:每个分镜包含以下字段:
  7368. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7369. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7370. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7371. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7372. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7373. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7374. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7375. - 运镜:场景+画面描述+运镜
  7376. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7377. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7378. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7379. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  7380. 6.{$mappedArtStyle_prompt}\n\n
  7381. 示例如下:\n
  7382. ###剧本名:西昆仑
  7383. ###故事梗概
  7384. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7385. ###剧本亮点
  7386. 亮点1:绝境奇药,生死一线
  7387. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7388. 亮点2:结拜兄妹,化解尴尬
  7389. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7390. 亮点3:纤发夺命,情愫暗涌
  7391. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7392. ###人物关系
  7393. 阿雪与梁萧之间存在兄妹之情。
  7394. ###核心矛盾
  7395. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7396. ###主体列表
  7397. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7398. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7399. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7400. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7401. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7402. 全景,正面拍摄,青年女性,亚洲人。
  7403. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7404. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7405. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7406. ###美术风格
  7407. 基础画风风格词:厚涂古风
  7408. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7409. ###场景列表
  7410. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7411. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7412. 无人物。}
  7413. ###分段剧本
  7414. 片段数量:8
  7415. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7416. ##片段1
  7417. 时长:12s
  7418. 分镜1
  7419. 出场角色:刀疤脸
  7420. 场景:边境小镇街道
  7421. 出场道具:酒杯-高脚杯
  7422. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7423. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7424. 配音台词:
  7425. 背景音效:
  7426. 分镜2
  7427. 出场角色:刀疤脸
  7428. 场景:悦来酒馆
  7429. 出场道具:酒杯-高脚杯
  7430. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7431. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7432. 配音台词:
  7433. 背景音效:
  7434. 分镜3
  7435. 出场角色:刀疤脸
  7436. 场景:悦来酒馆
  7437. 出场道具:酒杯-高脚杯
  7438. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7439. 运镜:从中景推向令牌特写。
  7440. 配音台词:
  7441. 背景音效:
  7442. 分镜4
  7443. 出场角色:刀疤脸
  7444. 场景:悦来酒馆
  7445. 出场道具:酒杯-高脚杯
  7446. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7447. 运镜:极速推向酒水溅起的瞬间。
  7448. 配音台词:
  7449. 背景音效:
  7450. 分镜5
  7451. 出场角色:刀疤脸
  7452. 场景:悦来酒馆
  7453. 出场道具:酒杯-高脚杯
  7454. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7455. 运镜:固定机位,利用倾斜构图制造压迫感。
  7456. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7457. 背景音效:
  7458. \n\n"
  7459. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7460. 强制要求:\n
  7461. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7462. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7463. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7464. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7465. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7466. 普通要求:\n
  7467. 1.剧本名(必须生成)必须与文档内容高度相关
  7468. $role_demo
  7469. $scene_demo
  7470. $prop_demo
  7471. 5.{$mappedArtStyle_prompt}\n\n
  7472. 示例如下:\n
  7473. ###剧本名:西昆仑
  7474. ###故事梗概
  7475. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7476. ###剧本亮点
  7477. 亮点1:绝境奇药,生死一线
  7478. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7479. 亮点2:结拜兄妹,化解尴尬
  7480. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7481. 亮点3:纤发夺命,情愫暗涌
  7482. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7483. ###人物关系
  7484. 阿雪与梁萧之间存在兄妹之情。
  7485. ###核心矛盾
  7486. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7487. ###主体列表
  7488. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7489. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7490. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7491. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7492. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7493. 全景,正面拍摄,青年女性,亚洲人。
  7494. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7495. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7496. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7497. ###美术风格
  7498. 基础画风风格词:厚涂古风
  7499. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7500. ###场景列表
  7501. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7502. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7503. 无人物。}
  7504. ###道具列表
  7505. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  7506. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  7507. $episode_count = $this->extractEpisodeNumber($prompt);
  7508. if ((int)getProp($anime, 'is_multi') !== 1) {
  7509. yield [
  7510. 'type' => 'done',
  7511. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  7512. 'reasoning' => '',
  7513. 'usage' => []
  7514. ];
  7515. return;
  7516. }
  7517. if ($episode_count) {
  7518. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  7519. $system_message = [
  7520. 'role' => 'system',
  7521. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7522. 强制要求:\n
  7523. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7524. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7525. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7526. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  7527. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  7528. 普通要求:\n
  7529. 1.<故事梗概>控制在200-300字左右
  7530. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7531. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7532. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  7533. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7534. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7535. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7536. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7537. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7538. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  7539. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  7540. 示例如下:\n
  7541. ###剧本名:西昆仑
  7542. ###故事梗概
  7543. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7544. ###剧本亮点
  7545. 亮点1:绝境奇药,生死一线
  7546. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  7547. 亮点2:结拜兄妹,化解尴尬
  7548. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  7549. 亮点3:纤发夺命,情愫暗涌
  7550. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  7551. ###人物关系
  7552. 阿雪与梁萧之间存在兄妹之情。
  7553. ###核心矛盾
  7554. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  7555. ###主体列表
  7556. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  7557. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  7558. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  7559. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  7560. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  7561. 全景,正面拍摄,青年女性,亚洲人。
  7562. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  7563. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  7564. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7565. ###美术风格
  7566. 基础画风风格词:厚涂古风
  7567. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  7568. ###场景列表
  7569. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  7570. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  7571. 无人物。}
  7572. ###分集详细内容
  7573. ##第1章 重生
  7574. 我重生了。
  7575. 源于一个男人偏执的暗恋。
  7576. ##第2章 相救
  7577. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  7578. 我眼睛扫向站在锅炉后的卞大伟。"
  7579. ];
  7580. // 构建消息
  7581. $messages = [
  7582. $system_message,
  7583. [
  7584. 'role' => 'user',
  7585. 'content' => "以下是文档内容:
  7586. {$content}
  7587. 用户问题:
  7588. {$question}"
  7589. ]
  7590. ];
  7591. }else {
  7592. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  7593. // 构建消息
  7594. $messages = [
  7595. $system_message,
  7596. [
  7597. 'role' => 'user',
  7598. 'content' => "以下是文档内容:
  7599. {$content}
  7600. 用户问题:
  7601. {$question}"
  7602. ]
  7603. ];
  7604. }else {
  7605. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  7606. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  7607. return (array)$value;
  7608. })->toArray();
  7609. array_unshift($messages, $system_message);
  7610. $messages[] = [
  7611. 'role' => 'user',
  7612. 'content' => $prompt
  7613. ];
  7614. }
  7615. }
  7616. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7617. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7618. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7619. if ($model === 'deepseek-chat') {
  7620. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7621. $model = 'deepseek-v4-flash';
  7622. $thinkingMode = 'disabled';
  7623. } elseif ($model === 'deepseek-reasoner') {
  7624. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7625. $model = 'deepseek-v4-flash';
  7626. $thinkingMode = 'enabled';
  7627. }
  7628. $post_data = [
  7629. 'model' => $model,
  7630. 'messages' => $messages,
  7631. // 'max_tokens' => 8192,
  7632. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7633. 'frequency_penalty' => 0,
  7634. 'presence_penalty' => 0,
  7635. 'response_format' => ['type' => 'text'],
  7636. 'thinking' => ['type' => $thinkingMode],
  7637. 'stream' => true // 启用流式输出
  7638. ];
  7639. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7640. // 根据模型类型选择调用方法
  7641. $fullContent = '';
  7642. $fullReasoningContent = '';
  7643. $usage = [];
  7644. // dd($post_data);
  7645. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  7646. try {
  7647. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7648. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7649. } else if (in_array($model, $this->gpt_text_models)) {
  7650. // GPT-5.4 模型使用 TokenRouter API
  7651. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7652. } else if (in_array($model, $this->gemini_text_models)) {
  7653. // Gemini 模型使用 Gemini API
  7654. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  7655. } else {
  7656. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7657. }
  7658. // 验证返回值类型
  7659. if (!is_iterable($streamGenerator)) {
  7660. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7661. dLog('deepseek')->error('方法名流式生成器无效', [
  7662. 'generator_type' => $errorType,
  7663. 'model' => $model,
  7664. // 添加其他上下文信息
  7665. ]);
  7666. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  7667. 'type' => $errorType,
  7668. 'model' => $model
  7669. ]);
  7670. yield [
  7671. 'type' => 'error',
  7672. // 根据方法返回相应的空数据结构
  7673. 'answer' => '',
  7674. 'reasoning' => '',
  7675. 'usage' => [],
  7676. 'error' => '接口返回数据异常,请重新请求'
  7677. ];
  7678. return;
  7679. }
  7680. // 处理流式输出
  7681. foreach ($streamGenerator as $chunk) {
  7682. if (isset($chunk['type'])) {
  7683. if ($chunk['type'] === 'done') {
  7684. $fullContent = $chunk['full_content'];
  7685. $fullReasoningContent = $chunk['full_reasoning'];
  7686. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7687. } else {
  7688. yield $chunk;
  7689. }
  7690. }
  7691. }
  7692. } catch (\Exception $e) {
  7693. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  7694. 'model' => $model,
  7695. 'trace' => $e->getTraceAsString()
  7696. ]);
  7697. logDB('deepseek', 'error', '方法名流式处理失败', [
  7698. 'error' => $e->getMessage(),
  7699. 'model' => $model
  7700. ]);
  7701. yield [
  7702. 'type' => 'error',
  7703. // 根据方法返回相应的空数据结构
  7704. 'answer' => '',
  7705. 'reasoning' => '',
  7706. 'usage' => [],
  7707. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7708. ];
  7709. return;
  7710. }
  7711. dLog('deepseek')->info('完整内容: '.$fullContent);
  7712. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7713. // 处理完整内容并返回最终结果
  7714. $script_arr = [];
  7715. if ($fullContent) {
  7716. $script_arr = handleScriptContentForAce($fullContent);
  7717. dLog('deepseek')->info('解析内容', $script_arr);
  7718. logDB('deepseek', 'info', '解析内容', $script_arr);
  7719. }
  7720. if (empty($script_arr['roles'])) {
  7721. // 未生成剧本相关内容,保存对话记录并返回提示
  7722. dLog('deepseek')->info('未生成剧本相关的内容');
  7723. try {
  7724. $now = date('Y-m-d H:i:s');
  7725. // 保存对话记录
  7726. $records = [
  7727. [
  7728. 'uid' => $uid,
  7729. 'anime_id' => $anime_id,
  7730. 'sequence' => 0,
  7731. 'role' => 'user',
  7732. 'content' => $prompt,
  7733. 'created_at' => $now,
  7734. 'updated_at' => $now
  7735. ],
  7736. [
  7737. 'uid' => $uid,
  7738. 'anime_id' => $anime_id,
  7739. 'sequence' => 0,
  7740. 'role' => 'assistant',
  7741. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  7742. 'created_at' => $now,
  7743. 'updated_at' => $now
  7744. ]
  7745. ];
  7746. DB::table('mp_anime_records')->insert($records);
  7747. } catch (\Exception $e) {
  7748. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7749. }
  7750. yield [
  7751. 'type' => 'done',
  7752. 'script' => [],
  7753. 'episode' => [],
  7754. 'answer' => $fullContent,
  7755. 'reasoning' => $fullReasoningContent,
  7756. 'usage' => $usage,
  7757. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  7758. ];
  7759. return;
  7760. }
  7761. // 替换美术风格
  7762. if ($mappedArtStyle !== '') {
  7763. $script_arr['art_style'] = $mappedArtStyle;
  7764. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  7765. }
  7766. if ($user_anime_name != '新剧本策划') {
  7767. $anime_name = trim((string)getProp($script_arr, 'script_name'));
  7768. $anime_name = preg_replace('/^[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+|[\s\x{3000}*《》〈〉「」『』【】\[\][]{}()()]+$/u', '', $anime_name) ?? $anime_name;
  7769. // 确认对话名称唯一性
  7770. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  7771. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  7772. }
  7773. }else {
  7774. $anime_name = $user_anime_name;
  7775. }
  7776. $table_data = [
  7777. 'user_id' => $uid,
  7778. 'model' => $model,
  7779. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  7780. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  7781. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  7782. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  7783. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  7784. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  7785. 'art_style_type' => $input_art_style,
  7786. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  7787. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  7788. 'status' => '解析完成',
  7789. 'generate_status' => '待执行',
  7790. 'updated_at' => date('Y-m-d H:i:s')
  7791. ];
  7792. if ($anime_name) $table_data['anime_name'] = $anime_name;
  7793. // 如果是修改集数,则将content内容更新(会改变原文)
  7794. if (isset($episode_count) && $episode_count > 0) {
  7795. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  7796. $table_data['start_episode_sequence'] = 1;
  7797. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  7798. }else {
  7799. // 如果需要生成原文内容,从script_arr中提取
  7800. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  7801. $table_data['content'] = $script_arr['content'];
  7802. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  7803. if (!$table_data['content']) {
  7804. yield [
  7805. 'type' => 'done',
  7806. 'script' => [],
  7807. 'episode' => [],
  7808. 'answer' => $fullContent,
  7809. 'reasoning' => $fullReasoningContent,
  7810. 'usage' => $usage,
  7811. 'error' => '未生成剧本内容,请调整提示词再试'
  7812. ];
  7813. return;
  7814. }
  7815. }
  7816. if (isset($table_data['content']) && $table_data['content']) {
  7817. $chapters = splitContent($table_data['content']);
  7818. $chapter_count = count($chapters);
  7819. if ($chapter_count > 0) {
  7820. $table_data['start_episode_sequence'] = 1;
  7821. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  7822. }
  7823. }
  7824. }
  7825. if ($extra_products) {
  7826. $table_data['extra_products'] = json_encode($extra_products, 256);
  7827. }
  7828. $single_episode = [];
  7829. try {
  7830. DB::beginTransaction();
  7831. $now = date('Y-m-d H:i:s');
  7832. // 更新动漫大纲
  7833. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7834. if (!$boolen) {
  7835. dLog('deepseek')->info('对话修改失败', $table_data);
  7836. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  7837. Utils::throwError('20003:对话修改失败');
  7838. }
  7839. // 保存对话记录
  7840. $records = [
  7841. [
  7842. 'uid' => $uid,
  7843. 'anime_id' => $anime_id,
  7844. 'sequence' => 0,
  7845. 'role' => 'user',
  7846. 'content' => $prompt,
  7847. 'created_at' => $now,
  7848. 'updated_at' => $now
  7849. ],
  7850. [
  7851. 'uid' => $uid,
  7852. 'anime_id' => $anime_id,
  7853. 'sequence' => 0,
  7854. 'role' => 'assistant',
  7855. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7856. 'content' => $fullContent,
  7857. 'created_at' => $now,
  7858. 'updated_at' => $now
  7859. ]
  7860. ];
  7861. // 保存对话记录
  7862. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7863. if (!$boolen3) {
  7864. Utils::throwError('20003:对话记录保存失败');
  7865. }
  7866. // 单剧集模式:生成并保存剧集信息
  7867. if ($is_single) {
  7868. $anime_name = getProp($anime, 'anime_name', '未命名');
  7869. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7870. if (empty($episode_arr['acts'])) {
  7871. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7872. }
  7873. $saveResult = $this->saveEpisodeVersionData(
  7874. $anime_id,
  7875. 1,
  7876. $episode_arr,
  7877. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7878. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7879. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7880. null,
  7881. null,
  7882. false,
  7883. $content,
  7884. $now,
  7885. $ref_products
  7886. );
  7887. $single_episode = $saveResult['episode'];
  7888. $episode_id = $saveResult['episode_id'];
  7889. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7890. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7891. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7892. 'props' => json_encode($saveResult['merged_props'], 256),
  7893. 'updated_at' => $now
  7894. ]);
  7895. if ($boolen5 === false) {
  7896. Utils::throwError('20003:单剧集主表资源同步失败');
  7897. }
  7898. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7899. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7900. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7901. $episode_record_content = '确认分镜大纲';
  7902. if ($content !== '') {
  7903. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7904. }
  7905. $episode_records = [
  7906. [
  7907. 'uid' => $uid,
  7908. 'anime_id' => $anime_id,
  7909. 'role' => 'user',
  7910. 'content' => $episode_record_content,
  7911. 'sequence' => 1,
  7912. 'episode_id' => $episode_id,
  7913. 'created_at' => $now,
  7914. 'updated_at' => $now
  7915. ],
  7916. [
  7917. 'uid' => $uid,
  7918. 'anime_id' => $anime_id,
  7919. 'role' => 'assistant',
  7920. 'content' => $fullContent,
  7921. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7922. 'sequence' => 1,
  7923. 'episode_id' => $episode_id,
  7924. 'created_at' => $now,
  7925. 'updated_at' => $now
  7926. ]
  7927. ];
  7928. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7929. if (!$boolen4) {
  7930. Utils::throwError('20003:单剧集分镜记录保存失败');
  7931. }
  7932. }
  7933. }catch (\Exception $e) {
  7934. DB::rollBack();
  7935. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  7936. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  7937. yield [
  7938. 'type' => 'done',
  7939. 'answer' => $fullContent,
  7940. 'reasoning' => $fullReasoningContent,
  7941. 'usage' => $usage,
  7942. 'error' => $e->getMessage(),
  7943. ];
  7944. return;
  7945. }
  7946. DB::commit();
  7947. dLog('deepseek')->info('保存完毕');
  7948. if ($is_single && !empty($single_episode)) {
  7949. // $this->batchSetGlobalRoleImg([
  7950. // 'anime_id' => $anime_id,
  7951. // ]);
  7952. // $this->batchSetGlobalSceneImg([
  7953. // 'anime_id' => $anime_id,
  7954. // ]);
  7955. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7956. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7957. }
  7958. $table_data['anime_id'] = $anime_id;
  7959. $table_data['roles'] = json_decode($table_data['roles'], true);
  7960. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7961. $table_data['props'] = json_decode($table_data['props'], true);
  7962. unset($table_data['updated_at']);
  7963. unset($table_data['status']);
  7964. yield [
  7965. 'type' => 'done',
  7966. 'script' => $table_data,
  7967. 'episode' => $single_episode,
  7968. 'answer' => $fullContent,
  7969. 'reasoning' => $fullReasoningContent,
  7970. 'usage' => $usage
  7971. ];
  7972. }
  7973. public function chatForAce($data) {
  7974. $uid = Site::getUid();
  7975. $anime_id = getProp($data, 'anime_id');
  7976. $file = getProp($data, 'file');
  7977. $content = getProp($data, 'content', '');
  7978. $bid = getProp($data, 'bid', 0);
  7979. $script_id = getProp($data, 'script_id', 0);
  7980. $episode_number = getProp($data, 'episode_number', 1);
  7981. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7982. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7983. if (!$anime) Utils::throwError('20003:该对话不存在!');
  7984. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  7985. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  7986. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  7987. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  7988. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  7989. $roles = is_array($roles) ? $roles : [];
  7990. $scenes = is_array($scenes) ? $scenes : [];
  7991. $extra_products = getProp($data, 'products', []);
  7992. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7993. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7994. $anime_script_id = getProp($anime, 'script_id');
  7995. if ($anime_script_id) {
  7996. $cpid = Site::getCpid();
  7997. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7998. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7999. ->where('mapping.script_id', $anime_script_id)
  8000. ->where('product.cpid', $cpid)
  8001. ->where('product.is_deleted', 0);
  8002. // 如果提供了 episode_number,则过滤指定集数
  8003. if ($episode_number !== null && $episode_number !== '') {
  8004. $script_products_mappings->where('mapping.episode_number', $episode_number);
  8005. }
  8006. $mappings = $script_products_mappings->select(
  8007. 'mapping.product_id',
  8008. 'mapping.episode_number',
  8009. 'product.product_name',
  8010. 'product.type',
  8011. 'product.product',
  8012. 'product.pic_prompt',
  8013. 'product.url',
  8014. 'product.pic_task_id',
  8015. 'product.pic_task_status',
  8016. 'product.three_view_image_url'
  8017. )
  8018. ->get();
  8019. // 按 product_id 分组,合并 episode_number
  8020. $productMap = [];
  8021. foreach ($mappings as $item) {
  8022. $product_id = $item->product_id;
  8023. $product_name = $item->product_name;
  8024. // 处理product_name两边的符号
  8025. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  8026. if (!isset($productMap[$product_id])) {
  8027. $productMap[$product_id] = [
  8028. 'product_id' => $product_id,
  8029. 'product_name' => $product_name,
  8030. 'type' => (int)$item->type,
  8031. 'product' => (int)$item->product,
  8032. 'pic_prompt' => $item->pic_prompt,
  8033. 'url' => $item->url,
  8034. 'pic_task_id' => $item->pic_task_id,
  8035. 'pic_task_status' => $item->pic_task_status,
  8036. 'episode_numbers' => [],
  8037. ];
  8038. }
  8039. // 添加 episode_number(去重)
  8040. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  8041. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  8042. }
  8043. }
  8044. // 将查询到的剧本资产合并到extra_products中
  8045. // 先构建extra_products的索引(以product_id+episode_number为key)
  8046. $extraProductsMap = [];
  8047. foreach ($extra_products as $item) {
  8048. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  8049. $extraProductsMap[$key] = $item;
  8050. }
  8051. // 合并剧本资产(去重:product_id+episode_number)
  8052. foreach ($productMap as $product) {
  8053. foreach ($product['episode_numbers'] as $ep_num) {
  8054. $key = $product['product_id'] . '_' . $ep_num;
  8055. // 如果不存在则添加
  8056. if (!isset($extraProductsMap[$key])) {
  8057. $extraProductsMap[$key] = [
  8058. 'product_id' => $product['product_id'],
  8059. 'product_name' => $product['product_name'],
  8060. 'type' => $product['type'],
  8061. 'product' => $product['product'],
  8062. 'pic_prompt' => $product['pic_prompt'],
  8063. 'url' => $product['url'],
  8064. 'pic_task_id' => $product['pic_task_id'],
  8065. 'pic_task_status' => $product['pic_task_status'],
  8066. 'episode_number' => $ep_num,
  8067. ];
  8068. }
  8069. }
  8070. }
  8071. // 重新赋值给extra_products
  8072. $extra_products = array_values($extraProductsMap);
  8073. }
  8074. // 处理提示词
  8075. if ($prompt && $extra_products) {
  8076. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  8077. foreach($extra_products as $item) {
  8078. $product_name = getProp($item, 'product_name');
  8079. if ($product_name) {
  8080. // 替换 {product_name} 为 product_name
  8081. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  8082. }
  8083. }
  8084. }
  8085. // 获取最后一集序号
  8086. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  8087. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  8088. // 转换主体列表和场景列表的格式
  8089. // 获取参考主体或场景
  8090. if ((int)$episode_number === 1) {
  8091. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  8092. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  8093. }else {
  8094. $prev_episode_number = $episode_number - 1;
  8095. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  8096. }
  8097. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  8098. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  8099. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  8100. // 合并anime_products和extra_products(extra_products优先,去重)
  8101. $anime_products = getProp($anime, 'extra_products');
  8102. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  8103. $ref_products = [];
  8104. foreach($anime_products as $item) {
  8105. $product_name = getProp($item, 'product_name');
  8106. $ref_products[$product_name] = $item;
  8107. }
  8108. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  8109. $extra_roles = []; // 从extra_products中提取的角色
  8110. $extra_scenes = []; // 从extra_products中提取的场景
  8111. $extra_props = []; // 从extra_products中提取的道具
  8112. if ($extra_products && is_array($extra_products)) {
  8113. foreach($extra_products as $item) {
  8114. $product = (int)getProp($item, 'product');
  8115. $product_name = getProp($item, 'product_name');
  8116. if ($product_name == '旁白') continue;
  8117. $pic_prompt = getProp($item, 'pic_prompt');
  8118. $ref_products[$product_name] = $item;
  8119. if ($product === 1) {
  8120. // 角色
  8121. $extra_roles[$product_name] = [
  8122. 'role' => $product_name,
  8123. 'pic_prompt' => $pic_prompt,
  8124. 'url' => getProp($item, 'url', ''),
  8125. ];
  8126. } elseif ($product === 2) {
  8127. // 场景
  8128. $extra_scenes[$product_name] = [
  8129. 'scene' => $product_name,
  8130. 'pic_prompt' => $pic_prompt,
  8131. 'url' => getProp($item, 'url', ''),
  8132. ];
  8133. } elseif ($product === 3) {
  8134. // 道具
  8135. $extra_props[$product_name] = [
  8136. 'prop' => $product_name,
  8137. 'pic_prompt' => $pic_prompt,
  8138. 'url' => getProp($item, 'url', ''),
  8139. ];
  8140. }
  8141. }
  8142. }
  8143. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  8144. $merged_roles = [];
  8145. foreach($ref_roles as $role) {
  8146. $role_name = getProp($role, 'role');
  8147. if (!isset($extra_roles[$role_name])) {
  8148. $merged_roles[$role_name] = $role;
  8149. }
  8150. }
  8151. // 添加extra_roles
  8152. foreach($extra_roles as $role_name => $role) {
  8153. $merged_roles[$role_name] = $role;
  8154. }
  8155. $ref_roles = array_values($merged_roles);
  8156. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  8157. $merged_scenes = [];
  8158. foreach($ref_scenes as $scene) {
  8159. $scene_name = getProp($scene, 'scene');
  8160. if (!isset($extra_scenes[$scene_name])) {
  8161. $merged_scenes[$scene_name] = $scene;
  8162. }
  8163. }
  8164. // 添加extra_scenes
  8165. foreach($extra_scenes as $scene_name => $scene) {
  8166. $merged_scenes[$scene_name] = $scene;
  8167. }
  8168. $ref_scenes = array_values($merged_scenes);
  8169. // 合并ref_props和extra_props(extra_props优先,去重)
  8170. $merged_props = [];
  8171. foreach($ref_props as $prop) {
  8172. $prop_name = getProp($prop, 'prop');
  8173. if (!isset($extra_props[$prop_name])) {
  8174. $merged_props[$prop_name] = $prop;
  8175. }
  8176. }
  8177. // 添加extra_props
  8178. foreach($extra_props as $prop_name => $prop) {
  8179. $merged_props[$prop_name] = $prop;
  8180. }
  8181. $ref_props = array_values($merged_props);
  8182. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  8183. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  8184. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  8185. // 构建强制主体、场景和道具提示词
  8186. $forced_roles_prompt = "";
  8187. $forced_scenes_prompt = "";
  8188. $forced_props_prompt = "";
  8189. if (!empty($extra_roles)) {
  8190. $forced_roles_list = "";
  8191. foreach($extra_roles as $role_name => $role) {
  8192. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  8193. }
  8194. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  8195. }
  8196. if (!empty($extra_scenes)) {
  8197. $forced_scenes_list = "";
  8198. foreach($extra_scenes as $scene_name => $scene) {
  8199. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  8200. }
  8201. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  8202. }
  8203. if (!empty($extra_props)) {
  8204. $forced_props_list = "";
  8205. foreach($extra_props as $prop_name => $prop) {
  8206. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  8207. }
  8208. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  8209. }
  8210. if ($anime_script_id) {
  8211. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  8212. }else if ($roles_content) {
  8213. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  8214. 主体范围:\n {$roles_content}\n
  8215. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  8216. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8217. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8218. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8219. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8220. }else {
  8221. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  8222. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  8223. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  8224. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  8225. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  8226. }
  8227. if ($anime_script_id) {
  8228. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  8229. }else if ($scenes_content) {
  8230. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8231. 场景范围:\n {$scenes_content}\n
  8232. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  8233. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  8234. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8235. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8236. }else {
  8237. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8238. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  8239. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  8240. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  8241. }
  8242. if ($anime_script_id) {
  8243. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  8244. }else if ($props_content) {
  8245. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  8246. 道具范围:\n {$props_content}\n
  8247. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  8248. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  8249. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8250. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8251. }else {
  8252. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  8253. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  8254. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  8255. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  8256. }
  8257. // 提取文件内容
  8258. if ($file) {
  8259. $uploaded_content = $this->extractFileContent($file);
  8260. if (!$uploaded_content) {
  8261. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  8262. }
  8263. } elseif ($script_id) {
  8264. $uploaded_content = $this->getContentByScriptId($script_id);
  8265. if (!$uploaded_content) {
  8266. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  8267. }
  8268. } elseif ($bid) {
  8269. $uploaded_content = $this->getContentByBid($bid);
  8270. if (!$uploaded_content) {
  8271. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  8272. }
  8273. } elseif ($content) {
  8274. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  8275. }
  8276. // elseif ($prompt) {
  8277. // $uploaded_content = filterContent($prompt);
  8278. // }
  8279. else {
  8280. $uploaded_content = '';
  8281. }
  8282. // 美术风格
  8283. $input_art_style = getProp($data, 'art_style');
  8284. if (!$input_art_style) {
  8285. $mappedArtStyle = getProp($anime, 'art_style');
  8286. }else {
  8287. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  8288. }
  8289. if (!$mappedArtStyle) {
  8290. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  8291. }else {
  8292. if (strstr($mappedArtStyle, '基础画风风格词')) {
  8293. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  8294. }else {
  8295. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  8296. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  8297. }
  8298. }
  8299. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8300. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  8301. // 强制要求:
  8302. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  8303. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  8304. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  8305. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  8306. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  8307. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  8308. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  8309. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  8310. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  8311. // 10.分镜要和场景列表、人物主体保持一致\n
  8312. // 普通要求:
  8313. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8314. // {$role_demo}
  8315. // {$scene_demo}
  8316. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8317. // 4.1片段分割逻辑(优先级从高到低):
  8318. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8319. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8320. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8321. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8322. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8323. // - 片段数量格式为: 片段数量:8
  8324. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8325. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8326. // 4.3分镜结构:每个分镜包含以下字段:
  8327. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  8328. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  8329. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8330. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  8331. // - 运镜:场景+画面描述+运镜
  8332. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  8333. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8334. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8335. // 5.$mappedArtStyle_prompt\n\n
  8336. // 示例格式:\n
  8337. // 第1集:隐形的守护者
  8338. // ###故事梗概
  8339. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8340. // ###美术风格
  8341. // 基础画风风格词:胡金铨武侠
  8342. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8343. // ###主体列表
  8344. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8345. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8346. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8347. // ###场景列表
  8348. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8349. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8350. // ###分段剧本
  8351. // 片段数量:8
  8352. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8353. // ##片段1
  8354. // 时长:12s
  8355. // 分镜1
  8356. // 场景:边境小镇街道
  8357. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8358. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8359. // 配音台词:
  8360. // 背景音效:
  8361. // 分镜2
  8362. // 场景:悦来酒馆
  8363. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8364. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8365. // 配音台词:
  8366. // 背景音效:
  8367. // 分镜3
  8368. // 场景:悦来酒馆
  8369. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8370. // 运镜:从中景推向令牌特写。
  8371. // 配音台词:
  8372. // 背景音效:
  8373. // 分镜4
  8374. // 场景:悦来酒馆
  8375. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8376. // 运镜:极速推向酒水溅起的瞬间。
  8377. // 配音台词:
  8378. // 背景音效:
  8379. // 分镜5
  8380. // 镜头描述
  8381. // 场景:悦来酒馆
  8382. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8383. // 运镜:固定机位,利用倾斜构图制造压迫感。
  8384. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8385. // 背景音效:
  8386. // \n\n";
  8387. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  8388. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  8389. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  8390. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  8391. 强制要求:
  8392. 不要返回任何json格式的内容,我需要的是纯文本内容返回。
  8393. 普通要求:
  8394. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  8395. {$role_demo}
  8396. {$scene_demo}
  8397. {$prop_demo}
  8398. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  8399. 5.1片段分割逻辑(优先级从高到低):
  8400. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  8401. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  8402. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  8403. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  8404. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  8405. - 片段数量格式为: 片段数量:8
  8406. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  8407. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  8408. 5.3分镜结构:每个分镜包含以下字段:
  8409. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  8410. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8411. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8412. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8413. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  8414. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8415. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  8416. - 运镜:场景+画面描述+运镜
  8417. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  8418. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  8419. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  8420. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  8421. 6.《情绪-视听语言映射表》:
  8422. 6.1 场景空间与时间心理学 (Scene & Temporality)
  8423. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8424. -----|---------|------------|----------------
  8425. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  8426. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  8427. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  8428. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  8429. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  8430. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  8431. -----|---------|------------|----------------
  8432. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  8433. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  8434. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  8435. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  8436. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  8437. --------|---------|--------------|-------------
  8438. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  8439. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  8440. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  8441. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  8442. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  8443. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  8444. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  8445. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  8446. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  8447. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  8448. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  8449. -----|---------|------------|------------
  8450. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  8451. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  8452. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  8453. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  8454. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  8455. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  8456. --------|---------|--------------|----------
  8457. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  8458. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  8459. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  8460. 6.6 声音设计与潜意识影响 (Soundscape)
  8461. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  8462. -----|---------|------------|------------------
  8463. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  8464. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  8465. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  8466. 理论基石:
  8467. - The Five C's of Cinematography by Joseph V. Mascelli
  8468. - Film Art: An Introduction by David Bordwell
  8469. - Sight, Sound, Motion by Herbert Zettl
  8470. - Notes on the Cinematograph by Robert Bresson
  8471. \n\n
  8472. 7.{$mappedArtStyle_prompt}
  8473. 示例格式:\n
  8474. 第1集:隐形的守护者
  8475. ###故事梗概
  8476. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  8477. ###美术风格
  8478. 基础画风风格词:胡金铨武侠
  8479. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  8480. ###主体列表
  8481. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  8482. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  8483. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  8484. ###场景列表
  8485. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  8486. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  8487. ###道具列表
  8488. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  8489. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  8490. ###分段剧本
  8491. 片段数量:8
  8492. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8493. ##片段1
  8494. 时长:12s
  8495. 分镜1
  8496. 出场角色:刀疤脸
  8497. 场景:边境小镇街道
  8498. 出场道具:酒杯-高脚杯
  8499. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8500. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8501. 配音台词:
  8502. 背景音效:
  8503. 分镜2
  8504. 出场角色:刀疤脸
  8505. 场景:悦来酒馆
  8506. 出场道具:酒杯-高脚杯
  8507. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8508. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8509. 配音台词:
  8510. 背景音效:
  8511. 分镜3
  8512. 出场角色:刀疤脸
  8513. 场景:悦来酒馆
  8514. 出场道具:酒杯-高脚杯
  8515. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8516. 运镜:从中景推向令牌特写。
  8517. 配音台词:
  8518. 背景音效:
  8519. 分镜4
  8520. 出场角色:刀疤脸
  8521. 场景:悦来酒馆
  8522. 出场道具:酒杯-高脚杯
  8523. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8524. 运镜:极速推向酒水溅起的瞬间。
  8525. 配音台词:
  8526. 背景音效:
  8527. 分镜5
  8528. 出场角色:刀疤脸
  8529. 场景:悦来酒馆
  8530. 出场道具:酒杯-高脚杯
  8531. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8532. 运镜:固定机位,利用倾斜构图制造压迫感。
  8533. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8534. 背景音效:
  8535. \n\n";
  8536. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  8537. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  8538. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  8539. $prompt = $origin_prompt;
  8540. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  8541. // 获取章节内容
  8542. $full_content = getProp($anime, 'content');
  8543. if ($uploaded_content) {
  8544. $full_content = $uploaded_content;
  8545. }
  8546. // 根据章节内容拆分章节
  8547. $chapters = splitContent($full_content);
  8548. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  8549. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  8550. $messages = [];
  8551. if ($prompt == '确认分镜大纲') {
  8552. // 暂时保留
  8553. $content = $chapter_content;
  8554. if ($is_single) $content = $full_content; // 单剧集使用全文
  8555. if (!$content) {
  8556. Utils::throwError('20003:章节内容无法获取,请确认');
  8557. }
  8558. $question = $is_single
  8559. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  8560. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  8561. // 构建消息
  8562. $messages[] =
  8563. [
  8564. 'role' => 'user',
  8565. 'content' => $question
  8566. ];
  8567. }else if ($prompt == '继续策划下一集') {
  8568. if ($is_single) {
  8569. Utils::throwError('20003:单剧集不支持继续策划下一集');
  8570. }
  8571. $content = $chapter_content;
  8572. if (!$content) {
  8573. Utils::throwError('20003:章节内容无法获取,请确认');
  8574. }
  8575. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  8576. // 获取上一集最后记录
  8577. $prev_sequence = $episode_number - 1;
  8578. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  8579. // 构建消息
  8580. $messages[] =
  8581. [
  8582. 'role' => 'user',
  8583. 'content' => $question
  8584. ];
  8585. // dd($messages);
  8586. }else {
  8587. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  8588. if (!$content) {
  8589. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  8590. }
  8591. if (!$content) {
  8592. Utils::throwError('20003:章节内容无法获取,请确认');
  8593. }
  8594. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  8595. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  8596. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  8597. if ($origin_prompt) {
  8598. $question .= "本次修改要求如下:\n{$origin_prompt}";
  8599. }
  8600. $messages[] =
  8601. [
  8602. 'role' => 'user',
  8603. 'content' => $question
  8604. ];
  8605. }
  8606. // 处理文本模型
  8607. $model = getProp($data, 'model');
  8608. if (!$model) {
  8609. // 用户没有输入,从anime表获取
  8610. $model = getProp($anime, 'model');
  8611. if (!$model) {
  8612. // anime表也没有,使用默认值
  8613. $model = 'deepseek-v4-pro';
  8614. }
  8615. }
  8616. // 验证模型是否在可用模型表中
  8617. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8618. $model = 'deepseek-v4-pro';
  8619. }
  8620. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  8621. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  8622. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  8623. if ($model === 'deepseek-chat') {
  8624. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  8625. $model = 'deepseek-v4-flash';
  8626. $thinkingMode = 'disabled';
  8627. } elseif ($model === 'deepseek-reasoner') {
  8628. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  8629. $model = 'deepseek-v4-flash';
  8630. $thinkingMode = 'enabled';
  8631. }
  8632. $post_data = [
  8633. 'model' => $model,
  8634. 'messages' => $messages,
  8635. // 'max_tokens' => 8192,
  8636. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8637. 'frequency_penalty' => 0,
  8638. 'presence_penalty' => 0,
  8639. 'response_format' => ['type' => 'text'],
  8640. 'thinking' => ['type' => $thinkingMode],
  8641. 'stream' => true // 启用流式输出
  8642. ];
  8643. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8644. // 根据模型类型选择调用方法
  8645. $fullContent = '';
  8646. $fullReasoningContent = '';
  8647. $usage = [];
  8648. try {
  8649. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8650. // DeepSeek 官方模型使用 DeepSeek API
  8651. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8652. } else if (in_array($model, $this->gpt_text_models)) {
  8653. // GPT-5.4 模型使用 TokenRouter API
  8654. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8655. } else if (in_array($model, $this->gemini_text_models)) {
  8656. // Gemini 模型使用 Gemini API
  8657. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8658. } else {
  8659. // 其他模型使用火山引擎API
  8660. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8661. }
  8662. // 验证返回值类型
  8663. if (!is_iterable($streamGenerator)) {
  8664. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  8665. dLog('deepseek')->error('chat流式生成器无效', [
  8666. 'generator_type' => $errorType,
  8667. 'model' => $model,
  8668. 'anime_id' => $anime_id,
  8669. 'episode_number' => $episode_number
  8670. ]);
  8671. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  8672. 'type' => $errorType,
  8673. 'model' => $model
  8674. ]);
  8675. yield [
  8676. 'type' => 'error',
  8677. 'episode' => [],
  8678. 'answer' => '',
  8679. 'reasoning' => '',
  8680. 'usage' => [],
  8681. 'error' => '接口返回数据异常,请重新请求'
  8682. ];
  8683. return;
  8684. }
  8685. // 处理流式输出
  8686. foreach ($streamGenerator as $chunk) {
  8687. if (isset($chunk['type'])) {
  8688. if ($chunk['type'] === 'done') {
  8689. // 最终结果
  8690. $fullContent = $chunk['full_content'];
  8691. $fullReasoningContent = $chunk['full_reasoning'];
  8692. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8693. } else {
  8694. // 逐块yield数据
  8695. yield $chunk;
  8696. }
  8697. }
  8698. }
  8699. } catch (\Exception $e) {
  8700. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  8701. 'model' => $model,
  8702. 'anime_id' => $anime_id,
  8703. 'episode_number' => $episode_number,
  8704. 'trace' => $e->getTraceAsString()
  8705. ]);
  8706. logDB('deepseek', 'error', 'chat流式处理失败', [
  8707. 'error' => $e->getMessage(),
  8708. 'model' => $model
  8709. ]);
  8710. yield [
  8711. 'type' => 'error',
  8712. 'episode' => [],
  8713. 'answer' => '',
  8714. 'reasoning' => '',
  8715. 'usage' => [],
  8716. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  8717. ];
  8718. return;
  8719. }
  8720. // 兼容模型偶发将整段正文包裹成 JSON 字符串返回
  8721. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  8722. dLog('deepseek')->info('完整内容: '.$fullContent);
  8723. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  8724. // 处理完整内容并返回最终结果
  8725. $episode_arr = handleEpisodeContentForAce($fullContent);
  8726. dLog('deepseek')->info('解析内容: ', $episode_arr);
  8727. logDB('deepseek', 'info', '解析内容', $episode_arr);
  8728. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  8729. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  8730. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  8731. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  8732. // }
  8733. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  8734. $max_retries = 3;
  8735. $retry_count = 0;
  8736. $validation_failed = false;
  8737. $validation_error_msg = '';
  8738. // 验证生成的内容
  8739. if ($anime_script_id) {
  8740. // 检查是否有acts数据
  8741. if (empty($episode_arr['acts'])) {
  8742. $validation_failed = true;
  8743. $validation_error_msg = '未生成分镜剧本相关的内容';
  8744. } else {
  8745. // 仅当存在强制主体设定时校验主体列表
  8746. if (!empty($extra_roles)) {
  8747. $generated_roles = array_column($episode_arr['roles'], 'role');
  8748. // 过滤掉"旁白"角色
  8749. $generated_roles = array_filter($generated_roles, function($role) {
  8750. return $role !== '旁白';
  8751. });
  8752. $expected_roles = array_keys($extra_roles);
  8753. // 找出生成的主体中不在预期列表中的主体
  8754. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8755. if (!empty($invalid_roles)) {
  8756. $validation_failed = true;
  8757. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8758. }
  8759. }
  8760. // 仅当存在强制场景设定时校验场景列表
  8761. if (!$validation_failed && !empty($extra_scenes)) {
  8762. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  8763. $expected_scenes = array_keys($extra_scenes);
  8764. // 找出生成的场景中不在预期列表中的场景
  8765. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8766. if (!empty($invalid_scenes)) {
  8767. $validation_failed = true;
  8768. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8769. }
  8770. }
  8771. // 仅当存在强制道具设定时校验道具列表
  8772. if (!$validation_failed && !empty($extra_props)) {
  8773. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8774. $expected_props = array_keys($extra_props);
  8775. // 找出生成的道具中不在预期列表中的道具
  8776. $invalid_props = array_diff($generated_props, $expected_props);
  8777. if (!empty($invalid_props)) {
  8778. $validation_failed = true;
  8779. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8780. }
  8781. }
  8782. }
  8783. } else {
  8784. // 如果没有anime_script_id,只检查是否有acts数据
  8785. if (empty($episode_arr['acts'])) {
  8786. $validation_failed = true;
  8787. $validation_error_msg = '未生成分镜剧本相关的内容';
  8788. }
  8789. }
  8790. // 重试逻辑
  8791. while ($validation_failed && $retry_count < $max_retries) {
  8792. $retry_count++;
  8793. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  8794. 'reason' => $validation_error_msg,
  8795. 'anime_id' => $anime_id,
  8796. 'episode_number' => $episode_number
  8797. ]);
  8798. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  8799. 'reason' => $validation_error_msg,
  8800. 'anime_id' => $anime_id
  8801. ]);
  8802. // 发送流式重试提示
  8803. yield [
  8804. 'type' => 'retry',
  8805. 'retry_count' => $retry_count,
  8806. 'reason' => $validation_error_msg
  8807. ];
  8808. // 构建重试提示词
  8809. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  8810. if ($anime_script_id) {
  8811. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  8812. $retry_prompt .= "2. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  8813. $retry_prompt .= "3. 必须包含完整的分镜剧本内容\n";
  8814. } else {
  8815. $retry_prompt .= "1. 必须包含完整的分镜剧本内容\n";
  8816. }
  8817. // 添加重试消息到messages
  8818. $messages[] = [
  8819. 'role' => 'assistant',
  8820. 'content' => $fullContent
  8821. ];
  8822. $messages[] = [
  8823. 'role' => 'user',
  8824. 'content' => $retry_prompt
  8825. ];
  8826. // 更新post_data的messages
  8827. $post_data['messages'] = $messages;
  8828. // 重新调用API
  8829. try {
  8830. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8831. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  8832. } else if (in_array($model, $this->gpt_text_models)) {
  8833. $streamGenerator = $this->gpt54StreamResponse($post_data);
  8834. } else if (in_array($model, $this->gemini_text_models)) {
  8835. // Gemini 模型使用 Gemini API
  8836. $streamGenerator = $this->geminiStreamResponse($post_data, $model);
  8837. } else {
  8838. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  8839. }
  8840. // 处理流式输出
  8841. $fullContent = '';
  8842. $fullReasoningContent = '';
  8843. foreach ($streamGenerator as $chunk) {
  8844. if (isset($chunk['type'])) {
  8845. if ($chunk['type'] === 'done') {
  8846. $fullContent = $chunk['full_content'];
  8847. $fullReasoningContent = $chunk['full_reasoning'];
  8848. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8849. } else {
  8850. yield $chunk;
  8851. }
  8852. }
  8853. }
  8854. // 重新解析内容
  8855. $fullContent = $this->unwrapJsonWrappedContent($fullContent);
  8856. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  8857. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  8858. $episode_arr = handleEpisodeContentForAce($fullContent);
  8859. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  8860. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  8861. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  8862. // }
  8863. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  8864. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  8865. // 重新验证
  8866. $validation_failed = false;
  8867. $validation_error_msg = '';
  8868. if ($anime_script_id) {
  8869. if (empty($episode_arr['acts'])) {
  8870. $validation_failed = true;
  8871. $validation_error_msg = '未生成分镜剧本相关的内容';
  8872. } else {
  8873. // 仅当存在强制主体设定时校验主体列表
  8874. if (!empty($extra_roles)) {
  8875. $generated_roles = array_column($episode_arr['roles'], 'role');
  8876. // 过滤掉"旁白"角色
  8877. $generated_roles = array_filter($generated_roles, function($role) {
  8878. return $role !== '旁白';
  8879. });
  8880. $expected_roles = array_keys($extra_roles);
  8881. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8882. if (!empty($invalid_roles)) {
  8883. $validation_failed = true;
  8884. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8885. }
  8886. }
  8887. // 仅当存在强制场景设定时校验场景列表
  8888. if (!$validation_failed && !empty($extra_scenes)) {
  8889. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  8890. $expected_scenes = array_keys($extra_scenes);
  8891. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8892. if (!empty($invalid_scenes)) {
  8893. $validation_failed = true;
  8894. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8895. }
  8896. }
  8897. // 仅当存在强制道具设定时校验道具列表
  8898. if (!$validation_failed && !empty($extra_props)) {
  8899. $generated_props = array_column($episode_arr['props'] ?? [], 'prop');
  8900. $expected_props = array_keys($extra_props);
  8901. $invalid_props = array_diff($generated_props, $expected_props);
  8902. if (!empty($invalid_props)) {
  8903. $validation_failed = true;
  8904. $validation_error_msg = '生成的道具列表包含不在【强制道具设定】中的道具:' . implode('、', $invalid_props);
  8905. }
  8906. }
  8907. }
  8908. } else {
  8909. if (empty($episode_arr['acts'])) {
  8910. $validation_failed = true;
  8911. $validation_error_msg = '未生成分镜剧本相关的内容';
  8912. }
  8913. }
  8914. } catch (\Exception $e) {
  8915. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  8916. 'trace' => $e->getTraceAsString()
  8917. ]);
  8918. break;
  8919. }
  8920. }
  8921. // 将生成内容中的资产合并进强制列表,保证后续数据合并包含新资产(即使没有强制列表也执行)
  8922. $extra_roles = $this->mergeGeneratedResources($episode_arr['roles'] ?? [], $extra_roles, 'role');
  8923. $extra_scenes = $this->mergeGeneratedResources($episode_arr['scenes'] ?? [], $extra_scenes, 'scene');
  8924. $extra_props = $this->mergeGeneratedResources($episode_arr['props'] ?? [], $extra_props, 'prop');
  8925. // 最后一次重试仍校验失败时,兼容合并非强制列表中的资产,保证可以保存并返回 episodes
  8926. if ($validation_failed && $retry_count >= $max_retries) {
  8927. dLog('deepseek')->info('最后一次重试仍校验失败,兼容非强制列表资产后继续保存', [
  8928. 'retry_count' => $retry_count,
  8929. 'last_error' => $validation_error_msg
  8930. ]);
  8931. logDB('deepseek', 'info', '最后一次重试校验失败,合并非强制资产', [
  8932. 'error' => $validation_error_msg,
  8933. 'anime_id' => $anime_id
  8934. ]);
  8935. $validation_failed = false;
  8936. $validation_error_msg = '';
  8937. }
  8938. // 如果重试后仍然失败
  8939. if ($validation_failed) {
  8940. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  8941. 'retry_count' => $retry_count,
  8942. 'last_error' => $validation_error_msg
  8943. ]);
  8944. try {
  8945. $now = date('Y-m-d H:i:s');
  8946. $records = [
  8947. [
  8948. 'uid' => $uid,
  8949. 'anime_id' => $anime_id,
  8950. 'sequence' => $episode_number,
  8951. 'role' => 'user',
  8952. 'content' => $prompt,
  8953. 'created_at' => $now,
  8954. 'updated_at' => $now
  8955. ],
  8956. [
  8957. 'uid' => $uid,
  8958. 'anime_id' => $anime_id,
  8959. 'sequence' => $episode_number,
  8960. 'role' => 'assistant',
  8961. 'content' => $fullContent,
  8962. 'created_at' => $now,
  8963. 'updated_at' => $now
  8964. ]
  8965. ];
  8966. DB::table('mp_anime_records')->insert($records);
  8967. } catch (\Exception $e) {
  8968. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8969. }
  8970. yield [
  8971. 'type' => 'done',
  8972. 'episode' => [],
  8973. 'answer' => $fullContent,
  8974. 'reasoning' => $fullReasoningContent,
  8975. 'usage' => $usage,
  8976. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  8977. ];
  8978. return;
  8979. }
  8980. // 验证成功,记录日志
  8981. if ($retry_count > 0) {
  8982. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  8983. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  8984. }
  8985. // 老逻辑
  8986. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  8987. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  8988. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  8989. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  8990. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  8991. $existing_props = is_array($existing_props) ? $existing_props : [];
  8992. $now = date('Y-m-d H:i:s');
  8993. try {
  8994. DB::beginTransaction();
  8995. $saveResult = $this->saveEpisodeVersionData(
  8996. $anime_id,
  8997. $episode_number,
  8998. $episode_arr,
  8999. $existing_roles,
  9000. $existing_scenes,
  9001. $existing_props,
  9002. $current_episode,
  9003. $base_episode,
  9004. $is_regenerate_version,
  9005. $content,
  9006. $now,
  9007. $ref_products
  9008. );
  9009. $episode = $saveResult['episode'];
  9010. $episode_id = $saveResult['episode_id'];
  9011. $merged_roles = $saveResult['merged_roles'];
  9012. $merged_scenes = $saveResult['merged_scenes'];
  9013. $merged_props = $saveResult['merged_props'];
  9014. $record_content = $origin_prompt;
  9015. if ($uploaded_content !== '') {
  9016. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  9017. }
  9018. $records = [
  9019. [
  9020. 'uid' => $uid,
  9021. 'anime_id' => $anime_id,
  9022. 'role' => 'user',
  9023. 'content' => $record_content,
  9024. 'sequence' => $episode_number,
  9025. 'episode_id' => $episode_id,
  9026. 'created_at' => $now,
  9027. 'updated_at' => $now
  9028. ],
  9029. [
  9030. 'uid' => $uid,
  9031. 'anime_id' => $anime_id,
  9032. 'role' => 'assistant',
  9033. 'content' => $fullContent,
  9034. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  9035. 'sequence' => $episode_number,
  9036. 'episode_id' => $episode_id,
  9037. 'created_at' => $now,
  9038. 'updated_at' => $now
  9039. ]
  9040. ];
  9041. $boolen4 = DB::table('mp_anime_records')->insert($records);
  9042. if (!$boolen4) {
  9043. Utils::throwError('20003:对话记录保存失败');
  9044. }
  9045. // 保存模型到anime表
  9046. $update_anime_data = [
  9047. 'model' => $model,
  9048. 'updated_at' => $now
  9049. ];
  9050. if ($uploaded_content) {
  9051. $update_anime_data['content'] = $uploaded_content;
  9052. }
  9053. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  9054. }catch (\Exception $e) {
  9055. DB::rollBack();
  9056. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  9057. yield [
  9058. 'type' => 'done',
  9059. 'answer' => $fullContent,
  9060. 'reasoning' => $fullReasoningContent,
  9061. 'usage' => $usage,
  9062. 'error' => $e->getMessage(),
  9063. ];
  9064. return;
  9065. }
  9066. DB::commit();
  9067. if ($is_global_generate_pics) {
  9068. // // 批量生成全局角色图片
  9069. // $this->batchSetGlobalRoleImg([
  9070. // 'anime_id' => $anime_id,
  9071. // ], true);
  9072. // // 批量生成全局场景图片
  9073. // $this->batchSetGlobalSceneImg([
  9074. // 'anime_id' => $anime_id,
  9075. // ], true);
  9076. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  9077. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  9078. }
  9079. $episode['episode_id'] = $episode_id;
  9080. $episode['roles'] = $merged_roles;
  9081. $episode['scenes'] = $merged_scenes;
  9082. $episode['props'] = $merged_props;
  9083. $episode['end_episode_sequence'] = $end_episode_sequence;
  9084. // 获取mp_animes表中的视频参数
  9085. $episode['video_params'] = [
  9086. 'video_model' => getProp($anime, 'video_model'),
  9087. 'video_resolution' => getProp($anime, 'video_resolution'),
  9088. 'ratio' => getProp($anime, 'video_ratio'),
  9089. ];
  9090. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9091. yield [
  9092. 'type' => 'done',
  9093. 'episode' => $episode,
  9094. 'answer' => $fullContent,
  9095. 'reasoning' => $fullReasoningContent,
  9096. 'usage' => $usage
  9097. ];
  9098. }
  9099. /**
  9100. * chatForAce的非流式版本 - 用于定时任务
  9101. * 只获取最终 type=done 的数据,并验证必要字段
  9102. *
  9103. * @param array $data 请求数据
  9104. * @return array 生成结果
  9105. */
  9106. public function chatForAceNonStream($data) {
  9107. $finalResult = null;
  9108. // 调用流式方法,只保存 type=done 的数据
  9109. foreach ($this->chatForAce($data) as $chunk) {
  9110. // 只关注最终结果
  9111. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  9112. $finalResult = $chunk;
  9113. break; // 找到 done 就退出循环
  9114. }
  9115. }
  9116. // 验证最终结果
  9117. if (!$finalResult) {
  9118. return ['error' => '生成失败:未获取到最终结果'];
  9119. }
  9120. // 检查是否有错误
  9121. if (isset($finalResult['error']) && $finalResult['error']) {
  9122. return $finalResult;
  9123. }
  9124. // 验证必要字段
  9125. $episode = $finalResult['episode'] ?? [];
  9126. // 验证 roles
  9127. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  9128. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  9129. }
  9130. // 验证 scenes
  9131. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  9132. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  9133. }
  9134. // 验证 props(道具可以为空,但必须存在且为数组)
  9135. if (!isset($episode['props']) || !is_array($episode['props'])) {
  9136. $episode['props'] = [];
  9137. }
  9138. // 验证 acts(分镜剧本)
  9139. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  9140. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  9141. }
  9142. // 更新验证后的 episode 数据
  9143. $finalResult['episode'] = $episode;
  9144. // 记录验证成功日志
  9145. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  9146. 'roles_count' => count($episode['roles']),
  9147. 'scenes_count' => count($episode['scenes']),
  9148. 'props_count' => count($episode['props']),
  9149. 'acts_count' => count($episode['acts'])
  9150. ]);
  9151. return $finalResult;
  9152. }
  9153. /**
  9154. * 批量生成多个分集
  9155. *
  9156. * @param array $data 请求数据
  9157. * @return array 任务信息
  9158. */
  9159. public function batchGenerateEpisodes($data) {
  9160. $uid = Site::getUid();
  9161. $cpid = Site::getCpid();
  9162. $anime_id = getProp($data, 'anime_id');
  9163. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  9164. if (!$anime_id) {
  9165. Utils::throwError('20003:anime_id参数缺失');
  9166. }
  9167. if ($generate_episode_number < 1) {
  9168. Utils::throwError('20003:生成集数必须大于0');
  9169. }
  9170. // 获取动漫信息
  9171. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9172. if (!$anime) {
  9173. Utils::throwError('20003:该剧集不存在');
  9174. }
  9175. // 检查是否是全能模式
  9176. if ((int)getProp($anime, 'ace_mode') !== 1) {
  9177. Utils::throwError('20003:只有全能模式才支持批量生成');
  9178. }
  9179. // 检查是否是多剧集模式
  9180. if ((int)getProp($anime, 'is_multi') !== 1) {
  9181. Utils::throwError('20003:单剧集不支持批量生成');
  9182. }
  9183. // 获取当前已生成的最大集数
  9184. $currentMaxEpisode = DB::table('mp_anime_episodes')
  9185. ->where('anime_id', $anime_id)
  9186. ->where('is_default', 1)
  9187. ->max('episode_number');
  9188. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  9189. // 确定起始集数
  9190. $startEpisodeNumber = $currentMaxEpisode + 1;
  9191. // 计算结束集数
  9192. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  9193. // 检查是否超过总集数限制
  9194. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  9195. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  9196. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  9197. }
  9198. $now = date('Y-m-d H:i:s');
  9199. $createdTasks = [];
  9200. $skippedTasks = [];
  9201. // 为每一集创建详情记录
  9202. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  9203. // 检查是否已有该集的任务记录
  9204. $existingTask = DB::table('mp_batch_episode_generation_details')
  9205. ->where('anime_id', $anime_id)
  9206. ->where('episode_number', $episodeNumber)
  9207. ->first();
  9208. if ($existingTask) {
  9209. // 如果已存在且未完成,跳过
  9210. if (in_array($existingTask->status, ['pending', 'processing'])) {
  9211. $skippedTasks[] = $episodeNumber;
  9212. continue;
  9213. }
  9214. // 如果是失败状态,可以重新创建(删除旧记录)
  9215. if ($existingTask->status === 'failed') {
  9216. DB::table('mp_batch_episode_generation_details')
  9217. ->where('id', $existingTask->id)
  9218. ->delete();
  9219. }
  9220. // 如果是已完成状态,也跳过
  9221. if ($existingTask->status === 'completed') {
  9222. $skippedTasks[] = $episodeNumber;
  9223. continue;
  9224. }
  9225. }
  9226. // 准备任务数据
  9227. $taskData = [
  9228. 'anime_id' => $anime_id,
  9229. 'uid' => $uid,
  9230. 'cpid' => $cpid,
  9231. 'episode_number' => $episodeNumber,
  9232. 'status' => 'pending',
  9233. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  9234. 'retry_count' => 0,
  9235. 'created_at' => $now,
  9236. 'updated_at' => $now
  9237. ];
  9238. // 创建任务记录
  9239. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  9240. if ($taskId) {
  9241. $createdTasks[] = $episodeNumber;
  9242. }
  9243. }
  9244. if (empty($createdTasks)) {
  9245. if (!empty($skippedTasks)) {
  9246. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  9247. } else {
  9248. Utils::throwError('20003:创建批量生成任务失败');
  9249. }
  9250. }
  9251. return [
  9252. 'anime_id' => $anime_id,
  9253. 'start_episode' => $startEpisodeNumber,
  9254. 'end_episode' => $endEpisodeNumber,
  9255. 'total_episodes' => $generate_episode_number,
  9256. 'created_episodes' => $createdTasks,
  9257. 'skipped_episodes' => $skippedTasks,
  9258. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集。" .
  9259. "已创建: " . implode(',', $createdTasks) .
  9260. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : "")
  9261. ];
  9262. }
  9263. /**
  9264. * 获取批量生成任务状态
  9265. *
  9266. * @param array $data 请求数据
  9267. * @return array 任务状态信息
  9268. */
  9269. public function getBatchGenerationTaskStatus($data) {
  9270. $anime_id = getProp($data, 'anime_id');
  9271. if (!$anime_id) {
  9272. Utils::throwError('20003:anime_id参数缺失');
  9273. }
  9274. // 获取该anime的所有任务
  9275. $tasks = DB::table('mp_batch_episode_generation_details')
  9276. ->where('anime_id', $anime_id)
  9277. ->orderBy('episode_number')
  9278. ->get()
  9279. ->map(function($item) {
  9280. return [
  9281. 'id' => $item->id,
  9282. 'episode_number' => $item->episode_number,
  9283. 'status' => $item->status,
  9284. 'error_message' => $item->error_message,
  9285. 'retry_count' => $item->retry_count,
  9286. 'created_at' => $item->created_at,
  9287. 'updated_at' => $item->updated_at,
  9288. 'completed_at' => $item->completed_at
  9289. ];
  9290. })
  9291. ->toArray();
  9292. if (empty($tasks)) {
  9293. Utils::throwError('20003:该剧集没有批量生成任务');
  9294. }
  9295. // 统计各状态数量
  9296. $totalCount = count($tasks);
  9297. $pendingCount = 0;
  9298. $processingCount = 0;
  9299. $completedCount = 0;
  9300. $failedCount = 0;
  9301. foreach ($tasks as $task) {
  9302. switch ($task['status']) {
  9303. case 'pending':
  9304. $pendingCount++;
  9305. break;
  9306. case 'processing':
  9307. $processingCount++;
  9308. break;
  9309. case 'completed':
  9310. $completedCount++;
  9311. break;
  9312. case 'failed':
  9313. $failedCount++;
  9314. break;
  9315. }
  9316. }
  9317. // 计算进度百分比
  9318. $progress = 0;
  9319. if ($totalCount > 0) {
  9320. $progress = round(($completedCount / $totalCount) * 100, 2);
  9321. }
  9322. // 判断整体状态
  9323. $overallStatus = 'processing';
  9324. if ($completedCount === $totalCount) {
  9325. $overallStatus = 'completed';
  9326. } elseif ($pendingCount === $totalCount) {
  9327. $overallStatus = 'pending';
  9328. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  9329. $overallStatus = 'failed';
  9330. }
  9331. return [
  9332. 'anime_id' => $anime_id,
  9333. 'total_episodes' => $totalCount,
  9334. 'pending_count' => $pendingCount,
  9335. 'processing_count' => $processingCount,
  9336. 'completed_count' => $completedCount,
  9337. 'failed_count' => $failedCount,
  9338. 'progress' => $progress,
  9339. 'overall_status' => $overallStatus,
  9340. 'tasks' => $tasks
  9341. ];
  9342. }
  9343. /**
  9344. * 将生成内容中不在强制列表中的资源合并进强制列表
  9345. * 用于最后一次重试仍校验失败时,兼容剧情需要的新资产
  9346. *
  9347. * @param array $generated 生成内容中的资源列表
  9348. * @param array $forced 强制资源列表(key为资源名称)
  9349. * @param string $type 资源类型:role、scene、prop
  9350. * @return array
  9351. */
  9352. private function mergeGeneratedResources(array $generated, array $forced, string $type): array
  9353. {
  9354. foreach ($generated as $item) {
  9355. $name = getProp($item, $type === 'role' ? 'role' : ($type === 'scene' ? 'scene' : 'prop'));
  9356. if ($name === null || $name === '') {
  9357. continue;
  9358. }
  9359. if ($name === '旁白') {
  9360. continue;
  9361. }
  9362. if (!isset($forced[$name])) {
  9363. $forced[$name] = $item;
  9364. }
  9365. }
  9366. return $forced;
  9367. }
  9368. /**
  9369. * 智能匹配并替换主体和场景名称
  9370. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  9371. *
  9372. * @param array $episode_arr 解析后的剧集数据
  9373. * @param array $extra_roles 强制主体设定(key为主体名称)
  9374. * @param array $extra_scenes 强制场景设定(key为场景名称)
  9375. * @return array 替换后的剧集数据
  9376. */
  9377. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  9378. $replaced_count = 0;
  9379. // 1. 处理主体列表
  9380. if (!empty($episode_arr['roles'])) {
  9381. foreach ($episode_arr['roles'] as &$role) {
  9382. $generated_role_name = $role['role'] ?? '';
  9383. // 跳过旁白
  9384. if ($generated_role_name === '旁白') {
  9385. continue;
  9386. }
  9387. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  9388. if (!isset($extra_roles[$generated_role_name])) {
  9389. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  9390. if ($matched_role) {
  9391. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  9392. $role['role'] = $matched_role;
  9393. $replaced_count++;
  9394. }
  9395. }
  9396. }
  9397. }
  9398. // 2. 处理场景列表
  9399. if (!empty($episode_arr['scenes'])) {
  9400. foreach ($episode_arr['scenes'] as &$scene) {
  9401. $generated_scene_name = $scene['scene'] ?? '';
  9402. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  9403. if (!isset($extra_scenes[$generated_scene_name])) {
  9404. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  9405. if ($matched_scene) {
  9406. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  9407. $scene['scene'] = $matched_scene;
  9408. $replaced_count++;
  9409. }
  9410. }
  9411. }
  9412. }
  9413. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  9414. if (!empty($episode_arr['acts'])) {
  9415. foreach ($episode_arr['acts'] as &$act) {
  9416. if (!empty($act['segments'])) {
  9417. foreach ($act['segments'] as &$segment) {
  9418. if (!empty($segment['segment_content'])) {
  9419. $original_content = $segment['segment_content'];
  9420. $replaced_content = $original_content;
  9421. // 替换场景名 - 在文本中查找并替换
  9422. foreach (array_keys($extra_scenes) as $full_scene_name) {
  9423. // 尝试找到可能的短名称
  9424. $potential_short_names = [];
  9425. // 提取场景名的主要部分(冒号之前)
  9426. if (mb_strpos($full_scene_name, ':') !== false) {
  9427. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  9428. $potential_short_names[] = $short_name;
  9429. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  9430. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  9431. $potential_short_names[] = $short_name;
  9432. }
  9433. // 替换场景字段中的短名称
  9434. foreach ($potential_short_names as $short_name) {
  9435. if ($short_name !== $full_scene_name) {
  9436. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  9437. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  9438. if ($new_content !== $replaced_content) {
  9439. $replaced_content = $new_content;
  9440. $replaced_count++;
  9441. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  9442. }
  9443. }
  9444. }
  9445. }
  9446. // 替换配音角色名(跳过旁白)
  9447. foreach (array_keys($extra_roles) as $full_role_name) {
  9448. if ($full_role_name === '旁白') {
  9449. continue;
  9450. }
  9451. // 尝试找到可能的短名称
  9452. $potential_short_names = [];
  9453. // 提取角色名的主要部分(短横线之前)
  9454. if (mb_strpos($full_role_name, '-') !== false) {
  9455. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  9456. $potential_short_names[] = $short_name;
  9457. }
  9458. // 替换配音台词中的短名称
  9459. foreach ($potential_short_names as $short_name) {
  9460. if ($short_name !== $full_role_name) {
  9461. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  9462. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  9463. if ($new_content !== $replaced_content) {
  9464. $replaced_content = $new_content;
  9465. $replaced_count++;
  9466. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  9467. }
  9468. }
  9469. }
  9470. }
  9471. // 如果有替换,更新segment_content
  9472. if ($replaced_content !== $original_content) {
  9473. $segment['segment_content'] = $replaced_content;
  9474. }
  9475. }
  9476. }
  9477. }
  9478. }
  9479. }
  9480. if ($replaced_count > 0) {
  9481. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  9482. 'replaced_count' => $replaced_count
  9483. ]);
  9484. }
  9485. return $episode_arr;
  9486. }
  9487. /**
  9488. * 查找匹配的名称
  9489. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  9490. *
  9491. * @param string $generated_name 生成的名称
  9492. * @param array $expected_names 预期的名称列表
  9493. * @return string|null 匹配到的名称,如果没有匹配则返回null
  9494. */
  9495. private function findMatchingName($generated_name, $expected_names) {
  9496. if (empty($generated_name)) {
  9497. return null;
  9498. }
  9499. // 尝试精确匹配
  9500. if (in_array($generated_name, $expected_names)) {
  9501. return $generated_name;
  9502. }
  9503. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  9504. foreach ($expected_names as $expected_name) {
  9505. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  9506. if (mb_strpos($expected_name, $generated_name) === 0) {
  9507. return $expected_name;
  9508. }
  9509. }
  9510. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  9511. // 这样可以处理一些变体,但优先级较低
  9512. foreach ($expected_names as $expected_name) {
  9513. if (mb_strpos($expected_name, $generated_name) !== false) {
  9514. return $expected_name;
  9515. }
  9516. }
  9517. return null;
  9518. }
  9519. /**
  9520. * 重新生成分段剧本
  9521. * @param array $data 包含以下字段:
  9522. * - prompt: string|null 用户修改要求(可选)
  9523. * - template_id: int|null 提示词模板ID(可选)
  9524. * - act_id: int|null 单个片段ID(与episode_id二选一)
  9525. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  9526. * @return array 返回生成结果
  9527. */
  9528. public function regenerateSegmentScript($data) {
  9529. $uid = Site::getUid();
  9530. $prompt = trim((string)getProp($data, 'prompt', ''));
  9531. $template_id = getProp($data, 'template_id', 0);
  9532. $act_id = getProp($data, 'act_id', 0);
  9533. $episode_id = getProp($data, 'episode_id', 0);
  9534. // 验证:prompt和template_id至少提供一个
  9535. if (empty($prompt) && empty($template_id)) {
  9536. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  9537. }
  9538. // 验证:act_id和episode_id二选一
  9539. if (empty($act_id) && empty($episode_id)) {
  9540. Utils::throwError('20003:请提供片段ID或剧集ID');
  9541. }
  9542. if (!empty($act_id) && !empty($episode_id)) {
  9543. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  9544. }
  9545. // 如果提供了template_id,获取模板提示词
  9546. $template_prompt = '';
  9547. if ($template_id > 0) {
  9548. $template = DB::table('mp_prompt_templates')
  9549. ->where('id', $template_id)
  9550. ->where('is_deleted', 0)
  9551. ->first();
  9552. if (!$template) {
  9553. Utils::throwError('20003:提示词模板不存在或已删除');
  9554. }
  9555. $template_prompt = $template->template_prompt ?? '';
  9556. }
  9557. // 合并用户提示词和模板提示词
  9558. $final_prompt = '';
  9559. if (!empty($template_prompt)) {
  9560. $final_prompt = $template_prompt;
  9561. if (!empty($prompt)) {
  9562. $final_prompt .= "\n\n补充要求:" . $prompt;
  9563. }
  9564. } else {
  9565. $final_prompt = $prompt;
  9566. }
  9567. // 获取需要重新生成的内容参考
  9568. $reference_content = '';
  9569. $target_episode_id = 0;
  9570. $target_anime_id = 0;
  9571. $target_episode_number = 0;
  9572. if ($act_id > 0) {
  9573. // 单个片段模式:获取该片段的内容
  9574. $segment = DB::table('mp_episode_segments')
  9575. ->where('id', $act_id)
  9576. ->first();
  9577. if (!$segment) {
  9578. Utils::throwError('20003:片段不存在');
  9579. }
  9580. $target_episode_id = $segment->episode_id;
  9581. $target_anime_id = $segment->anime_id;
  9582. $target_episode_number = $segment->episode_number;
  9583. $reference_content = $segment->act_content ?? '';
  9584. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  9585. } else {
  9586. // 整个剧集模式:获取所有片段的内容
  9587. $segments = DB::table('mp_episode_segments')
  9588. ->where('episode_id', $episode_id)
  9589. ->orderBy('act_number')
  9590. ->get();
  9591. if ($segments->isEmpty()) {
  9592. Utils::throwError('20003:该剧集没有片段数据');
  9593. }
  9594. $target_episode_id = $episode_id;
  9595. $target_anime_id = $segments[0]->anime_id;
  9596. $target_episode_number = $segments[0]->episode_number;
  9597. // 拼接所有片段内容,保留格式用于AI理解
  9598. $act_contents = [];
  9599. foreach ($segments as $seg) {
  9600. $act_number = $seg->act_number;
  9601. $act_content = $seg->act_content ?? '';
  9602. if (!empty($act_content)) {
  9603. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  9604. }
  9605. }
  9606. $reference_content = implode("\n\n", $act_contents);
  9607. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  9608. if ($episode_content) {
  9609. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  9610. }else {
  9611. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  9612. }
  9613. }
  9614. if (empty($reference_content)) {
  9615. Utils::throwError('20003:没有可参考的片段内容');
  9616. }
  9617. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  9618. $episode = DB::table('mp_anime_episodes')
  9619. ->where('id', $target_episode_id)
  9620. ->first();
  9621. if (!$episode) {
  9622. Utils::throwError('20003:剧集不存在');
  9623. }
  9624. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  9625. $anime_script_id = getProp($anime, 'script_id');
  9626. $intro = $episode->intro ?? '';
  9627. $art_style = $episode->art_style ?? '';
  9628. $roles = json_decode($episode->roles ?? '[]', true);
  9629. $scenes = json_decode($episode->scenes ?? '[]', true);
  9630. $props = json_decode($episode->props ?? '[]', true);
  9631. // 构建提示词中的主体列表和场景列表参考
  9632. $roles_ref = '';
  9633. if (!empty($roles) && is_array($roles)) {
  9634. $roles_list = [];
  9635. foreach ($roles as $role) {
  9636. $role_name = getProp($role, 'role', '');
  9637. $role_desc = getProp($role, 'description', '');
  9638. $pic_prompt = getProp($role, 'pic_prompt', '');
  9639. $voice_prompt = getProp($role, 'voice_prompt', '');
  9640. if (!empty($role_name)) {
  9641. $role_line = $role_name;
  9642. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  9643. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  9644. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  9645. $roles_list[] = $role_line;
  9646. }
  9647. }
  9648. if (!empty($roles_list)) {
  9649. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  9650. }
  9651. }
  9652. $scenes_ref = '';
  9653. if (!empty($scenes) && is_array($scenes)) {
  9654. $scenes_list = [];
  9655. foreach ($scenes as $scene) {
  9656. $scene_name = getProp($scene, 'scene', '');
  9657. $scene_desc = getProp($scene, 'description', '');
  9658. $pic_prompt = getProp($scene, 'pic_prompt', '');
  9659. if (!empty($scene_name)) {
  9660. $scene_line = $scene_name;
  9661. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  9662. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  9663. $scenes_list[] = $scene_line;
  9664. }
  9665. }
  9666. if (!empty($scenes_list)) {
  9667. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  9668. }
  9669. }
  9670. $props_ref = '';
  9671. if (!empty($props) && is_array($props)) {
  9672. $props_list = [];
  9673. foreach ($props as $prop) {
  9674. $prop_name = getProp($prop, 'prop', '');
  9675. $prop_desc = getProp($prop, 'description', '');
  9676. $pic_prompt = getProp($prop, 'pic_prompt', '');
  9677. if (!empty($prop_name)) {
  9678. $prop_line = $prop_name;
  9679. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  9680. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  9681. $props_list[] = $prop_line;
  9682. }
  9683. }
  9684. if (!empty($props_list)) {
  9685. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  9686. }
  9687. }
  9688. // 构建美术风格参考
  9689. $art_style_ref = '';
  9690. if (!empty($art_style)) {
  9691. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  9692. }
  9693. // 构建内容简介参考
  9694. $intro_ref = '';
  9695. if (!empty($intro)) {
  9696. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  9697. }
  9698. // 构建完整的AI提示词
  9699. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  9700. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  9701. $user_prompt .= $intro_ref;
  9702. $user_prompt .= $art_style_ref;
  9703. $user_prompt .= $reference_content;
  9704. // $user_prompt .= $roles_ref;
  9705. // $user_prompt .= $scenes_ref;
  9706. $system_prompt = "\n\n【强制要求】\n";
  9707. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  9708. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  9709. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  9710. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  9711. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  9712. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  9713. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  9714. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  9715. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  9716. ###分段剧本
  9717. 片段数量:8
  9718. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  9719. ##片段1
  9720. 时长:12s
  9721. 分镜1
  9722. 出场角色:刀疤脸
  9723. 场景:边境小镇街道
  9724. 出场道具:酒杯-高脚杯
  9725. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  9726. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  9727. 配音台词:
  9728. 背景音效:
  9729. 分镜2
  9730. 出场角色:刀疤脸
  9731. 场景:悦来酒馆
  9732. 出场道具:酒杯-高脚杯
  9733. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  9734. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  9735. 配音台词:
  9736. 背景音效:
  9737. 分镜3
  9738. 出场角色:刀疤脸
  9739. 场景:悦来酒馆
  9740. 出场道具:酒杯-高脚杯
  9741. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  9742. 运镜:从中景推向令牌特写。
  9743. 配音台词:
  9744. 背景音效:
  9745. 分镜4
  9746. 出场角色:刀疤脸
  9747. 场景:悦来酒馆
  9748. 出场道具:酒杯-高脚杯
  9749. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  9750. 运镜:极速推向酒水溅起的瞬间。
  9751. 配音台词:
  9752. 背景音效:
  9753. 分镜5
  9754. 出场角色:刀疤脸
  9755. 场景:悦来酒馆
  9756. 出场道具:酒杯-高脚杯
  9757. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  9758. 运镜:固定机位,利用倾斜构图制造压迫感。
  9759. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  9760. 背景音效:";
  9761. // 获取模型配置
  9762. $model = getProp($data, 'model');
  9763. if (!$model) {
  9764. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  9765. }
  9766. // 验证模型是否在可用模型表中
  9767. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9768. $model = 'deepseek-v4-pro';
  9769. }
  9770. // 模型兼容性处理
  9771. $thinkingMode = 'disabled';
  9772. $reasoningEffort = 'high';
  9773. if ($model === 'deepseek-chat') {
  9774. $model = 'deepseek-v4-flash';
  9775. $thinkingMode = 'disabled';
  9776. } elseif ($model === 'deepseek-reasoner') {
  9777. $model = 'deepseek-v4-flash';
  9778. $thinkingMode = 'enabled';
  9779. }
  9780. // 构建消息
  9781. $messages = [
  9782. [
  9783. 'role' => 'system',
  9784. 'content' => $system_prompt
  9785. ],
  9786. [
  9787. 'role' => 'user',
  9788. 'content' => $user_prompt
  9789. ]
  9790. ];
  9791. // dd($messages);
  9792. // 构建请求参数
  9793. $post_data = [
  9794. 'model' => $model,
  9795. 'messages' => $messages,
  9796. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  9797. 'frequency_penalty' => 0,
  9798. 'presence_penalty' => 0,
  9799. 'response_format' => ['type' => 'text'],
  9800. 'thinking' => ['type' => $thinkingMode],
  9801. 'stream' => false // 非流式输出
  9802. ];
  9803. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9804. // 调用AI生成新的分段剧本
  9805. try {
  9806. $fullContent = '';
  9807. $usage = [];
  9808. // 根据模型类型选择调用方法
  9809. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9810. // DeepSeek 官方模型使用 DeepSeek API
  9811. $chatResult = $this->chatOnly($post_data);
  9812. } else if (in_array($model, $this->gpt_text_models)) {
  9813. // GPT 模型使用 TokenRouter API
  9814. $chatResult = $this->gpt54ChatOnly($post_data);
  9815. } else {
  9816. // 其他模型使用火山引擎API
  9817. $chatResult = $this->volcEngineChatCompletion($post_data);
  9818. }
  9819. if (is_array($chatResult)) {
  9820. $fullContent = $chatResult['fullContent'] ?? '';
  9821. $usage = $chatResult['usage'] ?? [];
  9822. }
  9823. $generated_content = $fullContent;
  9824. if (empty($generated_content)) {
  9825. Utils::throwError('20003:AI生成内容为空,请重试');
  9826. }
  9827. // 解析生成的内容 - 按片段分割
  9828. $parsed_segments = [];
  9829. // 先在开头添加换行符,确保第1片段也能被正确分割
  9830. $normalizedText = "\n" . $generated_content;
  9831. $parts = preg_split('/\n\s*##/', $normalizedText);
  9832. foreach ($parts as $part) {
  9833. $part = trim($part);
  9834. if (empty($part)) continue;
  9835. // 匹配"片段X"格式
  9836. if (!preg_match('/^片段\d+/', $part)) {
  9837. continue;
  9838. }
  9839. // 分离标题和内容
  9840. $lines = explode("\n", $part, 2);
  9841. $actTitle = trim($lines[0]);
  9842. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  9843. // 解析标题,提取序号
  9844. $actNumber = 0;
  9845. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  9846. $actNumber = intval($segmentTitleMatch[1]);
  9847. } else {
  9848. $actNumber = count($parsed_segments) + 1;
  9849. }
  9850. // 提取时长(仅保留数字)
  9851. $actDuration = 0;
  9852. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  9853. $actDurationStr = trim($actDurationMatch[1]);
  9854. // 提取数字部分(支持整数和小数)
  9855. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  9856. $actDuration = (float)$numMatch[1];
  9857. }
  9858. }
  9859. // 清理act_content:去除时长、旁白音色等非分镜内容行
  9860. // 只保留分镜内容,并确保分镜标记使用【】格式
  9861. $cleaned_content = '';
  9862. $content_lines = explode("\n", $actContent);
  9863. $is_capturing = false; // 标记是否开始捕获分镜内容
  9864. $count = 0;
  9865. foreach ($content_lines as $line) {
  9866. $trimmed_line = trim($line);
  9867. // 跳过时长和旁白音色行
  9868. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  9869. continue;
  9870. }
  9871. // 检测是否是分镜开始
  9872. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  9873. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  9874. $count++;
  9875. $is_capturing = true;
  9876. // 如果没有【】,则添加
  9877. if (!preg_match('/^【/u', $trimmed_line)) {
  9878. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  9879. }
  9880. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  9881. }
  9882. // 如果已经开始捕获,则添加该行
  9883. if ($is_capturing && !empty($trimmed_line)) {
  9884. $cleaned_content .= $trimmed_line."\n";
  9885. }
  9886. }
  9887. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  9888. $parsed_segments[] = [
  9889. 'act_number' => $actNumber,
  9890. 'act_title' => $actTitle,
  9891. 'act_duration' => $actDuration,
  9892. 'act_content' => $cleaned_content,
  9893. ];
  9894. }
  9895. if (empty($parsed_segments)) {
  9896. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  9897. }
  9898. // 收集所有资产名称(角色、场景、道具)
  9899. $product_names = [];
  9900. // 收集角色名称
  9901. if (!empty($roles) && is_array($roles)) {
  9902. foreach ($roles as $role) {
  9903. $role_name = getProp($role, 'role', '');
  9904. if (!empty($role_name)) {
  9905. $product_names[] = $role_name;
  9906. }
  9907. }
  9908. }
  9909. // 收集场景名称
  9910. if (!empty($scenes) && is_array($scenes)) {
  9911. foreach ($scenes as $scene) {
  9912. $scene_name = getProp($scene, 'scene', '');
  9913. if (!empty($scene_name)) {
  9914. $product_names[] = $scene_name;
  9915. }
  9916. }
  9917. }
  9918. // 收集道具名称
  9919. if (!empty($props) && is_array($props)) {
  9920. foreach ($props as $prop) {
  9921. $prop_name = getProp($prop, 'prop', '');
  9922. if (!empty($prop_name)) {
  9923. $product_names[] = $prop_name;
  9924. }
  9925. }
  9926. }
  9927. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  9928. $product_names = array_unique($product_names);
  9929. usort($product_names, function($a, $b) {
  9930. return mb_strlen($b) - mb_strlen($a);
  9931. });
  9932. // 处理每个片段的 act_show_content
  9933. foreach ($parsed_segments as &$segment) {
  9934. $act_content = getProp($segment, 'act_content', '');
  9935. if (empty($act_content)) {
  9936. $segment['act_show_content'] = '';
  9937. continue;
  9938. }
  9939. $processed_content = $act_content;
  9940. // 统一替换所有资产名称为 {资产名} 格式
  9941. // 使用占位符避免嵌套替换问题
  9942. $placeholder_map = [];
  9943. $placeholder_index = 0;
  9944. foreach ($product_names as $product_name) {
  9945. // 转义特殊字符
  9946. $escaped_product = preg_quote($product_name, '/');
  9947. // 检查是否匹配且未被 {} 包裹
  9948. $processed_content = preg_replace_callback(
  9949. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  9950. function($matches) use (&$placeholder_map, &$placeholder_index) {
  9951. // 使用唯一占位符
  9952. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  9953. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  9954. $placeholder_index++;
  9955. return $placeholder;
  9956. },
  9957. $processed_content
  9958. );
  9959. }
  9960. // 将所有占位符替换回实际内容
  9961. foreach ($placeholder_map as $placeholder => $replacement) {
  9962. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  9963. }
  9964. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  9965. $shot_counter = 0;
  9966. $processed_content = preg_replace_callback(
  9967. '/【(?:镜头|分镜)(\d+)】/u',
  9968. function($matches) use (&$shot_counter) {
  9969. $shot_counter++;
  9970. return '【镜头' . $shot_counter . '】';
  9971. },
  9972. $processed_content
  9973. );
  9974. $segment['act_show_content'] = $processed_content;
  9975. }
  9976. unset($segment); // 解除引用
  9977. // 保存到数据库
  9978. $now = date('Y-m-d H:i:s');
  9979. $saved_acts = []; // 用于记录保存后的片段信息
  9980. if ($act_id > 0) {
  9981. // 单个片段模式:更新单条记录
  9982. if (count($parsed_segments) > 0) {
  9983. $new_segment = $parsed_segments[0];
  9984. $update_data = [
  9985. 'act_content' => getProp($new_segment, 'act_content', ''),
  9986. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  9987. 'act_title' => getProp($new_segment, 'act_title', ''),
  9988. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  9989. 'updated_at' => $now,
  9990. ];
  9991. DB::table('mp_episode_segments')
  9992. ->where('id', $act_id)
  9993. ->update($update_data);
  9994. // 获取更新后的记录
  9995. $updated_act = DB::table('mp_episode_segments')
  9996. ->where('id', $act_id)
  9997. ->first();
  9998. if ($updated_act) {
  9999. $saved_acts[] = [
  10000. 'act_id' => $updated_act->id,
  10001. 'act_number' => $updated_act->act_number,
  10002. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  10003. 'act_content' => $updated_act->act_content,
  10004. 'act_show_content' => $updated_act->act_show_content,
  10005. 'video_url' => $updated_act->video_url ?? '',
  10006. 'video_duration' => $updated_act->video_duration ?? 0,
  10007. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  10008. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  10009. ];
  10010. }
  10011. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  10012. }
  10013. } else {
  10014. // 整个剧集模式:删除原有记录并批量保存新记录
  10015. DB::beginTransaction();
  10016. try {
  10017. // 删除原有的所有片段记录
  10018. DB::table('mp_episode_segments')
  10019. ->where('episode_id', $target_episode_id)
  10020. ->delete();
  10021. // 批量插入新的片段记录
  10022. $segments_to_insert = [];
  10023. foreach ($parsed_segments as $index => $segment) {
  10024. $act_number = $index + 1;
  10025. $segments_to_insert[] = [
  10026. 'anime_id' => $target_anime_id,
  10027. 'episode_id' => $target_episode_id,
  10028. 'episode_number' => $target_episode_number,
  10029. 'act_number' => $act_number,
  10030. 'act_title' => getProp($segment, 'act_title', ''),
  10031. 'act_duration' => getProp($segment, 'act_duration', 0),
  10032. 'act_content' => getProp($segment, 'act_content', ''),
  10033. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  10034. 'created_at' => $now,
  10035. 'updated_at' => $now,
  10036. ];
  10037. }
  10038. if (!empty($segments_to_insert)) {
  10039. DB::table('mp_episode_segments')->insert($segments_to_insert);
  10040. }
  10041. DB::commit();
  10042. // 查询保存后的所有片段记录
  10043. $saved_segments = DB::table('mp_episode_segments')
  10044. ->where('episode_id', $target_episode_id)
  10045. ->orderBy('act_number')
  10046. ->get();
  10047. foreach ($saved_segments as $saved_segment) {
  10048. $saved_acts[] = [
  10049. 'act_id' => $saved_segment->id,
  10050. 'act_number' => $saved_segment->act_number,
  10051. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  10052. 'act_content' => $saved_segment->act_content,
  10053. 'act_show_content' => $saved_segment->act_show_content,
  10054. 'video_url' => $saved_segment->video_url ?? '',
  10055. 'video_duration' => $saved_segment->video_duration ?? 0,
  10056. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  10057. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  10058. ];
  10059. }
  10060. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  10061. 'episode_id' => $target_episode_id,
  10062. 'segments_count' => count($segments_to_insert)
  10063. ]);
  10064. } catch (\Exception $e) {
  10065. DB::rollBack();
  10066. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  10067. Utils::throwError('20003:保存失败,请重试');
  10068. }
  10069. }
  10070. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  10071. return [
  10072. 'anime_id' => $target_anime_id,
  10073. 'episode_id' => $target_episode_id,
  10074. 'title' => getProp($episode, 'title', ''),
  10075. 'episode_number' => $target_episode_number,
  10076. 'is_generated' => getProp($episode, 'is_generated', 0),
  10077. 'acts' => $saved_acts,
  10078. ];
  10079. } catch (\Exception $e) {
  10080. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  10081. throw $e;
  10082. }
  10083. }
  10084. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  10085. {
  10086. $episode_arr = [
  10087. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  10088. 'intro' => getProp($script_arr, 'intro'),
  10089. 'art_style' => getProp($script_arr, 'art_style'),
  10090. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  10091. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  10092. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  10093. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  10094. ];
  10095. if (empty($episode_arr['acts'])) {
  10096. $fallback_episode_arr = handleEpisodeContent($fullContent);
  10097. if (!empty($fallback_episode_arr['acts'])) {
  10098. $episode_arr = array_merge($fallback_episode_arr, [
  10099. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  10100. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  10101. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  10102. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  10103. ]);
  10104. }
  10105. }
  10106. // if (!getProp($episode_arr, 'episode_title')) {
  10107. // $episode_title = '';
  10108. // $episodes = getProp($script_arr, 'episodes', []);
  10109. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  10110. // $episode_title = '第1集:' . $episodes[0]['title'];
  10111. // }
  10112. // if (!$episode_title) {
  10113. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  10114. // }
  10115. // $episode_arr['episode_title'] = $episode_title;
  10116. // }
  10117. return $episode_arr;
  10118. }
  10119. private function saveEpisodeVersionData(
  10120. int $anime_id,
  10121. int $episode_number,
  10122. array $episode_arr,
  10123. array $existing_roles,
  10124. array $existing_scenes,
  10125. array $existing_props,
  10126. $current_episode,
  10127. $base_episode,
  10128. bool $is_regenerate_version,
  10129. string $content,
  10130. string $now,
  10131. array $ref_products = []
  10132. ): array {
  10133. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  10134. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  10135. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  10136. // 过滤掉关键字段为空的条目
  10137. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  10138. return !empty($item['role'] ?? null);
  10139. }));
  10140. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  10141. return !empty($item['scene'] ?? null);
  10142. }));
  10143. $merged_props = array_values(array_filter($generated_props, function ($item) {
  10144. return !empty($item['prop'] ?? null);
  10145. }));
  10146. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  10147. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  10148. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  10149. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  10150. $ace_mode = getProp($anime, 'ace_mode');
  10151. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  10152. $global_roles = json_decode(getProp($anime, 'roles'), true);
  10153. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  10154. $global_roles = is_array($global_roles) ? $global_roles : [];
  10155. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  10156. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  10157. $art_style_type = getProp($anime, 'art_style_type');
  10158. // 检查并创建 roles 的图片生成任务
  10159. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  10160. // 检查并创建 scenes 的图片生成任务
  10161. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  10162. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  10163. if ($arr && is_array($arr)) {
  10164. $merged_roles = $arr['roles'];
  10165. $merged_scenes = $arr['scenes'];
  10166. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  10167. }
  10168. // 确保数据是数组类型
  10169. if (!is_array($merged_roles)) {
  10170. dLog('deepseek')->error('merged_roles不是数组类型', [
  10171. 'type' => gettype($merged_roles),
  10172. 'value' => $merged_roles
  10173. ]);
  10174. $merged_roles = [];
  10175. }
  10176. if (!is_array($merged_scenes)) {
  10177. dLog('deepseek')->error('merged_scenes不是数组类型', [
  10178. 'type' => gettype($merged_scenes),
  10179. 'value' => $merged_scenes
  10180. ]);
  10181. $merged_scenes = [];
  10182. }
  10183. if (!is_array($merged_props)) {
  10184. dLog('deepseek')->error('merged_props不是数组类型', [
  10185. 'type' => gettype($merged_props),
  10186. 'value' => $merged_props
  10187. ]);
  10188. $merged_props = [];
  10189. }
  10190. // 同步新出现的主体和场景到全局
  10191. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  10192. $role_arr = [];
  10193. foreach ($merged_roles as $item) {
  10194. $role_arr[$item['role']] = $item;
  10195. }
  10196. $version_count = DB::table('mp_anime_episodes')
  10197. ->where('anime_id', $anime_id)
  10198. ->where('episode_number', $episode_number)
  10199. ->count('id');
  10200. $episode = [
  10201. 'anime_id' => $anime_id,
  10202. 'episode_number' => $episode_number,
  10203. 'title' => getProp($episode_arr, 'episode_title'),
  10204. 'content' => $content,
  10205. 'intro' => getProp($episode_arr, 'intro'),
  10206. 'art_style' => getProp($episode_arr, 'art_style'),
  10207. 'roles' => json_encode($merged_roles, 256),
  10208. 'scenes' => json_encode($merged_scenes, 256),
  10209. 'props' => json_encode($merged_props, 256),
  10210. 'generate_status' => '待执行',
  10211. 'generate_at' => $now,
  10212. 'is_default' => 1,
  10213. 'updated_at' => $now,
  10214. ];
  10215. $del_flag = false;
  10216. if ($is_regenerate_version) {
  10217. DB::table('mp_anime_episodes')
  10218. ->where('anime_id', $anime_id)
  10219. ->where('episode_number', $episode_number)
  10220. ->update(['is_default' => 0, 'updated_at' => $now]);
  10221. $episode['sequence'] = $version_count + 1;
  10222. $episode['created_at'] = $now;
  10223. $episode['cpid'] = Site::getCpid();
  10224. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  10225. if (!$episode_id) {
  10226. Utils::throwError('20003:创建剧集版本失败');
  10227. }
  10228. } else {
  10229. $target_episode = $current_episode ?: $base_episode;
  10230. if ($target_episode) {
  10231. $episode_id = getProp($target_episode, 'id');
  10232. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  10233. DB::table('mp_anime_episodes')
  10234. ->where('anime_id', $anime_id)
  10235. ->where('episode_number', $episode_number)
  10236. ->where('id', '<>', $episode_id)
  10237. ->update(['is_default' => 0, 'updated_at' => $now]);
  10238. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  10239. if ($boolen === false) {
  10240. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  10241. Utils::throwError('20003:分集内容保存失败');
  10242. }
  10243. $del_flag = true;
  10244. } else {
  10245. DB::table('mp_anime_episodes')
  10246. ->where('anime_id', $anime_id)
  10247. ->where('episode_number', $episode_number)
  10248. ->update(['is_default' => 0, 'updated_at' => $now]);
  10249. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  10250. $episode['created_at'] = $now;
  10251. $episode['cpid'] = Site::getCpid();
  10252. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  10253. if (!$episode_id) {
  10254. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  10255. Utils::throwError('20003:分集内容保存失败');
  10256. }
  10257. }
  10258. }
  10259. $segments = [];
  10260. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  10261. // 如果是第2集及以后,获取上一集的主体音色数据
  10262. $previous_roles_voice = [];
  10263. if ($episode_number >= 2) {
  10264. $previous_episode = DB::table('mp_anime_episodes')
  10265. ->where('anime_id', $anime_id)
  10266. ->where('episode_number', $episode_number - 1)
  10267. ->where('is_default', 1)
  10268. ->first();
  10269. if ($previous_episode) {
  10270. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  10271. if (is_array($previous_roles)) {
  10272. foreach ($previous_roles as $prev_role) {
  10273. $role_name = getProp($prev_role, 'role');
  10274. if ($role_name) {
  10275. $previous_roles_voice[$role_name] = [
  10276. 'voice_name' => getProp($prev_role, 'voice_name'),
  10277. 'voice_type' => getProp($prev_role, 'voice_type'),
  10278. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  10279. ];
  10280. $voice_prompt = getProp($prev_role, 'voice_prompt');
  10281. if ($voice_prompt) {
  10282. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  10283. }
  10284. }
  10285. }
  10286. }
  10287. }
  10288. }
  10289. // 将继承的音色数据同步到当前集的主体列表
  10290. if (!empty($previous_roles_voice)) {
  10291. foreach ($merged_roles as &$role) {
  10292. $role_name = getProp($role, 'role');
  10293. if ($role_name && isset($previous_roles_voice[$role_name])) {
  10294. // 强制继承上一集的音色数据
  10295. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  10296. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  10297. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  10298. // 如果上一集有 voice_prompt 则继承,否则跳过
  10299. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  10300. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  10301. }
  10302. }
  10303. }
  10304. unset($role); // 解除引用
  10305. // 更新 role_arr 以便后续使用
  10306. $role_arr = [];
  10307. foreach ($merged_roles as $item) {
  10308. $role_arr[$item['role']] = $item;
  10309. }
  10310. }
  10311. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  10312. $emotion_list = array_flip($emotion_list);
  10313. foreach ($acts as $act) {
  10314. $act_segments = getProp($act, 'segments', []);
  10315. if (!is_array($act_segments)) {
  10316. continue;
  10317. }
  10318. if ((int)$ace_mode === 1) {
  10319. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  10320. $merged_parts = [];
  10321. foreach ($act_segments as $seg) {
  10322. $seg_num = getProp($seg, 'segment_number');
  10323. $seg_content = getProp($seg, 'segment_content');
  10324. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  10325. }
  10326. $act_content = implode("\n", $merged_parts);
  10327. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  10328. $segments[] = [
  10329. 'anime_id' => $anime_id,
  10330. 'episode_id' => $episode_id,
  10331. 'episode_number' => $episode_number,
  10332. 'act_number' => getProp($act, 'act_number'),
  10333. 'act_title' => getProp($act, 'act_title'),
  10334. 'act_duration' => getProp($act, 'act_duration'),
  10335. 'act_content' => $act_content,
  10336. 'created_at' => $now,
  10337. 'updated_at' => $now
  10338. ];
  10339. } else {
  10340. foreach ($act_segments as $segment) {
  10341. $voice_actor = getProp($segment, 'voice_actor');
  10342. // 优先从上一集继承音色数据
  10343. $timbre_info = [];
  10344. if (isset($previous_roles_voice[$voice_actor])) {
  10345. // 从上一集继承音色数据
  10346. $timbre_info = $previous_roles_voice[$voice_actor];
  10347. } elseif (isset($role_arr[$voice_actor])) {
  10348. // 使用当前集的主体音色数据
  10349. $timbre_info = $role_arr[$voice_actor];
  10350. }
  10351. $voice_type = getProp($timbre_info, 'voice_type');
  10352. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  10353. if ($timbre_emotion) {
  10354. $timbre_emotion = explode(',', $timbre_emotion);
  10355. } else {
  10356. $timbre_emotion = [];
  10357. }
  10358. $emotion = getProp($segment, 'emotion', '中性');
  10359. if (!in_array($emotion, $timbre_emotion)) {
  10360. $emotion = '中性';
  10361. }
  10362. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  10363. $segments[] = [
  10364. 'anime_id' => $anime_id,
  10365. 'episode_id' => $episode_id,
  10366. 'episode_number' => $episode_number,
  10367. 'act_number' => getProp($act, 'act_number'),
  10368. 'act_title' => getProp($act, 'act_title'),
  10369. 'act_duration' => getProp($act, 'act_duration'),
  10370. 'segment_id' => getProp($segment, 'segment_id'),
  10371. 'segment_number' => getProp($segment, 'segment_number'),
  10372. 'segment_content' => getProp($segment, 'segment_content'),
  10373. 'description' => getProp($segment, 'description'),
  10374. 'composition' => getProp($segment, 'composition'),
  10375. 'camera_movement' => getProp($segment, 'camera_movement'),
  10376. 'voice_actor' => $voice_actor,
  10377. 'dialogue' => getProp($segment, 'dialogue'),
  10378. 'frame_type' => getProp($segment, 'frame_type'),
  10379. 'scene' => getProp($segment, 'scene'),
  10380. 'characters' => getProp($segment, 'characters'),
  10381. 'tail_frame' => getProp($segment, 'tail_frame'),
  10382. 'voice_name' => getProp($timbre_info, 'voice_name'),
  10383. 'voice_type' => $voice_type,
  10384. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  10385. 'emotion' => $emotion,
  10386. 'emotion_type' => $emotion_type,
  10387. 'gender' => getProp($segment, 'gender', '0'),
  10388. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  10389. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  10390. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  10391. 'pitch' => getProp($segment, 'pitch', 0),
  10392. 'created_at' => $now,
  10393. 'updated_at' => $now
  10394. ];
  10395. }
  10396. }
  10397. }
  10398. if ($segments) {
  10399. if ($del_flag) {
  10400. DB::table('mp_episode_segments')
  10401. ->where('anime_id', $anime_id)
  10402. ->where('episode_id', $episode_id)
  10403. ->delete();
  10404. }
  10405. $boolen = DB::table('mp_episode_segments')->insert($segments);
  10406. if (!$boolen) {
  10407. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  10408. Utils::throwError('20003:分镜内容保存失败');
  10409. }
  10410. }
  10411. dLog('deepseek')->info('segments', $segments);
  10412. // ace_mode=1: acts 返回值按合并格式调整
  10413. if ((int)$ace_mode === 1) {
  10414. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  10415. $act_map = [];
  10416. foreach ($table_act_data as $item) {
  10417. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  10418. }
  10419. $restructured_acts = [];
  10420. foreach ($acts as $act) {
  10421. $act_segments = getProp($act, 'segments', []);
  10422. if (!is_array($act_segments)) {
  10423. continue;
  10424. }
  10425. $merged_parts = [];
  10426. foreach ($act_segments as $seg) {
  10427. $seg_num = getProp($seg, 'segment_number');
  10428. $seg_content = getProp($seg, 'segment_content');
  10429. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  10430. }
  10431. $act_content = implode("\n", $merged_parts);
  10432. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  10433. $restructured_acts[] = [
  10434. 'anime_id' => $anime_id,
  10435. 'episode_id' => $episode_id,
  10436. 'episode_number' => $episode_number,
  10437. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  10438. 'act_number' => getProp($act, 'act_number'),
  10439. 'act_title' => getProp($act, 'act_title'),
  10440. 'act_duration' => getProp($act, 'act_duration'),
  10441. 'act_content' => $act_content,
  10442. 'created_at' => $now,
  10443. 'updated_at' => $now,
  10444. ];
  10445. }
  10446. $acts = $restructured_acts;
  10447. }
  10448. $episode['episode_id'] = $episode_id;
  10449. $episode['roles'] = $merged_roles;
  10450. $episode['scenes'] = $merged_scenes;
  10451. $episode['props'] = $merged_props;
  10452. $episode['acts'] = $acts;
  10453. return [
  10454. 'episode' => $episode,
  10455. 'episode_id' => $episode_id,
  10456. 'merged_roles' => $merged_roles,
  10457. 'merged_scenes' => $merged_scenes,
  10458. 'merged_props' => $merged_props,
  10459. ];
  10460. }
  10461. private function buildEpisodeItemContent(array $items, string $nameKey): string
  10462. {
  10463. $content = '';
  10464. foreach ($items as $item) {
  10465. $name = trim((string)getProp($item, $nameKey));
  10466. if ($name === '' || $name === '旁白') {
  10467. continue;
  10468. }
  10469. $description = trim((string)getProp($item, 'description'));
  10470. $content .= $name . ': ' . $description;
  10471. if ($nameKey == 'role') {
  10472. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  10473. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10474. $voice_name = trim(getProp($item, 'voice_name'));
  10475. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  10476. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  10477. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  10478. }else {
  10479. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  10480. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10481. }
  10482. $content .= "\n";
  10483. }
  10484. return trim($content);
  10485. }
  10486. private function getEpisodeChatContent($animeId, $sequence, $content) {
  10487. if ((int)$sequence <= 0) {
  10488. return [];
  10489. }
  10490. $origin_content = '';
  10491. if ($content) {
  10492. $origin_content = '本集剧情内容:'.$content;
  10493. }else {
  10494. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  10495. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  10496. }
  10497. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  10498. // 获取分集信息
  10499. $episode = DB::table('mp_anime_episodes')
  10500. ->where('anime_id', $animeId)
  10501. ->where('episode_number', $sequence)
  10502. ->where('is_default', 1)
  10503. ->first();
  10504. if (!$episode) {
  10505. return [];
  10506. }
  10507. $episode_id = getProp($episode, 'id');
  10508. $episode_number = getProp($episode, 'episode_number');
  10509. $title = getProp($episode, 'title');
  10510. $intro = getProp($episode, 'intro');
  10511. $art_style = getProp($episode, 'art_style');
  10512. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10513. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10514. // 组装纯文本内容
  10515. $content = '';
  10516. // 添加分集标题和梗概
  10517. $content .= "###第{$episode_number}集:{$title}\n\n";
  10518. $content .= "###故事梗概\n";
  10519. $content .= trim($intro) . "\n\n";
  10520. // 添加美术风格
  10521. $content .= "###美术风格\n";
  10522. $content .= trim($art_style) . "\n\n";
  10523. // 添加主体列表
  10524. $content .= "###主体列表\n";
  10525. $pangbai_voice_prompt = "";
  10526. foreach ($roles as $role) {
  10527. $name = getProp($role, 'role');
  10528. $description = getProp($role, 'description');
  10529. $pic_prompt = getProp($role, 'pic_prompt');
  10530. $voice_prompt = getProp($role, 'voice_prompt');
  10531. $voice_name = getProp($role, 'voice_name');
  10532. $content .= "{$name}: {$description}";
  10533. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10534. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  10535. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  10536. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  10537. $content .= "\n";
  10538. }
  10539. $content .= "\n";
  10540. // 添加场景列表
  10541. $content .= "###场景列表\n";
  10542. foreach ($scenes as $scene) {
  10543. $name = getProp($scene, 'scene');
  10544. $description = getProp($scene, 'description');
  10545. $pic_prompt = getProp($scene, 'pic_prompt');
  10546. $content .= "{$name}: {$description}";
  10547. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  10548. $content .= "\n";
  10549. }
  10550. $content .= "\n";
  10551. // 获取分镜信息
  10552. $segments = DB::table('mp_episode_segments')
  10553. ->where('anime_id', $animeId)
  10554. ->where('episode_id', $episode_id)
  10555. ->orderBy('segment_number')
  10556. ->get();
  10557. if ($segments && count($segments) > 0) {
  10558. if ((int)$ace_mode === 1) {
  10559. $content .= "###分段剧本\n";
  10560. // 获取片段数量
  10561. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  10562. $content .= "片段数量:{$act_count}\n";
  10563. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  10564. $content .= "\n";
  10565. }else {
  10566. $content .= "###分镜剧本\n";
  10567. }
  10568. // 按幕分组
  10569. $currentAct = null;
  10570. foreach ($segments as $segment) {
  10571. $act_number = getProp($segment, 'act_number');
  10572. $act_title = getProp($segment, 'act_title');
  10573. $act_duration = getProp($segment, 'act_duration');
  10574. $segment_number = getProp($segment, 'segment_number');
  10575. $segment_content = getProp($segment, 'segment_content');
  10576. $scene_description = getProp($segment, 'scene_description');
  10577. $scene_name = getProp($segment, 'scene_name');
  10578. $composition = getProp($segment, 'composition');
  10579. $camera_movement = getProp($segment, 'camera_movement');
  10580. $voice_type = getProp($segment, 'voice_type');
  10581. $characters = getProp($segment, 'characters');
  10582. $dialogue = getProp($segment, 'dialogue');
  10583. $frame_type = getProp($segment, 'frame_type');
  10584. $tail_frame_description = getProp($segment, 'tail_frame_description');
  10585. // 判断是否是全能模式
  10586. if ((int)$ace_mode === 1) { // 全能模式
  10587. // 如果是新的分段,添加分段标题
  10588. if ($act_number !== $currentAct) {
  10589. $currentAct = $act_number;
  10590. $content .= "##{$act_title}\n";
  10591. $content .= "时长:{$act_duration}s\n";
  10592. }
  10593. }else {
  10594. // 如果是新的幕,添加幕标题
  10595. if ($act_number !== $currentAct) {
  10596. $currentAct = $act_number;
  10597. $content .= "##第{$act_number}幕:{$scene_name}\n";
  10598. }
  10599. }
  10600. // 添加分镜信息
  10601. $content .= "分镜{$segment_number}\n";
  10602. $content .= "分镜内容:\n{$segment_content}\n";
  10603. // $content .= "画面描述:{$scene_description}\n";
  10604. // $content .= "场景:{$scene_name}\n";
  10605. // $content .= "构图设计:{$composition}\n";
  10606. // $content .= "运镜调度:{$camera_movement}\n";
  10607. // if (!empty($voice_type)) {
  10608. // $content .= "配音角色:{$voice_type}\n";
  10609. // }
  10610. // if (!empty($characters)) {
  10611. // $content .= "出镜角色:{$characters}\n";
  10612. // }
  10613. // if (!empty($dialogue)) {
  10614. // $content .= "台词内容:\"{$dialogue}\"\n";
  10615. // }
  10616. // $content .= "画面类型:{$frame_type}\n";
  10617. // $content .= "尾帧描述:{$tail_frame_description}\n";
  10618. $content .= "\n";
  10619. }
  10620. }
  10621. $content = trim($content);
  10622. if($content) $content = "上集剧本内容:\n{$content}";
  10623. return [
  10624. [
  10625. 'role' => 'user',
  10626. 'content' => $origin_content
  10627. ],
  10628. [
  10629. 'role' => 'assistant',
  10630. 'content' => $content
  10631. ]
  10632. ];
  10633. }
  10634. private function getEpisodeChatMessages($animeId, $sequence): array
  10635. {
  10636. if ((int)$sequence <= 0) {
  10637. return [];
  10638. }
  10639. return DB::table('mp_anime_records')
  10640. ->where('anime_id', $animeId)
  10641. ->where('sequence', $sequence)
  10642. ->where('episode_id', '>', 0)
  10643. ->select('role', 'content')
  10644. ->orderBy('created_at')
  10645. ->orderBy('id')
  10646. ->get()
  10647. ->map(function ($value) {
  10648. return (array)$value;
  10649. })
  10650. ->toArray();
  10651. }
  10652. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  10653. {
  10654. $existingMap = [];
  10655. foreach ($existingItems as $item) {
  10656. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  10657. if ($itemKey === '') {
  10658. continue;
  10659. }
  10660. $existingMap[$itemKey] = $item;
  10661. }
  10662. if (!$generatedItems) {
  10663. return array_values($existingItems);
  10664. }
  10665. $merged = [];
  10666. foreach ($generatedItems as $item) {
  10667. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  10668. if ($itemKey === '') {
  10669. continue;
  10670. }
  10671. if (isset($existingMap[$itemKey])) {
  10672. if (trim((string)getProp($item, 'description')) === '') {
  10673. $merged[] = $existingMap[$itemKey];
  10674. continue;
  10675. }
  10676. // 检查内容是否发生变化
  10677. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  10678. if (!$isChanged) {
  10679. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  10680. $mergedItem = [
  10681. $nameKey => trim((string)getProp($item, $nameKey)),
  10682. 'description' => trim((string)getProp($item, 'description')),
  10683. ];
  10684. // 如果有 pic_prompt,添加到合并项中
  10685. $picPrompt = getProp($item, 'pic_prompt');
  10686. if (!empty($picPrompt)) {
  10687. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  10688. }
  10689. // 继承现有项的 URL
  10690. $existingUrl = getProp($existingMap[$itemKey], 'url');
  10691. if (!empty($existingUrl)) {
  10692. $mergedItem['url'] = $existingUrl;
  10693. }
  10694. // 继承现有项的 task_id
  10695. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  10696. if (!empty($existingTaskId)) {
  10697. $mergedItem['task_id'] = $existingTaskId;
  10698. }
  10699. // 继承现有项的 task_status
  10700. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  10701. if (!empty($existingTaskStatus)) {
  10702. $mergedItem['task_status'] = $existingTaskStatus;
  10703. }
  10704. // 保留生成项的音色字段
  10705. $voiceName = getProp($item, 'voice_name');
  10706. if (!empty($voiceName)) {
  10707. $mergedItem['voice_name'] = $voiceName;
  10708. }
  10709. $voiceType = getProp($item, 'voice_type');
  10710. if (!empty($voiceType)) {
  10711. $mergedItem['voice_type'] = $voiceType;
  10712. }
  10713. $audioUrl = getProp($item, 'voice_audio_url');
  10714. if (!empty($audioUrl)) {
  10715. $mergedItem['voice_audio_url'] = $audioUrl;
  10716. }
  10717. $merged[] = $mergedItem;
  10718. } else {
  10719. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  10720. $mergedItem = [
  10721. $nameKey => trim((string)getProp($item, $nameKey)),
  10722. 'description' => trim((string)getProp($item, 'description')),
  10723. ];
  10724. // 如果有 pic_prompt,添加到合并项中
  10725. $picPrompt = getProp($item, 'pic_prompt');
  10726. if (!empty($picPrompt)) {
  10727. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  10728. }
  10729. // 保留生成项的音色字段
  10730. $voiceName = getProp($item, 'voice_name');
  10731. if (!empty($voiceName)) {
  10732. $mergedItem['voice_name'] = $voiceName;
  10733. }
  10734. $voiceType = getProp($item, 'voice_type');
  10735. if (!empty($voiceType)) {
  10736. $mergedItem['voice_type'] = $voiceType;
  10737. }
  10738. $audioUrl = getProp($item, 'voice_audio_url');
  10739. if (!empty($audioUrl)) {
  10740. $mergedItem['voice_audio_url'] = $audioUrl;
  10741. }
  10742. // 不继承 URL、task_id 和 task_status(重置状态)
  10743. $merged[] = $mergedItem;
  10744. }
  10745. } else {
  10746. // 新增项,保留生成项的所有字段
  10747. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  10748. }
  10749. }
  10750. return $merged ?: array_values($existingItems);
  10751. }
  10752. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  10753. {
  10754. $resetItem = [
  10755. $nameKey => trim((string)getProp($item, $nameKey)),
  10756. 'description' => trim((string)getProp($item, 'description')),
  10757. ];
  10758. // 保留指定的字段
  10759. foreach ($preserveFields as $field) {
  10760. $value = getProp($item, $field);
  10761. if (!empty($value)) {
  10762. $resetItem[$field] = $value;
  10763. }
  10764. }
  10765. return $resetItem;
  10766. }
  10767. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  10768. {
  10769. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  10770. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  10771. if ($existingKey !== $generatedKey) {
  10772. return true;
  10773. }
  10774. // 比较 description 是否变化
  10775. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  10776. return true;
  10777. }
  10778. // 比较 pic_prompt 是否变化
  10779. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  10780. }
  10781. private function normalizeEpisodeResourceKey($value): string
  10782. {
  10783. $value = trim((string)$value);
  10784. if ($value === '') {
  10785. return '';
  10786. }
  10787. return strtolower((string)preg_replace('/\s+/u', '', $value));
  10788. }
  10789. // 生成全局角色图片
  10790. private function batchSetGlobalRoleImg($data, $is_force=false) {
  10791. $anime_id = getProp($data, 'anime_id');
  10792. if (!$anime_id) Utils::throwError('1002:请选择对话');
  10793. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10794. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10795. $art_style = getProp($anime, 'art_style');
  10796. $update_flag = false;
  10797. foreach ($roles as &$role) {
  10798. $role_name = getProp($role, 'role');
  10799. if ($role_name == '旁白') continue;
  10800. // 优先使用 pic_prompt,如果没有则使用 description
  10801. $pic_prompt = getProp($role, 'pic_prompt');
  10802. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  10803. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  10804. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  10805. // 参考图地址
  10806. $ref_img_url = getProp($role, 'url');
  10807. if (!$is_force && $ref_img_url) continue;
  10808. $update_flag = true;
  10809. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  10810. try {
  10811. $params = [
  10812. 'prompt' => $description,
  10813. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  10814. 'ref_img_urls' => []
  10815. ];
  10816. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10817. $task_id = $task->id;
  10818. if (!$task_id) {
  10819. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  10820. }
  10821. $role['task_id'] = $task_id;
  10822. $role['task_status'] = 'processing';
  10823. } catch (\Exception $e) {
  10824. Utils::throwError("20003:" . $e->getMessage());
  10825. }
  10826. }
  10827. if (!$update_flag) return true;
  10828. // 保存角色信息
  10829. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  10830. 'roles' => json_encode($roles, 256),
  10831. 'generate_status' => '执行中',
  10832. 'generate_at' => date('Y-m-d H:i:s'),
  10833. 'updated_at' => date('Y-m-d H:i:s')
  10834. ]);
  10835. if (!$boolen) {
  10836. Utils::throwError('20003:保存角色信息失败');
  10837. }
  10838. return $boolen;
  10839. }
  10840. // 生成全局场景图片
  10841. private function batchSetGlobalSceneImg($data, $is_force=false) {
  10842. $anime_id = getProp($data, 'anime_id');
  10843. if (!$anime_id) Utils::throwError('1002:请选择对话');
  10844. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10845. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10846. $art_style = getProp($anime, 'art_style');
  10847. $update_flag = false;
  10848. foreach ($scenes as &$scene) {
  10849. $scene_name = getProp($scene, 'scene');
  10850. // 优先使用 pic_prompt,如果没有则使用 description
  10851. $pic_prompt = getProp($scene, 'pic_prompt');
  10852. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  10853. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  10854. // 参考图地址
  10855. $ref_img_url = getProp($scene, 'url');
  10856. if (!$is_force && $ref_img_url) continue;
  10857. $update_flag = true;
  10858. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  10859. try {
  10860. $params = [
  10861. 'prompt' => $description,
  10862. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  10863. 'ref_img_urls' => []
  10864. ];
  10865. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10866. $task_id = $task->id;
  10867. if (!$task_id) {
  10868. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  10869. }
  10870. $scene['task_id'] = $task_id;
  10871. $scene['task_status'] = 'processing';
  10872. } catch (\Exception $e) {
  10873. Utils::throwError("20003:" . $e->getMessage());
  10874. }
  10875. }
  10876. if (!$update_flag) return true;
  10877. // 保存角色信息
  10878. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  10879. 'scenes' => json_encode($scenes, 256),
  10880. 'generate_status' => '执行中',
  10881. 'generate_at' => date('Y-m-d H:i:s'),
  10882. 'updated_at' => date('Y-m-d H:i:s')
  10883. ]);
  10884. if (!$boolen) {
  10885. Utils::throwError('20003:保存角色信息失败');
  10886. }
  10887. return $boolen;
  10888. }
  10889. // 生成分镜主体、场景和道具图片
  10890. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  10891. $character_prefix = '';
  10892. $scene_prefix = '';
  10893. $prop_prefix = '';
  10894. if ($art_style_type) {
  10895. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  10896. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  10897. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  10898. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  10899. }
  10900. $update_flag = false;
  10901. // 获取上一集的roles、scenes和props数据
  10902. $prev_roles = [];
  10903. $prev_scenes = [];
  10904. $prev_props = [];
  10905. if ($episode_number > 1) {
  10906. $prev_episode = DB::table('mp_anime_episodes')
  10907. ->where('anime_id', $anime_id)
  10908. ->where('episode_number', $episode_number - 1)
  10909. ->where('is_default', 1)
  10910. ->first();
  10911. if ($prev_episode) {
  10912. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  10913. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  10914. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  10915. dLog('deepseek')->info("获取上一集数据成功", [
  10916. 'anime_id' => $anime_id,
  10917. 'prev_episode_number' => $episode_number - 1,
  10918. 'prev_roles_count' => count($prev_roles),
  10919. 'prev_scenes_count' => count($prev_scenes),
  10920. 'prev_props_count' => count($prev_props)
  10921. ]);
  10922. }
  10923. }
  10924. // 处理角色图片生成
  10925. foreach ($roles as &$role) {
  10926. $role_name = getProp($role, 'role');
  10927. if ($role_name == '旁白') continue;
  10928. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  10929. if (isset($ref_products[$role_name])) {
  10930. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  10931. if ($role['url']) continue;
  10932. }
  10933. $role_description = getProp($role, 'description');
  10934. $role_pic_prompt = getProp($role, 'pic_prompt');
  10935. $role_url = getProp($role, 'url');
  10936. // 检查是否可以从上一集继承
  10937. $inherited = false;
  10938. if (!$is_force && !empty($prev_roles)) {
  10939. foreach ($prev_roles as $prev_role) {
  10940. $prev_role_name = getProp($prev_role, 'role');
  10941. $prev_description = getProp($prev_role, 'description');
  10942. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  10943. $prev_url = getProp($prev_role, 'url');
  10944. $prev_task_id = getProp($prev_role, 'task_id');
  10945. $prev_task_status = getProp($prev_role, 'task_status');
  10946. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  10947. if ($role_name == $prev_role_name
  10948. && $role_description == $prev_description
  10949. && $role_pic_prompt == $prev_pic_prompt
  10950. && !empty($prev_url)) {
  10951. $role['task_id'] = $prev_task_id;
  10952. $role['task_status'] = $prev_task_status;
  10953. $role['url'] = $prev_url;
  10954. $inherited = true;
  10955. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  10956. 'anime_id' => $anime_id,
  10957. 'episode_number' => $episode_number,
  10958. 'task_id' => $prev_task_id,
  10959. 'url' => $prev_url
  10960. ]);
  10961. break;
  10962. }
  10963. }
  10964. }
  10965. // 如果已继承或已有url,跳过生成
  10966. if ($inherited || (!$is_force && $role_url)) {
  10967. continue;
  10968. }
  10969. // 优先使用 pic_prompt,如果没有则使用 description
  10970. $pic_prompt = getProp($role, 'pic_prompt');
  10971. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  10972. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10973. $update_flag = true;
  10974. // 调用AIImageGenerationService的生成图片任务接口
  10975. try {
  10976. $params = [
  10977. 'prompt' => $description,
  10978. 'ref_img_urls' => []
  10979. ];
  10980. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10981. $task_id = $task->id;
  10982. if (!$task_id) {
  10983. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  10984. continue; // 不中断,继续处理其他角色
  10985. }
  10986. $role['task_id'] = $task_id;
  10987. $role['task_status'] = 'processing';
  10988. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  10989. 'anime_id' => $anime_id,
  10990. 'episode_number' => $episode_number,
  10991. 'task_id' => $task_id
  10992. ]);
  10993. } catch (\Exception $e) {
  10994. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  10995. // 不抛出异常,继续处理其他角色
  10996. }
  10997. }
  10998. // 处理场景图片生成
  10999. foreach ($scenes as &$scene) {
  11000. $scene_name = getProp($scene, 'scene');
  11001. $scene_description = getProp($scene, 'description');
  11002. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  11003. $scene_url = getProp($scene, 'url');
  11004. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  11005. if (isset($ref_products[$scene_name])) {
  11006. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  11007. if ($scene['url']) continue;
  11008. }
  11009. // 检查是否可以从上一集继承
  11010. $inherited = false;
  11011. if (!$is_force && !empty($prev_scenes)) {
  11012. foreach ($prev_scenes as $prev_scene) {
  11013. $prev_scene_name = getProp($prev_scene, 'scene');
  11014. $prev_description = getProp($prev_scene, 'description');
  11015. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  11016. $prev_url = getProp($prev_scene, 'url');
  11017. $prev_task_id = getProp($prev_scene, 'task_id');
  11018. $prev_task_status = getProp($prev_scene, 'task_status');
  11019. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  11020. if ($scene_name == $prev_scene_name
  11021. && $scene_description == $prev_description
  11022. && $scene_pic_prompt == $prev_pic_prompt
  11023. && !empty($prev_url)) {
  11024. $scene['task_id'] = $prev_task_id;
  11025. $scene['task_status'] = $prev_task_status;
  11026. $scene['url'] = $prev_url;
  11027. $inherited = true;
  11028. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  11029. 'anime_id' => $anime_id,
  11030. 'episode_number' => $episode_number,
  11031. 'task_id' => $prev_task_id,
  11032. 'url' => $prev_url
  11033. ]);
  11034. break;
  11035. }
  11036. }
  11037. }
  11038. // 如果已继承或已有url,跳过生成
  11039. if ($inherited || (!$is_force && $scene_url)) {
  11040. continue;
  11041. }
  11042. // 优先使用 pic_prompt,如果没有则使用 description
  11043. $pic_prompt = getProp($scene, 'pic_prompt');
  11044. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  11045. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11046. $update_flag = true;
  11047. // 调用AIImageGenerationService的生成图片任务接口
  11048. try {
  11049. $params = [
  11050. 'prompt' => $description,
  11051. 'ref_img_urls' => []
  11052. ];
  11053. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11054. $task_id = $task->id;
  11055. if (!$task_id) {
  11056. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  11057. continue; // 不中断,继续处理其他场景
  11058. }
  11059. $scene['task_id'] = $task_id;
  11060. $scene['task_status'] = 'processing';
  11061. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  11062. 'anime_id' => $anime_id,
  11063. 'episode_number' => $episode_number,
  11064. 'task_id' => $task_id
  11065. ]);
  11066. } catch (\Exception $e) {
  11067. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  11068. // 不抛出异常,继续处理其他场景
  11069. }
  11070. }
  11071. // 处理道具图片生成(逻辑与场景一致)
  11072. foreach ($props as &$prop) {
  11073. $prop_name = getProp($prop, 'prop');
  11074. $prop_description = getProp($prop, 'description');
  11075. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  11076. $prop_url = getProp($prop, 'url');
  11077. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  11078. if (isset($ref_products[$prop_name])) {
  11079. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  11080. if ($prop['url']) continue;
  11081. }
  11082. // 检查是否可以从上一集继承
  11083. $inherited = false;
  11084. if (!$is_force && !empty($prev_props)) {
  11085. foreach ($prev_props as $prev_prop) {
  11086. $prev_prop_name = getProp($prev_prop, 'prop');
  11087. $prev_description = getProp($prev_prop, 'description');
  11088. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  11089. $prev_url = getProp($prev_prop, 'url');
  11090. $prev_task_id = getProp($prev_prop, 'task_id');
  11091. $prev_task_status = getProp($prev_prop, 'task_status');
  11092. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  11093. if ($prop_name == $prev_prop_name
  11094. && $prop_description == $prev_description
  11095. && $prop_pic_prompt == $prev_pic_prompt
  11096. && !empty($prev_url)) {
  11097. $prop['task_id'] = $prev_task_id;
  11098. $prop['task_status'] = $prev_task_status;
  11099. $prop['url'] = $prev_url;
  11100. $inherited = true;
  11101. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  11102. 'anime_id' => $anime_id,
  11103. 'episode_number' => $episode_number,
  11104. 'task_id' => $prev_task_id,
  11105. 'url' => $prev_url
  11106. ]);
  11107. break;
  11108. }
  11109. }
  11110. }
  11111. // 如果已继承或已有url,跳过生成
  11112. if ($inherited || (!$is_force && $prop_url)) {
  11113. continue;
  11114. }
  11115. // 优先使用 pic_prompt,如果没有则使用 description
  11116. $pic_prompt = getProp($prop, 'pic_prompt');
  11117. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  11118. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  11119. $update_flag = true;
  11120. // 调用AIImageGenerationService的生成图片任务接口
  11121. try {
  11122. $params = [
  11123. 'prompt' => $description,
  11124. 'ref_img_urls' => []
  11125. ];
  11126. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11127. $task_id = $task->id;
  11128. if (!$task_id) {
  11129. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  11130. continue; // 不中断,继续处理其他道具
  11131. }
  11132. $prop['task_id'] = $task_id;
  11133. $prop['task_status'] = 'processing';
  11134. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  11135. 'anime_id' => $anime_id,
  11136. 'episode_number' => $episode_number,
  11137. 'task_id' => $task_id
  11138. ]);
  11139. } catch (\Exception $e) {
  11140. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  11141. // 不抛出异常,继续处理其他道具
  11142. }
  11143. }
  11144. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  11145. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  11146. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  11147. // // 保存剧集的角色和场景信息
  11148. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  11149. // 'roles' => json_encode($roles, 256),
  11150. // 'scenes' => json_encode($scenes, 256),
  11151. // 'generate_status' => '执行中',
  11152. // 'generate_at' => date('Y-m-d H:i:s'),
  11153. // 'updated_at' => date('Y-m-d H:i:s')
  11154. // ]);
  11155. // if (!$boolen) {
  11156. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  11157. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  11158. // }
  11159. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  11160. // 'episode_id' => $episode_id,
  11161. 'roles_count' => count($roles),
  11162. 'scenes_count' => count($scenes),
  11163. 'props_count' => count($props)
  11164. ]);
  11165. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  11166. }
  11167. /**
  11168. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  11169. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  11170. *
  11171. * @param int $anime_id 动漫对话ID
  11172. * @param array $episode_roles 剧集角色数据
  11173. * @param array $episode_scenes 剧集场景数据
  11174. * @param array $episode_props 剧集道具数据
  11175. * @return bool
  11176. */
  11177. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  11178. // 获取全局数据
  11179. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11180. if (!$anime) {
  11181. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  11182. return false;
  11183. }
  11184. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11185. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11186. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  11187. $roles_added = false;
  11188. $roles_updated = false;
  11189. $scenes_added = false;
  11190. $props_added = false;
  11191. // 处理角色同步
  11192. foreach ($episode_roles as $episode_role) {
  11193. $episode_role_name = getProp($episode_role, 'role');
  11194. $episode_description = getProp($episode_role, 'description');
  11195. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  11196. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  11197. // 跳过旁白
  11198. if ($episode_role_name == '旁白') {
  11199. continue;
  11200. }
  11201. // 检查全局中是否已存在相同的角色
  11202. $exists = false;
  11203. $global_role_index = -1;
  11204. foreach ($global_roles as $index => $global_role) {
  11205. $global_role_name = getProp($global_role, 'role');
  11206. $global_description = getProp($global_role, 'description');
  11207. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  11208. // 如果role、description、pic_prompt三项都一致,则认为已存在
  11209. if ($episode_role_name == $global_role_name
  11210. && $episode_description == $global_description
  11211. && $episode_pic_prompt == $global_pic_prompt) {
  11212. $exists = true;
  11213. $global_role_index = $index;
  11214. break;
  11215. }
  11216. }
  11217. // 如果不存在,则添加到全局
  11218. if (!$exists) {
  11219. $global_roles[] = $episode_role;
  11220. $roles_added = true;
  11221. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  11222. 'anime_id' => $anime_id,
  11223. 'role' => $episode_role_name
  11224. ]);
  11225. } else {
  11226. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  11227. if (!empty($episode_voice_prompt)) {
  11228. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  11229. // 如果全局没有voice_prompt或与剧集不一致,则更新
  11230. if ($global_voice_prompt !== $episode_voice_prompt) {
  11231. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  11232. $roles_updated = true;
  11233. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  11234. 'anime_id' => $anime_id,
  11235. 'role' => $episode_role_name,
  11236. 'voice_prompt' => $episode_voice_prompt
  11237. ]);
  11238. }
  11239. }
  11240. }
  11241. }
  11242. // 处理场景同步
  11243. foreach ($episode_scenes as $episode_scene) {
  11244. $episode_scene_name = getProp($episode_scene, 'scene');
  11245. $episode_description = getProp($episode_scene, 'description');
  11246. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  11247. // 检查全局中是否已存在相同的场景
  11248. $exists = false;
  11249. foreach ($global_scenes as $global_scene) {
  11250. $global_scene_name = getProp($global_scene, 'scene');
  11251. $global_description = getProp($global_scene, 'description');
  11252. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  11253. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  11254. if ($episode_scene_name == $global_scene_name
  11255. && $episode_description == $global_description
  11256. && $episode_pic_prompt == $global_pic_prompt) {
  11257. $exists = true;
  11258. break;
  11259. }
  11260. }
  11261. // 如果不存在,则添加到全局
  11262. if (!$exists) {
  11263. $global_scenes[] = $episode_scene;
  11264. $scenes_added = true;
  11265. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  11266. 'anime_id' => $anime_id,
  11267. 'scene' => $episode_scene_name
  11268. ]);
  11269. }
  11270. }
  11271. // 处理道具同步(逻辑与场景一致)
  11272. foreach ($episode_props as $episode_prop) {
  11273. $episode_prop_name = getProp($episode_prop, 'prop');
  11274. $episode_description = getProp($episode_prop, 'description');
  11275. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  11276. // 检查全局中是否已存在相同的道具
  11277. $exists = false;
  11278. foreach ($global_props as $global_prop) {
  11279. $global_prop_name = getProp($global_prop, 'prop');
  11280. $global_description = getProp($global_prop, 'description');
  11281. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  11282. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  11283. if ($episode_prop_name == $global_prop_name
  11284. && $episode_description == $global_description
  11285. && $episode_pic_prompt == $global_pic_prompt) {
  11286. $exists = true;
  11287. break;
  11288. }
  11289. }
  11290. // 如果不存在,则添加到全局
  11291. if (!$exists) {
  11292. $global_props[] = $episode_prop;
  11293. $props_added = true;
  11294. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  11295. 'anime_id' => $anime_id,
  11296. 'prop' => $episode_prop_name
  11297. ]);
  11298. }
  11299. }
  11300. // 如果有新增或更新,则更新全局数据
  11301. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  11302. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  11303. if ($roles_added || $roles_updated) {
  11304. $update_data['roles'] = json_encode($global_roles, 256);
  11305. }
  11306. if ($scenes_added) {
  11307. $update_data['scenes'] = json_encode($global_scenes, 256);
  11308. }
  11309. if ($props_added) {
  11310. $update_data['props'] = json_encode($global_props, 256);
  11311. }
  11312. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  11313. dLog('deepseek')->info('剧集数据同步到全局完成', [
  11314. 'anime_id' => $anime_id,
  11315. 'roles_added' => $roles_added,
  11316. 'roles_updated' => $roles_updated,
  11317. 'scenes_added' => $scenes_added,
  11318. 'props_added' => $props_added,
  11319. 'global_roles_count' => count($global_roles),
  11320. 'global_scenes_count' => count($global_scenes),
  11321. 'global_props_count' => count($global_props)
  11322. ]);
  11323. }
  11324. return true;
  11325. }
  11326. /**
  11327. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  11328. *
  11329. * @param int $anime_id 动漫对话ID
  11330. * @param int $episode_id 分集ID
  11331. * @return bool
  11332. */
  11333. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  11334. // 获取全局角色和场景数据
  11335. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  11336. if (!$anime) {
  11337. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  11338. return false;
  11339. }
  11340. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  11341. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  11342. // 获取指定的分集
  11343. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  11344. if (!$episode) {
  11345. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  11346. return false;
  11347. }
  11348. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  11349. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  11350. $roles_updated = false;
  11351. $scenes_updated = false;
  11352. // 继承角色的task_id、task_status和url
  11353. foreach ($episode_roles as &$episode_role) {
  11354. $episode_role_name = getProp($episode_role, 'role');
  11355. $episode_description = getProp($episode_role, 'description');
  11356. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  11357. $episode_url = getProp($episode_role, 'url');
  11358. // 跳过旁白角色
  11359. if ($episode_role_name == '旁白') {
  11360. continue;
  11361. }
  11362. // 如果剧集中已有URL,跳过
  11363. if (!empty($episode_url)) {
  11364. continue;
  11365. }
  11366. // 遍历全局角色数据,查找匹配的角色
  11367. foreach ($global_roles as $global_role) {
  11368. $global_role_name = getProp($global_role, 'role');
  11369. $global_description = getProp($global_role, 'description');
  11370. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  11371. $global_url = getProp($global_role, 'url');
  11372. $global_task_id = getProp($global_role, 'task_id');
  11373. $global_task_status = getProp($global_role, 'task_status');
  11374. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  11375. if ($episode_role_name == $global_role_name
  11376. && $episode_description == $global_description
  11377. && $episode_pic_prompt == $global_pic_prompt) {
  11378. // 继承 task_id、task_status 和 url
  11379. if (!empty($global_task_id)) {
  11380. $episode_role['task_id'] = $global_task_id;
  11381. $episode_role['task_status'] = $global_task_status;
  11382. $roles_updated = true;
  11383. dLog('deepseek')->info('剧集角色继承全局task_id', [
  11384. 'episode_id' => $episode_id,
  11385. 'role' => $episode_role_name,
  11386. 'task_id' => $global_task_id,
  11387. 'task_status' => $global_task_status
  11388. ]);
  11389. }
  11390. if (!empty($global_url)) {
  11391. $episode_role['url'] = $global_url;
  11392. $roles_updated = true;
  11393. dLog('deepseek')->info('剧集角色继承全局url', [
  11394. 'episode_id' => $episode_id,
  11395. 'role' => $episode_role_name,
  11396. 'url' => $global_url
  11397. ]);
  11398. }
  11399. break;
  11400. }
  11401. }
  11402. }
  11403. // 继承场景的task_id、task_status和url
  11404. foreach ($episode_scenes as &$episode_scene) {
  11405. $episode_scene_name = getProp($episode_scene, 'scene');
  11406. $episode_description = getProp($episode_scene, 'description');
  11407. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  11408. $episode_url = getProp($episode_scene, 'url');
  11409. // 如果剧集中已有URL,跳过
  11410. if (!empty($episode_url)) {
  11411. continue;
  11412. }
  11413. // 遍历全局场景数据,查找匹配的场景
  11414. foreach ($global_scenes as $global_scene) {
  11415. $global_scene_name = getProp($global_scene, 'scene');
  11416. $global_description = getProp($global_scene, 'description');
  11417. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  11418. $global_url = getProp($global_scene, 'url');
  11419. $global_task_id = getProp($global_scene, 'task_id');
  11420. $global_task_status = getProp($global_scene, 'task_status');
  11421. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  11422. if ($episode_scene_name == $global_scene_name
  11423. && $episode_description == $global_description
  11424. && $episode_pic_prompt == $global_pic_prompt) {
  11425. // 继承 task_id、task_status 和 url
  11426. if (!empty($global_task_id)) {
  11427. $episode_scene['task_id'] = $global_task_id;
  11428. $episode_scene['task_status'] = $global_task_status;
  11429. $scenes_updated = true;
  11430. dLog('deepseek')->info('剧集场景继承全局task_id', [
  11431. 'episode_id' => $episode_id,
  11432. 'scene' => $episode_scene_name,
  11433. 'task_id' => $global_task_id,
  11434. 'task_status' => $global_task_status
  11435. ]);
  11436. }
  11437. if (!empty($global_url)) {
  11438. $episode_scene['url'] = $global_url;
  11439. $scenes_updated = true;
  11440. dLog('deepseek')->info('剧集场景继承全局url', [
  11441. 'episode_id' => $episode_id,
  11442. 'scene' => $episode_scene_name,
  11443. 'url' => $global_url
  11444. ]);
  11445. }
  11446. break;
  11447. }
  11448. }
  11449. }
  11450. // 如果有更新,则保存到数据库
  11451. if ($roles_updated || $scenes_updated) {
  11452. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  11453. if ($roles_updated) {
  11454. $update_data['roles'] = json_encode($episode_roles, 256);
  11455. }
  11456. if ($scenes_updated) {
  11457. $update_data['scenes'] = json_encode($episode_scenes, 256);
  11458. }
  11459. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  11460. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  11461. 'episode_id' => $episode_id,
  11462. 'roles_updated' => $roles_updated,
  11463. 'scenes_updated' => $scenes_updated
  11464. ]);
  11465. }
  11466. return true;
  11467. }
  11468. public function chatChangeImg($data) {
  11469. $segment = getProp($data, 'segment');
  11470. $segment_content = getProp($segment, 'segment_content');
  11471. $prompt = getProp($data, 'prompt');
  11472. $ref_img = getProp($data, 'ref_img');
  11473. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  11474. // 处理文本模型
  11475. $model = getProp($data, 'model');
  11476. if (!$model) {
  11477. // 用户没有输入,从anime表获取
  11478. $segment_id = getProp($segment, 'segment_id');
  11479. if ($segment_id) {
  11480. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  11481. if ($episode_id) {
  11482. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  11483. if ($anime_id) {
  11484. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  11485. }
  11486. }
  11487. }
  11488. if (!$model) {
  11489. // anime表也没有,使用默认值
  11490. $model = 'doubao-seed-2-0-mini-260215';
  11491. }
  11492. }
  11493. // 验证模型是否在可用模型表中
  11494. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  11495. $model = 'doubao-seed-2-0-mini-260215';
  11496. }
  11497. $messages[] =
  11498. [
  11499. 'role' => 'user',
  11500. 'content' => $question
  11501. ];
  11502. $post_data = [
  11503. 'model' => $model,
  11504. 'messages' => $messages,
  11505. // 'max_tokens' => 8192,
  11506. 'temperature' => 0.7,
  11507. 'frequency_penalty' => 0,
  11508. 'presence_penalty' => 0,
  11509. 'response_format' => ['type' => 'text'],
  11510. 'stream' => false // 是否启用流式输出
  11511. ];
  11512. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11513. // DeepSeek 官方模型使用 DeepSeek API
  11514. $chatResult = $this->chatOnly($post_data);
  11515. } else if (in_array($model, $this->gpt_text_models)) {
  11516. // GPT-5.4 模型使用 TokenRouter API
  11517. $chatResult = $this->gpt54ChatOnly($post_data);
  11518. } else {
  11519. // 其他模型使用火山引擎API
  11520. $chatResult = $this->volcEngineChatCompletion($post_data);
  11521. }
  11522. if (is_array($chatResult)) {
  11523. extract($chatResult);
  11524. }else {
  11525. Utils::throwError('20003: 接口调用失败!');
  11526. }
  11527. return [
  11528. 'type' => 'done',
  11529. // 'episode' => $episode,
  11530. 'answer' => $fullContent,
  11531. 'reasoning' => $fullReasoningContent,
  11532. 'usage' => $usage
  11533. ];
  11534. }
  11535. /**
  11536. * 仅调用 deepseek 对话接口(非流式)
  11537. *
  11538. * @param array $post_data
  11539. * @param int $timeout
  11540. * @return array
  11541. */
  11542. private function chatOnly($post_data, $timeout = 1800) {
  11543. $post_data['max_tokens'] = 300000;
  11544. $client = new Client(['timeout' => $timeout, 'verify' => false]);
  11545. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  11546. $response = $result->getBody()->getContents();
  11547. $response_arr = json_decode($response, true);
  11548. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  11549. $fullContent = '';
  11550. $fullReasoningContent = [];
  11551. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  11552. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  11553. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  11554. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  11555. }
  11556. return [
  11557. 'fullContent' => $fullContent,
  11558. 'fullReasoningContent' => $fullReasoningContent,
  11559. 'usage' => $usage
  11560. ];
  11561. }
  11562. /**
  11563. * 用 deepseek-v4-flash 非流式分析报错,返回不超过50字的用户友好提示
  11564. *
  11565. * @param string $errorMessage
  11566. * @return string|null
  11567. */
  11568. public function analyzeErrorMessage($errorMessage)
  11569. {
  11570. try {
  11571. $post_data = [
  11572. 'model' => 'deepseek-v4-flash',
  11573. 'messages' => [
  11574. [
  11575. 'role' => 'system',
  11576. 'content' => '你是视频生成任务的报错分析助手。请根据用户给出的原始报错,用一句中文提示告诉用户问题原因和下一步怎么做,不超过50个字,直接输出提示内容,不要解释、不要输出代码。',
  11577. ],
  11578. [
  11579. 'role' => 'user',
  11580. 'content' => (string)$errorMessage,
  11581. ],
  11582. ],
  11583. 'temperature' => 0.3,
  11584. 'frequency_penalty' => 0,
  11585. 'presence_penalty' => 0,
  11586. 'response_format' => ['type' => 'text'],
  11587. 'stream' => false,
  11588. ];
  11589. $result = $this->chatOnly($post_data, 8);
  11590. $content = trim((string)($result['fullContent'] ?? ''));
  11591. if ($content === '') {
  11592. return null;
  11593. }
  11594. return mb_substr($content, 0, 50);
  11595. } catch (\Exception $e) {
  11596. dLog('deepseek')->error('视频任务报错分析失败: ' . $e->getMessage(), [
  11597. 'error_message' => $errorMessage
  11598. ]);
  11599. return null;
  11600. }
  11601. }
  11602. // 仅调用 GPT-5.4 对话接口(非流式)
  11603. private function gpt54ChatOnly($post_data) {
  11604. $apiKey = env('GPT_54_API_KEY');
  11605. if (empty($apiKey)) {
  11606. Utils::throwError('20003:GPT-5.4 API Key未配置');
  11607. }
  11608. // 先探活,服务不可用时自动重试
  11609. $this->ensureGptServiceAvailable();
  11610. $client = new Client(['timeout' => 1800, 'verify' => false]);
  11611. $headers = [
  11612. 'Authorization' => 'Bearer ' . $apiKey,
  11613. 'Content-Type' => 'application/json'
  11614. ];
  11615. // 移除 thinking 参数,GPT-5.4 不支持
  11616. if (isset($post_data['thinking'])) {
  11617. unset($post_data['thinking']);
  11618. }
  11619. if (isset($post_data['reasoning_effort'])) {
  11620. unset($post_data['reasoning_effort']);
  11621. }
  11622. $post_data['max_completion_tokens'] = 100000;
  11623. // 确保 stream 为 false
  11624. $post_data['stream'] = false;
  11625. $maxRetries = $this->gptRetryTimes();
  11626. $interval = $this->gptRetryInterval();
  11627. $attempt = 0;
  11628. while (true) {
  11629. try {
  11630. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  11631. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  11632. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  11633. 'json' => $post_data,
  11634. 'headers' => $headers
  11635. ]);
  11636. $response = $result->getBody()->getContents();
  11637. $response_arr = json_decode($response, true);
  11638. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  11639. $fullContent = '';
  11640. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  11641. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  11642. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  11643. }
  11644. return [
  11645. 'fullContent' => $fullContent,
  11646. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  11647. 'usage' => $usage
  11648. ];
  11649. } catch (\Exception $e) {
  11650. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  11651. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  11652. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  11653. throw $e;
  11654. }
  11655. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  11656. 'retry' => $attempt + 1,
  11657. 'max_retries' => $maxRetries,
  11658. 'error' => $e->getMessage()
  11659. ]);
  11660. sleep($interval);
  11661. $attempt++;
  11662. }
  11663. }
  11664. }
  11665. private function splitContent($content) {
  11666. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  11667. $chapters = [];
  11668. // 匹配章节标题格式:
  11669. // 1. 标题可能独占一行,也可能在正文末尾或中间
  11670. // 2. 格式支持:
  11671. // - **第一集**
  11672. // - 第一集:
  11673. // - ###第1章 重生
  11674. // - ##第2章 相救
  11675. // - 第三章 共处一室
  11676. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  11677. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  11678. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  11679. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  11680. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  11681. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  11682. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  11683. // 先在每个标题前插入换行符(如果前面不是换行的话)
  11684. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  11685. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  11686. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  11687. // 用正则找出所有章节标题的位置
  11688. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  11689. $titleCount = count($matches[0]);
  11690. for ($i = 0; $i < $titleCount; $i++) {
  11691. // 获取当前章节标题
  11692. $titleLine = trim($matches[0][$i][0]);
  11693. // 去除标题开头的特殊符号
  11694. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  11695. // 去除标题结尾的冒号和特殊符号
  11696. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  11697. $cleanTitle = trim($cleanTitle);
  11698. // 获取当前标题的结束位置
  11699. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  11700. // 获取下一个章节标题的开始位置(如果存在)
  11701. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  11702. // 提取章节内容(从标题结束到下一个标题开始)
  11703. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  11704. // 清理内容:去除前后空白和分隔线
  11705. $chapterContent = trim($chapterContent);
  11706. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  11707. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  11708. if (!empty($cleanTitle) && !empty($chapterContent)) {
  11709. $chapters[] = [
  11710. 'title' => $cleanTitle,
  11711. 'content' => $chapterContent
  11712. ];
  11713. }
  11714. }
  11715. } else {
  11716. // 如果没有匹配到章节,返回整个内容
  11717. $chapters[] = [
  11718. 'title' => '',
  11719. 'content' => $content
  11720. ];
  11721. }
  11722. return $chapters;
  11723. }
  11724. public function getContentByBid($bid) {
  11725. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  11726. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  11727. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  11728. $content = '';
  11729. foreach ($chapters as $chapter) {
  11730. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  11731. }
  11732. return $content;
  11733. }
  11734. public function getContentByScriptId($script_id) {
  11735. $content = '';
  11736. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  11737. if ($contents) {
  11738. $content = implode(PHP_EOL, $contents);
  11739. }else {
  11740. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  11741. }
  11742. return $content;
  11743. }
  11744. /**
  11745. * 根据文件类型提取文本内容
  11746. *
  11747. * @param mixed $file 文件对象或文件路径
  11748. * @return string
  11749. */
  11750. public function extractFileContent($file) {
  11751. // 获取文件路径和扩展名
  11752. if (is_string($file)) {
  11753. $filePath = $file;
  11754. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  11755. } else {
  11756. // Laravel UploadedFile 对象
  11757. $filePath = $file->getRealPath();
  11758. $extension = strtolower($file->getClientOriginalExtension());
  11759. }
  11760. $content = '';
  11761. switch ($extension) {
  11762. case 'txt':
  11763. $content = $this->extractTxtContent($filePath);
  11764. break;
  11765. case 'pdf':
  11766. $content = $this->extractPdfContent($filePath);
  11767. break;
  11768. case 'doc':
  11769. case 'docx':
  11770. $content = $this->extractWordContent($filePath);
  11771. break;
  11772. // case 'jpg':
  11773. // case 'jpeg':
  11774. // case 'png':
  11775. // case 'gif':
  11776. // case 'bmp':
  11777. // case 'webp':
  11778. // $content = $this->extractImageContent($filePath);
  11779. // break;
  11780. default:
  11781. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  11782. }
  11783. return $content;
  11784. }
  11785. /**
  11786. * 提取 TXT 文件内容
  11787. */
  11788. private function extractTxtContent($filePath) {
  11789. if (!file_exists($filePath)) {
  11790. Utils::throwError('20003:文件不存在');
  11791. }
  11792. $content = file_get_contents($filePath);
  11793. // 尝试检测并转换编码
  11794. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  11795. if ($encoding && $encoding !== 'UTF-8') {
  11796. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  11797. }
  11798. return trim($content);
  11799. }
  11800. /**
  11801. * 提取 PDF 文件内容
  11802. */
  11803. private function extractPdfContent($filePath) {
  11804. if (!file_exists($filePath)) {
  11805. Utils::throwError('20003:文件不存在');
  11806. }
  11807. try {
  11808. $parser = new PdfParser();
  11809. $pdf = $parser->parseFile($filePath);
  11810. $content = $pdf->getText();
  11811. return trim($content);
  11812. } catch (\Exception $e) {
  11813. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  11814. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  11815. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  11816. }
  11817. }
  11818. /**
  11819. * 提取 Word 文件内容(支持 doc 和 docx)
  11820. */
  11821. private function extractWordContent($filePath) {
  11822. if (!file_exists($filePath)) {
  11823. Utils::throwError('20003:文件不存在');
  11824. }
  11825. try {
  11826. $phpWord = WordIOFactory::load($filePath);
  11827. $content = '';
  11828. foreach ($phpWord->getSections() as $section) {
  11829. foreach ($section->getElements() as $element) {
  11830. $content .= $this->extractWordElementText($element);
  11831. }
  11832. }
  11833. return trim($content);
  11834. } catch (\Exception $e) {
  11835. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  11836. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  11837. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  11838. }
  11839. }
  11840. /**
  11841. * 递归提取 Word 元素中的文本
  11842. */
  11843. private function extractWordElementText($element) {
  11844. $text = '';
  11845. if (method_exists($element, 'getText')) {
  11846. $text .= $element->getText() . "\n";
  11847. } elseif (method_exists($element, 'getElements')) {
  11848. foreach ($element->getElements() as $childElement) {
  11849. $text .= $this->extractWordElementText($childElement);
  11850. }
  11851. }
  11852. return $text;
  11853. }
  11854. /**
  11855. * 提取图片内容(使用火山引擎 OCR)
  11856. */
  11857. private function extractImageContent($filePath) {
  11858. if (!file_exists($filePath)) {
  11859. Utils::throwError('20003:文件不存在');
  11860. }
  11861. try {
  11862. // 读取图片并转换为 base64
  11863. $imageData = file_get_contents($filePath);
  11864. $base64Image = base64_encode($imageData);
  11865. // 调用火山引擎 OCR 服务
  11866. $content = $this->callVolcEngineOCR($base64Image);
  11867. return trim($content);
  11868. } catch (\Exception $e) {
  11869. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  11870. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  11871. Utils::throwError('20003:图片识别失败');
  11872. }
  11873. }
  11874. /**
  11875. * 调用火山引擎 OCR 服务识别图片文字
  11876. *
  11877. * @param string $base64Image base64 编码的图片数据
  11878. * @return string 识别的文字内容
  11879. */
  11880. private function callVolcEngineOCR($base64Image) {
  11881. $method = 'POST';
  11882. $service = 'cv';
  11883. $host = 'visual.volcengineapi.com';
  11884. $region = env('VOLC_REGION', 'cn-north-1');
  11885. $access_key = env('VOLC_AK');
  11886. $secret_key = env('VOLC_SK');
  11887. $action = 'OCRNormal';
  11888. $version = '2020-08-26';
  11889. if (!$access_key || !$secret_key) {
  11890. Utils::throwError('20003:请配置火山引擎 AK/SK');
  11891. }
  11892. // 请求体
  11893. $body = json_encode([
  11894. 'image_base64' => $base64Image
  11895. ]);
  11896. // 生成签名
  11897. $headers = $this->getVolcEngineSignHeaders(
  11898. $method, $service, $host, $region,
  11899. "Action={$action}&Version={$version}",
  11900. $access_key, $secret_key, $body
  11901. );
  11902. $client = new Client(['timeout' => 1800, 'verify' => false]);
  11903. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  11904. 'headers' => $headers,
  11905. 'body' => $body
  11906. ]);
  11907. $response_arr = json_decode($response->getBody()->getContents(), true);
  11908. // 提取识别的文字
  11909. $textLines = [];
  11910. if (isset($response_arr['data']['line_texts'])) {
  11911. $textLines = $response_arr['data']['line_texts'];
  11912. } elseif (isset($response_arr['data']['ocr_infos'])) {
  11913. foreach ($response_arr['data']['ocr_infos'] as $info) {
  11914. if (isset($info['text'])) {
  11915. $textLines[] = $info['text'];
  11916. }
  11917. }
  11918. }
  11919. if (empty($textLines)) {
  11920. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  11921. return '';
  11922. }
  11923. return implode("\n", $textLines);
  11924. }
  11925. /**
  11926. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  11927. */
  11928. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  11929. $contentType = 'application/json';
  11930. $accept = 'application/json';
  11931. // 获取当前UTC时间
  11932. $t = new DateTime('now', new DateTimeZone('UTC'));
  11933. $xDate = $t->format('Ymd\THis\Z');
  11934. $dateStamp = $t->format('Ymd');
  11935. // 计算 body 的 sha256 哈希
  11936. $payloadHash = hash('sha256', $body);
  11937. // 1. 拼接规范请求串
  11938. $canonicalUri = '/';
  11939. $canonicalQueryString = $queryString;
  11940. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  11941. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  11942. $canonicalRequest = implode("\n", [
  11943. $method,
  11944. $canonicalUri,
  11945. $canonicalQueryString,
  11946. $canonicalHeaders,
  11947. $signedHeaders,
  11948. $payloadHash
  11949. ]);
  11950. // 2. 拼接待签名字符串
  11951. $algorithm = 'HMAC-SHA256';
  11952. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  11953. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  11954. $stringToSign = implode("\n", [
  11955. $algorithm,
  11956. $xDate,
  11957. $credentialScope,
  11958. $hashedCanonicalRequest
  11959. ]);
  11960. // 3. 计算签名
  11961. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  11962. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  11963. // 4. 添加签名到请求头
  11964. $authorizationHeader = sprintf(
  11965. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  11966. $algorithm,
  11967. $access_key,
  11968. $credentialScope,
  11969. $signedHeaders,
  11970. $signature
  11971. );
  11972. return [
  11973. 'Accept' => $accept,
  11974. 'Content-Type' => $contentType,
  11975. 'Host' => $host,
  11976. 'X-Date' => $xDate,
  11977. 'X-Content-Sha256'=> $payloadHash,
  11978. 'Authorization' => $authorizationHeader
  11979. ];
  11980. }
  11981. public function generateScriptWords($cid, $model = 'r1') {
  11982. ini_set('max_execution_time', 0);
  11983. if (!$cid) Utils::throwError('20003: 请选择章节!');
  11984. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  11985. // 模型兼容性处理和思考模式设置
  11986. $thinkingMode = 'disabled';
  11987. $reasoningEffort = 'high';
  11988. if ($model == 'r1') {
  11989. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  11990. $thinkingMode = 'enabled';
  11991. } else {
  11992. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  11993. $thinkingMode = 'disabled';
  11994. }
  11995. $messages = [
  11996. [
  11997. 'role' => 'system',
  11998. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  11999. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  12000. 2.非对话部分请全部用旁白角色代替
  12001. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  12002. ],
  12003. [
  12004. 'role' => 'user',
  12005. 'content' => $content
  12006. ]
  12007. ];
  12008. $post_data = [
  12009. 'model' => $model,
  12010. 'messages' => $messages,
  12011. // 'max_tokens' => 8192,
  12012. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  12013. 'frequency_penalty' => 0,
  12014. 'presence_penalty' => 0,
  12015. 'thinking' => ['type' => $thinkingMode],
  12016. 'response_format' => [
  12017. 'type' => 'text'
  12018. ],
  12019. 'stream' => false
  12020. ];
  12021. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  12022. // 根据模型类型选择调用方法
  12023. $fullContent = '';
  12024. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  12025. // DeepSeek 官方模型使用 DeepSeek API
  12026. $chatResult = $this->chatOnly($post_data);
  12027. } else if (in_array($model, $this->gpt_text_models)) {
  12028. // GPT-5.4 模型使用 TokenRouter API
  12029. $chatResult = $this->gpt54ChatOnly($post_data);
  12030. } else {
  12031. // 其他模型使用火山引擎API
  12032. $chatResult = $this->volcEngineChatCompletion($post_data);
  12033. }
  12034. if (is_array($chatResult)) {
  12035. $fullContent = $chatResult['fullContent'];
  12036. }
  12037. return $fullContent;
  12038. }
  12039. /**
  12040. * 智能化解析集数信息
  12041. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  12042. *
  12043. * @param string $prompt 用户输入的提示词
  12044. * @return int|null 解析出的集数,如果没有找到则返回null
  12045. */
  12046. private function extractEpisodeNumber($prompt)
  12047. {
  12048. if (empty($prompt)) {
  12049. return null;
  12050. }
  12051. // 定义各种可能的表达模式
  12052. $patterns = [
  12053. // 基本模式:改成N集、调整成N集、修改成N集
  12054. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  12055. // 扩展模式:分成N集、拆分成N集、分割成N集
  12056. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  12057. // 数量模式:N集、共N集、总共N集
  12058. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  12059. // 制作模式:制作N集、生成N集、创建N集
  12060. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  12061. // 计划模式:计划N集、预计N集、打算N集
  12062. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  12063. // 需要模式:需要N集、要N集
  12064. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  12065. // 中文数字模式:改成三集、调整成五集等
  12066. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  12067. // 英文数字模式
  12068. '/(?: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',
  12069. ];
  12070. // 中文数字转阿拉伯数字的映射
  12071. $chineseNumbers = [
  12072. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  12073. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  12074. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  12075. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  12076. ];
  12077. // 逐个尝试匹配模式
  12078. foreach ($patterns as $pattern) {
  12079. if (preg_match($pattern, $prompt, $matches)) {
  12080. $number = trim($matches[1]);
  12081. // 如果是中文数字,转换为阿拉伯数字
  12082. if (isset($chineseNumbers[$number])) {
  12083. return $chineseNumbers[$number];
  12084. }
  12085. // 如果是阿拉伯数字,直接返回
  12086. if (is_numeric($number)) {
  12087. $episodeNum = intval($number);
  12088. // 合理性检查:集数应该在1-100之间
  12089. if ($episodeNum >= 1 && $episodeNum <= 100) {
  12090. return $episodeNum;
  12091. }
  12092. }
  12093. }
  12094. }
  12095. return null;
  12096. }
  12097. /**
  12098. * 调用火山引擎对话(Chat) API
  12099. *
  12100. * @param array $params 包含以下参数:
  12101. * - model: 模型ID(必填)
  12102. * - messages: 消息列表(必填)
  12103. * - stream: 是否流式输出(可选,默认false)
  12104. * - max_tokens: 最大输出token数(可选)
  12105. * - temperature: 采样温度(可选,默认1)
  12106. * - top_p: 核采样概率(可选,默认0.7)
  12107. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  12108. * - presence_penalty: 存在惩罚系数(可选,默认0)
  12109. * - stop: 停止词(可选)
  12110. * - tools: 工具列表(可选)
  12111. * @return array|Generator 非流式返回数组,流式返回生成器
  12112. */
  12113. public function volcEngineChatCompletion(array $params)
  12114. {
  12115. $apiKey = env('VOLC_AI_API_KEY');
  12116. if (empty($apiKey)) {
  12117. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  12118. }
  12119. // 构建请求参数
  12120. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  12121. $requestData = [
  12122. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  12123. 'messages' => $params['messages'] ?? [],
  12124. ];
  12125. if (!in_array($originalModel, $this->valid_text_models)) {
  12126. Utils::throwError('20003:该模型不支持!');
  12127. }
  12128. // 添加可选参数
  12129. if (isset($params['stream'])) {
  12130. $requestData['stream'] = $params['stream'];
  12131. }
  12132. if (isset($params['stream_options'])) {
  12133. $requestData['stream_options'] = $params['stream_options'];
  12134. }
  12135. if (isset($params['max_tokens'])) {
  12136. $requestData['max_tokens'] = $params['max_tokens'];
  12137. }else if (isset($params['max_completion_tokens'])) {
  12138. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  12139. }else {
  12140. $requestData['max_completion_tokens'] = 100000;
  12141. }
  12142. if (isset($params['temperature'])) {
  12143. $requestData['temperature'] = $params['temperature'];
  12144. }
  12145. if (isset($params['top_p'])) {
  12146. $requestData['top_p'] = $params['top_p'];
  12147. }
  12148. if (isset($params['frequency_penalty'])) {
  12149. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  12150. }
  12151. if (isset($params['presence_penalty'])) {
  12152. $requestData['presence_penalty'] = $params['presence_penalty'];
  12153. }
  12154. if (isset($params['stop'])) {
  12155. $requestData['stop'] = $params['stop'];
  12156. }
  12157. if (isset($params['tools'])) {
  12158. $requestData['tools'] = $params['tools'];
  12159. }
  12160. if (isset($params['tool_choice'])) {
  12161. $requestData['tool_choice'] = $params['tool_choice'];
  12162. }
  12163. if (isset($params['response_format'])) {
  12164. $requestData['response_format'] = $params['response_format'];
  12165. }
  12166. if (isset($params['thinking'])) {
  12167. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  12168. if (is_array($params['thinking'])) {
  12169. $requestData['thinking'] = $params['thinking'];
  12170. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  12171. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  12172. }
  12173. } else {
  12174. $requestData['thinking'] = ['type' => $params['thinking']];
  12175. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  12176. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  12177. }
  12178. }
  12179. } else {
  12180. $requestData['thinking'] = ['type' => 'disabled'];
  12181. }
  12182. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  12183. $client = new Client(['verify' => false, 'timeout' => 1800]);
  12184. try {
  12185. // 判断是否为流式输出
  12186. $isStream = isset($params['stream']) && $params['stream'] === true;
  12187. if ($isStream) {
  12188. // 流式输出
  12189. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  12190. } else {
  12191. // 非流式输出
  12192. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  12193. 'headers' => [
  12194. 'Authorization' => 'Bearer ' . $apiKey,
  12195. 'Content-Type' => 'application/json',
  12196. ],
  12197. 'json' => $requestData
  12198. ]);
  12199. $responseData = json_decode($response->getBody(), true);
  12200. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  12201. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  12202. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  12203. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  12204. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  12205. }
  12206. return [
  12207. 'fullContent' => $fullContent,
  12208. 'fullReasoningContent' => $fullReasoningContent,
  12209. 'usage' => $usage
  12210. ];
  12211. }
  12212. } catch (\Exception $e) {
  12213. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  12214. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  12215. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  12216. }
  12217. }
  12218. /**
  12219. * 火山引擎对话API流式输出
  12220. *
  12221. * @param Client $client HTTP客户端
  12222. * @param string $apiKey API密钥
  12223. * @param array $requestData 请求数据
  12224. * @return Generator
  12225. */
  12226. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  12227. {
  12228. try {
  12229. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  12230. 'headers' => [
  12231. 'Authorization' => 'Bearer ' . $apiKey,
  12232. 'Content-Type' => 'application/json',
  12233. ],
  12234. 'json' => $requestData,
  12235. 'stream' => true
  12236. ]);
  12237. $body = $response->getBody();
  12238. $buffer = '';
  12239. $fullContent = '';
  12240. $fullReasoningContent = '';
  12241. $usage = [];
  12242. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  12243. // 逐行读取流式响应
  12244. while (!$body->eof()) {
  12245. $chunk = $body->read(1024);
  12246. $buffer .= $chunk;
  12247. // 按行分割
  12248. $lines = explode("\n", $buffer);
  12249. $buffer = array_pop($lines);
  12250. foreach ($lines as $line) {
  12251. $line = trim($line);
  12252. if (empty($line)) {
  12253. continue;
  12254. }
  12255. // 检查是否是SSE数据行
  12256. if (strpos($line, 'data: ') !== 0) {
  12257. continue;
  12258. }
  12259. $data = substr($line, 6);
  12260. if ($data === '[DONE]') {
  12261. dLog('deepseek')->info('收到结束标记');
  12262. break 2;
  12263. }
  12264. try {
  12265. $json = json_decode($data, true);
  12266. if (json_last_error() !== JSON_ERROR_NONE) {
  12267. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  12268. continue;
  12269. }
  12270. if (isset($json['choices'][0]['delta'])) {
  12271. $delta = $json['choices'][0]['delta'];
  12272. // 处理思维链内容
  12273. if (isset($delta['reasoning_content'])) {
  12274. $fullReasoningContent .= $delta['reasoning_content'];
  12275. yield [
  12276. 'type' => 'reasoning',
  12277. 'content' => $delta['reasoning_content'],
  12278. 'full_reasoning' => $fullReasoningContent
  12279. ];
  12280. }
  12281. // 处理回答内容
  12282. if (isset($delta['content'])) {
  12283. $fullContent .= $delta['content'];
  12284. yield [
  12285. 'type' => 'content',
  12286. 'content' => $delta['content'],
  12287. ];
  12288. }
  12289. }
  12290. // 获取使用统计信息
  12291. if (isset($json['usage'])) {
  12292. $usage = $json['usage'];
  12293. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  12294. }
  12295. } catch (\Exception $e) {
  12296. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  12297. continue;
  12298. }
  12299. }
  12300. }
  12301. dLog('deepseek')->info('流式读取完成', [
  12302. 'content_length' => strlen($fullContent),
  12303. 'reasoning_length' => strlen($fullReasoningContent)
  12304. ]);
  12305. yield [
  12306. 'type' => 'done',
  12307. 'full_content' => $fullContent,
  12308. 'full_reasoning' => $fullReasoningContent,
  12309. 'usage' => $usage
  12310. ];
  12311. } catch (\Exception $e) {
  12312. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  12313. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  12314. throw $e;
  12315. }
  12316. }
  12317. /**
  12318. * 检查并创建图片生成任务
  12319. *
  12320. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  12321. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  12322. * @param string $nameKey 资源名称字段('role' 或 'scene')
  12323. * @param string $art_style 美术风格
  12324. * @return array 更新后的资源列表
  12325. */
  12326. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  12327. {
  12328. // 确保参数为数组
  12329. $merged_items = is_array($merged_items) ? $merged_items : [];
  12330. $global_items = is_array($global_items) ? $global_items : [];
  12331. // 构建全局资源映射表,用于快速查找
  12332. $global_map = [];
  12333. foreach ($global_items as $item) {
  12334. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  12335. if ($itemKey === '') {
  12336. continue;
  12337. }
  12338. $global_map[$itemKey] = $item;
  12339. }
  12340. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  12341. foreach ($merged_items as &$item) {
  12342. $item_name = getProp($item, $nameKey);
  12343. $item_description = getProp($item, 'description');
  12344. // $item_url = getProp($item, 'url');
  12345. // // 如果已有图片URL,跳过
  12346. // if (!empty($item_url)) {
  12347. // continue;
  12348. // }
  12349. // 如果是旁白角色,跳过
  12350. if ($nameKey === 'role' && $item_name === '旁白') {
  12351. continue;
  12352. }
  12353. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  12354. if ($itemKey === '') {
  12355. continue;
  12356. }
  12357. $need_create_task = false;
  12358. // 条件1:在全局资源中找不到匹配的名称
  12359. if (!isset($global_map[$itemKey])) {
  12360. $need_create_task = true;
  12361. } else {
  12362. // 条件2:名称匹配但描述或 pic_prompt 不一致
  12363. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  12364. $current_description = trim((string)$item_description);
  12365. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  12366. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  12367. // 如果 description 或 pic_prompt 有变化,需要重新生成
  12368. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  12369. $need_create_task = true;
  12370. }
  12371. }
  12372. // 如果需要创建任务,调用图片生成服务
  12373. if ($need_create_task) {
  12374. try {
  12375. // 优先使用 pic_prompt,如果没有则使用 description
  12376. $pic_prompt = getProp($item, 'pic_prompt');
  12377. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  12378. // 添加美术风格前缀
  12379. if ($art_style) {
  12380. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  12381. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  12382. $description = "{$prefix}:{$description}";
  12383. }
  12384. $params = [
  12385. 'prompt' => $description,
  12386. 'ref_img_urls' => []
  12387. ];
  12388. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  12389. $task_id = $task->id;
  12390. if ($task_id) {
  12391. $item['task_id'] = $task_id;
  12392. $item['task_status'] = 'processing';
  12393. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  12394. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  12395. }
  12396. } catch (\Exception $e) {
  12397. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  12398. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  12399. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  12400. // 不抛出异常,继续处理其他资源
  12401. }
  12402. }
  12403. }
  12404. return $merged_items;
  12405. }
  12406. /**
  12407. * 同步新出现的主体和场景到全局
  12408. *
  12409. * @param int $anime_id 动漫ID
  12410. * @param array $merged_roles 合并后的角色列表
  12411. * @param array $merged_scenes 合并后的场景列表
  12412. * @param array $global_roles 全局角色列表
  12413. * @param array $global_scenes 全局场景列表
  12414. * @return void
  12415. */
  12416. private function syncNewResourcesToGlobal(
  12417. int $anime_id,
  12418. array $merged_roles,
  12419. array $merged_scenes,
  12420. array $global_roles,
  12421. array $global_scenes
  12422. ): void {
  12423. // 构建全局角色映射表
  12424. $global_role_map = [];
  12425. foreach ($global_roles as $role) {
  12426. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  12427. if ($roleKey !== '') {
  12428. $global_role_map[$roleKey] = $role;
  12429. }
  12430. }
  12431. // 构建全局场景映射表
  12432. $global_scene_map = [];
  12433. foreach ($global_scenes as $scene) {
  12434. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  12435. if ($sceneKey !== '') {
  12436. $global_scene_map[$sceneKey] = $scene;
  12437. }
  12438. }
  12439. $need_update = false;
  12440. $new_global_roles = $global_roles;
  12441. $new_global_scenes = $global_scenes;
  12442. // 检查并添加新角色到全局
  12443. foreach ($merged_roles as $role) {
  12444. $role_name = getProp($role, 'role');
  12445. // 跳过旁白
  12446. if ($role_name === '旁白') {
  12447. continue;
  12448. }
  12449. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  12450. if ($roleKey === '') {
  12451. continue;
  12452. }
  12453. // 如果全局中不存在该角色,添加到全局
  12454. if (!isset($global_role_map[$roleKey])) {
  12455. $new_global_roles[] = [
  12456. 'role' => $role_name,
  12457. 'description' => getProp($role, 'description', ''),
  12458. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  12459. 'voice_name' => getProp($role, 'voice_name', ''),
  12460. 'voice_type' => getProp($role, 'voice_type', ''),
  12461. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  12462. 'url' => getProp($role, 'url', ''),
  12463. 'task_id' => getProp($role, 'task_id', ''),
  12464. 'task_status' => getProp($role, 'task_status', ''),
  12465. ];
  12466. $global_role_map[$roleKey] = true; // 标记已添加
  12467. $need_update = true;
  12468. dLog('deepseek')->info("新角色同步到全局", [
  12469. 'anime_id' => $anime_id,
  12470. 'role' => $role_name,
  12471. 'task_id' => getProp($role, 'task_id', ''),
  12472. ]);
  12473. }
  12474. // else {
  12475. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  12476. // $global_role = $global_role_map[$roleKey];
  12477. // if (is_array($global_role)) {
  12478. // $updated = false;
  12479. // $update_fields = [];
  12480. // // 检查描述是否更新
  12481. // $current_description = trim((string)getProp($role, 'description'));
  12482. // $global_description = trim((string)getProp($global_role, 'description'));
  12483. // if ($current_description !== '' && $current_description !== $global_description) {
  12484. // $updated = true;
  12485. // $update_fields[] = 'description';
  12486. // }
  12487. // // 检查pic_prompt是否更新
  12488. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  12489. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  12490. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  12491. // $updated = true;
  12492. // $update_fields[] = 'pic_prompt';
  12493. // }
  12494. // // 检查图片任务信息是否更新
  12495. // $current_task_id = getProp($role, 'task_id');
  12496. // $global_task_id = getProp($global_role, 'task_id');
  12497. // if ($current_task_id && $current_task_id !== $global_task_id) {
  12498. // $updated = true;
  12499. // $update_fields[] = 'task_id';
  12500. // }
  12501. // // 如果有更新,同步到全局
  12502. // if ($updated) {
  12503. // foreach ($new_global_roles as &$global_role_item) {
  12504. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  12505. // if ($global_role_key === $roleKey) {
  12506. // if (in_array('description', $update_fields)) {
  12507. // $global_role_item['description'] = $current_description;
  12508. // }
  12509. // if (in_array('pic_prompt', $update_fields)) {
  12510. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  12511. // }
  12512. // if (in_array('task_id', $update_fields)) {
  12513. // $global_role_item['task_id'] = $current_task_id;
  12514. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  12515. // $global_role_item['url'] = getProp($role, 'url', '');
  12516. // }
  12517. // break;
  12518. // }
  12519. // }
  12520. // $need_update = true;
  12521. // dLog('deepseek')->info("角色信息更新到全局", [
  12522. // 'anime_id' => $anime_id,
  12523. // 'role' => $role_name,
  12524. // 'update_fields' => implode(',', $update_fields),
  12525. // ]);
  12526. // }
  12527. // }
  12528. // }
  12529. }
  12530. // 检查并添加新场景到全局
  12531. foreach ($merged_scenes as $scene) {
  12532. $scene_name = getProp($scene, 'scene');
  12533. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  12534. if ($sceneKey === '') {
  12535. continue;
  12536. }
  12537. // 如果全局中不存在该场景,添加到全局
  12538. if (!isset($global_scene_map[$sceneKey])) {
  12539. $new_global_scenes[] = [
  12540. 'scene' => $scene_name,
  12541. 'description' => getProp($scene, 'description', ''),
  12542. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  12543. 'url' => getProp($scene, 'url', ''),
  12544. 'task_id' => getProp($scene, 'task_id', ''),
  12545. 'task_status' => getProp($scene, 'task_status', ''),
  12546. ];
  12547. $global_scene_map[$sceneKey] = true; // 标记已添加
  12548. $need_update = true;
  12549. dLog('deepseek')->info("新场景同步到全局", [
  12550. 'anime_id' => $anime_id,
  12551. 'scene' => $scene_name,
  12552. 'task_id' => getProp($scene, 'task_id', ''),
  12553. ]);
  12554. }
  12555. // else {
  12556. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  12557. // $global_scene = $global_scene_map[$sceneKey];
  12558. // if (is_array($global_scene)) {
  12559. // $updated = false;
  12560. // $update_fields = [];
  12561. // // 检查描述是否更新
  12562. // $current_description = trim((string)getProp($scene, 'description'));
  12563. // $global_description = trim((string)getProp($global_scene, 'description'));
  12564. // if ($current_description !== '' && $current_description !== $global_description) {
  12565. // $updated = true;
  12566. // $update_fields[] = 'description';
  12567. // }
  12568. // // 检查pic_prompt是否更新
  12569. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  12570. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  12571. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  12572. // $updated = true;
  12573. // $update_fields[] = 'pic_prompt';
  12574. // }
  12575. // // 检查图片任务信息是否更新
  12576. // $current_task_id = getProp($scene, 'task_id');
  12577. // $global_task_id = getProp($global_scene, 'task_id');
  12578. // if ($current_task_id && $current_task_id !== $global_task_id) {
  12579. // $updated = true;
  12580. // $update_fields[] = 'task_id';
  12581. // }
  12582. // // 如果有更新,同步到全局
  12583. // if ($updated) {
  12584. // foreach ($new_global_scenes as &$global_scene_item) {
  12585. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  12586. // if ($global_scene_key === $sceneKey) {
  12587. // if (in_array('description', $update_fields)) {
  12588. // $global_scene_item['description'] = $current_description;
  12589. // }
  12590. // if (in_array('pic_prompt', $update_fields)) {
  12591. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  12592. // }
  12593. // if (in_array('task_id', $update_fields)) {
  12594. // $global_scene_item['task_id'] = $current_task_id;
  12595. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  12596. // $global_scene_item['url'] = getProp($scene, 'url', '');
  12597. // }
  12598. // break;
  12599. // }
  12600. // }
  12601. // $need_update = true;
  12602. // dLog('deepseek')->info("场景信息更新到全局", [
  12603. // 'anime_id' => $anime_id,
  12604. // 'scene' => $scene_name,
  12605. // 'update_fields' => implode(',', $update_fields),
  12606. // ]);
  12607. // }
  12608. // }
  12609. // }
  12610. }
  12611. // 如果有新增或更新,更新数据库
  12612. if ($need_update) {
  12613. $update_data = [
  12614. 'roles' => json_encode($new_global_roles, 256),
  12615. 'scenes' => json_encode($new_global_scenes, 256),
  12616. 'updated_at' => date('Y-m-d H:i:s'),
  12617. ];
  12618. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  12619. if ($result !== false) {
  12620. dLog('deepseek')->info("全局角色和场景更新成功", [
  12621. 'anime_id' => $anime_id,
  12622. 'roles_count' => count($new_global_roles),
  12623. 'scenes_count' => count($new_global_scenes),
  12624. ]);
  12625. } else {
  12626. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  12627. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  12628. }
  12629. }
  12630. }
  12631. }