DeepSeekService.php 176 KB

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