DeepSeekService.php 298 KB

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