DeepSeekService.php 284 KB

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