DeepSeekService.php 288 KB

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