DeepSeekService.php 170 KB

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