DeepSeekService.php 651 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687
  1. <?php
  2. namespace App\Services\DeepSeek;
  3. use App\Consts\ErrorConst;
  4. use App\Consts\BaseConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use GuzzleHttp\Client;
  8. use DateTime;
  9. use DateTimeZone;
  10. use App\Services\AIGeneration\AIImageGenerationService;
  11. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Log;
  13. use Illuminate\Support\Facades\Redis;
  14. use OSS\Core\OssException;
  15. use OSS\OssClient;
  16. use Smalot\PdfParser\Parser as PdfParser;
  17. use TCPDF;
  18. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  19. use Predis\Command\Traits\Get\Get;
  20. class DeepSeekService
  21. {
  22. private $url;
  23. private $api_key;
  24. private $sys_message;
  25. private $headers;
  26. private $valid_text_models;
  27. private $gpt_text_models;
  28. protected $aiImageGenerationService;
  29. public function __construct(AIImageGenerationService $aiImageGenerationService) {
  30. $this->aiImageGenerationService = $aiImageGenerationService;
  31. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  32. $this->api_key = env('DEEPSEEK_API_KEY');
  33. $this->headers = [
  34. 'Authorization' => 'Bearer '.$this->api_key,
  35. 'Content-Type' => 'application/json; charset=UTF-8'
  36. ];
  37. // 火山引擎模型列表
  38. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  39. // GPT文本模型列表
  40. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  41. $this->sys_message = [
  42. 'role' => 'system',
  43. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  44. 强制要求:\n
  45. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  46. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  47. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  48. 普通要求:\n
  49. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  50. 2.<分集剧本>的要求如下:
  51.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  52.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  53.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  54.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  55. \n\n
  56. 示例如下:\n
  57. ###剧本名:西昆仑
  58. ###故事梗概
  59. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  60. ###剧本亮点
  61. 亮点1:绝境奇药,生死一线
  62. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  63. 亮点2:结拜兄妹,化解尴尬
  64. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  65. 亮点3:纤发夺命,情愫暗涌
  66. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  67. ###人物关系
  68. 阿雪与梁萧之间存在兄妹之情。
  69. ###核心矛盾
  70. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  71. ###主体列表
  72. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  73. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  74. 阴阳球:天地异宝,能化生精气,救人于危难。
  75. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  76. ###美术风格
  77. 基础画风风格词:厚涂古风
  78. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  79. ###场景列表
  80. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  81. ###分集剧本
  82. ##分集01
  83. 第1集: 第一集的标题
  84. 场景描述:地点、时间、场景
  85. 运镜:固定近距离
  86. 出场角色:男主、女主
  87. 台词内容:
  88. 女主: 女主对话
  89. 男主:男主对话
  90. 女主: 女主对话
  91. 男主: 男主对话
  92. ##分集02
  93. 第2集: 第二集的标题
  94. 场景描述:地点、时间、场景
  95. 运镜:固定近距离
  96. 出场角色:男主、女主
  97. 台词内容:
  98. 女主: 女主对话
  99. 男主:男主对话
  100. 女主: 女主对话
  101. 男主: 男主对话"
  102. ];
  103. }
  104. /**
  105. * 通用文生文方法 - 支持多模型流式输出和图片输入
  106. *
  107. * @param array $data 请求参数
  108. * @return \Generator 返回生成器,用于流式输出
  109. */
  110. public function generateText($data) {
  111. // 获取请求参数
  112. $model = getProp($data, 'model', 'deepseek-v3-2-251201'); // 默认使用deepseek-v3
  113. $messages = getProp($data, 'messages', []);
  114. $systemPrompt = getProp($data, 'system_prompt', '');
  115. $prompt = getProp($data, 'prompt', '');
  116. $images = getProp($data, 'images', []); // 支持多张图片
  117. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  118. // 如果没有提供messages,则根据system_prompt、content和images构建
  119. if (empty($messages)) {
  120. $messages = [];
  121. // 添加系统提示词
  122. if (!empty($systemPrompt)) {
  123. $messages[] = [
  124. 'role' => 'system',
  125. 'content' => $systemPrompt
  126. ];
  127. }
  128. // 构建用户消息内容(支持文本+图片)
  129. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  130. $userMessage = [
  131. 'role' => 'user',
  132. 'content' => []
  133. ];
  134. // 添加文本内容
  135. if (!empty($prompt)) {
  136. $userMessage['content'][] = [
  137. 'type' => 'text',
  138. 'text' => $prompt
  139. ];
  140. }
  141. // 处理上传的图片文件
  142. if (!empty($images)) {
  143. if (!is_array($images)) {
  144. $images = [$images];
  145. }
  146. foreach ($images as $image) {
  147. $imageBase64 = $this->processImageToBase64($image);
  148. if ($imageBase64) {
  149. $userMessage['content'][] = [
  150. 'type' => 'image_url',
  151. 'image_url' => [
  152. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  153. ]
  154. ];
  155. }
  156. }
  157. }
  158. // 处理图片URL
  159. if (!empty($imageUrls)) {
  160. if (!is_array($imageUrls)) {
  161. $imageUrls = [$imageUrls];
  162. }
  163. foreach ($imageUrls as $url) {
  164. if (!empty($url)) {
  165. $userMessage['content'][] = [
  166. 'type' => 'image_url',
  167. 'image_url' => [
  168. 'url' => $url
  169. ]
  170. ];
  171. }
  172. }
  173. }
  174. // 如果只有文本内容,简化为字符串格式
  175. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  176. $userMessage['content'] = $userMessage['content'][0]['text'];
  177. }
  178. $messages[] = $userMessage;
  179. }
  180. }
  181. // 验证messages不为空
  182. if (empty($messages)) {
  183. Utils::throwError('20003:请提供有效的对话内容');
  184. }
  185. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  186. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  187. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  188. if ($model === 'deepseek-chat') {
  189. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  190. $model = 'deepseek-v4-flash';
  191. $thinkingMode = 'disabled';
  192. } elseif ($model === 'deepseek-reasoner') {
  193. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  194. $model = 'deepseek-v4-flash';
  195. $thinkingMode = 'enabled';
  196. }
  197. // 构建请求参数
  198. $post_data = [
  199. 'model' => $model,
  200. 'messages' => $messages,
  201. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  202. 'temperature' => getProp($data, 'temperature', 1),
  203. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  204. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  205. 'thinking' => ['type' => $thinkingMode],
  206. 'stream' => true // 启用流式输出
  207. ];
  208. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  209. // 添加可选参数
  210. if (isset($data['top_p'])) {
  211. $post_data['top_p'] = $data['top_p'];
  212. }
  213. if (isset($data['response_format'])) {
  214. $post_data['response_format'] = $data['response_format'];
  215. }
  216. // 根据模型类型选择调用方法
  217. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  218. // DeepSeek 官方模型使用 DeepSeek API
  219. return $this->deepSeekStreamResponse($post_data);
  220. } else if (in_array($model, $this->gpt_text_models)) {
  221. // GPT 模型使用 TokenRouter API
  222. return $this->gpt54StreamResponse($post_data);
  223. } else if (in_array($model, $this->valid_text_models)) {
  224. // 火山引擎支持的模型使用火山引擎 API
  225. return $this->volcEngineChatCompletion($post_data);
  226. } else {
  227. Utils::throwError('20003:不支持的模型: ' . $model);
  228. }
  229. }
  230. public function createGenerateText($data) {
  231. $file = getProp($data, 'file');
  232. $uid = Site::getUid();
  233. $cpid = Site::getCpid();
  234. if (!$file) {
  235. Utils::throwError('20003:请上传文件');
  236. }
  237. // 提取文件内容
  238. $content = $this->extractFileContent($file);
  239. if (!$content) {
  240. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  241. }
  242. // 获取原始文件名(不含扩展名)作为script_name
  243. $originalName = $file->getClientOriginalName();
  244. $script_name = pathinfo($originalName, PATHINFO_FILENAME);
  245. if (!$script_name) {
  246. $script_name = '剧本_' . date('YmdHis');
  247. }
  248. // 如果剧本名称已存在,添加时间戳后缀
  249. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('is_deleted', 0)->exists()) {
  250. $script_name .= '_' . date('YmdHis');
  251. }
  252. // 插入数据到mp_scripts表
  253. $script_id = DB::table('mp_scripts')->insertGetId([
  254. 'script_name' => $script_name,
  255. 'user_id' => $uid,
  256. 'cpid' => $cpid,
  257. 'content' => $content,
  258. 'created_at' => date('Y-m-d H:i:s'),
  259. 'updated_at' => date('Y-m-d H:i:s')
  260. ]);
  261. return [
  262. 'script_id' => $script_id,
  263. 'script_name' => $script_name
  264. ];
  265. }
  266. /**
  267. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  268. *
  269. * @param array $data 请求参数
  270. * @return array 返回结果数组
  271. */
  272. public function newGenerateText($data) {
  273. // 获取请求参数
  274. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  275. $messages = getProp($data, 'messages', []);
  276. $systemPrompt = getProp($data, 'system_prompt', '');
  277. $prompt = getProp($data, 'prompt', '');
  278. $images = getProp($data, 'images', []); // 支持多张图片
  279. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  280. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  281. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  282. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  283. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  284. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  285. $originalContent = '';
  286. if ($script_id > 0) {
  287. $script = DB::table('mp_scripts')
  288. ->where('id', $script_id)
  289. ->where('is_deleted', 0)
  290. ->first();
  291. if (!$script) {
  292. Utils::throwError('20003:剧本不存在或已删除');
  293. }
  294. $originalContent = $script->content ?? '';
  295. if (empty($originalContent)) {
  296. Utils::throwError('20003:剧本内容为空');
  297. }
  298. // 将剧本内容添加到提示词前面
  299. if (!empty($originalContent)) {
  300. if (!empty($prompt)) {
  301. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  302. } else {
  303. $prompt = "原文内容:\n" . $originalContent;
  304. }
  305. }
  306. }
  307. // 新增: 如果提供了template_id,从数据库获取template_prompt
  308. if ($templateId > 0) {
  309. $template = DB::table('mp_prompt_templates')
  310. ->where('id', $templateId)
  311. ->where('is_deleted', 0)
  312. ->first();
  313. if (!$template) {
  314. Utils::throwError('20003:模板不存在或已删除');
  315. }
  316. $templatePrompt = $template->template_prompt ?? '';
  317. // 将模板提示词和用户输入的prompt组合
  318. // 模板为准,用户输入作为补充要求
  319. if (!empty($templatePrompt)) {
  320. if (!empty($prompt)) {
  321. $prompt = $templatePrompt . "\n\n" . $prompt;
  322. } else {
  323. $prompt = $templatePrompt;
  324. }
  325. }
  326. }
  327. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  328. if (empty($messages)) {
  329. $messages = [];
  330. // 添加系统提示词
  331. if (!empty($systemPrompt)) {
  332. $messages[] = [
  333. 'role' => 'system',
  334. 'content' => $systemPrompt
  335. ];
  336. }
  337. // 构建用户消息内容(支持文本+图片)
  338. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  339. $userMessage = [
  340. 'role' => 'user',
  341. 'content' => []
  342. ];
  343. // 添加文本内容
  344. if (!empty($prompt)) {
  345. $userMessage['content'][] = [
  346. 'type' => 'text',
  347. 'text' => $prompt
  348. ];
  349. }
  350. // 处理上传的图片文件
  351. if (!empty($images)) {
  352. if (!is_array($images)) {
  353. $images = [$images];
  354. }
  355. foreach ($images as $image) {
  356. $imageBase64 = $this->processImageToBase64($image);
  357. if ($imageBase64) {
  358. $userMessage['content'][] = [
  359. 'type' => 'image_url',
  360. 'image_url' => [
  361. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  362. ]
  363. ];
  364. }
  365. }
  366. }
  367. // 处理图片URL
  368. if (!empty($imageUrls)) {
  369. if (!is_array($imageUrls)) {
  370. $imageUrls = [$imageUrls];
  371. }
  372. foreach ($imageUrls as $url) {
  373. if (!empty($url)) {
  374. $userMessage['content'][] = [
  375. 'type' => 'image_url',
  376. 'image_url' => [
  377. 'url' => $url
  378. ]
  379. ];
  380. }
  381. }
  382. }
  383. // 如果只有文本内容,简化为字符串格式
  384. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  385. $userMessage['content'] = $userMessage['content'][0]['text'];
  386. }
  387. $messages[] = $userMessage;
  388. }
  389. }
  390. // 验证messages不为空
  391. if (empty($messages)) {
  392. Utils::throwError('20003:请提供有效的对话内容');
  393. }
  394. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  395. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  396. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  397. if ($model === 'deepseek-chat') {
  398. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  399. $model = 'deepseek-v4-flash';
  400. $thinkingMode = 'disabled';
  401. } elseif ($model === 'deepseek-reasoner') {
  402. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  403. $model = 'deepseek-v4-flash';
  404. $thinkingMode = 'enabled';
  405. }
  406. // 构建请求参数(非流式)
  407. $post_data = [
  408. 'model' => $model,
  409. 'messages' => $messages,
  410. 'temperature' => getProp($data, 'temperature', 1),
  411. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  412. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  413. 'thinking' => ['type' => $thinkingMode],
  414. 'stream' => false // 非流式输出
  415. ];
  416. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  417. // 添加可选参数
  418. if (isset($data['top_p'])) {
  419. $post_data['top_p'] = $data['top_p'];
  420. }
  421. // 新增: 根据response_format设置响应格式
  422. if ($responseFormat === 'json') {
  423. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  424. $hasJsonKeyword = false;
  425. foreach ($post_data['messages'] as $message) {
  426. if (isset($message['content'])) {
  427. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  428. if (stripos($content, 'json') !== false) {
  429. $hasJsonKeyword = true;
  430. break;
  431. }
  432. }
  433. }
  434. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  435. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  436. if (!$hasJsonKeyword) {
  437. $lastMessageIndex = count($post_data['messages']) - 1;
  438. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  439. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  440. // 如果content是字符串,直接追加
  441. if (is_string($lastContent)) {
  442. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  443. }
  444. // 如果content是数组(包含文本和图片),在文本部分追加
  445. else if (is_array($lastContent)) {
  446. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  447. if ($contentPart['type'] === 'text') {
  448. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  449. break;
  450. }
  451. }
  452. }
  453. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  454. }
  455. }
  456. // 设置response_format参数(所有支持的模型)
  457. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  458. // DeepSeek模型
  459. $post_data['response_format'] = ['type' => 'json_object'];
  460. } else if (in_array($model, $this->gpt_text_models)) {
  461. // GPT模型
  462. $post_data['response_format'] = ['type' => 'json_object'];
  463. } else if (in_array($model, $this->valid_text_models)) {
  464. // 火山引擎模型
  465. $post_data['response_format'] = ['type' => 'json_object'];
  466. }
  467. }
  468. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  469. $aiResult = null;
  470. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  471. // DeepSeek 官方模型使用现有的 chatOnly 方法
  472. $result = $this->chatOnly($post_data);
  473. // 记录实际使用的模型
  474. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  475. $aiResult = [
  476. 'content' => $result['fullContent'],
  477. 'reasoning_content' => $result['fullReasoningContent'],
  478. 'usage' => $result['usage'],
  479. 'model' => $model,
  480. 'finish_reason' => 'stop'
  481. ];
  482. } else if (in_array($model, $this->gpt_text_models)) {
  483. // GPT 模型使用现有的 gpt54ChatOnly 方法
  484. $result = $this->gpt54ChatOnly($post_data);
  485. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  486. $aiResult = [
  487. 'content' => $result['fullContent'],
  488. 'reasoning_content' => '',
  489. 'usage' => $result['usage'],
  490. 'model' => $model,
  491. 'finish_reason' => 'stop'
  492. ];
  493. } else if (in_array($model, $this->valid_text_models)) {
  494. // 火山引擎支持的模型使用火山引擎 API(非流式)
  495. $post_data['stream'] = false;
  496. $result = $this->volcEngineChatCompletion($post_data);
  497. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  498. 'requested_model' => $model,
  499. 'result_keys' => array_keys($result),
  500. 'has_fullContent' => isset($result['fullContent']),
  501. 'has_content' => isset($result['content'])
  502. ]);
  503. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  504. $aiResult = [
  505. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  506. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  507. 'usage' => $result['usage'] ?? [],
  508. 'model' => $model,
  509. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  510. ];
  511. } else {
  512. Utils::throwError('20003:不支持的模型: ' . $model);
  513. }
  514. // 新增: 如果提供了script_id,保存对话记录
  515. if ($script_id > 0 && $aiResult) {
  516. try {
  517. $uid = Site::getUid();
  518. $now = now();
  519. // 获取用户原始的prompt(不包含剧本内容)
  520. $originalPrompt = getProp($data, 'prompt', '');
  521. $recordsToInsert = [
  522. [
  523. 'uid' => $uid,
  524. 'script_id' => $script_id,
  525. 'sequence' => $sequence,
  526. 'role' => 'user',
  527. 'content' => $originalPrompt,
  528. 'created_at' => $now,
  529. 'updated_at' => $now,
  530. ],
  531. [
  532. 'uid' => $uid,
  533. 'script_id' => $script_id,
  534. 'sequence' => $sequence,
  535. 'role' => 'assistant',
  536. 'content' => $aiResult['content'],
  537. 'created_at' => $now,
  538. 'updated_at' => $now,
  539. ]
  540. ];
  541. DB::table('mp_script_records')->insert($recordsToInsert);
  542. // 获取刚插入的记录ID(假设按插入顺序返回)
  543. $insertedRecords = DB::table('mp_script_records')
  544. ->where('uid', $uid)
  545. ->where('script_id', $script_id)
  546. ->where('sequence', $sequence)
  547. ->orderBy('id', 'desc')
  548. ->limit(2)
  549. ->get()
  550. ->map(function ($record) {
  551. return [
  552. 'rid' => $record->id,
  553. 'script_id' => $record->script_id,
  554. 'sequence' => $record->sequence,
  555. 'role' => $record->role,
  556. 'content' => $record->content,
  557. 'created_at' => $record->created_at,
  558. ];
  559. })
  560. ->reverse()
  561. ->values()
  562. ->toArray();
  563. // 将记录信息添加到返回结果中
  564. $aiResult['records'] = $insertedRecords;
  565. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  566. } catch (\Exception $e) {
  567. // 记录错误但不影响主流程
  568. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  569. }
  570. }
  571. return $aiResult;
  572. }
  573. public function saveScriptChatHistory($data) {
  574. $uid = Site::getUid();
  575. $rid = getProp($data, 'rid');
  576. $script_id = getProp($data, 'script_id');
  577. $sequence = getProp($data, 'sequence', 0);
  578. $content = getProp($data, 'content');
  579. if (!$rid) {
  580. Utils::throwError('20003:请选择对话记录ID');
  581. }
  582. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  583. if (!$record) {
  584. Utils::throwError('20003:对话记录不存在');
  585. }
  586. if (!$script_id) {
  587. Utils::throwError('20003:请选择剧本');
  588. }
  589. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  590. if (!$script) {
  591. Utils::throwError('20003:剧本不存在');
  592. }
  593. // 批量插入数据
  594. return DB::table('mp_script_records')->where('id', $rid)->update([
  595. 'content' => $content,
  596. 'updated_at' => date('Y-m-d H:i:s')
  597. ]);
  598. }
  599. /**
  600. * 获取剧本的历史对话记录
  601. *
  602. * @param array $data 请求参数
  603. * @return array 返回历史记录数组
  604. */
  605. public function getScriptChatHistory($data) {
  606. $uid = Site::getUid();
  607. $script_id = getProp($data, 'script_id');
  608. $rid = getProp($data, 'rid');
  609. $sequence = getProp($data, 'sequence', null);
  610. if (!$script_id) {
  611. Utils::throwError('20003:请提供剧本ID');
  612. }
  613. // 验证剧本是否存在
  614. $script = DB::table('mp_scripts')
  615. ->where('id', $script_id)
  616. ->where('is_deleted', 0)
  617. ->first();
  618. if (!$script) {
  619. Utils::throwError('20003:剧本不存在');
  620. }
  621. // 构建查询
  622. $query = DB::table('mp_script_records')
  623. ->where('script_id', $script_id);
  624. // ->where('uid', $uid);
  625. // 如果提供了 sequence,则过滤指定剧集
  626. if ($sequence !== null) {
  627. $query->where('sequence', $sequence);
  628. }
  629. // 记录ID筛选
  630. if ($rid) {
  631. $query->where('id', $rid);
  632. }
  633. // 查询记录并按 id 正序排序
  634. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  635. ->orderBy('created_at', 'asc')
  636. ->orderBy('id', 'asc')
  637. ->get()
  638. ->map(function ($record) {
  639. return [
  640. 'rid' => $record->id,
  641. 'script_id' => $record->script_id,
  642. 'sequence' => $record->sequence,
  643. 'role' => $record->role,
  644. 'content' => $record->content,
  645. 'products' => $record->products ? json_decode($record->products) : [],
  646. 'created_at' => $record->created_at,
  647. ];
  648. })
  649. ->toArray();
  650. return $records;
  651. }
  652. /**
  653. * 处理图片转换为base64
  654. *
  655. * @param mixed $image 图片文件对象或文件路径
  656. * @return string|null base64编码的图片数据
  657. */
  658. private function processImageToBase64($image) {
  659. try {
  660. // 获取文件路径
  661. if (is_string($image)) {
  662. $filePath = $image;
  663. } else {
  664. // Laravel UploadedFile 对象
  665. $filePath = $image->getRealPath();
  666. }
  667. if (!file_exists($filePath)) {
  668. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  669. return null;
  670. }
  671. // 验证是否为图片文件
  672. $imageInfo = @getimagesize($filePath);
  673. if ($imageInfo === false) {
  674. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  675. return null;
  676. }
  677. // 读取图片并转换为base64
  678. $imageData = file_get_contents($filePath);
  679. $base64Image = base64_encode($imageData);
  680. dLog('deepseek')->info('图片转换成功', [
  681. 'size' => strlen($imageData),
  682. 'type' => $imageInfo['mime']
  683. ]);
  684. return $base64Image;
  685. } catch (\Exception $e) {
  686. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  687. return null;
  688. }
  689. }
  690. private function getArtStylePromptMappings($art_style='')
  691. {
  692. $arr = [
  693. '唯美真人风格' => [
  694. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  695. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  696. ],
  697. '真人古风风格' => [
  698. 'aliases' => ['真人古风风格', '真人古风'],
  699. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  700. ],
  701. '日系动漫风格' => [
  702. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  703. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  704. ],
  705. '国漫风格' => [
  706. 'aliases' => ['国漫风格', '国漫'],
  707. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  708. ],
  709. 'Q版卡通风格' => [
  710. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  711. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  712. ],
  713. '简约扁平风格' => [
  714. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  715. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  716. ],
  717. '武侠风格' => [
  718. 'aliases' => ['武侠风格', '武侠'],
  719. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  720. ],
  721. '古风仙侠风格' => [
  722. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  723. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  724. ],
  725. '新中式水墨风格' => [
  726. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  727. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  728. ],
  729. '写实插画风格' => [
  730. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  731. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  732. ],
  733. '3D卡通风格' => [
  734. 'aliases' => ['3D卡通风格', '3D卡通'],
  735. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  736. ],
  737. '条漫风格' => [
  738. 'aliases' => ['条漫风格', '条漫'],
  739. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  740. ],
  741. '赛博朋克风格' => [
  742. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  743. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  744. ],
  745. '暗黑悬疑风格' => [
  746. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  747. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  748. ],
  749. '治愈清新风格' => [
  750. 'aliases' => ['治愈清新风格', '治愈清新'],
  751. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  752. ],
  753. ];
  754. if($art_style) {
  755. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  756. }
  757. return $arr;
  758. $arr = [
  759. '唯美真人风格' => [
  760. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  761. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  762. 2. 色彩色调
  763. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  764. 3. 画质精度
  765. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  766. 4. 画面观感
  767. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  768. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  769. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  770. ],
  771. '真人古风风格' => [
  772. 'aliases' => ['真人古风风格', '真人古风'],
  773. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  774. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  775. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  776. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  777. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  778. ],
  779. '日系动漫风格' => [
  780. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  781. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  782. 正向提示词(中文)
  783. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  784. 必须遵守规则
  785. • 全程保持日系动漫风格,不混入其他画风
  786. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  787. • 画面适配所选画面比例,构图居中,主体突出
  788. • 线条干净、色彩统一,不杂乱、不突兀
  789. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  790. ],
  791. '国漫风格' => [
  792. 'aliases' => ['国漫风格', '国漫'],
  793. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  794. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  795. 必须遵守规则
  796. • 严格保持国漫画风,不串风格、不混画风
  797. • 角色形象统一,不随意改变五官、身材、服饰
  798. • 画面构图稳定,适合漫剧叙事展示
  799. • 色调统一,不出现脏色、杂色
  800. 禁止/避免词汇
  801. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  802. ],
  803. 'Q版卡通风格' => [
  804. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  805. 'prompt' => "风格说明
  806. 头大身小,造型可爱圆润,简约干净
  807. 正向提示词(中文)
  808. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  809. 必须遵守规则
  810. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  811. • 角色造型统一,表情可爱,不诡异
  812. • 画面简洁清爽,无多余复杂元素
  813. • 色彩明亮柔和,不刺眼
  814. 禁止/避免词汇
  815. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  816. ],
  817. '简约扁平风格' => [
  818. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  819. 'prompt' => "风格说明
  820. 色块简洁、无复杂渐变,现代极简风
  821. 正向提示词(中文)
  822. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  823. 必须遵守规则
  824. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  825. • 构图简洁,主体突出,无多余装饰
  826. • 色彩统一、干净,不杂乱
  827. 禁止/避免词汇
  828. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  829. ],
  830. '武侠风格' => [
  831. 'aliases' => ['武侠风格', '武侠'],
  832. 'prompt' => "风格说明
  833. 江湖气息,线条硬朗,动作感强
  834. 正向提示词(中文)
  835. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  836. 必须遵守规则
  837. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  838. • 角色形象、服饰、身材比例统一
  839. • 画面动作自然,不扭曲、不畸形
  840. 禁止/避免词汇
  841. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  842. ],
  843. '古风仙侠风格' => [
  844. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  845. 'prompt' => "风格说明
  846. 飘逸汉服、云雾仙气、唯美空灵
  847. 正向提示词(中文)
  848. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  849. 必须遵守规则
  850. • 保持古风仙侠统一画风,不混入现代、科幻元素
  851. • 角色服饰、发型、形象前后一致
  852. • 场景仙气飘逸,色调清雅统一
  853. • 画面唯美柔和,不阴暗、不诡异
  854. 禁止/避免词汇
  855. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  856. ],
  857. '新中式水墨风格' => [
  858. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  859. 'prompt' => "风格说明
  860. 淡墨渲染,毛笔笔触,留白意境
  861. 正向提示词(中文)
  862. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  863. 必须遵守规则
  864. • 严格保持水墨质感,不混入厚涂、写实、卡通
  865. • 色调淡雅统一,不浓艳杂乱
  866. • 画面干净有意境,不堆砌元素
  867. 禁止/避免词汇
  868. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  869. ],
  870. '写实插画风格' => [
  871. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  872. 'prompt' => "风格说明
  873. 接近真人比例,光影真实,质感细腻
  874. 正向提示词(中文)
  875. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  876. 必须遵守规则
  877. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  878. • 角色五官、身材、服饰高度统一
  879. • 画面清晰、光影自然、不扭曲
  880. 禁止/避免词汇
  881. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  882. ],
  883. '3D卡通风格' => [
  884. 'aliases' => ['3D卡通风格', '3D卡通'],
  885. 'prompt' => "风格说明
  886. 3D建模质感,柔和渲染,圆润可爱
  887. 正向提示词(中文)
  888. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  889. 必须遵守规则
  890. • 保持3D卡通统一质感,不出现2D杂乱线条
  891. • 角色模型、比例、形象前后一致
  892. • 画面干净,不模糊、不穿模
  893. 禁止/避免词汇
  894. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  895. ],
  896. '条漫风格' => [
  897. 'aliases' => ['条漫风格', '条漫'],
  898. 'prompt' => "风格说明
  899. 纵向分镜,上下滑动阅读,轻量化
  900. 正向提示词(中文)
  901. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  902. 必须遵守规则
  903. • 保持条漫纵向阅读逻辑,构图简洁
  904. • 画风统一,不混写实、3D、水墨
  905. • 画面干净,不杂乱
  906. 禁止/避免词汇
  907. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  908. ],
  909. '赛博朋克风格' => [
  910. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  911. 'prompt' => "风格说明
  912. 霓虹灯光、未来都市、暗色调、科技机械
  913. 正向提示词(中文)
  914. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  915. 必须遵守规则
  916. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  917. • 色调以暗调+霓虹为主,色彩统一
  918. • 画面科技感强,不杂乱
  919. 禁止/避免词汇
  920. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  921. ],
  922. '暗黑悬疑风格' => [
  923. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  924. 'prompt' => "风格说明
  925. 低饱和、冷色调、阴影重、神秘压抑
  926. 正向提示词(中文)
  927. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  928. 必须遵守规则
  929. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  930. • 画面氛围压抑神秘,但不低俗、不血腥
  931. • 角色形象统一,不崩坏
  932. 禁止/避免词汇
  933. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  934. ],
  935. '治愈清新风格' => [
  936. 'aliases' => ['治愈清新风格', '治愈清新'],
  937. 'prompt' => "风格说明
  938. 马卡龙色系、柔光、温暖干净
  939. 正向提示词(中文)
  940. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  941. 必须遵守规则
  942. • 保持治愈清新统一色调,不阴暗、不诡异
  943. • 画面柔和干净,无杂乱元素
  944. • 角色形象柔和可爱,不狰狞
  945. 禁止/避免词汇
  946. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  947. ],
  948. ];
  949. return $arr;
  950. }
  951. public function getArtStylePromptByInput($inputArtStyle): string
  952. {
  953. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  954. if ($normalizedInput === '') {
  955. return '';
  956. }
  957. return $this->getArtStylePromptMappings($normalizedInput);
  958. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  959. // foreach ($mapping['aliases'] as $alias) {
  960. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  961. // if ($normalizedAlias === '') {
  962. // continue;
  963. // }
  964. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  965. // return $mapping['prompt'];
  966. // }
  967. // }
  968. // }
  969. return '';
  970. }
  971. public function getArtStyleShortPromptByInput($inputArtStyle) {
  972. $stylePrefixes = [
  973. '唯美真人风格' => [
  974. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  975. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  976. ],
  977. '真人古风风格' => [
  978. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  979. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  980. ],
  981. '日系动漫风格' => [
  982. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  983. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  984. ],
  985. '国漫风格' => [
  986. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  987. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  988. ],
  989. 'Q版卡通风格' => [
  990. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  991. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  992. ],
  993. '简约扁平风格' => [
  994. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  995. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  996. ],
  997. '武侠风格' => [
  998. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  999. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  1000. ],
  1001. '古风仙侠风格' => [
  1002. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  1003. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  1004. ],
  1005. '新中式水墨风格' => [
  1006. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  1007. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  1008. ],
  1009. '写实插画风格' => [
  1010. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  1011. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  1012. ],
  1013. '3D卡通风格' => [
  1014. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  1015. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  1016. ],
  1017. '条漫风格' => [
  1018. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  1019. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  1020. ],
  1021. '赛博朋克风格' => [
  1022. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  1023. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  1024. ],
  1025. '暗黑悬疑风格' => [
  1026. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  1027. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  1028. ],
  1029. '治愈清新风格' => [
  1030. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  1031. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  1032. ]
  1033. ];
  1034. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  1035. }
  1036. private function normalizeArtStyleInput($value): string
  1037. {
  1038. $value = trim((string)$value);
  1039. if ($value === '') {
  1040. return '';
  1041. }
  1042. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  1043. return mb_strtolower($value, 'UTF-8');
  1044. }
  1045. private function replaceArtStyleSection(string $content, string $artStyle): string
  1046. {
  1047. if ($content === '' || $artStyle === '') {
  1048. return $content;
  1049. }
  1050. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  1051. if (!preg_match($pattern, $content)) {
  1052. return $content;
  1053. }
  1054. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  1055. }
  1056. /**
  1057. * DeepSeek流式输出处理方法
  1058. *
  1059. * @param array $post_data DeepSeek API请求参数
  1060. * @return \Generator 返回生成器,用于流式输出
  1061. */
  1062. private function deepSeekStreamResponse($post_data) {
  1063. // 设置最大输出tokens
  1064. $post_data['max_tokens'] = 300000;
  1065. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1066. $response = $client->post($this->url, [
  1067. 'json' => $post_data,
  1068. 'headers' => $this->headers,
  1069. 'stream' => true // 启用流式响应
  1070. ]);
  1071. $body = $response->getBody();
  1072. $fullContent = '';
  1073. $fullReasoningContent = '';
  1074. $usage = [];
  1075. $buffer = '';
  1076. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1077. // 逐行读取流式响应
  1078. while (!$body->eof()) {
  1079. $chunk = $body->read(1024); // 每次读取 1KB
  1080. $buffer .= $chunk;
  1081. // 按行分割
  1082. $lines = explode("\n", $buffer);
  1083. // 保留最后一个不完整的行
  1084. $buffer = array_pop($lines);
  1085. foreach ($lines as $line) {
  1086. $line = trim($line);
  1087. // 跳过空行
  1088. if (empty($line)) {
  1089. continue;
  1090. }
  1091. // 检查是否是 SSE 数据行
  1092. if (strpos($line, 'data: ') !== 0) {
  1093. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1094. continue;
  1095. }
  1096. $data = substr($line, 6); // 移除 "data: " 前缀
  1097. if ($data === '[DONE]') {
  1098. dLog('deepseek')->info('收到结束标记');
  1099. break 2; // 跳出两层循环
  1100. }
  1101. try {
  1102. $json = json_decode($data, true);
  1103. if (json_last_error() !== JSON_ERROR_NONE) {
  1104. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1105. continue;
  1106. }
  1107. if (isset($json['choices'][0]['delta'])) {
  1108. $delta = $json['choices'][0]['delta'];
  1109. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1110. if (isset($delta['reasoning_content'])) {
  1111. $fullReasoningContent .= $delta['reasoning_content'];
  1112. yield [
  1113. 'type' => 'reasoning',
  1114. 'content' => $delta['reasoning_content'],
  1115. 'full_reasoning' => $fullReasoningContent
  1116. ];
  1117. }
  1118. // 处理最终回答内容
  1119. if (isset($delta['content'])) {
  1120. $fullContent .= $delta['content'];
  1121. yield [
  1122. 'type' => 'content',
  1123. 'content' => $delta['content'],
  1124. ];
  1125. }
  1126. }
  1127. // 获取使用统计信息
  1128. if (isset($json['usage'])) {
  1129. $usage = $json['usage'];
  1130. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1131. }
  1132. } catch (\Exception $e) {
  1133. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1134. continue;
  1135. }
  1136. }
  1137. }
  1138. dLog('deepseek')->info('流式读取完成', [
  1139. 'content_length' => strlen($fullContent),
  1140. 'reasoning_length' => strlen($fullReasoningContent)
  1141. ]);
  1142. yield [
  1143. 'type' => 'done',
  1144. 'full_content' => $fullContent,
  1145. 'full_reasoning' => $fullReasoningContent,
  1146. 'usage' => $usage
  1147. ];
  1148. }
  1149. /**
  1150. * GPT 流式输出处理方法
  1151. *
  1152. * @param array $post_data GPT API请求参数
  1153. * @return \Generator 返回生成器,用于流式输出
  1154. */
  1155. private function gpt54StreamResponse($post_data) {
  1156. $apiKey = env('GPT_54_API_KEY');
  1157. if (empty($apiKey)) {
  1158. Utils::throwError('20003:GPT API Key未配置');
  1159. }
  1160. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1161. $headers = [
  1162. 'Authorization' => 'Bearer ' . $apiKey,
  1163. 'Content-Type' => 'application/json'
  1164. ];
  1165. // 移除 thinking 参数,GPT-5.4 不支持
  1166. if (isset($post_data['thinking'])) {
  1167. unset($post_data['thinking']);
  1168. }
  1169. if (isset($post_data['reasoning_effort'])) {
  1170. unset($post_data['reasoning_effort']);
  1171. }
  1172. $post_data['max_completion_tokens'] = 100000;
  1173. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  1174. $response = $client->post('https://api.nonelinear.com/v1/chat/completions', [
  1175. 'json' => $post_data,
  1176. 'headers' => $headers
  1177. ]);
  1178. $body = $response->getBody();
  1179. $fullContent = '';
  1180. $usage = [];
  1181. $buffer = '';
  1182. dLog('deepseek')->info('开始读取 GPT 流式响应');
  1183. // 逐行读取流式响应
  1184. while (!$body->eof()) {
  1185. $chunk = $body->read(1024); // 每次读取 1KB
  1186. $buffer .= $chunk;
  1187. // 按行分割
  1188. $lines = explode("\n", $buffer);
  1189. // 保留最后一个不完整的行
  1190. $buffer = array_pop($lines);
  1191. foreach ($lines as $line) {
  1192. $line = trim($line);
  1193. // 跳过空行
  1194. if (empty($line)) {
  1195. continue;
  1196. }
  1197. // 检查是否是 SSE 数据行
  1198. if (strpos($line, 'data: ') !== 0) {
  1199. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1200. continue;
  1201. }
  1202. $data = substr($line, 6); // 移除 "data: " 前缀
  1203. if ($data === '[DONE]') {
  1204. dLog('deepseek')->info('收到结束标记');
  1205. break 2; // 跳出两层循环
  1206. }
  1207. try {
  1208. $json = json_decode($data, true);
  1209. if (json_last_error() !== JSON_ERROR_NONE) {
  1210. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1211. continue;
  1212. }
  1213. if (isset($json['choices'][0]['delta'])) {
  1214. $delta = $json['choices'][0]['delta'];
  1215. // 处理回答内容
  1216. if (isset($delta['content'])) {
  1217. $fullContent .= $delta['content'];
  1218. yield [
  1219. 'type' => 'content',
  1220. 'content' => $delta['content'],
  1221. ];
  1222. }
  1223. }
  1224. // 获取使用统计信息
  1225. if (isset($json['usage'])) {
  1226. $usage = $json['usage'];
  1227. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1228. }
  1229. } catch (\Exception $e) {
  1230. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1231. continue;
  1232. }
  1233. }
  1234. }
  1235. dLog('deepseek')->info('流式读取完成', [
  1236. 'content_length' => strlen($fullContent)
  1237. ]);
  1238. yield [
  1239. 'type' => 'done',
  1240. 'full_content' => $fullContent,
  1241. 'full_reasoning' => '',
  1242. 'usage' => $usage
  1243. ];
  1244. }
  1245. // 与推理模型对话
  1246. public function chatWithReasoner($data) {
  1247. $content = getProp($data, 'content');
  1248. $model = getProp($data, 'model', 'r1');
  1249. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1250. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1251. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1252. if ($model == 'r1') {
  1253. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  1254. $thinkingMode = 'disabled';
  1255. } else {
  1256. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  1257. $thinkingMode = 'disabled';
  1258. }
  1259. // 获取可选情感(根据音色可支持情感选)
  1260. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  1261. $emotion_list = [];
  1262. foreach ($timbre_emotion as $emotion) {
  1263. $tmp = explode(',', $emotion);
  1264. $emotion_list = array_merge($emotion_list, $tmp);
  1265. }
  1266. $emotion_list = array_unique($emotion_list);
  1267. $emotion_str = implode('、', $emotion_list);
  1268. // // 获取可选情感
  1269. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  1270. // $emotion_str = implode('、', $emotion_list);
  1271. // 是否启用情感
  1272. $enable_emotion = getProp($data, 'enable_emotion', 0);
  1273. if ($enable_emotion) {
  1274. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  1275. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1276. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  1277. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  1278. }else {
  1279. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  1280. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1281. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  1282. }
  1283. $messages = [
  1284. [
  1285. 'role' => 'system',
  1286. 'content' => $sys_content
  1287. ],
  1288. [
  1289. 'role' => 'user',
  1290. 'content' => $content
  1291. ]
  1292. ];
  1293. $post_data = [
  1294. 'model' => $model,
  1295. 'messages' => $messages,
  1296. // 'max_tokens' => 8192,
  1297. 'temperature' => 1,
  1298. 'frequency_penalty' => 0,
  1299. 'presence_penalty' => 0,
  1300. 'thinking' => ['type' => $thinkingMode],
  1301. 'response_format' => [
  1302. 'type' => 'text'
  1303. ],
  1304. 'stream' => false
  1305. ];
  1306. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1307. // 根据模型类型选择调用方法
  1308. $fullContent = '';
  1309. $usage = [];
  1310. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1311. // DeepSeek 官方模型使用 DeepSeek API
  1312. $chatResult = $this->chatOnly($post_data);
  1313. } else if (in_array($model, $this->gpt_text_models)) {
  1314. // GPT-5.4 模型使用 TokenRouter API
  1315. $chatResult = $this->gpt54ChatOnly($post_data);
  1316. } else {
  1317. // 其他模型使用火山引擎API
  1318. $chatResult = $this->volcEngineChatCompletion($post_data);
  1319. }
  1320. if (is_array($chatResult)) {
  1321. $fullContent = $chatResult['fullContent'];
  1322. $usage = $chatResult['usage'];
  1323. }
  1324. // 处理获取到的剧本数据
  1325. $script_content = handleScriptWords($fullContent, $enable_emotion);
  1326. $result = [
  1327. 'origin_content' => $fullContent,
  1328. 'roles' => getProp($script_content, 'roles'),
  1329. 'words' => getProp($script_content, 'words'),
  1330. ];
  1331. return $result;
  1332. }
  1333. public function resetParagraphAudio($data) {
  1334. $bid = getProp($data, 'bid');
  1335. $cid = getProp($data, 'cid');
  1336. $version_id = getProp($data, 'version_id');
  1337. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  1338. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  1339. 'generate_status' => '待制作',
  1340. 'updated_at' => date('Y-m-d H:i:s')
  1341. ]);
  1342. }
  1343. public function saveParagraphAudio($data) {
  1344. $bid = getProp($data, 'bid');
  1345. $cid = getProp($data, 'cid');
  1346. $version_id = getProp($data, 'version_id');
  1347. $sequence = getProp($data, 'sequence');
  1348. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  1349. // 获取所有情感
  1350. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1351. $emotion_list = array_flip($emotion_list);
  1352. // 获取音色支持情感
  1353. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  1354. $timbre_emotion = explode(',', $timbre_emotion);
  1355. $emotion = getProp($data, 'emotion');
  1356. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  1357. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  1358. $list = [
  1359. 'bid' => $bid,
  1360. 'cid' => $cid,
  1361. 'version_id' => $version_id,
  1362. 'sequence' => $sequence,
  1363. 'role' => getProp($data, 'role'),
  1364. 'gender' => getProp($data, 'gender'),
  1365. 'text' => trim(getProp($data, 'text')),
  1366. 'emotion' => $emotion,
  1367. 'emotion_type' => $emotion_type,
  1368. 'voice_type' => getProp($data, 'voice_type'),
  1369. 'voice_name' => getProp($data, 'voice_name'),
  1370. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  1371. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  1372. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  1373. 'pitch' => getProp($data, 'pitch', 0),
  1374. // 'paragraph_audio_url' => '',
  1375. 'generate_status' => '制作中',
  1376. 'error_msg' => '',
  1377. 'updated_at' => date('Y-m-d H:i:s')
  1378. ];
  1379. $continue = false;
  1380. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  1381. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  1382. $list['generate_status'] = '制作成功';
  1383. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1384. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  1385. $continue = true;
  1386. }
  1387. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  1388. if ($id) {
  1389. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  1390. }else {
  1391. $list['created_at'] = date('Y-m-d H:i:s');
  1392. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  1393. $boolen = $id ? true : false;
  1394. }
  1395. // 如果更新成功则加入查询队列
  1396. if ($boolen) {
  1397. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  1398. Redis::sadd($redis_key, $id);
  1399. }
  1400. if ($boolen && !$continue) {
  1401. $boolen = false;
  1402. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1403. // 根据ID通过API通知合成音频
  1404. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  1405. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  1406. $response = $result->getBody()->getContents();
  1407. $response_arr = json_decode($response, true);
  1408. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1409. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1410. Log::info('通知火山生成段落音频失败: '.$error_msg);
  1411. Utils::throwError('20003:通知火山生成段落音频失败');
  1412. }
  1413. $boolen = true;
  1414. }
  1415. return $boolen;
  1416. }
  1417. public function insertAudioEffect($data) {
  1418. $audio_id = getProp($data, 'audio_id');
  1419. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1420. $bid = getProp($chapter_audio, 'bid');
  1421. $version_id = getProp($chapter_audio, 'version_id');
  1422. $cid = getProp($chapter_audio, 'cid');
  1423. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1424. $audio_effect_json = getProp($data, 'audio_effect_json');
  1425. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  1426. try {
  1427. DB::beginTransaction();
  1428. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1429. if (!$count) {
  1430. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1431. }else {
  1432. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1433. }
  1434. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1435. 'audio_effect_status' => '添加中',
  1436. 'audio_effect_json' => $audio_effect_json,
  1437. 'updated_at' => date('Y-m-d H:i:s')
  1438. ]);
  1439. if (!$boolen1) {
  1440. DB::rollBack();
  1441. Utils::throwError('20003:更新生成数据失败');
  1442. }
  1443. $id = DB::table('mp_audio_tasks')->insertGetId([
  1444. 'audio_id' => $audio_id,
  1445. 'generate_status' => '执行中',
  1446. 'generate_json' => json_encode([], 256),
  1447. 'bid' => $bid,
  1448. 'book_name' => getProp($chapter_audio, 'book_name'),
  1449. 'version_id' => $version_id,
  1450. 'version_name' => getProp($chapter_audio, 'version_name'),
  1451. 'cid' => $cid,
  1452. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1453. 'task_name' => $task_name,
  1454. 'created_at' => date('Y-m-d H:i:s'),
  1455. 'updated_at' => date('Y-m-d H:i:s')
  1456. ]);
  1457. if (!$id) {
  1458. DB::rollBack();
  1459. Utils::throwError('20003:创建任务失败');
  1460. }
  1461. }catch (\Exception $e) {
  1462. DB::rollBack();
  1463. Utils::throwError('20003:'.$e->getMessage());
  1464. }
  1465. DB::commit();
  1466. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1467. // 根据ID通过API通知合成音频
  1468. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1469. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1470. $response = $result->getBody()->getContents();
  1471. $response_arr = json_decode($response, true);
  1472. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1473. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1474. Log::info('通知火山插入音效失败: '.$error_msg);
  1475. Utils::throwError('20003:通知火山插入音效失败');
  1476. }
  1477. return true;
  1478. }
  1479. public function insertBgm($data) {
  1480. $audio_id = getProp($data, 'audio_id');
  1481. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1482. $bid = getProp($chapter_audio, 'bid');
  1483. $version_id = getProp($chapter_audio, 'version_id');
  1484. $cid = getProp($chapter_audio, 'cid');
  1485. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1486. $bgm_json = getProp($data, 'bgm_json');
  1487. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1488. if (!$bgm_json) {
  1489. $bgm_json = getProp($data, 'audio_effect_json');
  1490. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1491. }
  1492. try {
  1493. DB::beginTransaction();
  1494. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1495. if (!$count) {
  1496. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1497. }else {
  1498. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1499. }
  1500. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1501. 'bgm_status' => '添加中',
  1502. 'bgm_json' => $bgm_json,
  1503. 'updated_at' => date('Y-m-d H:i:s')
  1504. ]);
  1505. if (!$boolen1) {
  1506. DB::rollBack();
  1507. Utils::throwError('20003:更新生成数据失败');
  1508. }
  1509. $id = DB::table('mp_audio_tasks')->insertGetId([
  1510. 'audio_id' => $audio_id,
  1511. 'generate_status' => '执行中',
  1512. 'generate_json' => json_encode([], 256),
  1513. 'bid' => $bid,
  1514. 'book_name' => getProp($chapter_audio, 'book_name'),
  1515. 'version_id' => $version_id,
  1516. 'version_name' => getProp($chapter_audio, 'version_name'),
  1517. 'cid' => $cid,
  1518. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1519. 'task_name' => $task_name,
  1520. 'created_at' => date('Y-m-d H:i:s'),
  1521. 'updated_at' => date('Y-m-d H:i:s')
  1522. ]);
  1523. if (!$id) {
  1524. DB::rollBack();
  1525. Utils::throwError('20003:创建任务失败');
  1526. }
  1527. }catch (\Exception $e) {
  1528. DB::rollBack();
  1529. Utils::throwError('20003:'.$e->getMessage());
  1530. }
  1531. DB::commit();
  1532. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1533. // 根据ID通过API通知合成音频
  1534. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1535. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1536. $response = $result->getBody()->getContents();
  1537. $response_arr = json_decode($response, true);
  1538. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1539. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1540. Log::info('通知火山插入bgm失败: '.$error_msg);
  1541. Utils::throwError('20003:通知火山插入bgm失败');
  1542. }
  1543. return true;
  1544. }
  1545. public function getParagraphAudios($data) {
  1546. $bid = getProp($data, 'bid');
  1547. $cid = getProp($data, 'cid');
  1548. $version_id = getProp($data, 'version_id');
  1549. $sequence = getProp($data, 'sequence');
  1550. // 获取已生成的音频
  1551. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  1552. if ($sequence) $query->where('sequence', $sequence);
  1553. $paragraph_audios = $query->orderBy('sequence')->get();
  1554. $result = [];
  1555. foreach($paragraph_audios as $item) {
  1556. $result[] = [
  1557. 'sequence' => getProp($item, 'sequence'),
  1558. 'role' => getProp($item, 'role'),
  1559. 'gender' => getProp($item, 'gender'),
  1560. 'text' => trim(getProp($item, 'text')),
  1561. 'emotion' => getProp($item, 'emotion'),
  1562. 'emotion_type' => getProp($item, 'emotion_type'),
  1563. 'voice_type' => getProp($item, 'voice_type'),
  1564. 'voice_name' => getProp($item, 'voice_name'),
  1565. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1566. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1567. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1568. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1569. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  1570. ];
  1571. }
  1572. return $result;
  1573. }
  1574. // 新增合成任务
  1575. public function addGenerateTask($data) {
  1576. $bid = getProp($data, 'bid');
  1577. $cid = getProp($data, 'cid');
  1578. $version_id = getProp($data, 'version_id');
  1579. $generate_json = getProp($data, 'generate_json');
  1580. // 获取已生成的音频
  1581. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  1582. $paragraph_list = [];
  1583. foreach($paragraph_audios as $item) {
  1584. $paragraph_list[getProp($item, 'sequence')] = [
  1585. 'role' => getProp($item, 'role'),
  1586. 'gender' => getProp($item, 'gender'),
  1587. 'text' => trim(getProp($item, 'text')),
  1588. 'emotion' => getProp($item, 'emotion'),
  1589. 'emotion_type' => getProp($item, 'emotion_type'),
  1590. 'voice_type' => getProp($item, 'voice_type'),
  1591. 'voice_name' => getProp($item, 'voice_name'),
  1592. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1593. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1594. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1595. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1596. ];
  1597. }
  1598. // 更新角色-音色信息
  1599. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  1600. $existed_role_info = json_decode($existed_role_info, true);
  1601. if (!$existed_role_info) $existed_role_info = [];
  1602. // 获取情感信息
  1603. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1604. $emotion_list = array_flip($emotion_list);
  1605. // 获取音色对应情感组
  1606. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  1607. $timbre_emotion_list = [];
  1608. foreach($timbre_emotions as $item) {
  1609. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  1610. }
  1611. // 构造生成音频的json
  1612. $words = json_decode($generate_json, true);
  1613. // 最终合成前的参数组
  1614. $mp_chapter_paragraph_audios = [];
  1615. $sequence = 1;
  1616. $complete_paragraph_sequences = [];
  1617. foreach($words as &$word) {
  1618. 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:参数格式有误');
  1619. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  1620. $role = getProp($word, 'role');
  1621. $word['gender'] = (int)$word['gender'];
  1622. // 判断音色对应情感是否支持,不支持则调整为中性
  1623. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  1624. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  1625. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  1626. if (isset($emotion_list[getProp($word, 'emotion')])) {
  1627. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  1628. }else {
  1629. $word['emotion'] = '中性';
  1630. $word['emotion_type'] = 'neutral';
  1631. }
  1632. $existed_role_info[$role] = [
  1633. 'timbre_type' => $word['voice_type'],
  1634. 'timbre_name' => $word['voice_name'],
  1635. 'emotion' => $word['emotion'],
  1636. 'emotion_type' => $word['emotion_type'],
  1637. 'speed_ratio' => $word['speed_ratio'],
  1638. 'loudness_ratio'=> $word['loudness_ratio'],
  1639. 'emotion_scale' => $word['emotion_scale'],
  1640. 'pitch' => $word['pitch']
  1641. ];
  1642. $word['paragraph_audio_url'] = '';
  1643. // 判断生成参数是否相同,相同则直接使用已生成的音频
  1644. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  1645. // 如果音频存在并且参数都未改变则使用已生成的音频
  1646. if (getProp($paragraph, 'paragraph_audio_url')) {
  1647. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  1648. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  1649. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  1650. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  1651. // {
  1652. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1653. // }
  1654. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1655. }
  1656. $tmp = $word;
  1657. // 组装章节分句音频数据
  1658. // $tmp['sequence'] = getProp($word, 'sequence');
  1659. // $tmp['text'] = getProp($word, 'text');
  1660. // $tmp['emotion'] = getProp($word, 'emotion');
  1661. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  1662. // $tmp['voice_name'] = getProp($word, 'voice_name');
  1663. // $tmp['voice_type'] = getProp($word, 'voice_type');
  1664. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  1665. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  1666. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  1667. $tmp['bid'] = $bid;
  1668. $tmp['version_id'] = $version_id;
  1669. $tmp['cid'] = $cid;
  1670. $tmp['sequence'] = $sequence;
  1671. $tmp['created_at'] = date('Y-m-d H:i:s');
  1672. $tmp['updated_at'] = date('Y-m-d H:i:s');
  1673. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  1674. $mp_chapter_paragraph_audios[] = $tmp;
  1675. $complete_paragraph_sequences[] = $sequence;
  1676. $sequence++;
  1677. }
  1678. $generate_json = json_encode($words, 256);
  1679. // 判断是否有未生成字幕的段落
  1680. $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();
  1681. if ($no_subtitle_sequences) {
  1682. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  1683. }
  1684. try {
  1685. DB::beginTransaction();
  1686. $role_info = json_encode($existed_role_info, 256);
  1687. $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')]);
  1688. if (!$boolen) {
  1689. DB::rollBack();
  1690. Utils::throwError('20003:更新角色信息失败');
  1691. }
  1692. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  1693. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  1694. if (!$count) {
  1695. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1696. }else {
  1697. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1698. }
  1699. $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')]);
  1700. if (!$boolen1) {
  1701. DB::rollBack();
  1702. Utils::throwError('20003:更新生成数据失败');
  1703. }
  1704. $id = DB::table('mp_audio_tasks')->insertGetId([
  1705. 'audio_id' => getProp($chapter_audio, 'id'),
  1706. 'generate_status' => '执行中',
  1707. 'generate_json' => $generate_json,
  1708. 'bid' => $bid,
  1709. 'book_name' => getProp($chapter_audio, 'book_name'),
  1710. 'version_id' => $version_id,
  1711. 'version_name' => getProp($chapter_audio, 'version_name'),
  1712. 'cid' => $cid,
  1713. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1714. 'task_name' => $task_name,
  1715. 'created_at' => date('Y-m-d H:i:s'),
  1716. 'updated_at' => date('Y-m-d H:i:s')
  1717. ]);
  1718. if (!$id) {
  1719. DB::rollBack();
  1720. Utils::throwError('20003:创建任务失败');
  1721. }
  1722. // 删除不在段落序号范围内的其他数据
  1723. if ($complete_paragraph_sequences) {
  1724. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  1725. }
  1726. // // 删除章节分句音频数据并重新插入
  1727. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  1728. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  1729. // if (!$boolen3) {
  1730. // DB::rollBack();
  1731. // Utils::throwError('20003:更新章节分句音频失败');
  1732. // }
  1733. } catch (\Exception $e) {
  1734. DB::rollBack();
  1735. Utils::throwError('20003:'.$e->getMessage());
  1736. }
  1737. DB::commit();
  1738. // 通知火山生成音频
  1739. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1740. // 根据ID通过API通知合成音频
  1741. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  1742. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  1743. $response = $result->getBody()->getContents();
  1744. $response_arr = json_decode($response, true);
  1745. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1746. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1747. Log::info('通知火山生成音频失败: '.$error_msg);
  1748. Utils::throwError('20003:通知火山生成音频失败');
  1749. }
  1750. return true;
  1751. }
  1752. public function timbreList($data) {
  1753. $gender = getProp($data, 'gender');
  1754. $timbre_name = getProp($data, 'voice_name');
  1755. $category_id = getProp($data, 'category_id');
  1756. $age_stage = getProp($data, 'age_stage');
  1757. $query = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_name as voice_name', 'timbre_type as voice_type', 'gender', 'age_stage', 'language', 'emotion', 'label', 'first_category_id', 'first_category_name', 'second_category_id', 'second_category_name', 'third_category_id', 'third_category_name', 'audio_url');
  1758. if ($gender) {
  1759. $query->where('gender', $gender);
  1760. }
  1761. if ($timbre_name) {
  1762. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  1763. }
  1764. if ($category_id) {
  1765. $query->where(function ($query) use ($category_id) {
  1766. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  1767. });
  1768. }
  1769. if ($age_stage) {
  1770. $query->where('age_stage', $age_stage);
  1771. }
  1772. $list = $query->get()->map(function ($value) {
  1773. $value = (array)$value;
  1774. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  1775. return $value;
  1776. })->toArray();
  1777. return $list;
  1778. }
  1779. // 生成火山临时token
  1780. public function setStsToken() {
  1781. // ************* 配置参数 *************
  1782. $method = 'GET';
  1783. $service = 'sts';
  1784. $host = 'open.volcengineapi.com';
  1785. $region = env('VOLC_REGION');
  1786. $endpoint = 'https://open.volcengineapi.com';
  1787. // $endpoint = 'https://tos-cn-beijing.volces.com';
  1788. $access_key = env('VOLC_AK');
  1789. $secret_key = env('VOLC_SK');
  1790. // 获取缓存中的token,如果没有则请求接口
  1791. $token = Redis::get('volc_sts_token');
  1792. if (!$token) {
  1793. // 查询参数
  1794. $query_parameters = [
  1795. 'Action' => 'AssumeRole',
  1796. 'RoleSessionName' => 'user@zw',
  1797. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  1798. 'Version' => '2018-01-01'
  1799. ];
  1800. // 生成URL编码的查询字符串
  1801. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  1802. // 获取签名头信息
  1803. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  1804. // 构建完整URL
  1805. $request_url = $endpoint . '?' . $request_parameters;
  1806. $client = new Client(['verify' => false]);
  1807. $response = $client->get($request_url, ['headers' => $headers]);
  1808. $response_arr = json_decode($response->getBody()->getContents(), true);
  1809. $result = [
  1810. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  1811. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  1812. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  1813. 'Region' => env('VOLC_REGION'),
  1814. 'Endpoint' => env('VOLC_END_POINT'),
  1815. 'Bucket' => env('VOLC_BUCKET'),
  1816. ];
  1817. // 缓存token
  1818. Redis::setex('volc_sts_token', 3000, json_encode($result));
  1819. return $result;
  1820. } else {
  1821. return json_decode($token, true);
  1822. }
  1823. // $response = $response['Response'];
  1824. // $access_key = $response['Credentials']['AccessKeyId'];
  1825. // $secret_key = $response['Credentials']['AccessKeySecret'];
  1826. // $security_token = $response['Credentials']['SecurityToken'];
  1827. // $expiration = $response['Credentials']['Expiration'];
  1828. // dd($response_arr);
  1829. }
  1830. public function emotionGroups($data) {
  1831. $id = getProp($data, 'group_id');
  1832. $group_name = getProp($data, 'group_name');
  1833. $voice_type = getProp($data, 'voice_type');
  1834. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  1835. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  1836. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  1837. if ($group_name) {
  1838. $query->where('group_name', 'like', "%{$group_name}%");
  1839. }
  1840. if ($id) {
  1841. $query->where('id', $id);
  1842. }
  1843. if ($voice_type) {
  1844. $query->where('voice_type', $voice_type);
  1845. }
  1846. return $query->orderBy('id')->get()->map(function ($value) {
  1847. return (array)$value;
  1848. })->toArray();
  1849. }
  1850. private function sign($key, $msg) {
  1851. return hash_hmac('sha256', $msg, $key, true);
  1852. }
  1853. // 生成签名密钥
  1854. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  1855. $kDate = $this->sign($key, $dateStamp);
  1856. $kRegion = $this->sign($kDate, $regionName);
  1857. $kService = $this->sign($kRegion, $serviceName);
  1858. $kSigning = $this->sign($kService, 'request');
  1859. return $kSigning;
  1860. }
  1861. // 获取签名头信息
  1862. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  1863. $contenttype = 'application/x-www-form-urlencoded';
  1864. $accept = 'application/json';
  1865. // 获取当前UTC时间
  1866. $t = new DateTime('now', new DateTimeZone('UTC'));
  1867. $xdate = $t->format('Ymd\THis\Z');
  1868. $datestamp = $t->format('Ymd');
  1869. // 1. 拼接规范请求串
  1870. $canonical_uri = '/';
  1871. $canonical_querystring = $request_parameters;
  1872. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  1873. $signed_headers = 'content-type;host;x-date';
  1874. // 空请求体的SHA256哈希
  1875. $payload_hash = hash('sha256', '');
  1876. $canonical_request = implode("\n", [
  1877. $method,
  1878. $canonical_uri,
  1879. $canonical_querystring,
  1880. $canonical_headers,
  1881. $signed_headers,
  1882. $payload_hash
  1883. ]);
  1884. // 2. 拼接待签名字符串
  1885. $algorithm = 'HMAC-SHA256';
  1886. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  1887. $hashed_canonical_request = hash('sha256', $canonical_request);
  1888. $string_to_sign = implode("\n", [
  1889. $algorithm,
  1890. $xdate,
  1891. $credential_scope,
  1892. $hashed_canonical_request
  1893. ]);
  1894. // 3. 计算签名
  1895. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  1896. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  1897. // 4. 添加签名到请求头
  1898. $authorization_header = sprintf(
  1899. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  1900. $algorithm,
  1901. $access_key,
  1902. $credential_scope,
  1903. $signed_headers,
  1904. $signature
  1905. );
  1906. return [
  1907. 'Accept' => $accept,
  1908. 'Content-Type' => $contenttype,
  1909. 'X-Date' => $xdate,
  1910. 'Authorization' => $authorization_header
  1911. ];
  1912. }
  1913. // 文字合成语音(火山引擎)
  1914. public function tts($data) {
  1915. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  1916. $headers = [
  1917. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  1918. 'Content-Type' => 'application/json; charset=UTF-8'
  1919. ];
  1920. $post_data = [
  1921. 'app' => [
  1922. 'appid' => env('VOLC_APPID'),
  1923. 'token' => env('VOLC_TOKEN'),
  1924. 'cluster' => 'volcano_tts'
  1925. ],
  1926. 'user' => [
  1927. 'uid' => 'mp_audio'
  1928. ],
  1929. // 'audio' => [
  1930. // 'voice_type' =>
  1931. // ],
  1932. ];
  1933. }
  1934. public function scriptList($data) {
  1935. $uid = Site::getUid();
  1936. $script_id = getProp($data, 'script_id');
  1937. $script_name = getProp($data, 'script_name');
  1938. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  1939. if ($script_id) {
  1940. $query->where('id', $script_id);
  1941. }
  1942. if ($script_name) {
  1943. $query->where('script_name', 'like', "%{$script_name}%");
  1944. }
  1945. return $query->orderBy('created_at', 'desc')->paginate(12);
  1946. }
  1947. public function scripts($data) {
  1948. $uid = Site::getUid();
  1949. $script_id = getProp($data, 'script_id');
  1950. $script_name = getProp($data, 'script_name');
  1951. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  1952. if ($script_id) {
  1953. $query->where('id', $script_id);
  1954. }
  1955. if ($script_name) {
  1956. $query->where('script_name', 'like', "%{$script_name}%");
  1957. }
  1958. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  1959. return (array)$value;
  1960. })->toArray();
  1961. }
  1962. public function scriptInfo($data) {
  1963. $uid = Site::getUid();
  1964. $script_id = getProp($data, 'script_id');
  1965. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  1966. // ->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();
  1967. ->selectRaw('id as script_id, script_name')->first();
  1968. if (!$script) Utils::throwError('20003:该剧本不存在!');
  1969. $script = (array)$script;
  1970. // 获取分集组信息
  1971. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  1972. ->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')
  1973. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  1974. $value = (array)$value;
  1975. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  1976. return (array)$value;
  1977. })->toArray();
  1978. $script['group'] = $groups;
  1979. return $script;
  1980. }
  1981. public function createScript($data) {
  1982. $script_name = getProp($data, 'script_name');
  1983. $uid = Site::getUid(); // 获取当前用户ID
  1984. $cpid = Site::getCpid(); // 获取当前公司组ID
  1985. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  1986. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  1987. $script_name .= '_'.date('YmdHis');
  1988. }
  1989. return DB::table('mp_scripts')->insertGetId([
  1990. 'script_name' => $script_name,
  1991. 'user_id' => $uid,
  1992. 'cpid' => $cpid,
  1993. 'created_at' => date('Y-m-d H:i:s'),
  1994. 'updated_at' => date('Y-m-d H:i:s')
  1995. ]);
  1996. }
  1997. public function editScript($data) {
  1998. $script_id = getProp($data, 'script_id');
  1999. $script_name = getProp($data, 'script_name');
  2000. $uid = Site::getUid(); // 获取当前用户ID
  2001. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  2002. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  2003. if ($id && (int)$id !== (int)$script_id) {
  2004. $script_name .= '_'.date('YmdHis');
  2005. }
  2006. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2007. 'script_name' => $script_name,
  2008. 'updated_at' => date('Y-m-d H:i:s')
  2009. ]);
  2010. }
  2011. public function delScript($data) {
  2012. $script_id = getProp($data, 'script_id');
  2013. $uid = Site::getUid(); // 获取当前用户ID
  2014. if (!$script_id) Utils::throwError('20003:请选择剧本');
  2015. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2016. 'is_deleted' => 1,
  2017. 'updated_at' => date('Y-m-d H:i:s')
  2018. ]);
  2019. }
  2020. public function createEpisode($data) {
  2021. $script_id = getProp($data, 'script_id');
  2022. $group_name = getProp($data, 'group_name');
  2023. $remark = getProp($data, 'remark');
  2024. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  2025. $uid = Site::getUid(); // 获取当前用户ID
  2026. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  2027. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  2028. $group_name .= '_'.date('YmdHis');
  2029. }
  2030. return DB::table('mp_script_episode_group')->insertGetId([
  2031. 'script_id' => $script_id,
  2032. 'group_name' => $group_name,
  2033. 'user_id' => $uid,
  2034. 'remark' => $remark,
  2035. 'created_at' => date('Y-m-d H:i:s'),
  2036. 'updated_at' => date('Y-m-d H:i:s')
  2037. ]);
  2038. }
  2039. public function editEpisode($data) {
  2040. $group_id = getProp($data, 'group_id');
  2041. $start_episode_number = getProp($data, 'start_episode_number');
  2042. $end_episode_number = getProp($data, 'end_episode_number');
  2043. $group_name = getProp($data, 'group_name');
  2044. $uid = Site::getUid(); // 获取当前用户ID
  2045. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  2046. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  2047. if ($id && (int)$id !== (int)$group_id) {
  2048. $group_name .= '_'.date('YmdHis');
  2049. }
  2050. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2051. 'group_name' => $group_name,
  2052. 'start_episode_number' => $start_episode_number,
  2053. 'end_episode_number' => $end_episode_number,
  2054. 'updated_at' => date('Y-m-d H:i:s')
  2055. ]);
  2056. }
  2057. public function delEpisode($data) {
  2058. $group_id = getProp($data, 'group_id');
  2059. $uid = Site::getUid(); // 获取当前用户ID
  2060. if (!$group_id) Utils::throwError('20003:请选择分集');
  2061. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2062. 'is_deleted' => 1,
  2063. 'updated_at' => date('Y-m-d H:i:s')
  2064. ]);
  2065. }
  2066. /**
  2067. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2068. *
  2069. * @param array $data 包含以下参数:
  2070. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2071. * - question: 用户问题(可选)
  2072. * - model: 使用的模型(r1 或 v3,默认 v3)
  2073. * @return \Generator 返回生成器,用于流式输出
  2074. */
  2075. public function generateEpisodes($data) {
  2076. $script_id = getProp($data, 'script_id');
  2077. $group_id = getProp($data, 'group_id');
  2078. // $file = getProp($data, 'file');
  2079. $file = '';
  2080. $content = getProp($data, 'content', '');
  2081. // $bid = getProp($data, 'bid', 0);
  2082. $bid = 0;
  2083. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2084. if (!$group) {
  2085. Utils::throwError('20003:剧本分集不存在');
  2086. }
  2087. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  2088. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  2089. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  2090. $prompt = getProp($data, 'prompt');
  2091. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  2092. $model = getProp($data, 'model');
  2093. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2094. Utils::throwError('20003:该模型不存在!');
  2095. }
  2096. // 检查是否存在重叠的剧集序号范围
  2097. $exists_groups = DB::table('mp_script_episode_group')
  2098. ->where('script_id', $script_id)
  2099. ->where('id', '<>', $group_id) // 排除当前组
  2100. ->where('is_deleted', 0)
  2101. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2102. // 检查新范围是否与现有范围重叠
  2103. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2104. // 新范围的开始在现有范围内
  2105. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2106. ->where('end_episode_number', '>=', $start_episode_sequence);
  2107. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2108. // 新范围的结束在现有范围内
  2109. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2110. ->where('end_episode_number', '>=', $end_episode_sequence);
  2111. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2112. // 新范围完全包含现有范围
  2113. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2114. ->where('end_episode_number', '<=', $end_episode_sequence);
  2115. });
  2116. })
  2117. ->select('start_episode_number', 'end_episode_number')
  2118. ->get();
  2119. if ($exists_groups->isNotEmpty()) {
  2120. $conflict_ranges = [];
  2121. foreach ($exists_groups as $group) {
  2122. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2123. }
  2124. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2125. }
  2126. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2127. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2128. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2129. if ($model === 'deepseek-chat') {
  2130. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2131. $model = 'deepseek-v4-flash';
  2132. $thinkingMode = 'disabled';
  2133. } elseif ($model === 'deepseek-reasoner') {
  2134. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2135. $model = 'deepseek-v4-flash';
  2136. $thinkingMode = 'enabled';
  2137. }
  2138. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2139. if (!$script) {
  2140. Utils::throwError('20003:剧本不存在');
  2141. }
  2142. $content = getProp($group, 'content');
  2143. if (!$file && !$content && !$bid) {
  2144. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2145. }
  2146. // 提取文件内容
  2147. if ($file) {
  2148. $content = $this->extractFileContent($file);
  2149. if (!$content) {
  2150. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2151. }
  2152. } elseif ($bid) {
  2153. $content = $this->getContentByBid($bid);
  2154. if (!$content) {
  2155. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2156. }
  2157. } elseif ($content) {
  2158. $content = filterContent($content);
  2159. } elseif ($prompt) {
  2160. $content = filterContent($prompt);
  2161. } else {
  2162. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2163. }
  2164. // 构建消息
  2165. $messages = [
  2166. $this->sys_message,
  2167. [
  2168. 'role' => 'user',
  2169. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2170. ]
  2171. ];
  2172. $post_data = [
  2173. 'model' => $model,
  2174. 'messages' => $messages,
  2175. // 'max_tokens' => 8192,
  2176. 'temperature' => 0.7,
  2177. 'frequency_penalty' => 0,
  2178. 'presence_penalty' => 0,
  2179. 'thinking' => ['type' => $thinkingMode],
  2180. 'response_format' => ['type' => 'text'],
  2181. 'stream' => true
  2182. ];
  2183. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2184. // 根据模型类型选择调用方法
  2185. $fullContent = '';
  2186. $fullReasoningContent = '';
  2187. $usage = [];
  2188. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2189. // DeepSeek 官方模型使用 DeepSeek API
  2190. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2191. } else if (in_array($model, $this->gpt_text_models)) {
  2192. // GPT-5.4 模型使用 TokenRouter API
  2193. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2194. } else {
  2195. // 其他模型使用火山引擎API
  2196. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2197. }
  2198. // 处理流式输出
  2199. foreach ($streamGenerator as $chunk) {
  2200. if (isset($chunk['type'])) {
  2201. if ($chunk['type'] === 'done') {
  2202. // 最终结果
  2203. $fullContent = $chunk['full_content'];
  2204. $fullReasoningContent = $chunk['full_reasoning'];
  2205. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2206. } else {
  2207. // 逐块yield数据
  2208. yield $chunk;
  2209. }
  2210. }
  2211. }
  2212. dLog('deepseek')->info('完整内容: '.$fullContent);
  2213. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2214. // 处理完整内容并返回最终结果
  2215. $script_arr = [];
  2216. if ($fullContent) {
  2217. $script_arr = extractScriptContent($fullContent);
  2218. }
  2219. logDB('deepseek', 'info', '解析内容', $script_arr);
  2220. if (!$script_arr['episodes']) {
  2221. Utils::throwError('20003:未生成剧本相关信息');
  2222. // yield [
  2223. // 'type' => 'done',
  2224. // 'script' => $script_arr,
  2225. // 'msg' => '未生成剧本相关信息',
  2226. // 'answer' => $fullContent,
  2227. // 'reasoning' => $fullReasoningContent,
  2228. // 'usage' => $usage
  2229. // ];
  2230. // return ;
  2231. }
  2232. try {
  2233. DB::beginTransaction();
  2234. // // 返回前保存剧本内容
  2235. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2236. // 'content' => $content,
  2237. // 'updated_at' => date('Y-m-d H:i:s')
  2238. // ]);
  2239. // if (!$boolen) {
  2240. // Utils::throwError('20003:保存剧本内容失败');
  2241. // }
  2242. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2243. // 'start_episode_number' => $start_episode_sequence,
  2244. // 'end_episode_number' => $end_episode_sequence,
  2245. // 'updated_at' => date('Y-m-d H:i:s')
  2246. // ]);
  2247. // if (!$boolen1) {
  2248. // Utils::throwError('20003:保存分集失败');
  2249. // }
  2250. $episode_content = '';
  2251. $episodes = [];
  2252. foreach ($script_arr['episodes'] as $item) {
  2253. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  2254. // $episodes[] = [
  2255. // 'script_id' => $script_id,
  2256. // 'episode_number' => $item['episode_number'],
  2257. // 'episode_name' => $item['episode_name'],
  2258. // 'episode_content' => $item['episode_content'],
  2259. // 'created_at' => date('Y-m-d H:i:s'),
  2260. // 'updated_at' => date('Y-m-d H:i:s'),
  2261. // ];
  2262. }
  2263. if ($episode_content) {
  2264. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2265. 'episode_content' => $episode_content,
  2266. 'updated_at' => date('Y-m-d H:i:s')
  2267. ]);
  2268. if (!$boolen2) {
  2269. Utils::throwError('20003:保存分集内容失败');
  2270. }
  2271. }else {
  2272. Utils::throwError('20003:分集剧本解析失败');
  2273. }
  2274. }catch (\Exception $e) {
  2275. DB::rollBack();
  2276. Utils::throwError('20003:'.$e->getMessage());
  2277. }
  2278. DB::commit();
  2279. yield [
  2280. 'type' => 'done',
  2281. 'script' => $script_arr,
  2282. 'episode_content' => $episode_content,
  2283. 'answer' => $fullContent,
  2284. 'reasoning' => $fullReasoningContent,
  2285. 'usage' => $usage
  2286. ];
  2287. }
  2288. public function chatWithFileStream($data) {
  2289. $script_id = getProp($data, 'script_id');
  2290. $group_id = getProp($data, 'group_id');
  2291. $file = getProp($data, 'file');
  2292. $content = getProp($data, 'content', '');
  2293. $bid = getProp($data, 'bid', 0);
  2294. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2295. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2296. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  2297. $prompt = getProp($data, 'prompt');
  2298. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2299. if (!empty($prompt)) {
  2300. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2301. }
  2302. $question = getProp($data, 'question', $baseQuestion);
  2303. $model = getProp($data, 'model');
  2304. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2305. Utils::throwError('20003:该模型不存在!');
  2306. }
  2307. // 检查是否存在重叠的剧集序号范围
  2308. $exists_groups = DB::table('mp_script_episode_group')
  2309. ->where('script_id', $script_id)
  2310. ->where('id', '<>', $group_id)
  2311. ->where('is_deleted', 0)
  2312. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2313. // 检查新范围是否与现有范围重叠
  2314. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2315. // 新范围的开始在现有范围内
  2316. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2317. ->where('end_episode_number', '>=', $start_episode_sequence);
  2318. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2319. // 新范围的结束在现有范围内
  2320. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2321. ->where('end_episode_number', '>=', $end_episode_sequence);
  2322. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2323. // 新范围完全包含现有范围
  2324. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2325. ->where('end_episode_number', '<=', $end_episode_sequence);
  2326. });
  2327. })
  2328. ->select('start_episode_number', 'end_episode_number')
  2329. ->get();
  2330. if ($exists_groups->isNotEmpty()) {
  2331. $conflict_ranges = [];
  2332. foreach ($exists_groups as $group) {
  2333. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2334. }
  2335. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2336. }
  2337. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2338. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2339. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2340. if ($model === 'deepseek-chat') {
  2341. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2342. $model = 'deepseek-v4-flash';
  2343. $thinkingMode = 'disabled';
  2344. } elseif ($model === 'deepseek-reasoner') {
  2345. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2346. $model = 'deepseek-v4-flash';
  2347. $thinkingMode = 'enabled';
  2348. }
  2349. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2350. if (!$script) {
  2351. Utils::throwError('20003:剧本不存在');
  2352. }
  2353. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2354. if (!$group) {
  2355. Utils::throwError('20003:剧本分集不存在');
  2356. }
  2357. if (!$file && !$content && !$bid) {
  2358. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2359. }
  2360. // 提取文件内容
  2361. if ($file) {
  2362. $content = $this->extractFileContent($file);
  2363. if (!$content) {
  2364. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2365. }
  2366. } elseif ($bid) {
  2367. $content = $this->getContentByBid($bid);
  2368. if (!$content) {
  2369. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2370. }
  2371. } elseif ($content) {
  2372. $content = filterContent($content);
  2373. } elseif ($prompt) {
  2374. $content = filterContent($prompt);
  2375. } else {
  2376. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2377. }
  2378. // 构建消息
  2379. $messages = [
  2380. [
  2381. 'role' => 'system',
  2382. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  2383. 强制要求:\n
  2384. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2385. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  2386. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  2387. 普通要求:\n
  2388. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  2389. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  2390. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  2391. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  2392. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  2393. 示例如下:\n
  2394. ###剧本名:西昆仑
  2395. ###故事梗概
  2396. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2397. ###剧本亮点
  2398. 亮点1:绝境奇药,生死一线
  2399. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2400. 亮点2:结拜兄妹,化解尴尬
  2401. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2402. 亮点3:纤发夺命,情愫暗涌
  2403. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2404. ###人物关系
  2405. 阿雪与梁萧之间存在兄妹之情。
  2406. ###核心矛盾
  2407. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2408. ###主体列表
  2409. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2410. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2411. 阴阳球:天地异宝,能化生精气,救人于危难。
  2412. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2413. ###美术风格
  2414. 基础画风风格词:厚涂古风
  2415. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2416. ###场景列表
  2417. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  2418. [
  2419. 'role' => 'user',
  2420. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2421. ]
  2422. ];
  2423. $post_data = [
  2424. 'model' => $model,
  2425. 'messages' => $messages,
  2426. // 'max_tokens' => 8192,
  2427. 'temperature' => 0.7,
  2428. 'frequency_penalty' => 0,
  2429. 'presence_penalty' => 0,
  2430. 'thinking' => ['type' => $thinkingMode],
  2431. 'response_format' => ['type' => 'text'],
  2432. 'stream' => true
  2433. ];
  2434. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2435. // 根据模型类型选择调用方法
  2436. $fullContent = '';
  2437. $fullReasoningContent = '';
  2438. $usage = [];
  2439. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2440. // DeepSeek 官方模型使用 DeepSeek API
  2441. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2442. } else if (in_array($model, $this->gpt_text_models)) {
  2443. // GPT-5.4 模型使用 TokenRouter API
  2444. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2445. } else {
  2446. // 其他模型使用火山引擎API
  2447. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2448. }
  2449. // 处理流式输出
  2450. foreach ($streamGenerator as $chunk) {
  2451. if (isset($chunk['type'])) {
  2452. if ($chunk['type'] === 'done') {
  2453. // 最终结果
  2454. $fullContent = $chunk['full_content'];
  2455. $fullReasoningContent = $chunk['full_reasoning'];
  2456. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2457. } else {
  2458. // 逐块yield数据
  2459. yield $chunk;
  2460. }
  2461. }
  2462. }
  2463. dLog('deepseek')->info('完整内容: '.$fullContent);
  2464. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2465. // 处理完整内容并返回最终结果
  2466. $script_arr = [];
  2467. if ($fullContent) {
  2468. $script_arr = extractScriptContent($fullContent);
  2469. }
  2470. logDB('deepseek', 'info', '解析内容', $script_arr);
  2471. if (!$script_arr['roles']) {
  2472. Utils::throwError('20003:未生成剧本相关信息');
  2473. // yield [
  2474. // 'type' => 'done',
  2475. // 'script' => $script_arr,
  2476. // 'msg' => '未生成剧本相关信息',
  2477. // 'answer' => $fullContent,
  2478. // 'reasoning' => $fullReasoningContent,
  2479. // 'usage' => $usage
  2480. // ];
  2481. }
  2482. try {
  2483. DB::beginTransaction();
  2484. // // 返回前保存剧本内容
  2485. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2486. // 'content' => $content,
  2487. // 'status' => '解析完成',
  2488. // 'updated_at' => date('Y-m-d H:i:s')
  2489. // ]);
  2490. // if (!$boolen) {
  2491. // Utils::throwError('20003:保存剧本内容失败');
  2492. // }
  2493. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2494. 'start_episode_number' => $start_episode_sequence,
  2495. 'end_episode_number' => $end_episode_sequence,
  2496. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2497. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2498. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2499. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2500. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2501. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2502. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2503. 'status' => '解析完成',
  2504. 'content' => $content,
  2505. 'updated_at' => date('Y-m-d H:i:s')
  2506. ]);
  2507. if (!$boolen1) {
  2508. Utils::throwError('20003:保存分集失败');
  2509. }
  2510. // $episodes = [];
  2511. // foreach ($script_arr['episodes'] as $item) {
  2512. // $episodes[] = [
  2513. // 'script_id' => $script_id,
  2514. // 'episode_number' => $item['episode_number'],
  2515. // 'episode_name' => $item['episode_name'],
  2516. // 'episode_content' => $item['episode_content'],
  2517. // 'created_at' => date('Y-m-d H:i:s'),
  2518. // 'updated_at' => date('Y-m-d H:i:s'),
  2519. // ];
  2520. // }
  2521. // if ($episodes) {
  2522. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2523. // if (!$boolen2) {
  2524. // Utils::throwError('20003:保存分集内容失败');
  2525. // }
  2526. // }else {
  2527. // Utils::throwError('20003:分集剧本解析失败');
  2528. // }
  2529. }catch (\Exception $e) {
  2530. DB::rollBack();
  2531. Utils::throwError('20003:'.$e->getMessage());
  2532. }
  2533. DB::commit();
  2534. yield [
  2535. 'type' => 'done',
  2536. 'script' => $script_arr,
  2537. 'answer' => $fullContent,
  2538. 'reasoning' => $fullReasoningContent,
  2539. 'usage' => $usage
  2540. ];
  2541. }
  2542. /**
  2543. * 上传文件识别文字内容并与 DeepSeek 进行对话
  2544. *
  2545. * @param array $data 包含以下参数:
  2546. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2547. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  2548. * - model: 使用的模型(r1 或 v3,默认 v3)
  2549. * @return array
  2550. */
  2551. public function chatWithFile($data) {
  2552. $script_id = getProp($data, 'script_id');
  2553. $file = getProp($data, 'file');
  2554. $content = getProp($data, 'content', '');
  2555. $bid = getProp($data, 'bid', 0);
  2556. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2557. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2558. $prompt = getProp($data, 'prompt');
  2559. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2560. if (!empty($prompt)) {
  2561. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2562. }
  2563. $question = getProp($data, 'question', $baseQuestion);
  2564. // 处理文本模型
  2565. $model = getProp($data, 'model');
  2566. if (!$model) {
  2567. // 用户没有输入,使用默认值
  2568. $model = 'doubao-seed-2-0-mini-260215';
  2569. }
  2570. // 验证模型是否在可用模型表中
  2571. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2572. $model = 'doubao-seed-2-0-mini-260215';
  2573. }
  2574. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2575. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2576. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2577. if ($model === 'deepseek-chat') {
  2578. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2579. $model = 'deepseek-v4-flash';
  2580. $thinkingMode = 'disabled';
  2581. } elseif ($model === 'deepseek-reasoner') {
  2582. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2583. $model = 'deepseek-v4-flash';
  2584. $thinkingMode = 'enabled';
  2585. }
  2586. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2587. if (!$script) {
  2588. Utils::throwError('20003:剧本不存在');
  2589. }
  2590. if (!$file && !$content && !$bid) {
  2591. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2592. }
  2593. // 提取文件内容
  2594. if ($file) {
  2595. $content = $this->extractFileContent($file);
  2596. if (!$content) {
  2597. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2598. }
  2599. } elseif ($bid) {
  2600. $content = $this->getContentByBid($bid);
  2601. if (!$content) {
  2602. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2603. }
  2604. } elseif ($content) {
  2605. $content = filterContent($content);
  2606. } elseif ($prompt) {
  2607. $content = filterContent($prompt);
  2608. } else {
  2609. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2610. }
  2611. // 构建消息
  2612. $messages = [
  2613. $this->sys_message,
  2614. [
  2615. 'role' => 'user',
  2616. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2617. ]
  2618. ];
  2619. $post_data = [
  2620. 'model' => $model,
  2621. 'messages' => $messages,
  2622. // 'max_tokens' => 8192,
  2623. 'temperature' => 0.7,
  2624. 'frequency_penalty' => 0,
  2625. 'presence_penalty' => 0,
  2626. 'thinking' => ['type' => $thinkingMode],
  2627. 'response_format' => ['type' => 'text'],
  2628. 'stream' => false
  2629. ];
  2630. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2631. // 根据模型类型选择调用方法
  2632. $fullContent = '';
  2633. $usage = [];
  2634. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2635. // DeepSeek 官方模型使用 DeepSeek API
  2636. $chatResult = $this->chatOnly($post_data);
  2637. } else if (in_array($model, $this->gpt_text_models)) {
  2638. // GPT-5.4 模型使用 TokenRouter API
  2639. $chatResult = $this->gpt54ChatOnly($post_data);
  2640. } else {
  2641. // 其他模型使用火山引擎API
  2642. $chatResult = $this->volcEngineChatCompletion($post_data);
  2643. }
  2644. if (is_array($chatResult)) {
  2645. $fullContent = $chatResult['fullContent'];
  2646. $usage = $chatResult['usage'];
  2647. }
  2648. $script_arr = [];
  2649. // 处理结果
  2650. if ($fullContent) {
  2651. $script_arr = extractScriptContent($fullContent);
  2652. }
  2653. // 返回前保存剧本内容
  2654. DB::table('mp_scripts')->where('id', $script_id)->update([
  2655. 'content' => $content,
  2656. 'updated_at' => date('Y-m-d H:i:s')
  2657. ]);
  2658. return [
  2659. 'script' => $script_arr,
  2660. 'answer' => $fullContent,
  2661. 'usage' => $usage
  2662. ];
  2663. }
  2664. public function getEpisodeContent($data) {
  2665. $group_id = getProp($data, 'group_id');
  2666. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  2667. }
  2668. public function saveEpisodeContent($data) {
  2669. $script_id = getProp($data, 'script_id');
  2670. $group_id = getProp($data, 'group_id');
  2671. $start_episode_sequence = getProp($data, 'start_episode_number');
  2672. $end_episode_sequence = getProp($data, 'end_episode_number');
  2673. // 检查是否存在重叠的剧集序号范围
  2674. $exists_groups = DB::table('mp_script_episode_group')
  2675. ->where('script_id', $script_id)
  2676. ->where('id', '<>', $group_id) // 排除当前组
  2677. ->where('is_deleted', 0)
  2678. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2679. // 检查新范围是否与现有范围重叠
  2680. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2681. // 新范围的开始在现有范围内
  2682. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2683. ->where('end_episode_number', '>=', $start_episode_sequence);
  2684. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2685. // 新范围的结束在现有范围内
  2686. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2687. ->where('end_episode_number', '>=', $end_episode_sequence);
  2688. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2689. // 新范围完全包含现有范围
  2690. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2691. ->where('end_episode_number', '<=', $end_episode_sequence);
  2692. });
  2693. })
  2694. ->select('start_episode_number', 'end_episode_number')
  2695. ->get();
  2696. if ($exists_groups->isNotEmpty()) {
  2697. $conflict_ranges = [];
  2698. foreach ($exists_groups as $group) {
  2699. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2700. }
  2701. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2702. }
  2703. $episode_content = getProp($data, 'episode_content');
  2704. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  2705. 'content' => $episode_content,
  2706. 'start_episode_number' => $start_episode_sequence,
  2707. 'end_episode_number' => $end_episode_sequence,
  2708. 'updated_at' => date('Y-m-d H:i:s')
  2709. ]);
  2710. $script_arr =getProp($data, 'script', []);
  2711. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  2712. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2713. $script_id = getProp($data, 'script_id');
  2714. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  2715. try {
  2716. DB::beginTransaction();
  2717. $update_data = [
  2718. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2719. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2720. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2721. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2722. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2723. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2724. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2725. 'status' => 3,
  2726. 'start_episode_sequence' => $start_episode_sequence,
  2727. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  2728. 'episode_num' => count($script_arr['episodes']),
  2729. 'updated_at' => date('Y-m-d H:i:s')
  2730. ];
  2731. // 保存剧本内容
  2732. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  2733. if (!$boolen) {
  2734. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  2735. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  2736. Utils::throwError('20003:剧本内容保存失败');
  2737. }
  2738. // 保存分集内容
  2739. // 删除历史分集内容
  2740. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  2741. $episodes = [];
  2742. $sequence = 1;
  2743. foreach ($script_arr['episodes'] as $episode) {
  2744. $segment_number = 1;
  2745. foreach($episode['segments'] as $segment) {
  2746. $episodes[] = [
  2747. 'script_id' => $script_id,
  2748. 'episode_number' => $episode['episode_number'],
  2749. 'title' => $episode['title'],
  2750. // 'content' => $episode['content'],
  2751. 'content' => '',
  2752. 'segment_number' => $segment_number,
  2753. 'segment_content' => $segment['segment_content'],
  2754. 'sequence' => $sequence,
  2755. 'created_at' => date('Y-m-d H:i:s'),
  2756. 'updated_at' => date('Y-m-d H:i:s')
  2757. ];
  2758. $sequence++;
  2759. $segment_number++;
  2760. }
  2761. }
  2762. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2763. if (!$boolen2) {
  2764. dLog('deepseek')->info('分集内容保存失败', $episodes);
  2765. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  2766. Utils::throwError('20003:分集内容保存失败');
  2767. }
  2768. } catch (\Exception $e) {
  2769. DB::rollBack();
  2770. Utils::throwError('20003:'.$e->getMessage());
  2771. }
  2772. DB::commit();
  2773. return true;
  2774. }
  2775. public function getBookContent($data) {
  2776. $bid = getProp($data, 'bid');
  2777. $start_sequence = getProp($data, 'start_sequence');
  2778. $end_sequence = getProp($data, 'end_sequence');
  2779. $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])
  2780. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  2781. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  2782. return $return_content;
  2783. }
  2784. public function exportScript($data) {
  2785. $filename = getProp($data, 'filename');
  2786. $script_id = getProp($data, 'script_id');
  2787. $group_id = getProp($data, 'group_id');
  2788. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  2789. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  2790. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2791. $script = (array)$script;
  2792. // 获取分集组信息
  2793. if ($group_id) {
  2794. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2795. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2796. ->get()->map(function($value) {
  2797. return (array)$value;
  2798. })->toArray();
  2799. }else {
  2800. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2801. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2802. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  2803. return (array)$value;
  2804. })->toArray();
  2805. }
  2806. if (!$groups) Utils::throwError('20003:分集不存在');
  2807. $script['group'] = $groups;
  2808. $export_type = getProp($data, 'export_type', 'txt');
  2809. // 生成文件名
  2810. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  2811. // 根据导出类型生成不同格式的文件
  2812. switch ($export_type) {
  2813. case 'txt':
  2814. return $this->exportScriptAsTxt($script, $filename);
  2815. case 'pdf':
  2816. return $this->exportScriptAsPdf($script, $filename);
  2817. default:
  2818. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  2819. }
  2820. }
  2821. /**
  2822. * 导出剧本为TXT格式
  2823. */
  2824. private function exportScriptAsTxt($script, $filename) {
  2825. // 构建TXT内容
  2826. $content = $this->buildScriptContent($script);
  2827. // 设置响应头,直接下载
  2828. header('Content-Type: text/plain; charset=utf-8');
  2829. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  2830. header('Content-Length: ' . strlen($content));
  2831. // 输出内容并结束
  2832. echo $content;
  2833. exit();
  2834. }
  2835. /**
  2836. * 导出剧本为PDF格式
  2837. */
  2838. private function exportScriptAsPdf($script, $filename) {
  2839. // 使用HTML转PDF的方式来更好地支持中文
  2840. $htmlContent = $this->buildScriptHtmlForPdf($script);
  2841. // 创建PDF实例
  2842. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  2843. // 设置文档信息
  2844. $pdf->SetCreator('剧本导出系统');
  2845. $pdf->SetAuthor('系统');
  2846. $pdf->SetTitle($script['script_name']);
  2847. $pdf->SetSubject('剧本导出');
  2848. // 设置边距
  2849. $pdf->SetMargins(15, 15, 15);
  2850. $pdf->SetAutoPageBreak(TRUE, 15);
  2851. // 添加页面
  2852. $pdf->AddPage();
  2853. // 注册并使用 simsun.ttf 字体
  2854. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  2855. // 使用HTML内容生成PDF
  2856. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  2857. // 直接输出PDF文件供下载
  2858. header('Content-Type: application/pdf');
  2859. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  2860. // 直接输出PDF内容
  2861. $pdf->Output($filename . '.pdf', 'D');
  2862. exit();
  2863. }
  2864. /**
  2865. * 构建用于PDF的HTML内容
  2866. */
  2867. private function buildScriptHtmlForPdf($script) {
  2868. $html = '<style>
  2869. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  2870. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  2871. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  2872. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  2873. .info { margin-bottom: 8px; }
  2874. .group { margin-bottom: 30px; page-break-inside: avoid; }
  2875. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  2876. .segment { margin-bottom: 10px; margin-left: 20px; }
  2877. .episode-content { white-space: pre-wrap; }
  2878. </style>';
  2879. // 标题
  2880. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  2881. // 处理分组数据
  2882. if (!empty($script['group']) && is_array($script['group'])) {
  2883. $groups = (array)$script['group'];
  2884. foreach ($groups as $group) {
  2885. $html .= '<div class="group">';
  2886. // 分组标题
  2887. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  2888. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  2889. // 故事梗概
  2890. if (!empty($group['intro'])) {
  2891. $html .= '<h3>故事梗概</h3>';
  2892. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  2893. }
  2894. // 剧本亮点
  2895. if (!empty($group['highlights'])) {
  2896. $html .= '<h3>剧本亮点</h3>';
  2897. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  2898. }
  2899. // 人物关系
  2900. if (!empty($group['role_relationship'])) {
  2901. $html .= '<h3>人物关系</h3>';
  2902. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  2903. }
  2904. // 核心矛盾
  2905. if (!empty($group['core_contradiction'])) {
  2906. $html .= '<h3>核心矛盾</h3>';
  2907. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  2908. }
  2909. // 主体列表
  2910. if (!empty($group['roles']) && is_array($group['roles'])) {
  2911. $html .= '<h3>主体列表</h3>';
  2912. $html .= '<ul>';
  2913. foreach ($group['roles'] as $role) {
  2914. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  2915. }
  2916. $html .= '</ul>';
  2917. }
  2918. // 美术风格
  2919. if (!empty($group['art_style'])) {
  2920. $html .= '<h3>美术风格</h3>';
  2921. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  2922. }
  2923. // 场景列表
  2924. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  2925. $html .= '<h3>场景列表</h3>';
  2926. $html .= '<ul>';
  2927. foreach ($group['scenes'] as $scene) {
  2928. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  2929. }
  2930. $html .= '</ul>';
  2931. }
  2932. // 分集剧本
  2933. if (!empty($group['episode_content'])) {
  2934. $html .= '<h3>分集剧本</h3>';
  2935. // 去除零宽字符和其他不可见字符
  2936. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  2937. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  2938. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  2939. }
  2940. $html .= '</div>';
  2941. }
  2942. }
  2943. return $html;
  2944. }
  2945. /**
  2946. * 构建PDF内容
  2947. */
  2948. private function buildPdfContent($pdf, $script) {
  2949. // 标题
  2950. $pdf->SetFont('dejavusans', 'B', 18);
  2951. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  2952. $pdf->Ln(5);
  2953. // 基本信息
  2954. $pdf->SetFont('dejavusans', '', 12);
  2955. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  2956. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  2957. $pdf->Ln(5);
  2958. // 剧本简介
  2959. if (!empty($script['intro'])) {
  2960. $pdf->SetFont('dejavusans', 'B', 14);
  2961. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  2962. $pdf->SetFont('dejavusans', '', 12);
  2963. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  2964. $pdf->Ln(3);
  2965. }
  2966. // 亮点
  2967. if (!empty($script['highlights'])) {
  2968. $pdf->SetFont('dejavusans', 'B', 14);
  2969. $pdf->Cell(0, 10, '亮点', 0, 1);
  2970. $pdf->SetFont('dejavusans', '', 12);
  2971. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  2972. $pdf->Ln(3);
  2973. }
  2974. // 核心矛盾
  2975. if (!empty($script['core_contradiction'])) {
  2976. $pdf->SetFont('dejavusans', 'B', 14);
  2977. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  2978. $pdf->SetFont('dejavusans', '', 12);
  2979. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  2980. $pdf->Ln(3);
  2981. }
  2982. // 艺术风格
  2983. if (!empty($script['art_style'])) {
  2984. $pdf->SetFont('dejavusans', 'B', 14);
  2985. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  2986. $pdf->SetFont('dejavusans', '', 12);
  2987. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  2988. $pdf->Ln(3);
  2989. }
  2990. // 备注
  2991. if (!empty($script['remark'])) {
  2992. $pdf->SetFont('dejavusans', 'B', 14);
  2993. $pdf->Cell(0, 10, '备注', 0, 1);
  2994. $pdf->SetFont('dejavusans', '', 12);
  2995. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  2996. $pdf->Ln(3);
  2997. }
  2998. // 角色列表
  2999. if (!empty($script['roles']) && is_array($script['roles'])) {
  3000. $pdf->SetFont('dejavusans', 'B', 14);
  3001. $pdf->Cell(0, 10, '角色列表', 0, 1);
  3002. $pdf->SetFont('dejavusans', '', 12);
  3003. foreach ($script['roles'] as $index => $role) {
  3004. if (is_array($role) || is_object($role)) {
  3005. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  3006. } else {
  3007. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  3008. }
  3009. }
  3010. $pdf->Ln(3);
  3011. }
  3012. // 角色关系
  3013. if (!empty($script['role_relationship'])) {
  3014. $pdf->SetFont('dejavusans', 'B', 14);
  3015. $pdf->Cell(0, 10, '角色关系', 0, 1);
  3016. $pdf->SetFont('dejavusans', '', 12);
  3017. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  3018. $pdf->Ln(3);
  3019. }
  3020. // 场景列表
  3021. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  3022. $pdf->SetFont('dejavusans', 'B', 14);
  3023. $pdf->Cell(0, 10, '场景列表', 0, 1);
  3024. $pdf->SetFont('dejavusans', '', 12);
  3025. foreach ($script['scenes'] as $index => $scene) {
  3026. if (is_array($scene) || is_object($scene)) {
  3027. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  3028. } else {
  3029. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  3030. }
  3031. }
  3032. $pdf->Ln(5);
  3033. }
  3034. // 分集内容
  3035. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  3036. $pdf->SetFont('dejavusans', 'B', 16);
  3037. $pdf->Cell(0, 12, '分集内容', 0, 1);
  3038. $pdf->Ln(3);
  3039. foreach ($script['episodes'] as $episode) {
  3040. // 检查是否需要新页面
  3041. if ($pdf->GetY() > 250) {
  3042. $pdf->AddPage();
  3043. }
  3044. $pdf->SetFont('dejavusans', 'B', 14);
  3045. $episodeTitle = '第' . $episode['episode_number'] . '集';
  3046. if (!empty($episode['title'])) {
  3047. $episodeTitle .= ':' . $episode['title'];
  3048. }
  3049. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  3050. // 处理分段内容
  3051. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  3052. $pdf->SetFont('dejavusans', '', 12);
  3053. foreach ($episode['segments'] as $segment) {
  3054. if (!empty($segment['segment_content'])) {
  3055. // 如果有分段编号,显示分段标题
  3056. if (!empty($segment['segment_number'])) {
  3057. $pdf->SetFont('dejavusans', 'B', 12);
  3058. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  3059. $pdf->SetFont('dejavusans', '', 12);
  3060. }
  3061. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  3062. $pdf->Ln(2);
  3063. }
  3064. }
  3065. }
  3066. $pdf->Ln(5);
  3067. }
  3068. }
  3069. }
  3070. /**
  3071. * 构建剧本文本内容
  3072. */
  3073. private function buildScriptContent($script) {
  3074. $content = '';
  3075. $groups = $script['group'];
  3076. $groups = (array)$groups;
  3077. foreach ($groups as $group) {
  3078. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  3079. // 剧本基本信息
  3080. if (!empty($group['intro'])) {
  3081. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  3082. }
  3083. if (!empty($group['highlights'])) {
  3084. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  3085. }
  3086. if (!empty($group['role_relationship'])) {
  3087. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  3088. }
  3089. if (!empty($group['core_contradiction'])) {
  3090. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  3091. }
  3092. if (!empty($group['roles']) && is_array($group['roles'])) {
  3093. $content .= "###主体列表\n";
  3094. foreach ($group['roles'] as $role) {
  3095. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  3096. }
  3097. $content .= "\n\n";
  3098. }
  3099. if (!empty($group['art_style'])) {
  3100. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  3101. }
  3102. // 场景信息
  3103. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3104. $content .= "###场景列表\n";
  3105. foreach ($group['scenes'] as $scene) {
  3106. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  3107. }
  3108. $content .= "\n\n";
  3109. }
  3110. // 分集内容
  3111. if (!empty($group['episode_content'])) {
  3112. $content .= "###分集剧本\n";
  3113. $content .= $group['episode_content'];
  3114. // foreach ($script['episodes'] as $episode) {
  3115. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  3116. // // if (!empty($episode['episode_name'])) {
  3117. // // $content .= ":" . $episode['episode_name'];
  3118. // // }
  3119. // // $content .= "\n";
  3120. // $content .= $episode['episode_content'] . "\n\n";
  3121. // }
  3122. }
  3123. }
  3124. return $content;
  3125. }
  3126. /**
  3127. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3128. *
  3129. * @param array $data 包含以下参数:
  3130. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3131. * - question: 用户问题(可选)
  3132. * - model: 使用的模型(r1 或 v3,默认 v3)
  3133. * @return \Generator 返回生成器,用于流式输出
  3134. */
  3135. public function addChat($data) {
  3136. $uid = Site::getUid();
  3137. $anime_id = getProp($data, 'anime_id');
  3138. if (!$anime_id) Utils::throwError('20003:请选择对话');
  3139. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3140. if (!$anime) Utils::throwError('20003:对话不存在');
  3141. $file = getProp($data, 'file');
  3142. $content = getProp($data, 'content', '');
  3143. $bid = getProp($data, 'bid', 0);
  3144. $script_id = getProp($data, 'script_id', 0);
  3145. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  3146. $prompt = getProp($data, 'prompt');
  3147. $user_anime_name = getProp($anime, 'anime_name');
  3148. // 处理文本模型
  3149. $model = getProp($data, 'model');
  3150. if (!$model) {
  3151. // 用户没有输入,从anime表获取
  3152. $model = getProp($anime, 'model');
  3153. if (!$model) {
  3154. // anime表也没有,使用默认值
  3155. $model = 'doubao-seed-2-0-mini-260215';
  3156. }
  3157. }
  3158. // 验证模型是否在可用模型表中
  3159. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3160. $model = 'doubao-seed-2-0-mini-260215';
  3161. }
  3162. $is_multi = getProp($anime, 'is_multi');
  3163. $is_single = (int)$is_multi !== 1;
  3164. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3165. if ($prompt) {
  3166. $question .= "本次修改要求如下:\n{$prompt}";
  3167. }
  3168. // if (!$file && !$content && !$bid) {
  3169. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3170. // }
  3171. // 提取文件内容
  3172. if ($file) {
  3173. $content = $this->extractFileContent($file);
  3174. if (!$content) {
  3175. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3176. }
  3177. } elseif ($script_id) {
  3178. $content = $this->getContentByScriptId($script_id);
  3179. if (!$content) {
  3180. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3181. }
  3182. } elseif ($bid) {
  3183. $content = $this->getContentByBid($bid);
  3184. if (!$content) {
  3185. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3186. }
  3187. } elseif ($content) {
  3188. $content = filterContent($content);
  3189. } else {
  3190. $content = getProp($anime, 'content');
  3191. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3192. $need_generate_content = true;
  3193. }
  3194. }
  3195. // 美术风格
  3196. $input_art_style = getProp($data, 'art_style');
  3197. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3198. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3199. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3200. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3201. 中年女:邻居阿姨
  3202. 老年男:幽默大爷
  3203. 老年女:婆婆
  3204. 萌娃:奶气萌娃";
  3205. // 判断是否需要生成原文内容
  3206. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3207. // 如果需要生成原文内容,添加额外的要求
  3208. $content_generation_requirement = $need_generate_content
  3209. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3210. : "";
  3211. // 美术风格
  3212. if (!$mappedArtStyle) {
  3213. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3214. }else {
  3215. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3216. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3217. }else {
  3218. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3219. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3220. }
  3221. }
  3222. $systemPrompt = $is_single
  3223. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3224. 强制要求:
  3225. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3226. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3227. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3228. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3229. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3230. 普通要求:
  3231. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3232. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3233. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  3234. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3235. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3236. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3237. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3238. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3239. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3240. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3241. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3242. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3243. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3244. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3245. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3246. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3247. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3248. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3249. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3250. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3251. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3252. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3253. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3254. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3255. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3256. 5.{$mappedArtStyle_prompt}\n\n
  3257. 示例如下:\n
  3258. ###剧本名:西昆仑
  3259. ###故事梗概
  3260. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3261. ###剧本亮点
  3262. 亮点1:绝境奇药,生死一线
  3263. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3264. 亮点2:结拜兄妹,化解尴尬
  3265. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3266. 亮点3:纤发夺命,情愫暗涌
  3267. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3268. ###人物关系
  3269. 阿雪与梁萧之间存在兄妹之情。
  3270. ###核心矛盾
  3271. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3272. ###主体列表
  3273. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3274. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3275. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3276. 姿态:站立。}{{甜心小美}}
  3277. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3278. 全景,正面拍摄,青年女性,亚洲人。
  3279. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3280. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3281. 姿态:站立。}{{阳光青年}}
  3282. ###美术风格
  3283. 基础画风风格词:厚涂古风
  3284. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3285. ###场景列表
  3286. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3287. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3288. 无人物。}
  3289. ###分镜剧本
  3290. ##第1幕:徐家老旧厨房 白天 室内
  3291. 分镜1
  3292. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3293. 场景:徐家老旧厨房
  3294. 构图设计:全景,低角度仰视
  3295. 运镜调度:手持拍摄
  3296. 配音角色:旁白
  3297. 出镜角色:许芸-校服装、徐母
  3298. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3299. 画面类型:普通画面
  3300. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3301. 分镜2
  3302. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3303. 场景:徐家老旧厨房
  3304. 构图设计:近景,徐母面部特写
  3305. 运镜调度:固定镜头
  3306. 配音角色:徐母
  3307. 出镜角色:徐母
  3308. 台词内容:问我夜不归宿死哪儿去了。
  3309. 画面类型:对口型
  3310. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3311. ##第2幕:徐家简陋客厅 黄昏 室内
  3312. 分镜3
  3313. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3314. 场景:徐家简陋客厅
  3315. 构图设计:全景,景深虚化
  3316. 运镜调度:固定镜头
  3317. 配音角色:旁白
  3318. 出镜角色:无
  3319. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3320. 画面类型:普通画面
  3321. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3322. 分镜4
  3323. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3324. 场景:徐家简陋客厅
  3325. 构图设计:特写,火车票
  3326. 运镜调度:固定镜头
  3327. 配音角色:旁白
  3328. 出镜角色:无
  3329. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3330. 画面类型:普通画面
  3331. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  3332. "
  3333. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3334. 强制要求:\n
  3335. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3336. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3337. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3338. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3339. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3340. 普通要求:\n
  3341. 1.剧本名(必须生成)必须与文档内容高度相关
  3342. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3343. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3344. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3345. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3346. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3347. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3348. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3349. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3350. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3351. 4.{$mappedArtStyle_prompt}\n\n
  3352. 示例如下:\n
  3353. ###剧本名:西昆仑
  3354. ###故事梗概
  3355. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3356. ###剧本亮点
  3357. 亮点1:绝境奇药,生死一线
  3358. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3359. 亮点2:结拜兄妹,化解尴尬
  3360. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3361. 亮点3:纤发夺命,情愫暗涌
  3362. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3363. ###人物关系
  3364. 阿雪与梁萧之间存在兄妹之情。
  3365. ###核心矛盾
  3366. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3367. ###主体列表
  3368. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3369. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3370. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3371. 姿态:站立。}{{甜心小美}}
  3372. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3373. 全景,正面拍摄,青年女性,亚洲人。
  3374. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3375. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3376. 姿态:站立。}{{阳光青年}}
  3377. ###美术风格
  3378. 基础画风风格词:厚涂古风
  3379. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3380. ###场景列表
  3381. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3382. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3383. 无人物。}";
  3384. // 构建消息
  3385. $messages = [
  3386. [
  3387. 'role' => 'system',
  3388. 'content' => $systemPrompt
  3389. ],
  3390. [
  3391. 'role' => 'user',
  3392. 'content' => "以下是文档内容:
  3393. {$content}
  3394. 用户问题:
  3395. {$question}"
  3396. ]
  3397. ];
  3398. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3399. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3400. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3401. if ($model === 'deepseek-chat') {
  3402. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3403. $model = 'deepseek-v4-flash';
  3404. $thinkingMode = 'disabled';
  3405. } elseif ($model === 'deepseek-reasoner') {
  3406. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3407. $model = 'deepseek-v4-flash';
  3408. $thinkingMode = 'enabled';
  3409. }
  3410. $post_data = [
  3411. 'model' => $model,
  3412. 'messages' => $messages,
  3413. // 'max_tokens' => 8192,
  3414. 'temperature' => 0.7,
  3415. 'frequency_penalty' => 0,
  3416. 'presence_penalty' => 0,
  3417. 'response_format' => ['type' => 'text'],
  3418. 'thinking' => ['type'=>$thinkingMode],
  3419. 'stream' => true // 启用流式输出
  3420. ];
  3421. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3422. // 根据模型类型选择调用方法
  3423. $fullContent = '';
  3424. $fullReasoningContent = '';
  3425. $usage = [];
  3426. try {
  3427. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3428. // DeepSeek 官方模型使用 DeepSeek API
  3429. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3430. } else if (in_array($model, $this->gpt_text_models)) {
  3431. // GPT-5.4 模型使用 TokenRouter API
  3432. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3433. } else {
  3434. // 其他模型使用火山引擎API
  3435. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3436. }
  3437. // 验证返回值类型
  3438. if (!is_iterable($streamGenerator)) {
  3439. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  3440. dLog('deepseek')->error('addChat流式生成器无效', [
  3441. 'generator_type' => $errorType,
  3442. 'model' => $model,
  3443. 'anime_id' => $anime_id
  3444. ]);
  3445. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  3446. 'type' => $errorType,
  3447. 'model' => $model
  3448. ]);
  3449. yield [
  3450. 'type' => 'error',
  3451. 'script' => [],
  3452. 'episode' => [],
  3453. 'answer' => '',
  3454. 'reasoning' => '',
  3455. 'usage' => [],
  3456. 'error' => '接口返回数据异常,请重新请求'
  3457. ];
  3458. return;
  3459. }
  3460. // 处理流式输出
  3461. foreach ($streamGenerator as $chunk) {
  3462. if (isset($chunk['type'])) {
  3463. if ($chunk['type'] === 'done') {
  3464. // 最终结果
  3465. $fullContent = $chunk['full_content'];
  3466. $fullReasoningContent = $chunk['full_reasoning'];
  3467. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3468. } else {
  3469. // 逐块yield数据
  3470. yield $chunk;
  3471. }
  3472. }
  3473. }
  3474. } catch (\Exception $e) {
  3475. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  3476. 'model' => $model,
  3477. 'anime_id' => $anime_id,
  3478. 'trace' => $e->getTraceAsString()
  3479. ]);
  3480. logDB('deepseek', 'error', 'addChat流式处理失败', [
  3481. 'error' => $e->getMessage(),
  3482. 'model' => $model
  3483. ]);
  3484. yield [
  3485. 'type' => 'error',
  3486. 'script' => [],
  3487. 'episode' => [],
  3488. 'answer' => '',
  3489. 'reasoning' => '',
  3490. 'usage' => [],
  3491. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  3492. ];
  3493. return;
  3494. }
  3495. dLog('deepseek')->info('完整内容: '.$fullContent);
  3496. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3497. // 处理完整内容并返回最终结果
  3498. $script_arr = [];
  3499. if ($fullContent) {
  3500. $script_arr = handleScriptContent($fullContent);
  3501. dLog('deepseek')->info('解析内容', $script_arr);
  3502. logDB('deepseek', 'info', '解析内容', $script_arr);
  3503. }
  3504. if (empty($script_arr['roles'])) {
  3505. // 未生成剧本相关内容,保存对话记录并返回提示
  3506. dLog('deepseek')->info('未生成剧本相关的内容');
  3507. try {
  3508. DB::beginTransaction();
  3509. $now = date('Y-m-d H:i:s');
  3510. // 保存对话记录
  3511. $records = [
  3512. [
  3513. 'uid' => $uid,
  3514. 'anime_id' => $anime_id,
  3515. 'sequence' => 0,
  3516. 'role' => 'user',
  3517. 'content' => $prompt,
  3518. 'created_at' => $now,
  3519. 'updated_at' => $now
  3520. ],
  3521. [
  3522. 'uid' => $uid,
  3523. 'anime_id' => $anime_id,
  3524. 'sequence' => 0,
  3525. 'role' => 'assistant',
  3526. // 'content' => $fullContent,
  3527. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  3528. 'created_at' => $now,
  3529. 'updated_at' => $now
  3530. ]
  3531. ];
  3532. DB::table('mp_anime_records')->insert($records);
  3533. DB::commit();
  3534. } catch (\Exception $e) {
  3535. DB::rollBack();
  3536. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3537. }
  3538. yield [
  3539. 'type' => 'done',
  3540. 'script' => [],
  3541. 'episode' => [],
  3542. 'answer' => $fullContent,
  3543. 'reasoning' => $fullReasoningContent,
  3544. 'usage' => $usage,
  3545. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  3546. ];
  3547. return;
  3548. }
  3549. // 如果需要生成原文内容,从script_arr中提取
  3550. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  3551. $content = $script_arr['content'];
  3552. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  3553. if (!$content) {
  3554. yield [
  3555. 'type' => 'done',
  3556. 'script' => [],
  3557. 'episode' => [],
  3558. 'answer' => $fullContent,
  3559. 'reasoning' => $fullReasoningContent,
  3560. 'usage' => $usage,
  3561. 'error' => '未生成剧本内容,请调整提示词再试'
  3562. ];
  3563. return;
  3564. }
  3565. }
  3566. // 替换美术风格
  3567. if ($mappedArtStyle !== '') {
  3568. $script_arr['art_style'] = $mappedArtStyle;
  3569. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  3570. }
  3571. // 新建动漫
  3572. if ($user_anime_name == '新剧本策划') {
  3573. $anime_name = getProp($script_arr, 'script_name');
  3574. // if (!$anime_name) {
  3575. // // 未识别到剧本名,保存对话记录并返回提示
  3576. // dLog('deepseek')->info('未能识别到剧本名称');
  3577. // try {
  3578. // DB::beginTransaction();
  3579. // $now = date('Y-m-d H:i:s');
  3580. // // 保存对话记录
  3581. // $records = [
  3582. // [
  3583. // 'uid' => $uid,
  3584. // 'anime_id' => $anime_id,
  3585. // 'sequence' => 0,
  3586. // 'role' => 'user',
  3587. // 'content' => $prompt,
  3588. // 'created_at' => $now,
  3589. // 'updated_at' => $now
  3590. // ],
  3591. // [
  3592. // 'uid' => $uid,
  3593. // 'anime_id' => $anime_id,
  3594. // 'sequence' => 0,
  3595. // 'role' => 'assistant',
  3596. // 'content' => '未能生成剧本名称,请重试',
  3597. // 'created_at' => $now,
  3598. // 'updated_at' => $now
  3599. // ]
  3600. // ];
  3601. // DB::table('mp_anime_records')->insert($records);
  3602. // DB::commit();
  3603. // } catch (\Exception $e) {
  3604. // DB::rollBack();
  3605. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3606. // }
  3607. // yield [
  3608. // 'type' => 'done',
  3609. // 'script' => [],
  3610. // 'episode' => [],
  3611. // 'answer' => $fullContent,
  3612. // 'reasoning' => $fullReasoningContent,
  3613. // 'usage' => $usage,
  3614. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  3615. // ];
  3616. // return;
  3617. // }
  3618. // 确认对话名称唯一性
  3619. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  3620. $anime_name = $anime_name . '_' . date('YmdHis');
  3621. }
  3622. }else {
  3623. $anime_name = $user_anime_name;
  3624. }
  3625. $table_data = [
  3626. 'user_id' => $uid,
  3627. 'anime_name' => $anime_name,
  3628. 'model' => $model,
  3629. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3630. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3631. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3632. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3633. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3634. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3635. 'art_style_type' => $input_art_style,
  3636. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3637. 'status' => '解析完成',
  3638. 'content' => $content,
  3639. 'is_multi' => $is_multi,
  3640. 'ace_mode' => $ace_mode,
  3641. 'generate_status' => '待执行',
  3642. 'updated_at' => date('Y-m-d H:i:s')
  3643. ];
  3644. if ($table_data['content']) {
  3645. $chapters = $this->splitContent($table_data['content']);
  3646. $chapter_count = count($chapters);
  3647. if ($chapter_count > 0) {
  3648. $table_data['start_episode_sequence'] = 1;
  3649. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  3650. }
  3651. }
  3652. // 如果有剧本ID则进行绑定
  3653. if ($script_id) {
  3654. $table_data['script_id'] = $script_id;
  3655. }
  3656. $single_episode = [];
  3657. try {
  3658. DB::beginTransaction();
  3659. $now = date('Y-m-d H:i:s');
  3660. // 更新动漫大纲
  3661. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3662. if (!$boolen) {
  3663. dLog('deepseek')->info('动漫保存失败', $table_data);
  3664. Utils::throwError('20003:动漫保存失败');
  3665. }
  3666. // 保存对话记录
  3667. $records = [
  3668. [
  3669. 'uid' => $uid,
  3670. 'anime_id' => $anime_id,
  3671. 'sequence' => 0,
  3672. 'role' => 'user',
  3673. 'content' => $prompt,
  3674. 'created_at' => date('Y-m-d H:i:s'),
  3675. 'updated_at' => date('Y-m-d H:i:s')
  3676. ],
  3677. [
  3678. 'uid' => $uid,
  3679. 'anime_id' => $anime_id,
  3680. 'sequence' => 0,
  3681. 'role' => 'assistant',
  3682. 'content' => $fullContent,
  3683. 'created_at' => date('Y-m-d H:i:s'),
  3684. 'updated_at' => date('Y-m-d H:i:s')
  3685. ]
  3686. ];
  3687. // 保存对话记录
  3688. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3689. if (!$boolen3) {
  3690. Utils::throwError('20003:对话记录保存失败');
  3691. }
  3692. if ($is_single) {
  3693. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3694. if (empty($episode_arr['acts'])) {
  3695. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3696. }
  3697. $saveResult = $this->saveEpisodeVersionData(
  3698. $anime_id,
  3699. 1,
  3700. $episode_arr,
  3701. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3702. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3703. null,
  3704. null,
  3705. false,
  3706. $content,
  3707. $now
  3708. );
  3709. $single_episode = $saveResult['episode'];
  3710. $episode_id = $saveResult['episode_id'];
  3711. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3712. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3713. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3714. 'updated_at' => $now
  3715. ]);
  3716. if ($boolen5 === false) {
  3717. Utils::throwError('20003:单剧集主表资源同步失败');
  3718. }
  3719. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3720. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3721. $episode_record_content = '确认分镜大纲';
  3722. if ($content !== '') {
  3723. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  3724. }
  3725. $episode_records = [
  3726. [
  3727. 'uid' => $uid,
  3728. 'anime_id' => $anime_id,
  3729. 'role' => 'user',
  3730. 'content' => $episode_record_content,
  3731. 'sequence' => 1,
  3732. 'episode_id' => $episode_id,
  3733. 'created_at' => $now,
  3734. 'updated_at' => $now
  3735. ],
  3736. [
  3737. 'uid' => $uid,
  3738. 'anime_id' => $anime_id,
  3739. 'role' => 'assistant',
  3740. 'content' => $fullContent,
  3741. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3742. 'sequence' => 1,
  3743. 'episode_id' => $episode_id,
  3744. 'created_at' => $now,
  3745. 'updated_at' => $now
  3746. ]
  3747. ];
  3748. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3749. if (!$boolen4) {
  3750. Utils::throwError('20003:单剧集分镜记录保存失败');
  3751. }
  3752. }
  3753. }catch (\Exception $e) {
  3754. DB::rollBack();
  3755. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  3756. yield [
  3757. 'type' => 'done',
  3758. 'answer' => $fullContent,
  3759. 'reasoning' => $fullReasoningContent,
  3760. 'usage' => $usage,
  3761. 'error' => $e->getMessage(),
  3762. ];
  3763. return;
  3764. }
  3765. DB::commit();
  3766. dLog('deepseek')->info('保存完毕');
  3767. if ($is_single && !empty($single_episode)) {
  3768. // $this->batchSetGlobalRoleImg([
  3769. // 'anime_id' => $anime_id,
  3770. // ]);
  3771. // $this->batchSetGlobalSceneImg([
  3772. // 'anime_id' => $anime_id,
  3773. // ]);
  3774. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  3775. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  3776. }
  3777. $table_data['anime_id'] = $anime_id;
  3778. $table_data['roles'] = json_decode($table_data['roles'], true);
  3779. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  3780. // $table_data['episodes'] = $script_arr['episodes'];
  3781. unset($table_data['created_at']);
  3782. unset($table_data['updated_at']);
  3783. unset($table_data['status']);
  3784. dLog('deepseek')->info('开始返回');
  3785. yield [
  3786. 'type' => 'done',
  3787. 'script' => $table_data,
  3788. 'episode' => $single_episode,
  3789. 'answer' => $fullContent,
  3790. 'reasoning' => $fullReasoningContent,
  3791. 'usage' => $usage
  3792. ];
  3793. }
  3794. public function reGenerateAnime($data) {
  3795. $uid = Site::getUid();
  3796. $file = getProp($data, 'file');
  3797. $content = getProp($data, 'content', '');
  3798. $bid = getProp($data, 'bid', 0);
  3799. $script_id = getProp($data, 'script_id', 0);
  3800. $anime_id = getProp($data, 'anime_id');
  3801. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3802. if (!$anime) {
  3803. Utils::throwError('20003:该对话不存在');
  3804. }
  3805. $user_anime_name = getProp($anime, 'anime_name');
  3806. $prompt = getProp($data, 'prompt');
  3807. // 处理文本模型
  3808. $model = getProp($data, 'model');
  3809. if (!$model) {
  3810. // 用户没有输入,从anime表获取
  3811. $model = getProp($anime, 'model');
  3812. if (!$model) {
  3813. // anime表也没有,使用默认值
  3814. $model = 'doubao-seed-2-0-mini-260215';
  3815. }
  3816. }
  3817. // 验证模型是否在可用模型表中
  3818. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3819. $model = 'doubao-seed-2-0-mini-260215';
  3820. }
  3821. $is_multi = getProp($anime, 'is_multi', 1);
  3822. $is_single = (int)$is_multi !== 1;
  3823. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  3824. if ($is_single) {
  3825. $episode_exists = DB::table('mp_anime_episodes')
  3826. ->where('anime_id', $anime_id)
  3827. ->where('sequence', 1)
  3828. ->exists();
  3829. if ($episode_exists) {
  3830. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  3831. }
  3832. }
  3833. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3834. if ($prompt) {
  3835. $question .= "本次修改要求如下:\n{$prompt}";
  3836. }
  3837. // 提取文件内容
  3838. if ($file) {
  3839. $content = $this->extractFileContent($file);
  3840. if (!$content) {
  3841. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3842. }
  3843. } elseif ($script_id) {
  3844. $content = $this->getContentByScriptId($script_id);
  3845. if (!$content) {
  3846. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3847. }
  3848. } elseif ($bid) {
  3849. $content = $this->getContentByBid($bid);
  3850. if (!$content) {
  3851. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3852. }
  3853. } elseif ($content) {
  3854. $content = filterContent($content);
  3855. }else {
  3856. $content = filterContent(getProp($anime, 'content'));
  3857. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3858. $need_generate_content = true;
  3859. }
  3860. }
  3861. // 判断是否需要生成原文内容
  3862. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3863. // 如果需要生成原文内容,添加额外的要求
  3864. $content_generation_requirement = $need_generate_content
  3865. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3866. : "";
  3867. // 美术风格
  3868. $input_art_style = getProp($anime, 'art_style');
  3869. if (!$input_art_style) {
  3870. $input_art_style = getProp($data, 'art_style');
  3871. }
  3872. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3873. // 美术风格
  3874. if (!$mappedArtStyle) {
  3875. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3876. }else {
  3877. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3878. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3879. }else {
  3880. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3881. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3882. }
  3883. }
  3884. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3885. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3886. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3887. 中年女:邻居阿姨
  3888. 老年男:幽默大爷
  3889. 老年女:婆婆
  3890. 萌娃:奶气萌娃";
  3891. $system_message = ['role'=>'system', 'content'=>$is_single
  3892. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3893. 强制要求:
  3894. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3895. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3896. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3897. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3898. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3899. 普通要求:
  3900. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3901. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3902. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3903. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3904. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3905. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3906. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3907. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3908. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3909. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3910. 3.$mappedArtStyle_prompt\n\n
  3911. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3912. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3913. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3914. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3915. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3916. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3917. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3918. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3919. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3920. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3921. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3922. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3923. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3924. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3925. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3926. 示例如下:\n
  3927. ###剧本名:西昆仑
  3928. ###故事梗概
  3929. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3930. ###剧本亮点
  3931. 亮点1:绝境奇药,生死一线
  3932. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3933. 亮点2:结拜兄妹,化解尴尬
  3934. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3935. 亮点3:纤发夺命,情愫暗涌
  3936. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3937. ###人物关系
  3938. 阿雪与梁萧之间存在兄妹之情。
  3939. ###核心矛盾
  3940. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3941. ###主体列表
  3942. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3943. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3944. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3945. 姿态:站立。}{{甜心小美}}
  3946. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3947. 全景,正面拍摄,青年女性,亚洲人。
  3948. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3949. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3950. 姿态:站立。}{{阳光青年}}
  3951. ###美术风格
  3952. 基础画风风格词:厚涂古风
  3953. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3954. ###场景列表
  3955. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3956. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3957. 无人物。}
  3958. ###分镜剧本
  3959. ##第1幕:徐家老旧厨房 白天 室内
  3960. 分镜1
  3961. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3962. 场景:徐家老旧厨房
  3963. 构图设计:全景,低角度仰视
  3964. 运镜调度:手持拍摄
  3965. 配音角色:旁白
  3966. 出镜角色:许芸-校服装、徐母
  3967. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3968. 画面类型:普通画面
  3969. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3970. 分镜2
  3971. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3972. 场景:徐家老旧厨房
  3973. 构图设计:近景,徐母面部特写
  3974. 运镜调度:固定镜头
  3975. 配音角色:徐母
  3976. 出镜角色:徐母
  3977. 台词内容:问我夜不归宿死哪儿去了。
  3978. 画面类型:对口型
  3979. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3980. ##第2幕:徐家简陋客厅 黄昏 室内
  3981. 分镜3
  3982. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3983. 场景:徐家简陋客厅
  3984. 构图设计:全景,景深虚化
  3985. 运镜调度:固定镜头
  3986. 配音角色:旁白
  3987. 出镜角色:无
  3988. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3989. 画面类型:普通画面
  3990. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3991. 分镜4
  3992. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3993. 场景:徐家简陋客厅
  3994. 构图设计:特写,火车票
  3995. 运镜调度:固定镜头
  3996. 配音角色:旁白
  3997. 出镜角色:无
  3998. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3999. 画面类型:普通画面
  4000. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4001. "
  4002. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4003. 强制要求:\n
  4004. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4005. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4006. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4007. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4008. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4009. 普通要求:\n
  4010. 1.剧本名(必须生成)必须与文档内容高度相关
  4011. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4012. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4013. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4014. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4015. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4016. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4017. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4018. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4019. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4020. 4.$mappedArtStyle_prompt\n\n
  4021. 示例如下:\n
  4022. ###剧本名:西昆仑
  4023. ###故事梗概
  4024. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4025. ###剧本亮点
  4026. 亮点1:绝境奇药,生死一线
  4027. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4028. 亮点2:结拜兄妹,化解尴尬
  4029. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4030. 亮点3:纤发夺命,情愫暗涌
  4031. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4032. ###人物关系
  4033. 阿雪与梁萧之间存在兄妹之情。
  4034. ###核心矛盾
  4035. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4036. ###主体列表
  4037. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4038. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4039. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4040. 姿态:站立。}{{甜心小美}}
  4041. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4042. 全景,正面拍摄,青年女性,亚洲人。
  4043. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4044. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4045. 姿态:站立。}{{阳光青年}}
  4046. ###美术风格
  4047. 基础画风风格词:厚涂古风
  4048. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4049. ###场景列表
  4050. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4051. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4052. 无人物。}"];
  4053. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  4054. $episode_count = $this->extractEpisodeNumber($prompt);
  4055. if ((int)getProp($anime, 'is_multi') !== 1) {
  4056. yield [
  4057. 'type' => 'done',
  4058. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  4059. 'reasoning' => '',
  4060. 'usage' => []
  4061. ];
  4062. return;
  4063. }
  4064. if ($episode_count) {
  4065. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  4066. $system_message = [
  4067. 'role' => 'system',
  4068. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4069. 强制要求:\n
  4070. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4071. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4072. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4073. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4074. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4075. 普通要求:\n
  4076. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4077. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4078. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4079. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4080. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4081. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4082. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4083. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4084. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4085. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  4086. 示例如下:\n
  4087. ###剧本名:西昆仑
  4088. ###故事梗概
  4089. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4090. ###剧本亮点
  4091. 亮点1:绝境奇药,生死一线
  4092. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4093. 亮点2:结拜兄妹,化解尴尬
  4094. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4095. 亮点3:纤发夺命,情愫暗涌
  4096. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4097. ###人物关系
  4098. 阿雪与梁萧之间存在兄妹之情。
  4099. ###核心矛盾
  4100. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4101. ###主体列表
  4102. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4103. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4104. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4105. 姿态:站立。}{{甜心小美}}
  4106. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4107. 全景,正面拍摄,青年女性,亚洲人。
  4108. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4109. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4110. 姿态:站立。}{{阳光青年}}
  4111. ###美术风格
  4112. 基础画风风格词:厚涂古风
  4113. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4114. ###场景列表
  4115. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4116. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4117. 无人物。}
  4118. ###分集详细内容
  4119. ##第1章 重生
  4120. 我重生了。
  4121. 源于一个男人偏执的暗恋。
  4122. ##第2章 相救
  4123. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  4124. 我眼睛扫向站在锅炉后的卞大伟。"
  4125. ];
  4126. // 构建消息
  4127. $messages = [
  4128. $system_message,
  4129. [
  4130. 'role' => 'user',
  4131. 'content' => "以下是文档内容:
  4132. {$content}
  4133. 用户问题:
  4134. {$question}"
  4135. ]
  4136. ];
  4137. }else {
  4138. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  4139. // 构建消息
  4140. $messages = [
  4141. $system_message,
  4142. [
  4143. 'role' => 'user',
  4144. 'content' => "以下是文档内容:
  4145. {$content}
  4146. 用户问题:
  4147. {$question}"
  4148. ]
  4149. ];
  4150. }else {
  4151. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  4152. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  4153. return (array)$value;
  4154. })->toArray();
  4155. array_unshift($messages, $system_message);
  4156. $messages[] = [
  4157. 'role' => 'user',
  4158. 'content' => $prompt
  4159. ];
  4160. }
  4161. }
  4162. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4163. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4164. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4165. if ($model === 'deepseek-chat') {
  4166. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4167. $model = 'deepseek-v4-flash';
  4168. $thinkingMode = 'disabled';
  4169. } elseif ($model === 'deepseek-reasoner') {
  4170. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4171. $model = 'deepseek-v4-flash';
  4172. $thinkingMode = 'enabled';
  4173. }
  4174. $post_data = [
  4175. 'model' => $model,
  4176. 'messages' => $messages,
  4177. // 'max_tokens' => 8192,
  4178. 'temperature' => 0.7,
  4179. 'frequency_penalty' => 0,
  4180. 'presence_penalty' => 0,
  4181. 'response_format' => ['type' => 'text'],
  4182. 'thinking' => ['type' => $thinkingMode],
  4183. 'stream' => true // 启用流式输出
  4184. ];
  4185. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4186. // 根据模型类型选择调用方法
  4187. $fullContent = '';
  4188. $fullReasoningContent = '';
  4189. $usage = [];
  4190. // dd($post_data);
  4191. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  4192. try {
  4193. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4194. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4195. } else if (in_array($model, $this->gpt_text_models)) {
  4196. // GPT-5.4 模型使用 TokenRouter API
  4197. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4198. } else {
  4199. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4200. }
  4201. // 验证返回值类型
  4202. if (!is_iterable($streamGenerator)) {
  4203. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4204. dLog('deepseek')->error('方法名流式生成器无效', [
  4205. 'generator_type' => $errorType,
  4206. 'model' => $model,
  4207. // 添加其他上下文信息
  4208. ]);
  4209. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  4210. 'type' => $errorType,
  4211. 'model' => $model
  4212. ]);
  4213. yield [
  4214. 'type' => 'error',
  4215. // 根据方法返回相应的空数据结构
  4216. 'answer' => '',
  4217. 'reasoning' => '',
  4218. 'usage' => [],
  4219. 'error' => '接口返回数据异常,请重新请求'
  4220. ];
  4221. return;
  4222. }
  4223. // 处理流式输出
  4224. foreach ($streamGenerator as $chunk) {
  4225. if (isset($chunk['type'])) {
  4226. if ($chunk['type'] === 'done') {
  4227. $fullContent = $chunk['full_content'];
  4228. $fullReasoningContent = $chunk['full_reasoning'];
  4229. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4230. } else {
  4231. yield $chunk;
  4232. }
  4233. }
  4234. }
  4235. } catch (\Exception $e) {
  4236. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  4237. 'model' => $model,
  4238. 'trace' => $e->getTraceAsString()
  4239. ]);
  4240. logDB('deepseek', 'error', '方法名流式处理失败', [
  4241. 'error' => $e->getMessage(),
  4242. 'model' => $model
  4243. ]);
  4244. yield [
  4245. 'type' => 'error',
  4246. // 根据方法返回相应的空数据结构
  4247. 'answer' => '',
  4248. 'reasoning' => '',
  4249. 'usage' => [],
  4250. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4251. ];
  4252. return;
  4253. }
  4254. dLog('deepseek')->info('完整内容: '.$fullContent);
  4255. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4256. // 处理完整内容并返回最终结果
  4257. $script_arr = [];
  4258. if ($fullContent) {
  4259. $script_arr = handleScriptContent($fullContent);
  4260. dLog('deepseek')->info('解析内容', $script_arr);
  4261. logDB('deepseek', 'info', '解析内容', $script_arr);
  4262. }
  4263. if (empty($script_arr['roles'])) {
  4264. // 未生成剧本相关内容,保存对话记录并返回提示
  4265. dLog('deepseek')->info('未生成剧本相关的内容');
  4266. try {
  4267. $now = date('Y-m-d H:i:s');
  4268. // 保存对话记录
  4269. $records = [
  4270. [
  4271. 'uid' => $uid,
  4272. 'anime_id' => $anime_id,
  4273. 'sequence' => 0,
  4274. 'role' => 'user',
  4275. 'content' => $prompt,
  4276. 'created_at' => $now,
  4277. 'updated_at' => $now
  4278. ],
  4279. [
  4280. 'uid' => $uid,
  4281. 'anime_id' => $anime_id,
  4282. 'sequence' => 0,
  4283. 'role' => 'assistant',
  4284. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  4285. 'created_at' => $now,
  4286. 'updated_at' => $now
  4287. ]
  4288. ];
  4289. DB::table('mp_anime_records')->insert($records);
  4290. } catch (\Exception $e) {
  4291. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4292. }
  4293. yield [
  4294. 'type' => 'done',
  4295. 'script' => [],
  4296. 'episode' => [],
  4297. 'answer' => $fullContent,
  4298. 'reasoning' => $fullReasoningContent,
  4299. 'usage' => $usage,
  4300. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4301. ];
  4302. return;
  4303. }
  4304. // 替换美术风格
  4305. if ($mappedArtStyle !== '') {
  4306. $script_arr['art_style'] = $mappedArtStyle;
  4307. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4308. }
  4309. if ($user_anime_name != '新剧本策划') {
  4310. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  4311. // 确认对话名称唯一性
  4312. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4313. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  4314. }
  4315. }else {
  4316. $anime_name = $user_anime_name;
  4317. }
  4318. $table_data = [
  4319. 'user_id' => $uid,
  4320. 'model' => $model,
  4321. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4322. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4323. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4324. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4325. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4326. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4327. 'art_style_type' => $input_art_style,
  4328. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4329. 'status' => '解析完成',
  4330. 'generate_status' => '待执行',
  4331. 'updated_at' => date('Y-m-d H:i:s')
  4332. ];
  4333. if ($anime_name) $table_data['anime_name'] = $anime_name;
  4334. // 如果是修改集数,则将content内容更新(会改变原文)
  4335. if (isset($episode_count) && $episode_count > 0) {
  4336. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  4337. $table_data['start_episode_sequence'] = 1;
  4338. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  4339. }else {
  4340. // 如果需要生成原文内容,从script_arr中提取
  4341. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4342. $table_data['content'] = $script_arr['content'];
  4343. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  4344. if (!$table_data['content']) {
  4345. yield [
  4346. 'type' => 'done',
  4347. 'script' => [],
  4348. 'episode' => [],
  4349. 'answer' => $fullContent,
  4350. 'reasoning' => $fullReasoningContent,
  4351. 'usage' => $usage,
  4352. 'error' => '未生成剧本内容,请调整提示词再试'
  4353. ];
  4354. return;
  4355. }
  4356. }
  4357. if (isset($table_data['content']) && $table_data['content']) {
  4358. $chapters = $this->splitContent($table_data['content']);
  4359. $chapter_count = count($chapters);
  4360. if ($chapter_count > 0) {
  4361. $table_data['start_episode_sequence'] = 1;
  4362. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4363. }
  4364. }
  4365. }
  4366. $single_episode = [];
  4367. try {
  4368. DB::beginTransaction();
  4369. $now = date('Y-m-d H:i:s');
  4370. // 更新动漫大纲
  4371. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4372. if (!$boolen) {
  4373. dLog('deepseek')->info('对话修改失败', $table_data);
  4374. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  4375. Utils::throwError('20003:对话修改失败');
  4376. }
  4377. // 保存对话记录
  4378. $records = [
  4379. [
  4380. 'uid' => $uid,
  4381. 'anime_id' => $anime_id,
  4382. 'sequence' => 0,
  4383. 'role' => 'user',
  4384. 'content' => $prompt,
  4385. 'created_at' => $now,
  4386. 'updated_at' => $now
  4387. ],
  4388. [
  4389. 'uid' => $uid,
  4390. 'anime_id' => $anime_id,
  4391. 'sequence' => 0,
  4392. 'role' => 'assistant',
  4393. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4394. 'content' => $fullContent,
  4395. 'created_at' => $now,
  4396. 'updated_at' => $now
  4397. ]
  4398. ];
  4399. // 保存对话记录
  4400. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4401. if (!$boolen3) {
  4402. Utils::throwError('20003:对话记录保存失败');
  4403. }
  4404. // 单剧集模式:生成并保存剧集信息
  4405. if ($is_single) {
  4406. $anime_name = getProp($anime, 'anime_name', '未命名');
  4407. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4408. if (empty($episode_arr['acts'])) {
  4409. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4410. }
  4411. $saveResult = $this->saveEpisodeVersionData(
  4412. $anime_id,
  4413. 1,
  4414. $episode_arr,
  4415. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4416. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4417. null,
  4418. null,
  4419. false,
  4420. $content,
  4421. $now
  4422. );
  4423. $single_episode = $saveResult['episode'];
  4424. $episode_id = $saveResult['episode_id'];
  4425. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4426. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4427. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4428. 'updated_at' => $now
  4429. ]);
  4430. if ($boolen5 === false) {
  4431. Utils::throwError('20003:单剧集主表资源同步失败');
  4432. }
  4433. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4434. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4435. $episode_record_content = '确认分镜大纲';
  4436. if ($content !== '') {
  4437. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4438. }
  4439. $episode_records = [
  4440. [
  4441. 'uid' => $uid,
  4442. 'anime_id' => $anime_id,
  4443. 'role' => 'user',
  4444. 'content' => $episode_record_content,
  4445. 'sequence' => 1,
  4446. 'episode_id' => $episode_id,
  4447. 'created_at' => $now,
  4448. 'updated_at' => $now
  4449. ],
  4450. [
  4451. 'uid' => $uid,
  4452. 'anime_id' => $anime_id,
  4453. 'role' => 'assistant',
  4454. 'content' => $fullContent,
  4455. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4456. 'sequence' => 1,
  4457. 'episode_id' => $episode_id,
  4458. 'created_at' => $now,
  4459. 'updated_at' => $now
  4460. ]
  4461. ];
  4462. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4463. if (!$boolen4) {
  4464. Utils::throwError('20003:单剧集分镜记录保存失败');
  4465. }
  4466. }
  4467. }catch (\Exception $e) {
  4468. DB::rollBack();
  4469. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  4470. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  4471. yield [
  4472. 'type' => 'done',
  4473. 'answer' => $fullContent,
  4474. 'reasoning' => $fullReasoningContent,
  4475. 'usage' => $usage,
  4476. 'error' => $e->getMessage(),
  4477. ];
  4478. return;
  4479. }
  4480. DB::commit();
  4481. dLog('deepseek')->info('保存完毕');
  4482. if ($is_single && !empty($single_episode)) {
  4483. // $this->batchSetGlobalRoleImg([
  4484. // 'anime_id' => $anime_id,
  4485. // ]);
  4486. // $this->batchSetGlobalSceneImg([
  4487. // 'anime_id' => $anime_id,
  4488. // ]);
  4489. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4490. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4491. }
  4492. $table_data['anime_id'] = $anime_id;
  4493. $table_data['roles'] = json_decode($table_data['roles'], true);
  4494. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4495. unset($table_data['updated_at']);
  4496. unset($table_data['status']);
  4497. yield [
  4498. 'type' => 'done',
  4499. 'script' => $table_data,
  4500. 'episode' => $single_episode,
  4501. 'answer' => $fullContent,
  4502. 'reasoning' => $fullReasoningContent,
  4503. 'usage' => $usage
  4504. ];
  4505. }
  4506. public function chat($data) {
  4507. $uid = Site::getUid();
  4508. $anime_id = getProp($data, 'anime_id');
  4509. $file = getProp($data, 'file');
  4510. $content = getProp($data, 'content', '');
  4511. $bid = getProp($data, 'bid', 0);
  4512. $script_id = getProp($data, 'script_id', 0);
  4513. $episode_number = getProp($data, 'episode_number', 1);
  4514. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4515. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4516. if (!$anime) Utils::throwError('20003:该对话不存在!');
  4517. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  4518. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  4519. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  4520. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  4521. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  4522. $roles = is_array($roles) ? $roles : [];
  4523. $scenes = is_array($scenes) ? $scenes : [];
  4524. // 获取最后一集序号
  4525. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  4526. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  4527. // 转换主体列表和场景列表的格式
  4528. // 获取参考主体或场景
  4529. if ((int)$episode_number === 1) {
  4530. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  4531. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  4532. }else {
  4533. $prev_episode_number = $episode_number - 1;
  4534. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  4535. }
  4536. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  4537. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  4538. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  4539. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  4540. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4541. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4542. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4543. 中年女:邻居阿姨
  4544. 老年男:幽默大爷
  4545. 老年女:婆婆
  4546. 萌娃:奶气萌娃";
  4547. if ($roles_content) {
  4548. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  4549. 主体范围:\n {$roles_content}\n
  4550. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  4551. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4552. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4553. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4554. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4555. }else {
  4556. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4557. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4558. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4559. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4560. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4561. }
  4562. if ($scenes_content) {
  4563. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  4564. 场景范围:\n {$scenes_content}\n
  4565. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  4566. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4567. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4568. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4569. }else {
  4570. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4571. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4572. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4573. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4574. }
  4575. // 提取文件内容
  4576. if ($file) {
  4577. $uploaded_content = $this->extractFileContent($file);
  4578. if (!$uploaded_content) {
  4579. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4580. }
  4581. } elseif ($script_id) {
  4582. $uploaded_content = $this->getContentByScriptId($script_id);
  4583. if (!$uploaded_content) {
  4584. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4585. }
  4586. } elseif ($bid) {
  4587. $uploaded_content = $this->getContentByBid($bid);
  4588. if (!$uploaded_content) {
  4589. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4590. }
  4591. } elseif ($content) {
  4592. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  4593. }
  4594. // elseif ($prompt) {
  4595. // $uploaded_content = filterContent($prompt);
  4596. // }
  4597. else {
  4598. $uploaded_content = '';
  4599. }
  4600. $input_art_style = getProp($anime, 'art_style');
  4601. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4602. // 美术风格
  4603. if (!$mappedArtStyle) {
  4604. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4605. }else {
  4606. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4607. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4608. }else {
  4609. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4610. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4611. }
  4612. }
  4613. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4614. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4615. // 强制要求:
  4616. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4617. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4618. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4619. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4620. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  4621. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  4622. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  4623. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  4624. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  4625. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  4626. // - 分镜要和场景列表、人物主体保持一致\n
  4627. // 普通要求:
  4628. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4629. // {$role_demo}
  4630. // {$scene_demo}
  4631. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4632. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4633. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4634. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4635. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4636. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4637. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4638. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4639. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4640. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4641. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4642. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4643. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4644. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4645. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4646. // 5.$mappedArtStyle_prompt\n\n
  4647. // 示例格式:\n
  4648. // 第1集:隐形的守护者
  4649. // ###故事梗概
  4650. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4651. // ###美术风格
  4652. // 基础画风风格词:韩漫二次元
  4653. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4654. // ###主体列表
  4655. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4656. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4657. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4658. // ###场景列表
  4659. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4660. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4661. // 无人物。}
  4662. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4663. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4664. // 无人物。}
  4665. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4666. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4667. // 无人物。}
  4668. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4669. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4670. // 无人物。}
  4671. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4672. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4673. // 无人物。}
  4674. // ###分镜剧本
  4675. // ##第1幕:徐家老旧厨房 白天 室内
  4676. // 分镜1
  4677. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4678. // 场景:徐家老旧厨房
  4679. // 构图设计:全景,低角度仰视
  4680. // 运镜调度:手持拍摄
  4681. // 配音角色:旁白
  4682. // 出镜角色:许芸-校服装、徐母
  4683. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4684. // 画面类型:普通画面
  4685. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4686. // 分镜2
  4687. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4688. // 场景:徐家老旧厨房
  4689. // 构图设计:近景,徐母面部特写
  4690. // 运镜调度:固定镜头
  4691. // 配音角色:徐母
  4692. // 出镜角色:徐母
  4693. // 台词内容:问我夜不归宿死哪儿去了。
  4694. // 画面类型:对口型
  4695. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4696. // ##第2幕:徐家简陋客厅 黄昏 室内
  4697. // 分镜3
  4698. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4699. // 场景:徐家简陋客厅
  4700. // 构图设计:全景,景深虚化
  4701. // 运镜调度:固定镜头
  4702. // 配音角色:旁白
  4703. // 出镜角色:无
  4704. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4705. // 画面类型:普通画面
  4706. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4707. // 分镜4
  4708. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4709. // 场景:徐家简陋客厅
  4710. // 构图设计:特写,火车票
  4711. // 运镜调度:固定镜头
  4712. // 配音角色:旁白
  4713. // 出镜角色:无
  4714. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4715. // 画面类型:普通画面
  4716. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4717. // \n\n";
  4718. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  4719. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  4720. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  4721. 普通要求:
  4722. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4723. {$role_demo}
  4724. {$scene_demo}
  4725. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4726. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4727. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4728. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  4729. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4730. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4731. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4732. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4733. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4734. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4735. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4736. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4737. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4738. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4739. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4740. 5.$mappedArtStyle_prompt
  4741. 6.《情绪-视听语言映射表》:
  4742. 6.1 场景空间与时间心理学 (Scene & Temporality)
  4743. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4744. -----|---------|------------|----------------
  4745. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  4746. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  4747. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  4748. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  4749. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  4750. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4751. -----|---------|------------|----------------
  4752. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  4753. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  4754. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  4755. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  4756. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  4757. --------|---------|--------------|-------------
  4758. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  4759. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  4760. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  4761. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  4762. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  4763. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  4764. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  4765. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  4766. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  4767. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  4768. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  4769. -----|---------|------------|------------
  4770. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  4771. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  4772. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  4773. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  4774. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  4775. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  4776. --------|---------|--------------|----------
  4777. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  4778. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  4779. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  4780. 6.6 声音设计与潜意识影响 (Soundscape)
  4781. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  4782. -----|---------|------------|------------------
  4783. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  4784. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  4785. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  4786. 理论基石:
  4787. - The Five C's of Cinematography by Joseph V. Mascelli
  4788. - Film Art: An Introduction by David Bordwell
  4789. - Sight, Sound, Motion by Herbert Zettl
  4790. - Notes on the Cinematograph by Robert Bresson
  4791. \n\n
  4792. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  4793. 示例格式:\n
  4794. 第1集:隐形的守护者
  4795. ###故事梗概
  4796. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4797. ###美术风格
  4798. 基础画风风格词:韩漫二次元
  4799. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4800. ###主体列表
  4801. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4802. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4803. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4804. ###场景列表
  4805. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4806. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4807. 无人物。}
  4808. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4809. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4810. 无人物。}
  4811. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4812. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4813. 无人物。}
  4814. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4815. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4816. 无人物。}
  4817. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4818. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4819. 无人物。}
  4820. ###分镜剧本
  4821. ##第1幕:徐家老旧厨房 白天 室内
  4822. 分镜1
  4823. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4824. 场景:徐家老旧厨房
  4825. 构图设计:全景,低角度仰视
  4826. 运镜调度:手持拍摄
  4827. 配音角色:旁白
  4828. 出镜角色:许芸-校服装、徐母
  4829. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4830. 画面类型:普通画面
  4831. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4832. 分镜2
  4833. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4834. 场景:徐家老旧厨房
  4835. 构图设计:近景,徐母面部特写
  4836. 运镜调度:固定镜头
  4837. 配音角色:徐母
  4838. 出镜角色:徐母
  4839. 台词内容:问我夜不归宿死哪儿去了。
  4840. 画面类型:对口型
  4841. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4842. ##第2幕:徐家简陋客厅 黄昏 室内
  4843. 分镜3
  4844. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4845. 场景:徐家简陋客厅
  4846. 构图设计:全景,景深虚化
  4847. 运镜调度:固定镜头
  4848. 配音角色:旁白
  4849. 出镜角色:无
  4850. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4851. 画面类型:普通画面
  4852. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4853. 分镜4
  4854. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4855. 场景:徐家简陋客厅
  4856. 构图设计:特写,火车票
  4857. 运镜调度:固定镜头
  4858. 配音角色:旁白
  4859. 出镜角色:无
  4860. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4861. 画面类型:普通画面
  4862. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4863. \n\n";
  4864. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4865. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  4866. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  4867. $prompt = $origin_prompt;
  4868. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  4869. // 获取章节内容
  4870. $full_content = getProp($anime, 'content');
  4871. if ($uploaded_content) {
  4872. $full_content = $uploaded_content;
  4873. }
  4874. // 根据章节内容拆分章节
  4875. $chapters = $this->splitContent($full_content);
  4876. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  4877. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  4878. $messages = [];
  4879. if ($prompt == '确认分镜大纲') {
  4880. // 暂时保留
  4881. $content = $chapter_content;
  4882. if ($is_single) $content = $full_content; // 单剧集使用全文
  4883. if (!$content) {
  4884. Utils::throwError('20003:章节内容无法获取,请确认');
  4885. }
  4886. $question = $is_single
  4887. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  4888. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  4889. // 构建消息
  4890. $messages[] =
  4891. [
  4892. 'role' => 'user',
  4893. 'content' => $question
  4894. ];
  4895. }else if ($prompt == '继续策划下一集') {
  4896. if ($is_single) {
  4897. Utils::throwError('20003:单剧集不支持继续策划下一集');
  4898. }
  4899. $content = $chapter_content;
  4900. if (!$content) {
  4901. Utils::throwError('20003:章节内容无法获取,请确认');
  4902. }
  4903. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  4904. // 获取上一集最后记录
  4905. $prev_sequence = $episode_number - 1;
  4906. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  4907. // 构建消息
  4908. $messages[] =
  4909. [
  4910. 'role' => 'user',
  4911. 'content' => $question
  4912. ];
  4913. }else {
  4914. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  4915. if (!$content) {
  4916. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  4917. }
  4918. if (!$content) {
  4919. Utils::throwError('20003:章节内容无法获取,请确认');
  4920. }
  4921. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  4922. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  4923. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  4924. if ($origin_prompt) {
  4925. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  4926. }
  4927. $messages[] =
  4928. [
  4929. 'role' => 'user',
  4930. 'content' => $question
  4931. ];
  4932. }
  4933. // 处理文本模型
  4934. $model = getProp($data, 'model');
  4935. if (!$model) {
  4936. // 用户没有输入,从anime表获取
  4937. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4938. $model = getProp($anime, 'model');
  4939. if (!$model) {
  4940. // anime表也没有,使用默认值
  4941. $model = 'doubao-seed-2-0-mini-260215';
  4942. }
  4943. }
  4944. // 验证模型是否在可用模型表中
  4945. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4946. $model = 'doubao-seed-2-0-mini-260215';
  4947. }
  4948. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4949. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4950. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4951. if ($model === 'deepseek-chat') {
  4952. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4953. $model = 'deepseek-v4-flash';
  4954. $thinkingMode = 'disabled';
  4955. } elseif ($model === 'deepseek-reasoner') {
  4956. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4957. $model = 'deepseek-v4-flash';
  4958. $thinkingMode = 'enabled';
  4959. }
  4960. $post_data = [
  4961. 'model' => $model,
  4962. 'messages' => $messages,
  4963. // 'max_tokens' => 8192,
  4964. 'temperature' => 0.2,
  4965. 'frequency_penalty' => 0,
  4966. 'presence_penalty' => 0,
  4967. 'response_format' => ['type' => 'text'],
  4968. 'thinking' => ['type' => $thinkingMode],
  4969. 'stream' => true // 启用流式输出
  4970. ];
  4971. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4972. // 根据模型类型选择调用方法
  4973. $fullContent = '';
  4974. $fullReasoningContent = '';
  4975. $usage = [];
  4976. try {
  4977. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4978. // DeepSeek 官方模型使用 DeepSeek API
  4979. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4980. } else if (in_array($model, $this->gpt_text_models)) {
  4981. // GPT-5.4 模型使用 TokenRouter API
  4982. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4983. } else {
  4984. // 其他模型使用火山引擎API
  4985. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4986. }
  4987. // 验证返回值类型
  4988. if (!is_iterable($streamGenerator)) {
  4989. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4990. dLog('deepseek')->error('chat流式生成器无效', [
  4991. 'generator_type' => $errorType,
  4992. 'model' => $model,
  4993. 'anime_id' => $anime_id,
  4994. 'episode_number' => $episode_number
  4995. ]);
  4996. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  4997. 'type' => $errorType,
  4998. 'model' => $model
  4999. ]);
  5000. yield [
  5001. 'type' => 'error',
  5002. 'episode' => [],
  5003. 'answer' => '',
  5004. 'reasoning' => '',
  5005. 'usage' => [],
  5006. 'error' => '接口返回数据异常,请重新请求'
  5007. ];
  5008. return;
  5009. }
  5010. // 处理流式输出
  5011. foreach ($streamGenerator as $chunk) {
  5012. if (isset($chunk['type'])) {
  5013. if ($chunk['type'] === 'done') {
  5014. // 最终结果
  5015. $fullContent = $chunk['full_content'];
  5016. $fullReasoningContent = $chunk['full_reasoning'];
  5017. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5018. } else {
  5019. // 逐块yield数据
  5020. yield $chunk;
  5021. }
  5022. }
  5023. }
  5024. } catch (\Exception $e) {
  5025. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  5026. 'model' => $model,
  5027. 'anime_id' => $anime_id,
  5028. 'episode_number' => $episode_number,
  5029. 'trace' => $e->getTraceAsString()
  5030. ]);
  5031. logDB('deepseek', 'error', 'chat流式处理失败', [
  5032. 'error' => $e->getMessage(),
  5033. 'model' => $model
  5034. ]);
  5035. yield [
  5036. 'type' => 'error',
  5037. 'episode' => [],
  5038. 'answer' => '',
  5039. 'reasoning' => '',
  5040. 'usage' => [],
  5041. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5042. ];
  5043. return;
  5044. }
  5045. dLog('deepseek')->info('完整内容: '.$fullContent);
  5046. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5047. // 处理完整内容并返回最终结果
  5048. $episode_arr = handleEpisodeContent($fullContent);
  5049. logDB('deepseek', 'info', '解析内容', $episode_arr);
  5050. if (empty($episode_arr['acts'])) {
  5051. // 未生成剧本相关内容,保存对话记录并返回提示
  5052. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  5053. try {
  5054. $now = date('Y-m-d H:i:s');
  5055. // 保存对话记录
  5056. $records = [
  5057. [
  5058. 'uid' => $uid,
  5059. 'anime_id' => $anime_id,
  5060. 'sequence' => $episode_number,
  5061. 'role' => 'user',
  5062. 'content' => $prompt,
  5063. 'created_at' => $now,
  5064. 'updated_at' => $now
  5065. ],
  5066. [
  5067. 'uid' => $uid,
  5068. 'anime_id' => $anime_id,
  5069. 'sequence' => $episode_number,
  5070. 'role' => 'assistant',
  5071. 'content' => $fullContent,
  5072. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5073. 'created_at' => $now,
  5074. 'updated_at' => $now
  5075. ]
  5076. ];
  5077. DB::table('mp_anime_records')->insert($records);
  5078. } catch (\Exception $e) {
  5079. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5080. }
  5081. yield [
  5082. 'type' => 'done',
  5083. 'episode' => [],
  5084. 'answer' => $fullContent,
  5085. 'reasoning' => $fullReasoningContent,
  5086. 'usage' => $usage,
  5087. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  5088. ];
  5089. return;
  5090. }
  5091. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  5092. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  5093. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  5094. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  5095. $now = date('Y-m-d H:i:s');
  5096. try {
  5097. DB::beginTransaction();
  5098. $saveResult = $this->saveEpisodeVersionData(
  5099. $anime_id,
  5100. $episode_number,
  5101. $episode_arr,
  5102. $existing_roles,
  5103. $existing_scenes,
  5104. $current_episode,
  5105. $base_episode,
  5106. $is_regenerate_version,
  5107. $content,
  5108. $now
  5109. );
  5110. $episode = $saveResult['episode'];
  5111. $episode_id = $saveResult['episode_id'];
  5112. $merged_roles = $saveResult['merged_roles'];
  5113. $merged_scenes = $saveResult['merged_scenes'];
  5114. $record_content = $origin_prompt;
  5115. if ($uploaded_content !== '') {
  5116. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  5117. }
  5118. $records = [
  5119. [
  5120. 'uid' => $uid,
  5121. 'anime_id' => $anime_id,
  5122. 'role' => 'user',
  5123. 'content' => $record_content,
  5124. 'sequence' => $episode_number,
  5125. 'episode_id' => $episode_id,
  5126. 'created_at' => $now,
  5127. 'updated_at' => $now
  5128. ],
  5129. [
  5130. 'uid' => $uid,
  5131. 'anime_id' => $anime_id,
  5132. 'role' => 'assistant',
  5133. 'content' => $fullContent,
  5134. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5135. 'sequence' => $episode_number,
  5136. 'episode_id' => $episode_id,
  5137. 'created_at' => $now,
  5138. 'updated_at' => $now
  5139. ]
  5140. ];
  5141. $boolen4 = DB::table('mp_anime_records')->insert($records);
  5142. if (!$boolen4) {
  5143. Utils::throwError('20003:对话记录保存失败');
  5144. }
  5145. // 保存模型和内容到anime表
  5146. $update_anime_data = [
  5147. 'model' => $model,
  5148. 'updated_at' => $now
  5149. ];
  5150. if ($uploaded_content) {
  5151. $update_anime_data['content'] = $uploaded_content;
  5152. }
  5153. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  5154. }catch (\Exception $e) {
  5155. DB::rollBack();
  5156. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5157. yield [
  5158. 'type' => 'done',
  5159. 'answer' => $fullContent,
  5160. 'reasoning' => $fullReasoningContent,
  5161. 'usage' => $usage,
  5162. 'error' => $e->getMessage(),
  5163. ];
  5164. return;
  5165. }
  5166. DB::commit();
  5167. if ($is_global_generate_pics) {
  5168. // // 批量生成全局角色图片
  5169. // $this->batchSetGlobalRoleImg([
  5170. // 'anime_id' => $anime_id,
  5171. // ], true);
  5172. // // 批量生成全局场景图片
  5173. // $this->batchSetGlobalSceneImg([
  5174. // 'anime_id' => $anime_id,
  5175. // ], true);
  5176. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5177. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5178. }
  5179. $episode['episode_id'] = $episode_id;
  5180. $episode['roles'] = $merged_roles;
  5181. $episode['scenes'] = $merged_scenes;
  5182. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  5183. yield [
  5184. 'type' => 'done',
  5185. 'episode' => $episode,
  5186. 'answer' => $fullContent,
  5187. 'reasoning' => $fullReasoningContent,
  5188. 'usage' => $usage
  5189. ];
  5190. }
  5191. public function addChatForAce($data) {
  5192. $uid = Site::getUid();
  5193. $anime_id = getProp($data, 'anime_id');
  5194. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5195. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5196. if (!$anime) Utils::throwError('20003:对话不存在');
  5197. $file = getProp($data, 'file');
  5198. $content = getProp($data, 'content', '');
  5199. $bid = getProp($data, 'bid', 0);
  5200. $script_id = getProp($data, 'script_id', 0);
  5201. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5202. $prompt = getProp($data, 'prompt');
  5203. $extra_products = getProp($data, 'products', []);
  5204. if (!$extra_products) {
  5205. $extra_products = getProp($anime, 'extra_products');
  5206. if ($extra_products) {
  5207. $extra_products = json_decode($extra_products, true);
  5208. }else {
  5209. $extra_products = [];
  5210. }
  5211. }else {
  5212. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  5213. }
  5214. $user_anime_name = getProp($anime, 'anime_name');
  5215. // 处理提示词
  5216. if ($prompt && $extra_products) {
  5217. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  5218. foreach($extra_products as $item) {
  5219. $product_name = getProp($item, 'product_name');
  5220. if ($product_name) {
  5221. // 替换 {product_name} 为 product_name
  5222. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  5223. }
  5224. }
  5225. }
  5226. // 处理文本模型
  5227. $model = getProp($data, 'model');
  5228. if (!$model) {
  5229. // 用户没有输入,从anime表获取
  5230. $model = getProp($anime, 'model');
  5231. if (!$model) {
  5232. // anime表也没有,使用默认值
  5233. $model = 'doubao-seed-2-0-mini-260215';
  5234. }
  5235. }
  5236. // 验证模型是否在可用模型表中
  5237. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5238. $model = 'doubao-seed-2-0-mini-260215';
  5239. }
  5240. $is_multi = getProp($anime, 'is_multi');
  5241. $is_single = (int)$is_multi !== 1;
  5242. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  5243. if ($prompt) {
  5244. $question .= "本次修改要求如下:\n{$prompt}";
  5245. }
  5246. // if (!$file && !$content && !$bid) {
  5247. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5248. // }
  5249. // 提取文件内容
  5250. if ($file) {
  5251. $content = $this->extractFileContent($file);
  5252. if (!$content) {
  5253. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5254. }
  5255. } elseif ($script_id) {
  5256. $content = $this->getContentByScriptId($script_id);
  5257. if (!$content) {
  5258. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5259. }
  5260. } elseif ($bid) {
  5261. $content = $this->getContentByBid($bid);
  5262. if (!$content) {
  5263. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5264. }
  5265. } elseif ($content) {
  5266. $content = filterContent($content);
  5267. } else {
  5268. $content = getProp($anime, 'content');
  5269. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5270. $need_generate_content = true;
  5271. }
  5272. }
  5273. // 美术风格
  5274. $input_art_style = getProp($data, 'art_style');
  5275. if (!$input_art_style) {
  5276. $mappedArtStyle = getProp($anime, 'art_style');
  5277. }else {
  5278. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5279. }
  5280. // 判断是否需要生成原文内容
  5281. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5282. // 如果需要生成原文内容,添加额外的要求
  5283. $content_generation_requirement = $need_generate_content
  5284. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5285. : "";
  5286. // 美术风格
  5287. if (!$mappedArtStyle) {
  5288. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5289. }else {
  5290. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5291. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5292. }else {
  5293. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5294. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5295. }
  5296. }
  5297. // 构建主体和场景提示词
  5298. $extra_role_prompt = "\n";
  5299. $extra_scene_prompt = "\n";
  5300. $ref_products = []; // 参考资产
  5301. if ($extra_products) {
  5302. foreach($extra_products as $item) {
  5303. $product = getProp($item, 'product');
  5304. $product_name = getProp($item, 'product_name');
  5305. if ($product_name == '旁白') continue;
  5306. $ref_products[$product_name] = $item;
  5307. $pic_prompt = getProp($item, 'pic_prompt');
  5308. if ((int)$product === 1) {
  5309. // 拼接角色信息
  5310. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5311. } elseif ((int)$product === 2) {
  5312. // 拼接场景信息
  5313. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5314. }
  5315. }
  5316. // 优化提示词,融入剧本
  5317. if (!empty(trim($extra_role_prompt))) {
  5318. $extra_role_prompt = "\n2.5【强制主体设定-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  5319. }
  5320. if (!empty(trim($extra_scene_prompt))) {
  5321. $extra_scene_prompt = "\n3.4【强制场景设定-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  5322. }
  5323. }
  5324. $systemPrompt = $is_single
  5325. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5326. 强制要求:
  5327. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5328. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5329. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5330. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5331. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5332. 普通要求:
  5333. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5334. 3.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5335. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5336. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5337. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5338. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5339. {$extra_role_prompt}
  5340. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5341. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5342. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5343. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5344. {$extra_scene_prompt}
  5345. 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  5346. 4.1片段分割逻辑(优先级从高到低):
  5347. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  5348. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  5349. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  5350. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  5351. 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  5352. - 片段数量格式为: 片段数量:8
  5353. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5354. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  5355. 4.3分镜结构:每个分镜包含以下字段:
  5356. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  5357. - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  5358. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  5359. - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  5360. - 运镜:场景+画面描述+运镜
  5361. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  5362. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  5363. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  5364. 5.{$mappedArtStyle_prompt}\n\n
  5365. 示例如下:\n
  5366. ###剧本名:西昆仑
  5367. ###故事梗概
  5368. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5369. ###剧本亮点
  5370. 亮点1:绝境奇药,生死一线
  5371. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5372. 亮点2:结拜兄妹,化解尴尬
  5373. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5374. 亮点3:纤发夺命,情愫暗涌
  5375. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5376. ###人物关系
  5377. 阿雪与梁萧之间存在兄妹之情。
  5378. ###核心矛盾
  5379. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5380. ###主体列表
  5381. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5382. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5383. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5384. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5385. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5386. 全景,正面拍摄,青年女性,亚洲人。
  5387. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5388. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5389. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5390. ###美术风格
  5391. 基础画风风格词:厚涂古风
  5392. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5393. ###场景列表
  5394. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5395. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5396. 无人物。}
  5397. ###分段剧本
  5398. 片段数量:8
  5399. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  5400. ##片段1
  5401. 时长:12s
  5402. 分镜1
  5403. 场景:边境小镇街道
  5404. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  5405. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  5406. 配音台词:
  5407. 背景音效:
  5408. 分镜2
  5409. 场景:悦来酒馆
  5410. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  5411. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  5412. 配音台词:
  5413. 背景音效:
  5414. 分镜3
  5415. 场景:悦来酒馆
  5416. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  5417. 运镜:从中景推向令牌特写。
  5418. 配音台词:
  5419. 背景音效:
  5420. 分镜4
  5421. 场景:悦来酒馆
  5422. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  5423. 运镜:极速推向酒水溅起的瞬间。
  5424. 配音台词:
  5425. 背景音效:
  5426. 分镜5
  5427. 镜头描述
  5428. 场景:悦来酒馆
  5429. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  5430. 运镜:固定机位,利用倾斜构图制造压迫感。
  5431. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  5432. 背景音效:
  5433. \n\n"
  5434. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5435. 强制要求:\n
  5436. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5437. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5438. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5439. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5440. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5441. 普通要求:\n
  5442. 1.剧本名(必须生成)必须与文档内容高度相关
  5443. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5444. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5445. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5446. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5447. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5448. {$extra_role_prompt}
  5449. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5450. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5451. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5452. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5453. {$extra_scene_prompt}
  5454. 4.{$mappedArtStyle_prompt}\n\n
  5455. 示例如下:\n
  5456. ###剧本名:西昆仑
  5457. ###故事梗概
  5458. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5459. ###剧本亮点
  5460. 亮点1:绝境奇药,生死一线
  5461. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5462. 亮点2:结拜兄妹,化解尴尬
  5463. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5464. 亮点3:纤发夺命,情愫暗涌
  5465. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5466. ###人物关系
  5467. 阿雪与梁萧之间存在兄妹之情。
  5468. ###核心矛盾
  5469. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5470. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5471. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  5472. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  5473. ###主体列表
  5474. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5475. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5476. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5477. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5478. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5479. 全景,正面拍摄,青年女性,亚洲人。
  5480. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5481. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5482. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5483. ###美术风格
  5484. 基础画风风格词:厚涂古风
  5485. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5486. ###场景列表
  5487. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5488. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5489. 无人物。}";
  5490. // 构建消息
  5491. $messages = [
  5492. [
  5493. 'role' => 'system',
  5494. 'content' => $systemPrompt
  5495. ],
  5496. [
  5497. 'role' => 'user',
  5498. 'content' => "以下是文档内容:
  5499. {$content}
  5500. 用户问题:
  5501. {$question}"
  5502. ]
  5503. ];
  5504. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5505. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5506. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5507. if ($model === 'deepseek-chat') {
  5508. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5509. $model = 'deepseek-v4-flash';
  5510. $thinkingMode = 'disabled';
  5511. } elseif ($model === 'deepseek-reasoner') {
  5512. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5513. $model = 'deepseek-v4-flash';
  5514. $thinkingMode = 'enabled';
  5515. }
  5516. $post_data = [
  5517. 'model' => $model,
  5518. 'messages' => $messages,
  5519. // 'max_tokens' => 8192,
  5520. 'temperature' => 0.7,
  5521. 'frequency_penalty' => 0,
  5522. 'presence_penalty' => 0,
  5523. 'response_format' => ['type' => 'text'],
  5524. 'thinking' => ['type'=>$thinkingMode],
  5525. 'stream' => true // 启用流式输出
  5526. ];
  5527. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5528. // 根据模型类型选择调用方法
  5529. $fullContent = '';
  5530. $fullReasoningContent = '';
  5531. $usage = [];
  5532. try {
  5533. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5534. // DeepSeek 官方模型使用 DeepSeek API
  5535. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5536. } else if (in_array($model, $this->gpt_text_models)) {
  5537. // GPT-5.4 模型使用 TokenRouter API
  5538. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5539. } else {
  5540. // 其他模型使用火山引擎API
  5541. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5542. }
  5543. // 验证返回值类型
  5544. if (!is_iterable($streamGenerator)) {
  5545. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5546. dLog('deepseek')->error('addChat流式生成器无效', [
  5547. 'generator_type' => $errorType,
  5548. 'model' => $model,
  5549. 'anime_id' => $anime_id
  5550. ]);
  5551. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5552. 'type' => $errorType,
  5553. 'model' => $model
  5554. ]);
  5555. yield [
  5556. 'type' => 'error',
  5557. 'script' => [],
  5558. 'episode' => [],
  5559. 'answer' => '',
  5560. 'reasoning' => '',
  5561. 'usage' => [],
  5562. 'error' => '接口返回数据异常,请重新请求'
  5563. ];
  5564. return;
  5565. }
  5566. // 处理流式输出
  5567. foreach ($streamGenerator as $chunk) {
  5568. if (isset($chunk['type'])) {
  5569. if ($chunk['type'] === 'done') {
  5570. // 最终结果
  5571. $fullContent = $chunk['full_content'];
  5572. $fullReasoningContent = $chunk['full_reasoning'];
  5573. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5574. } else {
  5575. // 逐块yield数据
  5576. yield $chunk;
  5577. }
  5578. }
  5579. }
  5580. } catch (\Exception $e) {
  5581. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5582. 'model' => $model,
  5583. 'anime_id' => $anime_id,
  5584. 'trace' => $e->getTraceAsString()
  5585. ]);
  5586. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5587. 'error' => $e->getMessage(),
  5588. 'model' => $model
  5589. ]);
  5590. yield [
  5591. 'type' => 'error',
  5592. 'script' => [],
  5593. 'episode' => [],
  5594. 'answer' => '',
  5595. 'reasoning' => '',
  5596. 'usage' => [],
  5597. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5598. ];
  5599. return;
  5600. }
  5601. dLog('deepseek')->info('完整内容: '.$fullContent);
  5602. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5603. // 处理完整内容并返回最终结果
  5604. $script_arr = [];
  5605. if ($fullContent) {
  5606. $script_arr = handleScriptContentForAce($fullContent);
  5607. dLog('deepseek')->info('解析内容', $script_arr);
  5608. logDB('deepseek', 'info', '解析内容', $script_arr);
  5609. }
  5610. if (empty($script_arr['roles'])) {
  5611. // 未生成剧本相关内容,保存对话记录并返回提示
  5612. dLog('deepseek')->info('未生成剧本相关的内容');
  5613. try {
  5614. DB::beginTransaction();
  5615. $now = date('Y-m-d H:i:s');
  5616. // 保存对话记录
  5617. $records = [
  5618. [
  5619. 'uid' => $uid,
  5620. 'anime_id' => $anime_id,
  5621. 'sequence' => 0,
  5622. 'role' => 'user',
  5623. 'content' => $prompt,
  5624. 'created_at' => $now,
  5625. 'updated_at' => $now
  5626. ],
  5627. [
  5628. 'uid' => $uid,
  5629. 'anime_id' => $anime_id,
  5630. 'sequence' => 0,
  5631. 'role' => 'assistant',
  5632. // 'content' => $fullContent,
  5633. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5634. 'created_at' => $now,
  5635. 'updated_at' => $now
  5636. ]
  5637. ];
  5638. DB::table('mp_anime_records')->insert($records);
  5639. DB::commit();
  5640. } catch (\Exception $e) {
  5641. DB::rollBack();
  5642. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5643. }
  5644. yield [
  5645. 'type' => 'done',
  5646. 'script' => [],
  5647. 'episode' => [],
  5648. 'answer' => $fullContent,
  5649. 'reasoning' => $fullReasoningContent,
  5650. 'usage' => $usage,
  5651. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5652. ];
  5653. return;
  5654. }
  5655. // 如果需要生成原文内容,从script_arr中提取
  5656. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5657. $content = $script_arr['content'];
  5658. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5659. if (!$content) {
  5660. yield [
  5661. 'type' => 'done',
  5662. 'script' => [],
  5663. 'episode' => [],
  5664. 'answer' => $fullContent,
  5665. 'reasoning' => $fullReasoningContent,
  5666. 'usage' => $usage,
  5667. 'error' => '未生成剧本内容,请调整提示词再试'
  5668. ];
  5669. return;
  5670. }
  5671. }
  5672. // 替换美术风格
  5673. if ($mappedArtStyle !== '') {
  5674. $script_arr['art_style'] = $mappedArtStyle;
  5675. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5676. }
  5677. // 新建动漫
  5678. if ($user_anime_name == '新剧本策划') {
  5679. $anime_name = getProp($script_arr, 'script_name');
  5680. // if (!$anime_name) {
  5681. // // 未识别到剧本名,保存对话记录并返回提示
  5682. // dLog('deepseek')->info('未能识别到剧本名称');
  5683. // try {
  5684. // DB::beginTransaction();
  5685. // $now = date('Y-m-d H:i:s');
  5686. // // 保存对话记录
  5687. // $records = [
  5688. // [
  5689. // 'uid' => $uid,
  5690. // 'anime_id' => $anime_id,
  5691. // 'sequence' => 0,
  5692. // 'role' => 'user',
  5693. // 'content' => $prompt,
  5694. // 'created_at' => $now,
  5695. // 'updated_at' => $now
  5696. // ],
  5697. // [
  5698. // 'uid' => $uid,
  5699. // 'anime_id' => $anime_id,
  5700. // 'sequence' => 0,
  5701. // 'role' => 'assistant',
  5702. // 'content' => '未能生成剧本名称,请重试',
  5703. // 'created_at' => $now,
  5704. // 'updated_at' => $now
  5705. // ]
  5706. // ];
  5707. // DB::table('mp_anime_records')->insert($records);
  5708. // DB::commit();
  5709. // } catch (\Exception $e) {
  5710. // DB::rollBack();
  5711. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5712. // }
  5713. // yield [
  5714. // 'type' => 'done',
  5715. // 'script' => [],
  5716. // 'episode' => [],
  5717. // 'answer' => $fullContent,
  5718. // 'reasoning' => $fullReasoningContent,
  5719. // 'usage' => $usage,
  5720. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  5721. // ];
  5722. // return;
  5723. // }
  5724. // 确认对话名称唯一性
  5725. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5726. $anime_name = $anime_name . '_' . date('YmdHis');
  5727. }
  5728. }else {
  5729. $anime_name = $user_anime_name;
  5730. }
  5731. $table_data = [
  5732. 'user_id' => $uid,
  5733. 'anime_name' => $anime_name,
  5734. 'model' => $model,
  5735. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5736. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5737. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5738. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5739. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5740. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5741. 'art_style_type' => $input_art_style,
  5742. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5743. 'status' => '解析完成',
  5744. 'content' => $content,
  5745. 'is_multi' => $is_multi,
  5746. 'ace_mode' => $ace_mode,
  5747. 'generate_status' => '待执行',
  5748. 'updated_at' => date('Y-m-d H:i:s')
  5749. ];
  5750. if ($table_data['content']) {
  5751. $chapters = $this->splitContent($table_data['content']);
  5752. $chapter_count = count($chapters);
  5753. if ($chapter_count > 0) {
  5754. $table_data['start_episode_sequence'] = 1;
  5755. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5756. }
  5757. }
  5758. if ($extra_products) {
  5759. $table_data['extra_products'] = json_encode($extra_products, 256);
  5760. }
  5761. // 如果有剧本ID则进行绑定
  5762. if ($script_id) {
  5763. $table_data['script_id'] = $script_id;
  5764. }
  5765. $single_episode = [];
  5766. try {
  5767. DB::beginTransaction();
  5768. $now = date('Y-m-d H:i:s');
  5769. // 更新动漫大纲
  5770. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5771. if (!$boolen) {
  5772. dLog('deepseek')->info('动漫保存失败', $table_data);
  5773. Utils::throwError('20003:动漫保存失败');
  5774. }
  5775. // 保存对话记录
  5776. $records = [
  5777. [
  5778. 'uid' => $uid,
  5779. 'anime_id' => $anime_id,
  5780. 'sequence' => 0,
  5781. 'role' => 'user',
  5782. 'content' => $prompt,
  5783. 'created_at' => date('Y-m-d H:i:s'),
  5784. 'updated_at' => date('Y-m-d H:i:s')
  5785. ],
  5786. [
  5787. 'uid' => $uid,
  5788. 'anime_id' => $anime_id,
  5789. 'sequence' => 0,
  5790. 'role' => 'assistant',
  5791. 'content' => $fullContent,
  5792. 'created_at' => date('Y-m-d H:i:s'),
  5793. 'updated_at' => date('Y-m-d H:i:s')
  5794. ]
  5795. ];
  5796. // 保存对话记录
  5797. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5798. if (!$boolen3) {
  5799. Utils::throwError('20003:对话记录保存失败');
  5800. }
  5801. if ($is_single) {
  5802. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5803. if (empty($episode_arr['acts'])) {
  5804. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5805. }
  5806. $saveResult = $this->saveEpisodeVersionData(
  5807. $anime_id,
  5808. 1,
  5809. $episode_arr,
  5810. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5811. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5812. null,
  5813. null,
  5814. false,
  5815. $content,
  5816. $now,
  5817. $ref_products
  5818. );
  5819. $single_episode = $saveResult['episode'];
  5820. $episode_id = $saveResult['episode_id'];
  5821. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5822. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5823. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5824. 'updated_at' => $now
  5825. ]);
  5826. if ($boolen5 === false) {
  5827. Utils::throwError('20003:单剧集主表资源同步失败');
  5828. }
  5829. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5830. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5831. $episode_record_content = '确认分镜大纲';
  5832. if ($content !== '') {
  5833. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5834. }
  5835. $episode_records = [
  5836. [
  5837. 'uid' => $uid,
  5838. 'anime_id' => $anime_id,
  5839. 'role' => 'user',
  5840. 'content' => $episode_record_content,
  5841. 'sequence' => 1,
  5842. 'episode_id' => $episode_id,
  5843. 'created_at' => $now,
  5844. 'updated_at' => $now
  5845. ],
  5846. [
  5847. 'uid' => $uid,
  5848. 'anime_id' => $anime_id,
  5849. 'role' => 'assistant',
  5850. 'content' => $fullContent,
  5851. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5852. 'sequence' => 1,
  5853. 'episode_id' => $episode_id,
  5854. 'created_at' => $now,
  5855. 'updated_at' => $now
  5856. ]
  5857. ];
  5858. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5859. if (!$boolen4) {
  5860. Utils::throwError('20003:单剧集分镜记录保存失败');
  5861. }
  5862. }
  5863. }catch (\Exception $e) {
  5864. DB::rollBack();
  5865. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5866. yield [
  5867. 'type' => 'done',
  5868. 'answer' => $fullContent,
  5869. 'reasoning' => $fullReasoningContent,
  5870. 'usage' => $usage,
  5871. 'error' => $e->getMessage(),
  5872. ];
  5873. return;
  5874. }
  5875. DB::commit();
  5876. dLog('deepseek')->info('保存完毕');
  5877. if ($is_single && !empty($single_episode)) {
  5878. // $this->batchSetGlobalRoleImg([
  5879. // 'anime_id' => $anime_id,
  5880. // ]);
  5881. // $this->batchSetGlobalSceneImg([
  5882. // 'anime_id' => $anime_id,
  5883. // ]);
  5884. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5885. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5886. }
  5887. $table_data['anime_id'] = $anime_id;
  5888. $table_data['roles'] = json_decode($table_data['roles'], true);
  5889. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5890. // $table_data['episodes'] = $script_arr['episodes'];
  5891. unset($table_data['created_at']);
  5892. unset($table_data['updated_at']);
  5893. unset($table_data['status']);
  5894. dLog('deepseek')->info('开始返回');
  5895. yield [
  5896. 'type' => 'done',
  5897. 'script' => $table_data,
  5898. 'episode' => $single_episode,
  5899. 'answer' => $fullContent,
  5900. 'reasoning' => $fullReasoningContent,
  5901. 'usage' => $usage
  5902. ];
  5903. }
  5904. public function reGenerateAnimeForAce($data) {
  5905. $uid = Site::getUid();
  5906. $file = getProp($data, 'file');
  5907. $content = getProp($data, 'content', '');
  5908. $bid = getProp($data, 'bid', 0);
  5909. $script_id = getProp($data, 'script_id', 0);
  5910. $anime_id = getProp($data, 'anime_id');
  5911. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5912. if (!$anime) {
  5913. Utils::throwError('20003:该对话不存在');
  5914. }
  5915. $extra_products = getProp($data, 'products', []);
  5916. if (!$extra_products) {
  5917. $extra_products = getProp($anime, 'extra_products');
  5918. if ($extra_products) {
  5919. $extra_products = json_decode($extra_products, true);
  5920. }else {
  5921. $extra_products = [];
  5922. }
  5923. }else {
  5924. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  5925. }
  5926. $user_anime_name = getProp($anime, 'anime_name');
  5927. $prompt = getProp($data, 'prompt');
  5928. // 处理提示词
  5929. if ($prompt && $extra_products) {
  5930. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  5931. foreach($extra_products as $item) {
  5932. $product_name = getProp($item, 'product_name');
  5933. if ($product_name) {
  5934. // 替换 {product_name} 为 product_name
  5935. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  5936. }
  5937. }
  5938. }
  5939. // 处理文本模型
  5940. $model = getProp($data, 'model');
  5941. if (!$model) {
  5942. // 用户没有输入,从anime表获取
  5943. $model = getProp($anime, 'model');
  5944. if (!$model) {
  5945. // anime表也没有,使用默认值
  5946. $model = 'doubao-seed-2-0-mini-260215';
  5947. }
  5948. }
  5949. // 验证模型是否在可用模型表中
  5950. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5951. $model = 'doubao-seed-2-0-mini-260215';
  5952. }
  5953. $is_multi = getProp($anime, 'is_multi', 1);
  5954. $is_single = (int)$is_multi !== 1;
  5955. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  5956. if ($is_single) {
  5957. $episode_exists = DB::table('mp_anime_episodes')
  5958. ->where('anime_id', $anime_id)
  5959. ->where('sequence', 1)
  5960. ->exists();
  5961. if ($episode_exists) {
  5962. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  5963. }
  5964. }
  5965. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  5966. if ($prompt) {
  5967. $question .= "本次修改要求如下:\n{$prompt}";
  5968. }
  5969. // 提取文件内容
  5970. if ($file) {
  5971. $content = $this->extractFileContent($file);
  5972. if (!$content) {
  5973. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5974. }
  5975. } elseif ($script_id) {
  5976. $content = $this->getContentByScriptId($script_id);
  5977. if (!$content) {
  5978. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5979. }
  5980. } elseif ($bid) {
  5981. $content = $this->getContentByBid($bid);
  5982. if (!$content) {
  5983. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5984. }
  5985. } elseif ($content) {
  5986. $content = filterContent($content);
  5987. }else {
  5988. $content = filterContent(getProp($anime, 'content'));
  5989. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5990. $need_generate_content = true;
  5991. }
  5992. }
  5993. // 判断是否需要生成原文内容
  5994. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5995. // 如果需要生成原文内容,添加额外的要求
  5996. $content_generation_requirement = $need_generate_content
  5997. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5998. : "";
  5999. // 美术风格
  6000. $input_art_style = getProp($data, 'art_style');
  6001. if (!$input_art_style) {
  6002. $mappedArtStyle = getProp($anime, 'art_style');
  6003. }else {
  6004. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6005. }
  6006. if (!$mappedArtStyle) {
  6007. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6008. }else {
  6009. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6010. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6011. }else {
  6012. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6013. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6014. }
  6015. }
  6016. // 构建主体和场景提示词
  6017. $extra_role_prompt = "\n";
  6018. $extra_scene_prompt = "\n";
  6019. $ref_products = []; // 参考资产
  6020. if ($extra_products) {
  6021. foreach($extra_products as $item) {
  6022. $product = getProp($item, 'product');
  6023. $product_name = getProp($item, 'product_name');
  6024. if ($product_name == '旁白') continue;
  6025. $ref_products[$product_name] = $item;
  6026. $pic_prompt = getProp($item, 'pic_prompt');
  6027. if ((int)$product === 1) {
  6028. // 拼接角色信息
  6029. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6030. } elseif ((int)$product === 2) {
  6031. // 拼接场景信息
  6032. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6033. }
  6034. }
  6035. // 优化提示词,融入剧本
  6036. if (!empty(trim($extra_role_prompt))) {
  6037. $extra_role_prompt = "\n2.5【强制主体设定-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6038. }
  6039. if (!empty(trim($extra_scene_prompt))) {
  6040. $extra_scene_prompt = "\n3.4【强制场景设定-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6041. }
  6042. }
  6043. $system_message = ['role'=>'system', 'content'=>$is_single
  6044. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6045. 强制要求:
  6046. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6047. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6048. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6049. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6050. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6051. 普通要求:
  6052. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6053. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6054. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6055. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6056. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6057. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6058. {$extra_role_prompt}
  6059. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6060. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6061. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6062. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6063. {$extra_scene_prompt}
  6064. 3.$mappedArtStyle_prompt\n\n
  6065. 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6066. 4.1片段分割逻辑(优先级从高到低):
  6067. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6068. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6069. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6070. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6071. 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6072. - 片段数量格式为: 片段数量:8
  6073. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6074. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6075. 4.3分镜结构:每个分镜包含以下字段:
  6076. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  6077. - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  6078. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6079. - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  6080. - 运镜:场景+画面描述+运镜
  6081. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  6082. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6083. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6084. 示例如下:\n
  6085. ###剧本名:西昆仑
  6086. ###故事梗概
  6087. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6088. ###剧本亮点
  6089. 亮点1:绝境奇药,生死一线
  6090. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6091. 亮点2:结拜兄妹,化解尴尬
  6092. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6093. 亮点3:纤发夺命,情愫暗涌
  6094. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6095. ###人物关系
  6096. 阿雪与梁萧之间存在兄妹之情。
  6097. ###核心矛盾
  6098. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6099. ###主体列表
  6100. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6101. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6102. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6103. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6104. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6105. 全景,正面拍摄,青年女性,亚洲人。
  6106. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6107. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6108. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6109. ###美术风格
  6110. 基础画风风格词:厚涂古风
  6111. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6112. ###场景列表
  6113. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6114. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6115. 无人物。}
  6116. ###分段剧本
  6117. 片段数量:8
  6118. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6119. ##片段1
  6120. 时长:12s
  6121. 分镜1
  6122. 场景:边境小镇街道
  6123. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6124. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6125. 配音台词:
  6126. 背景音效:
  6127. 分镜2
  6128. 场景:悦来酒馆
  6129. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6130. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6131. 配音台词:
  6132. 背景音效:
  6133. 分镜3
  6134. 场景:悦来酒馆
  6135. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6136. 运镜:从中景推向令牌特写。
  6137. 配音台词:
  6138. 背景音效:
  6139. 分镜4
  6140. 场景:悦来酒馆
  6141. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6142. 运镜:极速推向酒水溅起的瞬间。
  6143. 配音台词:
  6144. 背景音效:
  6145. 分镜5
  6146. 镜头描述
  6147. 场景:悦来酒馆
  6148. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6149. 运镜:固定机位,利用倾斜构图制造压迫感。
  6150. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6151. 背景音效:
  6152. \n\n"
  6153. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6154. 强制要求:\n
  6155. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6156. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6157. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6158. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6159. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6160. 普通要求:\n
  6161. 1.剧本名(必须生成)必须与文档内容高度相关
  6162. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6163. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6164. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6165. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6166. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6167. {$extra_role_prompt}
  6168. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6169. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6170. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6171. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6172. {$extra_scene_prompt}
  6173. 4.$mappedArtStyle_prompt\n\n
  6174. 示例如下:\n
  6175. ###剧本名:西昆仑
  6176. ###故事梗概
  6177. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6178. ###剧本亮点
  6179. 亮点1:绝境奇药,生死一线
  6180. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6181. 亮点2:结拜兄妹,化解尴尬
  6182. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6183. 亮点3:纤发夺命,情愫暗涌
  6184. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6185. ###人物关系
  6186. 阿雪与梁萧之间存在兄妹之情。
  6187. ###核心矛盾
  6188. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6189. ###主体列表
  6190. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6191. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6192. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6193. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6194. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6195. 全景,正面拍摄,青年女性,亚洲人。
  6196. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6197. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6198. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6199. ###美术风格
  6200. 基础画风风格词:厚涂古风
  6201. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6202. ###场景列表
  6203. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6204. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6205. 无人物。}"];
  6206. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6207. $episode_count = $this->extractEpisodeNumber($prompt);
  6208. if ((int)getProp($anime, 'is_multi') !== 1) {
  6209. yield [
  6210. 'type' => 'done',
  6211. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6212. 'reasoning' => '',
  6213. 'usage' => []
  6214. ];
  6215. return;
  6216. }
  6217. if ($episode_count) {
  6218. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6219. $system_message = [
  6220. 'role' => 'system',
  6221. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6222. 强制要求:\n
  6223. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6224. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6225. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6226. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6227. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6228. 普通要求:\n
  6229. 1.<故事梗概>控制在200-300字左右
  6230. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6231. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6232. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6233. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6234. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6235. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6236. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6237. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6238. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6239. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6240. 示例如下:\n
  6241. ###剧本名:西昆仑
  6242. ###故事梗概
  6243. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6244. ###剧本亮点
  6245. 亮点1:绝境奇药,生死一线
  6246. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6247. 亮点2:结拜兄妹,化解尴尬
  6248. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6249. 亮点3:纤发夺命,情愫暗涌
  6250. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6251. ###人物关系
  6252. 阿雪与梁萧之间存在兄妹之情。
  6253. ###核心矛盾
  6254. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6255. ###主体列表
  6256. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6257. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6258. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6259. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6260. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6261. 全景,正面拍摄,青年女性,亚洲人。
  6262. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6263. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6264. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6265. ###美术风格
  6266. 基础画风风格词:厚涂古风
  6267. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6268. ###场景列表
  6269. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6270. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6271. 无人物。}
  6272. ###分集详细内容
  6273. ##第1章 重生
  6274. 我重生了。
  6275. 源于一个男人偏执的暗恋。
  6276. ##第2章 相救
  6277. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6278. 我眼睛扫向站在锅炉后的卞大伟。"
  6279. ];
  6280. // 构建消息
  6281. $messages = [
  6282. $system_message,
  6283. [
  6284. 'role' => 'user',
  6285. 'content' => "以下是文档内容:
  6286. {$content}
  6287. 用户问题:
  6288. {$question}"
  6289. ]
  6290. ];
  6291. }else {
  6292. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6293. // 构建消息
  6294. $messages = [
  6295. $system_message,
  6296. [
  6297. 'role' => 'user',
  6298. 'content' => "以下是文档内容:
  6299. {$content}
  6300. 用户问题:
  6301. {$question}"
  6302. ]
  6303. ];
  6304. }else {
  6305. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6306. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6307. return (array)$value;
  6308. })->toArray();
  6309. array_unshift($messages, $system_message);
  6310. $messages[] = [
  6311. 'role' => 'user',
  6312. 'content' => $prompt
  6313. ];
  6314. }
  6315. }
  6316. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6317. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6318. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6319. if ($model === 'deepseek-chat') {
  6320. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6321. $model = 'deepseek-v4-flash';
  6322. $thinkingMode = 'disabled';
  6323. } elseif ($model === 'deepseek-reasoner') {
  6324. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6325. $model = 'deepseek-v4-flash';
  6326. $thinkingMode = 'enabled';
  6327. }
  6328. $post_data = [
  6329. 'model' => $model,
  6330. 'messages' => $messages,
  6331. // 'max_tokens' => 8192,
  6332. 'temperature' => 0.7,
  6333. 'frequency_penalty' => 0,
  6334. 'presence_penalty' => 0,
  6335. 'response_format' => ['type' => 'text'],
  6336. 'thinking' => ['type' => $thinkingMode],
  6337. 'stream' => true // 启用流式输出
  6338. ];
  6339. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6340. // 根据模型类型选择调用方法
  6341. $fullContent = '';
  6342. $fullReasoningContent = '';
  6343. $usage = [];
  6344. // dd($post_data);
  6345. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6346. try {
  6347. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6348. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6349. } else if (in_array($model, $this->gpt_text_models)) {
  6350. // GPT-5.4 模型使用 TokenRouter API
  6351. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6352. } else {
  6353. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6354. }
  6355. // 验证返回值类型
  6356. if (!is_iterable($streamGenerator)) {
  6357. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6358. dLog('deepseek')->error('方法名流式生成器无效', [
  6359. 'generator_type' => $errorType,
  6360. 'model' => $model,
  6361. // 添加其他上下文信息
  6362. ]);
  6363. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6364. 'type' => $errorType,
  6365. 'model' => $model
  6366. ]);
  6367. yield [
  6368. 'type' => 'error',
  6369. // 根据方法返回相应的空数据结构
  6370. 'answer' => '',
  6371. 'reasoning' => '',
  6372. 'usage' => [],
  6373. 'error' => '接口返回数据异常,请重新请求'
  6374. ];
  6375. return;
  6376. }
  6377. // 处理流式输出
  6378. foreach ($streamGenerator as $chunk) {
  6379. if (isset($chunk['type'])) {
  6380. if ($chunk['type'] === 'done') {
  6381. $fullContent = $chunk['full_content'];
  6382. $fullReasoningContent = $chunk['full_reasoning'];
  6383. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6384. } else {
  6385. yield $chunk;
  6386. }
  6387. }
  6388. }
  6389. } catch (\Exception $e) {
  6390. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6391. 'model' => $model,
  6392. 'trace' => $e->getTraceAsString()
  6393. ]);
  6394. logDB('deepseek', 'error', '方法名流式处理失败', [
  6395. 'error' => $e->getMessage(),
  6396. 'model' => $model
  6397. ]);
  6398. yield [
  6399. 'type' => 'error',
  6400. // 根据方法返回相应的空数据结构
  6401. 'answer' => '',
  6402. 'reasoning' => '',
  6403. 'usage' => [],
  6404. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6405. ];
  6406. return;
  6407. }
  6408. dLog('deepseek')->info('完整内容: '.$fullContent);
  6409. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6410. // 处理完整内容并返回最终结果
  6411. $script_arr = [];
  6412. if ($fullContent) {
  6413. $script_arr = handleScriptContentForAce($fullContent);
  6414. dLog('deepseek')->info('解析内容', $script_arr);
  6415. logDB('deepseek', 'info', '解析内容', $script_arr);
  6416. }
  6417. if (empty($script_arr['roles'])) {
  6418. // 未生成剧本相关内容,保存对话记录并返回提示
  6419. dLog('deepseek')->info('未生成剧本相关的内容');
  6420. try {
  6421. $now = date('Y-m-d H:i:s');
  6422. // 保存对话记录
  6423. $records = [
  6424. [
  6425. 'uid' => $uid,
  6426. 'anime_id' => $anime_id,
  6427. 'sequence' => 0,
  6428. 'role' => 'user',
  6429. 'content' => $prompt,
  6430. 'created_at' => $now,
  6431. 'updated_at' => $now
  6432. ],
  6433. [
  6434. 'uid' => $uid,
  6435. 'anime_id' => $anime_id,
  6436. 'sequence' => 0,
  6437. 'role' => 'assistant',
  6438. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6439. 'created_at' => $now,
  6440. 'updated_at' => $now
  6441. ]
  6442. ];
  6443. DB::table('mp_anime_records')->insert($records);
  6444. } catch (\Exception $e) {
  6445. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6446. }
  6447. yield [
  6448. 'type' => 'done',
  6449. 'script' => [],
  6450. 'episode' => [],
  6451. 'answer' => $fullContent,
  6452. 'reasoning' => $fullReasoningContent,
  6453. 'usage' => $usage,
  6454. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6455. ];
  6456. return;
  6457. }
  6458. // 替换美术风格
  6459. if ($mappedArtStyle !== '') {
  6460. $script_arr['art_style'] = $mappedArtStyle;
  6461. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6462. }
  6463. if ($user_anime_name != '新剧本策划') {
  6464. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  6465. // 确认对话名称唯一性
  6466. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6467. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6468. }
  6469. }else {
  6470. $anime_name = $user_anime_name;
  6471. }
  6472. $table_data = [
  6473. 'user_id' => $uid,
  6474. 'model' => $model,
  6475. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6476. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6477. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6478. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6479. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6480. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6481. 'art_style_type' => $input_art_style,
  6482. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6483. 'status' => '解析完成',
  6484. 'generate_status' => '待执行',
  6485. 'updated_at' => date('Y-m-d H:i:s')
  6486. ];
  6487. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6488. // 如果是修改集数,则将content内容更新(会改变原文)
  6489. if (isset($episode_count) && $episode_count > 0) {
  6490. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6491. $table_data['start_episode_sequence'] = 1;
  6492. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6493. }else {
  6494. // 如果需要生成原文内容,从script_arr中提取
  6495. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6496. $table_data['content'] = $script_arr['content'];
  6497. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6498. if (!$table_data['content']) {
  6499. yield [
  6500. 'type' => 'done',
  6501. 'script' => [],
  6502. 'episode' => [],
  6503. 'answer' => $fullContent,
  6504. 'reasoning' => $fullReasoningContent,
  6505. 'usage' => $usage,
  6506. 'error' => '未生成剧本内容,请调整提示词再试'
  6507. ];
  6508. return;
  6509. }
  6510. }
  6511. if (isset($table_data['content']) && $table_data['content']) {
  6512. $chapters = $this->splitContent($table_data['content']);
  6513. $chapter_count = count($chapters);
  6514. if ($chapter_count > 0) {
  6515. $table_data['start_episode_sequence'] = 1;
  6516. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6517. }
  6518. }
  6519. }
  6520. if ($extra_products) {
  6521. $table_data['extra_products'] = json_encode($extra_products, 256);
  6522. }
  6523. $single_episode = [];
  6524. try {
  6525. DB::beginTransaction();
  6526. $now = date('Y-m-d H:i:s');
  6527. // 更新动漫大纲
  6528. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6529. if (!$boolen) {
  6530. dLog('deepseek')->info('对话修改失败', $table_data);
  6531. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6532. Utils::throwError('20003:对话修改失败');
  6533. }
  6534. // 保存对话记录
  6535. $records = [
  6536. [
  6537. 'uid' => $uid,
  6538. 'anime_id' => $anime_id,
  6539. 'sequence' => 0,
  6540. 'role' => 'user',
  6541. 'content' => $prompt,
  6542. 'created_at' => $now,
  6543. 'updated_at' => $now
  6544. ],
  6545. [
  6546. 'uid' => $uid,
  6547. 'anime_id' => $anime_id,
  6548. 'sequence' => 0,
  6549. 'role' => 'assistant',
  6550. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6551. 'content' => $fullContent,
  6552. 'created_at' => $now,
  6553. 'updated_at' => $now
  6554. ]
  6555. ];
  6556. // 保存对话记录
  6557. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6558. if (!$boolen3) {
  6559. Utils::throwError('20003:对话记录保存失败');
  6560. }
  6561. // 单剧集模式:生成并保存剧集信息
  6562. if ($is_single) {
  6563. $anime_name = getProp($anime, 'anime_name', '未命名');
  6564. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6565. if (empty($episode_arr['acts'])) {
  6566. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6567. }
  6568. $saveResult = $this->saveEpisodeVersionData(
  6569. $anime_id,
  6570. 1,
  6571. $episode_arr,
  6572. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6573. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6574. null,
  6575. null,
  6576. false,
  6577. $content,
  6578. $now,
  6579. $ref_products
  6580. );
  6581. $single_episode = $saveResult['episode'];
  6582. $episode_id = $saveResult['episode_id'];
  6583. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6584. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6585. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6586. 'updated_at' => $now
  6587. ]);
  6588. if ($boolen5 === false) {
  6589. Utils::throwError('20003:单剧集主表资源同步失败');
  6590. }
  6591. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6592. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6593. $episode_record_content = '确认分镜大纲';
  6594. if ($content !== '') {
  6595. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6596. }
  6597. $episode_records = [
  6598. [
  6599. 'uid' => $uid,
  6600. 'anime_id' => $anime_id,
  6601. 'role' => 'user',
  6602. 'content' => $episode_record_content,
  6603. 'sequence' => 1,
  6604. 'episode_id' => $episode_id,
  6605. 'created_at' => $now,
  6606. 'updated_at' => $now
  6607. ],
  6608. [
  6609. 'uid' => $uid,
  6610. 'anime_id' => $anime_id,
  6611. 'role' => 'assistant',
  6612. 'content' => $fullContent,
  6613. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6614. 'sequence' => 1,
  6615. 'episode_id' => $episode_id,
  6616. 'created_at' => $now,
  6617. 'updated_at' => $now
  6618. ]
  6619. ];
  6620. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6621. if (!$boolen4) {
  6622. Utils::throwError('20003:单剧集分镜记录保存失败');
  6623. }
  6624. }
  6625. }catch (\Exception $e) {
  6626. DB::rollBack();
  6627. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  6628. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  6629. yield [
  6630. 'type' => 'done',
  6631. 'answer' => $fullContent,
  6632. 'reasoning' => $fullReasoningContent,
  6633. 'usage' => $usage,
  6634. 'error' => $e->getMessage(),
  6635. ];
  6636. return;
  6637. }
  6638. DB::commit();
  6639. dLog('deepseek')->info('保存完毕');
  6640. if ($is_single && !empty($single_episode)) {
  6641. // $this->batchSetGlobalRoleImg([
  6642. // 'anime_id' => $anime_id,
  6643. // ]);
  6644. // $this->batchSetGlobalSceneImg([
  6645. // 'anime_id' => $anime_id,
  6646. // ]);
  6647. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6648. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6649. }
  6650. $table_data['anime_id'] = $anime_id;
  6651. $table_data['roles'] = json_decode($table_data['roles'], true);
  6652. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6653. unset($table_data['updated_at']);
  6654. unset($table_data['status']);
  6655. yield [
  6656. 'type' => 'done',
  6657. 'script' => $table_data,
  6658. 'episode' => $single_episode,
  6659. 'answer' => $fullContent,
  6660. 'reasoning' => $fullReasoningContent,
  6661. 'usage' => $usage
  6662. ];
  6663. }
  6664. public function chatForAce($data) {
  6665. $uid = Site::getUid();
  6666. $anime_id = getProp($data, 'anime_id');
  6667. $file = getProp($data, 'file');
  6668. $content = getProp($data, 'content', '');
  6669. $bid = getProp($data, 'bid', 0);
  6670. $script_id = getProp($data, 'script_id', 0);
  6671. $episode_number = getProp($data, 'episode_number', 1);
  6672. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6673. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6674. if (!$anime) Utils::throwError('20003:该对话不存在!');
  6675. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  6676. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  6677. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  6678. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  6679. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  6680. $roles = is_array($roles) ? $roles : [];
  6681. $scenes = is_array($scenes) ? $scenes : [];
  6682. $extra_products = getProp($data, 'products', []);
  6683. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6684. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6685. $anime_script_id = getProp($anime, 'script_id');
  6686. if ($anime_script_id) {
  6687. $cpid = Site::getCpid();
  6688. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6689. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6690. ->where('mapping.script_id', $anime_script_id)
  6691. ->where('product.cpid', $cpid)
  6692. ->where('product.is_deleted', 0);
  6693. // 如果提供了 episode_number,则过滤指定集数
  6694. if ($episode_number !== null && $episode_number !== '') {
  6695. $script_products_mappings->where('mapping.episode_number', $episode_number);
  6696. }
  6697. $mappings = $script_products_mappings->select(
  6698. 'mapping.product_id',
  6699. 'mapping.episode_number',
  6700. 'product.product_name',
  6701. 'product.type',
  6702. 'product.product',
  6703. 'product.pic_prompt',
  6704. 'product.url',
  6705. 'product.pic_task_id',
  6706. 'product.pic_task_status',
  6707. 'product.three_view_image_url'
  6708. )
  6709. ->get();
  6710. // 按 product_id 分组,合并 episode_number
  6711. $productMap = [];
  6712. foreach ($mappings as $item) {
  6713. $product_id = $item->product_id;
  6714. $product_name = $item->product_name;
  6715. if (!isset($productMap[$product_id])) {
  6716. $productMap[$product_id] = [
  6717. 'product_id' => $product_id,
  6718. 'product_name' => $product_name,
  6719. 'type' => (int)$item->type,
  6720. 'product' => (int)$item->product,
  6721. 'pic_prompt' => $item->pic_prompt,
  6722. 'url' => $item->url,
  6723. 'pic_task_id' => $item->pic_task_id,
  6724. 'pic_task_status' => $item->pic_task_status,
  6725. 'episode_numbers' => [],
  6726. ];
  6727. }
  6728. // 添加 episode_number(去重)
  6729. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6730. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6731. }
  6732. }
  6733. // 将查询到的剧本资产合并到extra_products中
  6734. // 先构建extra_products的索引(以product_id+episode_number为key)
  6735. $extraProductsMap = [];
  6736. foreach ($extra_products as $item) {
  6737. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  6738. $extraProductsMap[$key] = $item;
  6739. }
  6740. // 合并剧本资产(去重:product_id+episode_number)
  6741. foreach ($productMap as $product) {
  6742. foreach ($product['episode_numbers'] as $ep_num) {
  6743. $key = $product['product_id'] . '_' . $ep_num;
  6744. // 如果不存在则添加
  6745. if (!isset($extraProductsMap[$key])) {
  6746. $extraProductsMap[$key] = [
  6747. 'product_id' => $product['product_id'],
  6748. 'product_name' => $product['product_name'],
  6749. 'type' => $product['type'],
  6750. 'product' => $product['product'],
  6751. 'pic_prompt' => $product['pic_prompt'],
  6752. 'url' => $product['url'],
  6753. 'pic_task_id' => $product['pic_task_id'],
  6754. 'pic_task_status' => $product['pic_task_status'],
  6755. 'episode_number' => $ep_num,
  6756. ];
  6757. }
  6758. }
  6759. }
  6760. // 重新赋值给extra_products
  6761. $extra_products = array_values($extraProductsMap);
  6762. }
  6763. // 处理提示词
  6764. if ($prompt && $extra_products) {
  6765. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6766. foreach($extra_products as $item) {
  6767. $product_name = getProp($item, 'product_name');
  6768. if ($product_name) {
  6769. // 替换 {product_name} 为 product_name
  6770. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6771. }
  6772. }
  6773. }
  6774. // 获取最后一集序号
  6775. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  6776. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  6777. // 转换主体列表和场景列表的格式
  6778. // 获取参考主体或场景
  6779. if ((int)$episode_number === 1) {
  6780. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  6781. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  6782. }else {
  6783. $prev_episode_number = $episode_number - 1;
  6784. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  6785. }
  6786. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  6787. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  6788. // 合并anime_products和extra_products(extra_products优先,去重)
  6789. $anime_products = getProp($anime, 'extra_products');
  6790. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  6791. $ref_products = [];
  6792. foreach($anime_products as $item) {
  6793. $product_name = getProp($item, 'product_name');
  6794. $ref_products[$product_name] = $item;
  6795. }
  6796. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  6797. $extra_roles = []; // 从extra_products中提取的角色
  6798. $extra_scenes = []; // 从extra_products中提取的场景
  6799. if ($extra_products && is_array($extra_products)) {
  6800. foreach($extra_products as $item) {
  6801. $product = (int)getProp($item, 'product');
  6802. $product_name = getProp($item, 'product_name');
  6803. if ($product_name == '旁白') continue;
  6804. $pic_prompt = getProp($item, 'pic_prompt');
  6805. $ref_products[$product_name] = $item;
  6806. if ($product === 1) {
  6807. // 角色
  6808. $extra_roles[$product_name] = [
  6809. 'role' => $product_name,
  6810. 'pic_prompt' => $pic_prompt,
  6811. 'url' => getProp($item, 'url', ''),
  6812. ];
  6813. } elseif ($product === 2) {
  6814. // 场景
  6815. $extra_scenes[$product_name] = [
  6816. 'scene' => $product_name,
  6817. 'pic_prompt' => $pic_prompt,
  6818. 'url' => getProp($item, 'url', ''),
  6819. ];
  6820. }
  6821. }
  6822. }
  6823. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  6824. $merged_roles = [];
  6825. foreach($ref_roles as $role) {
  6826. $role_name = getProp($role, 'role');
  6827. if (!isset($extra_roles[$role_name])) {
  6828. $merged_roles[$role_name] = $role;
  6829. }
  6830. }
  6831. // 添加extra_roles
  6832. foreach($extra_roles as $role_name => $role) {
  6833. $merged_roles[$role_name] = $role;
  6834. }
  6835. $ref_roles = array_values($merged_roles);
  6836. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  6837. $merged_scenes = [];
  6838. foreach($ref_scenes as $scene) {
  6839. $scene_name = getProp($scene, 'scene');
  6840. if (!isset($extra_scenes[$scene_name])) {
  6841. $merged_scenes[$scene_name] = $scene;
  6842. }
  6843. }
  6844. // 添加extra_scenes
  6845. foreach($extra_scenes as $scene_name => $scene) {
  6846. $merged_scenes[$scene_name] = $scene;
  6847. }
  6848. $ref_scenes = array_values($merged_scenes);
  6849. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  6850. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  6851. // 构建强制主体和场景提示词
  6852. $forced_roles_prompt = "";
  6853. $forced_scenes_prompt = "";
  6854. if (!empty($extra_roles)) {
  6855. $forced_roles_list = "";
  6856. foreach($extra_roles as $role_name => $role) {
  6857. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  6858. }
  6859. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6860. }
  6861. if (!empty($extra_scenes)) {
  6862. $forced_scenes_list = "";
  6863. foreach($extra_scenes as $scene_name => $scene) {
  6864. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  6865. }
  6866. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6867. }
  6868. if ($roles_content) {
  6869. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  6870. 主体范围:\n {$roles_content}\n
  6871. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  6872. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6873. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6874. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6875. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  6876. }else {
  6877. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6878. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6879. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6880. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6881. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  6882. }
  6883. if ($scenes_content) {
  6884. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  6885. 场景范围:\n {$scenes_content}\n
  6886. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  6887. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  6888. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6889. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  6890. }else {
  6891. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6892. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6893. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6894. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  6895. }
  6896. // 提取文件内容
  6897. if ($file) {
  6898. $uploaded_content = $this->extractFileContent($file);
  6899. if (!$uploaded_content) {
  6900. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6901. }
  6902. } elseif ($script_id) {
  6903. $uploaded_content = $this->getContentByScriptId($script_id);
  6904. if (!$uploaded_content) {
  6905. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6906. }
  6907. } elseif ($bid) {
  6908. $uploaded_content = $this->getContentByBid($bid);
  6909. if (!$uploaded_content) {
  6910. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6911. }
  6912. } elseif ($content) {
  6913. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  6914. }
  6915. // elseif ($prompt) {
  6916. // $uploaded_content = filterContent($prompt);
  6917. // }
  6918. else {
  6919. $uploaded_content = '';
  6920. }
  6921. // 美术风格
  6922. $input_art_style = getProp($data, 'art_style');
  6923. if (!$input_art_style) {
  6924. $mappedArtStyle = getProp($anime, 'art_style');
  6925. }else {
  6926. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6927. }
  6928. if (!$mappedArtStyle) {
  6929. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6930. }else {
  6931. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6932. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6933. }else {
  6934. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6935. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6936. }
  6937. }
  6938. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6939. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6940. // 强制要求:
  6941. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6942. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6943. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6944. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  6945. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  6946. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  6947. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  6948. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  6949. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  6950. // 10.分镜要和场景列表、人物主体保持一致\n
  6951. // 普通要求:
  6952. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  6953. // {$role_demo}
  6954. // {$scene_demo}
  6955. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6956. // 4.1片段分割逻辑(优先级从高到低):
  6957. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6958. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6959. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6960. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6961. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6962. // - 片段数量格式为: 片段数量:8
  6963. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6964. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6965. // 4.3分镜结构:每个分镜包含以下字段:
  6966. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  6967. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  6968. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6969. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  6970. // - 运镜:场景+画面描述+运镜
  6971. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  6972. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6973. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  6974. // 5.$mappedArtStyle_prompt\n\n
  6975. // 示例格式:\n
  6976. // 第1集:隐形的守护者
  6977. // ###故事梗概
  6978. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6979. // ###美术风格
  6980. // 基础画风风格词:胡金铨武侠
  6981. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  6982. // ###主体列表
  6983. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6984. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  6985. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  6986. // ###场景列表
  6987. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  6988. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  6989. // ###分段剧本
  6990. // 片段数量:8
  6991. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6992. // ##片段1
  6993. // 时长:12s
  6994. // 分镜1
  6995. // 场景:边境小镇街道
  6996. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6997. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6998. // 配音台词:
  6999. // 背景音效:
  7000. // 分镜2
  7001. // 场景:悦来酒馆
  7002. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7003. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7004. // 配音台词:
  7005. // 背景音效:
  7006. // 分镜3
  7007. // 场景:悦来酒馆
  7008. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7009. // 运镜:从中景推向令牌特写。
  7010. // 配音台词:
  7011. // 背景音效:
  7012. // 分镜4
  7013. // 场景:悦来酒馆
  7014. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7015. // 运镜:极速推向酒水溅起的瞬间。
  7016. // 配音台词:
  7017. // 背景音效:
  7018. // 分镜5
  7019. // 镜头描述
  7020. // 场景:悦来酒馆
  7021. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7022. // 运镜:固定机位,利用倾斜构图制造压迫感。
  7023. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7024. // 背景音效:
  7025. // \n\n";
  7026. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7027. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7028. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  7029. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  7030. 普通要求:
  7031. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7032. {$role_demo}
  7033. {$scene_demo}
  7034. 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7035. 4.1片段分割逻辑(优先级从高到低):
  7036. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7037. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7038. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7039. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7040. 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7041. - 片段数量格式为: 片段数量:8
  7042. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7043. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7044. 4.3分镜结构:每个分镜包含以下字段:
  7045. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7046. - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  7047. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7048. - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  7049. - 运镜:场景+画面描述+运镜
  7050. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  7051. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7052. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7053. 5.{$mappedArtStyle_prompt}
  7054. 6.《情绪-视听语言映射表》:
  7055. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7056. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7057. -----|---------|------------|----------------
  7058. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7059. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7060. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7061. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7062. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7063. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7064. -----|---------|------------|----------------
  7065. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7066. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7067. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7068. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7069. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7070. --------|---------|--------------|-------------
  7071. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7072. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7073. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7074. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7075. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7076. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7077. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7078. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7079. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7080. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7081. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7082. -----|---------|------------|------------
  7083. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7084. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7085. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7086. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7087. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7088. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7089. --------|---------|--------------|----------
  7090. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7091. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7092. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7093. 6.6 声音设计与潜意识影响 (Soundscape)
  7094. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7095. -----|---------|------------|------------------
  7096. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7097. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7098. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7099. 理论基石:
  7100. - The Five C's of Cinematography by Joseph V. Mascelli
  7101. - Film Art: An Introduction by David Bordwell
  7102. - Sight, Sound, Motion by Herbert Zettl
  7103. - Notes on the Cinematograph by Robert Bresson
  7104. \n\n
  7105. 示例格式:\n
  7106. 第1集:隐形的守护者
  7107. ###故事梗概
  7108. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7109. ###美术风格
  7110. 基础画风风格词:胡金铨武侠
  7111. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7112. ###主体列表
  7113. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7114. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7115. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7116. ###场景列表
  7117. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7118. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7119. ###分段剧本
  7120. 片段数量:8
  7121. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7122. ##片段1
  7123. 时长:12s
  7124. 分镜1
  7125. 场景:边境小镇街道
  7126. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7127. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7128. 配音台词:
  7129. 背景音效:
  7130. 分镜2
  7131. 场景:悦来酒馆
  7132. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7133. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7134. 配音台词:
  7135. 背景音效:
  7136. 分镜3
  7137. 场景:悦来酒馆
  7138. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7139. 运镜:从中景推向令牌特写。
  7140. 配音台词:
  7141. 背景音效:
  7142. 分镜4
  7143. 场景:悦来酒馆
  7144. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7145. 运镜:极速推向酒水溅起的瞬间。
  7146. 配音台词:
  7147. 背景音效:
  7148. 分镜5
  7149. 镜头描述
  7150. 场景:悦来酒馆
  7151. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7152. 运镜:固定机位,利用倾斜构图制造压迫感。
  7153. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7154. 背景音效:
  7155. \n\n";
  7156. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7157. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  7158. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7159. $prompt = $origin_prompt;
  7160. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7161. // 获取章节内容
  7162. $full_content = getProp($anime, 'content');
  7163. if ($uploaded_content) {
  7164. $full_content = $uploaded_content;
  7165. }
  7166. // 根据章节内容拆分章节
  7167. $chapters = $this->splitContent($full_content);
  7168. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7169. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7170. $messages = [];
  7171. if ($prompt == '确认分镜大纲') {
  7172. // 暂时保留
  7173. $content = $chapter_content;
  7174. if ($is_single) $content = $full_content; // 单剧集使用全文
  7175. if (!$content) {
  7176. Utils::throwError('20003:章节内容无法获取,请确认');
  7177. }
  7178. $question = $is_single
  7179. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7180. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7181. // 构建消息
  7182. $messages[] =
  7183. [
  7184. 'role' => 'user',
  7185. 'content' => $question
  7186. ];
  7187. }else if ($prompt == '继续策划下一集') {
  7188. if ($is_single) {
  7189. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7190. }
  7191. $content = $chapter_content;
  7192. if (!$content) {
  7193. Utils::throwError('20003:章节内容无法获取,请确认');
  7194. }
  7195. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7196. // 获取上一集最后记录
  7197. $prev_sequence = $episode_number - 1;
  7198. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7199. // 构建消息
  7200. $messages[] =
  7201. [
  7202. 'role' => 'user',
  7203. 'content' => $question
  7204. ];
  7205. // dd($messages);
  7206. }else {
  7207. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7208. if (!$content) {
  7209. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7210. }
  7211. if (!$content) {
  7212. Utils::throwError('20003:章节内容无法获取,请确认');
  7213. }
  7214. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7215. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7216. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7217. if ($origin_prompt) {
  7218. $question .= "本次修改要求如下:\n{$origin_prompt}";
  7219. }
  7220. $messages[] =
  7221. [
  7222. 'role' => 'user',
  7223. 'content' => $question
  7224. ];
  7225. }
  7226. // 处理文本模型
  7227. $model = getProp($data, 'model');
  7228. if (!$model) {
  7229. // 用户没有输入,从anime表获取
  7230. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7231. $model = getProp($anime, 'model');
  7232. if (!$model) {
  7233. // anime表也没有,使用默认值
  7234. $model = 'doubao-seed-2-0-mini-260215';
  7235. }
  7236. }
  7237. // 验证模型是否在可用模型表中
  7238. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7239. $model = 'doubao-seed-2-0-mini-260215';
  7240. }
  7241. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7242. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7243. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7244. if ($model === 'deepseek-chat') {
  7245. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7246. $model = 'deepseek-v4-flash';
  7247. $thinkingMode = 'disabled';
  7248. } elseif ($model === 'deepseek-reasoner') {
  7249. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7250. $model = 'deepseek-v4-flash';
  7251. $thinkingMode = 'enabled';
  7252. }
  7253. $post_data = [
  7254. 'model' => $model,
  7255. 'messages' => $messages,
  7256. // 'max_tokens' => 8192,
  7257. 'temperature' => 0.7,
  7258. 'frequency_penalty' => 0,
  7259. 'presence_penalty' => 0,
  7260. 'response_format' => ['type' => 'text'],
  7261. 'thinking' => ['type' => $thinkingMode],
  7262. 'stream' => true // 启用流式输出
  7263. ];
  7264. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7265. // 根据模型类型选择调用方法
  7266. $fullContent = '';
  7267. $fullReasoningContent = '';
  7268. $usage = [];
  7269. try {
  7270. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7271. // DeepSeek 官方模型使用 DeepSeek API
  7272. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7273. } else if (in_array($model, $this->gpt_text_models)) {
  7274. // GPT-5.4 模型使用 TokenRouter API
  7275. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7276. } else {
  7277. // 其他模型使用火山引擎API
  7278. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7279. }
  7280. // 验证返回值类型
  7281. if (!is_iterable($streamGenerator)) {
  7282. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7283. dLog('deepseek')->error('chat流式生成器无效', [
  7284. 'generator_type' => $errorType,
  7285. 'model' => $model,
  7286. 'anime_id' => $anime_id,
  7287. 'episode_number' => $episode_number
  7288. ]);
  7289. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7290. 'type' => $errorType,
  7291. 'model' => $model
  7292. ]);
  7293. yield [
  7294. 'type' => 'error',
  7295. 'episode' => [],
  7296. 'answer' => '',
  7297. 'reasoning' => '',
  7298. 'usage' => [],
  7299. 'error' => '接口返回数据异常,请重新请求'
  7300. ];
  7301. return;
  7302. }
  7303. // 处理流式输出
  7304. foreach ($streamGenerator as $chunk) {
  7305. if (isset($chunk['type'])) {
  7306. if ($chunk['type'] === 'done') {
  7307. // 最终结果
  7308. $fullContent = $chunk['full_content'];
  7309. $fullReasoningContent = $chunk['full_reasoning'];
  7310. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7311. } else {
  7312. // 逐块yield数据
  7313. yield $chunk;
  7314. }
  7315. }
  7316. }
  7317. } catch (\Exception $e) {
  7318. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7319. 'model' => $model,
  7320. 'anime_id' => $anime_id,
  7321. 'episode_number' => $episode_number,
  7322. 'trace' => $e->getTraceAsString()
  7323. ]);
  7324. logDB('deepseek', 'error', 'chat流式处理失败', [
  7325. 'error' => $e->getMessage(),
  7326. 'model' => $model
  7327. ]);
  7328. yield [
  7329. 'type' => 'error',
  7330. 'episode' => [],
  7331. 'answer' => '',
  7332. 'reasoning' => '',
  7333. 'usage' => [],
  7334. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7335. ];
  7336. return;
  7337. }
  7338. dLog('deepseek')->info('完整内容: '.$fullContent);
  7339. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7340. // 处理完整内容并返回最终结果
  7341. $episode_arr = handleEpisodeContentForAce($fullContent);
  7342. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7343. if (empty($episode_arr['acts'])) {
  7344. // 未生成剧本相关内容,保存对话记录并返回提示
  7345. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  7346. try {
  7347. $now = date('Y-m-d H:i:s');
  7348. // 保存对话记录
  7349. $records = [
  7350. [
  7351. 'uid' => $uid,
  7352. 'anime_id' => $anime_id,
  7353. 'sequence' => $episode_number,
  7354. 'role' => 'user',
  7355. 'content' => $prompt,
  7356. 'created_at' => $now,
  7357. 'updated_at' => $now
  7358. ],
  7359. [
  7360. 'uid' => $uid,
  7361. 'anime_id' => $anime_id,
  7362. 'sequence' => $episode_number,
  7363. 'role' => 'assistant',
  7364. 'content' => $fullContent,
  7365. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7366. 'created_at' => $now,
  7367. 'updated_at' => $now
  7368. ]
  7369. ];
  7370. DB::table('mp_anime_records')->insert($records);
  7371. } catch (\Exception $e) {
  7372. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7373. }
  7374. yield [
  7375. 'type' => 'done',
  7376. 'episode' => [],
  7377. 'answer' => $fullContent,
  7378. 'reasoning' => $fullReasoningContent,
  7379. 'usage' => $usage,
  7380. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  7381. ];
  7382. return;
  7383. }
  7384. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  7385. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  7386. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  7387. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  7388. $now = date('Y-m-d H:i:s');
  7389. try {
  7390. DB::beginTransaction();
  7391. $saveResult = $this->saveEpisodeVersionData(
  7392. $anime_id,
  7393. $episode_number,
  7394. $episode_arr,
  7395. $existing_roles,
  7396. $existing_scenes,
  7397. $current_episode,
  7398. $base_episode,
  7399. $is_regenerate_version,
  7400. $content,
  7401. $now,
  7402. $ref_products
  7403. );
  7404. $episode = $saveResult['episode'];
  7405. $episode_id = $saveResult['episode_id'];
  7406. $merged_roles = $saveResult['merged_roles'];
  7407. $merged_scenes = $saveResult['merged_scenes'];
  7408. $record_content = $origin_prompt;
  7409. if ($uploaded_content !== '') {
  7410. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  7411. }
  7412. $records = [
  7413. [
  7414. 'uid' => $uid,
  7415. 'anime_id' => $anime_id,
  7416. 'role' => 'user',
  7417. 'content' => $record_content,
  7418. 'sequence' => $episode_number,
  7419. 'episode_id' => $episode_id,
  7420. 'created_at' => $now,
  7421. 'updated_at' => $now
  7422. ],
  7423. [
  7424. 'uid' => $uid,
  7425. 'anime_id' => $anime_id,
  7426. 'role' => 'assistant',
  7427. 'content' => $fullContent,
  7428. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7429. 'sequence' => $episode_number,
  7430. 'episode_id' => $episode_id,
  7431. 'created_at' => $now,
  7432. 'updated_at' => $now
  7433. ]
  7434. ];
  7435. $boolen4 = DB::table('mp_anime_records')->insert($records);
  7436. if (!$boolen4) {
  7437. Utils::throwError('20003:对话记录保存失败');
  7438. }
  7439. // 保存模型到anime表
  7440. $update_anime_data = [
  7441. 'model' => $model,
  7442. 'updated_at' => $now
  7443. ];
  7444. if ($uploaded_content) {
  7445. $update_anime_data['content'] = $uploaded_content;
  7446. }
  7447. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  7448. }catch (\Exception $e) {
  7449. DB::rollBack();
  7450. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7451. yield [
  7452. 'type' => 'done',
  7453. 'answer' => $fullContent,
  7454. 'reasoning' => $fullReasoningContent,
  7455. 'usage' => $usage,
  7456. 'error' => $e->getMessage(),
  7457. ];
  7458. return;
  7459. }
  7460. DB::commit();
  7461. if ($is_global_generate_pics) {
  7462. // // 批量生成全局角色图片
  7463. // $this->batchSetGlobalRoleImg([
  7464. // 'anime_id' => $anime_id,
  7465. // ], true);
  7466. // // 批量生成全局场景图片
  7467. // $this->batchSetGlobalSceneImg([
  7468. // 'anime_id' => $anime_id,
  7469. // ], true);
  7470. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7471. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7472. }
  7473. $episode['episode_id'] = $episode_id;
  7474. $episode['roles'] = $merged_roles;
  7475. $episode['scenes'] = $merged_scenes;
  7476. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  7477. yield [
  7478. 'type' => 'done',
  7479. 'episode' => $episode,
  7480. 'answer' => $fullContent,
  7481. 'reasoning' => $fullReasoningContent,
  7482. 'usage' => $usage
  7483. ];
  7484. }
  7485. /**
  7486. * 重新生成分段剧本
  7487. * @param array $data 包含以下字段:
  7488. * - prompt: string|null 用户修改要求(可选)
  7489. * - template_id: int|null 提示词模板ID(可选)
  7490. * - act_id: int|null 单个片段ID(与episode_id二选一)
  7491. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  7492. * @return array 返回生成结果
  7493. */
  7494. public function regenerateSegmentScript($data) {
  7495. $uid = Site::getUid();
  7496. $prompt = trim((string)getProp($data, 'prompt', ''));
  7497. $template_id = getProp($data, 'template_id', 0);
  7498. $act_id = getProp($data, 'act_id', 0);
  7499. $episode_id = getProp($data, 'episode_id', 0);
  7500. // 验证:prompt和template_id至少提供一个
  7501. if (empty($prompt) && empty($template_id)) {
  7502. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  7503. }
  7504. // 验证:act_id和episode_id二选一
  7505. if (empty($act_id) && empty($episode_id)) {
  7506. Utils::throwError('20003:请提供片段ID或剧集ID');
  7507. }
  7508. if (!empty($act_id) && !empty($episode_id)) {
  7509. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  7510. }
  7511. // 如果提供了template_id,获取模板提示词
  7512. $template_prompt = '';
  7513. if ($template_id > 0) {
  7514. $template = DB::table('mp_prompt_templates')
  7515. ->where('id', $template_id)
  7516. ->where('is_deleted', 0)
  7517. ->first();
  7518. if (!$template) {
  7519. Utils::throwError('20003:提示词模板不存在或已删除');
  7520. }
  7521. $template_prompt = $template->template_prompt ?? '';
  7522. }
  7523. // 合并用户提示词和模板提示词
  7524. $final_prompt = '';
  7525. if (!empty($template_prompt)) {
  7526. $final_prompt = $template_prompt;
  7527. if (!empty($prompt)) {
  7528. $final_prompt .= "\n\n补充要求:" . $prompt;
  7529. }
  7530. } else {
  7531. $final_prompt = $prompt;
  7532. }
  7533. // 获取需要重新生成的内容参考
  7534. $reference_content = '';
  7535. $target_episode_id = 0;
  7536. $target_anime_id = 0;
  7537. $target_episode_number = 0;
  7538. if ($act_id > 0) {
  7539. // 单个片段模式:获取该片段的内容
  7540. $segment = DB::table('mp_episode_segments')
  7541. ->where('id', $act_id)
  7542. ->first();
  7543. if (!$segment) {
  7544. Utils::throwError('20003:片段不存在');
  7545. }
  7546. $target_episode_id = $segment->episode_id;
  7547. $target_anime_id = $segment->anime_id;
  7548. $target_episode_number = $segment->episode_number;
  7549. $reference_content = $segment->act_content ?? '';
  7550. } else {
  7551. // 整个剧集模式:获取所有片段的内容
  7552. $segments = DB::table('mp_episode_segments')
  7553. ->where('episode_id', $episode_id)
  7554. ->orderBy('act_number')
  7555. ->get();
  7556. if ($segments->isEmpty()) {
  7557. Utils::throwError('20003:该剧集没有片段数据');
  7558. }
  7559. $target_episode_id = $episode_id;
  7560. $target_anime_id = $segments[0]->anime_id;
  7561. $target_episode_number = $segments[0]->episode_number;
  7562. // 拼接所有片段内容,保留格式用于AI理解
  7563. $act_contents = [];
  7564. foreach ($segments as $seg) {
  7565. $act_number = $seg->act_number;
  7566. $act_content = $seg->act_content ?? '';
  7567. if (!empty($act_content)) {
  7568. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  7569. }
  7570. }
  7571. $reference_content = implode("\n\n", $act_contents);
  7572. }
  7573. if (empty($reference_content)) {
  7574. Utils::throwError('20003:没有可参考的片段内容');
  7575. }
  7576. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  7577. $episode = DB::table('mp_anime_episodes')
  7578. ->where('id', $target_episode_id)
  7579. ->first();
  7580. if (!$episode) {
  7581. Utils::throwError('20003:剧集不存在');
  7582. }
  7583. $intro = $episode->intro ?? '';
  7584. $art_style = $episode->art_style ?? '';
  7585. $roles = json_decode($episode->roles ?? '[]', true);
  7586. $scenes = json_decode($episode->scenes ?? '[]', true);
  7587. // 构建提示词中的主体列表和场景列表参考
  7588. $roles_ref = '';
  7589. if (!empty($roles) && is_array($roles)) {
  7590. $roles_list = [];
  7591. foreach ($roles as $role) {
  7592. $role_name = getProp($role, 'role', '');
  7593. $role_desc = getProp($role, 'description', '');
  7594. $pic_prompt = getProp($role, 'pic_prompt', '');
  7595. $voice_prompt = getProp($role, 'voice_prompt', '');
  7596. if (!empty($role_name)) {
  7597. $role_line = $role_name;
  7598. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  7599. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  7600. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  7601. $roles_list[] = $role_line;
  7602. }
  7603. }
  7604. if (!empty($roles_list)) {
  7605. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  7606. }
  7607. }
  7608. $scenes_ref = '';
  7609. if (!empty($scenes) && is_array($scenes)) {
  7610. $scenes_list = [];
  7611. foreach ($scenes as $scene) {
  7612. $scene_name = getProp($scene, 'scene', '');
  7613. $scene_desc = getProp($scene, 'description', '');
  7614. $pic_prompt = getProp($scene, 'pic_prompt', '');
  7615. if (!empty($scene_name)) {
  7616. $scene_line = $scene_name;
  7617. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  7618. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  7619. $scenes_list[] = $scene_line;
  7620. }
  7621. }
  7622. if (!empty($scenes_list)) {
  7623. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  7624. }
  7625. }
  7626. // 构建美术风格参考
  7627. $art_style_ref = '';
  7628. if (!empty($art_style)) {
  7629. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  7630. }
  7631. // 构建内容简介参考
  7632. $intro_ref = '';
  7633. if (!empty($intro)) {
  7634. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  7635. }
  7636. // 构建完整的AI提示词
  7637. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  7638. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  7639. $user_prompt .= "\n\n【原分段剧本内容】\n{$reference_content}";
  7640. $user_prompt .= $intro_ref;
  7641. $user_prompt .= $art_style_ref;
  7642. $user_prompt .= $roles_ref;
  7643. $user_prompt .= $scenes_ref;
  7644. $system_prompt = "\n\n【强制要求】\n";
  7645. $system_prompt .= "- 请仅生成<分段剧本>部分,格式强制设置如下,不要生成其他任何内容:";
  7646. $system_prompt .= "###分段剧本
  7647. 片段数量:8
  7648. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7649. ##片段1
  7650. 时长:12s
  7651. 分镜1
  7652. 场景:边境小镇街道
  7653. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7654. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7655. 配音台词:
  7656. 背景音效:
  7657. 分镜2
  7658. 场景:悦来酒馆
  7659. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7660. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7661. 配音台词:
  7662. 背景音效:
  7663. 分镜3
  7664. 场景:悦来酒馆
  7665. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7666. 运镜:从中景推向令牌特写。
  7667. 配音台词:
  7668. 背景音效:
  7669. 分镜4
  7670. 场景:悦来酒馆
  7671. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7672. 运镜:极速推向酒水溅起的瞬间。
  7673. 配音台词:
  7674. 背景音效:
  7675. 分镜5
  7676. 镜头描述
  7677. 场景:悦来酒馆
  7678. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7679. 运镜:固定机位,利用倾斜构图制造压迫感。
  7680. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7681. 背景音效:";
  7682. $system_prompt .= "- 每个分镜包含:分镜序号、场景、画面、运镜、配音台词、背景音效\n";
  7683. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表)\n";
  7684. $system_prompt .= "- 出场角色必须从【主体列表参考】中选择(如果提供了主体列表)\n";
  7685. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  7686. // 获取模型配置
  7687. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  7688. $model = $anime ? ($anime->model ?? 'doubao-seed-2-0-mini-260215') : 'doubao-seed-2-0-mini-260215';
  7689. // 验证模型是否在可用模型表中
  7690. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7691. $model = 'doubao-seed-2-0-mini-260215';
  7692. }
  7693. // 模型兼容性处理
  7694. $thinkingMode = 'disabled';
  7695. $reasoningEffort = 'high';
  7696. if ($model === 'deepseek-chat') {
  7697. $model = 'deepseek-v4-flash';
  7698. $thinkingMode = 'disabled';
  7699. } elseif ($model === 'deepseek-reasoner') {
  7700. $model = 'deepseek-v4-flash';
  7701. $thinkingMode = 'enabled';
  7702. }
  7703. // 构建消息
  7704. $messages = [
  7705. [
  7706. 'role' => 'system',
  7707. 'content' => $system_prompt
  7708. ],
  7709. [
  7710. 'role' => 'user',
  7711. 'content' => $user_prompt
  7712. ]
  7713. ];
  7714. // 构建请求参数
  7715. $post_data = [
  7716. 'model' => $model,
  7717. 'messages' => $messages,
  7718. 'temperature' => 0.7,
  7719. 'frequency_penalty' => 0,
  7720. 'presence_penalty' => 0,
  7721. 'response_format' => ['type' => 'text'],
  7722. 'thinking' => ['type' => $thinkingMode],
  7723. 'stream' => false // 非流式输出
  7724. ];
  7725. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7726. // 调用AI生成新的分段剧本
  7727. try {
  7728. $fullContent = '';
  7729. $usage = [];
  7730. // 根据模型类型选择调用方法
  7731. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7732. // DeepSeek 官方模型使用 DeepSeek API
  7733. $chatResult = $this->chatOnly($post_data);
  7734. } else if (in_array($model, $this->gpt_text_models)) {
  7735. // GPT 模型使用 TokenRouter API
  7736. $chatResult = $this->gpt54ChatOnly($post_data);
  7737. } else {
  7738. // 其他模型使用火山引擎API
  7739. $chatResult = $this->volcEngineChatCompletion($post_data);
  7740. }
  7741. if (is_array($chatResult)) {
  7742. $fullContent = $chatResult['fullContent'] ?? '';
  7743. $usage = $chatResult['usage'] ?? [];
  7744. }
  7745. $generated_content = $fullContent;
  7746. if (empty($generated_content)) {
  7747. Utils::throwError('20003:AI生成内容为空,请重试');
  7748. }
  7749. // 解析生成的内容 - 按片段分割
  7750. $parsed_segments = [];
  7751. // 先在开头添加换行符,确保第1片段也能被正确分割
  7752. $normalizedText = "\n" . $generated_content;
  7753. $parts = preg_split('/\n\s*##/', $normalizedText);
  7754. foreach ($parts as $part) {
  7755. $part = trim($part);
  7756. if (empty($part)) continue;
  7757. // 匹配"片段X"格式
  7758. if (!preg_match('/^片段\d+/', $part)) {
  7759. continue;
  7760. }
  7761. // 分离标题和内容
  7762. $lines = explode("\n", $part, 2);
  7763. $actTitle = trim($lines[0]);
  7764. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  7765. // 解析标题,提取序号
  7766. $actNumber = 0;
  7767. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  7768. $actNumber = intval($segmentTitleMatch[1]);
  7769. } else {
  7770. $actNumber = count($parsed_segments) + 1;
  7771. }
  7772. // 提取时长(仅保留数字)
  7773. $actDuration = 0;
  7774. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  7775. $actDurationStr = trim($actDurationMatch[1]);
  7776. // 提取数字部分(支持整数和小数)
  7777. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  7778. $actDuration = (float)$numMatch[1];
  7779. }
  7780. }
  7781. // 清理act_content:去除时长、旁白音色等非分镜内容行
  7782. // 只保留分镜内容,并确保分镜标记使用【】格式
  7783. $cleaned_content = '';
  7784. $content_lines = explode("\n", $actContent);
  7785. $is_capturing = false; // 标记是否开始捕获分镜内容
  7786. foreach ($content_lines as $line) {
  7787. $trimmed_line = trim($line);
  7788. // 跳过时长和旁白音色行
  7789. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  7790. continue;
  7791. }
  7792. // 检测是否是分镜开始
  7793. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  7794. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  7795. $is_capturing = true;
  7796. // 如果没有【】,则添加
  7797. if (!preg_match('/^【/u', $trimmed_line)) {
  7798. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  7799. }
  7800. }
  7801. // 如果已经开始捕获,则添加该行
  7802. if ($is_capturing && !empty($trimmed_line)) {
  7803. $cleaned_content .= $trimmed_line;
  7804. }
  7805. }
  7806. $parsed_segments[] = [
  7807. 'act_number' => $actNumber,
  7808. 'act_title' => $actTitle,
  7809. 'act_duration' => $actDuration,
  7810. 'act_content' => $cleaned_content,
  7811. ];
  7812. }
  7813. if (empty($parsed_segments)) {
  7814. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  7815. }
  7816. // 获取角色和场景名称用于标记
  7817. $role_names = [];
  7818. $scene_names = [];
  7819. if (!empty($roles) && is_array($roles)) {
  7820. foreach ($roles as $role) {
  7821. $role_name = getProp($role, 'role', '');
  7822. if (!empty($role_name)) {
  7823. $role_names[] = $role_name;
  7824. }
  7825. }
  7826. }
  7827. if (!empty($scenes) && is_array($scenes)) {
  7828. foreach ($scenes as $scene) {
  7829. $scene_name = getProp($scene, 'scene', '');
  7830. if (!empty($scene_name)) {
  7831. $scene_names[] = $scene_name;
  7832. }
  7833. }
  7834. }
  7835. // 处理每个片段的 act_show_content
  7836. foreach ($parsed_segments as &$segment) {
  7837. $act_content = getProp($segment, 'act_content', '');
  7838. if (empty($act_content)) {
  7839. $segment['act_show_content'] = '';
  7840. continue;
  7841. }
  7842. $processed_content = $act_content;
  7843. // 先匹配场景(在"场景:"后面)
  7844. foreach ($scene_names as $scene_name) {
  7845. // 转义特殊字符
  7846. $escaped_scene = preg_quote($scene_name, '/');
  7847. // 匹配场景:后面的场景名称(可能换行,也可能不换行)
  7848. $pattern = '/(场景:[\s\r\n]*)(' . $escaped_scene . ')/u';
  7849. $processed_content = preg_replace_callback($pattern, function($matches) {
  7850. $prefix = $matches[1];
  7851. $scene_name = $matches[2];
  7852. // 检查是否已经被标记
  7853. if (strpos($scene_name, '{') === false && strpos($scene_name, '}') === false) {
  7854. return $prefix . '{' . $scene_name . '}';
  7855. }
  7856. return $matches[0];
  7857. }, $processed_content);
  7858. }
  7859. // 再匹配角色名称(只在"画面:"部分)
  7860. foreach ($role_names as $role_name) {
  7861. // 转义特殊字符
  7862. $escaped_role = preg_quote($role_name, '/');
  7863. // 只匹配"画面:"开始到换行之前的内容
  7864. $pattern = '/(画面:[^\n]*)/u';
  7865. $processed_content = preg_replace_callback($pattern, function($matches) use ($escaped_role) {
  7866. $line = $matches[1]; // 整行"画面:xxxxx"
  7867. // 在这一行中匹配所有角色名(避免重复标记)
  7868. $new_line = preg_replace(
  7869. '/(?<![{])(' . $escaped_role . ')(?![}])/u',
  7870. '{$1}',
  7871. $line
  7872. );
  7873. return $new_line;
  7874. }, $processed_content);
  7875. }
  7876. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  7877. $shot_counter = 0;
  7878. $processed_content = preg_replace_callback(
  7879. '/【(?:镜头|分镜)(\d+)】/u',
  7880. function($matches) use (&$shot_counter) {
  7881. $shot_counter++;
  7882. return '【镜头' . $shot_counter . '】';
  7883. },
  7884. $processed_content
  7885. );
  7886. $segment['act_show_content'] = $processed_content;
  7887. }
  7888. unset($segment); // 解除引用
  7889. // 保存到数据库
  7890. $now = date('Y-m-d H:i:s');
  7891. $saved_acts = []; // 用于记录保存后的片段信息
  7892. if ($act_id > 0) {
  7893. // 单个片段模式:更新单条记录
  7894. if (count($parsed_segments) > 0) {
  7895. $new_segment = $parsed_segments[0];
  7896. $update_data = [
  7897. 'act_content' => getProp($new_segment, 'act_content', ''),
  7898. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  7899. 'act_title' => getProp($new_segment, 'act_title', ''),
  7900. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  7901. 'updated_at' => $now,
  7902. ];
  7903. DB::table('mp_episode_segments')
  7904. ->where('id', $act_id)
  7905. ->update($update_data);
  7906. // 获取更新后的记录
  7907. $updated_act = DB::table('mp_episode_segments')
  7908. ->where('id', $act_id)
  7909. ->first();
  7910. if ($updated_act) {
  7911. $saved_acts[] = [
  7912. 'act_id' => $updated_act->id,
  7913. 'act_number' => $updated_act->act_number,
  7914. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  7915. 'act_content' => $updated_act->act_content,
  7916. 'act_show_content' => $updated_act->act_show_content,
  7917. 'video_url' => $updated_act->video_url ?? '',
  7918. 'video_duration' => $updated_act->video_duration ?? 0,
  7919. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  7920. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  7921. ];
  7922. }
  7923. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  7924. }
  7925. } else {
  7926. // 整个剧集模式:删除原有记录并批量保存新记录
  7927. DB::beginTransaction();
  7928. try {
  7929. // 删除原有的所有片段记录
  7930. DB::table('mp_episode_segments')
  7931. ->where('episode_id', $target_episode_id)
  7932. ->delete();
  7933. // 批量插入新的片段记录
  7934. $segments_to_insert = [];
  7935. foreach ($parsed_segments as $index => $segment) {
  7936. $act_number = $index + 1;
  7937. $segments_to_insert[] = [
  7938. 'anime_id' => $target_anime_id,
  7939. 'episode_id' => $target_episode_id,
  7940. 'episode_number' => $target_episode_number,
  7941. 'act_number' => $act_number,
  7942. 'act_title' => getProp($segment, 'act_title', ''),
  7943. 'act_duration' => getProp($segment, 'act_duration', 0),
  7944. 'act_content' => getProp($segment, 'act_content', ''),
  7945. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  7946. 'created_at' => $now,
  7947. 'updated_at' => $now,
  7948. ];
  7949. }
  7950. if (!empty($segments_to_insert)) {
  7951. DB::table('mp_episode_segments')->insert($segments_to_insert);
  7952. }
  7953. DB::commit();
  7954. // 查询保存后的所有片段记录
  7955. $saved_segments = DB::table('mp_episode_segments')
  7956. ->where('episode_id', $target_episode_id)
  7957. ->orderBy('act_number')
  7958. ->get();
  7959. foreach ($saved_segments as $saved_segment) {
  7960. $saved_acts[] = [
  7961. 'act_id' => $saved_segment->id,
  7962. 'act_number' => $saved_segment->act_number,
  7963. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  7964. 'act_content' => $saved_segment->act_content,
  7965. 'act_show_content' => $saved_segment->act_show_content,
  7966. 'video_url' => $saved_segment->video_url ?? '',
  7967. 'video_duration' => $saved_segment->video_duration ?? 0,
  7968. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  7969. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  7970. ];
  7971. }
  7972. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  7973. 'episode_id' => $target_episode_id,
  7974. 'segments_count' => count($segments_to_insert)
  7975. ]);
  7976. } catch (\Exception $e) {
  7977. DB::rollBack();
  7978. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  7979. Utils::throwError('20003:保存失败,请重试');
  7980. }
  7981. }
  7982. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  7983. return [
  7984. 'anime_id' => $target_anime_id,
  7985. 'episode_id' => $target_episode_id,
  7986. 'title' => getProp($episode, 'title', ''),
  7987. 'episode_number' => $target_episode_number,
  7988. 'is_generated' => getProp($episode, 'is_generated', 0),
  7989. 'acts' => $saved_acts,
  7990. ];
  7991. } catch (\Exception $e) {
  7992. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  7993. throw $e;
  7994. }
  7995. }
  7996. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  7997. {
  7998. $episode_arr = [
  7999. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  8000. 'intro' => getProp($script_arr, 'intro'),
  8001. 'art_style' => getProp($script_arr, 'art_style'),
  8002. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8003. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8004. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  8005. ];
  8006. if (empty($episode_arr['acts'])) {
  8007. $fallback_episode_arr = handleEpisodeContent($fullContent);
  8008. if (!empty($fallback_episode_arr['acts'])) {
  8009. $episode_arr = array_merge($fallback_episode_arr, [
  8010. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  8011. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  8012. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  8013. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  8014. ]);
  8015. }
  8016. }
  8017. // if (!getProp($episode_arr, 'episode_title')) {
  8018. // $episode_title = '';
  8019. // $episodes = getProp($script_arr, 'episodes', []);
  8020. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  8021. // $episode_title = '第1集:' . $episodes[0]['title'];
  8022. // }
  8023. // if (!$episode_title) {
  8024. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  8025. // }
  8026. // $episode_arr['episode_title'] = $episode_title;
  8027. // }
  8028. return $episode_arr;
  8029. }
  8030. private function saveEpisodeVersionData(
  8031. int $anime_id,
  8032. int $episode_number,
  8033. array $episode_arr,
  8034. array $existing_roles,
  8035. array $existing_scenes,
  8036. $current_episode,
  8037. $base_episode,
  8038. bool $is_regenerate_version,
  8039. string $content,
  8040. string $now,
  8041. array $ref_products = []
  8042. ): array {
  8043. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  8044. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  8045. $merged_roles = $generated_roles;
  8046. $merged_scenes = $generated_scenes;
  8047. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  8048. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  8049. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  8050. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8051. $ace_mode = getProp($anime, 'ace_mode');
  8052. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  8053. $global_roles = json_decode(getProp($anime, 'roles'), true);
  8054. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  8055. $global_roles = is_array($global_roles) ? $global_roles : [];
  8056. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  8057. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  8058. $art_style_type = getProp($anime, 'art_style_type');
  8059. // 检查并创建 roles 的图片生成任务
  8060. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  8061. // 检查并创建 scenes 的图片生成任务
  8062. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  8063. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $ref_products, $art_style_type);
  8064. if ($arr && is_array($arr)) {
  8065. $merged_roles = $arr['roles'];
  8066. $merged_scenes = $arr['scenes'];
  8067. }
  8068. // 确保数据是数组类型
  8069. if (!is_array($merged_roles)) {
  8070. dLog('deepseek')->error('merged_roles不是数组类型', [
  8071. 'type' => gettype($merged_roles),
  8072. 'value' => $merged_roles
  8073. ]);
  8074. $merged_roles = [];
  8075. }
  8076. if (!is_array($merged_scenes)) {
  8077. dLog('deepseek')->error('merged_scenes不是数组类型', [
  8078. 'type' => gettype($merged_scenes),
  8079. 'value' => $merged_scenes
  8080. ]);
  8081. $merged_scenes = [];
  8082. }
  8083. // 同步新出现的主体和场景到全局
  8084. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  8085. $role_arr = [];
  8086. foreach ($merged_roles as $item) {
  8087. $role_arr[$item['role']] = $item;
  8088. }
  8089. $version_count = DB::table('mp_anime_episodes')
  8090. ->where('anime_id', $anime_id)
  8091. ->where('episode_number', $episode_number)
  8092. ->count('id');
  8093. $episode = [
  8094. 'anime_id' => $anime_id,
  8095. 'episode_number' => $episode_number,
  8096. 'title' => getProp($episode_arr, 'episode_title'),
  8097. 'content' => $content,
  8098. 'intro' => getProp($episode_arr, 'intro'),
  8099. 'art_style' => getProp($episode_arr, 'art_style'),
  8100. 'roles' => json_encode($merged_roles, 256),
  8101. 'scenes' => json_encode($merged_scenes, 256),
  8102. 'generate_status' => '待执行',
  8103. 'generate_at' => $now,
  8104. 'is_default' => 1,
  8105. 'updated_at' => $now,
  8106. ];
  8107. $del_flag = false;
  8108. if ($is_regenerate_version) {
  8109. DB::table('mp_anime_episodes')
  8110. ->where('anime_id', $anime_id)
  8111. ->where('episode_number', $episode_number)
  8112. ->update(['is_default' => 0, 'updated_at' => $now]);
  8113. $episode['sequence'] = $version_count + 1;
  8114. $episode['created_at'] = $now;
  8115. $episode['cpid'] = Site::getCpid();
  8116. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  8117. if (!$episode_id) {
  8118. Utils::throwError('20003:创建剧集版本失败');
  8119. }
  8120. } else {
  8121. $target_episode = $current_episode ?: $base_episode;
  8122. if ($target_episode) {
  8123. $episode_id = getProp($target_episode, 'id');
  8124. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  8125. DB::table('mp_anime_episodes')
  8126. ->where('anime_id', $anime_id)
  8127. ->where('episode_number', $episode_number)
  8128. ->where('id', '<>', $episode_id)
  8129. ->update(['is_default' => 0, 'updated_at' => $now]);
  8130. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  8131. if ($boolen === false) {
  8132. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  8133. Utils::throwError('20003:分集内容保存失败');
  8134. }
  8135. $del_flag = true;
  8136. } else {
  8137. DB::table('mp_anime_episodes')
  8138. ->where('anime_id', $anime_id)
  8139. ->where('episode_number', $episode_number)
  8140. ->update(['is_default' => 0, 'updated_at' => $now]);
  8141. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  8142. $episode['created_at'] = $now;
  8143. $episode['cpid'] = Site::getCpid();
  8144. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  8145. if (!$episode_id) {
  8146. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  8147. Utils::throwError('20003:分集内容保存失败');
  8148. }
  8149. }
  8150. }
  8151. $segments = [];
  8152. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  8153. // 如果是第2集及以后,获取上一集的主体音色数据
  8154. $previous_roles_voice = [];
  8155. if ($episode_number >= 2) {
  8156. $previous_episode = DB::table('mp_anime_episodes')
  8157. ->where('anime_id', $anime_id)
  8158. ->where('episode_number', $episode_number - 1)
  8159. ->where('is_default', 1)
  8160. ->first();
  8161. if ($previous_episode) {
  8162. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  8163. if (is_array($previous_roles)) {
  8164. foreach ($previous_roles as $prev_role) {
  8165. $role_name = getProp($prev_role, 'role');
  8166. if ($role_name) {
  8167. $previous_roles_voice[$role_name] = [
  8168. 'voice_name' => getProp($prev_role, 'voice_name'),
  8169. 'voice_type' => getProp($prev_role, 'voice_type'),
  8170. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  8171. ];
  8172. $voice_prompt = getProp($prev_role, 'voice_prompt');
  8173. if ($voice_prompt) {
  8174. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  8175. }
  8176. }
  8177. }
  8178. }
  8179. }
  8180. }
  8181. // 将继承的音色数据同步到当前集的主体列表
  8182. if (!empty($previous_roles_voice)) {
  8183. foreach ($merged_roles as &$role) {
  8184. $role_name = getProp($role, 'role');
  8185. if ($role_name && isset($previous_roles_voice[$role_name])) {
  8186. // 强制继承上一集的音色数据
  8187. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  8188. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  8189. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  8190. // 如果上一集有 voice_prompt 则继承,否则跳过
  8191. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  8192. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  8193. }
  8194. }
  8195. }
  8196. unset($role); // 解除引用
  8197. // 更新 role_arr 以便后续使用
  8198. $role_arr = [];
  8199. foreach ($merged_roles as $item) {
  8200. $role_arr[$item['role']] = $item;
  8201. }
  8202. }
  8203. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  8204. $emotion_list = array_flip($emotion_list);
  8205. foreach ($acts as $act) {
  8206. $act_segments = getProp($act, 'segments', []);
  8207. if (!is_array($act_segments)) {
  8208. continue;
  8209. }
  8210. if ((int)$ace_mode === 1) {
  8211. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  8212. $merged_parts = [];
  8213. foreach ($act_segments as $seg) {
  8214. $seg_num = getProp($seg, 'segment_number');
  8215. $seg_content = getProp($seg, 'segment_content');
  8216. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  8217. }
  8218. $segments[] = [
  8219. 'anime_id' => $anime_id,
  8220. 'episode_id' => $episode_id,
  8221. 'episode_number' => $episode_number,
  8222. 'act_number' => getProp($act, 'act_number'),
  8223. 'act_title' => getProp($act, 'act_title'),
  8224. 'act_duration' => getProp($act, 'act_duration'),
  8225. 'act_content' => implode("\n", $merged_parts),
  8226. 'created_at' => $now,
  8227. 'updated_at' => $now
  8228. ];
  8229. } else {
  8230. foreach ($act_segments as $segment) {
  8231. $voice_actor = getProp($segment, 'voice_actor');
  8232. // 优先从上一集继承音色数据
  8233. $timbre_info = [];
  8234. if (isset($previous_roles_voice[$voice_actor])) {
  8235. // 从上一集继承音色数据
  8236. $timbre_info = $previous_roles_voice[$voice_actor];
  8237. } elseif (isset($role_arr[$voice_actor])) {
  8238. // 使用当前集的主体音色数据
  8239. $timbre_info = $role_arr[$voice_actor];
  8240. }
  8241. $voice_type = getProp($timbre_info, 'voice_type');
  8242. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  8243. if ($timbre_emotion) {
  8244. $timbre_emotion = explode(',', $timbre_emotion);
  8245. } else {
  8246. $timbre_emotion = [];
  8247. }
  8248. $emotion = getProp($segment, 'emotion', '中性');
  8249. if (!in_array($emotion, $timbre_emotion)) {
  8250. $emotion = '中性';
  8251. }
  8252. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  8253. $segments[] = [
  8254. 'anime_id' => $anime_id,
  8255. 'episode_id' => $episode_id,
  8256. 'episode_number' => $episode_number,
  8257. 'act_number' => getProp($act, 'act_number'),
  8258. 'act_title' => getProp($act, 'act_title'),
  8259. 'act_duration' => getProp($act, 'act_duration'),
  8260. 'segment_id' => getProp($segment, 'segment_id'),
  8261. 'segment_number' => getProp($segment, 'segment_number'),
  8262. 'segment_content' => getProp($segment, 'segment_content'),
  8263. 'description' => getProp($segment, 'description'),
  8264. 'composition' => getProp($segment, 'composition'),
  8265. 'camera_movement' => getProp($segment, 'camera_movement'),
  8266. 'voice_actor' => $voice_actor,
  8267. 'dialogue' => getProp($segment, 'dialogue'),
  8268. 'frame_type' => getProp($segment, 'frame_type'),
  8269. 'scene' => getProp($segment, 'scene'),
  8270. 'characters' => getProp($segment, 'characters'),
  8271. 'tail_frame' => getProp($segment, 'tail_frame'),
  8272. 'voice_name' => getProp($timbre_info, 'voice_name'),
  8273. 'voice_type' => $voice_type,
  8274. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  8275. 'emotion' => $emotion,
  8276. 'emotion_type' => $emotion_type,
  8277. 'gender' => getProp($segment, 'gender', '0'),
  8278. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  8279. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  8280. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  8281. 'pitch' => getProp($segment, 'pitch', 0),
  8282. 'created_at' => $now,
  8283. 'updated_at' => $now
  8284. ];
  8285. }
  8286. }
  8287. }
  8288. if ($segments) {
  8289. if ($del_flag) {
  8290. DB::table('mp_episode_segments')
  8291. ->where('anime_id', $anime_id)
  8292. ->where('episode_id', $episode_id)
  8293. ->delete();
  8294. }
  8295. $boolen = DB::table('mp_episode_segments')->insert($segments);
  8296. if (!$boolen) {
  8297. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  8298. Utils::throwError('20003:分镜内容保存失败');
  8299. }
  8300. }
  8301. dLog('deepseek')->info('segments', $segments);
  8302. // ace_mode=1: acts 返回值按合并格式调整
  8303. if ((int)$ace_mode === 1) {
  8304. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  8305. $act_map = [];
  8306. foreach ($table_act_data as $item) {
  8307. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  8308. }
  8309. $restructured_acts = [];
  8310. foreach ($acts as $act) {
  8311. $act_segments = getProp($act, 'segments', []);
  8312. if (!is_array($act_segments)) {
  8313. continue;
  8314. }
  8315. $merged_parts = [];
  8316. foreach ($act_segments as $seg) {
  8317. $seg_num = getProp($seg, 'segment_number');
  8318. $seg_content = getProp($seg, 'segment_content');
  8319. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  8320. }
  8321. $restructured_acts[] = [
  8322. 'anime_id' => $anime_id,
  8323. 'episode_id' => $episode_id,
  8324. 'episode_number' => $episode_number,
  8325. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  8326. 'act_number' => getProp($act, 'act_number'),
  8327. 'act_title' => getProp($act, 'act_title'),
  8328. 'act_duration' => getProp($act, 'act_duration'),
  8329. 'act_content' => implode("\n", $merged_parts),
  8330. 'created_at' => $now,
  8331. 'updated_at' => $now,
  8332. ];
  8333. }
  8334. $acts = $restructured_acts;
  8335. }
  8336. $episode['episode_id'] = $episode_id;
  8337. $episode['roles'] = $merged_roles;
  8338. $episode['scenes'] = $merged_scenes;
  8339. $episode['acts'] = $acts;
  8340. return [
  8341. 'episode' => $episode,
  8342. 'episode_id' => $episode_id,
  8343. 'merged_roles' => $merged_roles,
  8344. 'merged_scenes' => $merged_scenes,
  8345. ];
  8346. }
  8347. private function buildEpisodeItemContent(array $items, string $nameKey): string
  8348. {
  8349. $content = '';
  8350. foreach ($items as $item) {
  8351. $name = trim((string)getProp($item, $nameKey));
  8352. if ($name === '' || $name === '旁白') {
  8353. continue;
  8354. }
  8355. $description = trim((string)getProp($item, 'description'));
  8356. $content .= $name . ': ' . $description;
  8357. if ($nameKey == 'role') {
  8358. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  8359. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  8360. $voice_name = trim(getProp($item, 'voice_name'));
  8361. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  8362. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  8363. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  8364. }else {
  8365. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  8366. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  8367. }
  8368. $content .= "\n";
  8369. }
  8370. return trim($content);
  8371. }
  8372. private function getEpisodeChatContent($animeId, $sequence, $content) {
  8373. if ((int)$sequence <= 0) {
  8374. return [];
  8375. }
  8376. $origin_content = '';
  8377. if ($content) {
  8378. $origin_content = '本集剧情内容:'.$content;
  8379. }else {
  8380. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  8381. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  8382. }
  8383. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  8384. // 获取分集信息
  8385. $episode = DB::table('mp_anime_episodes')
  8386. ->where('anime_id', $animeId)
  8387. ->where('episode_number', $sequence)
  8388. ->where('is_default', 1)
  8389. ->first();
  8390. if (!$episode) {
  8391. return [];
  8392. }
  8393. $episode_id = getProp($episode, 'id');
  8394. $episode_number = getProp($episode, 'episode_number');
  8395. $title = getProp($episode, 'title');
  8396. $intro = getProp($episode, 'intro');
  8397. $art_style = getProp($episode, 'art_style');
  8398. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  8399. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  8400. // 组装纯文本内容
  8401. $content = '';
  8402. // 添加分集标题和梗概
  8403. $content .= "###第{$episode_number}集:{$title}\n\n";
  8404. $content .= "###故事梗概\n";
  8405. $content .= trim($intro) . "\n\n";
  8406. // 添加美术风格
  8407. $content .= "###美术风格\n";
  8408. $content .= trim($art_style) . "\n\n";
  8409. // 添加主体列表
  8410. $content .= "###主体列表\n";
  8411. $pangbai_voice_prompt = "";
  8412. foreach ($roles as $role) {
  8413. $name = getProp($role, 'role');
  8414. $description = getProp($role, 'description');
  8415. $pic_prompt = getProp($role, 'pic_prompt');
  8416. $voice_prompt = getProp($role, 'voice_prompt');
  8417. $voice_name = getProp($role, 'voice_name');
  8418. $content .= "{$name}: {$description}";
  8419. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  8420. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  8421. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  8422. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  8423. $content .= "\n";
  8424. }
  8425. $content .= "\n";
  8426. // 添加场景列表
  8427. $content .= "###场景列表\n";
  8428. foreach ($scenes as $scene) {
  8429. $name = getProp($scene, 'scene');
  8430. $description = getProp($scene, 'description');
  8431. $pic_prompt = getProp($scene, 'pic_prompt');
  8432. $content .= "{$name}: {$description}";
  8433. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  8434. $content .= "\n";
  8435. }
  8436. $content .= "\n";
  8437. // 获取分镜信息
  8438. $segments = DB::table('mp_episode_segments')
  8439. ->where('anime_id', $animeId)
  8440. ->where('episode_id', $episode_id)
  8441. ->orderBy('segment_number')
  8442. ->get();
  8443. if ($segments && count($segments) > 0) {
  8444. if ((int)$ace_mode === 1) {
  8445. $content .= "###分段剧本\n";
  8446. // 获取片段数量
  8447. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  8448. $content .= "片段数量:{$act_count}\n";
  8449. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  8450. $content .= "\n";
  8451. }else {
  8452. $content .= "###分镜剧本\n";
  8453. }
  8454. // 按幕分组
  8455. $currentAct = null;
  8456. foreach ($segments as $segment) {
  8457. $act_number = getProp($segment, 'act_number');
  8458. $act_title = getProp($segment, 'act_title');
  8459. $act_duration = getProp($segment, 'act_duration');
  8460. $segment_number = getProp($segment, 'segment_number');
  8461. $segment_content = getProp($segment, 'segment_content');
  8462. $scene_description = getProp($segment, 'scene_description');
  8463. $scene_name = getProp($segment, 'scene_name');
  8464. $composition = getProp($segment, 'composition');
  8465. $camera_movement = getProp($segment, 'camera_movement');
  8466. $voice_type = getProp($segment, 'voice_type');
  8467. $characters = getProp($segment, 'characters');
  8468. $dialogue = getProp($segment, 'dialogue');
  8469. $frame_type = getProp($segment, 'frame_type');
  8470. $tail_frame_description = getProp($segment, 'tail_frame_description');
  8471. // 判断是否是全能模式
  8472. if ((int)$ace_mode === 1) { // 全能模式
  8473. // 如果是新的分段,添加分段标题
  8474. if ($act_number !== $currentAct) {
  8475. $currentAct = $act_number;
  8476. $content .= "##{$act_title}\n";
  8477. $content .= "时长:{$act_duration}s\n";
  8478. }
  8479. }else {
  8480. // 如果是新的幕,添加幕标题
  8481. if ($act_number !== $currentAct) {
  8482. $currentAct = $act_number;
  8483. $content .= "##第{$act_number}幕:{$scene_name}\n";
  8484. }
  8485. }
  8486. // 添加分镜信息
  8487. $content .= "分镜{$segment_number}\n";
  8488. $content .= "分镜内容:\n{$segment_content}\n";
  8489. // $content .= "画面描述:{$scene_description}\n";
  8490. // $content .= "场景:{$scene_name}\n";
  8491. // $content .= "构图设计:{$composition}\n";
  8492. // $content .= "运镜调度:{$camera_movement}\n";
  8493. // if (!empty($voice_type)) {
  8494. // $content .= "配音角色:{$voice_type}\n";
  8495. // }
  8496. // if (!empty($characters)) {
  8497. // $content .= "出镜角色:{$characters}\n";
  8498. // }
  8499. // if (!empty($dialogue)) {
  8500. // $content .= "台词内容:\"{$dialogue}\"\n";
  8501. // }
  8502. // $content .= "画面类型:{$frame_type}\n";
  8503. // $content .= "尾帧描述:{$tail_frame_description}\n";
  8504. $content .= "\n";
  8505. }
  8506. }
  8507. $content = trim($content);
  8508. if($content) $content = "上集剧本内容:\n{$content}";
  8509. return [
  8510. [
  8511. 'role' => 'user',
  8512. 'content' => $origin_content
  8513. ],
  8514. [
  8515. 'role' => 'assistant',
  8516. 'content' => $content
  8517. ]
  8518. ];
  8519. }
  8520. private function getEpisodeChatMessages($animeId, $sequence): array
  8521. {
  8522. if ((int)$sequence <= 0) {
  8523. return [];
  8524. }
  8525. return DB::table('mp_anime_records')
  8526. ->where('anime_id', $animeId)
  8527. ->where('sequence', $sequence)
  8528. ->where('episode_id', '>', 0)
  8529. ->select('role', 'content')
  8530. ->orderBy('created_at')
  8531. ->orderBy('id')
  8532. ->get()
  8533. ->map(function ($value) {
  8534. return (array)$value;
  8535. })
  8536. ->toArray();
  8537. }
  8538. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  8539. {
  8540. $existingMap = [];
  8541. foreach ($existingItems as $item) {
  8542. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  8543. if ($itemKey === '') {
  8544. continue;
  8545. }
  8546. $existingMap[$itemKey] = $item;
  8547. }
  8548. if (!$generatedItems) {
  8549. return array_values($existingItems);
  8550. }
  8551. $merged = [];
  8552. foreach ($generatedItems as $item) {
  8553. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  8554. if ($itemKey === '') {
  8555. continue;
  8556. }
  8557. if (isset($existingMap[$itemKey])) {
  8558. if (trim((string)getProp($item, 'description')) === '') {
  8559. $merged[] = $existingMap[$itemKey];
  8560. continue;
  8561. }
  8562. // 检查内容是否发生变化
  8563. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  8564. if (!$isChanged) {
  8565. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  8566. $mergedItem = [
  8567. $nameKey => trim((string)getProp($item, $nameKey)),
  8568. 'description' => trim((string)getProp($item, 'description')),
  8569. ];
  8570. // 如果有 pic_prompt,添加到合并项中
  8571. $picPrompt = getProp($item, 'pic_prompt');
  8572. if (!empty($picPrompt)) {
  8573. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  8574. }
  8575. // 继承现有项的 URL
  8576. $existingUrl = getProp($existingMap[$itemKey], 'url');
  8577. if (!empty($existingUrl)) {
  8578. $mergedItem['url'] = $existingUrl;
  8579. }
  8580. // 继承现有项的 task_id
  8581. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  8582. if (!empty($existingTaskId)) {
  8583. $mergedItem['task_id'] = $existingTaskId;
  8584. }
  8585. // 继承现有项的 task_status
  8586. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  8587. if (!empty($existingTaskStatus)) {
  8588. $mergedItem['task_status'] = $existingTaskStatus;
  8589. }
  8590. // 保留生成项的音色字段
  8591. $voiceName = getProp($item, 'voice_name');
  8592. if (!empty($voiceName)) {
  8593. $mergedItem['voice_name'] = $voiceName;
  8594. }
  8595. $voiceType = getProp($item, 'voice_type');
  8596. if (!empty($voiceType)) {
  8597. $mergedItem['voice_type'] = $voiceType;
  8598. }
  8599. $audioUrl = getProp($item, 'voice_audio_url');
  8600. if (!empty($audioUrl)) {
  8601. $mergedItem['voice_audio_url'] = $audioUrl;
  8602. }
  8603. $merged[] = $mergedItem;
  8604. } else {
  8605. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  8606. $mergedItem = [
  8607. $nameKey => trim((string)getProp($item, $nameKey)),
  8608. 'description' => trim((string)getProp($item, 'description')),
  8609. ];
  8610. // 如果有 pic_prompt,添加到合并项中
  8611. $picPrompt = getProp($item, 'pic_prompt');
  8612. if (!empty($picPrompt)) {
  8613. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  8614. }
  8615. // 保留生成项的音色字段
  8616. $voiceName = getProp($item, 'voice_name');
  8617. if (!empty($voiceName)) {
  8618. $mergedItem['voice_name'] = $voiceName;
  8619. }
  8620. $voiceType = getProp($item, 'voice_type');
  8621. if (!empty($voiceType)) {
  8622. $mergedItem['voice_type'] = $voiceType;
  8623. }
  8624. $audioUrl = getProp($item, 'voice_audio_url');
  8625. if (!empty($audioUrl)) {
  8626. $mergedItem['voice_audio_url'] = $audioUrl;
  8627. }
  8628. // 不继承 URL、task_id 和 task_status(重置状态)
  8629. $merged[] = $mergedItem;
  8630. }
  8631. } else {
  8632. // 新增项,保留生成项的所有字段
  8633. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  8634. }
  8635. }
  8636. return $merged ?: array_values($existingItems);
  8637. }
  8638. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  8639. {
  8640. $resetItem = [
  8641. $nameKey => trim((string)getProp($item, $nameKey)),
  8642. 'description' => trim((string)getProp($item, 'description')),
  8643. ];
  8644. // 保留指定的字段
  8645. foreach ($preserveFields as $field) {
  8646. $value = getProp($item, $field);
  8647. if (!empty($value)) {
  8648. $resetItem[$field] = $value;
  8649. }
  8650. }
  8651. return $resetItem;
  8652. }
  8653. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  8654. {
  8655. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  8656. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  8657. if ($existingKey !== $generatedKey) {
  8658. return true;
  8659. }
  8660. // 比较 description 是否变化
  8661. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  8662. return true;
  8663. }
  8664. // 比较 pic_prompt 是否变化
  8665. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  8666. }
  8667. private function normalizeEpisodeResourceKey($value): string
  8668. {
  8669. $value = trim((string)$value);
  8670. if ($value === '') {
  8671. return '';
  8672. }
  8673. return strtolower((string)preg_replace('/\s+/u', '', $value));
  8674. }
  8675. // 生成全局角色图片
  8676. private function batchSetGlobalRoleImg($data, $is_force=false) {
  8677. $anime_id = getProp($data, 'anime_id');
  8678. if (!$anime_id) Utils::throwError('1002:请选择对话');
  8679. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  8680. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  8681. $art_style = getProp($anime, 'art_style');
  8682. $update_flag = false;
  8683. foreach ($roles as &$role) {
  8684. $role_name = getProp($role, 'role');
  8685. if ($role_name == '旁白') continue;
  8686. // 优先使用 pic_prompt,如果没有则使用 description
  8687. $pic_prompt = getProp($role, 'pic_prompt');
  8688. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  8689. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  8690. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  8691. // 参考图地址
  8692. $ref_img_url = getProp($role, 'url');
  8693. if (!$is_force && $ref_img_url) continue;
  8694. $update_flag = true;
  8695. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  8696. try {
  8697. $params = [
  8698. 'prompt' => $description,
  8699. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  8700. 'ref_img_urls' => []
  8701. ];
  8702. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8703. $task_id = $task->id;
  8704. if (!$task_id) {
  8705. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  8706. }
  8707. $role['task_id'] = $task_id;
  8708. $role['task_status'] = 'processing';
  8709. } catch (\Exception $e) {
  8710. Utils::throwError("20003:" . $e->getMessage());
  8711. }
  8712. }
  8713. if (!$update_flag) return true;
  8714. // 保存角色信息
  8715. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  8716. 'roles' => json_encode($roles, 256),
  8717. 'generate_status' => '执行中',
  8718. 'generate_at' => date('Y-m-d H:i:s'),
  8719. 'updated_at' => date('Y-m-d H:i:s')
  8720. ]);
  8721. if (!$boolen) {
  8722. Utils::throwError('20003:保存角色信息失败');
  8723. }
  8724. return $boolen;
  8725. }
  8726. // 生成全局场景图片
  8727. private function batchSetGlobalSceneImg($data, $is_force=false) {
  8728. $anime_id = getProp($data, 'anime_id');
  8729. if (!$anime_id) Utils::throwError('1002:请选择对话');
  8730. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  8731. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  8732. $art_style = getProp($anime, 'art_style');
  8733. $update_flag = false;
  8734. foreach ($scenes as &$scene) {
  8735. $scene_name = getProp($scene, 'scene');
  8736. // 优先使用 pic_prompt,如果没有则使用 description
  8737. $pic_prompt = getProp($scene, 'pic_prompt');
  8738. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  8739. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  8740. // 参考图地址
  8741. $ref_img_url = getProp($scene, 'url');
  8742. if (!$is_force && $ref_img_url) continue;
  8743. $update_flag = true;
  8744. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  8745. try {
  8746. $params = [
  8747. 'prompt' => $description,
  8748. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  8749. 'ref_img_urls' => []
  8750. ];
  8751. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8752. $task_id = $task->id;
  8753. if (!$task_id) {
  8754. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  8755. }
  8756. $scene['task_id'] = $task_id;
  8757. $scene['task_status'] = 'processing';
  8758. } catch (\Exception $e) {
  8759. Utils::throwError("20003:" . $e->getMessage());
  8760. }
  8761. }
  8762. if (!$update_flag) return true;
  8763. // 保存角色信息
  8764. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  8765. 'scenes' => json_encode($scenes, 256),
  8766. 'generate_status' => '执行中',
  8767. 'generate_at' => date('Y-m-d H:i:s'),
  8768. 'updated_at' => date('Y-m-d H:i:s')
  8769. ]);
  8770. if (!$boolen) {
  8771. Utils::throwError('20003:保存角色信息失败');
  8772. }
  8773. return $boolen;
  8774. }
  8775. // 生成分镜主体和场景图片
  8776. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $ref_products=[], $art_style_type='', $is_force=false) {
  8777. $character_prefix = '';
  8778. $scene_prefix = '';
  8779. if ($art_style_type) {
  8780. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  8781. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  8782. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  8783. }
  8784. $update_flag = false;
  8785. // 获取上一集的roles和scenes数据
  8786. $prev_roles = [];
  8787. $prev_scenes = [];
  8788. if ($episode_number > 1) {
  8789. $prev_episode = DB::table('mp_anime_episodes')
  8790. ->where('anime_id', $anime_id)
  8791. ->where('episode_number', $episode_number - 1)
  8792. ->where('is_default', 1)
  8793. ->first();
  8794. if ($prev_episode) {
  8795. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  8796. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  8797. dLog('deepseek')->info("获取上一集数据成功", [
  8798. 'anime_id' => $anime_id,
  8799. 'prev_episode_number' => $episode_number - 1,
  8800. 'prev_roles_count' => count($prev_roles),
  8801. 'prev_scenes_count' => count($prev_scenes)
  8802. ]);
  8803. }
  8804. }
  8805. // 处理角色图片生成
  8806. foreach ($roles as &$role) {
  8807. $role_name = getProp($role, 'role');
  8808. if ($role_name == '旁白') continue;
  8809. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  8810. if (isset($ref_products[$role_name])) {
  8811. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  8812. if ($role['url']) continue;
  8813. }
  8814. $role_description = getProp($role, 'description');
  8815. $role_pic_prompt = getProp($role, 'pic_prompt');
  8816. $role_url = getProp($role, 'url');
  8817. // 检查是否可以从上一集继承
  8818. $inherited = false;
  8819. if (!$is_force && !empty($prev_roles)) {
  8820. foreach ($prev_roles as $prev_role) {
  8821. $prev_role_name = getProp($prev_role, 'role');
  8822. $prev_description = getProp($prev_role, 'description');
  8823. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  8824. $prev_url = getProp($prev_role, 'url');
  8825. $prev_task_id = getProp($prev_role, 'task_id');
  8826. $prev_task_status = getProp($prev_role, 'task_status');
  8827. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  8828. if ($role_name == $prev_role_name
  8829. && $role_description == $prev_description
  8830. && $role_pic_prompt == $prev_pic_prompt
  8831. && !empty($prev_url)) {
  8832. $role['task_id'] = $prev_task_id;
  8833. $role['task_status'] = $prev_task_status;
  8834. $role['url'] = $prev_url;
  8835. $inherited = true;
  8836. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  8837. 'anime_id' => $anime_id,
  8838. 'episode_number' => $episode_number,
  8839. 'task_id' => $prev_task_id,
  8840. 'url' => $prev_url
  8841. ]);
  8842. break;
  8843. }
  8844. }
  8845. }
  8846. // 如果已继承或已有url,跳过生成
  8847. if ($inherited || (!$is_force && $role_url)) {
  8848. continue;
  8849. }
  8850. // 优先使用 pic_prompt,如果没有则使用 description
  8851. $pic_prompt = getProp($role, 'pic_prompt');
  8852. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  8853. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  8854. $update_flag = true;
  8855. // 调用AIImageGenerationService的生成图片任务接口
  8856. try {
  8857. $params = [
  8858. 'prompt' => $description,
  8859. 'ref_img_urls' => []
  8860. ];
  8861. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8862. $task_id = $task->id;
  8863. if (!$task_id) {
  8864. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  8865. continue; // 不中断,继续处理其他角色
  8866. }
  8867. $role['task_id'] = $task_id;
  8868. $role['task_status'] = 'processing';
  8869. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  8870. 'anime_id' => $anime_id,
  8871. 'episode_number' => $episode_number,
  8872. 'task_id' => $task_id
  8873. ]);
  8874. } catch (\Exception $e) {
  8875. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  8876. // 不抛出异常,继续处理其他角色
  8877. }
  8878. }
  8879. // 处理场景图片生成
  8880. foreach ($scenes as &$scene) {
  8881. $scene_name = getProp($scene, 'scene');
  8882. $scene_description = getProp($scene, 'description');
  8883. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  8884. $scene_url = getProp($scene, 'url');
  8885. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  8886. if (isset($ref_products[$scene_name])) {
  8887. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  8888. if ($scene['url']) continue;
  8889. }
  8890. // 检查是否可以从上一集继承
  8891. $inherited = false;
  8892. if (!$is_force && !empty($prev_scenes)) {
  8893. foreach ($prev_scenes as $prev_scene) {
  8894. $prev_scene_name = getProp($prev_scene, 'scene');
  8895. $prev_description = getProp($prev_scene, 'description');
  8896. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  8897. $prev_url = getProp($prev_scene, 'url');
  8898. $prev_task_id = getProp($prev_scene, 'task_id');
  8899. $prev_task_status = getProp($prev_scene, 'task_status');
  8900. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  8901. if ($scene_name == $prev_scene_name
  8902. && $scene_description == $prev_description
  8903. && $scene_pic_prompt == $prev_pic_prompt
  8904. && !empty($prev_url)) {
  8905. $scene['task_id'] = $prev_task_id;
  8906. $scene['task_status'] = $prev_task_status;
  8907. $scene['url'] = $prev_url;
  8908. $inherited = true;
  8909. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  8910. 'anime_id' => $anime_id,
  8911. 'episode_number' => $episode_number,
  8912. 'task_id' => $prev_task_id,
  8913. 'url' => $prev_url
  8914. ]);
  8915. break;
  8916. }
  8917. }
  8918. }
  8919. // 如果已继承或已有url,跳过生成
  8920. if ($inherited || (!$is_force && $scene_url)) {
  8921. continue;
  8922. }
  8923. // 优先使用 pic_prompt,如果没有则使用 description
  8924. $pic_prompt = getProp($scene, 'pic_prompt');
  8925. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  8926. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  8927. $update_flag = true;
  8928. // 调用AIImageGenerationService的生成图片任务接口
  8929. try {
  8930. $params = [
  8931. 'prompt' => $description,
  8932. 'ref_img_urls' => []
  8933. ];
  8934. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  8935. $task_id = $task->id;
  8936. if (!$task_id) {
  8937. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  8938. continue; // 不中断,继续处理其他场景
  8939. }
  8940. $scene['task_id'] = $task_id;
  8941. $scene['task_status'] = 'processing';
  8942. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  8943. 'anime_id' => $anime_id,
  8944. 'episode_number' => $episode_number,
  8945. 'task_id' => $task_id
  8946. ]);
  8947. } catch (\Exception $e) {
  8948. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  8949. // 不抛出异常,继续处理其他场景
  8950. }
  8951. }
  8952. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes];
  8953. // 将处理完毕的roles和scenes与全局(mp_animes)数据对比并合并
  8954. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes);
  8955. // // 保存剧集的角色和场景信息
  8956. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  8957. // 'roles' => json_encode($roles, 256),
  8958. // 'scenes' => json_encode($scenes, 256),
  8959. // 'generate_status' => '执行中',
  8960. // 'generate_at' => date('Y-m-d H:i:s'),
  8961. // 'updated_at' => date('Y-m-d H:i:s')
  8962. // ]);
  8963. // if (!$boolen) {
  8964. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  8965. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  8966. // }
  8967. dLog('deepseek')->info('剧集角色和场景图片任务创建完成', [
  8968. // 'episode_id' => $episode_id,
  8969. 'roles_count' => count($roles),
  8970. 'scenes_count' => count($scenes)
  8971. ]);
  8972. return ['roles' => $roles, 'scenes' => $scenes];
  8973. }
  8974. /**
  8975. * 将剧集的roles和scenes同步到全局(mp_animes)
  8976. * 如果全局中不存在相同的role/scene(role、description、pic_prompt三项一致),则添加到全局
  8977. *
  8978. * @param int $anime_id 动漫对话ID
  8979. * @param array $episode_roles 剧集角色数据
  8980. * @param array $episode_scenes 剧集场景数据
  8981. * @return bool
  8982. */
  8983. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes) {
  8984. // 获取全局数据
  8985. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  8986. if (!$anime) {
  8987. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  8988. return false;
  8989. }
  8990. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  8991. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  8992. $roles_added = false;
  8993. $roles_updated = false;
  8994. $scenes_added = false;
  8995. // 处理角色同步
  8996. foreach ($episode_roles as $episode_role) {
  8997. $episode_role_name = getProp($episode_role, 'role');
  8998. $episode_description = getProp($episode_role, 'description');
  8999. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  9000. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  9001. // 跳过旁白
  9002. if ($episode_role_name == '旁白') {
  9003. continue;
  9004. }
  9005. // 检查全局中是否已存在相同的角色
  9006. $exists = false;
  9007. $global_role_index = -1;
  9008. foreach ($global_roles as $index => $global_role) {
  9009. $global_role_name = getProp($global_role, 'role');
  9010. $global_description = getProp($global_role, 'description');
  9011. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  9012. // 如果role、description、pic_prompt三项都一致,则认为已存在
  9013. if ($episode_role_name == $global_role_name
  9014. && $episode_description == $global_description
  9015. && $episode_pic_prompt == $global_pic_prompt) {
  9016. $exists = true;
  9017. $global_role_index = $index;
  9018. break;
  9019. }
  9020. }
  9021. // 如果不存在,则添加到全局
  9022. if (!$exists) {
  9023. $global_roles[] = $episode_role;
  9024. $roles_added = true;
  9025. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  9026. 'anime_id' => $anime_id,
  9027. 'role' => $episode_role_name
  9028. ]);
  9029. } else {
  9030. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  9031. if (!empty($episode_voice_prompt)) {
  9032. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  9033. // 如果全局没有voice_prompt或与剧集不一致,则更新
  9034. if ($global_voice_prompt !== $episode_voice_prompt) {
  9035. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  9036. $roles_updated = true;
  9037. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  9038. 'anime_id' => $anime_id,
  9039. 'role' => $episode_role_name,
  9040. 'voice_prompt' => $episode_voice_prompt
  9041. ]);
  9042. }
  9043. }
  9044. }
  9045. }
  9046. // 处理场景同步
  9047. foreach ($episode_scenes as $episode_scene) {
  9048. $episode_scene_name = getProp($episode_scene, 'scene');
  9049. $episode_description = getProp($episode_scene, 'description');
  9050. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  9051. // 检查全局中是否已存在相同的场景
  9052. $exists = false;
  9053. foreach ($global_scenes as $global_scene) {
  9054. $global_scene_name = getProp($global_scene, 'scene');
  9055. $global_description = getProp($global_scene, 'description');
  9056. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  9057. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  9058. if ($episode_scene_name == $global_scene_name
  9059. && $episode_description == $global_description
  9060. && $episode_pic_prompt == $global_pic_prompt) {
  9061. $exists = true;
  9062. break;
  9063. }
  9064. }
  9065. // 如果不存在,则添加到全局
  9066. if (!$exists) {
  9067. $global_scenes[] = $episode_scene;
  9068. $scenes_added = true;
  9069. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  9070. 'anime_id' => $anime_id,
  9071. 'scene' => $episode_scene_name
  9072. ]);
  9073. }
  9074. }
  9075. // 如果有新增或更新,则更新全局数据
  9076. if ($roles_added || $roles_updated || $scenes_added) {
  9077. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  9078. if ($roles_added || $roles_updated) {
  9079. $update_data['roles'] = json_encode($global_roles, 256);
  9080. }
  9081. if ($scenes_added) {
  9082. $update_data['scenes'] = json_encode($global_scenes, 256);
  9083. }
  9084. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  9085. dLog('deepseek')->info('剧集数据同步到全局完成', [
  9086. 'anime_id' => $anime_id,
  9087. 'roles_added' => $roles_added,
  9088. 'roles_updated' => $roles_updated,
  9089. 'scenes_added' => $scenes_added,
  9090. 'global_roles_count' => count($global_roles),
  9091. 'global_scenes_count' => count($global_scenes)
  9092. ]);
  9093. }
  9094. return true;
  9095. }
  9096. /**
  9097. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  9098. *
  9099. * @param int $anime_id 动漫对话ID
  9100. * @param int $episode_id 分集ID
  9101. * @return bool
  9102. */
  9103. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  9104. // 获取全局角色和场景数据
  9105. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9106. if (!$anime) {
  9107. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  9108. return false;
  9109. }
  9110. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9111. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  9112. // 获取指定的分集
  9113. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  9114. if (!$episode) {
  9115. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  9116. return false;
  9117. }
  9118. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9119. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9120. $roles_updated = false;
  9121. $scenes_updated = false;
  9122. // 继承角色的task_id、task_status和url
  9123. foreach ($episode_roles as &$episode_role) {
  9124. $episode_role_name = getProp($episode_role, 'role');
  9125. $episode_description = getProp($episode_role, 'description');
  9126. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  9127. $episode_url = getProp($episode_role, 'url');
  9128. // 跳过旁白角色
  9129. if ($episode_role_name == '旁白') {
  9130. continue;
  9131. }
  9132. // 如果剧集中已有URL,跳过
  9133. if (!empty($episode_url)) {
  9134. continue;
  9135. }
  9136. // 遍历全局角色数据,查找匹配的角色
  9137. foreach ($global_roles as $global_role) {
  9138. $global_role_name = getProp($global_role, 'role');
  9139. $global_description = getProp($global_role, 'description');
  9140. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  9141. $global_url = getProp($global_role, 'url');
  9142. $global_task_id = getProp($global_role, 'task_id');
  9143. $global_task_status = getProp($global_role, 'task_status');
  9144. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  9145. if ($episode_role_name == $global_role_name
  9146. && $episode_description == $global_description
  9147. && $episode_pic_prompt == $global_pic_prompt) {
  9148. // 继承 task_id、task_status 和 url
  9149. if (!empty($global_task_id)) {
  9150. $episode_role['task_id'] = $global_task_id;
  9151. $episode_role['task_status'] = $global_task_status;
  9152. $roles_updated = true;
  9153. dLog('deepseek')->info('剧集角色继承全局task_id', [
  9154. 'episode_id' => $episode_id,
  9155. 'role' => $episode_role_name,
  9156. 'task_id' => $global_task_id,
  9157. 'task_status' => $global_task_status
  9158. ]);
  9159. }
  9160. if (!empty($global_url)) {
  9161. $episode_role['url'] = $global_url;
  9162. $roles_updated = true;
  9163. dLog('deepseek')->info('剧集角色继承全局url', [
  9164. 'episode_id' => $episode_id,
  9165. 'role' => $episode_role_name,
  9166. 'url' => $global_url
  9167. ]);
  9168. }
  9169. break;
  9170. }
  9171. }
  9172. }
  9173. // 继承场景的task_id、task_status和url
  9174. foreach ($episode_scenes as &$episode_scene) {
  9175. $episode_scene_name = getProp($episode_scene, 'scene');
  9176. $episode_description = getProp($episode_scene, 'description');
  9177. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  9178. $episode_url = getProp($episode_scene, 'url');
  9179. // 如果剧集中已有URL,跳过
  9180. if (!empty($episode_url)) {
  9181. continue;
  9182. }
  9183. // 遍历全局场景数据,查找匹配的场景
  9184. foreach ($global_scenes as $global_scene) {
  9185. $global_scene_name = getProp($global_scene, 'scene');
  9186. $global_description = getProp($global_scene, 'description');
  9187. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  9188. $global_url = getProp($global_scene, 'url');
  9189. $global_task_id = getProp($global_scene, 'task_id');
  9190. $global_task_status = getProp($global_scene, 'task_status');
  9191. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  9192. if ($episode_scene_name == $global_scene_name
  9193. && $episode_description == $global_description
  9194. && $episode_pic_prompt == $global_pic_prompt) {
  9195. // 继承 task_id、task_status 和 url
  9196. if (!empty($global_task_id)) {
  9197. $episode_scene['task_id'] = $global_task_id;
  9198. $episode_scene['task_status'] = $global_task_status;
  9199. $scenes_updated = true;
  9200. dLog('deepseek')->info('剧集场景继承全局task_id', [
  9201. 'episode_id' => $episode_id,
  9202. 'scene' => $episode_scene_name,
  9203. 'task_id' => $global_task_id,
  9204. 'task_status' => $global_task_status
  9205. ]);
  9206. }
  9207. if (!empty($global_url)) {
  9208. $episode_scene['url'] = $global_url;
  9209. $scenes_updated = true;
  9210. dLog('deepseek')->info('剧集场景继承全局url', [
  9211. 'episode_id' => $episode_id,
  9212. 'scene' => $episode_scene_name,
  9213. 'url' => $global_url
  9214. ]);
  9215. }
  9216. break;
  9217. }
  9218. }
  9219. }
  9220. // 如果有更新,则保存到数据库
  9221. if ($roles_updated || $scenes_updated) {
  9222. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  9223. if ($roles_updated) {
  9224. $update_data['roles'] = json_encode($episode_roles, 256);
  9225. }
  9226. if ($scenes_updated) {
  9227. $update_data['scenes'] = json_encode($episode_scenes, 256);
  9228. }
  9229. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  9230. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  9231. 'episode_id' => $episode_id,
  9232. 'roles_updated' => $roles_updated,
  9233. 'scenes_updated' => $scenes_updated
  9234. ]);
  9235. }
  9236. return true;
  9237. }
  9238. public function chatChangeImg($data) {
  9239. $segment = getProp($data, 'segment');
  9240. $segment_content = getProp($segment, 'segment_content');
  9241. $prompt = getProp($data, 'prompt');
  9242. $ref_img = getProp($data, 'ref_img');
  9243. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  9244. // 处理文本模型
  9245. $model = getProp($data, 'model');
  9246. if (!$model) {
  9247. // 用户没有输入,从anime表获取
  9248. $segment_id = getProp($segment, 'segment_id');
  9249. if ($segment_id) {
  9250. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  9251. if ($episode_id) {
  9252. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  9253. if ($anime_id) {
  9254. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  9255. }
  9256. }
  9257. }
  9258. if (!$model) {
  9259. // anime表也没有,使用默认值
  9260. $model = 'doubao-seed-2-0-mini-260215';
  9261. }
  9262. }
  9263. // 验证模型是否在可用模型表中
  9264. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  9265. $model = 'doubao-seed-2-0-mini-260215';
  9266. }
  9267. $messages[] =
  9268. [
  9269. 'role' => 'user',
  9270. 'content' => $question
  9271. ];
  9272. $post_data = [
  9273. 'model' => $model,
  9274. 'messages' => $messages,
  9275. // 'max_tokens' => 8192,
  9276. 'temperature' => 0.7,
  9277. 'frequency_penalty' => 0,
  9278. 'presence_penalty' => 0,
  9279. 'response_format' => ['type' => 'text'],
  9280. 'stream' => false // 是否启用流式输出
  9281. ];
  9282. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9283. // DeepSeek 官方模型使用 DeepSeek API
  9284. $chatResult = $this->chatOnly($post_data);
  9285. } else if (in_array($model, $this->gpt_text_models)) {
  9286. // GPT-5.4 模型使用 TokenRouter API
  9287. $chatResult = $this->gpt54ChatOnly($post_data);
  9288. } else {
  9289. // 其他模型使用火山引擎API
  9290. $chatResult = $this->volcEngineChatCompletion($post_data);
  9291. }
  9292. if (is_array($chatResult)) {
  9293. extract($chatResult);
  9294. }else {
  9295. Utils::throwError('20003: 接口调用失败!');
  9296. }
  9297. return [
  9298. 'type' => 'done',
  9299. // 'episode' => $episode,
  9300. 'answer' => $fullContent,
  9301. 'reasoning' => $fullReasoningContent,
  9302. 'usage' => $usage
  9303. ];
  9304. }
  9305. // 仅调用deepseek对话接口
  9306. private function chatOnly($post_data) {
  9307. $post_data['max_tokens'] = 300000;
  9308. $client = new Client(['timeout' => 1800, 'verify' => false]);
  9309. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  9310. $response = $result->getBody()->getContents();
  9311. $response_arr = json_decode($response, true);
  9312. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  9313. $fullContent = '';
  9314. $fullReasoningContent = [];
  9315. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  9316. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  9317. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  9318. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  9319. }
  9320. return [
  9321. 'fullContent' => $fullContent,
  9322. 'fullReasoningContent' => $fullReasoningContent,
  9323. 'usage' => $usage
  9324. ];
  9325. }
  9326. // 仅调用 GPT-5.4 对话接口(非流式)
  9327. private function gpt54ChatOnly($post_data) {
  9328. $apiKey = env('GPT_54_API_KEY');
  9329. if (empty($apiKey)) {
  9330. Utils::throwError('20003:GPT-5.4 API Key未配置');
  9331. }
  9332. $client = new Client(['timeout' => 1800, 'verify' => false]);
  9333. $headers = [
  9334. 'Authorization' => 'Bearer ' . $apiKey,
  9335. 'Content-Type' => 'application/json'
  9336. ];
  9337. // 移除 thinking 参数,GPT-5.4 不支持
  9338. if (isset($post_data['thinking'])) {
  9339. unset($post_data['thinking']);
  9340. }
  9341. if (isset($post_data['reasoning_effort'])) {
  9342. unset($post_data['reasoning_effort']);
  9343. }
  9344. $post_data['max_completion_tokens'] = 100000;
  9345. // 确保 stream 为 false
  9346. $post_data['stream'] = false;
  9347. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  9348. $result = $client->post('https://api.nonelinear.com/v1/chat/completions', [
  9349. 'json' => $post_data,
  9350. 'headers' => $headers
  9351. ]);
  9352. $response = $result->getBody()->getContents();
  9353. $response_arr = json_decode($response, true);
  9354. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  9355. $fullContent = '';
  9356. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  9357. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  9358. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  9359. }
  9360. return [
  9361. 'fullContent' => $fullContent,
  9362. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  9363. 'usage' => $usage
  9364. ];
  9365. }
  9366. private function splitContent($content) {
  9367. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  9368. $chapters = [];
  9369. // 匹配章节标题格式:
  9370. // 1. 标题独占一行
  9371. // 2. 格式支持:
  9372. // - **第一集**
  9373. // - 第一集:
  9374. // - ###第1章 重生
  9375. // - ##第2章 相救
  9376. // - 第三章 共处一室
  9377. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  9378. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  9379. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  9380. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  9381. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  9382. // 先用正则找出所有章节标题的位置
  9383. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  9384. $titleCount = count($matches[0]);
  9385. for ($i = 0; $i < $titleCount; $i++) {
  9386. // 获取当前章节标题
  9387. $titleLine = trim($matches[0][$i][0]);
  9388. // 去除标题开头的特殊符号
  9389. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  9390. // 去除标题结尾的冒号
  9391. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  9392. $cleanTitle = trim($cleanTitle);
  9393. // 获取当前标题的结束位置
  9394. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  9395. // 获取下一个章节标题的开始位置(如果存在)
  9396. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  9397. // 提取章节内容(从标题结束到下一个标题开始)
  9398. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  9399. // 清理内容:去除前后空白和分隔线
  9400. $chapterContent = trim($chapterContent);
  9401. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  9402. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  9403. if (!empty($cleanTitle) && !empty($chapterContent)) {
  9404. $chapters[] = [
  9405. 'title' => $cleanTitle,
  9406. 'content' => $chapterContent
  9407. ];
  9408. }
  9409. }
  9410. } else {
  9411. // 如果没有匹配到章节,返回整个内容
  9412. $chapters[] = [
  9413. 'title' => '',
  9414. 'content' => $content
  9415. ];
  9416. }
  9417. return $chapters;
  9418. }
  9419. public function getContentByBid($bid) {
  9420. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  9421. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  9422. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  9423. $content = '';
  9424. foreach ($chapters as $chapter) {
  9425. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  9426. }
  9427. return $content;
  9428. }
  9429. public function getContentByScriptId($script_id) {
  9430. $content = '';
  9431. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  9432. if ($contents) {
  9433. $content = implode(PHP_EOL, $contents);
  9434. }else {
  9435. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  9436. }
  9437. return $content;
  9438. }
  9439. /**
  9440. * 根据文件类型提取文本内容
  9441. *
  9442. * @param mixed $file 文件对象或文件路径
  9443. * @return string
  9444. */
  9445. public function extractFileContent($file) {
  9446. // 获取文件路径和扩展名
  9447. if (is_string($file)) {
  9448. $filePath = $file;
  9449. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  9450. } else {
  9451. // Laravel UploadedFile 对象
  9452. $filePath = $file->getRealPath();
  9453. $extension = strtolower($file->getClientOriginalExtension());
  9454. }
  9455. $content = '';
  9456. switch ($extension) {
  9457. case 'txt':
  9458. $content = $this->extractTxtContent($filePath);
  9459. break;
  9460. case 'pdf':
  9461. $content = $this->extractPdfContent($filePath);
  9462. break;
  9463. case 'doc':
  9464. case 'docx':
  9465. $content = $this->extractWordContent($filePath);
  9466. break;
  9467. // case 'jpg':
  9468. // case 'jpeg':
  9469. // case 'png':
  9470. // case 'gif':
  9471. // case 'bmp':
  9472. // case 'webp':
  9473. // $content = $this->extractImageContent($filePath);
  9474. // break;
  9475. default:
  9476. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  9477. }
  9478. return $content;
  9479. }
  9480. /**
  9481. * 提取 TXT 文件内容
  9482. */
  9483. private function extractTxtContent($filePath) {
  9484. if (!file_exists($filePath)) {
  9485. Utils::throwError('20003:文件不存在');
  9486. }
  9487. $content = file_get_contents($filePath);
  9488. // 尝试检测并转换编码
  9489. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  9490. if ($encoding && $encoding !== 'UTF-8') {
  9491. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  9492. }
  9493. return trim($content);
  9494. }
  9495. /**
  9496. * 提取 PDF 文件内容
  9497. */
  9498. private function extractPdfContent($filePath) {
  9499. if (!file_exists($filePath)) {
  9500. Utils::throwError('20003:文件不存在');
  9501. }
  9502. try {
  9503. $parser = new PdfParser();
  9504. $pdf = $parser->parseFile($filePath);
  9505. $content = $pdf->getText();
  9506. return trim($content);
  9507. } catch (\Exception $e) {
  9508. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  9509. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  9510. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  9511. }
  9512. }
  9513. /**
  9514. * 提取 Word 文件内容(支持 doc 和 docx)
  9515. */
  9516. private function extractWordContent($filePath) {
  9517. if (!file_exists($filePath)) {
  9518. Utils::throwError('20003:文件不存在');
  9519. }
  9520. try {
  9521. $phpWord = WordIOFactory::load($filePath);
  9522. $content = '';
  9523. foreach ($phpWord->getSections() as $section) {
  9524. foreach ($section->getElements() as $element) {
  9525. $content .= $this->extractWordElementText($element);
  9526. }
  9527. }
  9528. return trim($content);
  9529. } catch (\Exception $e) {
  9530. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  9531. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  9532. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  9533. }
  9534. }
  9535. /**
  9536. * 递归提取 Word 元素中的文本
  9537. */
  9538. private function extractWordElementText($element) {
  9539. $text = '';
  9540. if (method_exists($element, 'getText')) {
  9541. $text .= $element->getText() . "\n";
  9542. } elseif (method_exists($element, 'getElements')) {
  9543. foreach ($element->getElements() as $childElement) {
  9544. $text .= $this->extractWordElementText($childElement);
  9545. }
  9546. }
  9547. return $text;
  9548. }
  9549. /**
  9550. * 提取图片内容(使用火山引擎 OCR)
  9551. */
  9552. private function extractImageContent($filePath) {
  9553. if (!file_exists($filePath)) {
  9554. Utils::throwError('20003:文件不存在');
  9555. }
  9556. try {
  9557. // 读取图片并转换为 base64
  9558. $imageData = file_get_contents($filePath);
  9559. $base64Image = base64_encode($imageData);
  9560. // 调用火山引擎 OCR 服务
  9561. $content = $this->callVolcEngineOCR($base64Image);
  9562. return trim($content);
  9563. } catch (\Exception $e) {
  9564. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  9565. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  9566. Utils::throwError('20003:图片识别失败');
  9567. }
  9568. }
  9569. /**
  9570. * 调用火山引擎 OCR 服务识别图片文字
  9571. *
  9572. * @param string $base64Image base64 编码的图片数据
  9573. * @return string 识别的文字内容
  9574. */
  9575. private function callVolcEngineOCR($base64Image) {
  9576. $method = 'POST';
  9577. $service = 'cv';
  9578. $host = 'visual.volcengineapi.com';
  9579. $region = env('VOLC_REGION', 'cn-north-1');
  9580. $access_key = env('VOLC_AK');
  9581. $secret_key = env('VOLC_SK');
  9582. $action = 'OCRNormal';
  9583. $version = '2020-08-26';
  9584. if (!$access_key || !$secret_key) {
  9585. Utils::throwError('20003:请配置火山引擎 AK/SK');
  9586. }
  9587. // 请求体
  9588. $body = json_encode([
  9589. 'image_base64' => $base64Image
  9590. ]);
  9591. // 生成签名
  9592. $headers = $this->getVolcEngineSignHeaders(
  9593. $method, $service, $host, $region,
  9594. "Action={$action}&Version={$version}",
  9595. $access_key, $secret_key, $body
  9596. );
  9597. $client = new Client(['timeout' => 1800, 'verify' => false]);
  9598. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  9599. 'headers' => $headers,
  9600. 'body' => $body
  9601. ]);
  9602. $response_arr = json_decode($response->getBody()->getContents(), true);
  9603. // 提取识别的文字
  9604. $textLines = [];
  9605. if (isset($response_arr['data']['line_texts'])) {
  9606. $textLines = $response_arr['data']['line_texts'];
  9607. } elseif (isset($response_arr['data']['ocr_infos'])) {
  9608. foreach ($response_arr['data']['ocr_infos'] as $info) {
  9609. if (isset($info['text'])) {
  9610. $textLines[] = $info['text'];
  9611. }
  9612. }
  9613. }
  9614. if (empty($textLines)) {
  9615. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  9616. return '';
  9617. }
  9618. return implode("\n", $textLines);
  9619. }
  9620. /**
  9621. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  9622. */
  9623. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  9624. $contentType = 'application/json';
  9625. $accept = 'application/json';
  9626. // 获取当前UTC时间
  9627. $t = new DateTime('now', new DateTimeZone('UTC'));
  9628. $xDate = $t->format('Ymd\THis\Z');
  9629. $dateStamp = $t->format('Ymd');
  9630. // 计算 body 的 sha256 哈希
  9631. $payloadHash = hash('sha256', $body);
  9632. // 1. 拼接规范请求串
  9633. $canonicalUri = '/';
  9634. $canonicalQueryString = $queryString;
  9635. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  9636. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  9637. $canonicalRequest = implode("\n", [
  9638. $method,
  9639. $canonicalUri,
  9640. $canonicalQueryString,
  9641. $canonicalHeaders,
  9642. $signedHeaders,
  9643. $payloadHash
  9644. ]);
  9645. // 2. 拼接待签名字符串
  9646. $algorithm = 'HMAC-SHA256';
  9647. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  9648. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  9649. $stringToSign = implode("\n", [
  9650. $algorithm,
  9651. $xDate,
  9652. $credentialScope,
  9653. $hashedCanonicalRequest
  9654. ]);
  9655. // 3. 计算签名
  9656. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  9657. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  9658. // 4. 添加签名到请求头
  9659. $authorizationHeader = sprintf(
  9660. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  9661. $algorithm,
  9662. $access_key,
  9663. $credentialScope,
  9664. $signedHeaders,
  9665. $signature
  9666. );
  9667. return [
  9668. 'Accept' => $accept,
  9669. 'Content-Type' => $contentType,
  9670. 'Host' => $host,
  9671. 'X-Date' => $xDate,
  9672. 'X-Content-Sha256'=> $payloadHash,
  9673. 'Authorization' => $authorizationHeader
  9674. ];
  9675. }
  9676. public function generateScriptWords($cid, $model = 'r1') {
  9677. ini_set('max_execution_time', 0);
  9678. if (!$cid) Utils::throwError('20003: 请选择章节!');
  9679. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  9680. // 模型兼容性处理和思考模式设置
  9681. $thinkingMode = 'disabled';
  9682. $reasoningEffort = 'high';
  9683. if ($model == 'r1') {
  9684. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  9685. $thinkingMode = 'enabled';
  9686. } else {
  9687. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  9688. $thinkingMode = 'disabled';
  9689. }
  9690. $messages = [
  9691. [
  9692. 'role' => 'system',
  9693. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  9694. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  9695. 2.非对话部分请全部用旁白角色代替
  9696. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  9697. ],
  9698. [
  9699. 'role' => 'user',
  9700. 'content' => $content
  9701. ]
  9702. ];
  9703. $post_data = [
  9704. 'model' => $model,
  9705. 'messages' => $messages,
  9706. // 'max_tokens' => 8192,
  9707. 'temperature' => 1,
  9708. 'frequency_penalty' => 0,
  9709. 'presence_penalty' => 0,
  9710. 'thinking' => ['type' => $thinkingMode],
  9711. 'response_format' => [
  9712. 'type' => 'text'
  9713. ],
  9714. 'stream' => false
  9715. ];
  9716. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  9717. // 根据模型类型选择调用方法
  9718. $fullContent = '';
  9719. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  9720. // DeepSeek 官方模型使用 DeepSeek API
  9721. $chatResult = $this->chatOnly($post_data);
  9722. } else if (in_array($model, $this->gpt_text_models)) {
  9723. // GPT-5.4 模型使用 TokenRouter API
  9724. $chatResult = $this->gpt54ChatOnly($post_data);
  9725. } else {
  9726. // 其他模型使用火山引擎API
  9727. $chatResult = $this->volcEngineChatCompletion($post_data);
  9728. }
  9729. if (is_array($chatResult)) {
  9730. $fullContent = $chatResult['fullContent'];
  9731. }
  9732. return $fullContent;
  9733. }
  9734. /**
  9735. * 智能化解析集数信息
  9736. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  9737. *
  9738. * @param string $prompt 用户输入的提示词
  9739. * @return int|null 解析出的集数,如果没有找到则返回null
  9740. */
  9741. private function extractEpisodeNumber($prompt)
  9742. {
  9743. if (empty($prompt)) {
  9744. return null;
  9745. }
  9746. // 定义各种可能的表达模式
  9747. $patterns = [
  9748. // 基本模式:改成N集、调整成N集、修改成N集
  9749. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  9750. // 扩展模式:分成N集、拆分成N集、分割成N集
  9751. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  9752. // 数量模式:N集、共N集、总共N集
  9753. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  9754. // 制作模式:制作N集、生成N集、创建N集
  9755. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  9756. // 计划模式:计划N集、预计N集、打算N集
  9757. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  9758. // 需要模式:需要N集、要N集
  9759. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  9760. // 中文数字模式:改成三集、调整成五集等
  9761. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  9762. // 英文数字模式
  9763. '/(?: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',
  9764. ];
  9765. // 中文数字转阿拉伯数字的映射
  9766. $chineseNumbers = [
  9767. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  9768. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  9769. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  9770. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  9771. ];
  9772. // 逐个尝试匹配模式
  9773. foreach ($patterns as $pattern) {
  9774. if (preg_match($pattern, $prompt, $matches)) {
  9775. $number = trim($matches[1]);
  9776. // 如果是中文数字,转换为阿拉伯数字
  9777. if (isset($chineseNumbers[$number])) {
  9778. return $chineseNumbers[$number];
  9779. }
  9780. // 如果是阿拉伯数字,直接返回
  9781. if (is_numeric($number)) {
  9782. $episodeNum = intval($number);
  9783. // 合理性检查:集数应该在1-100之间
  9784. if ($episodeNum >= 1 && $episodeNum <= 100) {
  9785. return $episodeNum;
  9786. }
  9787. }
  9788. }
  9789. }
  9790. return null;
  9791. }
  9792. /**
  9793. * 调用火山引擎对话(Chat) API
  9794. *
  9795. * @param array $params 包含以下参数:
  9796. * - model: 模型ID(必填)
  9797. * - messages: 消息列表(必填)
  9798. * - stream: 是否流式输出(可选,默认false)
  9799. * - max_tokens: 最大输出token数(可选)
  9800. * - temperature: 采样温度(可选,默认1)
  9801. * - top_p: 核采样概率(可选,默认0.7)
  9802. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  9803. * - presence_penalty: 存在惩罚系数(可选,默认0)
  9804. * - stop: 停止词(可选)
  9805. * - tools: 工具列表(可选)
  9806. * @return array|Generator 非流式返回数组,流式返回生成器
  9807. */
  9808. public function volcEngineChatCompletion(array $params)
  9809. {
  9810. $apiKey = env('VOLC_AI_API_KEY');
  9811. if (empty($apiKey)) {
  9812. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  9813. }
  9814. // 构建请求参数
  9815. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  9816. $requestData = [
  9817. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  9818. 'messages' => $params['messages'] ?? [],
  9819. ];
  9820. if (!in_array($originalModel, $this->valid_text_models)) {
  9821. Utils::throwError('20003:该模型不支持!');
  9822. }
  9823. // 添加可选参数
  9824. if (isset($params['stream'])) {
  9825. $requestData['stream'] = $params['stream'];
  9826. }
  9827. if (isset($params['stream_options'])) {
  9828. $requestData['stream_options'] = $params['stream_options'];
  9829. }
  9830. if (isset($params['max_tokens'])) {
  9831. $requestData['max_tokens'] = $params['max_tokens'];
  9832. }else if (isset($params['max_completion_tokens'])) {
  9833. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  9834. }else {
  9835. $requestData['max_completion_tokens'] = 100000;
  9836. }
  9837. if (isset($params['temperature'])) {
  9838. $requestData['temperature'] = $params['temperature'];
  9839. }
  9840. if (isset($params['top_p'])) {
  9841. $requestData['top_p'] = $params['top_p'];
  9842. }
  9843. if (isset($params['frequency_penalty'])) {
  9844. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  9845. }
  9846. if (isset($params['presence_penalty'])) {
  9847. $requestData['presence_penalty'] = $params['presence_penalty'];
  9848. }
  9849. if (isset($params['stop'])) {
  9850. $requestData['stop'] = $params['stop'];
  9851. }
  9852. if (isset($params['tools'])) {
  9853. $requestData['tools'] = $params['tools'];
  9854. }
  9855. if (isset($params['tool_choice'])) {
  9856. $requestData['tool_choice'] = $params['tool_choice'];
  9857. }
  9858. if (isset($params['response_format'])) {
  9859. $requestData['response_format'] = $params['response_format'];
  9860. }
  9861. if (isset($params['thinking'])) {
  9862. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  9863. if (is_array($params['thinking'])) {
  9864. $requestData['thinking'] = $params['thinking'];
  9865. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  9866. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  9867. }
  9868. } else {
  9869. $requestData['thinking'] = ['type' => $params['thinking']];
  9870. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  9871. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  9872. }
  9873. }
  9874. } else {
  9875. $requestData['thinking'] = ['type' => 'disabled'];
  9876. }
  9877. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  9878. $client = new Client(['verify' => false, 'timeout' => 1800]);
  9879. try {
  9880. // 判断是否为流式输出
  9881. $isStream = isset($params['stream']) && $params['stream'] === true;
  9882. if ($isStream) {
  9883. // 流式输出
  9884. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  9885. } else {
  9886. // 非流式输出
  9887. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  9888. 'headers' => [
  9889. 'Authorization' => 'Bearer ' . $apiKey,
  9890. 'Content-Type' => 'application/json',
  9891. ],
  9892. 'json' => $requestData
  9893. ]);
  9894. $responseData = json_decode($response->getBody(), true);
  9895. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  9896. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  9897. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  9898. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  9899. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  9900. }
  9901. return [
  9902. 'fullContent' => $fullContent,
  9903. 'fullReasoningContent' => $fullReasoningContent,
  9904. 'usage' => $usage
  9905. ];
  9906. }
  9907. } catch (\Exception $e) {
  9908. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  9909. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  9910. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  9911. }
  9912. }
  9913. /**
  9914. * 火山引擎对话API流式输出
  9915. *
  9916. * @param Client $client HTTP客户端
  9917. * @param string $apiKey API密钥
  9918. * @param array $requestData 请求数据
  9919. * @return Generator
  9920. */
  9921. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  9922. {
  9923. try {
  9924. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  9925. 'headers' => [
  9926. 'Authorization' => 'Bearer ' . $apiKey,
  9927. 'Content-Type' => 'application/json',
  9928. ],
  9929. 'json' => $requestData,
  9930. 'stream' => true
  9931. ]);
  9932. $body = $response->getBody();
  9933. $buffer = '';
  9934. $fullContent = '';
  9935. $fullReasoningContent = '';
  9936. $usage = [];
  9937. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  9938. // 逐行读取流式响应
  9939. while (!$body->eof()) {
  9940. $chunk = $body->read(1024);
  9941. $buffer .= $chunk;
  9942. // 按行分割
  9943. $lines = explode("\n", $buffer);
  9944. $buffer = array_pop($lines);
  9945. foreach ($lines as $line) {
  9946. $line = trim($line);
  9947. if (empty($line)) {
  9948. continue;
  9949. }
  9950. // 检查是否是SSE数据行
  9951. if (strpos($line, 'data: ') !== 0) {
  9952. continue;
  9953. }
  9954. $data = substr($line, 6);
  9955. if ($data === '[DONE]') {
  9956. dLog('deepseek')->info('收到结束标记');
  9957. break 2;
  9958. }
  9959. try {
  9960. $json = json_decode($data, true);
  9961. if (json_last_error() !== JSON_ERROR_NONE) {
  9962. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  9963. continue;
  9964. }
  9965. if (isset($json['choices'][0]['delta'])) {
  9966. $delta = $json['choices'][0]['delta'];
  9967. // 处理思维链内容
  9968. if (isset($delta['reasoning_content'])) {
  9969. $fullReasoningContent .= $delta['reasoning_content'];
  9970. yield [
  9971. 'type' => 'reasoning',
  9972. 'content' => $delta['reasoning_content'],
  9973. 'full_reasoning' => $fullReasoningContent
  9974. ];
  9975. }
  9976. // 处理回答内容
  9977. if (isset($delta['content'])) {
  9978. $fullContent .= $delta['content'];
  9979. yield [
  9980. 'type' => 'content',
  9981. 'content' => $delta['content'],
  9982. ];
  9983. }
  9984. }
  9985. // 获取使用统计信息
  9986. if (isset($json['usage'])) {
  9987. $usage = $json['usage'];
  9988. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  9989. }
  9990. } catch (\Exception $e) {
  9991. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  9992. continue;
  9993. }
  9994. }
  9995. }
  9996. dLog('deepseek')->info('流式读取完成', [
  9997. 'content_length' => strlen($fullContent),
  9998. 'reasoning_length' => strlen($fullReasoningContent)
  9999. ]);
  10000. yield [
  10001. 'type' => 'done',
  10002. 'full_content' => $fullContent,
  10003. 'full_reasoning' => $fullReasoningContent,
  10004. 'usage' => $usage
  10005. ];
  10006. } catch (\Exception $e) {
  10007. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  10008. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  10009. throw $e;
  10010. }
  10011. }
  10012. /**
  10013. * 检查并创建图片生成任务
  10014. *
  10015. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  10016. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  10017. * @param string $nameKey 资源名称字段('role' 或 'scene')
  10018. * @param string $art_style 美术风格
  10019. * @return array 更新后的资源列表
  10020. */
  10021. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  10022. {
  10023. // 确保参数为数组
  10024. $merged_items = is_array($merged_items) ? $merged_items : [];
  10025. $global_items = is_array($global_items) ? $global_items : [];
  10026. // 构建全局资源映射表,用于快速查找
  10027. $global_map = [];
  10028. foreach ($global_items as $item) {
  10029. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  10030. if ($itemKey === '') {
  10031. continue;
  10032. }
  10033. $global_map[$itemKey] = $item;
  10034. }
  10035. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  10036. foreach ($merged_items as &$item) {
  10037. $item_name = getProp($item, $nameKey);
  10038. $item_description = getProp($item, 'description');
  10039. // $item_url = getProp($item, 'url');
  10040. // // 如果已有图片URL,跳过
  10041. // if (!empty($item_url)) {
  10042. // continue;
  10043. // }
  10044. // 如果是旁白角色,跳过
  10045. if ($nameKey === 'role' && $item_name === '旁白') {
  10046. continue;
  10047. }
  10048. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  10049. if ($itemKey === '') {
  10050. continue;
  10051. }
  10052. $need_create_task = false;
  10053. // 条件1:在全局资源中找不到匹配的名称
  10054. if (!isset($global_map[$itemKey])) {
  10055. $need_create_task = true;
  10056. } else {
  10057. // 条件2:名称匹配但描述或 pic_prompt 不一致
  10058. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  10059. $current_description = trim((string)$item_description);
  10060. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  10061. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  10062. // 如果 description 或 pic_prompt 有变化,需要重新生成
  10063. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  10064. $need_create_task = true;
  10065. }
  10066. }
  10067. // 如果需要创建任务,调用图片生成服务
  10068. if ($need_create_task) {
  10069. try {
  10070. // 优先使用 pic_prompt,如果没有则使用 description
  10071. $pic_prompt = getProp($item, 'pic_prompt');
  10072. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  10073. // 添加美术风格前缀
  10074. if ($art_style) {
  10075. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  10076. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  10077. $description = "{$prefix}:{$description}";
  10078. }
  10079. $params = [
  10080. 'prompt' => $description,
  10081. 'ref_img_urls' => []
  10082. ];
  10083. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10084. $task_id = $task->id;
  10085. if ($task_id) {
  10086. $item['task_id'] = $task_id;
  10087. $item['task_status'] = 'processing';
  10088. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  10089. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  10090. }
  10091. } catch (\Exception $e) {
  10092. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  10093. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  10094. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  10095. // 不抛出异常,继续处理其他资源
  10096. }
  10097. }
  10098. }
  10099. return $merged_items;
  10100. }
  10101. /**
  10102. * 同步新出现的主体和场景到全局
  10103. *
  10104. * @param int $anime_id 动漫ID
  10105. * @param array $merged_roles 合并后的角色列表
  10106. * @param array $merged_scenes 合并后的场景列表
  10107. * @param array $global_roles 全局角色列表
  10108. * @param array $global_scenes 全局场景列表
  10109. * @return void
  10110. */
  10111. private function syncNewResourcesToGlobal(
  10112. int $anime_id,
  10113. array $merged_roles,
  10114. array $merged_scenes,
  10115. array $global_roles,
  10116. array $global_scenes
  10117. ): void {
  10118. // 构建全局角色映射表
  10119. $global_role_map = [];
  10120. foreach ($global_roles as $role) {
  10121. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  10122. if ($roleKey !== '') {
  10123. $global_role_map[$roleKey] = $role;
  10124. }
  10125. }
  10126. // 构建全局场景映射表
  10127. $global_scene_map = [];
  10128. foreach ($global_scenes as $scene) {
  10129. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  10130. if ($sceneKey !== '') {
  10131. $global_scene_map[$sceneKey] = $scene;
  10132. }
  10133. }
  10134. $need_update = false;
  10135. $new_global_roles = $global_roles;
  10136. $new_global_scenes = $global_scenes;
  10137. // 检查并添加新角色到全局
  10138. foreach ($merged_roles as $role) {
  10139. $role_name = getProp($role, 'role');
  10140. // 跳过旁白
  10141. if ($role_name === '旁白') {
  10142. continue;
  10143. }
  10144. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  10145. if ($roleKey === '') {
  10146. continue;
  10147. }
  10148. // 如果全局中不存在该角色,添加到全局
  10149. if (!isset($global_role_map[$roleKey])) {
  10150. $new_global_roles[] = [
  10151. 'role' => $role_name,
  10152. 'description' => getProp($role, 'description', ''),
  10153. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  10154. 'voice_name' => getProp($role, 'voice_name', ''),
  10155. 'voice_type' => getProp($role, 'voice_type', ''),
  10156. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  10157. 'url' => getProp($role, 'url', ''),
  10158. 'task_id' => getProp($role, 'task_id', ''),
  10159. 'task_status' => getProp($role, 'task_status', ''),
  10160. ];
  10161. $global_role_map[$roleKey] = true; // 标记已添加
  10162. $need_update = true;
  10163. dLog('deepseek')->info("新角色同步到全局", [
  10164. 'anime_id' => $anime_id,
  10165. 'role' => $role_name,
  10166. 'task_id' => getProp($role, 'task_id', ''),
  10167. ]);
  10168. }
  10169. // else {
  10170. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  10171. // $global_role = $global_role_map[$roleKey];
  10172. // if (is_array($global_role)) {
  10173. // $updated = false;
  10174. // $update_fields = [];
  10175. // // 检查描述是否更新
  10176. // $current_description = trim((string)getProp($role, 'description'));
  10177. // $global_description = trim((string)getProp($global_role, 'description'));
  10178. // if ($current_description !== '' && $current_description !== $global_description) {
  10179. // $updated = true;
  10180. // $update_fields[] = 'description';
  10181. // }
  10182. // // 检查pic_prompt是否更新
  10183. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  10184. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  10185. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  10186. // $updated = true;
  10187. // $update_fields[] = 'pic_prompt';
  10188. // }
  10189. // // 检查图片任务信息是否更新
  10190. // $current_task_id = getProp($role, 'task_id');
  10191. // $global_task_id = getProp($global_role, 'task_id');
  10192. // if ($current_task_id && $current_task_id !== $global_task_id) {
  10193. // $updated = true;
  10194. // $update_fields[] = 'task_id';
  10195. // }
  10196. // // 如果有更新,同步到全局
  10197. // if ($updated) {
  10198. // foreach ($new_global_roles as &$global_role_item) {
  10199. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  10200. // if ($global_role_key === $roleKey) {
  10201. // if (in_array('description', $update_fields)) {
  10202. // $global_role_item['description'] = $current_description;
  10203. // }
  10204. // if (in_array('pic_prompt', $update_fields)) {
  10205. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  10206. // }
  10207. // if (in_array('task_id', $update_fields)) {
  10208. // $global_role_item['task_id'] = $current_task_id;
  10209. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  10210. // $global_role_item['url'] = getProp($role, 'url', '');
  10211. // }
  10212. // break;
  10213. // }
  10214. // }
  10215. // $need_update = true;
  10216. // dLog('deepseek')->info("角色信息更新到全局", [
  10217. // 'anime_id' => $anime_id,
  10218. // 'role' => $role_name,
  10219. // 'update_fields' => implode(',', $update_fields),
  10220. // ]);
  10221. // }
  10222. // }
  10223. // }
  10224. }
  10225. // 检查并添加新场景到全局
  10226. foreach ($merged_scenes as $scene) {
  10227. $scene_name = getProp($scene, 'scene');
  10228. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  10229. if ($sceneKey === '') {
  10230. continue;
  10231. }
  10232. // 如果全局中不存在该场景,添加到全局
  10233. if (!isset($global_scene_map[$sceneKey])) {
  10234. $new_global_scenes[] = [
  10235. 'scene' => $scene_name,
  10236. 'description' => getProp($scene, 'description', ''),
  10237. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  10238. 'url' => getProp($scene, 'url', ''),
  10239. 'task_id' => getProp($scene, 'task_id', ''),
  10240. 'task_status' => getProp($scene, 'task_status', ''),
  10241. ];
  10242. $global_scene_map[$sceneKey] = true; // 标记已添加
  10243. $need_update = true;
  10244. dLog('deepseek')->info("新场景同步到全局", [
  10245. 'anime_id' => $anime_id,
  10246. 'scene' => $scene_name,
  10247. 'task_id' => getProp($scene, 'task_id', ''),
  10248. ]);
  10249. }
  10250. // else {
  10251. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  10252. // $global_scene = $global_scene_map[$sceneKey];
  10253. // if (is_array($global_scene)) {
  10254. // $updated = false;
  10255. // $update_fields = [];
  10256. // // 检查描述是否更新
  10257. // $current_description = trim((string)getProp($scene, 'description'));
  10258. // $global_description = trim((string)getProp($global_scene, 'description'));
  10259. // if ($current_description !== '' && $current_description !== $global_description) {
  10260. // $updated = true;
  10261. // $update_fields[] = 'description';
  10262. // }
  10263. // // 检查pic_prompt是否更新
  10264. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  10265. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  10266. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  10267. // $updated = true;
  10268. // $update_fields[] = 'pic_prompt';
  10269. // }
  10270. // // 检查图片任务信息是否更新
  10271. // $current_task_id = getProp($scene, 'task_id');
  10272. // $global_task_id = getProp($global_scene, 'task_id');
  10273. // if ($current_task_id && $current_task_id !== $global_task_id) {
  10274. // $updated = true;
  10275. // $update_fields[] = 'task_id';
  10276. // }
  10277. // // 如果有更新,同步到全局
  10278. // if ($updated) {
  10279. // foreach ($new_global_scenes as &$global_scene_item) {
  10280. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  10281. // if ($global_scene_key === $sceneKey) {
  10282. // if (in_array('description', $update_fields)) {
  10283. // $global_scene_item['description'] = $current_description;
  10284. // }
  10285. // if (in_array('pic_prompt', $update_fields)) {
  10286. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  10287. // }
  10288. // if (in_array('task_id', $update_fields)) {
  10289. // $global_scene_item['task_id'] = $current_task_id;
  10290. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  10291. // $global_scene_item['url'] = getProp($scene, 'url', '');
  10292. // }
  10293. // break;
  10294. // }
  10295. // }
  10296. // $need_update = true;
  10297. // dLog('deepseek')->info("场景信息更新到全局", [
  10298. // 'anime_id' => $anime_id,
  10299. // 'scene' => $scene_name,
  10300. // 'update_fields' => implode(',', $update_fields),
  10301. // ]);
  10302. // }
  10303. // }
  10304. // }
  10305. }
  10306. // 如果有新增或更新,更新数据库
  10307. if ($need_update) {
  10308. $update_data = [
  10309. 'roles' => json_encode($new_global_roles, 256),
  10310. 'scenes' => json_encode($new_global_scenes, 256),
  10311. 'updated_at' => date('Y-m-d H:i:s'),
  10312. ];
  10313. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  10314. if ($result !== false) {
  10315. dLog('deepseek')->info("全局角色和场景更新成功", [
  10316. 'anime_id' => $anime_id,
  10317. 'roles_count' => count($new_global_roles),
  10318. 'scenes_count' => count($new_global_scenes),
  10319. ]);
  10320. } else {
  10321. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  10322. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  10323. }
  10324. }
  10325. }
  10326. }