DeepSeekService.php 232 KB

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