DeepSeekService.php 177 KB

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