DeepSeekService.php 264 KB

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