DeepSeekService.php 177 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754
  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. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  2211. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  2212. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  2213. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  2214. // 提取文件内容
  2215. if ($content) {
  2216. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  2217. } elseif ($file) {
  2218. $uploaded_content = $this->extractFileContent($file);
  2219. if (!$uploaded_content) {
  2220. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2221. }
  2222. } elseif ($bid) {
  2223. $uploaded_content = $this->getContentByBid($bid);
  2224. if (!$uploaded_content) {
  2225. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2226. }
  2227. }else {
  2228. $uploaded_content = '';
  2229. }
  2230. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  2231. $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间用###分隔;同时板块之间需满足以下要求:\n
  2232. 强制要求:
  2233. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2234. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答\n
  2235. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等\n
  2236. 普通要求:
  2237. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}
  2238. 2.<主体列表>必须在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个),不得自定义(需带上冒号后的具体描述):{$roles_content}\n
  2239. 2.1如果分集内容中出现了<主体列表>中不存在的新主体,则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在主题列表中
  2240. 3.<场景列表>必须在以下场景中选择多个(根据拆分出的分镜剧本来确认具体几个),不得自定义(需带上冒号后的具体描述):{$scenes_content}\n
  2241. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”: \n
  2242. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。\n
  2243. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音音色”、“台词内容”和“画面类型”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。\n
  2244. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。\n
  2245. 4.4“分镜信息”中的“台词内容”需与原文中的台词完全一致,不得修改或添加任何内容。\n
  2246. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。\n
  2247. 4.6“分镜信息”中的“场景”需对应本集中的<场景列表>中的一个(不带详细表述)\n
  2248. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无\n
  2249. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面\n\n
  2250. 示例格式:\n
  2251. 第1集:隐形的守护者
  2252. ###故事梗概
  2253. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  2254. ###美术风格
  2255. 基础画风风格词:韩漫二次元
  2256. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  2257. ###主体列表
  2258. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。
  2259. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。
  2260. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。
  2261. 卞大伟:许芸名义上的表哥,阴险暴戾的无业游民。他身材肥胖,面部肉感重,一双小眼睛透着阴冷。
  2262. 徐母:许芸亲生母亲,重男轻女且极度刻薄,面容严厉。
  2263. ###场景列表
  2264. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。
  2265. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。
  2266. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。
  2267. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。
  2268. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。
  2269. ###分镜剧本
  2270. ##第1幕:徐家老旧厨房 白天 室内
  2271. 分镜1
  2272. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  2273. 场景:徐家老旧厨房
  2274. 构图设计:全景,低角度仰视
  2275. 运镜调度:手持拍摄
  2276. 配音角色:旁白
  2277. 出镜角色:许芸-校服装、徐母
  2278. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  2279. 画面类型:普通画面
  2280. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  2281. 分镜2
  2282. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  2283. 场景:徐家老旧厨房
  2284. 构图设计:近景,徐母面部特写
  2285. 运镜调度:固定镜头
  2286. 配音角色:徐母
  2287. 出镜角色:徐母
  2288. 台词内容:问我夜不归宿死哪儿去了。
  2289. 画面类型:对口型
  2290. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  2291. ##第2幕:徐家简陋客厅 黄昏 室内
  2292. 分镜3
  2293. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  2294. 场景:徐家简陋客厅
  2295. 构图设计:全景,景深虚化
  2296. 运镜调度:固定镜头
  2297. 配音角色:旁白
  2298. 出镜角色:无
  2299. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  2300. 画面类型:普通画面
  2301. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  2302. 分镜4
  2303. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  2304. 场景:徐家简陋客厅
  2305. 构图设计:特写,火车票
  2306. 运镜调度:固定镜头
  2307. 配音角色:旁白
  2308. 出镜角色:无
  2309. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  2310. 画面类型:普通画面
  2311. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  2312. \n\n";
  2313. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  2314. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  2315. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  2316. $prompt = $origin_prompt;
  2317. // 获取章节内容
  2318. $full_content = getProp($anime, 'content');
  2319. // 根据章节内容拆分章节
  2320. $chapters = $this->splitContent($full_content);
  2321. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  2322. $messages = [];
  2323. if ($prompt == '确认分镜大纲') {
  2324. $content = $uploaded_content ?: $chapter_content;
  2325. if ((int)getProp($anime, 'is_multi') !== 1) $content = $full_content; // 单剧集使用全文
  2326. if (!$content) {
  2327. Utils::throwError('20003:章节内容无法获取,请确认');
  2328. }
  2329. $question = $demo."请根据以上要求分析本章剧情,完成分镜剧本,本章剧情内容如下: \n\n$content";
  2330. // 构建消息
  2331. $messages[] =
  2332. [
  2333. 'role' => 'user',
  2334. 'content' => $question
  2335. ];
  2336. }else if ($prompt == '继续策划下一集') {
  2337. $content = $uploaded_content ?: $chapter_content;
  2338. if (!$content) {
  2339. Utils::throwError('20003:章节内容无法获取,请确认');
  2340. }
  2341. $question = $demo."请根据以上要求分析本章剧情,完成分镜剧本(需衔接上一章内容),本章剧情内容如下: \n\n$content";
  2342. // 获取上一集最后记录
  2343. $prev_sequence = $episode_number - 1;
  2344. $messages = $this->getEpisodeChatMessages($anime_id, $prev_sequence);
  2345. // 构建消息
  2346. $messages[] =
  2347. [
  2348. 'role' => 'user',
  2349. 'content' => $question
  2350. ];
  2351. }else {
  2352. $content = $uploaded_content ?: trim((string)getProp($base_episode, 'content'));
  2353. if (!$content) {
  2354. $content = $chapter_content ?: $full_content;
  2355. }
  2356. if (!$content) {
  2357. Utils::throwError('20003:章节内容无法获取,请确认');
  2358. }
  2359. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  2360. $question = $demo . "\n请基于以上历史对话记录,重新生成第{$episode_number}集完整的新版本剧集,并严格按示例格式输出完整内容。"
  2361. . "\n\n本次修改要求如下:\n{$origin_prompt}";
  2362. $messages[] =
  2363. [
  2364. 'role' => 'user',
  2365. 'content' => $question
  2366. ];
  2367. }
  2368. $model = getProp($data, 'model', 'v3');
  2369. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  2370. $post_data = [
  2371. 'model' => $model,
  2372. 'messages' => $messages,
  2373. 'max_tokens' => 8192,
  2374. 'temperature' => 0.7,
  2375. 'frequency_penalty' => 0,
  2376. 'presence_penalty' => 0,
  2377. 'response_format' => ['type' => 'text'],
  2378. 'stream' => true // 启用流式输出
  2379. ];
  2380. $client = new Client(['timeout' => 1200, 'verify' => false]);
  2381. $response = $client->post($this->url, [
  2382. 'json' => $post_data,
  2383. 'headers' => $this->headers,
  2384. 'stream' => true // 启用流式响应
  2385. ]);
  2386. $body = $response->getBody();
  2387. $fullContent = '';
  2388. $fullReasoningContent = '';
  2389. $usage = [];
  2390. $buffer = '';
  2391. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  2392. // 逐行读取流式响应
  2393. while (!$body->eof()) {
  2394. $chunk = $body->read(1024); // 每次读取 1KB
  2395. $buffer .= $chunk;
  2396. // 按行分割
  2397. $lines = explode("\n", $buffer);
  2398. // 保留最后一个不完整的行
  2399. $buffer = array_pop($lines);
  2400. foreach ($lines as $line) {
  2401. $line = trim($line);
  2402. // 跳过空行
  2403. if (empty($line)) {
  2404. continue;
  2405. }
  2406. // dLog('deepseek')->info('收到原始行数据', ['line' => $line]);
  2407. // 检查是否是 SSE 数据行
  2408. if (strpos($line, 'data: ') !== 0) {
  2409. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  2410. continue;
  2411. }
  2412. $data = substr($line, 6); // 移除 "data: " 前缀
  2413. if ($data === '[DONE]') {
  2414. dLog('deepseek')->info('收到结束标记');
  2415. break 2; // 跳出两层循环
  2416. }
  2417. try {
  2418. $json = json_decode($data, true);
  2419. if (json_last_error() !== JSON_ERROR_NONE) {
  2420. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  2421. continue;
  2422. }
  2423. // dLog('deepseek')->info('成功解析 JSON', ['has_choices' => isset($json['choices'])]);
  2424. if (isset($json['choices'][0]['delta'])) {
  2425. $delta = $json['choices'][0]['delta'];
  2426. // 处理思维链内容(仅 deepseek-reasoner 模型)
  2427. // 注释掉以下内容则不返回d思维链内容
  2428. if (isset($delta['reasoning_content'])) {
  2429. $fullReasoningContent .= $delta['reasoning_content'];
  2430. // dLog('deepseek')->info('输出思维链内容', ['length' => strlen($delta['reasoning_content'])]);
  2431. yield [
  2432. 'type' => 'reasoning',
  2433. 'content' => $delta['reasoning_content'],
  2434. 'full_reasoning' => $fullReasoningContent
  2435. ];
  2436. }
  2437. // 处理最终回答内容
  2438. if (isset($delta['content'])) {
  2439. $fullContent .= $delta['content'];
  2440. // dLog('deepseek')->info('输出回答内容', ['length' => strlen($delta['content'])]);
  2441. yield [
  2442. 'type' => 'content',
  2443. 'content' => $delta['content'],
  2444. 'full_content' => $fullContent
  2445. ];
  2446. }
  2447. }
  2448. // 获取使用统计信息
  2449. if (isset($json['usage'])) {
  2450. $usage = $json['usage'];
  2451. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  2452. }
  2453. } catch (\Exception $e) {
  2454. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  2455. continue;
  2456. }
  2457. }
  2458. }
  2459. dLog('deepseek')->info('流式读取完成', [
  2460. 'content_length' => strlen($fullContent),
  2461. 'reasoning_length' => strlen($fullReasoningContent)
  2462. ]);
  2463. dLog('deepseek')->info('完整内容: '.$fullContent);
  2464. // 处理完整内容并返回最终结果
  2465. $episode_arr = handleEpisodeContent($fullContent);
  2466. if (empty($episode_arr['acts'])) {
  2467. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  2468. yield [
  2469. 'type' => 'done',
  2470. 'episode' => [],
  2471. 'answer' => $fullContent,
  2472. 'reasoning' => $fullReasoningContent,
  2473. 'usage' => $usage
  2474. ];
  2475. return;
  2476. }
  2477. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  2478. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  2479. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  2480. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  2481. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  2482. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  2483. $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  2484. $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  2485. // dLog('deepseek')->info('修改后的数据: ', [$merged_roles, $merged_scenes]);
  2486. // exit();
  2487. $now = date('Y-m-d H:i:s');
  2488. try {
  2489. DB::beginTransaction();
  2490. $version_count = DB::table('mp_anime_episodes')
  2491. ->where('anime_id', $anime_id)
  2492. ->where('episode_number', $episode_number)
  2493. ->count('id');
  2494. $episode = [
  2495. 'anime_id' => $anime_id,
  2496. 'episode_number' => $episode_number,
  2497. 'title' => getProp($episode_arr, 'episode_title'),
  2498. 'content' => $content,
  2499. 'intro' => getProp($episode_arr, 'intro'),
  2500. 'art_style' => getProp($episode_arr, 'art_style'),
  2501. 'roles' => json_encode($merged_roles, 256),
  2502. 'scenes' => json_encode($merged_scenes, 256),
  2503. 'generate_status' => '待执行',
  2504. 'generate_at' => $now,
  2505. 'is_default' => 1,
  2506. 'updated_at' => $now,
  2507. ];
  2508. if ($is_regenerate_version) {
  2509. DB::table('mp_anime_episodes')
  2510. ->where('anime_id', $anime_id)
  2511. ->where('episode_number', $episode_number)
  2512. ->update(['is_default' => 0, 'updated_at' => $now]);
  2513. $episode['sequence'] = $version_count + 1;
  2514. $episode['created_at'] = $now;
  2515. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  2516. if (!$episode_id) {
  2517. Utils::throwError('20003:创建剧集版本失败');
  2518. }
  2519. } else {
  2520. $target_episode = $current_episode ?: $base_episode;
  2521. if ($target_episode) {
  2522. $episode_id = getProp($target_episode, 'id');
  2523. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  2524. DB::table('mp_anime_episodes')
  2525. ->where('anime_id', $anime_id)
  2526. ->where('episode_number', $episode_number)
  2527. ->where('id', '<>', $episode_id)
  2528. ->update(['is_default' => 0, 'updated_at' => $now]);
  2529. $boolen2 = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  2530. if ($boolen2 === false) {
  2531. Utils::throwError('20003:分集内容保存失败');
  2532. }
  2533. } else {
  2534. DB::table('mp_anime_episodes')
  2535. ->where('anime_id', $anime_id)
  2536. ->where('episode_number', $episode_number)
  2537. ->update(['is_default' => 0, 'updated_at' => $now]);
  2538. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  2539. $episode['created_at'] = $now;
  2540. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  2541. if (!$episode_id) {
  2542. Utils::throwError('20003:分集内容保存失败');
  2543. }
  2544. }
  2545. }
  2546. $segments = [];
  2547. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  2548. foreach ($acts as $act) {
  2549. $act_segments = getProp($act, 'segments', []);
  2550. if (!is_array($act_segments)) {
  2551. continue;
  2552. }
  2553. foreach ($act_segments as $segment) {
  2554. $segments[] = [
  2555. 'anime_id' => $anime_id,
  2556. 'episode_id' => $episode_id,
  2557. 'episode_number' => $episode_number,
  2558. 'act_number' => getProp($act, 'act_number'),
  2559. 'act_title' => getProp($act, 'act_title'),
  2560. 'segment_id' => getProp($segment, 'segment_id'),
  2561. 'segment_number' => getProp($segment, 'segment_number'),
  2562. 'segment_content' => getProp($segment, 'segment_content'),
  2563. 'description' => getProp($segment, 'description'),
  2564. 'composition' => getProp($segment, 'composition'),
  2565. 'camera_movement' => getProp($segment, 'camera_movement'),
  2566. 'voice_actor' => getProp($segment, 'voice_actor'),
  2567. 'dialogue' => getProp($segment, 'dialogue'),
  2568. 'frame_type' => getProp($segment, 'frame_type'),
  2569. 'scene' => getProp($segment, 'scene'),
  2570. 'characters' => getProp($segment, 'characters'),
  2571. 'created_at' => $now,
  2572. 'updated_at' => $now
  2573. ];
  2574. }
  2575. }
  2576. if ($segments) {
  2577. $boolen3 = DB::table('mp_episode_segments')->insert($segments);
  2578. if (!$boolen3) {
  2579. Utils::throwError('20003:分镜内容保存失败');
  2580. }
  2581. }
  2582. $record_content = $origin_prompt;
  2583. if ($uploaded_content !== '') {
  2584. $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  2585. }
  2586. $records = [
  2587. [
  2588. 'uid' => $uid,
  2589. 'anime_id' => $anime_id,
  2590. 'role' => 'user',
  2591. 'content' => $record_content,
  2592. 'sequence' => $episode_number,
  2593. 'episode_id' => $episode_id,
  2594. 'created_at' => $now,
  2595. 'updated_at' => $now
  2596. ],
  2597. [
  2598. 'uid' => $uid,
  2599. 'anime_id' => $anime_id,
  2600. 'role' => 'assistant',
  2601. 'content' => $fullContent,
  2602. 'sequence' => $episode_number,
  2603. 'episode_id' => $episode_id,
  2604. 'created_at' => $now,
  2605. 'updated_at' => $now
  2606. ]
  2607. ];
  2608. $boolen4 = DB::table('mp_anime_records')->insert($records);
  2609. if (!$boolen4) {
  2610. Utils::throwError('20003:对话记录保存失败');
  2611. }
  2612. }catch (\Exception $e) {
  2613. DB::rollBack();
  2614. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  2615. yield [
  2616. 'type' => 'done',
  2617. 'answer' => $fullContent,
  2618. 'reasoning' => $fullReasoningContent,
  2619. 'usage' => $usage,
  2620. 'error' => $e->getMessage(),
  2621. ];
  2622. return;
  2623. }
  2624. DB::commit();
  2625. if ($is_global_generate_pics) {
  2626. // 批量生成全局角色图片
  2627. $this->batchSetGlobalRoleImg([
  2628. 'anime_id' => $anime_id,
  2629. 'episode_number' => $episode_number
  2630. ]);
  2631. // 批量生成全局场景图片
  2632. $this->batchSetGlobalSceneImg([
  2633. 'anime_id' => $anime_id,
  2634. 'episode_number' => $episode_number
  2635. ]);
  2636. }
  2637. $episode['episode_id'] = $episode_id;
  2638. $episode['roles'] = $merged_roles;
  2639. $episode['scenes'] = $merged_scenes;
  2640. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  2641. yield [
  2642. 'type' => 'done',
  2643. 'episode' => $episode,
  2644. 'answer' => $fullContent,
  2645. 'reasoning' => $fullReasoningContent,
  2646. 'usage' => $usage
  2647. ];
  2648. }
  2649. private function buildEpisodeItemContent(array $items, string $nameKey): string
  2650. {
  2651. $content = '';
  2652. foreach ($items as $item) {
  2653. $name = trim((string)getProp($item, $nameKey));
  2654. if ($name === '') {
  2655. continue;
  2656. }
  2657. $description = trim((string)getProp($item, 'description'));
  2658. $content .= $name . ': ' . $description . "\n";
  2659. }
  2660. return trim($content);
  2661. }
  2662. private function getEpisodeChatMessages($animeId, $sequence): array
  2663. {
  2664. if ((int)$sequence <= 0) {
  2665. return [];
  2666. }
  2667. return DB::table('mp_anime_records')
  2668. ->where('anime_id', $animeId)
  2669. ->where('sequence', $sequence)
  2670. ->select('role', 'content')
  2671. ->orderBy('created_at')
  2672. ->orderBy('id')
  2673. ->get()
  2674. ->map(function ($value) {
  2675. return (array)$value;
  2676. })
  2677. ->toArray();
  2678. }
  2679. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  2680. {
  2681. $existingMap = [];
  2682. foreach ($existingItems as $item) {
  2683. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  2684. if ($itemKey === '') {
  2685. continue;
  2686. }
  2687. $existingMap[$itemKey] = $item;
  2688. }
  2689. if (!$generatedItems) {
  2690. return array_values($existingItems);
  2691. }
  2692. $merged = [];
  2693. foreach ($generatedItems as $item) {
  2694. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  2695. if ($itemKey === '') {
  2696. continue;
  2697. }
  2698. if (isset($existingMap[$itemKey])) {
  2699. if (trim((string)getProp($item, 'description')) === '') {
  2700. $merged[] = $existingMap[$itemKey];
  2701. continue;
  2702. }
  2703. if (!$this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey)) {
  2704. $merged[] = $existingMap[$itemKey];
  2705. continue;
  2706. }
  2707. }
  2708. // 重置资源项,并尝试从现有项中继承URL
  2709. $resetItem = $this->resetEpisodeResourceItem($item, $nameKey);
  2710. // 如果现有项存在且有URL,而生成项没有URL,则继承现有URL
  2711. if (isset($existingMap[$itemKey])) {
  2712. $existingUrl = getProp($existingMap[$itemKey], 'url');
  2713. $generatedUrl = getProp($item, 'url');
  2714. // 条件:1.现有URL存在 2.生成URL不存在 3.名称和描述一致(已通过itemKey和上面的逻辑保证)
  2715. if (!empty($existingUrl) && empty($generatedUrl)) {
  2716. $resetItem['url'] = $existingUrl;
  2717. }
  2718. }
  2719. $merged[] = $resetItem;
  2720. }
  2721. return $merged ?: array_values($existingItems);
  2722. }
  2723. private function resetEpisodeResourceItem(array $item, string $nameKey): array
  2724. {
  2725. $resetItem = [
  2726. $nameKey => trim((string)getProp($item, $nameKey)),
  2727. 'description' => trim((string)getProp($item, 'description')),
  2728. ];
  2729. // 如果生成项本身有URL,保留它
  2730. $url = getProp($item, 'url');
  2731. if (!empty($url)) {
  2732. $resetItem['url'] = $url;
  2733. }
  2734. return $resetItem;
  2735. }
  2736. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  2737. {
  2738. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  2739. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  2740. if ($existingKey !== $generatedKey) {
  2741. return true;
  2742. }
  2743. return trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'));
  2744. }
  2745. private function normalizeEpisodeResourceKey($value): string
  2746. {
  2747. $value = trim((string)$value);
  2748. if ($value === '') {
  2749. return '';
  2750. }
  2751. return strtolower((string)preg_replace('/\s+/u', '', $value));
  2752. }
  2753. // 生成全局角色图片
  2754. private function batchSetGlobalRoleImg($data) {
  2755. $anime_id = getProp($data, 'anime_id');
  2756. $episode_number = getProp($data, 'episode_number');
  2757. if (!$anime_id) Utils::throwError('1002:请选择对话');
  2758. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  2759. $roles = json_decode(getProp($anime, 'roles'), true);
  2760. $art_style = getProp($anime, 'art_style');
  2761. foreach ($roles as &$role) {
  2762. $role_name = getProp($role, 'role');
  2763. $description = getProp($role, 'description');
  2764. if ($art_style) $description = "美术风格:\n$art_style\n主体描述:$description";
  2765. // 参考图地址
  2766. $ref_img_url = getProp($role, 'url');
  2767. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  2768. try {
  2769. $params = [
  2770. 'prompt' => $description,
  2771. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  2772. ];
  2773. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2774. $task_id = $task->id;
  2775. if (!$task_id) {
  2776. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  2777. }
  2778. $role['task_id'] = $task_id;
  2779. $role['task_status'] = 'processing';
  2780. } catch (\Exception $e) {
  2781. Utils::throwError("20003:" . $e->getMessage());
  2782. }
  2783. }
  2784. // 保存角色信息
  2785. // $boolen = DB::table('mp_animes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->update([
  2786. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  2787. 'roles' => json_encode($roles, 256),
  2788. 'generate_status' => '执行中',
  2789. 'generate_at' => date('Y-m-d H:i:s'),
  2790. 'updated_at' => date('Y-m-d H:i:s')
  2791. ]);
  2792. if (!$boolen) {
  2793. Utils::throwError('20003:保存角色信息失败');
  2794. }
  2795. return $boolen;
  2796. }
  2797. // 生成全局场景图片
  2798. private function batchSetGlobalSceneImg($data) {
  2799. $anime_id = getProp($data, 'anime_id');
  2800. if (!$anime_id) Utils::throwError('1002:请选择对话');
  2801. $episode_number = getProp($data, 'episode_number');
  2802. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  2803. $scenes = json_decode(getProp($anime, 'scenes'), true);
  2804. $art_style = getProp($anime, 'art_style');
  2805. foreach ($scenes as &$scene) {
  2806. $scene_name = getProp($scene, 'scene');
  2807. $description = getProp($scene, 'description');
  2808. if ($art_style) $description = "美术风格:\n$art_style\n\n场景描述:$description";
  2809. // 参考图地址
  2810. $ref_img_url = getProp($scene, 'url');
  2811. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  2812. try {
  2813. $params = [
  2814. 'prompt' => $description,
  2815. 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  2816. ];
  2817. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  2818. $task_id = $task->id;
  2819. if (!$task_id) {
  2820. Utils::throwError("20003: 角色({$scene_name})生成图片失败");
  2821. }
  2822. $scene['task_id'] = $task_id;
  2823. $scene['task_status'] = 'processing';
  2824. } catch (\Exception $e) {
  2825. Utils::throwError("20003:" . $e->getMessage());
  2826. }
  2827. }
  2828. // 保存角色信息
  2829. // $boolen = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->update([
  2830. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  2831. 'scenes' => json_encode($scenes, 256),
  2832. 'generate_status' => '执行中',
  2833. 'generate_at' => date('Y-m-d H:i:s'),
  2834. 'updated_at' => date('Y-m-d H:i:s')
  2835. ]);
  2836. if (!$boolen) {
  2837. Utils::throwError('20003:保存角色信息失败');
  2838. }
  2839. return $boolen;
  2840. }
  2841. public function chatChangeImg($data) {
  2842. $segment = getProp($data, 'segment');
  2843. $segment_content = getProp($segment, 'segment_content');
  2844. $prompt = getProp($data, 'prompt');
  2845. $ref_img = getProp($data, 'ref_img');
  2846. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  2847. $model = getProp($data, 'model', 'v3');
  2848. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  2849. $messages[] =
  2850. [
  2851. 'role' => 'user',
  2852. 'content' => $question
  2853. ];
  2854. $post_data = [
  2855. 'model' => $model,
  2856. 'messages' => $messages,
  2857. 'max_tokens' => 8192,
  2858. 'temperature' => 0.7,
  2859. 'frequency_penalty' => 0,
  2860. 'presence_penalty' => 0,
  2861. 'response_format' => ['type' => 'text'],
  2862. 'stream' => false // 是否启用流式输出
  2863. ];
  2864. // 调用流式输出的deepseek
  2865. $chatResult = $this->chatOnly($post_data);
  2866. if (is_array($chatResult)) {
  2867. extract($chatResult);
  2868. }else {
  2869. Utils::throwError('20003: 接口调用失败!');
  2870. }
  2871. return [
  2872. 'type' => 'done',
  2873. // 'episode' => $episode,
  2874. 'answer' => $fullContent,
  2875. 'reasoning' => $fullReasoningContent,
  2876. 'usage' => $usage
  2877. ];
  2878. }
  2879. // 仅调用deepseek对话接口
  2880. private function chatOnly($post_data) {
  2881. $client = new Client(['timeout' => 1200, 'verify' => false]);
  2882. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  2883. $response = $result->getBody()->getContents();
  2884. $response_arr = json_decode($response, true);
  2885. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  2886. $fullContent = '';
  2887. $fullReasoningContent = [];
  2888. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  2889. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  2890. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  2891. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  2892. }
  2893. return [
  2894. 'fullContent' => $fullContent,
  2895. 'fullReasoningContent' => $fullReasoningContent,
  2896. 'usage' => $usage
  2897. ];
  2898. }
  2899. private function splitContent($content) {
  2900. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  2901. $chapters = [];
  2902. // 匹配不同格式的章节标题:###第X章、##第X章、第X章
  2903. $pattern = '/^(#{0,3}\s*第[^章]*章[^\n]*)\n(.*?)(?=\n#{0,3}\s*第[^章]*章|\z)/ms';
  2904. if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
  2905. foreach ($matches as $match) {
  2906. $title = trim($match[1], "# \t\n\r\0\x0B"); // 去除标题前的#号和空白字符
  2907. $chapterContent = trim($match[2]); // 去除内容前后的空白字符
  2908. if (!empty($title) && !empty($chapterContent)) {
  2909. $chapters[] = [
  2910. 'title' => $title,
  2911. 'content' => $chapterContent
  2912. ];
  2913. }
  2914. }
  2915. }
  2916. return $chapters;
  2917. }
  2918. public function getContentByBid($bid) {
  2919. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  2920. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  2921. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  2922. $content = '';
  2923. foreach ($chapters as $chapter) {
  2924. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  2925. }
  2926. return $content;
  2927. }
  2928. /**
  2929. * 根据文件类型提取文本内容
  2930. *
  2931. * @param mixed $file 文件对象或文件路径
  2932. * @return string
  2933. */
  2934. public function extractFileContent($file) {
  2935. // 获取文件路径和扩展名
  2936. if (is_string($file)) {
  2937. $filePath = $file;
  2938. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  2939. } else {
  2940. // Laravel UploadedFile 对象
  2941. $filePath = $file->getRealPath();
  2942. $extension = strtolower($file->getClientOriginalExtension());
  2943. }
  2944. $content = '';
  2945. switch ($extension) {
  2946. case 'txt':
  2947. $content = $this->extractTxtContent($filePath);
  2948. break;
  2949. case 'pdf':
  2950. $content = $this->extractPdfContent($filePath);
  2951. break;
  2952. case 'doc':
  2953. case 'docx':
  2954. $content = $this->extractWordContent($filePath);
  2955. break;
  2956. // case 'jpg':
  2957. // case 'jpeg':
  2958. // case 'png':
  2959. // case 'gif':
  2960. // case 'bmp':
  2961. // case 'webp':
  2962. // $content = $this->extractImageContent($filePath);
  2963. // break;
  2964. default:
  2965. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  2966. }
  2967. return $content;
  2968. }
  2969. /**
  2970. * 提取 TXT 文件内容
  2971. */
  2972. private function extractTxtContent($filePath) {
  2973. if (!file_exists($filePath)) {
  2974. Utils::throwError('20003:文件不存在');
  2975. }
  2976. $content = file_get_contents($filePath);
  2977. // 尝试检测并转换编码
  2978. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  2979. if ($encoding && $encoding !== 'UTF-8') {
  2980. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  2981. }
  2982. return trim($content);
  2983. }
  2984. /**
  2985. * 提取 PDF 文件内容
  2986. */
  2987. private function extractPdfContent($filePath) {
  2988. if (!file_exists($filePath)) {
  2989. Utils::throwError('20003:文件不存在');
  2990. }
  2991. try {
  2992. $parser = new PdfParser();
  2993. $pdf = $parser->parseFile($filePath);
  2994. $content = $pdf->getText();
  2995. return trim($content);
  2996. } catch (\Exception $e) {
  2997. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  2998. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  2999. }
  3000. }
  3001. /**
  3002. * 提取 Word 文件内容(支持 doc 和 docx)
  3003. */
  3004. private function extractWordContent($filePath) {
  3005. if (!file_exists($filePath)) {
  3006. Utils::throwError('20003:文件不存在');
  3007. }
  3008. try {
  3009. $phpWord = WordIOFactory::load($filePath);
  3010. $content = '';
  3011. foreach ($phpWord->getSections() as $section) {
  3012. foreach ($section->getElements() as $element) {
  3013. $content .= $this->extractWordElementText($element);
  3014. }
  3015. }
  3016. return trim($content);
  3017. } catch (\Exception $e) {
  3018. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  3019. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  3020. }
  3021. }
  3022. /**
  3023. * 递归提取 Word 元素中的文本
  3024. */
  3025. private function extractWordElementText($element) {
  3026. $text = '';
  3027. if (method_exists($element, 'getText')) {
  3028. $text .= $element->getText() . "\n";
  3029. } elseif (method_exists($element, 'getElements')) {
  3030. foreach ($element->getElements() as $childElement) {
  3031. $text .= $this->extractWordElementText($childElement);
  3032. }
  3033. }
  3034. return $text;
  3035. }
  3036. /**
  3037. * 提取图片内容(使用火山引擎 OCR)
  3038. */
  3039. private function extractImageContent($filePath) {
  3040. if (!file_exists($filePath)) {
  3041. Utils::throwError('20003:文件不存在');
  3042. }
  3043. try {
  3044. // 读取图片并转换为 base64
  3045. $imageData = file_get_contents($filePath);
  3046. $base64Image = base64_encode($imageData);
  3047. // 调用火山引擎 OCR 服务
  3048. $content = $this->callVolcEngineOCR($base64Image);
  3049. return trim($content);
  3050. } catch (\Exception $e) {
  3051. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  3052. Utils::throwError('20003:图片识别失败');
  3053. }
  3054. }
  3055. /**
  3056. * 调用火山引擎 OCR 服务识别图片文字
  3057. *
  3058. * @param string $base64Image base64 编码的图片数据
  3059. * @return string 识别的文字内容
  3060. */
  3061. private function callVolcEngineOCR($base64Image) {
  3062. $method = 'POST';
  3063. $service = 'cv';
  3064. $host = 'visual.volcengineapi.com';
  3065. $region = env('VOLC_REGION', 'cn-north-1');
  3066. $access_key = env('VOLC_AK');
  3067. $secret_key = env('VOLC_SK');
  3068. $action = 'OCRNormal';
  3069. $version = '2020-08-26';
  3070. if (!$access_key || !$secret_key) {
  3071. Utils::throwError('20003:请配置火山引擎 AK/SK');
  3072. }
  3073. // 请求体
  3074. $body = json_encode([
  3075. 'image_base64' => $base64Image
  3076. ]);
  3077. // 生成签名
  3078. $headers = $this->getVolcEngineSignHeaders(
  3079. $method, $service, $host, $region,
  3080. "Action={$action}&Version={$version}",
  3081. $access_key, $secret_key, $body
  3082. );
  3083. $client = new Client(['timeout' => 60, 'verify' => false]);
  3084. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  3085. 'headers' => $headers,
  3086. 'body' => $body
  3087. ]);
  3088. $response_arr = json_decode($response->getBody()->getContents(), true);
  3089. // 提取识别的文字
  3090. $textLines = [];
  3091. if (isset($response_arr['data']['line_texts'])) {
  3092. $textLines = $response_arr['data']['line_texts'];
  3093. } elseif (isset($response_arr['data']['ocr_infos'])) {
  3094. foreach ($response_arr['data']['ocr_infos'] as $info) {
  3095. if (isset($info['text'])) {
  3096. $textLines[] = $info['text'];
  3097. }
  3098. }
  3099. }
  3100. if (empty($textLines)) {
  3101. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  3102. return '';
  3103. }
  3104. return implode("\n", $textLines);
  3105. }
  3106. /**
  3107. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  3108. */
  3109. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  3110. $contentType = 'application/json';
  3111. $accept = 'application/json';
  3112. // 获取当前UTC时间
  3113. $t = new DateTime('now', new DateTimeZone('UTC'));
  3114. $xDate = $t->format('Ymd\THis\Z');
  3115. $dateStamp = $t->format('Ymd');
  3116. // 计算 body 的 sha256 哈希
  3117. $payloadHash = hash('sha256', $body);
  3118. // 1. 拼接规范请求串
  3119. $canonicalUri = '/';
  3120. $canonicalQueryString = $queryString;
  3121. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  3122. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  3123. $canonicalRequest = implode("\n", [
  3124. $method,
  3125. $canonicalUri,
  3126. $canonicalQueryString,
  3127. $canonicalHeaders,
  3128. $signedHeaders,
  3129. $payloadHash
  3130. ]);
  3131. // 2. 拼接待签名字符串
  3132. $algorithm = 'HMAC-SHA256';
  3133. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  3134. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  3135. $stringToSign = implode("\n", [
  3136. $algorithm,
  3137. $xDate,
  3138. $credentialScope,
  3139. $hashedCanonicalRequest
  3140. ]);
  3141. // 3. 计算签名
  3142. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  3143. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  3144. // 4. 添加签名到请求头
  3145. $authorizationHeader = sprintf(
  3146. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  3147. $algorithm,
  3148. $access_key,
  3149. $credentialScope,
  3150. $signedHeaders,
  3151. $signature
  3152. );
  3153. return [
  3154. 'Accept' => $accept,
  3155. 'Content-Type' => $contentType,
  3156. 'Host' => $host,
  3157. 'X-Date' => $xDate,
  3158. 'X-Content-Sha256'=> $payloadHash,
  3159. 'Authorization' => $authorizationHeader
  3160. ];
  3161. }
  3162. public function generateScriptWords($cid, $model = 'r1') {
  3163. ini_set('max_execution_time', 0);
  3164. if (!$cid) Utils::throwError('20003: 请选择章节!');
  3165. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  3166. $model = $model == 'r1' ? 'deepseek-reasoner' : 'deepseek-chat';
  3167. $messages = [
  3168. [
  3169. 'role' => 'system',
  3170. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  3171. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  3172. 2.非对话部分请全部用旁白角色代替
  3173. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  3174. ],
  3175. [
  3176. 'role' => 'user',
  3177. 'content' => $content
  3178. ]
  3179. ];
  3180. $post_data = [
  3181. 'model' => $model, // R1模型: deepseek-reasoner V3模型: deepseek-chat
  3182. 'messages' => $messages,
  3183. 'max_tokens' => 8192,
  3184. 'temperature' => 1, // 采样温度,介于 0 和 2 之间。更高的值,如 0.8,会使输出更随机,而更低的值,如 0.2,会使其更加集中和确定。 我们通常建议可以更改这个值或者更改 top_p,但不建议同时对两者进行修改。
  3185. // 'top_p' => 1, // 作为调节采样温度的替代方案(<=1),模型会考虑前 top_p 概率的 token 的结果。所以 0.1 就意味着只有包括在最高 10% 概率中的 token 会被考虑。 我们通常建议修改这个值或者更改 temperature,但不建议同时对两者进行修改。
  3186. 'frequency_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其在已有文本中的出现频率受到相应的惩罚,降低模型重复相同内容的可能性。
  3187. 'presence_penalty' => 0, // 介于 -2.0 和 2.0 之间的数字。如果该值为正,那么新 token 会根据其是否已在已有文本中出现受到相应的惩罚,从而增加模型谈论新主题的可能性。
  3188. 'response_format' => [
  3189. 'type' => 'text' // 默认值text,回答的结果输出文字(非接口返回值是text,接口返回值还是json字串),还可选:json_object,输出json格式
  3190. ],
  3191. 'stream' => false // 是否流式输出,如果设置为 True,将会以 SSE(server-sent events)的形式以流式发送消息增量。消息流以 data: [DONE] 结尾。
  3192. ];
  3193. $client = new Client(['timeout' => 1200, 'verify' => false]);
  3194. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  3195. $response = $result->getBody()->getContents();
  3196. $response_arr = json_decode($response, true);
  3197. $update_data = [];
  3198. $content = '';
  3199. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  3200. $content = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  3201. $update_data = [
  3202. 'role' => 'assistant',
  3203. 'content' => $response_arr['choices'][0]['message']['content'],
  3204. 'usage' => isset($response_arr['usage']) ? $response_arr['usage'] : []
  3205. ];
  3206. }
  3207. return $content;
  3208. }
  3209. /**
  3210. * 智能化解析集数信息
  3211. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  3212. *
  3213. * @param string $prompt 用户输入的提示词
  3214. * @return int|null 解析出的集数,如果没有找到则返回null
  3215. */
  3216. private function extractEpisodeNumber($prompt)
  3217. {
  3218. if (empty($prompt)) {
  3219. return null;
  3220. }
  3221. // 定义各种可能的表达模式
  3222. $patterns = [
  3223. // 基本模式:改成N集、调整成N集、修改成N集
  3224. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  3225. // 扩展模式:分成N集、拆分成N集、分割成N集
  3226. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  3227. // 数量模式:N集、共N集、总共N集
  3228. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  3229. // 制作模式:制作N集、生成N集、创建N集
  3230. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  3231. // 计划模式:计划N集、预计N集、打算N集
  3232. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  3233. // 需要模式:需要N集、要N集
  3234. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  3235. // 中文数字模式:改成三集、调整成五集等
  3236. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  3237. // 英文数字模式
  3238. '/(?: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',
  3239. ];
  3240. // 中文数字转阿拉伯数字的映射
  3241. $chineseNumbers = [
  3242. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  3243. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  3244. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  3245. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  3246. ];
  3247. // 逐个尝试匹配模式
  3248. foreach ($patterns as $pattern) {
  3249. if (preg_match($pattern, $prompt, $matches)) {
  3250. $number = trim($matches[1]);
  3251. // 如果是中文数字,转换为阿拉伯数字
  3252. if (isset($chineseNumbers[$number])) {
  3253. return $chineseNumbers[$number];
  3254. }
  3255. // 如果是阿拉伯数字,直接返回
  3256. if (is_numeric($number)) {
  3257. $episodeNum = intval($number);
  3258. // 合理性检查:集数应该在1-100之间
  3259. if ($episodeNum >= 1 && $episodeNum <= 100) {
  3260. return $episodeNum;
  3261. }
  3262. }
  3263. }
  3264. }
  3265. return null;
  3266. }
  3267. }