DeepSeekService.php 329 KB

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