DeepSeekService.php 296 KB

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