DeepSeekService.php 311 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375
  1. <?php
  2. namespace App\Services\DeepSeek;
  3. use App\Consts\ErrorConst;
  4. use App\Facade\Site;
  5. use App\Libs\Utils;
  6. use GuzzleHttp\Client;
  7. use DateTime;
  8. use DateTimeZone;
  9. use App\Services\AIGeneration\AIImageGenerationService;
  10. use Illuminate\Support\Facades\DB;
  11. use Illuminate\Support\Facades\Log;
  12. use Illuminate\Support\Facades\Redis;
  13. use OSS\Core\OssException;
  14. use OSS\OssClient;
  15. use Smalot\PdfParser\Parser as PdfParser;
  16. use TCPDF;
  17. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  18. use Predis\Command\Traits\Get\Get;
  19. class DeepSeekService
  20. {
  21. private $url;
  22. private $api_key;
  23. private $sys_message;
  24. private $headers;
  25. private $valid_text_models;
  26. protected $aiImageGenerationService;
  27. public function __construct(AIImageGenerationService $aiImageGenerationService) {
  28. $this->aiImageGenerationService = $aiImageGenerationService;
  29. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  30. $this->api_key = env('DEEPSEEK_API_KEY');
  31. $this->headers = [
  32. 'Authorization' => 'Bearer '.$this->api_key,
  33. 'Content-Type' => 'application/json; charset=UTF-8'
  34. ];
  35. // 火山引擎模型列表
  36. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  37. $this->sys_message = [
  38. 'role' => 'system',
  39. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  40. 强制要求:\n
  41. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  42. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  43. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  44. 普通要求:\n
  45. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  46. 2.<分集剧本>的要求如下:
  47.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  48.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  49.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  50.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  51. \n\n
  52. 示例如下:\n
  53. ###剧本名:西昆仑
  54. ###故事梗概
  55. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  56. ###剧本亮点
  57. 亮点1:绝境奇药,生死一线
  58. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  59. 亮点2:结拜兄妹,化解尴尬
  60. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  61. 亮点3:纤发夺命,情愫暗涌
  62. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  63. ###人物关系
  64. 阿雪与梁萧之间存在兄妹之情。
  65. ###核心矛盾
  66. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  67. ###主体列表
  68. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  69. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  70. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  71. 阴阳球:天地异宝,能化生精气,救人于危难。
  72. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  73. ###美术风格
  74. 基础画风风格词:厚涂古风
  75. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  76. ###场景列表
  77. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  78. ###分集剧本
  79. ##分集01
  80. 第1集: 第一集的标题
  81. 场景描述:地点、时间、场景
  82. 运镜:固定近距离
  83. 出场角色:男主、女主
  84. 台词内容:
  85. 女主: 女主对话
  86. 男主:男主对话
  87. 女主: 女主对话
  88. 男主: 男主对话
  89. ##分集02
  90. 第2集: 第二集的标题
  91. 场景描述:地点、时间、场景
  92. 运镜:固定近距离
  93. 出场角色:男主、女主
  94. 台词内容:
  95. 女主: 女主对话
  96. 男主:男主对话
  97. 女主: 女主对话
  98. 男主: 男主对话"
  99. ];
  100. }
  101. /**
  102. * 通用文生文方法 - 支持多模型流式输出和图片输入
  103. *
  104. * @param array $data 请求参数
  105. * @return \Generator 返回生成器,用于流式输出
  106. */
  107. public function generateText($data) {
  108. // 获取请求参数
  109. $model = getProp($data, 'model', 'deepseek-v3-2-251201'); // 默认使用deepseek-v3
  110. $messages = getProp($data, 'messages', []);
  111. $systemPrompt = getProp($data, 'system_prompt', '');
  112. $prompt = getProp($data, 'prompt', '');
  113. $images = getProp($data, 'images', []); // 支持多张图片
  114. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  115. // 如果没有提供messages,则根据system_prompt、content和images构建
  116. if (empty($messages)) {
  117. $messages = [];
  118. // 添加系统提示词
  119. if (!empty($systemPrompt)) {
  120. $messages[] = [
  121. 'role' => 'system',
  122. 'content' => $systemPrompt
  123. ];
  124. }
  125. // 构建用户消息内容(支持文本+图片)
  126. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  127. $userMessage = [
  128. 'role' => 'user',
  129. 'content' => []
  130. ];
  131. // 添加文本内容
  132. if (!empty($prompt)) {
  133. $userMessage['content'][] = [
  134. 'type' => 'text',
  135. 'text' => $prompt
  136. ];
  137. }
  138. // 处理上传的图片文件
  139. if (!empty($images)) {
  140. if (!is_array($images)) {
  141. $images = [$images];
  142. }
  143. foreach ($images as $image) {
  144. $imageBase64 = $this->processImageToBase64($image);
  145. if ($imageBase64) {
  146. $userMessage['content'][] = [
  147. 'type' => 'image_url',
  148. 'image_url' => [
  149. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  150. ]
  151. ];
  152. }
  153. }
  154. }
  155. // 处理图片URL
  156. if (!empty($imageUrls)) {
  157. if (!is_array($imageUrls)) {
  158. $imageUrls = [$imageUrls];
  159. }
  160. foreach ($imageUrls as $url) {
  161. if (!empty($url)) {
  162. $userMessage['content'][] = [
  163. 'type' => 'image_url',
  164. 'image_url' => [
  165. 'url' => $url
  166. ]
  167. ];
  168. }
  169. }
  170. }
  171. // 如果只有文本内容,简化为字符串格式
  172. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  173. $userMessage['content'] = $userMessage['content'][0]['text'];
  174. }
  175. $messages[] = $userMessage;
  176. }
  177. }
  178. // 验证messages不为空
  179. if (empty($messages)) {
  180. Utils::throwError('20003:请提供有效的对话内容');
  181. }
  182. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  183. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  184. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  185. if ($model === 'deepseek-chat') {
  186. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  187. $model = 'deepseek-v4-flash';
  188. $thinkingMode = 'disabled';
  189. } elseif ($model === 'deepseek-reasoner') {
  190. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  191. $model = 'deepseek-v4-flash';
  192. $thinkingMode = 'enabled';
  193. }
  194. // 构建请求参数
  195. $post_data = [
  196. 'model' => $model,
  197. 'messages' => $messages,
  198. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  199. 'temperature' => getProp($data, 'temperature', 1),
  200. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  201. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  202. 'thinking' => ['type' => $thinkingMode],
  203. 'stream' => true // 启用流式输出
  204. ];
  205. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  206. // 添加可选参数
  207. if (isset($data['top_p'])) {
  208. $post_data['top_p'] = $data['top_p'];
  209. }
  210. if (isset($data['response_format'])) {
  211. $post_data['response_format'] = $data['response_format'];
  212. }
  213. dLog('deepseek')->info('通用文生文请求参数', ['model' => $model, 'thinking' => $thinkingMode, 'messages_count' => count($messages)]);
  214. // 根据模型类型选择调用方法
  215. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  216. // DeepSeek 官方模型使用 DeepSeek API
  217. return $this->deepSeekStreamResponse($post_data);
  218. } else if (in_array($model, $this->valid_text_models)) {
  219. // 火山引擎支持的模型使用火山引擎 API
  220. return $this->volcEngineChatCompletion($post_data);
  221. } else {
  222. Utils::throwError('20003:不支持的模型: ' . $model);
  223. }
  224. }
  225. /**
  226. * 处理图片转换为base64
  227. *
  228. * @param mixed $image 图片文件对象或文件路径
  229. * @return string|null base64编码的图片数据
  230. */
  231. private function processImageToBase64($image) {
  232. try {
  233. // 获取文件路径
  234. if (is_string($image)) {
  235. $filePath = $image;
  236. } else {
  237. // Laravel UploadedFile 对象
  238. $filePath = $image->getRealPath();
  239. }
  240. if (!file_exists($filePath)) {
  241. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  242. return null;
  243. }
  244. // 验证是否为图片文件
  245. $imageInfo = @getimagesize($filePath);
  246. if ($imageInfo === false) {
  247. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  248. return null;
  249. }
  250. // 读取图片并转换为base64
  251. $imageData = file_get_contents($filePath);
  252. $base64Image = base64_encode($imageData);
  253. dLog('deepseek')->info('图片转换成功', [
  254. 'size' => strlen($imageData),
  255. 'type' => $imageInfo['mime']
  256. ]);
  257. return $base64Image;
  258. } catch (\Exception $e) {
  259. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  260. return null;
  261. }
  262. }
  263. private function getArtStylePromptMappings(): array
  264. {
  265. return [
  266. '唯美真人风格' => [
  267. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  268. 'prompt' => "极致真实人像摄影,真人实拍质感,原生相机直出,细腻真实的皮肤肌理,保留皮肤毛孔、细微绒毛、自然瑕疵,不假面、不塑料,自然原生五官,流畅骨相,生动自然的微表情,松弛不僵硬
  269. 真实自然光/柔和人造柔光,光影过渡自然柔和,明暗层次高级,不硬光死黑
  270. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  271. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  272. ],
  273. '真人古风风格' => [
  274. 'aliases' => ['真人古风风格', '真人古风'],
  275. 'prompt' => "极致真实古装人像摄影,真人实拍质感,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  276. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  277. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  278. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化,中式古典场景(古庭院、竹林、山间、古廊桥、烟雨江南、月夜楼台)
  279. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  280. ],
  281. '日系动漫风格' => [
  282. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  283. 'prompt' => "日系动漫风格,线条干净流畅,色彩明亮柔和,人物精致,光影细腻,画面统一稳定"
  284. ],
  285. '国漫风格' => [
  286. 'aliases' => ['国漫风格', '国漫'],
  287. 'prompt' => "国漫风格,线条硬朗,人物成熟大气,色彩浓郁,光影对比强烈,整体画风统一,适合漫剧叙事"
  288. ],
  289. 'Q版卡通风格' => [
  290. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  291. 'prompt' => "Q版卡通风格,头大身小造型可爱,线条简洁,色彩明快,无复杂阴影,整体萌系干净统一"
  292. ],
  293. '简约扁平风格' => [
  294. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  295. 'prompt' => "简约扁平风格,大块纯色无渐变,线条简洁现代,画面干净清爽,不出现复杂纹理与光影"
  296. ],
  297. '古风仙侠风格' => [
  298. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  299. 'prompt' => "古风仙侠风格,汉服飘逸,云雾缭绕仙气空灵,色调清雅,光影柔和,国风氛围统一"
  300. ],
  301. '武侠风格' => [
  302. 'aliases' => ['武侠风格', '武侠'],
  303. 'prompt' => "武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态自然,色调沉稳大气"
  304. ],
  305. '新中式水墨风格' => [
  306. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  307. 'prompt' => "新中式水墨风格,淡墨渲染笔触自然,留白有意境,色调清雅,国风质感统一不杂乱"
  308. ],
  309. '写实插画风格' => [
  310. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  311. 'prompt' => "写实插画风格,真实人体比例,光影自然细腻,画面质感真实,不卡通不崩坏"
  312. ],
  313. '3D卡通风格' => [
  314. 'aliases' => ['3D卡通风格', '3D卡通'],
  315. 'prompt' => "3D卡通风格,立体建模质感柔和,造型圆润光滑,光影干净,整体风格统一不穿模"
  316. ],
  317. '条漫风格' => [
  318. 'aliases' => ['条漫风格', '条漫'],
  319. 'prompt' => "条漫风格,纵向分镜简洁,色彩清淡,适合上下滑动阅读,画面轻量化且整体统一"
  320. ],
  321. '赛博朋克风格' => [
  322. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  323. 'prompt' => "赛博朋克风格,霓虹灯光未来都市,暗色调科技感强,高对比光影,风格统一强烈"
  324. ],
  325. '暗黑悬疑风格' => [
  326. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  327. 'prompt' => "暗黑悬疑风格,低饱和冷色调,强阴影光线昏暗,氛围神秘压抑,整体色调统一"
  328. ],
  329. '治愈清新风格' => [
  330. 'aliases' => ['治愈清新风格', '治愈清新'],
  331. 'prompt' => "治愈清新风格,马卡龙柔和色系,柔光暖调,画面干净舒适,氛围温暖不杂乱"
  332. ],
  333. ];
  334. }
  335. public function getArtStylePromptByInput($inputArtStyle): string
  336. {
  337. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  338. if ($normalizedInput === '') {
  339. return '';
  340. }
  341. foreach ($this->getArtStylePromptMappings() as $mapping) {
  342. foreach ($mapping['aliases'] as $alias) {
  343. $normalizedAlias = $this->normalizeArtStyleInput($alias);
  344. if ($normalizedAlias === '') {
  345. continue;
  346. }
  347. if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  348. return $mapping['prompt'];
  349. }
  350. }
  351. }
  352. return '';
  353. }
  354. private function normalizeArtStyleInput($value): string
  355. {
  356. $value = trim((string)$value);
  357. if ($value === '') {
  358. return '';
  359. }
  360. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  361. return mb_strtolower($value, 'UTF-8');
  362. }
  363. private function replaceArtStyleSection(string $content, string $artStyle): string
  364. {
  365. if ($content === '' || $artStyle === '') {
  366. return $content;
  367. }
  368. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  369. if (!preg_match($pattern, $content)) {
  370. return $content;
  371. }
  372. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  373. }
  374. /**
  375. * DeepSeek流式输出处理方法
  376. *
  377. * @param array $post_data DeepSeek API请求参数
  378. * @return \Generator 返回生成器,用于流式输出
  379. */
  380. private function deepSeekStreamResponse($post_data) {
  381. $client = new Client(['timeout' => 1200, 'verify' => false]);
  382. $response = $client->post($this->url, [
  383. 'json' => $post_data,
  384. 'headers' => $this->headers,
  385. 'stream' => true // 启用流式响应
  386. ]);
  387. $body = $response->getBody();
  388. $fullContent = '';
  389. $fullReasoningContent = '';
  390. $usage = [];
  391. $buffer = '';
  392. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  393. // 逐行读取流式响应
  394. while (!$body->eof()) {
  395. $chunk = $body->read(1024); // 每次读取 1KB
  396. $buffer .= $chunk;
  397. // 按行分割
  398. $lines = explode("\n", $buffer);
  399. // 保留最后一个不完整的行
  400. $buffer = array_pop($lines);
  401. foreach ($lines as $line) {
  402. $line = trim($line);
  403. // 跳过空行
  404. if (empty($line)) {
  405. continue;
  406. }
  407. // 检查是否是 SSE 数据行
  408. if (strpos($line, 'data: ') !== 0) {
  409. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  410. continue;
  411. }
  412. $data = substr($line, 6); // 移除 "data: " 前缀
  413. if ($data === '[DONE]') {
  414. dLog('deepseek')->info('收到结束标记');
  415. break 2; // 跳出两层循环
  416. }
  417. try {
  418. $json = json_decode($data, true);
  419. if (json_last_error() !== JSON_ERROR_NONE) {
  420. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  421. continue;
  422. }
  423. if (isset($json['choices'][0]['delta'])) {
  424. $delta = $json['choices'][0]['delta'];
  425. // 处理思维链内容(仅 deepseek-reasoner 模型)
  426. if (isset($delta['reasoning_content'])) {
  427. $fullReasoningContent .= $delta['reasoning_content'];
  428. yield [
  429. 'type' => 'reasoning',
  430. 'content' => $delta['reasoning_content'],
  431. 'full_reasoning' => $fullReasoningContent
  432. ];
  433. }
  434. // 处理最终回答内容
  435. if (isset($delta['content'])) {
  436. $fullContent .= $delta['content'];
  437. yield [
  438. 'type' => 'content',
  439. 'content' => $delta['content'],
  440. ];
  441. }
  442. }
  443. // 获取使用统计信息
  444. if (isset($json['usage'])) {
  445. $usage = $json['usage'];
  446. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  447. }
  448. } catch (\Exception $e) {
  449. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  450. continue;
  451. }
  452. }
  453. }
  454. dLog('deepseek')->info('流式读取完成', [
  455. 'content_length' => strlen($fullContent),
  456. 'reasoning_length' => strlen($fullReasoningContent)
  457. ]);
  458. yield [
  459. 'type' => 'done',
  460. 'full_content' => $fullContent,
  461. 'full_reasoning' => $fullReasoningContent,
  462. 'usage' => $usage
  463. ];
  464. }
  465. // 与推理模型对话
  466. public function chatWithReasoner($data) {
  467. $content = getProp($data, 'content');
  468. $model = getProp($data, 'model', 'r1');
  469. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  470. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  471. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  472. if ($model == 'r1') {
  473. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  474. $thinkingMode = 'disabled';
  475. } else {
  476. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  477. $thinkingMode = 'disabled';
  478. }
  479. // 获取可选情感(根据音色可支持情感选)
  480. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  481. $emotion_list = [];
  482. foreach ($timbre_emotion as $emotion) {
  483. $tmp = explode(',', $emotion);
  484. $emotion_list = array_merge($emotion_list, $tmp);
  485. }
  486. $emotion_list = array_unique($emotion_list);
  487. $emotion_str = implode('、', $emotion_list);
  488. // // 获取可选情感
  489. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  490. // $emotion_str = implode('、', $emotion_list);
  491. // 是否启用情感
  492. $enable_emotion = getProp($data, 'enable_emotion', 0);
  493. if ($enable_emotion) {
  494. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  495. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  496. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  497. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  498. }else {
  499. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  500. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  501. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  502. }
  503. $messages = [
  504. [
  505. 'role' => 'system',
  506. 'content' => $sys_content
  507. ],
  508. [
  509. 'role' => 'user',
  510. 'content' => $content
  511. ]
  512. ];
  513. $post_data = [
  514. 'model' => $model,
  515. 'messages' => $messages,
  516. // 'max_tokens' => 8192,
  517. 'temperature' => 1,
  518. 'frequency_penalty' => 0,
  519. 'presence_penalty' => 0,
  520. 'thinking' => ['type' => $thinkingMode],
  521. 'response_format' => [
  522. 'type' => 'text'
  523. ],
  524. 'stream' => false
  525. ];
  526. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  527. // 根据模型类型选择调用方法
  528. $fullContent = '';
  529. $usage = [];
  530. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  531. // DeepSeek 官方模型使用 DeepSeek API
  532. $chatResult = $this->chatOnly($post_data);
  533. } else {
  534. // 其他模型使用火山引擎API
  535. $chatResult = $this->volcEngineChatCompletion($post_data);
  536. }
  537. if (is_array($chatResult)) {
  538. $fullContent = $chatResult['fullContent'];
  539. $usage = $chatResult['usage'];
  540. }
  541. // 处理获取到的剧本数据
  542. $script_content = handleScriptWords($fullContent, $enable_emotion);
  543. $result = [
  544. 'origin_content' => $fullContent,
  545. 'roles' => getProp($script_content, 'roles'),
  546. 'words' => getProp($script_content, 'words'),
  547. ];
  548. return $result;
  549. }
  550. public function resetParagraphAudio($data) {
  551. $bid = getProp($data, 'bid');
  552. $cid = getProp($data, 'cid');
  553. $version_id = getProp($data, 'version_id');
  554. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  555. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  556. 'generate_status' => '待制作',
  557. 'updated_at' => date('Y-m-d H:i:s')
  558. ]);
  559. }
  560. public function saveParagraphAudio($data) {
  561. $bid = getProp($data, 'bid');
  562. $cid = getProp($data, 'cid');
  563. $version_id = getProp($data, 'version_id');
  564. $sequence = getProp($data, 'sequence');
  565. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  566. // 获取所有情感
  567. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  568. $emotion_list = array_flip($emotion_list);
  569. // 获取音色支持情感
  570. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  571. $timbre_emotion = explode(',', $timbre_emotion);
  572. $emotion = getProp($data, 'emotion');
  573. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  574. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  575. $list = [
  576. 'bid' => $bid,
  577. 'cid' => $cid,
  578. 'version_id' => $version_id,
  579. 'sequence' => $sequence,
  580. 'role' => getProp($data, 'role'),
  581. 'gender' => getProp($data, 'gender'),
  582. 'text' => trim(getProp($data, 'text')),
  583. 'emotion' => $emotion,
  584. 'emotion_type' => $emotion_type,
  585. 'voice_type' => getProp($data, 'voice_type'),
  586. 'voice_name' => getProp($data, 'voice_name'),
  587. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  588. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  589. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  590. 'pitch' => getProp($data, 'pitch', 0),
  591. // 'paragraph_audio_url' => '',
  592. 'generate_status' => '制作中',
  593. 'error_msg' => '',
  594. 'updated_at' => date('Y-m-d H:i:s')
  595. ];
  596. $continue = false;
  597. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  598. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  599. $list['generate_status'] = '制作成功';
  600. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  601. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  602. $continue = true;
  603. }
  604. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  605. if ($id) {
  606. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  607. }else {
  608. $list['created_at'] = date('Y-m-d H:i:s');
  609. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  610. $boolen = $id ? true : false;
  611. }
  612. // 如果更新成功则加入查询队列
  613. if ($boolen) {
  614. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  615. Redis::sadd($redis_key, $id);
  616. }
  617. if ($boolen && !$continue) {
  618. $boolen = false;
  619. $client = new Client(['timeout' => 300, 'verify' => false]);
  620. // 根据ID通过API通知合成音频
  621. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  622. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  623. $response = $result->getBody()->getContents();
  624. $response_arr = json_decode($response, true);
  625. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  626. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  627. Log::info('通知火山生成段落音频失败: '.$error_msg);
  628. Utils::throwError('20003:通知火山生成段落音频失败');
  629. }
  630. $boolen = true;
  631. }
  632. return $boolen;
  633. }
  634. public function insertAudioEffect($data) {
  635. $audio_id = getProp($data, 'audio_id');
  636. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  637. $bid = getProp($chapter_audio, 'bid');
  638. $version_id = getProp($chapter_audio, 'version_id');
  639. $cid = getProp($chapter_audio, 'cid');
  640. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  641. $audio_effect_json = getProp($data, 'audio_effect_json');
  642. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  643. try {
  644. DB::beginTransaction();
  645. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  646. if (!$count) {
  647. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  648. }else {
  649. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  650. }
  651. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  652. 'audio_effect_status' => '添加中',
  653. 'audio_effect_json' => $audio_effect_json,
  654. 'updated_at' => date('Y-m-d H:i:s')
  655. ]);
  656. if (!$boolen1) {
  657. DB::rollBack();
  658. Utils::throwError('20003:更新生成数据失败');
  659. }
  660. $id = DB::table('mp_audio_tasks')->insertGetId([
  661. 'audio_id' => $audio_id,
  662. 'generate_status' => '执行中',
  663. 'generate_json' => json_encode([], 256),
  664. 'bid' => $bid,
  665. 'book_name' => getProp($chapter_audio, 'book_name'),
  666. 'version_id' => $version_id,
  667. 'version_name' => getProp($chapter_audio, 'version_name'),
  668. 'cid' => $cid,
  669. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  670. 'task_name' => $task_name,
  671. 'created_at' => date('Y-m-d H:i:s'),
  672. 'updated_at' => date('Y-m-d H:i:s')
  673. ]);
  674. if (!$id) {
  675. DB::rollBack();
  676. Utils::throwError('20003:创建任务失败');
  677. }
  678. }catch (\Exception $e) {
  679. DB::rollBack();
  680. Utils::throwError('20003:'.$e->getMessage());
  681. }
  682. DB::commit();
  683. $client = new Client(['timeout' => 300, 'verify' => false]);
  684. // 根据ID通过API通知合成音频
  685. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  686. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  687. $response = $result->getBody()->getContents();
  688. $response_arr = json_decode($response, true);
  689. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  690. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  691. Log::info('通知火山插入音效失败: '.$error_msg);
  692. Utils::throwError('20003:通知火山插入音效失败');
  693. }
  694. return true;
  695. }
  696. public function insertBgm($data) {
  697. $audio_id = getProp($data, 'audio_id');
  698. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  699. $bid = getProp($chapter_audio, 'bid');
  700. $version_id = getProp($chapter_audio, 'version_id');
  701. $cid = getProp($chapter_audio, 'cid');
  702. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  703. $bgm_json = getProp($data, 'bgm_json');
  704. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  705. if (!$bgm_json) {
  706. $bgm_json = getProp($data, 'audio_effect_json');
  707. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  708. }
  709. try {
  710. DB::beginTransaction();
  711. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  712. if (!$count) {
  713. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  714. }else {
  715. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  716. }
  717. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  718. 'bgm_status' => '添加中',
  719. 'bgm_json' => $bgm_json,
  720. 'updated_at' => date('Y-m-d H:i:s')
  721. ]);
  722. if (!$boolen1) {
  723. DB::rollBack();
  724. Utils::throwError('20003:更新生成数据失败');
  725. }
  726. $id = DB::table('mp_audio_tasks')->insertGetId([
  727. 'audio_id' => $audio_id,
  728. 'generate_status' => '执行中',
  729. 'generate_json' => json_encode([], 256),
  730. 'bid' => $bid,
  731. 'book_name' => getProp($chapter_audio, 'book_name'),
  732. 'version_id' => $version_id,
  733. 'version_name' => getProp($chapter_audio, 'version_name'),
  734. 'cid' => $cid,
  735. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  736. 'task_name' => $task_name,
  737. 'created_at' => date('Y-m-d H:i:s'),
  738. 'updated_at' => date('Y-m-d H:i:s')
  739. ]);
  740. if (!$id) {
  741. DB::rollBack();
  742. Utils::throwError('20003:创建任务失败');
  743. }
  744. }catch (\Exception $e) {
  745. DB::rollBack();
  746. Utils::throwError('20003:'.$e->getMessage());
  747. }
  748. DB::commit();
  749. $client = new Client(['timeout' => 300, 'verify' => false]);
  750. // 根据ID通过API通知合成音频
  751. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  752. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  753. $response = $result->getBody()->getContents();
  754. $response_arr = json_decode($response, true);
  755. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  756. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  757. Log::info('通知火山插入bgm失败: '.$error_msg);
  758. Utils::throwError('20003:通知火山插入bgm失败');
  759. }
  760. return true;
  761. }
  762. public function getParagraphAudios($data) {
  763. $bid = getProp($data, 'bid');
  764. $cid = getProp($data, 'cid');
  765. $version_id = getProp($data, 'version_id');
  766. $sequence = getProp($data, 'sequence');
  767. // 获取已生成的音频
  768. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  769. if ($sequence) $query->where('sequence', $sequence);
  770. $paragraph_audios = $query->orderBy('sequence')->get();
  771. $result = [];
  772. foreach($paragraph_audios as $item) {
  773. $result[] = [
  774. 'sequence' => getProp($item, 'sequence'),
  775. 'role' => getProp($item, 'role'),
  776. 'gender' => getProp($item, 'gender'),
  777. 'text' => trim(getProp($item, 'text')),
  778. 'emotion' => getProp($item, 'emotion'),
  779. 'emotion_type' => getProp($item, 'emotion_type'),
  780. 'voice_type' => getProp($item, 'voice_type'),
  781. 'voice_name' => getProp($item, 'voice_name'),
  782. 'speed_ratio' => getProp($item, 'speed_ratio'),
  783. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  784. 'emotion_scale' => getProp($item, 'emotion_scale'),
  785. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  786. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  787. ];
  788. }
  789. return $result;
  790. }
  791. // 新增合成任务
  792. public function addGenerateTask($data) {
  793. $bid = getProp($data, 'bid');
  794. $cid = getProp($data, 'cid');
  795. $version_id = getProp($data, 'version_id');
  796. $generate_json = getProp($data, 'generate_json');
  797. // 获取已生成的音频
  798. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  799. $paragraph_list = [];
  800. foreach($paragraph_audios as $item) {
  801. $paragraph_list[getProp($item, 'sequence')] = [
  802. 'role' => getProp($item, 'role'),
  803. 'gender' => getProp($item, 'gender'),
  804. 'text' => trim(getProp($item, 'text')),
  805. 'emotion' => getProp($item, 'emotion'),
  806. 'emotion_type' => getProp($item, 'emotion_type'),
  807. 'voice_type' => getProp($item, 'voice_type'),
  808. 'voice_name' => getProp($item, 'voice_name'),
  809. 'speed_ratio' => getProp($item, 'speed_ratio'),
  810. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  811. 'emotion_scale' => getProp($item, 'emotion_scale'),
  812. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  813. ];
  814. }
  815. // 更新角色-音色信息
  816. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  817. $existed_role_info = json_decode($existed_role_info, true);
  818. if (!$existed_role_info) $existed_role_info = [];
  819. // 获取情感信息
  820. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  821. $emotion_list = array_flip($emotion_list);
  822. // 获取音色对应情感组
  823. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  824. $timbre_emotion_list = [];
  825. foreach($timbre_emotions as $item) {
  826. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  827. }
  828. // 构造生成音频的json
  829. $words = json_decode($generate_json, true);
  830. // 最终合成前的参数组
  831. $mp_chapter_paragraph_audios = [];
  832. $sequence = 1;
  833. $complete_paragraph_sequences = [];
  834. foreach($words as &$word) {
  835. 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:参数格式有误');
  836. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  837. $role = getProp($word, 'role');
  838. $word['gender'] = (int)$word['gender'];
  839. // 判断音色对应情感是否支持,不支持则调整为中性
  840. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  841. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  842. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  843. if (isset($emotion_list[getProp($word, 'emotion')])) {
  844. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  845. }else {
  846. $word['emotion'] = '中性';
  847. $word['emotion_type'] = 'neutral';
  848. }
  849. $existed_role_info[$role] = [
  850. 'timbre_type' => $word['voice_type'],
  851. 'timbre_name' => $word['voice_name'],
  852. 'emotion' => $word['emotion'],
  853. 'emotion_type' => $word['emotion_type'],
  854. 'speed_ratio' => $word['speed_ratio'],
  855. 'loudness_ratio'=> $word['loudness_ratio'],
  856. 'emotion_scale' => $word['emotion_scale'],
  857. 'pitch' => $word['pitch']
  858. ];
  859. $word['paragraph_audio_url'] = '';
  860. // 判断生成参数是否相同,相同则直接使用已生成的音频
  861. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  862. // 如果音频存在并且参数都未改变则使用已生成的音频
  863. if (getProp($paragraph, 'paragraph_audio_url')) {
  864. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  865. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  866. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  867. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  868. // {
  869. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  870. // }
  871. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  872. }
  873. $tmp = $word;
  874. // 组装章节分句音频数据
  875. // $tmp['sequence'] = getProp($word, 'sequence');
  876. // $tmp['text'] = getProp($word, 'text');
  877. // $tmp['emotion'] = getProp($word, 'emotion');
  878. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  879. // $tmp['voice_name'] = getProp($word, 'voice_name');
  880. // $tmp['voice_type'] = getProp($word, 'voice_type');
  881. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  882. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  883. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  884. $tmp['bid'] = $bid;
  885. $tmp['version_id'] = $version_id;
  886. $tmp['cid'] = $cid;
  887. $tmp['sequence'] = $sequence;
  888. $tmp['created_at'] = date('Y-m-d H:i:s');
  889. $tmp['updated_at'] = date('Y-m-d H:i:s');
  890. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  891. $mp_chapter_paragraph_audios[] = $tmp;
  892. $complete_paragraph_sequences[] = $sequence;
  893. $sequence++;
  894. }
  895. $generate_json = json_encode($words, 256);
  896. // 判断是否有未生成字幕的段落
  897. $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();
  898. if ($no_subtitle_sequences) {
  899. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  900. }
  901. try {
  902. DB::beginTransaction();
  903. $role_info = json_encode($existed_role_info, 256);
  904. $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')]);
  905. if (!$boolen) {
  906. DB::rollBack();
  907. Utils::throwError('20003:更新角色信息失败');
  908. }
  909. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  910. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  911. if (!$count) {
  912. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  913. }else {
  914. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  915. }
  916. $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')]);
  917. if (!$boolen1) {
  918. DB::rollBack();
  919. Utils::throwError('20003:更新生成数据失败');
  920. }
  921. $id = DB::table('mp_audio_tasks')->insertGetId([
  922. 'audio_id' => getProp($chapter_audio, 'id'),
  923. 'generate_status' => '执行中',
  924. 'generate_json' => $generate_json,
  925. 'bid' => $bid,
  926. 'book_name' => getProp($chapter_audio, 'book_name'),
  927. 'version_id' => $version_id,
  928. 'version_name' => getProp($chapter_audio, 'version_name'),
  929. 'cid' => $cid,
  930. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  931. 'task_name' => $task_name,
  932. 'created_at' => date('Y-m-d H:i:s'),
  933. 'updated_at' => date('Y-m-d H:i:s')
  934. ]);
  935. if (!$id) {
  936. DB::rollBack();
  937. Utils::throwError('20003:创建任务失败');
  938. }
  939. // 删除不在段落序号范围内的其他数据
  940. if ($complete_paragraph_sequences) {
  941. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  942. }
  943. // // 删除章节分句音频数据并重新插入
  944. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  945. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  946. // if (!$boolen3) {
  947. // DB::rollBack();
  948. // Utils::throwError('20003:更新章节分句音频失败');
  949. // }
  950. } catch (\Exception $e) {
  951. DB::rollBack();
  952. Utils::throwError('20003:'.$e->getMessage());
  953. }
  954. DB::commit();
  955. // 通知火山生成音频
  956. $client = new Client(['timeout' => 300, 'verify' => false]);
  957. // 根据ID通过API通知合成音频
  958. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  959. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  960. $response = $result->getBody()->getContents();
  961. $response_arr = json_decode($response, true);
  962. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  963. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  964. Log::info('通知火山生成音频失败: '.$error_msg);
  965. Utils::throwError('20003:通知火山生成音频失败');
  966. }
  967. return true;
  968. }
  969. public function timbreList($data) {
  970. $gender = getProp($data, 'gender');
  971. $timbre_name = getProp($data, 'voice_name');
  972. $category_id = getProp($data, 'category_id');
  973. $query = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_name as voice_name', 'timbre_type as voice_type', 'gender', 'language', 'emotion', 'label', 'first_category_id', 'first_category_name', 'second_category_id', 'second_category_name', 'third_category_id', 'third_category_name', 'audio_url');
  974. if ($gender) {
  975. $query->where('gender', $gender);
  976. }
  977. if ($timbre_name) {
  978. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  979. }
  980. if ($category_id) {
  981. $query->where(function ($query) use ($category_id) {
  982. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  983. });
  984. }
  985. $list = $query->get()->map(function ($value) {
  986. $value = (array)$value;
  987. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  988. return $value;
  989. })->toArray();
  990. return $list;
  991. }
  992. // 生成火山临时token
  993. public function setStsToken() {
  994. // ************* 配置参数 *************
  995. $method = 'GET';
  996. $service = 'sts';
  997. $host = 'open.volcengineapi.com';
  998. $region = env('VOLC_REGION');
  999. $endpoint = 'https://open.volcengineapi.com';
  1000. // $endpoint = 'https://tos-cn-beijing.volces.com';
  1001. $access_key = env('VOLC_AK');
  1002. $secret_key = env('VOLC_SK');
  1003. // 获取缓存中的token,如果没有则请求接口
  1004. $token = Redis::get('volc_sts_token');
  1005. if (!$token) {
  1006. // 查询参数
  1007. $query_parameters = [
  1008. 'Action' => 'AssumeRole',
  1009. 'RoleSessionName' => 'user@zw',
  1010. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  1011. 'Version' => '2018-01-01'
  1012. ];
  1013. // 生成URL编码的查询字符串
  1014. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  1015. // 获取签名头信息
  1016. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  1017. // 构建完整URL
  1018. $request_url = $endpoint . '?' . $request_parameters;
  1019. $client = new Client(['verify' => false]);
  1020. $response = $client->get($request_url, ['headers' => $headers]);
  1021. $response_arr = json_decode($response->getBody()->getContents(), true);
  1022. $result = [
  1023. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  1024. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  1025. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  1026. 'Region' => env('VOLC_REGION'),
  1027. 'Endpoint' => env('VOLC_END_POINT'),
  1028. 'Bucket' => env('VOLC_BUCKET'),
  1029. ];
  1030. // 缓存token
  1031. Redis::setex('volc_sts_token', 3000, json_encode($result));
  1032. return $result;
  1033. } else {
  1034. return json_decode($token, true);
  1035. }
  1036. // $response = $response['Response'];
  1037. // $access_key = $response['Credentials']['AccessKeyId'];
  1038. // $secret_key = $response['Credentials']['AccessKeySecret'];
  1039. // $security_token = $response['Credentials']['SecurityToken'];
  1040. // $expiration = $response['Credentials']['Expiration'];
  1041. // dd($response_arr);
  1042. }
  1043. public function emotionGroups($data) {
  1044. $id = getProp($data, 'group_id');
  1045. $group_name = getProp($data, 'group_name');
  1046. $voice_type = getProp($data, 'voice_type');
  1047. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  1048. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  1049. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  1050. if ($group_name) {
  1051. $query->where('group_name', 'like', "%{$group_name}%");
  1052. }
  1053. if ($id) {
  1054. $query->where('id', $id);
  1055. }
  1056. if ($voice_type) {
  1057. $query->where('voice_type', $voice_type);
  1058. }
  1059. return $query->orderBy('id')->get()->map(function ($value) {
  1060. return (array)$value;
  1061. })->toArray();
  1062. }
  1063. private function sign($key, $msg) {
  1064. return hash_hmac('sha256', $msg, $key, true);
  1065. }
  1066. // 生成签名密钥
  1067. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  1068. $kDate = $this->sign($key, $dateStamp);
  1069. $kRegion = $this->sign($kDate, $regionName);
  1070. $kService = $this->sign($kRegion, $serviceName);
  1071. $kSigning = $this->sign($kService, 'request');
  1072. return $kSigning;
  1073. }
  1074. // 获取签名头信息
  1075. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  1076. $contenttype = 'application/x-www-form-urlencoded';
  1077. $accept = 'application/json';
  1078. // 获取当前UTC时间
  1079. $t = new DateTime('now', new DateTimeZone('UTC'));
  1080. $xdate = $t->format('Ymd\THis\Z');
  1081. $datestamp = $t->format('Ymd');
  1082. // 1. 拼接规范请求串
  1083. $canonical_uri = '/';
  1084. $canonical_querystring = $request_parameters;
  1085. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  1086. $signed_headers = 'content-type;host;x-date';
  1087. // 空请求体的SHA256哈希
  1088. $payload_hash = hash('sha256', '');
  1089. $canonical_request = implode("\n", [
  1090. $method,
  1091. $canonical_uri,
  1092. $canonical_querystring,
  1093. $canonical_headers,
  1094. $signed_headers,
  1095. $payload_hash
  1096. ]);
  1097. // 2. 拼接待签名字符串
  1098. $algorithm = 'HMAC-SHA256';
  1099. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  1100. $hashed_canonical_request = hash('sha256', $canonical_request);
  1101. $string_to_sign = implode("\n", [
  1102. $algorithm,
  1103. $xdate,
  1104. $credential_scope,
  1105. $hashed_canonical_request
  1106. ]);
  1107. // 3. 计算签名
  1108. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  1109. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  1110. // 4. 添加签名到请求头
  1111. $authorization_header = sprintf(
  1112. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  1113. $algorithm,
  1114. $access_key,
  1115. $credential_scope,
  1116. $signed_headers,
  1117. $signature
  1118. );
  1119. return [
  1120. 'Accept' => $accept,
  1121. 'Content-Type' => $contenttype,
  1122. 'X-Date' => $xdate,
  1123. 'Authorization' => $authorization_header
  1124. ];
  1125. }
  1126. // 文字合成语音(火山引擎)
  1127. public function tts($data) {
  1128. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  1129. $headers = [
  1130. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  1131. 'Content-Type' => 'application/json; charset=UTF-8'
  1132. ];
  1133. $post_data = [
  1134. 'app' => [
  1135. 'appid' => env('VOLC_APPID'),
  1136. 'token' => env('VOLC_TOKEN'),
  1137. 'cluster' => 'volcano_tts'
  1138. ],
  1139. 'user' => [
  1140. 'uid' => 'mp_audio'
  1141. ],
  1142. // 'audio' => [
  1143. // 'voice_type' =>
  1144. // ],
  1145. ];
  1146. }
  1147. public function scriptList($data) {
  1148. $script_id = getProp($data, 'script_id');
  1149. $script_name = getProp($data, 'script_name');
  1150. $query = DB::table('mp_scripts')->where('is_deleted', 0)->select('*');
  1151. if ($script_id) {
  1152. $query->where('id', $script_id);
  1153. }
  1154. if ($script_name) {
  1155. $query->where('script_name', 'like', "%{$script_name}%");
  1156. }
  1157. return $query->orderBy('created_at', 'desc')->paginate(12);
  1158. }
  1159. public function scripts($data) {
  1160. $script_id = getProp($data, 'script_id');
  1161. $script_name = getProp($data, 'script_name');
  1162. $query = DB::table('mp_scripts')->where('is_deleted', 0)->select('id as script_id', 'script_name');
  1163. if ($script_id) {
  1164. $query->where('id', $script_id);
  1165. }
  1166. if ($script_name) {
  1167. $query->where('script_name', 'like', "%{$script_name}%");
  1168. }
  1169. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  1170. return (array)$value;
  1171. })->toArray();
  1172. }
  1173. public function scriptInfo($data) {
  1174. $script_id = getProp($data, 'script_id');
  1175. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  1176. // ->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();
  1177. ->selectRaw('id as script_id, script_name')->first();
  1178. if (!$script) Utils::throwError('20003:该剧本不存在!');
  1179. $script = (array)$script;
  1180. // 获取分集组信息
  1181. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  1182. ->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')
  1183. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  1184. $value = (array)$value;
  1185. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  1186. return (array)$value;
  1187. })->toArray();
  1188. $script['group'] = $groups;
  1189. return $script;
  1190. }
  1191. public function createScript($data) {
  1192. $script_name = getProp($data, 'script_name');
  1193. $uid = Site::getUid(); // 获取当前用户ID
  1194. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  1195. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  1196. $script_name .= '_'.date('YmdHis');
  1197. }
  1198. return DB::table('mp_scripts')->insertGetId([
  1199. 'script_name' => $script_name,
  1200. 'user_id' => $uid,
  1201. 'created_at' => date('Y-m-d H:i:s'),
  1202. 'updated_at' => date('Y-m-d H:i:s')
  1203. ]);
  1204. }
  1205. public function editScript($data) {
  1206. $script_id = getProp($data, 'script_id');
  1207. $script_name = getProp($data, 'script_name');
  1208. $uid = Site::getUid(); // 获取当前用户ID
  1209. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  1210. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  1211. if ($id && (int)$id !== (int)$script_id) {
  1212. $script_name .= '_'.date('YmdHis');
  1213. }
  1214. return DB::table('mp_scripts')->where('id', $script_id)->update([
  1215. 'script_name' => $script_name,
  1216. 'updated_at' => date('Y-m-d H:i:s')
  1217. ]);
  1218. }
  1219. public function delScript($data) {
  1220. $script_id = getProp($data, 'script_id');
  1221. $uid = Site::getUid(); // 获取当前用户ID
  1222. if (!$script_id) Utils::throwError('20003:请选择剧本');
  1223. return DB::table('mp_scripts')->where('id', $script_id)->update([
  1224. 'is_deleted' => 1,
  1225. 'updated_at' => date('Y-m-d H:i:s')
  1226. ]);
  1227. }
  1228. public function createEpisode($data) {
  1229. $script_id = getProp($data, 'script_id');
  1230. $group_name = getProp($data, 'group_name');
  1231. $remark = getProp($data, 'remark');
  1232. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  1233. $uid = Site::getUid(); // 获取当前用户ID
  1234. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  1235. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  1236. $group_name .= '_'.date('YmdHis');
  1237. }
  1238. return DB::table('mp_script_episode_group')->insertGetId([
  1239. 'script_id' => $script_id,
  1240. 'group_name' => $group_name,
  1241. 'user_id' => $uid,
  1242. 'remark' => $remark,
  1243. 'created_at' => date('Y-m-d H:i:s'),
  1244. 'updated_at' => date('Y-m-d H:i:s')
  1245. ]);
  1246. }
  1247. public function editEpisode($data) {
  1248. $group_id = getProp($data, 'group_id');
  1249. $start_episode_number = getProp($data, 'start_episode_number');
  1250. $end_episode_number = getProp($data, 'end_episode_number');
  1251. $group_name = getProp($data, 'group_name');
  1252. $uid = Site::getUid(); // 获取当前用户ID
  1253. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  1254. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  1255. if ($id && (int)$id !== (int)$group_id) {
  1256. $group_name .= '_'.date('YmdHis');
  1257. }
  1258. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1259. 'group_name' => $group_name,
  1260. 'start_episode_number' => $start_episode_number,
  1261. 'end_episode_number' => $end_episode_number,
  1262. 'updated_at' => date('Y-m-d H:i:s')
  1263. ]);
  1264. }
  1265. public function delEpisode($data) {
  1266. $group_id = getProp($data, 'group_id');
  1267. $uid = Site::getUid(); // 获取当前用户ID
  1268. if (!$group_id) Utils::throwError('20003:请选择分集');
  1269. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1270. 'is_deleted' => 1,
  1271. 'updated_at' => date('Y-m-d H:i:s')
  1272. ]);
  1273. }
  1274. /**
  1275. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  1276. *
  1277. * @param array $data 包含以下参数:
  1278. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1279. * - question: 用户问题(可选)
  1280. * - model: 使用的模型(r1 或 v3,默认 v3)
  1281. * @return \Generator 返回生成器,用于流式输出
  1282. */
  1283. public function generateEpisodes($data) {
  1284. $script_id = getProp($data, 'script_id');
  1285. $group_id = getProp($data, 'group_id');
  1286. // $file = getProp($data, 'file');
  1287. $file = '';
  1288. $content = getProp($data, 'content', '');
  1289. // $bid = getProp($data, 'bid', 0);
  1290. $bid = 0;
  1291. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  1292. if (!$group) {
  1293. Utils::throwError('20003:剧本分集不存在');
  1294. }
  1295. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  1296. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  1297. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  1298. $prompt = getProp($data, 'prompt');
  1299. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  1300. $model = getProp($data, 'model');
  1301. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  1302. Utils::throwError('20003:该模型不存在!');
  1303. }
  1304. // 检查是否存在重叠的剧集序号范围
  1305. $exists_groups = DB::table('mp_script_episode_group')
  1306. ->where('script_id', $script_id)
  1307. ->where('id', '<>', $group_id) // 排除当前组
  1308. ->where('is_deleted', 0)
  1309. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  1310. // 检查新范围是否与现有范围重叠
  1311. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1312. // 新范围的开始在现有范围内
  1313. $q->where('start_episode_number', '<=', $start_episode_sequence)
  1314. ->where('end_episode_number', '>=', $start_episode_sequence);
  1315. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1316. // 新范围的结束在现有范围内
  1317. $q->where('start_episode_number', '<=', $end_episode_sequence)
  1318. ->where('end_episode_number', '>=', $end_episode_sequence);
  1319. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1320. // 新范围完全包含现有范围
  1321. $q->where('start_episode_number', '>=', $start_episode_sequence)
  1322. ->where('end_episode_number', '<=', $end_episode_sequence);
  1323. });
  1324. })
  1325. ->select('start_episode_number', 'end_episode_number')
  1326. ->get();
  1327. if ($exists_groups->isNotEmpty()) {
  1328. $conflict_ranges = [];
  1329. foreach ($exists_groups as $group) {
  1330. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  1331. }
  1332. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  1333. }
  1334. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1335. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1336. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1337. if ($model === 'deepseek-chat') {
  1338. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1339. $model = 'deepseek-v4-flash';
  1340. $thinkingMode = 'disabled';
  1341. } elseif ($model === 'deepseek-reasoner') {
  1342. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1343. $model = 'deepseek-v4-flash';
  1344. $thinkingMode = 'enabled';
  1345. }
  1346. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1347. if (!$script) {
  1348. Utils::throwError('20003:剧本不存在');
  1349. }
  1350. $content = getProp($group, 'content');
  1351. if (!$file && !$content && !$bid) {
  1352. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1353. }
  1354. // 提取文件内容
  1355. if ($file) {
  1356. $content = $this->extractFileContent($file);
  1357. if (!$content) {
  1358. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1359. }
  1360. } elseif ($bid) {
  1361. $content = $this->getContentByBid($bid);
  1362. if (!$content) {
  1363. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1364. }
  1365. } elseif ($content) {
  1366. $content = filterContent($content);
  1367. } elseif ($prompt) {
  1368. $content = filterContent($prompt);
  1369. } else {
  1370. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1371. }
  1372. // 构建消息
  1373. $messages = [
  1374. $this->sys_message,
  1375. [
  1376. 'role' => 'user',
  1377. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1378. ]
  1379. ];
  1380. $post_data = [
  1381. 'model' => $model,
  1382. 'messages' => $messages,
  1383. // 'max_tokens' => 8192,
  1384. 'temperature' => 0.7,
  1385. 'frequency_penalty' => 0,
  1386. 'presence_penalty' => 0,
  1387. 'thinking' => ['type' => $thinkingMode],
  1388. 'response_format' => ['type' => 'text'],
  1389. 'stream' => true
  1390. ];
  1391. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1392. // 根据模型类型选择调用方法
  1393. $fullContent = '';
  1394. $fullReasoningContent = '';
  1395. $usage = [];
  1396. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1397. // DeepSeek 官方模型使用 DeepSeek API
  1398. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  1399. } else {
  1400. // 其他模型使用火山引擎API
  1401. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  1402. }
  1403. // 处理流式输出
  1404. foreach ($streamGenerator as $chunk) {
  1405. if (isset($chunk['type'])) {
  1406. if ($chunk['type'] === 'done') {
  1407. // 最终结果
  1408. $fullContent = $chunk['full_content'];
  1409. $fullReasoningContent = $chunk['full_reasoning'];
  1410. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  1411. } else {
  1412. // 逐块yield数据
  1413. yield $chunk;
  1414. }
  1415. }
  1416. }
  1417. dLog('deepseek')->info('完整内容: '.$fullContent);
  1418. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  1419. // 处理完整内容并返回最终结果
  1420. $script_arr = [];
  1421. if ($fullContent) {
  1422. $script_arr = extractScriptContent($fullContent);
  1423. }
  1424. logDB('deepseek', 'info', '解析内容', $script_arr);
  1425. if (!$script_arr['episodes']) {
  1426. Utils::throwError('20003:未生成剧本相关信息');
  1427. // yield [
  1428. // 'type' => 'done',
  1429. // 'script' => $script_arr,
  1430. // 'msg' => '未生成剧本相关信息',
  1431. // 'answer' => $fullContent,
  1432. // 'reasoning' => $fullReasoningContent,
  1433. // 'usage' => $usage
  1434. // ];
  1435. // return ;
  1436. }
  1437. try {
  1438. DB::beginTransaction();
  1439. // // 返回前保存剧本内容
  1440. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  1441. // 'content' => $content,
  1442. // 'updated_at' => date('Y-m-d H:i:s')
  1443. // ]);
  1444. // if (!$boolen) {
  1445. // Utils::throwError('20003:保存剧本内容失败');
  1446. // }
  1447. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1448. // 'start_episode_number' => $start_episode_sequence,
  1449. // 'end_episode_number' => $end_episode_sequence,
  1450. // 'updated_at' => date('Y-m-d H:i:s')
  1451. // ]);
  1452. // if (!$boolen1) {
  1453. // Utils::throwError('20003:保存分集失败');
  1454. // }
  1455. $episode_content = '';
  1456. $episodes = [];
  1457. foreach ($script_arr['episodes'] as $item) {
  1458. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  1459. // $episodes[] = [
  1460. // 'script_id' => $script_id,
  1461. // 'episode_number' => $item['episode_number'],
  1462. // 'episode_name' => $item['episode_name'],
  1463. // 'episode_content' => $item['episode_content'],
  1464. // 'created_at' => date('Y-m-d H:i:s'),
  1465. // 'updated_at' => date('Y-m-d H:i:s'),
  1466. // ];
  1467. }
  1468. if ($episode_content) {
  1469. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1470. 'episode_content' => $episode_content,
  1471. 'updated_at' => date('Y-m-d H:i:s')
  1472. ]);
  1473. if (!$boolen2) {
  1474. Utils::throwError('20003:保存分集内容失败');
  1475. }
  1476. }else {
  1477. Utils::throwError('20003:分集剧本解析失败');
  1478. }
  1479. }catch (\Exception $e) {
  1480. DB::rollBack();
  1481. Utils::throwError('20003:'.$e->getMessage());
  1482. }
  1483. DB::commit();
  1484. yield [
  1485. 'type' => 'done',
  1486. 'script' => $script_arr,
  1487. 'episode_content' => $episode_content,
  1488. 'answer' => $fullContent,
  1489. 'reasoning' => $fullReasoningContent,
  1490. 'usage' => $usage
  1491. ];
  1492. }
  1493. public function chatWithFileStream($data) {
  1494. $script_id = getProp($data, 'script_id');
  1495. $group_id = getProp($data, 'group_id');
  1496. $file = getProp($data, 'file');
  1497. $content = getProp($data, 'content', '');
  1498. $bid = getProp($data, 'bid', 0);
  1499. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1500. $total_episode_num = getProp($data, 'total_episode_num', 30);
  1501. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  1502. $prompt = getProp($data, 'prompt');
  1503. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n本次修改要求如下: {$prompt}\n");
  1504. $model = getProp($data, 'model');
  1505. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  1506. Utils::throwError('20003:该模型不存在!');
  1507. }
  1508. // 检查是否存在重叠的剧集序号范围
  1509. $exists_groups = DB::table('mp_script_episode_group')
  1510. ->where('script_id', $script_id)
  1511. ->where('id', '<>', $group_id)
  1512. ->where('is_deleted', 0)
  1513. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  1514. // 检查新范围是否与现有范围重叠
  1515. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1516. // 新范围的开始在现有范围内
  1517. $q->where('start_episode_number', '<=', $start_episode_sequence)
  1518. ->where('end_episode_number', '>=', $start_episode_sequence);
  1519. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1520. // 新范围的结束在现有范围内
  1521. $q->where('start_episode_number', '<=', $end_episode_sequence)
  1522. ->where('end_episode_number', '>=', $end_episode_sequence);
  1523. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1524. // 新范围完全包含现有范围
  1525. $q->where('start_episode_number', '>=', $start_episode_sequence)
  1526. ->where('end_episode_number', '<=', $end_episode_sequence);
  1527. });
  1528. })
  1529. ->select('start_episode_number', 'end_episode_number')
  1530. ->get();
  1531. if ($exists_groups->isNotEmpty()) {
  1532. $conflict_ranges = [];
  1533. foreach ($exists_groups as $group) {
  1534. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  1535. }
  1536. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  1537. }
  1538. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1539. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1540. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1541. if ($model === 'deepseek-chat') {
  1542. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1543. $model = 'deepseek-v4-flash';
  1544. $thinkingMode = 'disabled';
  1545. } elseif ($model === 'deepseek-reasoner') {
  1546. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1547. $model = 'deepseek-v4-flash';
  1548. $thinkingMode = 'enabled';
  1549. }
  1550. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1551. if (!$script) {
  1552. Utils::throwError('20003:剧本不存在');
  1553. }
  1554. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  1555. if (!$group) {
  1556. Utils::throwError('20003:剧本分集不存在');
  1557. }
  1558. if (!$file && !$content && !$bid) {
  1559. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1560. }
  1561. // 提取文件内容
  1562. if ($file) {
  1563. $content = $this->extractFileContent($file);
  1564. if (!$content) {
  1565. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1566. }
  1567. } elseif ($bid) {
  1568. $content = $this->getContentByBid($bid);
  1569. if (!$content) {
  1570. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1571. }
  1572. } elseif ($content) {
  1573. $content = filterContent($content);
  1574. } elseif ($prompt) {
  1575. $content = filterContent($prompt);
  1576. } else {
  1577. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1578. }
  1579. // 构建消息
  1580. $messages = [
  1581. [
  1582. 'role' => 'system',
  1583. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  1584. 强制要求:\n
  1585. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  1586. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  1587. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  1588. 普通要求:\n
  1589. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  1590. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  1591. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  1592. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  1593. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  1594. 示例如下:\n
  1595. ###剧本名:西昆仑
  1596. ###故事梗概
  1597. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1598. ###剧本亮点
  1599. 亮点1:绝境奇药,生死一线
  1600. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  1601. 亮点2:结拜兄妹,化解尴尬
  1602. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  1603. 亮点3:纤发夺命,情愫暗涌
  1604. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  1605. ###人物关系
  1606. 阿雪与梁萧之间存在兄妹之情。
  1607. ###核心矛盾
  1608. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  1609. ###主体列表
  1610. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  1611. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  1612. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  1613. 阴阳球:天地异宝,能化生精气,救人于危难。
  1614. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  1615. ###美术风格
  1616. 基础画风风格词:厚涂古风
  1617. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  1618. ###场景列表
  1619. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  1620. [
  1621. 'role' => 'user',
  1622. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1623. ]
  1624. ];
  1625. $post_data = [
  1626. 'model' => $model,
  1627. 'messages' => $messages,
  1628. // 'max_tokens' => 8192,
  1629. 'temperature' => 0.7,
  1630. 'frequency_penalty' => 0,
  1631. 'presence_penalty' => 0,
  1632. 'thinking' => ['type' => $thinkingMode],
  1633. 'response_format' => ['type' => 'text'],
  1634. 'stream' => true
  1635. ];
  1636. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1637. // 根据模型类型选择调用方法
  1638. $fullContent = '';
  1639. $fullReasoningContent = '';
  1640. $usage = [];
  1641. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1642. // DeepSeek 官方模型使用 DeepSeek API
  1643. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  1644. } else {
  1645. // 其他模型使用火山引擎API
  1646. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  1647. }
  1648. // 处理流式输出
  1649. foreach ($streamGenerator as $chunk) {
  1650. if (isset($chunk['type'])) {
  1651. if ($chunk['type'] === 'done') {
  1652. // 最终结果
  1653. $fullContent = $chunk['full_content'];
  1654. $fullReasoningContent = $chunk['full_reasoning'];
  1655. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  1656. } else {
  1657. // 逐块yield数据
  1658. yield $chunk;
  1659. }
  1660. }
  1661. }
  1662. dLog('deepseek')->info('完整内容: '.$fullContent);
  1663. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  1664. // 处理完整内容并返回最终结果
  1665. $script_arr = [];
  1666. if ($fullContent) {
  1667. $script_arr = extractScriptContent($fullContent);
  1668. }
  1669. logDB('deepseek', 'info', '解析内容', $script_arr);
  1670. if (!$script_arr['roles']) {
  1671. Utils::throwError('20003:未生成剧本相关信息');
  1672. // yield [
  1673. // 'type' => 'done',
  1674. // 'script' => $script_arr,
  1675. // 'msg' => '未生成剧本相关信息',
  1676. // 'answer' => $fullContent,
  1677. // 'reasoning' => $fullReasoningContent,
  1678. // 'usage' => $usage
  1679. // ];
  1680. }
  1681. try {
  1682. DB::beginTransaction();
  1683. // // 返回前保存剧本内容
  1684. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  1685. // 'content' => $content,
  1686. // 'status' => '解析完成',
  1687. // 'updated_at' => date('Y-m-d H:i:s')
  1688. // ]);
  1689. // if (!$boolen) {
  1690. // Utils::throwError('20003:保存剧本内容失败');
  1691. // }
  1692. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  1693. 'start_episode_number' => $start_episode_sequence,
  1694. 'end_episode_number' => $end_episode_sequence,
  1695. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  1696. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  1697. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  1698. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  1699. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  1700. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  1701. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  1702. 'status' => '解析完成',
  1703. 'content' => $content,
  1704. 'updated_at' => date('Y-m-d H:i:s')
  1705. ]);
  1706. if (!$boolen1) {
  1707. Utils::throwError('20003:保存分集失败');
  1708. }
  1709. // $episodes = [];
  1710. // foreach ($script_arr['episodes'] as $item) {
  1711. // $episodes[] = [
  1712. // 'script_id' => $script_id,
  1713. // 'episode_number' => $item['episode_number'],
  1714. // 'episode_name' => $item['episode_name'],
  1715. // 'episode_content' => $item['episode_content'],
  1716. // 'created_at' => date('Y-m-d H:i:s'),
  1717. // 'updated_at' => date('Y-m-d H:i:s'),
  1718. // ];
  1719. // }
  1720. // if ($episodes) {
  1721. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  1722. // if (!$boolen2) {
  1723. // Utils::throwError('20003:保存分集内容失败');
  1724. // }
  1725. // }else {
  1726. // Utils::throwError('20003:分集剧本解析失败');
  1727. // }
  1728. }catch (\Exception $e) {
  1729. DB::rollBack();
  1730. Utils::throwError('20003:'.$e->getMessage());
  1731. }
  1732. DB::commit();
  1733. yield [
  1734. 'type' => 'done',
  1735. 'script' => $script_arr,
  1736. 'answer' => $fullContent,
  1737. 'reasoning' => $fullReasoningContent,
  1738. 'usage' => $usage
  1739. ];
  1740. }
  1741. /**
  1742. * 上传文件识别文字内容并与 DeepSeek 进行对话
  1743. *
  1744. * @param array $data 包含以下参数:
  1745. * - file: 上传的文件(UploadedFile 对象)或文件路径
  1746. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  1747. * - model: 使用的模型(r1 或 v3,默认 v3)
  1748. * @return array
  1749. */
  1750. public function chatWithFile($data) {
  1751. $script_id = getProp($data, 'script_id');
  1752. $file = getProp($data, 'file');
  1753. $content = getProp($data, 'content', '');
  1754. $bid = getProp($data, 'bid', 0);
  1755. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1756. $total_episode_num = getProp($data, 'total_episode_num', 30);
  1757. $prompt = getProp($data, 'prompt');
  1758. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n本次修改要求如下: {$prompt}\n");
  1759. // 处理文本模型
  1760. $model = getProp($data, 'model');
  1761. if (!$model) {
  1762. // 用户没有输入,使用默认值
  1763. $model = 'doubao-seed-2-0-mini-260215';
  1764. }
  1765. // 验证模型是否在可用模型表中
  1766. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  1767. $model = 'doubao-seed-2-0-mini-260215';
  1768. }
  1769. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1770. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1771. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1772. if ($model === 'deepseek-chat') {
  1773. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  1774. $model = 'deepseek-v4-flash';
  1775. $thinkingMode = 'disabled';
  1776. } elseif ($model === 'deepseek-reasoner') {
  1777. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  1778. $model = 'deepseek-v4-flash';
  1779. $thinkingMode = 'enabled';
  1780. }
  1781. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  1782. if (!$script) {
  1783. Utils::throwError('20003:剧本不存在');
  1784. }
  1785. if (!$file && !$content && !$bid) {
  1786. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1787. }
  1788. // 提取文件内容
  1789. if ($file) {
  1790. $content = $this->extractFileContent($file);
  1791. if (!$content) {
  1792. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  1793. }
  1794. } elseif ($bid) {
  1795. $content = $this->getContentByBid($bid);
  1796. if (!$content) {
  1797. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  1798. }
  1799. } elseif ($content) {
  1800. $content = filterContent($content);
  1801. } elseif ($prompt) {
  1802. $content = filterContent($prompt);
  1803. } else {
  1804. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  1805. }
  1806. // 构建消息
  1807. $messages = [
  1808. $this->sys_message,
  1809. [
  1810. 'role' => 'user',
  1811. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  1812. ]
  1813. ];
  1814. $post_data = [
  1815. 'model' => $model,
  1816. 'messages' => $messages,
  1817. // 'max_tokens' => 8192,
  1818. 'temperature' => 0.7,
  1819. 'frequency_penalty' => 0,
  1820. 'presence_penalty' => 0,
  1821. 'thinking' => ['type' => $thinkingMode],
  1822. 'response_format' => ['type' => 'text'],
  1823. 'stream' => false
  1824. ];
  1825. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1826. // 根据模型类型选择调用方法
  1827. $fullContent = '';
  1828. $usage = [];
  1829. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1830. // DeepSeek 官方模型使用 DeepSeek API
  1831. $chatResult = $this->chatOnly($post_data);
  1832. } else {
  1833. // 其他模型使用火山引擎API
  1834. $chatResult = $this->volcEngineChatCompletion($post_data);
  1835. }
  1836. if (is_array($chatResult)) {
  1837. $fullContent = $chatResult['fullContent'];
  1838. $usage = $chatResult['usage'];
  1839. }
  1840. $script_arr = [];
  1841. // 处理结果
  1842. if ($fullContent) {
  1843. $script_arr = extractScriptContent($fullContent);
  1844. }
  1845. // 返回前保存剧本内容
  1846. DB::table('mp_scripts')->where('id', $script_id)->update([
  1847. 'content' => $content,
  1848. 'updated_at' => date('Y-m-d H:i:s')
  1849. ]);
  1850. return [
  1851. 'script' => $script_arr,
  1852. 'answer' => $fullContent,
  1853. 'usage' => $usage
  1854. ];
  1855. }
  1856. public function getEpisodeContent($data) {
  1857. $group_id = getProp($data, 'group_id');
  1858. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  1859. }
  1860. public function saveEpisodeContent($data) {
  1861. $script_id = getProp($data, 'script_id');
  1862. $group_id = getProp($data, 'group_id');
  1863. $start_episode_sequence = getProp($data, 'start_episode_number');
  1864. $end_episode_sequence = getProp($data, 'end_episode_number');
  1865. // 检查是否存在重叠的剧集序号范围
  1866. $exists_groups = DB::table('mp_script_episode_group')
  1867. ->where('script_id', $script_id)
  1868. ->where('id', '<>', $group_id) // 排除当前组
  1869. ->where('is_deleted', 0)
  1870. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  1871. // 检查新范围是否与现有范围重叠
  1872. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1873. // 新范围的开始在现有范围内
  1874. $q->where('start_episode_number', '<=', $start_episode_sequence)
  1875. ->where('end_episode_number', '>=', $start_episode_sequence);
  1876. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1877. // 新范围的结束在现有范围内
  1878. $q->where('start_episode_number', '<=', $end_episode_sequence)
  1879. ->where('end_episode_number', '>=', $end_episode_sequence);
  1880. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  1881. // 新范围完全包含现有范围
  1882. $q->where('start_episode_number', '>=', $start_episode_sequence)
  1883. ->where('end_episode_number', '<=', $end_episode_sequence);
  1884. });
  1885. })
  1886. ->select('start_episode_number', 'end_episode_number')
  1887. ->get();
  1888. if ($exists_groups->isNotEmpty()) {
  1889. $conflict_ranges = [];
  1890. foreach ($exists_groups as $group) {
  1891. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  1892. }
  1893. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  1894. }
  1895. $episode_content = getProp($data, 'episode_content');
  1896. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  1897. 'content' => $episode_content,
  1898. 'start_episode_number' => $start_episode_sequence,
  1899. 'end_episode_number' => $end_episode_sequence,
  1900. 'updated_at' => date('Y-m-d H:i:s')
  1901. ]);
  1902. $script_arr =getProp($data, 'script', []);
  1903. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  1904. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  1905. $script_id = getProp($data, 'script_id');
  1906. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  1907. try {
  1908. DB::beginTransaction();
  1909. $update_data = [
  1910. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  1911. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  1912. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  1913. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  1914. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  1915. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  1916. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  1917. 'status' => 3,
  1918. 'start_episode_sequence' => $start_episode_sequence,
  1919. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  1920. 'episode_num' => count($script_arr['episodes']),
  1921. 'updated_at' => date('Y-m-d H:i:s')
  1922. ];
  1923. // 保存剧本内容
  1924. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  1925. if (!$boolen) {
  1926. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  1927. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  1928. Utils::throwError('20003:剧本内容保存失败');
  1929. }
  1930. // 保存分集内容
  1931. // 删除历史分集内容
  1932. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  1933. $episodes = [];
  1934. $sequence = 1;
  1935. foreach ($script_arr['episodes'] as $episode) {
  1936. $segment_number = 1;
  1937. foreach($episode['segments'] as $segment) {
  1938. $episodes[] = [
  1939. 'script_id' => $script_id,
  1940. 'episode_number' => $episode['episode_number'],
  1941. 'title' => $episode['title'],
  1942. // 'content' => $episode['content'],
  1943. 'content' => '',
  1944. 'segment_number' => $segment_number,
  1945. 'segment_content' => $segment['segment_content'],
  1946. 'sequence' => $sequence,
  1947. 'created_at' => date('Y-m-d H:i:s'),
  1948. 'updated_at' => date('Y-m-d H:i:s')
  1949. ];
  1950. $sequence++;
  1951. $segment_number++;
  1952. }
  1953. }
  1954. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  1955. if (!$boolen2) {
  1956. dLog('deepseek')->info('分集内容保存失败', $episodes);
  1957. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  1958. Utils::throwError('20003:分集内容保存失败');
  1959. }
  1960. } catch (\Exception $e) {
  1961. DB::rollBack();
  1962. Utils::throwError('20003:'.$e->getMessage());
  1963. }
  1964. DB::commit();
  1965. return true;
  1966. }
  1967. public function getBookContent($data) {
  1968. $bid = getProp($data, 'bid');
  1969. $start_sequence = getProp($data, 'start_sequence');
  1970. $end_sequence = getProp($data, 'end_sequence');
  1971. $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])
  1972. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  1973. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  1974. return $return_content;
  1975. }
  1976. public function exportScript($data) {
  1977. $filename = getProp($data, 'filename');
  1978. $script_id = getProp($data, 'script_id');
  1979. $group_id = getProp($data, 'group_id');
  1980. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  1981. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  1982. if (!$script) Utils::throwError('20003:该剧本不存在!');
  1983. $script = (array)$script;
  1984. // 获取分集组信息
  1985. if ($group_id) {
  1986. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  1987. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  1988. ->get()->map(function($value) {
  1989. return (array)$value;
  1990. })->toArray();
  1991. }else {
  1992. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  1993. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  1994. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  1995. return (array)$value;
  1996. })->toArray();
  1997. }
  1998. if (!$groups) Utils::throwError('20003:分集不存在');
  1999. $script['group'] = $groups;
  2000. $export_type = getProp($data, 'export_type', 'txt');
  2001. // 生成文件名
  2002. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  2003. // 根据导出类型生成不同格式的文件
  2004. switch ($export_type) {
  2005. case 'txt':
  2006. return $this->exportScriptAsTxt($script, $filename);
  2007. case 'pdf':
  2008. return $this->exportScriptAsPdf($script, $filename);
  2009. default:
  2010. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  2011. }
  2012. }
  2013. /**
  2014. * 导出剧本为TXT格式
  2015. */
  2016. private function exportScriptAsTxt($script, $filename) {
  2017. // 构建TXT内容
  2018. $content = $this->buildScriptContent($script);
  2019. // 设置响应头,直接下载
  2020. header('Content-Type: text/plain; charset=utf-8');
  2021. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  2022. header('Content-Length: ' . strlen($content));
  2023. // 输出内容并结束
  2024. echo $content;
  2025. exit();
  2026. }
  2027. /**
  2028. * 导出剧本为PDF格式
  2029. */
  2030. private function exportScriptAsPdf($script, $filename) {
  2031. // 使用HTML转PDF的方式来更好地支持中文
  2032. $htmlContent = $this->buildScriptHtmlForPdf($script);
  2033. // 创建PDF实例
  2034. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  2035. // 设置文档信息
  2036. $pdf->SetCreator('剧本导出系统');
  2037. $pdf->SetAuthor('系统');
  2038. $pdf->SetTitle($script['script_name']);
  2039. $pdf->SetSubject('剧本导出');
  2040. // 设置边距
  2041. $pdf->SetMargins(15, 15, 15);
  2042. $pdf->SetAutoPageBreak(TRUE, 15);
  2043. // 添加页面
  2044. $pdf->AddPage();
  2045. // 注册并使用 simsun.ttf 字体
  2046. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  2047. // 使用HTML内容生成PDF
  2048. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  2049. // 直接输出PDF文件供下载
  2050. header('Content-Type: application/pdf');
  2051. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  2052. // 直接输出PDF内容
  2053. $pdf->Output($filename . '.pdf', 'D');
  2054. exit();
  2055. }
  2056. /**
  2057. * 构建用于PDF的HTML内容
  2058. */
  2059. private function buildScriptHtmlForPdf($script) {
  2060. $html = '<style>
  2061. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  2062. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  2063. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  2064. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  2065. .info { margin-bottom: 8px; }
  2066. .group { margin-bottom: 30px; page-break-inside: avoid; }
  2067. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  2068. .segment { margin-bottom: 10px; margin-left: 20px; }
  2069. .episode-content { white-space: pre-wrap; }
  2070. </style>';
  2071. // 标题
  2072. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  2073. // 处理分组数据
  2074. if (!empty($script['group']) && is_array($script['group'])) {
  2075. $groups = (array)$script['group'];
  2076. foreach ($groups as $group) {
  2077. $html .= '<div class="group">';
  2078. // 分组标题
  2079. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  2080. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  2081. // 故事梗概
  2082. if (!empty($group['intro'])) {
  2083. $html .= '<h3>故事梗概</h3>';
  2084. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  2085. }
  2086. // 剧本亮点
  2087. if (!empty($group['highlights'])) {
  2088. $html .= '<h3>剧本亮点</h3>';
  2089. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  2090. }
  2091. // 人物关系
  2092. if (!empty($group['role_relationship'])) {
  2093. $html .= '<h3>人物关系</h3>';
  2094. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  2095. }
  2096. // 核心矛盾
  2097. if (!empty($group['core_contradiction'])) {
  2098. $html .= '<h3>核心矛盾</h3>';
  2099. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  2100. }
  2101. // 主体列表
  2102. if (!empty($group['roles']) && is_array($group['roles'])) {
  2103. $html .= '<h3>主体列表</h3>';
  2104. $html .= '<ul>';
  2105. foreach ($group['roles'] as $role) {
  2106. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  2107. }
  2108. $html .= '</ul>';
  2109. }
  2110. // 美术风格
  2111. if (!empty($group['art_style'])) {
  2112. $html .= '<h3>美术风格</h3>';
  2113. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  2114. }
  2115. // 场景列表
  2116. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  2117. $html .= '<h3>场景列表</h3>';
  2118. $html .= '<ul>';
  2119. foreach ($group['scenes'] as $scene) {
  2120. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  2121. }
  2122. $html .= '</ul>';
  2123. }
  2124. // 分集剧本
  2125. if (!empty($group['episode_content'])) {
  2126. $html .= '<h3>分集剧本</h3>';
  2127. // 去除零宽字符和其他不可见字符
  2128. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  2129. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  2130. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  2131. }
  2132. $html .= '</div>';
  2133. }
  2134. }
  2135. return $html;
  2136. }
  2137. /**
  2138. * 构建PDF内容
  2139. */
  2140. private function buildPdfContent($pdf, $script) {
  2141. // 标题
  2142. $pdf->SetFont('dejavusans', 'B', 18);
  2143. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  2144. $pdf->Ln(5);
  2145. // 基本信息
  2146. $pdf->SetFont('dejavusans', '', 12);
  2147. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  2148. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  2149. $pdf->Ln(5);
  2150. // 剧本简介
  2151. if (!empty($script['intro'])) {
  2152. $pdf->SetFont('dejavusans', 'B', 14);
  2153. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  2154. $pdf->SetFont('dejavusans', '', 12);
  2155. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  2156. $pdf->Ln(3);
  2157. }
  2158. // 亮点
  2159. if (!empty($script['highlights'])) {
  2160. $pdf->SetFont('dejavusans', 'B', 14);
  2161. $pdf->Cell(0, 10, '亮点', 0, 1);
  2162. $pdf->SetFont('dejavusans', '', 12);
  2163. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  2164. $pdf->Ln(3);
  2165. }
  2166. // 核心矛盾
  2167. if (!empty($script['core_contradiction'])) {
  2168. $pdf->SetFont('dejavusans', 'B', 14);
  2169. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  2170. $pdf->SetFont('dejavusans', '', 12);
  2171. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  2172. $pdf->Ln(3);
  2173. }
  2174. // 艺术风格
  2175. if (!empty($script['art_style'])) {
  2176. $pdf->SetFont('dejavusans', 'B', 14);
  2177. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  2178. $pdf->SetFont('dejavusans', '', 12);
  2179. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  2180. $pdf->Ln(3);
  2181. }
  2182. // 备注
  2183. if (!empty($script['remark'])) {
  2184. $pdf->SetFont('dejavusans', 'B', 14);
  2185. $pdf->Cell(0, 10, '备注', 0, 1);
  2186. $pdf->SetFont('dejavusans', '', 12);
  2187. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  2188. $pdf->Ln(3);
  2189. }
  2190. // 角色列表
  2191. if (!empty($script['roles']) && is_array($script['roles'])) {
  2192. $pdf->SetFont('dejavusans', 'B', 14);
  2193. $pdf->Cell(0, 10, '角色列表', 0, 1);
  2194. $pdf->SetFont('dejavusans', '', 12);
  2195. foreach ($script['roles'] as $index => $role) {
  2196. if (is_array($role) || is_object($role)) {
  2197. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  2198. } else {
  2199. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  2200. }
  2201. }
  2202. $pdf->Ln(3);
  2203. }
  2204. // 角色关系
  2205. if (!empty($script['role_relationship'])) {
  2206. $pdf->SetFont('dejavusans', 'B', 14);
  2207. $pdf->Cell(0, 10, '角色关系', 0, 1);
  2208. $pdf->SetFont('dejavusans', '', 12);
  2209. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  2210. $pdf->Ln(3);
  2211. }
  2212. // 场景列表
  2213. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  2214. $pdf->SetFont('dejavusans', 'B', 14);
  2215. $pdf->Cell(0, 10, '场景列表', 0, 1);
  2216. $pdf->SetFont('dejavusans', '', 12);
  2217. foreach ($script['scenes'] as $index => $scene) {
  2218. if (is_array($scene) || is_object($scene)) {
  2219. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  2220. } else {
  2221. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  2222. }
  2223. }
  2224. $pdf->Ln(5);
  2225. }
  2226. // 分集内容
  2227. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  2228. $pdf->SetFont('dejavusans', 'B', 16);
  2229. $pdf->Cell(0, 12, '分集内容', 0, 1);
  2230. $pdf->Ln(3);
  2231. foreach ($script['episodes'] as $episode) {
  2232. // 检查是否需要新页面
  2233. if ($pdf->GetY() > 250) {
  2234. $pdf->AddPage();
  2235. }
  2236. $pdf->SetFont('dejavusans', 'B', 14);
  2237. $episodeTitle = '第' . $episode['episode_number'] . '集';
  2238. if (!empty($episode['title'])) {
  2239. $episodeTitle .= ':' . $episode['title'];
  2240. }
  2241. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  2242. // 处理分段内容
  2243. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  2244. $pdf->SetFont('dejavusans', '', 12);
  2245. foreach ($episode['segments'] as $segment) {
  2246. if (!empty($segment['segment_content'])) {
  2247. // 如果有分段编号,显示分段标题
  2248. if (!empty($segment['segment_number'])) {
  2249. $pdf->SetFont('dejavusans', 'B', 12);
  2250. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  2251. $pdf->SetFont('dejavusans', '', 12);
  2252. }
  2253. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  2254. $pdf->Ln(2);
  2255. }
  2256. }
  2257. }
  2258. $pdf->Ln(5);
  2259. }
  2260. }
  2261. }
  2262. /**
  2263. * 构建剧本文本内容
  2264. */
  2265. private function buildScriptContent($script) {
  2266. $content = '';
  2267. $groups = $script['group'];
  2268. $groups = (array)$groups;
  2269. foreach ($groups as $group) {
  2270. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  2271. // 剧本基本信息
  2272. if (!empty($group['intro'])) {
  2273. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  2274. }
  2275. if (!empty($group['highlights'])) {
  2276. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  2277. }
  2278. if (!empty($group['role_relationship'])) {
  2279. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  2280. }
  2281. if (!empty($group['core_contradiction'])) {
  2282. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  2283. }
  2284. if (!empty($group['roles']) && is_array($group['roles'])) {
  2285. $content .= "###主体列表\n";
  2286. foreach ($group['roles'] as $role) {
  2287. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  2288. }
  2289. $content .= "\n\n";
  2290. }
  2291. if (!empty($group['art_style'])) {
  2292. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  2293. }
  2294. // 场景信息
  2295. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  2296. $content .= "###场景列表\n";
  2297. foreach ($group['scenes'] as $scene) {
  2298. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  2299. }
  2300. $content .= "\n\n";
  2301. }
  2302. // 分集内容
  2303. if (!empty($group['episode_content'])) {
  2304. $content .= "###分集剧本\n";
  2305. $content .= $group['episode_content'];
  2306. // foreach ($script['episodes'] as $episode) {
  2307. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  2308. // // if (!empty($episode['episode_name'])) {
  2309. // // $content .= ":" . $episode['episode_name'];
  2310. // // }
  2311. // // $content .= "\n";
  2312. // $content .= $episode['episode_content'] . "\n\n";
  2313. // }
  2314. }
  2315. }
  2316. return $content;
  2317. }
  2318. /**
  2319. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2320. *
  2321. * @param array $data 包含以下参数:
  2322. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2323. * - question: 用户问题(可选)
  2324. * - model: 使用的模型(r1 或 v3,默认 v3)
  2325. * @return \Generator 返回生成器,用于流式输出
  2326. */
  2327. public function addChat($data) {
  2328. $uid = Site::getUid();
  2329. $anime_id = getProp($data, 'anime_id');
  2330. if (!$anime_id) Utils::throwError('20003:请选择对话');
  2331. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  2332. if (!$anime) Utils::throwError('20003:对话不存在');
  2333. $file = getProp($data, 'file');
  2334. $content = getProp($data, 'content', '');
  2335. $bid = getProp($data, 'bid', 0);
  2336. $script_id = getProp($data, 'script_id', 0);
  2337. $prompt = getProp($data, 'prompt');
  2338. $user_anime_name = getProp($anime, 'anime_name');
  2339. // 处理文本模型
  2340. $model = getProp($data, 'model');
  2341. if (!$model) {
  2342. // 用户没有输入,从anime表获取
  2343. $model = getProp($anime, 'model');
  2344. if (!$model) {
  2345. // anime表也没有,使用默认值
  2346. $model = 'doubao-seed-2-0-mini-260215';
  2347. }
  2348. }
  2349. // 验证模型是否在可用模型表中
  2350. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2351. $model = 'doubao-seed-2-0-mini-260215';
  2352. }
  2353. $is_multi = getProp($anime, 'is_multi');
  2354. $is_single = (int)$is_multi !== 1;
  2355. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n本次修改要求如下:\n{$prompt}" : "请根据实例格式完成剧本大纲\n本次修改要求如下:\n{$prompt}");
  2356. // if (!$file && !$content && !$bid) {
  2357. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2358. // }
  2359. // 提取文件内容
  2360. if ($file) {
  2361. $content = $this->extractFileContent($file);
  2362. if (!$content) {
  2363. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2364. }
  2365. } elseif ($script_id) {
  2366. $content = $this->getContentByScriptId($script_id);
  2367. if (!$content) {
  2368. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  2369. }
  2370. } elseif ($bid) {
  2371. $content = $this->getContentByBid($bid);
  2372. if (!$content) {
  2373. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2374. }
  2375. } elseif ($content) {
  2376. $content = filterContent($content);
  2377. } else {
  2378. $content = getProp($anime, 'content');
  2379. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  2380. $need_generate_content = true;
  2381. }
  2382. }
  2383. // 美术风格
  2384. $input_art_style = getProp($data, 'art_style');
  2385. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  2386. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  2387. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  2388. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  2389. 中年女:邻居阿姨
  2390. 老年男:幽默大爷
  2391. 老年女:婆婆
  2392. 萌娃:奶气萌娃";
  2393. // 判断是否需要生成原文内容
  2394. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  2395. // 如果需要生成原文内容,添加额外的要求
  2396. $content_generation_requirement = $need_generate_content
  2397. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  2398. : "";
  2399. // 美术风格
  2400. if (!$mappedArtStyle) {
  2401. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  2402. }else {
  2403. $mappedArtStyle_prompt = "美术风格强制设置如下:\n基础画风风格词: {$input_art_style}\n{$mappedArtStyle}>(原样输出,不得更改任何内容)\n";
  2404. }
  2405. $systemPrompt = $is_single
  2406. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  2407. 强制要求:
  2408. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2409. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2410. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  2411. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  2412. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  2413. 普通要求:
  2414. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  2415. 2.{$mappedArtStyle_prompt}
  2416. 2.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如角色-少年、角色-青年、角色-中年、角色-老年这种情况,不得出现角色-愤怒、角色-隐忍、角色-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细
  2417. 2.1<主体列表>的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  2418. 3.2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述
  2419. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  2420. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  2421. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  2422. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  2423. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  2424. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  2425. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)。
  2426. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  2427. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  2428. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  2429. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  2430. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  2431. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  2432. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  2433. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  2434. 示例如下:\n
  2435. ###剧本名:西昆仑
  2436. ###故事梗概
  2437. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2438. ###剧本亮点
  2439. 亮点1:绝境奇药,生死一线
  2440. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2441. 亮点2:结拜兄妹,化解尴尬
  2442. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2443. 亮点3:纤发夺命,情愫暗涌
  2444. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2445. ###人物关系
  2446. 阿雪与梁萧之间存在兄妹之情。
  2447. ###核心矛盾
  2448. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2449. ###主体列表
  2450. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2451. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  2452. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2453. 阴阳球:天地异宝,能化生精气,救人于危难。
  2454. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2455. ###美术风格
  2456. 基础画风风格词:厚涂古风
  2457. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2458. ###场景列表
  2459. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  2460. ###分镜剧本
  2461. ##第1幕:徐家老旧厨房 白天 室内
  2462. 分镜1
  2463. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  2464. 场景:徐家老旧厨房
  2465. 构图设计:全景,低角度仰视
  2466. 运镜调度:手持拍摄
  2467. 配音角色:旁白
  2468. 出镜角色:许芸-校服装、徐母
  2469. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  2470. 画面类型:普通画面
  2471. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  2472. 分镜2
  2473. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  2474. 场景:徐家老旧厨房
  2475. 构图设计:近景,徐母面部特写
  2476. 运镜调度:固定镜头
  2477. 配音角色:徐母
  2478. 出镜角色:徐母
  2479. 台词内容:问我夜不归宿死哪儿去了。
  2480. 画面类型:对口型
  2481. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  2482. ##第2幕:徐家简陋客厅 黄昏 室内
  2483. 分镜3
  2484. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  2485. 场景:徐家简陋客厅
  2486. 构图设计:全景,景深虚化
  2487. 运镜调度:固定镜头
  2488. 配音角色:旁白
  2489. 出镜角色:无
  2490. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  2491. 画面类型:普通画面
  2492. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  2493. 分镜4
  2494. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  2495. 场景:徐家简陋客厅
  2496. 构图设计:特写,火车票
  2497. 运镜调度:固定镜头
  2498. 配音角色:旁白
  2499. 出镜角色:无
  2500. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  2501. 画面类型:普通画面
  2502. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  2503. "
  2504. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  2505. 强制要求:\n
  2506. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2507. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  2508. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  2509. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  2510. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  2511. 普通要求:\n
  2512. 1.剧本名(必须生成)必须与文档内容高度相关
  2513. 2.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细
  2514. 3.{$mappedArtStyle_prompt}
  2515. 4.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n\n
  2516. 示例如下:\n
  2517. ###剧本名:西昆仑
  2518. ###故事梗概
  2519. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2520. ###剧本亮点
  2521. 亮点1:绝境奇药,生死一线
  2522. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2523. 亮点2:结拜兄妹,化解尴尬
  2524. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2525. 亮点3:纤发夺命,情愫暗涌
  2526. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2527. ###人物关系
  2528. 阿雪与梁萧之间存在兄妹之情。
  2529. ###核心矛盾
  2530. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2531. ###主体列表
  2532. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2533. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  2534. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2535. 阴阳球:天地异宝,能化生精气,救人于危难。
  2536. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2537. ###美术风格
  2538. 基础画风风格词:厚涂古风
  2539. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2540. ###场景列表
  2541. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。";
  2542. // 构建消息
  2543. $messages = [
  2544. [
  2545. 'role' => 'system',
  2546. 'content' => $systemPrompt
  2547. ],
  2548. [
  2549. 'role' => 'user',
  2550. 'content' => "以下是文档内容:
  2551. {$content}
  2552. 用户问题:
  2553. {$question}"
  2554. ]
  2555. ];
  2556. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2557. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2558. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2559. if ($model === 'deepseek-chat') {
  2560. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2561. $model = 'deepseek-v4-flash';
  2562. $thinkingMode = 'disabled';
  2563. } elseif ($model === 'deepseek-reasoner') {
  2564. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2565. $model = 'deepseek-v4-flash';
  2566. $thinkingMode = 'enabled';
  2567. }
  2568. $post_data = [
  2569. 'model' => $model,
  2570. 'messages' => $messages,
  2571. // 'max_tokens' => 8192,
  2572. 'temperature' => 0.7,
  2573. 'frequency_penalty' => 0,
  2574. 'presence_penalty' => 0,
  2575. 'response_format' => ['type' => 'text'],
  2576. 'thinking' => ['type'=>$thinkingMode],
  2577. 'stream' => true // 启用流式输出
  2578. ];
  2579. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2580. // 根据模型类型选择调用方法
  2581. $fullContent = '';
  2582. $fullReasoningContent = '';
  2583. $usage = [];
  2584. try {
  2585. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2586. // DeepSeek 官方模型使用 DeepSeek API
  2587. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2588. } else {
  2589. // 其他模型使用火山引擎API
  2590. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2591. }
  2592. // 验证返回值类型
  2593. if (!is_iterable($streamGenerator)) {
  2594. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  2595. dLog('deepseek')->error('addChat流式生成器无效', [
  2596. 'generator_type' => $errorType,
  2597. 'model' => $model,
  2598. 'anime_id' => $anime_id
  2599. ]);
  2600. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  2601. 'type' => $errorType,
  2602. 'model' => $model
  2603. ]);
  2604. yield [
  2605. 'type' => 'error',
  2606. 'script' => [],
  2607. 'episode' => [],
  2608. 'answer' => '',
  2609. 'reasoning' => '',
  2610. 'usage' => [],
  2611. 'error' => '接口返回数据异常,请重新请求'
  2612. ];
  2613. return;
  2614. }
  2615. // 处理流式输出
  2616. foreach ($streamGenerator as $chunk) {
  2617. if (isset($chunk['type'])) {
  2618. if ($chunk['type'] === 'done') {
  2619. // 最终结果
  2620. $fullContent = $chunk['full_content'];
  2621. $fullReasoningContent = $chunk['full_reasoning'];
  2622. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2623. } else {
  2624. // 逐块yield数据
  2625. yield $chunk;
  2626. }
  2627. }
  2628. }
  2629. } catch (\Exception $e) {
  2630. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  2631. 'model' => $model,
  2632. 'anime_id' => $anime_id,
  2633. 'trace' => $e->getTraceAsString()
  2634. ]);
  2635. logDB('deepseek', 'error', 'addChat流式处理失败', [
  2636. 'error' => $e->getMessage(),
  2637. 'model' => $model
  2638. ]);
  2639. yield [
  2640. 'type' => 'error',
  2641. 'script' => [],
  2642. 'episode' => [],
  2643. 'answer' => '',
  2644. 'reasoning' => '',
  2645. 'usage' => [],
  2646. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  2647. ];
  2648. return;
  2649. }
  2650. dLog('deepseek')->info('完整内容: '.$fullContent);
  2651. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  2652. // 处理完整内容并返回最终结果
  2653. $script_arr = [];
  2654. if ($fullContent) {
  2655. $script_arr = handleScriptContent($fullContent);
  2656. dLog('deepseek')->info('解析内容', $script_arr);
  2657. logDB('deepseek', 'info', '解析内容', $script_arr);
  2658. }
  2659. if (empty($script_arr['roles'])) {
  2660. // 未生成剧本相关内容,保存对话记录并返回提示
  2661. dLog('deepseek')->info('未生成剧本相关的内容');
  2662. try {
  2663. DB::beginTransaction();
  2664. $now = date('Y-m-d H:i:s');
  2665. // 保存对话记录
  2666. $records = [
  2667. [
  2668. 'uid' => $uid,
  2669. 'anime_id' => $anime_id,
  2670. 'sequence' => 0,
  2671. 'role' => 'user',
  2672. 'content' => $prompt,
  2673. 'created_at' => $now,
  2674. 'updated_at' => $now
  2675. ],
  2676. [
  2677. 'uid' => $uid,
  2678. 'anime_id' => $anime_id,
  2679. 'sequence' => 0,
  2680. 'role' => 'assistant',
  2681. // 'content' => $fullContent,
  2682. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  2683. 'created_at' => $now,
  2684. 'updated_at' => $now
  2685. ]
  2686. ];
  2687. DB::table('mp_anime_records')->insert($records);
  2688. DB::commit();
  2689. } catch (\Exception $e) {
  2690. DB::rollBack();
  2691. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  2692. }
  2693. yield [
  2694. 'type' => 'done',
  2695. 'script' => [],
  2696. 'episode' => [],
  2697. 'answer' => $fullContent,
  2698. 'reasoning' => $fullReasoningContent,
  2699. 'usage' => $usage,
  2700. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  2701. ];
  2702. return;
  2703. }
  2704. // 如果需要生成原文内容,从script_arr中提取
  2705. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  2706. $content = $script_arr['content'];
  2707. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  2708. if (!$content) {
  2709. yield [
  2710. 'type' => 'done',
  2711. 'script' => [],
  2712. 'episode' => [],
  2713. 'answer' => $fullContent,
  2714. 'reasoning' => $fullReasoningContent,
  2715. 'usage' => $usage,
  2716. 'error' => '未生成剧本内容,请调整提示词再试'
  2717. ];
  2718. return;
  2719. }
  2720. }
  2721. // 替换美术风格
  2722. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  2723. if ($mappedArtStyle !== '') {
  2724. $script_arr['art_style'] = $mappedArtStyle;
  2725. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  2726. }
  2727. // 新建动漫
  2728. if ($user_anime_name == '新剧本策划') {
  2729. $anime_name = getProp($script_arr, 'script_name');
  2730. // if (!$anime_name) {
  2731. // // 未识别到剧本名,保存对话记录并返回提示
  2732. // dLog('deepseek')->info('未能识别到剧本名称');
  2733. // try {
  2734. // DB::beginTransaction();
  2735. // $now = date('Y-m-d H:i:s');
  2736. // // 保存对话记录
  2737. // $records = [
  2738. // [
  2739. // 'uid' => $uid,
  2740. // 'anime_id' => $anime_id,
  2741. // 'sequence' => 0,
  2742. // 'role' => 'user',
  2743. // 'content' => $prompt,
  2744. // 'created_at' => $now,
  2745. // 'updated_at' => $now
  2746. // ],
  2747. // [
  2748. // 'uid' => $uid,
  2749. // 'anime_id' => $anime_id,
  2750. // 'sequence' => 0,
  2751. // 'role' => 'assistant',
  2752. // 'content' => '未能生成剧本名称,请重试',
  2753. // 'created_at' => $now,
  2754. // 'updated_at' => $now
  2755. // ]
  2756. // ];
  2757. // DB::table('mp_anime_records')->insert($records);
  2758. // DB::commit();
  2759. // } catch (\Exception $e) {
  2760. // DB::rollBack();
  2761. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  2762. // }
  2763. // yield [
  2764. // 'type' => 'done',
  2765. // 'script' => [],
  2766. // 'episode' => [],
  2767. // 'answer' => $fullContent,
  2768. // 'reasoning' => $fullReasoningContent,
  2769. // 'usage' => $usage,
  2770. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  2771. // ];
  2772. // return;
  2773. // }
  2774. // 确认对话名称唯一性
  2775. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  2776. $anime_name = $anime_name . '_' . date('YmdHis');
  2777. }
  2778. }else {
  2779. $anime_name = $user_anime_name;
  2780. }
  2781. $table_data = [
  2782. 'user_id' => $uid,
  2783. 'anime_name' => $anime_name,
  2784. 'model' => $model,
  2785. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2786. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2787. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2788. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2789. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  2790. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2791. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  2792. 'status' => '解析完成',
  2793. 'content' => $content,
  2794. 'is_multi' => $is_multi,
  2795. 'generate_status' => '待执行',
  2796. 'updated_at' => date('Y-m-d H:i:s')
  2797. ];
  2798. $single_episode = [];
  2799. try {
  2800. DB::beginTransaction();
  2801. $now = date('Y-m-d H:i:s');
  2802. // 更新动漫大纲
  2803. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  2804. if (!$boolen) {
  2805. dLog('deepseek')->info('动漫保存失败', $table_data);
  2806. Utils::throwError('20003:动漫保存失败');
  2807. }
  2808. // 保存对话记录
  2809. $records = [
  2810. [
  2811. 'uid' => $uid,
  2812. 'anime_id' => $anime_id,
  2813. 'sequence' => 0,
  2814. 'role' => 'user',
  2815. 'content' => $prompt,
  2816. 'created_at' => date('Y-m-d H:i:s'),
  2817. 'updated_at' => date('Y-m-d H:i:s')
  2818. ],
  2819. [
  2820. 'uid' => $uid,
  2821. 'anime_id' => $anime_id,
  2822. 'sequence' => 0,
  2823. 'role' => 'assistant',
  2824. 'content' => $fullContent,
  2825. 'created_at' => date('Y-m-d H:i:s'),
  2826. 'updated_at' => date('Y-m-d H:i:s')
  2827. ]
  2828. ];
  2829. // 保存对话记录
  2830. $boolen3 = DB::table('mp_anime_records')->insert($records);
  2831. if (!$boolen3) {
  2832. Utils::throwError('20003:对话记录保存失败');
  2833. }
  2834. if ($is_single) {
  2835. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  2836. if (empty($episode_arr['acts'])) {
  2837. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  2838. }
  2839. $saveResult = $this->saveEpisodeVersionData(
  2840. $anime_id,
  2841. 1,
  2842. $episode_arr,
  2843. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  2844. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  2845. null,
  2846. null,
  2847. false,
  2848. $content,
  2849. $now
  2850. );
  2851. $single_episode = $saveResult['episode'];
  2852. $episode_id = $saveResult['episode_id'];
  2853. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  2854. 'roles' => json_encode($saveResult['merged_roles'], 256),
  2855. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  2856. 'updated_at' => $now
  2857. ]);
  2858. if ($boolen5 === false) {
  2859. Utils::throwError('20003:单剧集主表资源同步失败');
  2860. }
  2861. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  2862. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  2863. $episode_record_content = '确认分镜大纲';
  2864. if ($content !== '') {
  2865. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  2866. }
  2867. $episode_records = [
  2868. [
  2869. 'uid' => $uid,
  2870. 'anime_id' => $anime_id,
  2871. 'role' => 'user',
  2872. 'content' => $episode_record_content,
  2873. 'sequence' => 1,
  2874. 'episode_id' => $episode_id,
  2875. 'created_at' => $now,
  2876. 'updated_at' => $now
  2877. ],
  2878. [
  2879. 'uid' => $uid,
  2880. 'anime_id' => $anime_id,
  2881. 'role' => 'assistant',
  2882. 'content' => $fullContent,
  2883. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  2884. 'sequence' => 1,
  2885. 'episode_id' => $episode_id,
  2886. 'created_at' => $now,
  2887. 'updated_at' => $now
  2888. ]
  2889. ];
  2890. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  2891. if (!$boolen4) {
  2892. Utils::throwError('20003:单剧集分镜记录保存失败');
  2893. }
  2894. }
  2895. }catch (\Exception $e) {
  2896. DB::rollBack();
  2897. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  2898. yield [
  2899. 'type' => 'done',
  2900. 'answer' => $fullContent,
  2901. 'reasoning' => $fullReasoningContent,
  2902. 'usage' => $usage,
  2903. 'error' => $e->getMessage(),
  2904. ];
  2905. return;
  2906. }
  2907. DB::commit();
  2908. dLog('deepseek')->info('保存完毕');
  2909. if ($is_single && !empty($single_episode)) {
  2910. $this->batchSetGlobalRoleImg([
  2911. 'anime_id' => $anime_id,
  2912. ]);
  2913. $this->batchSetGlobalSceneImg([
  2914. 'anime_id' => $anime_id,
  2915. ]);
  2916. // 将全局角色和场景的task_id、task_status和url继承给当前分集
  2917. $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  2918. }
  2919. $table_data['anime_id'] = $anime_id;
  2920. $table_data['roles'] = json_decode($table_data['roles'], true);
  2921. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  2922. // $table_data['episodes'] = $script_arr['episodes'];
  2923. unset($table_data['created_at']);
  2924. unset($table_data['updated_at']);
  2925. unset($table_data['status']);
  2926. dLog('deepseek')->info('开始返回');
  2927. yield [
  2928. 'type' => 'done',
  2929. 'script' => $table_data,
  2930. 'episode' => $single_episode,
  2931. 'answer' => $fullContent,
  2932. 'reasoning' => $fullReasoningContent,
  2933. 'usage' => $usage
  2934. ];
  2935. }
  2936. public function reGenerateAnime($data) {
  2937. $uid = Site::getUid();
  2938. $file = getProp($data, 'file');
  2939. $content = getProp($data, 'content', '');
  2940. $bid = getProp($data, 'bid', 0);
  2941. $script_id = getProp($data, 'script_id', 0);
  2942. $anime_id = getProp($data, 'anime_id');
  2943. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  2944. if (!$anime) {
  2945. Utils::throwError('20003:该对话不存在');
  2946. }
  2947. $user_anime_name = getProp($anime, 'anime_name');
  2948. $prompt = getProp($data, 'prompt');
  2949. // 处理文本模型
  2950. $model = getProp($data, 'model');
  2951. if (!$model) {
  2952. // 用户没有输入,从anime表获取
  2953. $model = getProp($anime, 'model');
  2954. if (!$model) {
  2955. // anime表也没有,使用默认值
  2956. $model = 'doubao-seed-2-0-mini-260215';
  2957. }
  2958. }
  2959. // 验证模型是否在可用模型表中
  2960. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2961. $model = 'doubao-seed-2-0-mini-260215';
  2962. }
  2963. $is_multi = getProp($anime, 'is_multi', 1);
  2964. $is_single = (int)$is_multi !== 1;
  2965. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  2966. if ($is_single) {
  2967. $episode_exists = DB::table('mp_anime_episodes')
  2968. ->where('anime_id', $anime_id)
  2969. ->where('sequence', 1)
  2970. ->exists();
  2971. if ($episode_exists) {
  2972. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  2973. }
  2974. }
  2975. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n本次修改要求如下:\n{$prompt}" : "请根据实例格式完成剧本大纲\n本次修改要求如下:\n{$prompt}");
  2976. // 提取文件内容
  2977. if ($file) {
  2978. $content = $this->extractFileContent($file);
  2979. if (!$content) {
  2980. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2981. }
  2982. } elseif ($script_id) {
  2983. $content = $this->getContentByScriptId($script_id);
  2984. if (!$content) {
  2985. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  2986. }
  2987. } elseif ($bid) {
  2988. $content = $this->getContentByBid($bid);
  2989. if (!$content) {
  2990. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2991. }
  2992. } elseif ($content) {
  2993. $content = filterContent($content);
  2994. }else {
  2995. $content = filterContent(getProp($anime, 'content'));
  2996. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  2997. $need_generate_content = true;
  2998. }
  2999. }
  3000. // 判断是否需要生成原文内容
  3001. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3002. // 如果需要生成原文内容,添加额外的要求
  3003. $content_generation_requirement = $need_generate_content
  3004. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3005. : "";
  3006. // 美术风格
  3007. $input_art_style = getProp($data, 'art_style');
  3008. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3009. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3010. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3011. 中年女:邻居阿姨
  3012. 老年男:幽默大爷
  3013. 老年女:婆婆
  3014. 萌娃:奶气萌娃";
  3015. $system_message = ['role'=>'system', 'content'=>$is_single
  3016. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3017. 强制要求:
  3018. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3019. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3020. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3021. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3022. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3023. 普通要求:
  3024. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3025. 2.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如角色-少年、角色-青年、角色-中年、角色-老年这种情况,不得出现角色-愤怒、角色-隐忍、角色-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细
  3026. 2.1<主体列表>的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3027. 3.2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述
  3028. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3029. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3030. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3031. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3032. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3033. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3034. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)。
  3035. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3036. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3037. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3038. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3039. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3040. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3041. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3042. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3043. 示例如下:\n
  3044. ###剧本名:西昆仑
  3045. ###故事梗概
  3046. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3047. ###剧本亮点
  3048. 亮点1:绝境奇药,生死一线
  3049. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3050. 亮点2:结拜兄妹,化解尴尬
  3051. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3052. 亮点3:纤发夺命,情愫暗涌
  3053. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3054. ###人物关系
  3055. 阿雪与梁萧之间存在兄妹之情。
  3056. ###核心矛盾
  3057. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3058. ###主体列表
  3059. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  3060. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  3061. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  3062. 阴阳球:天地异宝,能化生精气,救人于危难。
  3063. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  3064. ###美术风格
  3065. 基础画风风格词:厚涂古风
  3066. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3067. ###场景列表
  3068. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  3069. ###分镜剧本
  3070. ##第1幕:徐家老旧厨房 白天 室内
  3071. 分镜1
  3072. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3073. 场景:徐家老旧厨房
  3074. 构图设计:全景,低角度仰视
  3075. 运镜调度:手持拍摄
  3076. 配音角色:旁白
  3077. 出镜角色:许芸-校服装、徐母
  3078. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3079. 画面类型:普通画面
  3080. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3081. 分镜2
  3082. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3083. 场景:徐家老旧厨房
  3084. 构图设计:近景,徐母面部特写
  3085. 运镜调度:固定镜头
  3086. 配音角色:徐母
  3087. 出镜角色:徐母
  3088. 台词内容:问我夜不归宿死哪儿去了。
  3089. 画面类型:对口型
  3090. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3091. ##第2幕:徐家简陋客厅 黄昏 室内
  3092. 分镜3
  3093. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3094. 场景:徐家简陋客厅
  3095. 构图设计:全景,景深虚化
  3096. 运镜调度:固定镜头
  3097. 配音角色:旁白
  3098. 出镜角色:无
  3099. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3100. 画面类型:普通画面
  3101. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3102. 分镜4
  3103. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3104. 场景:徐家简陋客厅
  3105. 构图设计:特写,火车票
  3106. 运镜调度:固定镜头
  3107. 配音角色:旁白
  3108. 出镜角色:无
  3109. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3110. 画面类型:普通画面
  3111. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  3112. "
  3113. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3114. 强制要求:\n
  3115. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3116. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3117. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3118. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3119. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3120. 普通要求:\n
  3121. 1.剧本名(必须生成)必须与文档内容高度相关
  3122. 2.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  3123. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n\n
  3124. 示例如下:\n
  3125. ###剧本名:西昆仑
  3126. ###故事梗概
  3127. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3128. ###剧本亮点
  3129. 亮点1:绝境奇药,生死一线
  3130. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3131. 亮点2:结拜兄妹,化解尴尬
  3132. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3133. 亮点3:纤发夺命,情愫暗涌
  3134. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3135. ###人物关系
  3136. 阿雪与梁萧之间存在兄妹之情。
  3137. ###核心矛盾
  3138. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3139. ###主体列表
  3140. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  3141. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  3142. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  3143. 阴阳球:天地异宝,能化生精气,救人于危难。
  3144. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  3145. ###美术风格
  3146. 基础画风风格词:厚涂古风
  3147. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3148. ###场景列表
  3149. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"];
  3150. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  3151. $episode_count = $this->extractEpisodeNumber($prompt);
  3152. if ((int)getProp($anime, 'is_multi') !== 1) {
  3153. yield [
  3154. 'type' => 'done',
  3155. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  3156. 'reasoning' => '',
  3157. 'usage' => []
  3158. ];
  3159. return;
  3160. }
  3161. if ($episode_count) {
  3162. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  3163. $system_message = [
  3164. 'role' => 'system',
  3165. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3166. 强制要求:\n
  3167. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3168. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3169. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3170. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3171. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3172. 普通要求:\n
  3173. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  3174. 2.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述\n
  3175. 3.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  3176. 示例如下:\n
  3177. ###剧本名:西昆仑
  3178. ###故事梗概
  3179. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3180. ###剧本亮点
  3181. 亮点1:绝境奇药,生死一线
  3182. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3183. 亮点2:结拜兄妹,化解尴尬
  3184. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3185. 亮点3:纤发夺命,情愫暗涌
  3186. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3187. ###人物关系
  3188. 阿雪与梁萧之间存在兄妹之情。
  3189. ###核心矛盾
  3190. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3191. ###主体列表
  3192. 阿雪-病重:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  3193. 阿雪-羞涩:经“阴阳球”救治后逐渐恢复,脸颊泛起红晕,眼神娇羞,情愫暗生。
  3194. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  3195. 阴阳球:天地异宝,能化生精气,救人于危难。
  3196. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  3197. ###美术风格
  3198. 基础画风风格词:厚涂古风
  3199. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3200. ###场景列表
  3201. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  3202. ###分集详细内容
  3203. ##第1章 重生
  3204. 我重生了。
  3205. 源于一个男人偏执的暗恋。
  3206. ##第2章 相救
  3207. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  3208. 我眼睛扫向站在锅炉后的卞大伟。"
  3209. ];
  3210. // 构建消息
  3211. $messages = [
  3212. $system_message,
  3213. [
  3214. 'role' => 'user',
  3215. 'content' => "以下是文档内容:
  3216. {$content}
  3217. 用户问题:
  3218. {$question}"
  3219. ]
  3220. ];
  3221. }else {
  3222. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  3223. // 构建消息
  3224. $messages = [
  3225. $system_message,
  3226. [
  3227. 'role' => 'user',
  3228. 'content' => "以下是文档内容:
  3229. {$content}
  3230. 用户问题:
  3231. {$question}"
  3232. ]
  3233. ];
  3234. }else {
  3235. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  3236. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  3237. return (array)$value;
  3238. })->toArray();
  3239. array_unshift($messages, $system_message);
  3240. $messages[] = [
  3241. 'role' => 'user',
  3242. 'content' => $prompt
  3243. ];
  3244. }
  3245. }
  3246. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3247. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3248. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3249. if ($model === 'deepseek-chat') {
  3250. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3251. $model = 'deepseek-v4-flash';
  3252. $thinkingMode = 'disabled';
  3253. } elseif ($model === 'deepseek-reasoner') {
  3254. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3255. $model = 'deepseek-v4-flash';
  3256. $thinkingMode = 'enabled';
  3257. }
  3258. $post_data = [
  3259. 'model' => $model,
  3260. 'messages' => $messages,
  3261. // 'max_tokens' => 8192,
  3262. 'temperature' => 0.7,
  3263. 'frequency_penalty' => 0,
  3264. 'presence_penalty' => 0,
  3265. 'response_format' => ['type' => 'text'],
  3266. 'thinking' => ['type' => $thinkingMode],
  3267. 'stream' => true // 启用流式输出
  3268. ];
  3269. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3270. // 根据模型类型选择调用方法
  3271. $fullContent = '';
  3272. $fullReasoningContent = '';
  3273. $usage = [];
  3274. // dd($post_data);
  3275. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  3276. try {
  3277. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3278. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3279. } else {
  3280. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3281. }
  3282. // 验证返回值类型
  3283. if (!is_iterable($streamGenerator)) {
  3284. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  3285. dLog('deepseek')->error('方法名流式生成器无效', [
  3286. 'generator_type' => $errorType,
  3287. 'model' => $model,
  3288. // 添加其他上下文信息
  3289. ]);
  3290. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  3291. 'type' => $errorType,
  3292. 'model' => $model
  3293. ]);
  3294. yield [
  3295. 'type' => 'error',
  3296. // 根据方法返回相应的空数据结构
  3297. 'answer' => '',
  3298. 'reasoning' => '',
  3299. 'usage' => [],
  3300. 'error' => '接口返回数据异常,请重新请求'
  3301. ];
  3302. return;
  3303. }
  3304. // 处理流式输出
  3305. foreach ($streamGenerator as $chunk) {
  3306. if (isset($chunk['type'])) {
  3307. if ($chunk['type'] === 'done') {
  3308. $fullContent = $chunk['full_content'];
  3309. $fullReasoningContent = $chunk['full_reasoning'];
  3310. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3311. } else {
  3312. yield $chunk;
  3313. }
  3314. }
  3315. }
  3316. } catch (\Exception $e) {
  3317. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  3318. 'model' => $model,
  3319. 'trace' => $e->getTraceAsString()
  3320. ]);
  3321. logDB('deepseek', 'error', '方法名流式处理失败', [
  3322. 'error' => $e->getMessage(),
  3323. 'model' => $model
  3324. ]);
  3325. yield [
  3326. 'type' => 'error',
  3327. // 根据方法返回相应的空数据结构
  3328. 'answer' => '',
  3329. 'reasoning' => '',
  3330. 'usage' => [],
  3331. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  3332. ];
  3333. return;
  3334. }
  3335. dLog('deepseek')->info('完整内容: '.$fullContent);
  3336. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3337. // 处理完整内容并返回最终结果
  3338. $script_arr = [];
  3339. if ($fullContent) {
  3340. $script_arr = handleScriptContent($fullContent);
  3341. dLog('deepseek')->info('解析内容', $script_arr);
  3342. logDB('deepseek', 'info', '解析内容', $script_arr);
  3343. }
  3344. if (empty($script_arr['roles'])) {
  3345. // 未生成剧本相关内容,保存对话记录并返回提示
  3346. dLog('deepseek')->info('未生成剧本相关的内容');
  3347. try {
  3348. $now = date('Y-m-d H:i:s');
  3349. // 保存对话记录
  3350. $records = [
  3351. [
  3352. 'uid' => $uid,
  3353. 'anime_id' => $anime_id,
  3354. 'sequence' => 0,
  3355. 'role' => 'user',
  3356. 'content' => $prompt,
  3357. 'created_at' => $now,
  3358. 'updated_at' => $now
  3359. ],
  3360. [
  3361. 'uid' => $uid,
  3362. 'anime_id' => $anime_id,
  3363. 'sequence' => 0,
  3364. 'role' => 'assistant',
  3365. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  3366. 'created_at' => $now,
  3367. 'updated_at' => $now
  3368. ]
  3369. ];
  3370. DB::table('mp_anime_records')->insert($records);
  3371. } catch (\Exception $e) {
  3372. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3373. }
  3374. yield [
  3375. 'type' => 'done',
  3376. 'script' => [],
  3377. 'episode' => [],
  3378. 'answer' => $fullContent,
  3379. 'reasoning' => $fullReasoningContent,
  3380. 'usage' => $usage,
  3381. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  3382. ];
  3383. return;
  3384. }
  3385. // 替换美术风格
  3386. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3387. if ($mappedArtStyle !== '') {
  3388. $script_arr['art_style'] = $mappedArtStyle;
  3389. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  3390. }
  3391. if ($user_anime_name != '新剧本策划') {
  3392. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  3393. // 确认对话名称唯一性
  3394. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  3395. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  3396. }
  3397. }else {
  3398. $anime_name = $user_anime_name;
  3399. }
  3400. $table_data = [
  3401. 'user_id' => $uid,
  3402. 'model' => $model,
  3403. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3404. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3405. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3406. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3407. 'roles' => isset($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '',
  3408. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3409. 'scenes' => isset($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '',
  3410. 'status' => '解析完成',
  3411. 'generate_status' => '待执行',
  3412. 'updated_at' => date('Y-m-d H:i:s')
  3413. ];
  3414. if ($anime_name) $table_data['anime_name'] = $anime_name;
  3415. // 如果是修改集数,则将content内容更新(会改变原文)
  3416. if (isset($episode_count) && $episode_count > 0) {
  3417. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  3418. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  3419. }else {
  3420. // 如果需要生成原文内容,从script_arr中提取
  3421. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  3422. $table_data['content'] = $script_arr['content'];
  3423. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  3424. if (!$content) {
  3425. yield [
  3426. 'type' => 'done',
  3427. 'script' => [],
  3428. 'episode' => [],
  3429. 'answer' => $fullContent,
  3430. 'reasoning' => $fullReasoningContent,
  3431. 'usage' => $usage,
  3432. 'error' => '未生成剧本内容,请调整提示词再试'
  3433. ];
  3434. return;
  3435. }
  3436. } else {
  3437. $chapters = $this->splitContent($content);
  3438. $chapter_count = count($chapters);
  3439. if ($chapter_count > 0) {
  3440. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  3441. }
  3442. }
  3443. }
  3444. $single_episode = [];
  3445. try {
  3446. DB::beginTransaction();
  3447. $now = date('Y-m-d H:i:s');
  3448. // 更新动漫大纲
  3449. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3450. if (!$boolen) {
  3451. dLog('deepseek')->info('对话修改失败', $table_data);
  3452. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  3453. Utils::throwError('20003:对话修改失败');
  3454. }
  3455. // 保存对话记录
  3456. $records = [
  3457. [
  3458. 'uid' => $uid,
  3459. 'anime_id' => $anime_id,
  3460. 'sequence' => 0,
  3461. 'role' => 'user',
  3462. 'content' => $prompt,
  3463. 'created_at' => $now,
  3464. 'updated_at' => $now
  3465. ],
  3466. [
  3467. 'uid' => $uid,
  3468. 'anime_id' => $anime_id,
  3469. 'sequence' => 0,
  3470. 'role' => 'assistant',
  3471. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3472. 'content' => $fullContent,
  3473. 'created_at' => $now,
  3474. 'updated_at' => $now
  3475. ]
  3476. ];
  3477. // 保存对话记录
  3478. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3479. if (!$boolen3) {
  3480. Utils::throwError('20003:对话记录保存失败');
  3481. }
  3482. // 单剧集模式:生成并保存剧集信息
  3483. if ($is_single) {
  3484. $anime_name = getProp($anime, 'anime_name', '未命名');
  3485. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3486. if (empty($episode_arr['acts'])) {
  3487. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3488. }
  3489. $saveResult = $this->saveEpisodeVersionData(
  3490. $anime_id,
  3491. 1,
  3492. $episode_arr,
  3493. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3494. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3495. null,
  3496. null,
  3497. false,
  3498. $content,
  3499. $now
  3500. );
  3501. $single_episode = $saveResult['episode'];
  3502. $episode_id = $saveResult['episode_id'];
  3503. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3504. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3505. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3506. 'updated_at' => $now
  3507. ]);
  3508. if ($boolen5 === false) {
  3509. Utils::throwError('20003:单剧集主表资源同步失败');
  3510. }
  3511. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3512. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3513. $episode_record_content = '确认分镜大纲';
  3514. if ($content !== '') {
  3515. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  3516. }
  3517. $episode_records = [
  3518. [
  3519. 'uid' => $uid,
  3520. 'anime_id' => $anime_id,
  3521. 'role' => 'user',
  3522. 'content' => $episode_record_content,
  3523. 'sequence' => 1,
  3524. 'episode_id' => $episode_id,
  3525. 'created_at' => $now,
  3526. 'updated_at' => $now
  3527. ],
  3528. [
  3529. 'uid' => $uid,
  3530. 'anime_id' => $anime_id,
  3531. 'role' => 'assistant',
  3532. 'content' => $fullContent,
  3533. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3534. 'sequence' => 1,
  3535. 'episode_id' => $episode_id,
  3536. 'created_at' => $now,
  3537. 'updated_at' => $now
  3538. ]
  3539. ];
  3540. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3541. if (!$boolen4) {
  3542. Utils::throwError('20003:单剧集分镜记录保存失败');
  3543. }
  3544. }
  3545. }catch (\Exception $e) {
  3546. DB::rollBack();
  3547. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  3548. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  3549. yield [
  3550. 'type' => 'done',
  3551. 'answer' => $fullContent,
  3552. 'reasoning' => $fullReasoningContent,
  3553. 'usage' => $usage,
  3554. 'error' => $e->getMessage(),
  3555. ];
  3556. return;
  3557. }
  3558. DB::commit();
  3559. dLog('deepseek')->info('保存完毕');
  3560. if ($is_single && !empty($single_episode)) {
  3561. $this->batchSetGlobalRoleImg([
  3562. 'anime_id' => $anime_id,
  3563. ]);
  3564. $this->batchSetGlobalSceneImg([
  3565. 'anime_id' => $anime_id,
  3566. ]);
  3567. // 将全局角色和场景的task_id、task_status和url继承给当前分集
  3568. $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  3569. }
  3570. $table_data['anime_id'] = $anime_id;
  3571. $table_data['roles'] = json_decode($table_data['roles'], true);
  3572. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  3573. unset($table_data['updated_at']);
  3574. unset($table_data['status']);
  3575. yield [
  3576. 'type' => 'done',
  3577. 'script' => $table_data,
  3578. 'episode' => $single_episode,
  3579. 'answer' => $fullContent,
  3580. 'reasoning' => $fullReasoningContent,
  3581. 'usage' => $usage
  3582. ];
  3583. }
  3584. public function chat($data) {
  3585. $uid = Site::getUid();
  3586. $anime_id = getProp($data, 'anime_id');
  3587. $file = getProp($data, 'file');
  3588. $content = getProp($data, 'content', '');
  3589. $bid = getProp($data, 'bid', 0);
  3590. $script_id = getProp($data, 'script_id', 0);
  3591. $episode_number = getProp($data, 'episode_number', 1);
  3592. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  3593. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3594. if (!$anime) Utils::throwError('20003:该对话不存在!');
  3595. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  3596. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  3597. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  3598. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  3599. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  3600. $roles = is_array($roles) ? $roles : [];
  3601. $scenes = is_array($scenes) ? $scenes : [];
  3602. // 转换主体列表和场景列表的格式
  3603. $roles_content = $this->buildEpisodeItemContent($roles, 'role');
  3604. $scenes_content = $this->buildEpisodeItemContent($scenes, 'scene');
  3605. // 获取音色列表
  3606. // $timbres = DB::table('mp_timbres')->select('timbre_name')->where('is_enabled', 1)->where('id', '<=', 15)->get()->map(function ($value) {
  3607. // $value = (array)$value;
  3608. // $value['timbre_name'] = str_replace('(多情感)', '', $value['timbre_name']);
  3609. // return $value;
  3610. // })->pluck('timbre_name')->toArray();
  3611. // $timbres_content = implode('、', $timbres);
  3612. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3613. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3614. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3615. 中年女:邻居阿姨
  3616. 老年男:幽默大爷
  3617. 老年女:婆婆
  3618. 萌娃:奶气萌娃";
  3619. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  3620. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  3621. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  3622. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  3623. // 提取文件内容
  3624. if ($file) {
  3625. $uploaded_content = $this->extractFileContent($file);
  3626. if (!$uploaded_content) {
  3627. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3628. }
  3629. } elseif ($script_id) {
  3630. $uploaded_content = $this->getContentByScriptId($script_id);
  3631. if (!$uploaded_content) {
  3632. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3633. }
  3634. } elseif ($bid) {
  3635. $uploaded_content = $this->getContentByBid($bid);
  3636. if (!$uploaded_content) {
  3637. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3638. }
  3639. } elseif ($content) {
  3640. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  3641. }
  3642. // elseif ($prompt) {
  3643. // $uploaded_content = filterContent($prompt);
  3644. // }
  3645. else {
  3646. $uploaded_content = '';
  3647. }
  3648. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  3649. $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3650. 强制要求:
  3651. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3652. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3653. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3654. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  3655. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3656. 普通要求:
  3657. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  3658. 2.<主体列表>必须在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个),不得自定义(需带上冒号后的具体描述):\n{$roles_content}。
  3659. 2.1如果分集内容中出现了<主体列表>中不存在的新主体,则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在主题列表中。
  3660. 2.2主体列表的音色必须在以下音色中($timbres_content)选择,需要角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3661. 3.<场景列表>必须在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,除非出现<场景列表>中不存在的场景,否则不得自定义:\n{$scenes_content}。
  3662. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3663. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3664. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3665. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3666. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3667. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3668. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)。
  3669. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3670. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3671. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3672. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3673. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3674. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3675. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3676. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3677. 示例格式:\n
  3678. 第1集:隐形的守护者
  3679. ###故事梗概
  3680. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  3681. ###美术风格
  3682. 基础画风风格词:韩漫二次元
  3683. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  3684. ###主体列表
  3685. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{{甜心小美}}
  3686. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{{爽快思思}}
  3687. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{{阳光青年}}
  3688. 卞大伟:许芸名义上的表哥,阴险暴戾的无业游民。他身材肥胖,面部肉感重,一双小眼睛透着阴冷。{{广州德哥}}
  3689. 徐母:许芸亲生母亲,重男轻女且极度刻薄,面容严厉。{{邻居阿姨}}
  3690. ###场景列表
  3691. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。
  3692. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。
  3693. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。
  3694. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。
  3695. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。
  3696. ###分镜剧本
  3697. ##第1幕:徐家老旧厨房 白天 室内
  3698. 分镜1
  3699. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3700. 场景:徐家老旧厨房
  3701. 构图设计:全景,低角度仰视
  3702. 运镜调度:手持拍摄
  3703. 配音角色:旁白
  3704. 出镜角色:许芸-校服装、徐母
  3705. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3706. 画面类型:普通画面
  3707. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3708. 分镜2
  3709. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3710. 场景:徐家老旧厨房
  3711. 构图设计:近景,徐母面部特写
  3712. 运镜调度:固定镜头
  3713. 配音角色:徐母
  3714. 出镜角色:徐母
  3715. 台词内容:问我夜不归宿死哪儿去了。
  3716. 画面类型:对口型
  3717. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3718. ##第2幕:徐家简陋客厅 黄昏 室内
  3719. 分镜3
  3720. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3721. 场景:徐家简陋客厅
  3722. 构图设计:全景,景深虚化
  3723. 运镜调度:固定镜头
  3724. 配音角色:旁白
  3725. 出镜角色:无
  3726. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3727. 画面类型:普通画面
  3728. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3729. 分镜4
  3730. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3731. 场景:徐家简陋客厅
  3732. 构图设计:特写,火车票
  3733. 运镜调度:固定镜头
  3734. 配音角色:旁白
  3735. 出镜角色:无
  3736. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3737. 画面类型:普通画面
  3738. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  3739. \n\n";
  3740. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  3741. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  3742. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  3743. $prompt = $origin_prompt;
  3744. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  3745. // 获取章节内容
  3746. $full_content = getProp($anime, 'content');
  3747. // 根据章节内容拆分章节
  3748. $chapters = $this->splitContent($full_content);
  3749. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  3750. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  3751. $messages = [];
  3752. if ($prompt == '确认分镜大纲') {
  3753. $content = $uploaded_content ?: $chapter_content;
  3754. if ($is_single) $content = $full_content; // 单剧集使用全文
  3755. if (!$content) {
  3756. Utils::throwError('20003:章节内容无法获取,请确认');
  3757. }
  3758. $question = $is_single
  3759. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  3760. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本章剧情内容如下: \n\n$content";
  3761. // 构建消息
  3762. $messages[] =
  3763. [
  3764. 'role' => 'user',
  3765. 'content' => $question
  3766. ];
  3767. }else if ($prompt == '继续策划下一集') {
  3768. if ($is_single) {
  3769. Utils::throwError('20003:单剧集不支持继续策划下一集');
  3770. }
  3771. $content = $uploaded_content ?: $chapter_content;
  3772. if (!$content) {
  3773. Utils::throwError('20003:章节内容无法获取,请确认');
  3774. }
  3775. $question = $demo."请根据以上要求分析本章剧情,完成本章分镜剧本(需衔接上一章内容)";
  3776. // 获取上一集最后记录
  3777. $prev_sequence = $episode_number - 1;
  3778. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence);
  3779. // 构建消息
  3780. $messages[] =
  3781. [
  3782. 'role' => 'user',
  3783. 'content' => $question
  3784. ];
  3785. }else {
  3786. $content = $uploaded_content ?: trim((string)getProp($base_episode, 'content'));
  3787. if (!$content) {
  3788. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  3789. }
  3790. if (!$content) {
  3791. Utils::throwError('20003:章节内容无法获取,请确认');
  3792. }
  3793. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  3794. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  3795. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。"
  3796. . "\n\n本次修改要求如下:\n{$origin_prompt}";
  3797. $messages[] =
  3798. [
  3799. 'role' => 'user',
  3800. 'content' => $question
  3801. ];
  3802. }
  3803. // 处理文本模型
  3804. $model = getProp($data, 'model');
  3805. if (!$model) {
  3806. // 用户没有输入,从anime表获取
  3807. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3808. $model = getProp($anime, 'model');
  3809. if (!$model) {
  3810. // anime表也没有,使用默认值
  3811. $model = 'doubao-seed-2-0-mini-260215';
  3812. }
  3813. }
  3814. // 验证模型是否在可用模型表中
  3815. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3816. $model = 'doubao-seed-2-0-mini-260215';
  3817. }
  3818. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3819. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3820. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3821. if ($model === 'deepseek-chat') {
  3822. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3823. $model = 'deepseek-v4-flash';
  3824. $thinkingMode = 'disabled';
  3825. } elseif ($model === 'deepseek-reasoner') {
  3826. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3827. $model = 'deepseek-v4-flash';
  3828. $thinkingMode = 'enabled';
  3829. }
  3830. $post_data = [
  3831. 'model' => $model,
  3832. 'messages' => $messages,
  3833. // 'max_tokens' => 8192,
  3834. 'temperature' => 0.7,
  3835. 'frequency_penalty' => 0,
  3836. 'presence_penalty' => 0,
  3837. 'response_format' => ['type' => 'text'],
  3838. 'thinking' => ['type' => $thinkingMode],
  3839. 'stream' => true // 启用流式输出
  3840. ];
  3841. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3842. // 根据模型类型选择调用方法
  3843. $fullContent = '';
  3844. $fullReasoningContent = '';
  3845. $usage = [];
  3846. try {
  3847. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3848. // DeepSeek 官方模型使用 DeepSeek API
  3849. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3850. } else {
  3851. // 其他模型使用火山引擎API
  3852. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3853. }
  3854. // 验证返回值类型
  3855. if (!is_iterable($streamGenerator)) {
  3856. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  3857. dLog('deepseek')->error('chat流式生成器无效', [
  3858. 'generator_type' => $errorType,
  3859. 'model' => $model,
  3860. 'anime_id' => $anime_id,
  3861. 'episode_number' => $episode_number
  3862. ]);
  3863. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  3864. 'type' => $errorType,
  3865. 'model' => $model
  3866. ]);
  3867. yield [
  3868. 'type' => 'error',
  3869. 'episode' => [],
  3870. 'answer' => '',
  3871. 'reasoning' => '',
  3872. 'usage' => [],
  3873. 'error' => '接口返回数据异常,请重新请求'
  3874. ];
  3875. return;
  3876. }
  3877. // 处理流式输出
  3878. foreach ($streamGenerator as $chunk) {
  3879. if (isset($chunk['type'])) {
  3880. if ($chunk['type'] === 'done') {
  3881. // 最终结果
  3882. $fullContent = $chunk['full_content'];
  3883. $fullReasoningContent = $chunk['full_reasoning'];
  3884. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3885. } else {
  3886. // 逐块yield数据
  3887. yield $chunk;
  3888. }
  3889. }
  3890. }
  3891. } catch (\Exception $e) {
  3892. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  3893. 'model' => $model,
  3894. 'anime_id' => $anime_id,
  3895. 'episode_number' => $episode_number,
  3896. 'trace' => $e->getTraceAsString()
  3897. ]);
  3898. logDB('deepseek', 'error', 'chat流式处理失败', [
  3899. 'error' => $e->getMessage(),
  3900. 'model' => $model
  3901. ]);
  3902. yield [
  3903. 'type' => 'error',
  3904. 'episode' => [],
  3905. 'answer' => '',
  3906. 'reasoning' => '',
  3907. 'usage' => [],
  3908. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  3909. ];
  3910. return;
  3911. }
  3912. dLog('deepseek')->info('完整内容: '.$fullContent);
  3913. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3914. // 处理完整内容并返回最终结果
  3915. $episode_arr = handleEpisodeContent($fullContent);
  3916. logDB('deepseek', 'info', '解析内容', $episode_arr);
  3917. if (empty($episode_arr['acts'])) {
  3918. // 未生成剧本相关内容,保存对话记录并返回提示
  3919. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  3920. try {
  3921. $now = date('Y-m-d H:i:s');
  3922. // 保存对话记录
  3923. $records = [
  3924. [
  3925. 'uid' => $uid,
  3926. 'anime_id' => $anime_id,
  3927. 'sequence' => $episode_number,
  3928. 'role' => 'user',
  3929. 'content' => $prompt,
  3930. 'created_at' => $now,
  3931. 'updated_at' => $now
  3932. ],
  3933. [
  3934. 'uid' => $uid,
  3935. 'anime_id' => $anime_id,
  3936. 'sequence' => $episode_number,
  3937. 'role' => 'assistant',
  3938. 'content' => $fullContent,
  3939. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3940. 'created_at' => $now,
  3941. 'updated_at' => $now
  3942. ]
  3943. ];
  3944. DB::table('mp_anime_records')->insert($records);
  3945. } catch (\Exception $e) {
  3946. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3947. }
  3948. yield [
  3949. 'type' => 'done',
  3950. 'episode' => [],
  3951. 'answer' => $fullContent,
  3952. 'reasoning' => $fullReasoningContent,
  3953. 'usage' => $usage,
  3954. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  3955. ];
  3956. return;
  3957. }
  3958. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  3959. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  3960. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  3961. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  3962. $now = date('Y-m-d H:i:s');
  3963. try {
  3964. DB::beginTransaction();
  3965. $saveResult = $this->saveEpisodeVersionData(
  3966. $anime_id,
  3967. $episode_number,
  3968. $episode_arr,
  3969. $existing_roles,
  3970. $existing_scenes,
  3971. $current_episode,
  3972. $base_episode,
  3973. $is_regenerate_version,
  3974. $content,
  3975. $now
  3976. );
  3977. $episode = $saveResult['episode'];
  3978. $episode_id = $saveResult['episode_id'];
  3979. $merged_roles = $saveResult['merged_roles'];
  3980. $merged_scenes = $saveResult['merged_scenes'];
  3981. $record_content = $origin_prompt;
  3982. if ($uploaded_content !== '') {
  3983. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  3984. }
  3985. $records = [
  3986. [
  3987. 'uid' => $uid,
  3988. 'anime_id' => $anime_id,
  3989. 'role' => 'user',
  3990. 'content' => $record_content,
  3991. 'sequence' => $episode_number,
  3992. 'episode_id' => $episode_id,
  3993. 'created_at' => $now,
  3994. 'updated_at' => $now
  3995. ],
  3996. [
  3997. 'uid' => $uid,
  3998. 'anime_id' => $anime_id,
  3999. 'role' => 'assistant',
  4000. 'content' => $fullContent,
  4001. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4002. 'sequence' => $episode_number,
  4003. 'episode_id' => $episode_id,
  4004. 'created_at' => $now,
  4005. 'updated_at' => $now
  4006. ]
  4007. ];
  4008. $boolen4 = DB::table('mp_anime_records')->insert($records);
  4009. if (!$boolen4) {
  4010. Utils::throwError('20003:对话记录保存失败');
  4011. }
  4012. // 保存模型到anime表
  4013. DB::table('mp_animes')->where('id', $anime_id)->update([
  4014. 'model' => $model,
  4015. 'updated_at' => $now
  4016. ]);
  4017. }catch (\Exception $e) {
  4018. DB::rollBack();
  4019. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  4020. yield [
  4021. 'type' => 'done',
  4022. 'answer' => $fullContent,
  4023. 'reasoning' => $fullReasoningContent,
  4024. 'usage' => $usage,
  4025. 'error' => $e->getMessage(),
  4026. ];
  4027. return;
  4028. }
  4029. DB::commit();
  4030. if ($is_global_generate_pics) {
  4031. // 批量生成全局角色图片
  4032. $this->batchSetGlobalRoleImg([
  4033. 'anime_id' => $anime_id,
  4034. ]);
  4035. // 批量生成全局场景图片
  4036. $this->batchSetGlobalSceneImg([
  4037. 'anime_id' => $anime_id,
  4038. ]);
  4039. // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4040. $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4041. }
  4042. $episode['episode_id'] = $episode_id;
  4043. $episode['roles'] = $merged_roles;
  4044. $episode['scenes'] = $merged_scenes;
  4045. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  4046. yield [
  4047. 'type' => 'done',
  4048. 'episode' => $episode,
  4049. 'answer' => $fullContent,
  4050. 'reasoning' => $fullReasoningContent,
  4051. 'usage' => $usage
  4052. ];
  4053. }
  4054. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  4055. {
  4056. $episode_arr = [
  4057. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  4058. 'intro' => getProp($script_arr, 'intro'),
  4059. 'art_style' => getProp($script_arr, 'art_style'),
  4060. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4061. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4062. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  4063. ];
  4064. if (empty($episode_arr['acts'])) {
  4065. $fallback_episode_arr = handleEpisodeContent($fullContent);
  4066. if (!empty($fallback_episode_arr['acts'])) {
  4067. $episode_arr = array_merge($fallback_episode_arr, [
  4068. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  4069. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  4070. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  4071. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  4072. ]);
  4073. }
  4074. }
  4075. // if (!getProp($episode_arr, 'episode_title')) {
  4076. // $episode_title = '';
  4077. // $episodes = getProp($script_arr, 'episodes', []);
  4078. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  4079. // $episode_title = '第1集:' . $episodes[0]['title'];
  4080. // }
  4081. // if (!$episode_title) {
  4082. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  4083. // }
  4084. // $episode_arr['episode_title'] = $episode_title;
  4085. // }
  4086. return $episode_arr;
  4087. }
  4088. private function saveEpisodeVersionData(
  4089. int $anime_id,
  4090. int $episode_number,
  4091. array $episode_arr,
  4092. array $existing_roles,
  4093. array $existing_scenes,
  4094. $current_episode,
  4095. $base_episode,
  4096. bool $is_regenerate_version,
  4097. string $content,
  4098. string $now
  4099. ): array {
  4100. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  4101. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  4102. $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  4103. $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  4104. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  4105. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4106. $global_roles = json_decode(getProp($anime, 'roles'), true);
  4107. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  4108. $global_roles = is_array($global_roles) ? $global_roles : [];
  4109. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  4110. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  4111. // 检查并创建 roles 的图片生成任务
  4112. $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  4113. // 检查并创建 scenes 的图片生成任务
  4114. $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  4115. $role_arr = [];
  4116. foreach ($merged_roles as $item) {
  4117. $role_arr[$item['role']] = $item;
  4118. }
  4119. $version_count = DB::table('mp_anime_episodes')
  4120. ->where('anime_id', $anime_id)
  4121. ->where('episode_number', $episode_number)
  4122. ->count('id');
  4123. $episode = [
  4124. 'anime_id' => $anime_id,
  4125. 'episode_number' => $episode_number,
  4126. 'title' => getProp($episode_arr, 'episode_title'),
  4127. 'content' => $content,
  4128. 'intro' => getProp($episode_arr, 'intro'),
  4129. 'art_style' => getProp($episode_arr, 'art_style'),
  4130. 'roles' => json_encode($merged_roles, 256),
  4131. 'scenes' => json_encode($merged_scenes, 256),
  4132. 'generate_status' => '待执行',
  4133. 'generate_at' => $now,
  4134. 'is_default' => 1,
  4135. 'updated_at' => $now,
  4136. ];
  4137. $del_flag = false;
  4138. if ($is_regenerate_version) {
  4139. DB::table('mp_anime_episodes')
  4140. ->where('anime_id', $anime_id)
  4141. ->where('episode_number', $episode_number)
  4142. ->update(['is_default' => 0, 'updated_at' => $now]);
  4143. $episode['sequence'] = $version_count + 1;
  4144. $episode['created_at'] = $now;
  4145. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  4146. if (!$episode_id) {
  4147. Utils::throwError('20003:创建剧集版本失败');
  4148. }
  4149. } else {
  4150. $target_episode = $current_episode ?: $base_episode;
  4151. if ($target_episode) {
  4152. $episode_id = getProp($target_episode, 'id');
  4153. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  4154. DB::table('mp_anime_episodes')
  4155. ->where('anime_id', $anime_id)
  4156. ->where('episode_number', $episode_number)
  4157. ->where('id', '<>', $episode_id)
  4158. ->update(['is_default' => 0, 'updated_at' => $now]);
  4159. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  4160. if ($boolen === false) {
  4161. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  4162. Utils::throwError('20003:分集内容保存失败');
  4163. }
  4164. $del_flag = true;
  4165. } else {
  4166. DB::table('mp_anime_episodes')
  4167. ->where('anime_id', $anime_id)
  4168. ->where('episode_number', $episode_number)
  4169. ->update(['is_default' => 0, 'updated_at' => $now]);
  4170. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  4171. $episode['created_at'] = $now;
  4172. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  4173. if (!$episode_id) {
  4174. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  4175. Utils::throwError('20003:分集内容保存失败');
  4176. }
  4177. }
  4178. }
  4179. $segments = [];
  4180. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  4181. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  4182. $emotion_list = array_flip($emotion_list);
  4183. foreach ($acts as $act) {
  4184. $act_segments = getProp($act, 'segments', []);
  4185. if (!is_array($act_segments)) {
  4186. continue;
  4187. }
  4188. foreach ($act_segments as $segment) {
  4189. $voice_actor = getProp($segment, 'voice_actor');
  4190. $timbre_info = isset($role_arr[$voice_actor]) ? $role_arr[$voice_actor] : [];
  4191. $voice_type = getProp($timbre_info, 'voice_type');
  4192. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  4193. if ($timbre_emotion) {
  4194. $timbre_emotion = explode(',', $timbre_emotion);
  4195. } else {
  4196. $timbre_emotion = [];
  4197. }
  4198. $emotion = getProp($segment, 'emotion', '中性');
  4199. if (!in_array($emotion, $timbre_emotion)) {
  4200. $emotion = '中性';
  4201. }
  4202. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  4203. $segments[] = [
  4204. 'anime_id' => $anime_id,
  4205. 'episode_id' => $episode_id,
  4206. 'episode_number' => $episode_number,
  4207. 'act_number' => getProp($act, 'act_number'),
  4208. 'act_title' => getProp($act, 'act_title'),
  4209. 'segment_id' => getProp($segment, 'segment_id'),
  4210. 'segment_number' => getProp($segment, 'segment_number'),
  4211. 'segment_content' => getProp($segment, 'segment_content'),
  4212. 'description' => getProp($segment, 'description'),
  4213. 'composition' => getProp($segment, 'composition'),
  4214. 'camera_movement' => getProp($segment, 'camera_movement'),
  4215. 'voice_actor' => $voice_actor,
  4216. 'dialogue' => getProp($segment, 'dialogue'),
  4217. 'frame_type' => getProp($segment, 'frame_type'),
  4218. 'scene' => getProp($segment, 'scene'),
  4219. 'characters' => getProp($segment, 'characters'),
  4220. 'tail_frame' => getProp($segment, 'tail_frame'),
  4221. 'voice_name' => getProp($timbre_info, 'voice_name'),
  4222. 'voice_type' => $voice_type,
  4223. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  4224. 'emotion' => $emotion,
  4225. 'emotion_type' => $emotion_type,
  4226. 'gender' => getProp($segment, 'gender', '0'),
  4227. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  4228. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  4229. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  4230. 'pitch' => getProp($segment, 'pitch', 0),
  4231. 'created_at' => $now,
  4232. 'updated_at' => $now
  4233. ];
  4234. }
  4235. }
  4236. if ($segments) {
  4237. if ($del_flag) {
  4238. DB::table('mp_episode_segments')
  4239. ->where('anime_id', $anime_id)
  4240. ->where('episode_id', $episode_id)
  4241. ->delete();
  4242. }
  4243. $boolen = DB::table('mp_episode_segments')->insert($segments);
  4244. if (!$boolen) {
  4245. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  4246. Utils::throwError('20003:分镜内容保存失败');
  4247. }
  4248. }
  4249. $episode['episode_id'] = $episode_id;
  4250. $episode['roles'] = $merged_roles;
  4251. $episode['scenes'] = $merged_scenes;
  4252. $episode['acts'] = $acts;
  4253. return [
  4254. 'episode' => $episode,
  4255. 'episode_id' => $episode_id,
  4256. 'merged_roles' => $merged_roles,
  4257. 'merged_scenes' => $merged_scenes,
  4258. ];
  4259. }
  4260. private function buildEpisodeItemContent(array $items, string $nameKey): string
  4261. {
  4262. $content = '';
  4263. foreach ($items as $item) {
  4264. $name = trim((string)getProp($item, $nameKey));
  4265. if ($name === '') {
  4266. continue;
  4267. }
  4268. $description = trim((string)getProp($item, 'description'));
  4269. $content .= $name . ': ' . $description . "\n";
  4270. }
  4271. return trim($content);
  4272. }
  4273. private function getEpisodeChatContent($animeId, $sequence) {
  4274. if ((int)$sequence <= 0) {
  4275. return [];
  4276. }
  4277. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  4278. if ($origin_content) $origin_content = '原文内容:'.$origin_content;
  4279. // 获取分集信息
  4280. $episode = DB::table('mp_anime_episodes')
  4281. ->where('anime_id', $animeId)
  4282. ->where('sequence', $sequence)
  4283. ->where('is_default', 1)
  4284. ->first();
  4285. if (!$episode) {
  4286. return [];
  4287. }
  4288. $episode_id = getProp($episode, 'id');
  4289. $episode_number = getProp($episode, 'episode_number');
  4290. $title = getProp($episode, 'title');
  4291. $intro = getProp($episode, 'intro');
  4292. $art_style = getProp($episode, 'art_style');
  4293. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  4294. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  4295. // 组装纯文本内容
  4296. $content = '';
  4297. // 添加分集标题和梗概
  4298. $content .= "###第{$episode_number}集:{$title}\n\n";
  4299. $content .= "###故事梗概\n";
  4300. $content .= trim($intro) . "\n\n";
  4301. // 添加美术风格
  4302. $content .= "###美术风格\n";
  4303. $content .= trim($art_style) . "\n\n";
  4304. // 添加主体列表
  4305. $content .= "###主体列表\n";
  4306. foreach ($roles as $role) {
  4307. $name = getProp($role, 'name');
  4308. $description = getProp($role, 'description');
  4309. $content .= "{$name}: {$description}\n";
  4310. }
  4311. $content .= "\n";
  4312. // 添加场景列表
  4313. $content .= "###场景列表\n";
  4314. foreach ($scenes as $scene) {
  4315. $name = getProp($scene, 'name');
  4316. $description = getProp($scene, 'description');
  4317. $content .= "{$name}: {$description}\n";
  4318. }
  4319. $content .= "\n";
  4320. // 获取分镜信息
  4321. $segments = DB::table('mp_episode_segments')
  4322. ->where('anime_id', $animeId)
  4323. ->where('episode_id', $episode_id)
  4324. ->orderBy('segment_number')
  4325. ->get();
  4326. if ($segments && count($segments) > 0) {
  4327. $content .= "###分镜剧本\n";
  4328. // 按幕分组
  4329. $currentAct = null;
  4330. foreach ($segments as $segment) {
  4331. $act_number = getProp($segment, 'act_number');
  4332. $segment_number = getProp($segment, 'segment_number');
  4333. $segment_content = getProp($segment, 'segment_content');
  4334. $scene_description = getProp($segment, 'scene_description');
  4335. $scene_name = getProp($segment, 'scene_name');
  4336. $composition = getProp($segment, 'composition');
  4337. $camera_movement = getProp($segment, 'camera_movement');
  4338. $voice_type = getProp($segment, 'voice_type');
  4339. $characters = getProp($segment, 'characters');
  4340. $dialogue = getProp($segment, 'dialogue');
  4341. $frame_type = getProp($segment, 'frame_type');
  4342. $tail_frame_description = getProp($segment, 'tail_frame_description');
  4343. // 如果是新的幕,添加幕标题
  4344. if ($act_number !== $currentAct) {
  4345. $currentAct = $act_number;
  4346. $content .= "##第{$act_number}幕:{$scene_name}\n";
  4347. }
  4348. // 添加分镜信息
  4349. $content .= "分镜{$segment_number}\n";
  4350. $content .= "分镜内容:{$segment_content}\n";
  4351. // $content .= "画面描述:{$scene_description}\n";
  4352. // $content .= "场景:{$scene_name}\n";
  4353. // $content .= "构图设计:{$composition}\n";
  4354. // $content .= "运镜调度:{$camera_movement}\n";
  4355. // if (!empty($voice_type)) {
  4356. // $content .= "配音角色:{$voice_type}\n";
  4357. // }
  4358. // if (!empty($characters)) {
  4359. // $content .= "出镜角色:{$characters}\n";
  4360. // }
  4361. // if (!empty($dialogue)) {
  4362. // $content .= "台词内容:\"{$dialogue}\"\n";
  4363. // }
  4364. // $content .= "画面类型:{$frame_type}\n";
  4365. // $content .= "尾帧描述:{$tail_frame_description}\n";
  4366. $content .= "\n";
  4367. }
  4368. }
  4369. $content = trim($content);
  4370. if($content) $content = "上集剧本内容:\n{$content}";
  4371. return [
  4372. [
  4373. 'role' => 'user',
  4374. 'content' => $origin_content
  4375. ],
  4376. [
  4377. 'role' => 'assistant',
  4378. 'content' => $content
  4379. ]
  4380. ];
  4381. }
  4382. private function getEpisodeChatMessages($animeId, $sequence): array
  4383. {
  4384. if ((int)$sequence <= 0) {
  4385. return [];
  4386. }
  4387. return DB::table('mp_anime_records')
  4388. ->where('anime_id', $animeId)
  4389. ->where('sequence', $sequence)
  4390. ->where('episode_id', '>', 0)
  4391. ->select('role', 'content')
  4392. ->orderBy('created_at')
  4393. ->orderBy('id')
  4394. ->get()
  4395. ->map(function ($value) {
  4396. return (array)$value;
  4397. })
  4398. ->toArray();
  4399. }
  4400. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  4401. {
  4402. $existingMap = [];
  4403. foreach ($existingItems as $item) {
  4404. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  4405. if ($itemKey === '') {
  4406. continue;
  4407. }
  4408. $existingMap[$itemKey] = $item;
  4409. }
  4410. if (!$generatedItems) {
  4411. return array_values($existingItems);
  4412. }
  4413. $merged = [];
  4414. foreach ($generatedItems as $item) {
  4415. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  4416. if ($itemKey === '') {
  4417. continue;
  4418. }
  4419. if (isset($existingMap[$itemKey])) {
  4420. if (trim((string)getProp($item, 'description')) === '') {
  4421. $merged[] = $existingMap[$itemKey];
  4422. continue;
  4423. }
  4424. // 检查内容是否发生变化
  4425. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  4426. if (!$isChanged) {
  4427. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  4428. $mergedItem = [
  4429. $nameKey => trim((string)getProp($item, $nameKey)),
  4430. 'description' => trim((string)getProp($item, 'description')),
  4431. ];
  4432. // 继承现有项的 URL
  4433. $existingUrl = getProp($existingMap[$itemKey], 'url');
  4434. if (!empty($existingUrl)) {
  4435. $mergedItem['url'] = $existingUrl;
  4436. }
  4437. // 继承现有项的 task_id
  4438. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  4439. if (!empty($existingTaskId)) {
  4440. $mergedItem['task_id'] = $existingTaskId;
  4441. }
  4442. // 继承现有项的 task_status
  4443. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  4444. if (!empty($existingTaskStatus)) {
  4445. $mergedItem['task_status'] = $existingTaskStatus;
  4446. }
  4447. // 保留生成项的音色字段
  4448. $voiceName = getProp($item, 'voice_name');
  4449. if (!empty($voiceName)) {
  4450. $mergedItem['voice_name'] = $voiceName;
  4451. }
  4452. $voiceType = getProp($item, 'voice_type');
  4453. if (!empty($voiceType)) {
  4454. $mergedItem['voice_type'] = $voiceType;
  4455. }
  4456. $audioUrl = getProp($item, 'voice_audio_url');
  4457. if (!empty($audioUrl)) {
  4458. $mergedItem['voice_audio_url'] = $audioUrl;
  4459. }
  4460. $merged[] = $mergedItem;
  4461. } else {
  4462. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  4463. $mergedItem = [
  4464. $nameKey => trim((string)getProp($item, $nameKey)),
  4465. 'description' => trim((string)getProp($item, 'description')),
  4466. ];
  4467. // 保留生成项的音色字段
  4468. $voiceName = getProp($item, 'voice_name');
  4469. if (!empty($voiceName)) {
  4470. $mergedItem['voice_name'] = $voiceName;
  4471. }
  4472. $voiceType = getProp($item, 'voice_type');
  4473. if (!empty($voiceType)) {
  4474. $mergedItem['voice_type'] = $voiceType;
  4475. }
  4476. $audioUrl = getProp($item, 'voice_audio_url');
  4477. if (!empty($audioUrl)) {
  4478. $mergedItem['voice_audio_url'] = $audioUrl;
  4479. }
  4480. // 不继承 URL、task_id 和 task_status(重置状态)
  4481. $merged[] = $mergedItem;
  4482. }
  4483. } else {
  4484. // 新增项,保留生成项的所有字段
  4485. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url']);
  4486. }
  4487. }
  4488. return $merged ?: array_values($existingItems);
  4489. }
  4490. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  4491. {
  4492. $resetItem = [
  4493. $nameKey => trim((string)getProp($item, $nameKey)),
  4494. 'description' => trim((string)getProp($item, 'description')),
  4495. ];
  4496. // 保留指定的字段
  4497. foreach ($preserveFields as $field) {
  4498. $value = getProp($item, $field);
  4499. if (!empty($value)) {
  4500. $resetItem[$field] = $value;
  4501. }
  4502. }
  4503. return $resetItem;
  4504. }
  4505. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  4506. {
  4507. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  4508. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  4509. if ($existingKey !== $generatedKey) {
  4510. return true;
  4511. }
  4512. return trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'));
  4513. }
  4514. private function normalizeEpisodeResourceKey($value): string
  4515. {
  4516. $value = trim((string)$value);
  4517. if ($value === '') {
  4518. return '';
  4519. }
  4520. return strtolower((string)preg_replace('/\s+/u', '', $value));
  4521. }
  4522. // 生成全局角色图片
  4523. private function batchSetGlobalRoleImg($data, $is_force=false) {
  4524. $anime_id = getProp($data, 'anime_id');
  4525. if (!$anime_id) Utils::throwError('1002:请选择对话');
  4526. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4527. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  4528. $art_style = getProp($anime, 'art_style');
  4529. $update_flag = false;
  4530. foreach ($roles as &$role) {
  4531. $role_name = getProp($role, 'role');
  4532. if ($role_name == '旁白') continue;
  4533. $description = getProp($role, 'description');
  4534. if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点在于主体人物信息,需要突出人物形象,不显示场景或背景信息";
  4535. // 参考图地址
  4536. $ref_img_url = getProp($role, 'url');
  4537. if (!$is_force && $ref_img_url) continue;
  4538. $update_flag = true;
  4539. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  4540. try {
  4541. $params = [
  4542. 'prompt' => $description,
  4543. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  4544. ];
  4545. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4546. $task_id = $task->id;
  4547. if (!$task_id) {
  4548. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  4549. }
  4550. $role['task_id'] = $task_id;
  4551. $role['task_status'] = 'processing';
  4552. } catch (\Exception $e) {
  4553. Utils::throwError("20003:" . $e->getMessage());
  4554. }
  4555. }
  4556. if (!$update_flag) return true;
  4557. // 保存角色信息
  4558. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  4559. 'roles' => json_encode($roles, 256),
  4560. 'generate_status' => '执行中',
  4561. 'generate_at' => date('Y-m-d H:i:s'),
  4562. 'updated_at' => date('Y-m-d H:i:s')
  4563. ]);
  4564. if (!$boolen) {
  4565. Utils::throwError('20003:保存角色信息失败');
  4566. }
  4567. return $boolen;
  4568. }
  4569. // 生成全局场景图片
  4570. private function batchSetGlobalSceneImg($data, $is_force=false) {
  4571. $anime_id = getProp($data, 'anime_id');
  4572. if (!$anime_id) Utils::throwError('1002:请选择对话');
  4573. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4574. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  4575. $art_style = getProp($anime, 'art_style');
  4576. $update_flag = false;
  4577. foreach ($scenes as &$scene) {
  4578. $scene_name = getProp($scene, 'scene');
  4579. $description = getProp($scene, 'description');
  4580. if ($art_style) $description = "美术风格:\n{$art_style}\n\n场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  4581. // 参考图地址
  4582. $ref_img_url = getProp($scene, 'url');
  4583. if (!$is_force && $ref_img_url) continue;
  4584. $update_flag = true;
  4585. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  4586. try {
  4587. $params = [
  4588. 'prompt' => $description,
  4589. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  4590. ];
  4591. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  4592. $task_id = $task->id;
  4593. if (!$task_id) {
  4594. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  4595. }
  4596. $scene['task_id'] = $task_id;
  4597. $scene['task_status'] = 'processing';
  4598. } catch (\Exception $e) {
  4599. Utils::throwError("20003:" . $e->getMessage());
  4600. }
  4601. }
  4602. if (!$update_flag) return true;
  4603. // 保存角色信息
  4604. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  4605. 'scenes' => json_encode($scenes, 256),
  4606. 'generate_status' => '执行中',
  4607. 'generate_at' => date('Y-m-d H:i:s'),
  4608. 'updated_at' => date('Y-m-d H:i:s')
  4609. ]);
  4610. if (!$boolen) {
  4611. Utils::throwError('20003:保存角色信息失败');
  4612. }
  4613. return $boolen;
  4614. }
  4615. /**
  4616. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  4617. *
  4618. * @param int $anime_id 动漫对话ID
  4619. * @param int $episode_id 分集ID
  4620. * @return bool
  4621. */
  4622. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  4623. // 获取全局角色和场景数据
  4624. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  4625. if (!$anime) {
  4626. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  4627. return false;
  4628. }
  4629. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  4630. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  4631. // 获取指定的分集
  4632. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  4633. if (!$episode) {
  4634. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  4635. return false;
  4636. }
  4637. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  4638. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  4639. $roles_updated = false;
  4640. $scenes_updated = false;
  4641. // 继承角色的task_id、task_status和url
  4642. foreach ($episode_roles as &$episode_role) {
  4643. $episode_role_name = getProp($episode_role, 'role');
  4644. $episode_description = getProp($episode_role, 'description');
  4645. $episode_url = getProp($episode_role, 'url');
  4646. // 跳过旁白角色
  4647. if ($episode_role_name == '旁白') {
  4648. continue;
  4649. }
  4650. // 如果剧集中已有URL,跳过
  4651. if (!empty($episode_url)) {
  4652. continue;
  4653. }
  4654. // 遍历全局角色数据,查找匹配的角色
  4655. foreach ($global_roles as $global_role) {
  4656. $global_role_name = getProp($global_role, 'role');
  4657. $global_description = getProp($global_role, 'description');
  4658. $global_url = getProp($global_role, 'url');
  4659. $global_task_id = getProp($global_role, 'task_id');
  4660. $global_task_status = getProp($global_role, 'task_status');
  4661. // 满足条件:1.角色名相同 2.描述相同 3.剧集中URL为空
  4662. if ($episode_role_name == $global_role_name && $episode_description == $global_description) {
  4663. // 继承 task_id、task_status 和 url
  4664. if (!empty($global_task_id)) {
  4665. $episode_role['task_id'] = $global_task_id;
  4666. $episode_role['task_status'] = $global_task_status;
  4667. $roles_updated = true;
  4668. dLog('deepseek')->info('剧集角色继承全局task_id', [
  4669. 'episode_id' => $episode_id,
  4670. 'role' => $episode_role_name,
  4671. 'task_id' => $global_task_id,
  4672. 'task_status' => $global_task_status
  4673. ]);
  4674. }
  4675. if (!empty($global_url)) {
  4676. $episode_role['url'] = $global_url;
  4677. $roles_updated = true;
  4678. dLog('deepseek')->info('剧集角色继承全局url', [
  4679. 'episode_id' => $episode_id,
  4680. 'role' => $episode_role_name,
  4681. 'url' => $global_url
  4682. ]);
  4683. }
  4684. break;
  4685. }
  4686. }
  4687. }
  4688. // 继承场景的task_id、task_status和url
  4689. foreach ($episode_scenes as &$episode_scene) {
  4690. $episode_scene_name = getProp($episode_scene, 'scene');
  4691. $episode_description = getProp($episode_scene, 'description');
  4692. $episode_url = getProp($episode_scene, 'url');
  4693. // 如果剧集中已有URL,跳过
  4694. if (!empty($episode_url)) {
  4695. continue;
  4696. }
  4697. // 遍历全局场景数据,查找匹配的场景
  4698. foreach ($global_scenes as $global_scene) {
  4699. $global_scene_name = getProp($global_scene, 'scene');
  4700. $global_description = getProp($global_scene, 'description');
  4701. $global_url = getProp($global_scene, 'url');
  4702. $global_task_id = getProp($global_scene, 'task_id');
  4703. $global_task_status = getProp($global_scene, 'task_status');
  4704. // 满足条件:1.场景名相同 2.描述相同 3.剧集中URL为空
  4705. if ($episode_scene_name == $global_scene_name && $episode_description == $global_description) {
  4706. // 继承 task_id、task_status 和 url
  4707. if (!empty($global_task_id)) {
  4708. $episode_scene['task_id'] = $global_task_id;
  4709. $episode_scene['task_status'] = $global_task_status;
  4710. $scenes_updated = true;
  4711. dLog('deepseek')->info('剧集场景继承全局task_id', [
  4712. 'episode_id' => $episode_id,
  4713. 'scene' => $episode_scene_name,
  4714. 'task_id' => $global_task_id,
  4715. 'task_status' => $global_task_status
  4716. ]);
  4717. }
  4718. if (!empty($global_url)) {
  4719. $episode_scene['url'] = $global_url;
  4720. $scenes_updated = true;
  4721. dLog('deepseek')->info('剧集场景继承全局url', [
  4722. 'episode_id' => $episode_id,
  4723. 'scene' => $episode_scene_name,
  4724. 'url' => $global_url
  4725. ]);
  4726. }
  4727. break;
  4728. }
  4729. }
  4730. }
  4731. // 如果有更新,则保存到数据库
  4732. if ($roles_updated || $scenes_updated) {
  4733. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  4734. if ($roles_updated) {
  4735. $update_data['roles'] = json_encode($episode_roles, 256);
  4736. }
  4737. if ($scenes_updated) {
  4738. $update_data['scenes'] = json_encode($episode_scenes, 256);
  4739. }
  4740. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  4741. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  4742. 'episode_id' => $episode_id,
  4743. 'roles_updated' => $roles_updated,
  4744. 'scenes_updated' => $scenes_updated
  4745. ]);
  4746. }
  4747. return true;
  4748. }
  4749. public function chatChangeImg($data) {
  4750. $segment = getProp($data, 'segment');
  4751. $segment_content = getProp($segment, 'segment_content');
  4752. $prompt = getProp($data, 'prompt');
  4753. $ref_img = getProp($data, 'ref_img');
  4754. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  4755. // 处理文本模型
  4756. $model = getProp($data, 'model');
  4757. if (!$model) {
  4758. // 用户没有输入,从anime表获取
  4759. $segment_id = getProp($segment, 'segment_id');
  4760. if ($segment_id) {
  4761. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  4762. if ($episode_id) {
  4763. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  4764. if ($anime_id) {
  4765. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  4766. }
  4767. }
  4768. }
  4769. if (!$model) {
  4770. // anime表也没有,使用默认值
  4771. $model = 'doubao-seed-2-0-mini-260215';
  4772. }
  4773. }
  4774. // 验证模型是否在可用模型表中
  4775. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4776. $model = 'doubao-seed-2-0-mini-260215';
  4777. }
  4778. $messages[] =
  4779. [
  4780. 'role' => 'user',
  4781. 'content' => $question
  4782. ];
  4783. $post_data = [
  4784. 'model' => $model,
  4785. 'messages' => $messages,
  4786. // 'max_tokens' => 8192,
  4787. 'temperature' => 0.7,
  4788. 'frequency_penalty' => 0,
  4789. 'presence_penalty' => 0,
  4790. 'response_format' => ['type' => 'text'],
  4791. 'stream' => false // 是否启用流式输出
  4792. ];
  4793. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4794. // DeepSeek 官方模型使用 DeepSeek API
  4795. $chatResult = $this->chatOnly($post_data);
  4796. } else {
  4797. // 其他模型使用火山引擎API
  4798. $chatResult = $this->volcEngineChatCompletion($post_data);
  4799. }
  4800. if (is_array($chatResult)) {
  4801. extract($chatResult);
  4802. }else {
  4803. Utils::throwError('20003: 接口调用失败!');
  4804. }
  4805. return [
  4806. 'type' => 'done',
  4807. // 'episode' => $episode,
  4808. 'answer' => $fullContent,
  4809. 'reasoning' => $fullReasoningContent,
  4810. 'usage' => $usage
  4811. ];
  4812. }
  4813. // 仅调用deepseek对话接口
  4814. private function chatOnly($post_data) {
  4815. $client = new Client(['timeout' => 1200, 'verify' => false]);
  4816. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  4817. $response = $result->getBody()->getContents();
  4818. $response_arr = json_decode($response, true);
  4819. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  4820. $fullContent = '';
  4821. $fullReasoningContent = [];
  4822. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  4823. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  4824. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  4825. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  4826. }
  4827. return [
  4828. 'fullContent' => $fullContent,
  4829. 'fullReasoningContent' => $fullReasoningContent,
  4830. 'usage' => $usage
  4831. ];
  4832. }
  4833. private function splitContent($content) {
  4834. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  4835. $chapters = [];
  4836. // 匹配不同格式的章节标题:###第X章、##第X章、第X章
  4837. $pattern = '/^(#{0,3}\s*第[^章]*章[^\n]*)\n(.*?)(?=\n#{0,3}\s*第[^章]*章|\z)/ms';
  4838. if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
  4839. foreach ($matches as $match) {
  4840. $title = trim($match[1], "# \t\n\r\0\x0B"); // 去除标题前的#号和空白字符
  4841. $chapterContent = trim($match[2]); // 去除内容前后的空白字符
  4842. if (!empty($title) && !empty($chapterContent)) {
  4843. $chapters[] = [
  4844. 'title' => $title,
  4845. 'content' => $chapterContent
  4846. ];
  4847. }
  4848. }
  4849. }else {
  4850. $chapters[] = [
  4851. 'title' => '',
  4852. 'content' => $content
  4853. ];
  4854. }
  4855. return $chapters;
  4856. }
  4857. public function getContentByBid($bid) {
  4858. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  4859. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  4860. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  4861. $content = '';
  4862. foreach ($chapters as $chapter) {
  4863. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  4864. }
  4865. return $content;
  4866. }
  4867. public function getContentByScriptId($script_id) {
  4868. $content = '';
  4869. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  4870. if ($contents) $content = implode(PHP_EOL, $contents);
  4871. return $content;
  4872. }
  4873. /**
  4874. * 根据文件类型提取文本内容
  4875. *
  4876. * @param mixed $file 文件对象或文件路径
  4877. * @return string
  4878. */
  4879. public function extractFileContent($file) {
  4880. // 获取文件路径和扩展名
  4881. if (is_string($file)) {
  4882. $filePath = $file;
  4883. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  4884. } else {
  4885. // Laravel UploadedFile 对象
  4886. $filePath = $file->getRealPath();
  4887. $extension = strtolower($file->getClientOriginalExtension());
  4888. }
  4889. $content = '';
  4890. switch ($extension) {
  4891. case 'txt':
  4892. $content = $this->extractTxtContent($filePath);
  4893. break;
  4894. case 'pdf':
  4895. $content = $this->extractPdfContent($filePath);
  4896. break;
  4897. case 'doc':
  4898. case 'docx':
  4899. $content = $this->extractWordContent($filePath);
  4900. break;
  4901. // case 'jpg':
  4902. // case 'jpeg':
  4903. // case 'png':
  4904. // case 'gif':
  4905. // case 'bmp':
  4906. // case 'webp':
  4907. // $content = $this->extractImageContent($filePath);
  4908. // break;
  4909. default:
  4910. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  4911. }
  4912. return $content;
  4913. }
  4914. /**
  4915. * 提取 TXT 文件内容
  4916. */
  4917. private function extractTxtContent($filePath) {
  4918. if (!file_exists($filePath)) {
  4919. Utils::throwError('20003:文件不存在');
  4920. }
  4921. $content = file_get_contents($filePath);
  4922. // 尝试检测并转换编码
  4923. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  4924. if ($encoding && $encoding !== 'UTF-8') {
  4925. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  4926. }
  4927. return trim($content);
  4928. }
  4929. /**
  4930. * 提取 PDF 文件内容
  4931. */
  4932. private function extractPdfContent($filePath) {
  4933. if (!file_exists($filePath)) {
  4934. Utils::throwError('20003:文件不存在');
  4935. }
  4936. try {
  4937. $parser = new PdfParser();
  4938. $pdf = $parser->parseFile($filePath);
  4939. $content = $pdf->getText();
  4940. return trim($content);
  4941. } catch (\Exception $e) {
  4942. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  4943. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  4944. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  4945. }
  4946. }
  4947. /**
  4948. * 提取 Word 文件内容(支持 doc 和 docx)
  4949. */
  4950. private function extractWordContent($filePath) {
  4951. if (!file_exists($filePath)) {
  4952. Utils::throwError('20003:文件不存在');
  4953. }
  4954. try {
  4955. $phpWord = WordIOFactory::load($filePath);
  4956. $content = '';
  4957. foreach ($phpWord->getSections() as $section) {
  4958. foreach ($section->getElements() as $element) {
  4959. $content .= $this->extractWordElementText($element);
  4960. }
  4961. }
  4962. return trim($content);
  4963. } catch (\Exception $e) {
  4964. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  4965. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  4966. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  4967. }
  4968. }
  4969. /**
  4970. * 递归提取 Word 元素中的文本
  4971. */
  4972. private function extractWordElementText($element) {
  4973. $text = '';
  4974. if (method_exists($element, 'getText')) {
  4975. $text .= $element->getText() . "\n";
  4976. } elseif (method_exists($element, 'getElements')) {
  4977. foreach ($element->getElements() as $childElement) {
  4978. $text .= $this->extractWordElementText($childElement);
  4979. }
  4980. }
  4981. return $text;
  4982. }
  4983. /**
  4984. * 提取图片内容(使用火山引擎 OCR)
  4985. */
  4986. private function extractImageContent($filePath) {
  4987. if (!file_exists($filePath)) {
  4988. Utils::throwError('20003:文件不存在');
  4989. }
  4990. try {
  4991. // 读取图片并转换为 base64
  4992. $imageData = file_get_contents($filePath);
  4993. $base64Image = base64_encode($imageData);
  4994. // 调用火山引擎 OCR 服务
  4995. $content = $this->callVolcEngineOCR($base64Image);
  4996. return trim($content);
  4997. } catch (\Exception $e) {
  4998. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  4999. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  5000. Utils::throwError('20003:图片识别失败');
  5001. }
  5002. }
  5003. /**
  5004. * 调用火山引擎 OCR 服务识别图片文字
  5005. *
  5006. * @param string $base64Image base64 编码的图片数据
  5007. * @return string 识别的文字内容
  5008. */
  5009. private function callVolcEngineOCR($base64Image) {
  5010. $method = 'POST';
  5011. $service = 'cv';
  5012. $host = 'visual.volcengineapi.com';
  5013. $region = env('VOLC_REGION', 'cn-north-1');
  5014. $access_key = env('VOLC_AK');
  5015. $secret_key = env('VOLC_SK');
  5016. $action = 'OCRNormal';
  5017. $version = '2020-08-26';
  5018. if (!$access_key || !$secret_key) {
  5019. Utils::throwError('20003:请配置火山引擎 AK/SK');
  5020. }
  5021. // 请求体
  5022. $body = json_encode([
  5023. 'image_base64' => $base64Image
  5024. ]);
  5025. // 生成签名
  5026. $headers = $this->getVolcEngineSignHeaders(
  5027. $method, $service, $host, $region,
  5028. "Action={$action}&Version={$version}",
  5029. $access_key, $secret_key, $body
  5030. );
  5031. $client = new Client(['timeout' => 60, 'verify' => false]);
  5032. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  5033. 'headers' => $headers,
  5034. 'body' => $body
  5035. ]);
  5036. $response_arr = json_decode($response->getBody()->getContents(), true);
  5037. // 提取识别的文字
  5038. $textLines = [];
  5039. if (isset($response_arr['data']['line_texts'])) {
  5040. $textLines = $response_arr['data']['line_texts'];
  5041. } elseif (isset($response_arr['data']['ocr_infos'])) {
  5042. foreach ($response_arr['data']['ocr_infos'] as $info) {
  5043. if (isset($info['text'])) {
  5044. $textLines[] = $info['text'];
  5045. }
  5046. }
  5047. }
  5048. if (empty($textLines)) {
  5049. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  5050. return '';
  5051. }
  5052. return implode("\n", $textLines);
  5053. }
  5054. /**
  5055. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  5056. */
  5057. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  5058. $contentType = 'application/json';
  5059. $accept = 'application/json';
  5060. // 获取当前UTC时间
  5061. $t = new DateTime('now', new DateTimeZone('UTC'));
  5062. $xDate = $t->format('Ymd\THis\Z');
  5063. $dateStamp = $t->format('Ymd');
  5064. // 计算 body 的 sha256 哈希
  5065. $payloadHash = hash('sha256', $body);
  5066. // 1. 拼接规范请求串
  5067. $canonicalUri = '/';
  5068. $canonicalQueryString = $queryString;
  5069. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  5070. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  5071. $canonicalRequest = implode("\n", [
  5072. $method,
  5073. $canonicalUri,
  5074. $canonicalQueryString,
  5075. $canonicalHeaders,
  5076. $signedHeaders,
  5077. $payloadHash
  5078. ]);
  5079. // 2. 拼接待签名字符串
  5080. $algorithm = 'HMAC-SHA256';
  5081. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  5082. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  5083. $stringToSign = implode("\n", [
  5084. $algorithm,
  5085. $xDate,
  5086. $credentialScope,
  5087. $hashedCanonicalRequest
  5088. ]);
  5089. // 3. 计算签名
  5090. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  5091. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  5092. // 4. 添加签名到请求头
  5093. $authorizationHeader = sprintf(
  5094. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  5095. $algorithm,
  5096. $access_key,
  5097. $credentialScope,
  5098. $signedHeaders,
  5099. $signature
  5100. );
  5101. return [
  5102. 'Accept' => $accept,
  5103. 'Content-Type' => $contentType,
  5104. 'Host' => $host,
  5105. 'X-Date' => $xDate,
  5106. 'X-Content-Sha256'=> $payloadHash,
  5107. 'Authorization' => $authorizationHeader
  5108. ];
  5109. }
  5110. public function generateScriptWords($cid, $model = 'r1') {
  5111. ini_set('max_execution_time', 0);
  5112. if (!$cid) Utils::throwError('20003: 请选择章节!');
  5113. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  5114. // 模型兼容性处理和思考模式设置
  5115. $thinkingMode = 'disabled';
  5116. $reasoningEffort = 'high';
  5117. if ($model == 'r1') {
  5118. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  5119. $thinkingMode = 'enabled';
  5120. } else {
  5121. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  5122. $thinkingMode = 'disabled';
  5123. }
  5124. $messages = [
  5125. [
  5126. 'role' => 'system',
  5127. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  5128. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  5129. 2.非对话部分请全部用旁白角色代替
  5130. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  5131. ],
  5132. [
  5133. 'role' => 'user',
  5134. 'content' => $content
  5135. ]
  5136. ];
  5137. $post_data = [
  5138. 'model' => $model,
  5139. 'messages' => $messages,
  5140. // 'max_tokens' => 8192,
  5141. 'temperature' => 1,
  5142. 'frequency_penalty' => 0,
  5143. 'presence_penalty' => 0,
  5144. 'thinking' => ['type' => $thinkingMode],
  5145. 'response_format' => [
  5146. 'type' => 'text'
  5147. ],
  5148. 'stream' => false
  5149. ];
  5150. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5151. // 根据模型类型选择调用方法
  5152. $fullContent = '';
  5153. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5154. // DeepSeek 官方模型使用 DeepSeek API
  5155. $chatResult = $this->chatOnly($post_data);
  5156. } else {
  5157. // 其他模型使用火山引擎API
  5158. $chatResult = $this->volcEngineChatCompletion($post_data);
  5159. }
  5160. if (is_array($chatResult)) {
  5161. $fullContent = $chatResult['fullContent'];
  5162. }
  5163. return $fullContent;
  5164. }
  5165. /**
  5166. * 智能化解析集数信息
  5167. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  5168. *
  5169. * @param string $prompt 用户输入的提示词
  5170. * @return int|null 解析出的集数,如果没有找到则返回null
  5171. */
  5172. private function extractEpisodeNumber($prompt)
  5173. {
  5174. if (empty($prompt)) {
  5175. return null;
  5176. }
  5177. // 定义各种可能的表达模式
  5178. $patterns = [
  5179. // 基本模式:改成N集、调整成N集、修改成N集
  5180. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  5181. // 扩展模式:分成N集、拆分成N集、分割成N集
  5182. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  5183. // 数量模式:N集、共N集、总共N集
  5184. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  5185. // 制作模式:制作N集、生成N集、创建N集
  5186. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  5187. // 计划模式:计划N集、预计N集、打算N集
  5188. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  5189. // 需要模式:需要N集、要N集
  5190. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  5191. // 中文数字模式:改成三集、调整成五集等
  5192. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  5193. // 英文数字模式
  5194. '/(?: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',
  5195. ];
  5196. // 中文数字转阿拉伯数字的映射
  5197. $chineseNumbers = [
  5198. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  5199. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  5200. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  5201. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  5202. ];
  5203. // 逐个尝试匹配模式
  5204. foreach ($patterns as $pattern) {
  5205. if (preg_match($pattern, $prompt, $matches)) {
  5206. $number = trim($matches[1]);
  5207. // 如果是中文数字,转换为阿拉伯数字
  5208. if (isset($chineseNumbers[$number])) {
  5209. return $chineseNumbers[$number];
  5210. }
  5211. // 如果是阿拉伯数字,直接返回
  5212. if (is_numeric($number)) {
  5213. $episodeNum = intval($number);
  5214. // 合理性检查:集数应该在1-100之间
  5215. if ($episodeNum >= 1 && $episodeNum <= 100) {
  5216. return $episodeNum;
  5217. }
  5218. }
  5219. }
  5220. }
  5221. return null;
  5222. }
  5223. /**
  5224. * 调用火山引擎对话(Chat) API
  5225. *
  5226. * @param array $params 包含以下参数:
  5227. * - model: 模型ID(必填)
  5228. * - messages: 消息列表(必填)
  5229. * - stream: 是否流式输出(可选,默认false)
  5230. * - max_tokens: 最大输出token数(可选)
  5231. * - temperature: 采样温度(可选,默认1)
  5232. * - top_p: 核采样概率(可选,默认0.7)
  5233. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  5234. * - presence_penalty: 存在惩罚系数(可选,默认0)
  5235. * - stop: 停止词(可选)
  5236. * - tools: 工具列表(可选)
  5237. * @return array|Generator 非流式返回数组,流式返回生成器
  5238. */
  5239. public function volcEngineChatCompletion(array $params)
  5240. {
  5241. $apiKey = env('VOLC_AI_API_KEY');
  5242. if (empty($apiKey)) {
  5243. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  5244. }
  5245. // 构建请求参数
  5246. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  5247. $requestData = [
  5248. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  5249. 'messages' => $params['messages'] ?? [],
  5250. ];
  5251. if (!in_array($originalModel, $this->valid_text_models)) {
  5252. Utils::throwError('20003:该模型不支持!');
  5253. }
  5254. // 添加可选参数
  5255. if (isset($params['stream'])) {
  5256. $requestData['stream'] = $params['stream'];
  5257. }
  5258. if (isset($params['stream_options'])) {
  5259. $requestData['stream_options'] = $params['stream_options'];
  5260. }
  5261. if (isset($params['max_tokens'])) {
  5262. $requestData['max_tokens'] = $params['max_tokens'];
  5263. }
  5264. if (isset($params['max_completion_tokens'])) {
  5265. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  5266. }
  5267. if (isset($params['temperature'])) {
  5268. $requestData['temperature'] = $params['temperature'];
  5269. }
  5270. if (isset($params['top_p'])) {
  5271. $requestData['top_p'] = $params['top_p'];
  5272. }
  5273. if (isset($params['frequency_penalty'])) {
  5274. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  5275. }
  5276. if (isset($params['presence_penalty'])) {
  5277. $requestData['presence_penalty'] = $params['presence_penalty'];
  5278. }
  5279. if (isset($params['stop'])) {
  5280. $requestData['stop'] = $params['stop'];
  5281. }
  5282. if (isset($params['tools'])) {
  5283. $requestData['tools'] = $params['tools'];
  5284. }
  5285. if (isset($params['tool_choice'])) {
  5286. $requestData['tool_choice'] = $params['tool_choice'];
  5287. }
  5288. if (isset($params['response_format'])) {
  5289. $requestData['response_format'] = $params['response_format'];
  5290. }
  5291. if (isset($params['thinking'])) {
  5292. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  5293. if (is_array($params['thinking'])) {
  5294. $requestData['thinking'] = $params['thinking'];
  5295. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  5296. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  5297. }
  5298. } else {
  5299. $requestData['thinking'] = ['type' => $params['thinking']];
  5300. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  5301. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  5302. }
  5303. }
  5304. } else {
  5305. $requestData['thinking'] = ['type' => 'disabled'];
  5306. }
  5307. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  5308. $client = new Client(['verify' => false, 'timeout' => 1200]);
  5309. try {
  5310. // 判断是否为流式输出
  5311. $isStream = isset($params['stream']) && $params['stream'] === true;
  5312. if ($isStream) {
  5313. // 流式输出
  5314. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  5315. } else {
  5316. // 非流式输出
  5317. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  5318. 'headers' => [
  5319. 'Authorization' => 'Bearer ' . $apiKey,
  5320. 'Content-Type' => 'application/json',
  5321. ],
  5322. 'json' => $requestData
  5323. ]);
  5324. $responseData = json_decode($response->getBody(), true);
  5325. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  5326. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  5327. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  5328. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  5329. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  5330. }
  5331. return [
  5332. 'fullContent' => $fullContent,
  5333. 'fullReasoningContent' => $fullReasoningContent,
  5334. 'usage' => $usage
  5335. ];
  5336. }
  5337. } catch (\Exception $e) {
  5338. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  5339. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  5340. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  5341. }
  5342. }
  5343. /**
  5344. * 火山引擎对话API流式输出
  5345. *
  5346. * @param Client $client HTTP客户端
  5347. * @param string $apiKey API密钥
  5348. * @param array $requestData 请求数据
  5349. * @return Generator
  5350. */
  5351. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  5352. {
  5353. try {
  5354. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  5355. 'headers' => [
  5356. 'Authorization' => 'Bearer ' . $apiKey,
  5357. 'Content-Type' => 'application/json',
  5358. ],
  5359. 'json' => $requestData,
  5360. 'stream' => true
  5361. ]);
  5362. $body = $response->getBody();
  5363. $buffer = '';
  5364. $fullContent = '';
  5365. $fullReasoningContent = '';
  5366. $usage = [];
  5367. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  5368. // 逐行读取流式响应
  5369. while (!$body->eof()) {
  5370. $chunk = $body->read(1024);
  5371. $buffer .= $chunk;
  5372. // 按行分割
  5373. $lines = explode("\n", $buffer);
  5374. $buffer = array_pop($lines);
  5375. foreach ($lines as $line) {
  5376. $line = trim($line);
  5377. if (empty($line)) {
  5378. continue;
  5379. }
  5380. // 检查是否是SSE数据行
  5381. if (strpos($line, 'data: ') !== 0) {
  5382. continue;
  5383. }
  5384. $data = substr($line, 6);
  5385. if ($data === '[DONE]') {
  5386. dLog('deepseek')->info('收到结束标记');
  5387. break 2;
  5388. }
  5389. try {
  5390. $json = json_decode($data, true);
  5391. if (json_last_error() !== JSON_ERROR_NONE) {
  5392. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  5393. continue;
  5394. }
  5395. if (isset($json['choices'][0]['delta'])) {
  5396. $delta = $json['choices'][0]['delta'];
  5397. // 处理思维链内容
  5398. if (isset($delta['reasoning_content'])) {
  5399. $fullReasoningContent .= $delta['reasoning_content'];
  5400. yield [
  5401. 'type' => 'reasoning',
  5402. 'content' => $delta['reasoning_content'],
  5403. 'full_reasoning' => $fullReasoningContent
  5404. ];
  5405. }
  5406. // 处理回答内容
  5407. if (isset($delta['content'])) {
  5408. $fullContent .= $delta['content'];
  5409. yield [
  5410. 'type' => 'content',
  5411. 'content' => $delta['content'],
  5412. ];
  5413. }
  5414. }
  5415. // 获取使用统计信息
  5416. if (isset($json['usage'])) {
  5417. $usage = $json['usage'];
  5418. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  5419. }
  5420. } catch (\Exception $e) {
  5421. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  5422. continue;
  5423. }
  5424. }
  5425. }
  5426. dLog('deepseek')->info('流式读取完成', [
  5427. 'content_length' => strlen($fullContent),
  5428. 'reasoning_length' => strlen($fullReasoningContent)
  5429. ]);
  5430. yield [
  5431. 'type' => 'done',
  5432. 'full_content' => $fullContent,
  5433. 'full_reasoning' => $fullReasoningContent,
  5434. 'usage' => $usage
  5435. ];
  5436. } catch (\Exception $e) {
  5437. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  5438. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  5439. throw $e;
  5440. }
  5441. }
  5442. /**
  5443. * 检查并创建图片生成任务
  5444. *
  5445. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  5446. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  5447. * @param string $nameKey 资源名称字段('role' 或 'scene')
  5448. * @param string $art_style 美术风格
  5449. * @return array 更新后的资源列表
  5450. */
  5451. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  5452. {
  5453. // 确保参数为数组
  5454. $merged_items = is_array($merged_items) ? $merged_items : [];
  5455. $global_items = is_array($global_items) ? $global_items : [];
  5456. // 构建全局资源映射表,用于快速查找
  5457. $global_map = [];
  5458. foreach ($global_items as $item) {
  5459. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  5460. if ($itemKey === '') {
  5461. continue;
  5462. }
  5463. $global_map[$itemKey] = $item;
  5464. }
  5465. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  5466. foreach ($merged_items as &$item) {
  5467. $item_name = getProp($item, $nameKey);
  5468. $item_description = getProp($item, 'description');
  5469. // $item_url = getProp($item, 'url');
  5470. // // 如果已有图片URL,跳过
  5471. // if (!empty($item_url)) {
  5472. // continue;
  5473. // }
  5474. // 如果是旁白角色,跳过
  5475. if ($nameKey === 'role' && $item_name === '旁白') {
  5476. continue;
  5477. }
  5478. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  5479. if ($itemKey === '') {
  5480. continue;
  5481. }
  5482. $need_create_task = false;
  5483. // 条件1:在全局资源中找不到匹配的名称
  5484. if (!isset($global_map[$itemKey])) {
  5485. $need_create_task = true;
  5486. } else {
  5487. // 条件2:名称匹配但描述不一致
  5488. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  5489. $current_description = trim((string)$item_description);
  5490. if ($global_description !== $current_description) {
  5491. $need_create_task = true;
  5492. }
  5493. }
  5494. // 如果需要创建任务,调用图片生成服务
  5495. if ($need_create_task) {
  5496. try {
  5497. $description = $item_description;
  5498. // 添加美术风格前缀
  5499. if ($art_style) {
  5500. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  5501. $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  5502. }
  5503. $params = [
  5504. 'prompt' => $description,
  5505. 'ref_img_urls' => []
  5506. ];
  5507. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  5508. $task_id = $task->id;
  5509. if ($task_id) {
  5510. $item['task_id'] = $task_id;
  5511. $item['task_status'] = 'processing';
  5512. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  5513. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  5514. }
  5515. } catch (\Exception $e) {
  5516. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  5517. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  5518. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  5519. // 不抛出异常,继续处理其他资源
  5520. }
  5521. }
  5522. }
  5523. return $merged_items;
  5524. }
  5525. /**
  5526. * 解析分镜内容的公开方法
  5527. */
  5528. public function parseSegmentContent($segment_content, $model = null) {
  5529. if (!$model) {
  5530. $model = DB::table('mp_text_models')->where('is_enabled', 1)->orderBy('id')->value('model');
  5531. if (!$model) {
  5532. return $segment_content;
  5533. }
  5534. }
  5535. // 构建系统提示词
  5536. $systemPrompt = "你是一个专业的分镜内容解析助手。请将用户提供的分镜内容解析成标准格式,包含以下字段:
  5537. 画面描述:详细描述画面内容
  5538. 构图设计:镜头构图方式
  5539. 运镜调度:摄影机运动方式
  5540. 配音角色:配音的角色名称
  5541. 台词内容:角色说的话
  5542. 画面类型:普通画面或对口型
  5543. 场景:拍摄场景
  5544. 出镜角色:画面中出现的角色
  5545. 尾帧描述:镜头结束时的画面描述
  5546. 情感:配音情感(开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦)
  5547. 性别:1(男)、2(女)、0(中性)
  5548. 语速:-50到100之间的整数
  5549. 音量:-50到100之间的整数
  5550. 情感强度:1到5之间的整数
  5551. 音调:-12到12之间的整数
  5552. 请严格按照上述格式输出,如果某个字段无法确定,请设置合理的默认值。";
  5553. // 构建消息
  5554. $messages = [
  5555. [
  5556. 'role' => 'system',
  5557. 'content' => $systemPrompt
  5558. ],
  5559. [
  5560. 'role' => 'user',
  5561. 'content' => $segment_content
  5562. ]
  5563. ];
  5564. $post_data = [
  5565. 'model' => $model,
  5566. 'messages' => $messages,
  5567. // 'max_tokens' => 2048,
  5568. 'temperature' => 0.7,
  5569. 'frequency_penalty' => 0,
  5570. 'presence_penalty' => 0,
  5571. 'response_format' => ['type' => 'text'],
  5572. 'stream' => false
  5573. ];
  5574. try {
  5575. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5576. // 使用DeepSeek API
  5577. $chatResult = $this->chatOnly($post_data);
  5578. } else {
  5579. // 使用火山引擎API
  5580. $chatResult = $this->volcEngineChatCompletion($post_data);
  5581. }
  5582. if (is_array($chatResult) && !empty($chatResult['fullContent'])) {
  5583. return $chatResult['fullContent'];
  5584. }
  5585. } catch (\Exception $e) {
  5586. dLog('deepseek')->error('解析分镜内容失败: ' . $e->getMessage());
  5587. logDB('deepseek', 'error', '解析分镜内容失败', ['error' => $e->getMessage()]);
  5588. }
  5589. return $segment_content;
  5590. }
  5591. }