DeepSeekService.php 733 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259
  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 App\Services\PointsService;
  12. use Illuminate\Support\Facades\DB;
  13. use Illuminate\Support\Facades\Log;
  14. use Illuminate\Support\Facades\Redis;
  15. use OSS\Core\OssException;
  16. use OSS\OssClient;
  17. use Smalot\PdfParser\Parser as PdfParser;
  18. use TCPDF;
  19. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  20. use Predis\Command\Traits\Get\Get;
  21. class DeepSeekService
  22. {
  23. private $url;
  24. private $api_key;
  25. private $sys_message;
  26. private $headers;
  27. private $valid_text_models;
  28. private $gpt_text_models;
  29. protected $aiImageGenerationService;
  30. protected $pointsService;
  31. public function __construct(AIImageGenerationService $aiImageGenerationService, PointsService $pointsService) {
  32. $this->aiImageGenerationService = $aiImageGenerationService;
  33. $this->pointsService = $pointsService;
  34. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  35. $this->api_key = env('DEEPSEEK_API_KEY');
  36. $this->headers = [
  37. 'Authorization' => 'Bearer '.$this->api_key,
  38. 'Content-Type' => 'application/json; charset=UTF-8'
  39. ];
  40. // 火山引擎模型列表
  41. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  42. // GPT文本模型列表
  43. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  44. $this->sys_message = [
  45. 'role' => 'system',
  46. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  47. 强制要求:\n
  48. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  49. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  50. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  51. 普通要求:\n
  52. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  53. 2.<分集剧本>的要求如下:
  54.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  55.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  56.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  57.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  58. \n\n
  59. 示例如下:\n
  60. ###剧本名:西昆仑
  61. ###故事梗概
  62. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  63. ###剧本亮点
  64. 亮点1:绝境奇药,生死一线
  65. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  66. 亮点2:结拜兄妹,化解尴尬
  67. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  68. 亮点3:纤发夺命,情愫暗涌
  69. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  70. ###人物关系
  71. 阿雪与梁萧之间存在兄妹之情。
  72. ###核心矛盾
  73. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  74. ###主体列表
  75. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  76. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  77. 阴阳球:天地异宝,能化生精气,救人于危难。
  78. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  79. ###美术风格
  80. 基础画风风格词:厚涂古风
  81. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  82. ###场景列表
  83. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  84. ###分集剧本
  85. ##分集01
  86. 第1集: 第一集的标题
  87. 场景描述:地点、时间、场景
  88. 运镜:固定近距离
  89. 出场角色:男主、女主
  90. 台词内容:
  91. 女主: 女主对话
  92. 男主:男主对话
  93. 女主: 女主对话
  94. 男主: 男主对话
  95. ##分集02
  96. 第2集: 第二集的标题
  97. 场景描述:地点、时间、场景
  98. 运镜:固定近距离
  99. 出场角色:男主、女主
  100. 台词内容:
  101. 女主: 女主对话
  102. 男主:男主对话
  103. 女主: 女主对话
  104. 男主: 男主对话"
  105. ];
  106. }
  107. /**
  108. * 通用文生文方法 - 支持多模型流式输出和图片输入
  109. *
  110. * @param array $data 请求参数
  111. * @return \Generator 返回生成器,用于流式输出
  112. */
  113. public function generateText($data) {
  114. // 获取请求参数
  115. $model = getProp($data, 'model', 'deepseek-v4-flash'); // 默认使用deepseek-v3
  116. $messages = getProp($data, 'messages', []);
  117. $systemPrompt = getProp($data, 'system_prompt', '');
  118. $prompt = getProp($data, 'prompt', '');
  119. $images = getProp($data, 'images', []); // 支持多张图片
  120. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  121. // 如果没有提供messages,则根据system_prompt、content和images构建
  122. if (empty($messages)) {
  123. $messages = [];
  124. // 添加系统提示词
  125. if (!empty($systemPrompt)) {
  126. $messages[] = [
  127. 'role' => 'system',
  128. 'content' => $systemPrompt
  129. ];
  130. }
  131. // 构建用户消息内容(支持文本+图片)
  132. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  133. $userMessage = [
  134. 'role' => 'user',
  135. 'content' => []
  136. ];
  137. // 添加文本内容
  138. if (!empty($prompt)) {
  139. $userMessage['content'][] = [
  140. 'type' => 'text',
  141. 'text' => $prompt
  142. ];
  143. }
  144. // 处理上传的图片文件
  145. if (!empty($images)) {
  146. if (!is_array($images)) {
  147. $images = [$images];
  148. }
  149. foreach ($images as $image) {
  150. $imageBase64 = $this->processImageToBase64($image);
  151. if ($imageBase64) {
  152. $userMessage['content'][] = [
  153. 'type' => 'image_url',
  154. 'image_url' => [
  155. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  156. ]
  157. ];
  158. }
  159. }
  160. }
  161. // 处理图片URL
  162. if (!empty($imageUrls)) {
  163. if (!is_array($imageUrls)) {
  164. $imageUrls = [$imageUrls];
  165. }
  166. foreach ($imageUrls as $url) {
  167. if (!empty($url)) {
  168. $userMessage['content'][] = [
  169. 'type' => 'image_url',
  170. 'image_url' => [
  171. 'url' => $url
  172. ]
  173. ];
  174. }
  175. }
  176. }
  177. // 如果只有文本内容,简化为字符串格式
  178. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  179. $userMessage['content'] = $userMessage['content'][0]['text'];
  180. }
  181. $messages[] = $userMessage;
  182. }
  183. }
  184. // 验证messages不为空
  185. if (empty($messages)) {
  186. Utils::throwError('20003:请提供有效的对话内容');
  187. }
  188. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  189. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  190. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  191. if ($model === 'deepseek-chat') {
  192. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  193. $model = 'deepseek-v4-flash';
  194. $thinkingMode = 'disabled';
  195. } elseif ($model === 'deepseek-reasoner') {
  196. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  197. $model = 'deepseek-v4-flash';
  198. $thinkingMode = 'enabled';
  199. }
  200. // 构建请求参数
  201. $post_data = [
  202. 'model' => $model,
  203. 'messages' => $messages,
  204. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  205. 'temperature' => getProp($data, 'temperature', 1),
  206. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  207. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  208. 'thinking' => ['type' => $thinkingMode],
  209. 'stream' => true // 启用流式输出
  210. ];
  211. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  212. // 添加可选参数
  213. if (isset($data['top_p'])) {
  214. $post_data['top_p'] = $data['top_p'];
  215. }
  216. if (isset($data['response_format'])) {
  217. $post_data['response_format'] = $data['response_format'];
  218. }
  219. // 根据模型类型选择调用方法
  220. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  221. // DeepSeek 官方模型使用 DeepSeek API
  222. return $this->deepSeekStreamResponse($post_data);
  223. } else if (in_array($model, $this->gpt_text_models)) {
  224. // GPT 模型使用 TokenRouter API
  225. return $this->gpt54StreamResponse($post_data);
  226. } else if (in_array($model, $this->valid_text_models)) {
  227. // 火山引擎支持的模型使用火山引擎 API
  228. return $this->volcEngineChatCompletion($post_data);
  229. } else {
  230. Utils::throwError('20003:不支持的模型: ' . $model);
  231. }
  232. }
  233. public function createGenerateText($data) {
  234. $file = getProp($data, 'file');
  235. $uid = Site::getUid();
  236. $cpid = Site::getCpid();
  237. if (!$file) {
  238. Utils::throwError('20003:请上传文件');
  239. }
  240. // 提取文件内容
  241. $content = $this->extractFileContent($file);
  242. if (!$content) {
  243. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  244. }
  245. // 获取原始文件名(不含扩展名)作为script_name
  246. $originalName = $file->getClientOriginalName();
  247. $script_name = pathinfo($originalName, PATHINFO_FILENAME);
  248. if (!$script_name) {
  249. Utils::throwError('20003:未识别到剧本名,请联系管理员');
  250. }
  251. // 如果同一用户的剧本名存在则提示
  252. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('user_id', $uid)->where('is_deleted', 0)->exists()) {
  253. Utils::throwError('20003:你已上传过该剧本,请修改文件名后上传');
  254. }
  255. // 插入数据到mp_scripts表
  256. $script_id = DB::table('mp_scripts')->insertGetId([
  257. 'script_name' => $script_name,
  258. 'user_id' => $uid,
  259. 'cpid' => $cpid,
  260. 'content' => $content,
  261. 'created_at' => date('Y-m-d H:i:s'),
  262. 'updated_at' => date('Y-m-d H:i:s')
  263. ]);
  264. return [
  265. 'script_id' => $script_id,
  266. 'script_name' => $script_name
  267. ];
  268. }
  269. /**
  270. * AI对话调用成功后的积分扣费(返回结果前调用)
  271. *
  272. * 计费失败抛错,由调用方事务回滚,避免“成功但未扣费”。
  273. *
  274. * @param int $uid
  275. * @param int $tokens
  276. * @param array $chargeInfo
  277. * @return void
  278. */
  279. private function chargeChatSuccess(int $uid, int $tokens, array $chargeInfo): void
  280. {
  281. $result = $this->pointsService->recordChatCharge(
  282. $uid,
  283. PointsService::CHAT_CHARGE_POINTS,
  284. $tokens,
  285. $chargeInfo
  286. );
  287. if (empty($result['charged'])) {
  288. throw new \Exception('AI对话计费失败: ' . (string)($result['reason'] ?? 'unknown'));
  289. }
  290. }
  291. /**
  292. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  293. *
  294. * @param array $data 请求参数
  295. * @return array 返回结果数组
  296. */
  297. public function newGenerateText($data) {
  298. // 获取请求参数
  299. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  300. $messages = getProp($data, 'messages', []);
  301. $systemPrompt = getProp($data, 'system_prompt', '');
  302. $prompt = getProp($data, 'prompt', '');
  303. $images = getProp($data, 'images', []); // 支持多张图片
  304. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  305. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  306. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  307. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  308. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  309. // 新增: 如果提供了script_id,提前校验是否已有生成中的任务
  310. $generateTaskId = 0;
  311. $uid = Site::getUid();
  312. if ($script_id > 0) {
  313. $existingTask = DB::table('mp_script_generate_tasks')
  314. ->where('uid', $uid)
  315. ->where('script_id', $script_id)
  316. ->orderByDesc('id')
  317. ->first();
  318. // 如果已有生成中的任务,直接提示,避免前端长时间等待
  319. if ($existingTask && in_array(getProp($existingTask, 'status'), ['pending', 'processing'])) {
  320. Utils::throwError('20003:该剧本资产正在生成中,请稍后重试');
  321. }
  322. }
  323. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  324. $originalContent = '';
  325. $hasValidScript = false; // 是否已加载到有效剧本(存在且内容非空)
  326. if ($script_id > 0) {
  327. $script = DB::table('mp_scripts')
  328. ->where('id', $script_id)
  329. ->where('is_deleted', 0)
  330. ->first();
  331. if (!$script) {
  332. Utils::throwError('20003:剧本不存在或已删除');
  333. }
  334. $originalContent = $script->content ?? '';
  335. if (empty($originalContent)) {
  336. Utils::throwError('20003:剧本内容为空');
  337. }
  338. $hasValidScript = true;
  339. // 将剧本内容添加到提示词前面
  340. if (!empty($originalContent)) {
  341. if (!empty($prompt)) {
  342. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  343. } else {
  344. $prompt = "原文内容:\n" . $originalContent;
  345. }
  346. }
  347. }
  348. // 新增: 如果提供了template_id,从数据库获取template_prompt
  349. if ($templateId > 0) {
  350. $template = DB::table('mp_prompt_templates')
  351. ->where('id', $templateId)
  352. ->where('is_deleted', 0)
  353. ->first();
  354. if (!$template) {
  355. Utils::throwError('20003:模板不存在或已删除');
  356. }
  357. $templatePrompt = $template->template_prompt ?? '';
  358. // 将模板提示词和用户输入的prompt组合
  359. // 模板为准,用户输入作为补充要求
  360. if (!empty($templatePrompt)) {
  361. if (!empty($prompt)) {
  362. $prompt = $templatePrompt . "\n\n" . $prompt;
  363. } else {
  364. $prompt = $templatePrompt;
  365. }
  366. }
  367. }
  368. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  369. if (empty($messages)) {
  370. $messages = [];
  371. // 添加系统提示词
  372. if (!empty($systemPrompt)) {
  373. $messages[] = [
  374. 'role' => 'system',
  375. 'content' => $systemPrompt
  376. ];
  377. }
  378. // 构建用户消息内容(支持文本+图片)
  379. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  380. $userMessage = [
  381. 'role' => 'user',
  382. 'content' => []
  383. ];
  384. // 添加文本内容
  385. if (!empty($prompt)) {
  386. $userMessage['content'][] = [
  387. 'type' => 'text',
  388. 'text' => $prompt
  389. ];
  390. }
  391. // 处理上传的图片文件
  392. if (!empty($images)) {
  393. if (!is_array($images)) {
  394. $images = [$images];
  395. }
  396. foreach ($images as $image) {
  397. $imageBase64 = $this->processImageToBase64($image);
  398. if ($imageBase64) {
  399. $userMessage['content'][] = [
  400. 'type' => 'image_url',
  401. 'image_url' => [
  402. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  403. ]
  404. ];
  405. }
  406. }
  407. }
  408. // 处理图片URL
  409. if (!empty($imageUrls)) {
  410. if (!is_array($imageUrls)) {
  411. $imageUrls = [$imageUrls];
  412. }
  413. foreach ($imageUrls as $url) {
  414. if (!empty($url)) {
  415. $userMessage['content'][] = [
  416. 'type' => 'image_url',
  417. 'image_url' => [
  418. 'url' => $url
  419. ]
  420. ];
  421. }
  422. }
  423. }
  424. // 如果只有文本内容,简化为字符串格式
  425. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  426. $userMessage['content'] = $userMessage['content'][0]['text'];
  427. }
  428. $messages[] = $userMessage;
  429. }
  430. }
  431. // 验证messages不为空
  432. if (empty($messages)) {
  433. Utils::throwError('20003:请提供有效的对话内容');
  434. }
  435. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  436. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  437. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  438. if ($model === 'deepseek-chat') {
  439. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  440. $model = 'deepseek-v4-flash';
  441. $thinkingMode = 'disabled';
  442. } elseif ($model === 'deepseek-reasoner') {
  443. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  444. $model = 'deepseek-v4-flash';
  445. $thinkingMode = 'enabled';
  446. }
  447. // 构建请求参数(非流式)
  448. $post_data = [
  449. 'model' => $model,
  450. 'messages' => $messages,
  451. 'temperature' => getProp($data, 'temperature', 1),
  452. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  453. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  454. 'thinking' => ['type' => $thinkingMode],
  455. 'stream' => false // 非流式输出
  456. ];
  457. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  458. // 添加可选参数
  459. if (isset($data['top_p'])) {
  460. $post_data['top_p'] = $data['top_p'];
  461. }
  462. // 新增: 根据response_format设置响应格式
  463. if ($responseFormat === 'json') {
  464. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  465. $hasJsonKeyword = false;
  466. foreach ($post_data['messages'] as $message) {
  467. if (isset($message['content'])) {
  468. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  469. if (stripos($content, 'json') !== false) {
  470. $hasJsonKeyword = true;
  471. break;
  472. }
  473. }
  474. }
  475. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  476. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  477. if (!$hasJsonKeyword) {
  478. $lastMessageIndex = count($post_data['messages']) - 1;
  479. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  480. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  481. // 如果content是字符串,直接追加
  482. if (is_string($lastContent)) {
  483. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  484. }
  485. // 如果content是数组(包含文本和图片),在文本部分追加
  486. else if (is_array($lastContent)) {
  487. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  488. if ($contentPart['type'] === 'text') {
  489. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  490. break;
  491. }
  492. }
  493. }
  494. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  495. }
  496. }
  497. // 设置response_format参数(所有支持的模型)
  498. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  499. // DeepSeek模型
  500. $post_data['response_format'] = ['type' => 'json_object'];
  501. } else if (in_array($model, $this->gpt_text_models)) {
  502. // GPT模型
  503. $post_data['response_format'] = ['type' => 'json_object'];
  504. } else if (in_array($model, $this->valid_text_models)) {
  505. // 火山引擎模型
  506. $post_data['response_format'] = ['type' => 'json_object'];
  507. }
  508. }
  509. // 新增: 如果提供了script_id,创建剧本资产生成任务(所有参数校验通过后创建,避免校验失败留下卡在生成中的任务)
  510. if ($script_id > 0) {
  511. $uid = Site::getUid();
  512. // 创建新的生成任务
  513. $generateTaskId = DB::table('mp_script_generate_tasks')->insertGetId([
  514. 'uid' => $uid,
  515. 'script_id' => $script_id,
  516. 'sequence' => $sequence,
  517. 'status' => 'processing',
  518. 'prompt' => getProp($data, 'prompt', ''),
  519. 'started_at' => date('Y-m-d H:i:s'),
  520. 'created_at' => date('Y-m-d H:i:s'),
  521. 'updated_at' => date('Y-m-d H:i:s')
  522. ]);
  523. }
  524. // 积分余额预检(仅存在有效剧本时按 chat 类型计费,不足直接报错)
  525. if ($hasValidScript) {
  526. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  527. }
  528. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  529. try {
  530. $aiResult = null;
  531. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  532. // DeepSeek 官方模型使用现有的 chatOnly 方法
  533. $result = $this->chatOnly($post_data);
  534. // 记录实际使用的模型
  535. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  536. $aiResult = [
  537. 'content' => $result['fullContent'],
  538. 'reasoning_content' => $result['fullReasoningContent'],
  539. 'usage' => $result['usage'],
  540. 'model' => $model,
  541. 'finish_reason' => 'stop'
  542. ];
  543. } else if (in_array($model, $this->gpt_text_models)) {
  544. // GPT 模型使用现有的 gpt54ChatOnly 方法
  545. $result = $this->gpt54ChatOnly($post_data);
  546. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  547. $aiResult = [
  548. 'content' => $result['fullContent'],
  549. 'reasoning_content' => '',
  550. 'usage' => $result['usage'],
  551. 'model' => $model,
  552. 'finish_reason' => 'stop'
  553. ];
  554. } else if (in_array($model, $this->valid_text_models)) {
  555. // 火山引擎支持的模型使用火山引擎 API(非流式)
  556. $post_data['stream'] = false;
  557. $result = $this->volcEngineChatCompletion($post_data);
  558. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  559. 'requested_model' => $model,
  560. 'result_keys' => array_keys($result),
  561. 'has_fullContent' => isset($result['fullContent']),
  562. 'has_content' => isset($result['content'])
  563. ]);
  564. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  565. $aiResult = [
  566. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  567. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  568. 'usage' => $result['usage'] ?? [],
  569. 'model' => $model,
  570. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  571. ];
  572. } else {
  573. Utils::throwError('20003:不支持的模型: ' . $model);
  574. }
  575. } catch (\Exception $e) {
  576. // 生成失败,更新任务状态
  577. if ($generateTaskId) {
  578. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  579. 'status' => 'failed',
  580. 'error_message' => $e->getMessage(),
  581. 'completed_at' => date('Y-m-d H:i:s'),
  582. 'updated_at' => date('Y-m-d H:i:s')
  583. ]);
  584. }
  585. Utils::throwError('20003:' . str_replace(':',':',$e->getMessage()));
  586. }
  587. // 生成成功,更新任务状态
  588. if ($generateTaskId && $aiResult) {
  589. DB::table('mp_script_generate_tasks')->where('id', $generateTaskId)->update([
  590. 'status' => 'success',
  591. 'result' => getProp($aiResult, 'content', ''),
  592. 'completed_at' => date('Y-m-d H:i:s'),
  593. 'updated_at' => date('Y-m-d H:i:s')
  594. ]);
  595. $aiResult['generate_task_id'] = $generateTaskId;
  596. }
  597. // 调用成功且存在有效剧本时,返回结果前扣除积分并记录明细(chat类型10积分)
  598. if ($hasValidScript && $aiResult && !empty($aiResult['content'])) {
  599. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($aiResult['usage'] ?? []), [
  600. 'model' => $model,
  601. 'script_id' => $script_id,
  602. 'sequence' => $sequence,
  603. 'source' => 'newGenerateText',
  604. ]);
  605. }
  606. // 新增: 如果提供了script_id,保存对话记录
  607. if ($script_id > 0 && $aiResult) {
  608. try {
  609. $uid = Site::getUid();
  610. $now = now();
  611. // 获取用户原始的prompt(不包含剧本内容)
  612. $originalPrompt = getProp($data, 'prompt', '');
  613. $recordsToInsert = [
  614. [
  615. 'uid' => $uid,
  616. 'script_id' => $script_id,
  617. 'sequence' => $sequence,
  618. 'role' => 'user',
  619. 'content' => $originalPrompt,
  620. 'created_at' => $now,
  621. 'updated_at' => $now,
  622. ],
  623. [
  624. 'uid' => $uid,
  625. 'script_id' => $script_id,
  626. 'sequence' => $sequence,
  627. 'role' => 'assistant',
  628. 'content' => $aiResult['content'],
  629. 'created_at' => $now,
  630. 'updated_at' => $now,
  631. ]
  632. ];
  633. DB::table('mp_script_records')->insert($recordsToInsert);
  634. // 获取刚插入的记录ID(假设按插入顺序返回)
  635. $insertedRecords = DB::table('mp_script_records')
  636. ->where('uid', $uid)
  637. ->where('script_id', $script_id)
  638. ->where('sequence', $sequence)
  639. ->orderBy('id', 'desc')
  640. ->limit(2)
  641. ->get()
  642. ->map(function ($record) {
  643. return [
  644. 'rid' => $record->id,
  645. 'script_id' => $record->script_id,
  646. 'sequence' => $record->sequence,
  647. 'role' => $record->role,
  648. 'content' => $record->content,
  649. 'created_at' => $record->created_at,
  650. ];
  651. })
  652. ->reverse()
  653. ->values()
  654. ->toArray();
  655. // 将记录信息添加到返回结果中
  656. $aiResult['records'] = $insertedRecords;
  657. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  658. } catch (\Exception $e) {
  659. // 记录错误但不影响主流程
  660. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  661. }
  662. }
  663. return $aiResult;
  664. }
  665. /**
  666. * 获取剧本资产生成任务列表(按用户分页,每页15条)
  667. *
  668. * @param array $data
  669. * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
  670. */
  671. public function getScriptGenerateTasks($data) {
  672. $uid = Site::getUid();
  673. return DB::table('mp_script_generate_tasks as t')
  674. ->leftJoin('mp_scripts as s', 't.script_id', '=', 's.id')
  675. ->where('t.uid', $uid)
  676. ->select('t.id', 't.script_id', 's.script_name', 't.sequence', 't.status', 't.error_message', 't.started_at', 't.completed_at')
  677. ->orderByDesc('t.id')
  678. ->paginate(15);
  679. }
  680. public function saveScriptChatHistory($data) {
  681. $uid = Site::getUid();
  682. $rid = getProp($data, 'rid');
  683. $script_id = getProp($data, 'script_id');
  684. $sequence = getProp($data, 'sequence', 0);
  685. $content = getProp($data, 'content');
  686. if (!$rid) {
  687. Utils::throwError('20003:请选择对话记录ID');
  688. }
  689. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  690. if (!$record) {
  691. Utils::throwError('20003:对话记录不存在');
  692. }
  693. if (!$script_id) {
  694. Utils::throwError('20003:请选择剧本');
  695. }
  696. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  697. if (!$script) {
  698. Utils::throwError('20003:剧本不存在');
  699. }
  700. // 批量插入数据
  701. return DB::table('mp_script_records')->where('id', $rid)->update([
  702. 'content' => $content,
  703. 'updated_at' => date('Y-m-d H:i:s')
  704. ]);
  705. }
  706. /**
  707. * 获取剧本的历史对话记录
  708. *
  709. * @param array $data 请求参数
  710. * @return array 返回历史记录数组
  711. */
  712. public function getScriptChatHistory($data) {
  713. $uid = Site::getUid();
  714. $script_id = getProp($data, 'script_id');
  715. $rid = getProp($data, 'rid');
  716. $sequence = getProp($data, 'sequence', null);
  717. if (!$script_id) {
  718. Utils::throwError('20003:请提供剧本ID');
  719. }
  720. // 验证剧本是否存在
  721. $script = DB::table('mp_scripts')
  722. ->where('id', $script_id)
  723. ->where('is_deleted', 0)
  724. ->first();
  725. if (!$script) {
  726. Utils::throwError('20003:剧本不存在');
  727. }
  728. // 构建查询
  729. $query = DB::table('mp_script_records')
  730. ->where('script_id', $script_id);
  731. // ->where('uid', $uid);
  732. // 如果提供了 sequence,则过滤指定剧集
  733. if ($sequence !== null) {
  734. $query->where('sequence', $sequence);
  735. }
  736. // 记录ID筛选
  737. if ($rid) {
  738. $query->where('id', $rid);
  739. }
  740. // 查询记录并按 id 正序排序
  741. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  742. ->orderBy('created_at', 'asc')
  743. ->orderBy('id', 'asc')
  744. ->get()
  745. ->map(function ($record) {
  746. return [
  747. 'rid' => $record->id,
  748. 'script_id' => $record->script_id,
  749. 'sequence' => $record->sequence,
  750. 'role' => $record->role,
  751. 'content' => $record->content,
  752. 'products' => $record->products ? json_decode($record->products) : [],
  753. 'created_at' => $record->created_at,
  754. ];
  755. })
  756. ->toArray();
  757. return $records;
  758. }
  759. /**
  760. * 处理图片转换为base64
  761. *
  762. * @param mixed $image 图片文件对象或文件路径
  763. * @return string|null base64编码的图片数据
  764. */
  765. private function processImageToBase64($image) {
  766. try {
  767. // 获取文件路径
  768. if (is_string($image)) {
  769. $filePath = $image;
  770. } else {
  771. // Laravel UploadedFile 对象
  772. $filePath = $image->getRealPath();
  773. }
  774. if (!file_exists($filePath)) {
  775. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  776. return null;
  777. }
  778. // 验证是否为图片文件
  779. $imageInfo = @getimagesize($filePath);
  780. if ($imageInfo === false) {
  781. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  782. return null;
  783. }
  784. // 读取图片并转换为base64
  785. $imageData = file_get_contents($filePath);
  786. $base64Image = base64_encode($imageData);
  787. dLog('deepseek')->info('图片转换成功', [
  788. 'size' => strlen($imageData),
  789. 'type' => $imageInfo['mime']
  790. ]);
  791. return $base64Image;
  792. } catch (\Exception $e) {
  793. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  794. return null;
  795. }
  796. }
  797. private function getArtStylePromptMappings($art_style='')
  798. {
  799. $arr = [
  800. '唯美真人风格' => [
  801. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  802. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  803. ],
  804. '真人古风风格' => [
  805. 'aliases' => ['真人古风风格', '真人古风'],
  806. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  807. ],
  808. '日系动漫风格' => [
  809. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  810. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  811. ],
  812. '国漫风格' => [
  813. 'aliases' => ['国漫风格', '国漫'],
  814. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  815. ],
  816. 'Q版卡通风格' => [
  817. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  818. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  819. ],
  820. '简约扁平风格' => [
  821. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  822. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  823. ],
  824. '武侠风格' => [
  825. 'aliases' => ['武侠风格', '武侠'],
  826. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  827. ],
  828. '古风仙侠风格' => [
  829. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  830. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  831. ],
  832. '新中式水墨风格' => [
  833. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  834. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  835. ],
  836. '写实插画风格' => [
  837. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  838. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  839. ],
  840. '3D卡通风格' => [
  841. 'aliases' => ['3D卡通风格', '3D卡通'],
  842. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  843. ],
  844. '条漫风格' => [
  845. 'aliases' => ['条漫风格', '条漫'],
  846. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  847. ],
  848. '赛博朋克风格' => [
  849. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  850. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  851. ],
  852. '暗黑悬疑风格' => [
  853. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  854. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  855. ],
  856. '治愈清新风格' => [
  857. 'aliases' => ['治愈清新风格', '治愈清新'],
  858. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  859. ],
  860. '3D真人风格' => [
  861. 'aliases' => ['3D', '3D真人', '3D真人风格'],
  862. 'prompt' => "3D真人短剧风格,超写实质感,电影级布光与景深,竖屏构图,中心聚焦,高饱和度色彩与强对比,微表情细腻,动作凌厉,快节奏强冲突,沉浸式代入感。"
  863. ],
  864. ];
  865. if($art_style) {
  866. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  867. }
  868. return $arr;
  869. $arr = [
  870. '唯美真人风格' => [
  871. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  872. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  873. 2. 色彩色调
  874. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  875. 3. 画质精度
  876. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  877. 4. 画面观感
  878. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  879. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  880. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  881. ],
  882. '真人古风风格' => [
  883. 'aliases' => ['真人古风风格', '真人古风'],
  884. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  885. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  886. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  887. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  888. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  889. ],
  890. '日系动漫风格' => [
  891. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  892. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  893. 正向提示词(中文)
  894. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  895. 必须遵守规则
  896. • 全程保持日系动漫风格,不混入其他画风
  897. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  898. • 画面适配所选画面比例,构图居中,主体突出
  899. • 线条干净、色彩统一,不杂乱、不突兀
  900. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  901. ],
  902. '国漫风格' => [
  903. 'aliases' => ['国漫风格', '国漫'],
  904. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  905. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  906. 必须遵守规则
  907. • 严格保持国漫画风,不串风格、不混画风
  908. • 角色形象统一,不随意改变五官、身材、服饰
  909. • 画面构图稳定,适合漫剧叙事展示
  910. • 色调统一,不出现脏色、杂色
  911. 禁止/避免词汇
  912. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  913. ],
  914. 'Q版卡通风格' => [
  915. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  916. 'prompt' => "风格说明
  917. 头大身小,造型可爱圆润,简约干净
  918. 正向提示词(中文)
  919. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  920. 必须遵守规则
  921. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  922. • 角色造型统一,表情可爱,不诡异
  923. • 画面简洁清爽,无多余复杂元素
  924. • 色彩明亮柔和,不刺眼
  925. 禁止/避免词汇
  926. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  927. ],
  928. '简约扁平风格' => [
  929. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  930. 'prompt' => "风格说明
  931. 色块简洁、无复杂渐变,现代极简风
  932. 正向提示词(中文)
  933. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  934. 必须遵守规则
  935. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  936. • 构图简洁,主体突出,无多余装饰
  937. • 色彩统一、干净,不杂乱
  938. 禁止/避免词汇
  939. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  940. ],
  941. '武侠风格' => [
  942. 'aliases' => ['武侠风格', '武侠'],
  943. 'prompt' => "风格说明
  944. 江湖气息,线条硬朗,动作感强
  945. 正向提示词(中文)
  946. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  947. 必须遵守规则
  948. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  949. • 角色形象、服饰、身材比例统一
  950. • 画面动作自然,不扭曲、不畸形
  951. 禁止/避免词汇
  952. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  953. ],
  954. '古风仙侠风格' => [
  955. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  956. 'prompt' => "风格说明
  957. 飘逸汉服、云雾仙气、唯美空灵
  958. 正向提示词(中文)
  959. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  960. 必须遵守规则
  961. • 保持古风仙侠统一画风,不混入现代、科幻元素
  962. • 角色服饰、发型、形象前后一致
  963. • 场景仙气飘逸,色调清雅统一
  964. • 画面唯美柔和,不阴暗、不诡异
  965. 禁止/避免词汇
  966. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  967. ],
  968. '新中式水墨风格' => [
  969. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  970. 'prompt' => "风格说明
  971. 淡墨渲染,毛笔笔触,留白意境
  972. 正向提示词(中文)
  973. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  974. 必须遵守规则
  975. • 严格保持水墨质感,不混入厚涂、写实、卡通
  976. • 色调淡雅统一,不浓艳杂乱
  977. • 画面干净有意境,不堆砌元素
  978. 禁止/避免词汇
  979. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  980. ],
  981. '写实插画风格' => [
  982. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  983. 'prompt' => "风格说明
  984. 接近真人比例,光影真实,质感细腻
  985. 正向提示词(中文)
  986. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  987. 必须遵守规则
  988. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  989. • 角色五官、身材、服饰高度统一
  990. • 画面清晰、光影自然、不扭曲
  991. 禁止/避免词汇
  992. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  993. ],
  994. '3D卡通风格' => [
  995. 'aliases' => ['3D卡通风格', '3D卡通'],
  996. 'prompt' => "风格说明
  997. 3D建模质感,柔和渲染,圆润可爱
  998. 正向提示词(中文)
  999. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  1000. 必须遵守规则
  1001. • 保持3D卡通统一质感,不出现2D杂乱线条
  1002. • 角色模型、比例、形象前后一致
  1003. • 画面干净,不模糊、不穿模
  1004. 禁止/避免词汇
  1005. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  1006. ],
  1007. '条漫风格' => [
  1008. 'aliases' => ['条漫风格', '条漫'],
  1009. 'prompt' => "风格说明
  1010. 纵向分镜,上下滑动阅读,轻量化
  1011. 正向提示词(中文)
  1012. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  1013. 必须遵守规则
  1014. • 保持条漫纵向阅读逻辑,构图简洁
  1015. • 画风统一,不混写实、3D、水墨
  1016. • 画面干净,不杂乱
  1017. 禁止/避免词汇
  1018. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  1019. ],
  1020. '赛博朋克风格' => [
  1021. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  1022. 'prompt' => "风格说明
  1023. 霓虹灯光、未来都市、暗色调、科技机械
  1024. 正向提示词(中文)
  1025. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  1026. 必须遵守规则
  1027. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  1028. • 色调以暗调+霓虹为主,色彩统一
  1029. • 画面科技感强,不杂乱
  1030. 禁止/避免词汇
  1031. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  1032. ],
  1033. '暗黑悬疑风格' => [
  1034. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  1035. 'prompt' => "风格说明
  1036. 低饱和、冷色调、阴影重、神秘压抑
  1037. 正向提示词(中文)
  1038. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  1039. 必须遵守规则
  1040. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  1041. • 画面氛围压抑神秘,但不低俗、不血腥
  1042. • 角色形象统一,不崩坏
  1043. 禁止/避免词汇
  1044. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  1045. ],
  1046. '治愈清新风格' => [
  1047. 'aliases' => ['治愈清新风格', '治愈清新'],
  1048. 'prompt' => "风格说明
  1049. 马卡龙色系、柔光、温暖干净
  1050. 正向提示词(中文)
  1051. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  1052. 必须遵守规则
  1053. • 保持治愈清新统一色调,不阴暗、不诡异
  1054. • 画面柔和干净,无杂乱元素
  1055. • 角色形象柔和可爱,不狰狞
  1056. 禁止/避免词汇
  1057. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  1058. ],
  1059. ];
  1060. return $arr;
  1061. }
  1062. public function getArtStylePromptByInput($inputArtStyle): string
  1063. {
  1064. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  1065. if ($normalizedInput === '') {
  1066. return '';
  1067. }
  1068. return $this->getArtStylePromptMappings($normalizedInput);
  1069. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  1070. // foreach ($mapping['aliases'] as $alias) {
  1071. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  1072. // if ($normalizedAlias === '') {
  1073. // continue;
  1074. // }
  1075. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  1076. // return $mapping['prompt'];
  1077. // }
  1078. // }
  1079. // }
  1080. return '';
  1081. }
  1082. public function getArtStyleShortPromptByInput($inputArtStyle) {
  1083. $stylePrefixes = [
  1084. '唯美真人风格' => [
  1085. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  1086. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  1087. ],
  1088. '真人古风风格' => [
  1089. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  1090. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  1091. ],
  1092. '日系动漫风格' => [
  1093. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  1094. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  1095. ],
  1096. '国漫风格' => [
  1097. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  1098. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  1099. ],
  1100. 'Q版卡通风格' => [
  1101. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  1102. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  1103. ],
  1104. '简约扁平风格' => [
  1105. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  1106. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  1107. ],
  1108. '武侠风格' => [
  1109. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  1110. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  1111. ],
  1112. '古风仙侠风格' => [
  1113. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  1114. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  1115. ],
  1116. '新中式水墨风格' => [
  1117. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  1118. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  1119. ],
  1120. '写实插画风格' => [
  1121. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  1122. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  1123. ],
  1124. '3D卡通风格' => [
  1125. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  1126. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  1127. ],
  1128. '条漫风格' => [
  1129. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  1130. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  1131. ],
  1132. '赛博朋克风格' => [
  1133. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  1134. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  1135. ],
  1136. '暗黑悬疑风格' => [
  1137. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  1138. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  1139. ],
  1140. '治愈清新风格' => [
  1141. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  1142. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  1143. ]
  1144. ];
  1145. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  1146. }
  1147. private function normalizeArtStyleInput($value): string
  1148. {
  1149. $value = trim((string)$value);
  1150. if ($value === '') {
  1151. return '';
  1152. }
  1153. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  1154. return mb_strtolower($value, 'UTF-8');
  1155. }
  1156. private function replaceArtStyleSection(string $content, string $artStyle): string
  1157. {
  1158. if ($content === '' || $artStyle === '') {
  1159. return $content;
  1160. }
  1161. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  1162. if (!preg_match($pattern, $content)) {
  1163. return $content;
  1164. }
  1165. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  1166. }
  1167. /**
  1168. * DeepSeek流式输出处理方法
  1169. *
  1170. * @param array $post_data DeepSeek API请求参数
  1171. * @return \Generator 返回生成器,用于流式输出
  1172. */
  1173. private function deepSeekStreamResponse($post_data) {
  1174. // 设置最大输出tokens
  1175. $post_data['max_tokens'] = 300000;
  1176. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  1177. $post_data['stream_options'] = ['include_usage' => true];
  1178. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1179. $response = $client->post($this->url, [
  1180. 'json' => $post_data,
  1181. 'headers' => $this->headers,
  1182. 'stream' => true // 启用流式响应
  1183. ]);
  1184. $body = $response->getBody();
  1185. $fullContent = '';
  1186. $fullReasoningContent = '';
  1187. $usage = [];
  1188. $buffer = '';
  1189. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1190. // 逐行读取流式响应
  1191. while (!$body->eof()) {
  1192. $chunk = $body->read(1024); // 每次读取 1KB
  1193. $buffer .= $chunk;
  1194. // 按行分割
  1195. $lines = explode("\n", $buffer);
  1196. // 保留最后一个不完整的行
  1197. $buffer = array_pop($lines);
  1198. foreach ($lines as $line) {
  1199. $line = trim($line);
  1200. // 跳过空行
  1201. if (empty($line)) {
  1202. continue;
  1203. }
  1204. // 检查是否是 SSE 数据行
  1205. if (strpos($line, 'data: ') !== 0) {
  1206. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1207. continue;
  1208. }
  1209. $data = substr($line, 6); // 移除 "data: " 前缀
  1210. if ($data === '[DONE]') {
  1211. dLog('deepseek')->info('收到结束标记');
  1212. break 2; // 跳出两层循环
  1213. }
  1214. try {
  1215. $json = json_decode($data, true);
  1216. if (json_last_error() !== JSON_ERROR_NONE) {
  1217. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1218. continue;
  1219. }
  1220. if (isset($json['choices'][0]['delta'])) {
  1221. $delta = $json['choices'][0]['delta'];
  1222. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1223. if (isset($delta['reasoning_content'])) {
  1224. $fullReasoningContent .= $delta['reasoning_content'];
  1225. yield [
  1226. 'type' => 'reasoning',
  1227. 'content' => $delta['reasoning_content'],
  1228. 'full_reasoning' => $fullReasoningContent
  1229. ];
  1230. }
  1231. // 处理最终回答内容
  1232. if (isset($delta['content'])) {
  1233. $fullContent .= $delta['content'];
  1234. yield [
  1235. 'type' => 'content',
  1236. 'content' => $delta['content'],
  1237. ];
  1238. }
  1239. }
  1240. // 获取使用统计信息
  1241. if (isset($json['usage'])) {
  1242. $usage = $json['usage'];
  1243. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1244. }
  1245. } catch (\Exception $e) {
  1246. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1247. continue;
  1248. }
  1249. }
  1250. }
  1251. dLog('deepseek')->info('流式读取完成', [
  1252. 'content_length' => strlen($fullContent),
  1253. 'reasoning_length' => strlen($fullReasoningContent)
  1254. ]);
  1255. yield [
  1256. 'type' => 'done',
  1257. 'full_content' => $fullContent,
  1258. 'full_reasoning' => $fullReasoningContent,
  1259. 'usage' => $usage
  1260. ];
  1261. }
  1262. /**
  1263. * GPT 重试次数(env 可配置,默认 5 次)
  1264. */
  1265. private function gptRetryTimes()
  1266. {
  1267. return (int)env('GPT_RETRY_TIMES', 5);
  1268. }
  1269. /**
  1270. * GPT 重试间隔秒数(env 可配置,默认 10 秒)
  1271. */
  1272. private function gptRetryInterval()
  1273. {
  1274. return (int)env('GPT_RETRY_INTERVAL', 10);
  1275. }
  1276. /**
  1277. * 判断 GPT 请求异常是否可重试
  1278. * 仅连接失败/超时等传输层异常、5xx、429 可重试;其余 4xx(401/400 等)不重试
  1279. */
  1280. private function isGptRetryableException(\Exception $e)
  1281. {
  1282. if (!($e instanceof \GuzzleHttp\Exception\GuzzleException)) {
  1283. return false;
  1284. }
  1285. if ($e instanceof \GuzzleHttp\Exception\BadResponseException && $e->getResponse()) {
  1286. $status = $e->getResponse()->getStatusCode();
  1287. return $status >= 500 || $status == 429;
  1288. }
  1289. return true;
  1290. }
  1291. /**
  1292. * GPT 中转站探活:GET /v1/models,5 秒短超时
  1293. * 连接成功(含 401/403/404)视为可用;连接失败/超时/5xx/429 视为不可用
  1294. */
  1295. private function checkGptServiceAvailable()
  1296. {
  1297. $apiKey = env('GPT_54_API_KEY');
  1298. if (empty($apiKey)) {
  1299. return false;
  1300. }
  1301. try {
  1302. $checkClient = new Client(['timeout' => 5, 'verify' => false, 'http_errors' => false]);
  1303. $response = $checkClient->get('https://ai-api.kkidc.com/v1/models', [
  1304. 'headers' => [
  1305. 'Authorization' => 'Bearer ' . $apiKey,
  1306. 'Content-Type' => 'application/json'
  1307. ]
  1308. ]);
  1309. $status = $response->getStatusCode();
  1310. return $status < 500 && $status != 429;
  1311. } catch (\Exception $e) {
  1312. return false;
  1313. }
  1314. }
  1315. /**
  1316. * 探活并重试:最多重试 gptRetryTimes() 次,间隔 gptRetryInterval() 秒
  1317. * 全部失败抛出友好错误
  1318. */
  1319. private function ensureGptServiceAvailable()
  1320. {
  1321. $maxRetries = $this->gptRetryTimes();
  1322. $interval = $this->gptRetryInterval();
  1323. for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
  1324. if ($this->checkGptServiceAvailable()) {
  1325. return;
  1326. }
  1327. if ($attempt < $maxRetries) {
  1328. dLog('deepseek')->warning('GPT 中转站探活失败,准备重试', [
  1329. 'retry' => $attempt + 1,
  1330. 'max_retries' => $maxRetries
  1331. ]);
  1332. sleep($interval);
  1333. }
  1334. }
  1335. dLog('deepseek')->error('GPT 中转站探活失败,重试次数已用完');
  1336. logDB('deepseek', 'error', 'GPT 中转站服务不可用', [
  1337. 'max_retries' => $maxRetries,
  1338. 'interval' => $interval
  1339. ]);
  1340. Utils::throwError('20003:GPT 中转站服务暂时不可用,请稍后重试');
  1341. }
  1342. /**
  1343. * GPT 流式输出处理方法
  1344. *
  1345. * @param array $post_data GPT API请求参数
  1346. * @return \Generator 返回生成器,用于流式输出
  1347. */
  1348. private function gpt54StreamResponse($post_data) {
  1349. $apiKey = env('GPT_54_API_KEY');
  1350. if (empty($apiKey)) {
  1351. Utils::throwError('20003:GPT API Key未配置');
  1352. }
  1353. // 先探活,服务不可用时自动重试
  1354. $this->ensureGptServiceAvailable();
  1355. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1356. $headers = [
  1357. 'Authorization' => 'Bearer ' . $apiKey,
  1358. 'Content-Type' => 'application/json'
  1359. ];
  1360. // 移除 thinking 参数,GPT-5.4 不支持
  1361. if (isset($post_data['thinking'])) {
  1362. unset($post_data['thinking']);
  1363. }
  1364. if (isset($post_data['reasoning_effort'])) {
  1365. unset($post_data['reasoning_effort']);
  1366. }
  1367. $post_data['max_completion_tokens'] = 100000;
  1368. // 流式请求显式声明返回 usage(在最后一个 chunk 中返回)
  1369. $post_data['stream_options'] = ['include_usage' => true];
  1370. $maxRetries = $this->gptRetryTimes();
  1371. $interval = $this->gptRetryInterval();
  1372. $attempt = 0;
  1373. while (true) {
  1374. $fullContent = '';
  1375. $usage = [];
  1376. $buffer = '';
  1377. try {
  1378. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  1379. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  1380. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  1381. 'json' => $post_data,
  1382. 'headers' => $headers,
  1383. 'stream' => true // 启用流式响应
  1384. ]);
  1385. $body = $response->getBody();
  1386. dLog('deepseek')->info('开始读取 GPT 流式响应');
  1387. // 逐行读取流式响应
  1388. while (!$body->eof()) {
  1389. $chunk = $body->read(1024); // 每次读取 1KB
  1390. $buffer .= $chunk;
  1391. // 按行分割
  1392. $lines = explode("\n", $buffer);
  1393. // 保留最后一个不完整的行
  1394. $buffer = array_pop($lines);
  1395. foreach ($lines as $line) {
  1396. $line = trim($line);
  1397. // 跳过空行
  1398. if (empty($line)) {
  1399. continue;
  1400. }
  1401. // 检查是否是 SSE 数据行
  1402. if (strpos($line, 'data: ') !== 0) {
  1403. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1404. continue;
  1405. }
  1406. $data = substr($line, 6); // 移除 "data: " 前缀
  1407. if ($data === '[DONE]') {
  1408. dLog('deepseek')->info('收到结束标记');
  1409. break 2; // 跳出 foreach 和流读取循环
  1410. }
  1411. try {
  1412. $json = json_decode($data, true);
  1413. if (json_last_error() !== JSON_ERROR_NONE) {
  1414. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1415. continue;
  1416. }
  1417. if (isset($json['choices'][0]['delta'])) {
  1418. $delta = $json['choices'][0]['delta'];
  1419. // 处理回答内容
  1420. if (isset($delta['content'])) {
  1421. $fullContent .= $delta['content'];
  1422. yield [
  1423. 'type' => 'content',
  1424. 'content' => $delta['content'],
  1425. ];
  1426. }
  1427. }
  1428. // 获取使用统计信息
  1429. if (isset($json['usage'])) {
  1430. $usage = $json['usage'];
  1431. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1432. }
  1433. } catch (\Exception $e) {
  1434. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1435. continue;
  1436. }
  1437. }
  1438. }
  1439. dLog('deepseek')->info('流式读取完成', [
  1440. 'content_length' => strlen($fullContent)
  1441. ]);
  1442. yield [
  1443. 'type' => 'done',
  1444. 'full_content' => $fullContent,
  1445. 'full_reasoning' => '',
  1446. 'usage' => $usage
  1447. ];
  1448. return;
  1449. } catch (\Exception $e) {
  1450. // 已输出内容不重试(避免重复);非可重试异常不重试;重试次数用完则抛出
  1451. if (!empty($fullContent) || !$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  1452. dLog('deepseek')->error('GPT 流式请求失败: ' . $e->getMessage());
  1453. logDB('deepseek', 'error', 'GPT 流式请求失败', ['error' => $e->getMessage()]);
  1454. throw $e;
  1455. }
  1456. dLog('deepseek')->warning('GPT 流式请求失败,准备重试', [
  1457. 'retry' => $attempt + 1,
  1458. 'max_retries' => $maxRetries,
  1459. 'error' => $e->getMessage()
  1460. ]);
  1461. sleep($interval);
  1462. $attempt++;
  1463. }
  1464. }
  1465. }
  1466. // 与推理模型对话
  1467. public function chatWithReasoner($data) {
  1468. $content = getProp($data, 'content');
  1469. $model = getProp($data, 'model', 'r1');
  1470. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1471. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1472. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1473. if ($model == 'r1') {
  1474. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  1475. $thinkingMode = 'disabled';
  1476. } else {
  1477. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  1478. $thinkingMode = 'disabled';
  1479. }
  1480. // 获取可选情感(根据音色可支持情感选)
  1481. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  1482. $emotion_list = [];
  1483. foreach ($timbre_emotion as $emotion) {
  1484. $tmp = explode(',', $emotion);
  1485. $emotion_list = array_merge($emotion_list, $tmp);
  1486. }
  1487. $emotion_list = array_unique($emotion_list);
  1488. $emotion_str = implode('、', $emotion_list);
  1489. // // 获取可选情感
  1490. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  1491. // $emotion_str = implode('、', $emotion_list);
  1492. // 是否启用情感
  1493. $enable_emotion = getProp($data, 'enable_emotion', 0);
  1494. if ($enable_emotion) {
  1495. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  1496. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1497. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  1498. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  1499. }else {
  1500. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  1501. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1502. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  1503. }
  1504. $messages = [
  1505. [
  1506. 'role' => 'system',
  1507. 'content' => $sys_content
  1508. ],
  1509. [
  1510. 'role' => 'user',
  1511. 'content' => $content
  1512. ]
  1513. ];
  1514. $post_data = [
  1515. 'model' => $model,
  1516. 'messages' => $messages,
  1517. // 'max_tokens' => 8192,
  1518. 'temperature' => 1,
  1519. 'frequency_penalty' => 0,
  1520. 'presence_penalty' => 0,
  1521. 'thinking' => ['type' => $thinkingMode],
  1522. 'response_format' => [
  1523. 'type' => 'text'
  1524. ],
  1525. 'stream' => false
  1526. ];
  1527. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1528. // 根据模型类型选择调用方法
  1529. $fullContent = '';
  1530. $usage = [];
  1531. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1532. // DeepSeek 官方模型使用 DeepSeek API
  1533. $chatResult = $this->chatOnly($post_data);
  1534. } else if (in_array($model, $this->gpt_text_models)) {
  1535. // GPT-5.4 模型使用 TokenRouter API
  1536. $chatResult = $this->gpt54ChatOnly($post_data);
  1537. } else {
  1538. // 其他模型使用火山引擎API
  1539. $chatResult = $this->volcEngineChatCompletion($post_data);
  1540. }
  1541. if (is_array($chatResult)) {
  1542. $fullContent = $chatResult['fullContent'];
  1543. $usage = $chatResult['usage'];
  1544. }
  1545. // 处理获取到的剧本数据
  1546. $script_content = handleScriptWords($fullContent, $enable_emotion);
  1547. $result = [
  1548. 'origin_content' => $fullContent,
  1549. 'roles' => getProp($script_content, 'roles'),
  1550. 'words' => getProp($script_content, 'words'),
  1551. ];
  1552. return $result;
  1553. }
  1554. public function resetParagraphAudio($data) {
  1555. $bid = getProp($data, 'bid');
  1556. $cid = getProp($data, 'cid');
  1557. $version_id = getProp($data, 'version_id');
  1558. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  1559. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  1560. 'generate_status' => '待制作',
  1561. 'updated_at' => date('Y-m-d H:i:s')
  1562. ]);
  1563. }
  1564. public function saveParagraphAudio($data) {
  1565. $bid = getProp($data, 'bid');
  1566. $cid = getProp($data, 'cid');
  1567. $version_id = getProp($data, 'version_id');
  1568. $sequence = getProp($data, 'sequence');
  1569. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  1570. // 获取所有情感
  1571. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1572. $emotion_list = array_flip($emotion_list);
  1573. // 获取音色支持情感
  1574. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  1575. $timbre_emotion = explode(',', $timbre_emotion);
  1576. $emotion = getProp($data, 'emotion');
  1577. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  1578. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  1579. $list = [
  1580. 'bid' => $bid,
  1581. 'cid' => $cid,
  1582. 'version_id' => $version_id,
  1583. 'sequence' => $sequence,
  1584. 'role' => getProp($data, 'role'),
  1585. 'gender' => getProp($data, 'gender'),
  1586. 'text' => trim(getProp($data, 'text')),
  1587. 'emotion' => $emotion,
  1588. 'emotion_type' => $emotion_type,
  1589. 'voice_type' => getProp($data, 'voice_type'),
  1590. 'voice_name' => getProp($data, 'voice_name'),
  1591. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  1592. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  1593. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  1594. 'pitch' => getProp($data, 'pitch', 0),
  1595. // 'paragraph_audio_url' => '',
  1596. 'generate_status' => '制作中',
  1597. 'error_msg' => '',
  1598. 'updated_at' => date('Y-m-d H:i:s')
  1599. ];
  1600. $continue = false;
  1601. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  1602. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  1603. $list['generate_status'] = '制作成功';
  1604. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1605. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  1606. $continue = true;
  1607. }
  1608. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  1609. if ($id) {
  1610. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  1611. }else {
  1612. $list['created_at'] = date('Y-m-d H:i:s');
  1613. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  1614. $boolen = $id ? true : false;
  1615. }
  1616. // 如果更新成功则加入查询队列
  1617. if ($boolen) {
  1618. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  1619. Redis::sadd($redis_key, $id);
  1620. }
  1621. if ($boolen && !$continue) {
  1622. $boolen = false;
  1623. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1624. // 根据ID通过API通知合成音频
  1625. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  1626. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  1627. $response = $result->getBody()->getContents();
  1628. $response_arr = json_decode($response, true);
  1629. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1630. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1631. Log::info('通知火山生成段落音频失败: '.$error_msg);
  1632. Utils::throwError('20003:通知火山生成段落音频失败');
  1633. }
  1634. $boolen = true;
  1635. }
  1636. return $boolen;
  1637. }
  1638. public function insertAudioEffect($data) {
  1639. $audio_id = getProp($data, 'audio_id');
  1640. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1641. $bid = getProp($chapter_audio, 'bid');
  1642. $version_id = getProp($chapter_audio, 'version_id');
  1643. $cid = getProp($chapter_audio, 'cid');
  1644. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1645. $audio_effect_json = getProp($data, 'audio_effect_json');
  1646. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  1647. try {
  1648. DB::beginTransaction();
  1649. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1650. if (!$count) {
  1651. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1652. }else {
  1653. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1654. }
  1655. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1656. 'audio_effect_status' => '添加中',
  1657. 'audio_effect_json' => $audio_effect_json,
  1658. 'updated_at' => date('Y-m-d H:i:s')
  1659. ]);
  1660. if (!$boolen1) {
  1661. DB::rollBack();
  1662. Utils::throwError('20003:更新生成数据失败');
  1663. }
  1664. $id = DB::table('mp_audio_tasks')->insertGetId([
  1665. 'audio_id' => $audio_id,
  1666. 'generate_status' => '执行中',
  1667. 'generate_json' => json_encode([], 256),
  1668. 'bid' => $bid,
  1669. 'book_name' => getProp($chapter_audio, 'book_name'),
  1670. 'version_id' => $version_id,
  1671. 'version_name' => getProp($chapter_audio, 'version_name'),
  1672. 'cid' => $cid,
  1673. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1674. 'task_name' => $task_name,
  1675. 'created_at' => date('Y-m-d H:i:s'),
  1676. 'updated_at' => date('Y-m-d H:i:s')
  1677. ]);
  1678. if (!$id) {
  1679. DB::rollBack();
  1680. Utils::throwError('20003:创建任务失败');
  1681. }
  1682. }catch (\Exception $e) {
  1683. DB::rollBack();
  1684. Utils::throwError('20003:'.$e->getMessage());
  1685. }
  1686. DB::commit();
  1687. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1688. // 根据ID通过API通知合成音频
  1689. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1690. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1691. $response = $result->getBody()->getContents();
  1692. $response_arr = json_decode($response, true);
  1693. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1694. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1695. Log::info('通知火山插入音效失败: '.$error_msg);
  1696. Utils::throwError('20003:通知火山插入音效失败');
  1697. }
  1698. return true;
  1699. }
  1700. public function insertBgm($data) {
  1701. $audio_id = getProp($data, 'audio_id');
  1702. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1703. $bid = getProp($chapter_audio, 'bid');
  1704. $version_id = getProp($chapter_audio, 'version_id');
  1705. $cid = getProp($chapter_audio, 'cid');
  1706. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1707. $bgm_json = getProp($data, 'bgm_json');
  1708. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1709. if (!$bgm_json) {
  1710. $bgm_json = getProp($data, 'audio_effect_json');
  1711. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1712. }
  1713. try {
  1714. DB::beginTransaction();
  1715. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1716. if (!$count) {
  1717. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1718. }else {
  1719. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1720. }
  1721. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1722. 'bgm_status' => '添加中',
  1723. 'bgm_json' => $bgm_json,
  1724. 'updated_at' => date('Y-m-d H:i:s')
  1725. ]);
  1726. if (!$boolen1) {
  1727. DB::rollBack();
  1728. Utils::throwError('20003:更新生成数据失败');
  1729. }
  1730. $id = DB::table('mp_audio_tasks')->insertGetId([
  1731. 'audio_id' => $audio_id,
  1732. 'generate_status' => '执行中',
  1733. 'generate_json' => json_encode([], 256),
  1734. 'bid' => $bid,
  1735. 'book_name' => getProp($chapter_audio, 'book_name'),
  1736. 'version_id' => $version_id,
  1737. 'version_name' => getProp($chapter_audio, 'version_name'),
  1738. 'cid' => $cid,
  1739. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1740. 'task_name' => $task_name,
  1741. 'created_at' => date('Y-m-d H:i:s'),
  1742. 'updated_at' => date('Y-m-d H:i:s')
  1743. ]);
  1744. if (!$id) {
  1745. DB::rollBack();
  1746. Utils::throwError('20003:创建任务失败');
  1747. }
  1748. }catch (\Exception $e) {
  1749. DB::rollBack();
  1750. Utils::throwError('20003:'.$e->getMessage());
  1751. }
  1752. DB::commit();
  1753. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1754. // 根据ID通过API通知合成音频
  1755. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1756. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1757. $response = $result->getBody()->getContents();
  1758. $response_arr = json_decode($response, true);
  1759. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1760. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1761. Log::info('通知火山插入bgm失败: '.$error_msg);
  1762. Utils::throwError('20003:通知火山插入bgm失败');
  1763. }
  1764. return true;
  1765. }
  1766. public function getParagraphAudios($data) {
  1767. $bid = getProp($data, 'bid');
  1768. $cid = getProp($data, 'cid');
  1769. $version_id = getProp($data, 'version_id');
  1770. $sequence = getProp($data, 'sequence');
  1771. // 获取已生成的音频
  1772. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  1773. if ($sequence) $query->where('sequence', $sequence);
  1774. $paragraph_audios = $query->orderBy('sequence')->get();
  1775. $result = [];
  1776. foreach($paragraph_audios as $item) {
  1777. $result[] = [
  1778. 'sequence' => getProp($item, 'sequence'),
  1779. 'role' => getProp($item, 'role'),
  1780. 'gender' => getProp($item, 'gender'),
  1781. 'text' => trim(getProp($item, 'text')),
  1782. 'emotion' => getProp($item, 'emotion'),
  1783. 'emotion_type' => getProp($item, 'emotion_type'),
  1784. 'voice_type' => getProp($item, 'voice_type'),
  1785. 'voice_name' => getProp($item, 'voice_name'),
  1786. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1787. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1788. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1789. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1790. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  1791. ];
  1792. }
  1793. return $result;
  1794. }
  1795. // 新增合成任务
  1796. public function addGenerateTask($data) {
  1797. $bid = getProp($data, 'bid');
  1798. $cid = getProp($data, 'cid');
  1799. $version_id = getProp($data, 'version_id');
  1800. $generate_json = getProp($data, 'generate_json');
  1801. // 获取已生成的音频
  1802. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  1803. $paragraph_list = [];
  1804. foreach($paragraph_audios as $item) {
  1805. $paragraph_list[getProp($item, 'sequence')] = [
  1806. 'role' => getProp($item, 'role'),
  1807. 'gender' => getProp($item, 'gender'),
  1808. 'text' => trim(getProp($item, 'text')),
  1809. 'emotion' => getProp($item, 'emotion'),
  1810. 'emotion_type' => getProp($item, 'emotion_type'),
  1811. 'voice_type' => getProp($item, 'voice_type'),
  1812. 'voice_name' => getProp($item, 'voice_name'),
  1813. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1814. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1815. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1816. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1817. ];
  1818. }
  1819. // 更新角色-音色信息
  1820. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  1821. $existed_role_info = json_decode($existed_role_info, true);
  1822. if (!$existed_role_info) $existed_role_info = [];
  1823. // 获取情感信息
  1824. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1825. $emotion_list = array_flip($emotion_list);
  1826. // 获取音色对应情感组
  1827. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  1828. $timbre_emotion_list = [];
  1829. foreach($timbre_emotions as $item) {
  1830. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  1831. }
  1832. // 构造生成音频的json
  1833. $words = json_decode($generate_json, true);
  1834. // 最终合成前的参数组
  1835. $mp_chapter_paragraph_audios = [];
  1836. $sequence = 1;
  1837. $complete_paragraph_sequences = [];
  1838. foreach($words as &$word) {
  1839. 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:参数格式有误');
  1840. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  1841. $role = getProp($word, 'role');
  1842. $word['gender'] = (int)$word['gender'];
  1843. // 判断音色对应情感是否支持,不支持则调整为中性
  1844. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  1845. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  1846. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  1847. if (isset($emotion_list[getProp($word, 'emotion')])) {
  1848. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  1849. }else {
  1850. $word['emotion'] = '中性';
  1851. $word['emotion_type'] = 'neutral';
  1852. }
  1853. $existed_role_info[$role] = [
  1854. 'timbre_type' => $word['voice_type'],
  1855. 'timbre_name' => $word['voice_name'],
  1856. 'emotion' => $word['emotion'],
  1857. 'emotion_type' => $word['emotion_type'],
  1858. 'speed_ratio' => $word['speed_ratio'],
  1859. 'loudness_ratio'=> $word['loudness_ratio'],
  1860. 'emotion_scale' => $word['emotion_scale'],
  1861. 'pitch' => $word['pitch']
  1862. ];
  1863. $word['paragraph_audio_url'] = '';
  1864. // 判断生成参数是否相同,相同则直接使用已生成的音频
  1865. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  1866. // 如果音频存在并且参数都未改变则使用已生成的音频
  1867. if (getProp($paragraph, 'paragraph_audio_url')) {
  1868. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  1869. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  1870. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  1871. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  1872. // {
  1873. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1874. // }
  1875. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1876. }
  1877. $tmp = $word;
  1878. // 组装章节分句音频数据
  1879. // $tmp['sequence'] = getProp($word, 'sequence');
  1880. // $tmp['text'] = getProp($word, 'text');
  1881. // $tmp['emotion'] = getProp($word, 'emotion');
  1882. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  1883. // $tmp['voice_name'] = getProp($word, 'voice_name');
  1884. // $tmp['voice_type'] = getProp($word, 'voice_type');
  1885. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  1886. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  1887. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  1888. $tmp['bid'] = $bid;
  1889. $tmp['version_id'] = $version_id;
  1890. $tmp['cid'] = $cid;
  1891. $tmp['sequence'] = $sequence;
  1892. $tmp['created_at'] = date('Y-m-d H:i:s');
  1893. $tmp['updated_at'] = date('Y-m-d H:i:s');
  1894. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  1895. $mp_chapter_paragraph_audios[] = $tmp;
  1896. $complete_paragraph_sequences[] = $sequence;
  1897. $sequence++;
  1898. }
  1899. $generate_json = json_encode($words, 256);
  1900. // 判断是否有未生成字幕的段落
  1901. $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();
  1902. if ($no_subtitle_sequences) {
  1903. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  1904. }
  1905. try {
  1906. DB::beginTransaction();
  1907. $role_info = json_encode($existed_role_info, 256);
  1908. $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')]);
  1909. if (!$boolen) {
  1910. DB::rollBack();
  1911. Utils::throwError('20003:更新角色信息失败');
  1912. }
  1913. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  1914. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  1915. if (!$count) {
  1916. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1917. }else {
  1918. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1919. }
  1920. $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')]);
  1921. if (!$boolen1) {
  1922. DB::rollBack();
  1923. Utils::throwError('20003:更新生成数据失败');
  1924. }
  1925. $id = DB::table('mp_audio_tasks')->insertGetId([
  1926. 'audio_id' => getProp($chapter_audio, 'id'),
  1927. 'generate_status' => '执行中',
  1928. 'generate_json' => $generate_json,
  1929. 'bid' => $bid,
  1930. 'book_name' => getProp($chapter_audio, 'book_name'),
  1931. 'version_id' => $version_id,
  1932. 'version_name' => getProp($chapter_audio, 'version_name'),
  1933. 'cid' => $cid,
  1934. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1935. 'task_name' => $task_name,
  1936. 'created_at' => date('Y-m-d H:i:s'),
  1937. 'updated_at' => date('Y-m-d H:i:s')
  1938. ]);
  1939. if (!$id) {
  1940. DB::rollBack();
  1941. Utils::throwError('20003:创建任务失败');
  1942. }
  1943. // 删除不在段落序号范围内的其他数据
  1944. if ($complete_paragraph_sequences) {
  1945. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  1946. }
  1947. // // 删除章节分句音频数据并重新插入
  1948. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  1949. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  1950. // if (!$boolen3) {
  1951. // DB::rollBack();
  1952. // Utils::throwError('20003:更新章节分句音频失败');
  1953. // }
  1954. } catch (\Exception $e) {
  1955. DB::rollBack();
  1956. Utils::throwError('20003:'.$e->getMessage());
  1957. }
  1958. DB::commit();
  1959. // 通知火山生成音频
  1960. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1961. // 根据ID通过API通知合成音频
  1962. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  1963. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  1964. $response = $result->getBody()->getContents();
  1965. $response_arr = json_decode($response, true);
  1966. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1967. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1968. Log::info('通知火山生成音频失败: '.$error_msg);
  1969. Utils::throwError('20003:通知火山生成音频失败');
  1970. }
  1971. return true;
  1972. }
  1973. public function timbreList($data) {
  1974. $gender = getProp($data, 'gender');
  1975. $timbre_name = getProp($data, 'voice_name');
  1976. $category_id = getProp($data, 'category_id');
  1977. $age_stage = getProp($data, 'age_stage');
  1978. $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');
  1979. if ($gender) {
  1980. $query->where('gender', $gender);
  1981. }
  1982. if ($timbre_name) {
  1983. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  1984. }
  1985. if ($category_id) {
  1986. $query->where(function ($query) use ($category_id) {
  1987. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  1988. });
  1989. }
  1990. if ($age_stage) {
  1991. $query->where('age_stage', $age_stage);
  1992. }
  1993. $list = $query->get()->map(function ($value) {
  1994. $value = (array)$value;
  1995. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  1996. return $value;
  1997. })->toArray();
  1998. return $list;
  1999. }
  2000. // 生成火山临时token
  2001. public function setStsToken() {
  2002. // ************* 配置参数 *************
  2003. $method = 'GET';
  2004. $service = 'sts';
  2005. $host = 'open.volcengineapi.com';
  2006. $region = env('VOLC_REGION');
  2007. $endpoint = 'https://open.volcengineapi.com';
  2008. // $endpoint = 'https://tos-cn-beijing.volces.com';
  2009. $access_key = env('VOLC_AK');
  2010. $secret_key = env('VOLC_SK');
  2011. // 获取缓存中的token,如果没有则请求接口
  2012. $token = Redis::get('volc_sts_token');
  2013. if (!$token) {
  2014. // 查询参数
  2015. $query_parameters = [
  2016. 'Action' => 'AssumeRole',
  2017. 'RoleSessionName' => 'user@zw',
  2018. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  2019. 'Version' => '2018-01-01'
  2020. ];
  2021. // 生成URL编码的查询字符串
  2022. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  2023. // 获取签名头信息
  2024. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  2025. // 构建完整URL
  2026. $request_url = $endpoint . '?' . $request_parameters;
  2027. $client = new Client(['verify' => false]);
  2028. $response = $client->get($request_url, ['headers' => $headers]);
  2029. $response_arr = json_decode($response->getBody()->getContents(), true);
  2030. $result = [
  2031. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  2032. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  2033. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  2034. 'Region' => env('VOLC_REGION'),
  2035. 'Endpoint' => env('VOLC_END_POINT'),
  2036. 'Bucket' => env('VOLC_BUCKET'),
  2037. ];
  2038. // 缓存token
  2039. Redis::setex('volc_sts_token', 3000, json_encode($result));
  2040. return $result;
  2041. } else {
  2042. return json_decode($token, true);
  2043. }
  2044. // $response = $response['Response'];
  2045. // $access_key = $response['Credentials']['AccessKeyId'];
  2046. // $secret_key = $response['Credentials']['AccessKeySecret'];
  2047. // $security_token = $response['Credentials']['SecurityToken'];
  2048. // $expiration = $response['Credentials']['Expiration'];
  2049. // dd($response_arr);
  2050. }
  2051. public function emotionGroups($data) {
  2052. $id = getProp($data, 'group_id');
  2053. $group_name = getProp($data, 'group_name');
  2054. $voice_type = getProp($data, 'voice_type');
  2055. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  2056. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  2057. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  2058. if ($group_name) {
  2059. $query->where('group_name', 'like', "%{$group_name}%");
  2060. }
  2061. if ($id) {
  2062. $query->where('id', $id);
  2063. }
  2064. if ($voice_type) {
  2065. $query->where('voice_type', $voice_type);
  2066. }
  2067. return $query->orderBy('id')->get()->map(function ($value) {
  2068. return (array)$value;
  2069. })->toArray();
  2070. }
  2071. private function sign($key, $msg) {
  2072. return hash_hmac('sha256', $msg, $key, true);
  2073. }
  2074. // 生成签名密钥
  2075. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  2076. $kDate = $this->sign($key, $dateStamp);
  2077. $kRegion = $this->sign($kDate, $regionName);
  2078. $kService = $this->sign($kRegion, $serviceName);
  2079. $kSigning = $this->sign($kService, 'request');
  2080. return $kSigning;
  2081. }
  2082. // 获取签名头信息
  2083. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  2084. $contenttype = 'application/x-www-form-urlencoded';
  2085. $accept = 'application/json';
  2086. // 获取当前UTC时间
  2087. $t = new DateTime('now', new DateTimeZone('UTC'));
  2088. $xdate = $t->format('Ymd\THis\Z');
  2089. $datestamp = $t->format('Ymd');
  2090. // 1. 拼接规范请求串
  2091. $canonical_uri = '/';
  2092. $canonical_querystring = $request_parameters;
  2093. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  2094. $signed_headers = 'content-type;host;x-date';
  2095. // 空请求体的SHA256哈希
  2096. $payload_hash = hash('sha256', '');
  2097. $canonical_request = implode("\n", [
  2098. $method,
  2099. $canonical_uri,
  2100. $canonical_querystring,
  2101. $canonical_headers,
  2102. $signed_headers,
  2103. $payload_hash
  2104. ]);
  2105. // 2. 拼接待签名字符串
  2106. $algorithm = 'HMAC-SHA256';
  2107. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  2108. $hashed_canonical_request = hash('sha256', $canonical_request);
  2109. $string_to_sign = implode("\n", [
  2110. $algorithm,
  2111. $xdate,
  2112. $credential_scope,
  2113. $hashed_canonical_request
  2114. ]);
  2115. // 3. 计算签名
  2116. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  2117. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  2118. // 4. 添加签名到请求头
  2119. $authorization_header = sprintf(
  2120. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  2121. $algorithm,
  2122. $access_key,
  2123. $credential_scope,
  2124. $signed_headers,
  2125. $signature
  2126. );
  2127. return [
  2128. 'Accept' => $accept,
  2129. 'Content-Type' => $contenttype,
  2130. 'X-Date' => $xdate,
  2131. 'Authorization' => $authorization_header
  2132. ];
  2133. }
  2134. // 文字合成语音(火山引擎)
  2135. public function tts($data) {
  2136. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  2137. $headers = [
  2138. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  2139. 'Content-Type' => 'application/json; charset=UTF-8'
  2140. ];
  2141. $post_data = [
  2142. 'app' => [
  2143. 'appid' => env('VOLC_APPID'),
  2144. 'token' => env('VOLC_TOKEN'),
  2145. 'cluster' => 'volcano_tts'
  2146. ],
  2147. 'user' => [
  2148. 'uid' => 'mp_audio'
  2149. ],
  2150. // 'audio' => [
  2151. // 'voice_type' =>
  2152. // ],
  2153. ];
  2154. }
  2155. public function scriptList($data) {
  2156. $uid = Site::getUid();
  2157. $script_id = getProp($data, 'script_id');
  2158. $script_name = getProp($data, 'script_name');
  2159. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  2160. if ($script_id) {
  2161. $query->where('id', $script_id);
  2162. }
  2163. if ($script_name) {
  2164. $query->where('script_name', 'like', "%{$script_name}%");
  2165. }
  2166. return $query->orderBy('created_at', 'desc')->paginate(12);
  2167. }
  2168. public function scripts($data) {
  2169. $uid = Site::getUid();
  2170. $script_id = getProp($data, 'script_id');
  2171. $script_name = getProp($data, 'script_name');
  2172. $is_products = getProp($data, 'is_products');
  2173. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  2174. if ($script_id) {
  2175. $query->where('id', $script_id);
  2176. }
  2177. if ($is_products !== '') {
  2178. $query->where('is_products', $is_products);
  2179. }
  2180. if ($script_name) {
  2181. $query->where('script_name', 'like', "%{$script_name}%");
  2182. }
  2183. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  2184. return (array)$value;
  2185. })->toArray();
  2186. }
  2187. public function scriptInfo($data) {
  2188. $uid = Site::getUid();
  2189. $script_id = getProp($data, 'script_id');
  2190. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  2191. // ->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();
  2192. ->selectRaw('id as script_id, script_name')->first();
  2193. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2194. $script = (array)$script;
  2195. // 获取分集组信息
  2196. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  2197. ->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')
  2198. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  2199. $value = (array)$value;
  2200. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  2201. return (array)$value;
  2202. })->toArray();
  2203. $script['group'] = $groups;
  2204. return $script;
  2205. }
  2206. public function createScript($data) {
  2207. $script_name = getProp($data, 'script_name');
  2208. $uid = Site::getUid(); // 获取当前用户ID
  2209. $cpid = Site::getCpid(); // 获取当前公司组ID
  2210. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  2211. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  2212. $script_name .= '_'.date('YmdHis');
  2213. }
  2214. return DB::table('mp_scripts')->insertGetId([
  2215. 'script_name' => $script_name,
  2216. 'user_id' => $uid,
  2217. 'cpid' => $cpid,
  2218. 'created_at' => date('Y-m-d H:i:s'),
  2219. 'updated_at' => date('Y-m-d H:i:s')
  2220. ]);
  2221. }
  2222. public function editScript($data) {
  2223. $script_id = getProp($data, 'script_id');
  2224. $script_name = getProp($data, 'script_name');
  2225. $uid = Site::getUid(); // 获取当前用户ID
  2226. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  2227. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  2228. if ($id && (int)$id !== (int)$script_id) {
  2229. $script_name .= '_'.date('YmdHis');
  2230. }
  2231. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2232. 'script_name' => $script_name,
  2233. 'updated_at' => date('Y-m-d H:i:s')
  2234. ]);
  2235. }
  2236. public function delScript($data) {
  2237. $script_id = getProp($data, 'script_id');
  2238. $uid = Site::getUid(); // 获取当前用户ID
  2239. if (!$script_id) Utils::throwError('20003:请选择剧本');
  2240. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2241. 'is_deleted' => 1,
  2242. 'updated_at' => date('Y-m-d H:i:s')
  2243. ]);
  2244. }
  2245. public function createEpisode($data) {
  2246. $script_id = getProp($data, 'script_id');
  2247. $group_name = getProp($data, 'group_name');
  2248. $remark = getProp($data, 'remark');
  2249. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  2250. $uid = Site::getUid(); // 获取当前用户ID
  2251. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  2252. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  2253. $group_name .= '_'.date('YmdHis');
  2254. }
  2255. return DB::table('mp_script_episode_group')->insertGetId([
  2256. 'script_id' => $script_id,
  2257. 'group_name' => $group_name,
  2258. 'user_id' => $uid,
  2259. 'remark' => $remark,
  2260. 'created_at' => date('Y-m-d H:i:s'),
  2261. 'updated_at' => date('Y-m-d H:i:s')
  2262. ]);
  2263. }
  2264. public function editEpisode($data) {
  2265. $group_id = getProp($data, 'group_id');
  2266. $start_episode_number = getProp($data, 'start_episode_number');
  2267. $end_episode_number = getProp($data, 'end_episode_number');
  2268. $group_name = getProp($data, 'group_name');
  2269. $uid = Site::getUid(); // 获取当前用户ID
  2270. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  2271. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  2272. if ($id && (int)$id !== (int)$group_id) {
  2273. $group_name .= '_'.date('YmdHis');
  2274. }
  2275. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2276. 'group_name' => $group_name,
  2277. 'start_episode_number' => $start_episode_number,
  2278. 'end_episode_number' => $end_episode_number,
  2279. 'updated_at' => date('Y-m-d H:i:s')
  2280. ]);
  2281. }
  2282. public function delEpisode($data) {
  2283. $group_id = getProp($data, 'group_id');
  2284. $uid = Site::getUid(); // 获取当前用户ID
  2285. if (!$group_id) Utils::throwError('20003:请选择分集');
  2286. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2287. 'is_deleted' => 1,
  2288. 'updated_at' => date('Y-m-d H:i:s')
  2289. ]);
  2290. }
  2291. /**
  2292. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2293. *
  2294. * @param array $data 包含以下参数:
  2295. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2296. * - question: 用户问题(可选)
  2297. * - model: 使用的模型(r1 或 v3,默认 v3)
  2298. * @return \Generator 返回生成器,用于流式输出
  2299. */
  2300. public function generateEpisodes($data) {
  2301. $script_id = getProp($data, 'script_id');
  2302. $group_id = getProp($data, 'group_id');
  2303. // $file = getProp($data, 'file');
  2304. $file = '';
  2305. $content = getProp($data, 'content', '');
  2306. // $bid = getProp($data, 'bid', 0);
  2307. $bid = 0;
  2308. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2309. if (!$group) {
  2310. Utils::throwError('20003:剧本分集不存在');
  2311. }
  2312. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  2313. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  2314. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  2315. $prompt = getProp($data, 'prompt');
  2316. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  2317. $model = getProp($data, 'model');
  2318. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2319. Utils::throwError('20003:该模型不存在!');
  2320. }
  2321. // 检查是否存在重叠的剧集序号范围
  2322. $exists_groups = DB::table('mp_script_episode_group')
  2323. ->where('script_id', $script_id)
  2324. ->where('id', '<>', $group_id) // 排除当前组
  2325. ->where('is_deleted', 0)
  2326. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2327. // 检查新范围是否与现有范围重叠
  2328. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2329. // 新范围的开始在现有范围内
  2330. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2331. ->where('end_episode_number', '>=', $start_episode_sequence);
  2332. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2333. // 新范围的结束在现有范围内
  2334. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2335. ->where('end_episode_number', '>=', $end_episode_sequence);
  2336. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2337. // 新范围完全包含现有范围
  2338. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2339. ->where('end_episode_number', '<=', $end_episode_sequence);
  2340. });
  2341. })
  2342. ->select('start_episode_number', 'end_episode_number')
  2343. ->get();
  2344. if ($exists_groups->isNotEmpty()) {
  2345. $conflict_ranges = [];
  2346. foreach ($exists_groups as $group) {
  2347. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2348. }
  2349. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2350. }
  2351. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2352. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2353. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2354. if ($model === 'deepseek-chat') {
  2355. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2356. $model = 'deepseek-v4-flash';
  2357. $thinkingMode = 'disabled';
  2358. } elseif ($model === 'deepseek-reasoner') {
  2359. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2360. $model = 'deepseek-v4-flash';
  2361. $thinkingMode = 'enabled';
  2362. }
  2363. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2364. if (!$script) {
  2365. Utils::throwError('20003:剧本不存在');
  2366. }
  2367. $content = getProp($group, 'content');
  2368. if (!$file && !$content && !$bid) {
  2369. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2370. }
  2371. // 提取文件内容
  2372. if ($file) {
  2373. $content = $this->extractFileContent($file);
  2374. if (!$content) {
  2375. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2376. }
  2377. } elseif ($bid) {
  2378. $content = $this->getContentByBid($bid);
  2379. if (!$content) {
  2380. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2381. }
  2382. } elseif ($content) {
  2383. $content = filterContent($content);
  2384. } elseif ($prompt) {
  2385. $content = filterContent($prompt);
  2386. } else {
  2387. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2388. }
  2389. // 构建消息
  2390. $messages = [
  2391. $this->sys_message,
  2392. [
  2393. 'role' => 'user',
  2394. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2395. ]
  2396. ];
  2397. $post_data = [
  2398. 'model' => $model,
  2399. 'messages' => $messages,
  2400. // 'max_tokens' => 8192,
  2401. 'temperature' => 0.7,
  2402. 'frequency_penalty' => 0,
  2403. 'presence_penalty' => 0,
  2404. 'thinking' => ['type' => $thinkingMode],
  2405. 'response_format' => ['type' => 'text'],
  2406. 'stream' => true
  2407. ];
  2408. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2409. // 根据模型类型选择调用方法
  2410. $fullContent = '';
  2411. $fullReasoningContent = '';
  2412. $usage = [];
  2413. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2414. // DeepSeek 官方模型使用 DeepSeek API
  2415. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2416. } else if (in_array($model, $this->gpt_text_models)) {
  2417. // GPT-5.4 模型使用 TokenRouter API
  2418. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2419. } else {
  2420. // 其他模型使用火山引擎API
  2421. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2422. }
  2423. // 处理流式输出
  2424. foreach ($streamGenerator as $chunk) {
  2425. if (isset($chunk['type'])) {
  2426. if ($chunk['type'] === 'done') {
  2427. // 最终结果
  2428. $fullContent = $chunk['full_content'];
  2429. $fullReasoningContent = $chunk['full_reasoning'];
  2430. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2431. } else {
  2432. // 逐块yield数据
  2433. yield $chunk;
  2434. }
  2435. }
  2436. }
  2437. dLog('deepseek')->info('完整内容: '.$fullContent);
  2438. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2439. // 处理完整内容并返回最终结果
  2440. $script_arr = [];
  2441. if ($fullContent) {
  2442. $script_arr = extractScriptContent($fullContent);
  2443. }
  2444. logDB('deepseek', 'info', '解析内容', $script_arr);
  2445. if (!$script_arr['episodes']) {
  2446. Utils::throwError('20003:未生成剧本相关信息');
  2447. // yield [
  2448. // 'type' => 'done',
  2449. // 'script' => $script_arr,
  2450. // 'msg' => '未生成剧本相关信息',
  2451. // 'answer' => $fullContent,
  2452. // 'reasoning' => $fullReasoningContent,
  2453. // 'usage' => $usage
  2454. // ];
  2455. // return ;
  2456. }
  2457. try {
  2458. DB::beginTransaction();
  2459. // // 返回前保存剧本内容
  2460. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2461. // 'content' => $content,
  2462. // 'updated_at' => date('Y-m-d H:i:s')
  2463. // ]);
  2464. // if (!$boolen) {
  2465. // Utils::throwError('20003:保存剧本内容失败');
  2466. // }
  2467. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2468. // 'start_episode_number' => $start_episode_sequence,
  2469. // 'end_episode_number' => $end_episode_sequence,
  2470. // 'updated_at' => date('Y-m-d H:i:s')
  2471. // ]);
  2472. // if (!$boolen1) {
  2473. // Utils::throwError('20003:保存分集失败');
  2474. // }
  2475. $episode_content = '';
  2476. $episodes = [];
  2477. foreach ($script_arr['episodes'] as $item) {
  2478. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  2479. // $episodes[] = [
  2480. // 'script_id' => $script_id,
  2481. // 'episode_number' => $item['episode_number'],
  2482. // 'episode_name' => $item['episode_name'],
  2483. // 'episode_content' => $item['episode_content'],
  2484. // 'created_at' => date('Y-m-d H:i:s'),
  2485. // 'updated_at' => date('Y-m-d H:i:s'),
  2486. // ];
  2487. }
  2488. if ($episode_content) {
  2489. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2490. 'episode_content' => $episode_content,
  2491. 'updated_at' => date('Y-m-d H:i:s')
  2492. ]);
  2493. if (!$boolen2) {
  2494. Utils::throwError('20003:保存分集内容失败');
  2495. }
  2496. }else {
  2497. Utils::throwError('20003:分集剧本解析失败');
  2498. }
  2499. }catch (\Exception $e) {
  2500. DB::rollBack();
  2501. Utils::throwError('20003:'.$e->getMessage());
  2502. }
  2503. DB::commit();
  2504. yield [
  2505. 'type' => 'done',
  2506. 'script' => $script_arr,
  2507. 'episode_content' => $episode_content,
  2508. 'answer' => $fullContent,
  2509. 'reasoning' => $fullReasoningContent,
  2510. 'usage' => $usage
  2511. ];
  2512. }
  2513. public function chatWithFileStream($data) {
  2514. $script_id = getProp($data, 'script_id');
  2515. $group_id = getProp($data, 'group_id');
  2516. $file = getProp($data, 'file');
  2517. $content = getProp($data, 'content', '');
  2518. $bid = getProp($data, 'bid', 0);
  2519. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2520. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2521. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  2522. $prompt = getProp($data, 'prompt');
  2523. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2524. if (!empty($prompt)) {
  2525. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2526. }
  2527. $question = getProp($data, 'question', $baseQuestion);
  2528. $model = getProp($data, 'model');
  2529. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2530. Utils::throwError('20003:该模型不存在!');
  2531. }
  2532. // 检查是否存在重叠的剧集序号范围
  2533. $exists_groups = DB::table('mp_script_episode_group')
  2534. ->where('script_id', $script_id)
  2535. ->where('id', '<>', $group_id)
  2536. ->where('is_deleted', 0)
  2537. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2538. // 检查新范围是否与现有范围重叠
  2539. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2540. // 新范围的开始在现有范围内
  2541. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2542. ->where('end_episode_number', '>=', $start_episode_sequence);
  2543. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2544. // 新范围的结束在现有范围内
  2545. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2546. ->where('end_episode_number', '>=', $end_episode_sequence);
  2547. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2548. // 新范围完全包含现有范围
  2549. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2550. ->where('end_episode_number', '<=', $end_episode_sequence);
  2551. });
  2552. })
  2553. ->select('start_episode_number', 'end_episode_number')
  2554. ->get();
  2555. if ($exists_groups->isNotEmpty()) {
  2556. $conflict_ranges = [];
  2557. foreach ($exists_groups as $group) {
  2558. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2559. }
  2560. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2561. }
  2562. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2563. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2564. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2565. if ($model === 'deepseek-chat') {
  2566. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2567. $model = 'deepseek-v4-flash';
  2568. $thinkingMode = 'disabled';
  2569. } elseif ($model === 'deepseek-reasoner') {
  2570. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2571. $model = 'deepseek-v4-flash';
  2572. $thinkingMode = 'enabled';
  2573. }
  2574. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2575. if (!$script) {
  2576. Utils::throwError('20003:剧本不存在');
  2577. }
  2578. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2579. if (!$group) {
  2580. Utils::throwError('20003:剧本分集不存在');
  2581. }
  2582. if (!$file && !$content && !$bid) {
  2583. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2584. }
  2585. // 提取文件内容
  2586. if ($file) {
  2587. $content = $this->extractFileContent($file);
  2588. if (!$content) {
  2589. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2590. }
  2591. } elseif ($bid) {
  2592. $content = $this->getContentByBid($bid);
  2593. if (!$content) {
  2594. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2595. }
  2596. } elseif ($content) {
  2597. $content = filterContent($content);
  2598. } elseif ($prompt) {
  2599. $content = filterContent($prompt);
  2600. } else {
  2601. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2602. }
  2603. // 构建消息
  2604. $messages = [
  2605. [
  2606. 'role' => 'system',
  2607. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  2608. 强制要求:\n
  2609. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2610. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  2611. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  2612. 普通要求:\n
  2613. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  2614. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  2615. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  2616. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  2617. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  2618. 示例如下:\n
  2619. ###剧本名:西昆仑
  2620. ###故事梗概
  2621. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2622. ###剧本亮点
  2623. 亮点1:绝境奇药,生死一线
  2624. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2625. 亮点2:结拜兄妹,化解尴尬
  2626. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2627. 亮点3:纤发夺命,情愫暗涌
  2628. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2629. ###人物关系
  2630. 阿雪与梁萧之间存在兄妹之情。
  2631. ###核心矛盾
  2632. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2633. ###主体列表
  2634. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2635. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2636. 阴阳球:天地异宝,能化生精气,救人于危难。
  2637. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2638. ###美术风格
  2639. 基础画风风格词:厚涂古风
  2640. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2641. ###场景列表
  2642. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  2643. [
  2644. 'role' => 'user',
  2645. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2646. ]
  2647. ];
  2648. $post_data = [
  2649. 'model' => $model,
  2650. 'messages' => $messages,
  2651. // 'max_tokens' => 8192,
  2652. 'temperature' => 0.7,
  2653. 'frequency_penalty' => 0,
  2654. 'presence_penalty' => 0,
  2655. 'thinking' => ['type' => $thinkingMode],
  2656. 'response_format' => ['type' => 'text'],
  2657. 'stream' => true
  2658. ];
  2659. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2660. // 根据模型类型选择调用方法
  2661. $fullContent = '';
  2662. $fullReasoningContent = '';
  2663. $usage = [];
  2664. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2665. // DeepSeek 官方模型使用 DeepSeek API
  2666. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2667. } else if (in_array($model, $this->gpt_text_models)) {
  2668. // GPT-5.4 模型使用 TokenRouter API
  2669. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2670. } else {
  2671. // 其他模型使用火山引擎API
  2672. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2673. }
  2674. // 处理流式输出
  2675. foreach ($streamGenerator as $chunk) {
  2676. if (isset($chunk['type'])) {
  2677. if ($chunk['type'] === 'done') {
  2678. // 最终结果
  2679. $fullContent = $chunk['full_content'];
  2680. $fullReasoningContent = $chunk['full_reasoning'];
  2681. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2682. } else {
  2683. // 逐块yield数据
  2684. yield $chunk;
  2685. }
  2686. }
  2687. }
  2688. dLog('deepseek')->info('完整内容: '.$fullContent);
  2689. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2690. // 处理完整内容并返回最终结果
  2691. $script_arr = [];
  2692. if ($fullContent) {
  2693. $script_arr = extractScriptContent($fullContent);
  2694. }
  2695. logDB('deepseek', 'info', '解析内容', $script_arr);
  2696. if (!$script_arr['roles']) {
  2697. Utils::throwError('20003:未生成剧本相关信息');
  2698. // yield [
  2699. // 'type' => 'done',
  2700. // 'script' => $script_arr,
  2701. // 'msg' => '未生成剧本相关信息',
  2702. // 'answer' => $fullContent,
  2703. // 'reasoning' => $fullReasoningContent,
  2704. // 'usage' => $usage
  2705. // ];
  2706. }
  2707. try {
  2708. DB::beginTransaction();
  2709. // // 返回前保存剧本内容
  2710. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2711. // 'content' => $content,
  2712. // 'status' => '解析完成',
  2713. // 'updated_at' => date('Y-m-d H:i:s')
  2714. // ]);
  2715. // if (!$boolen) {
  2716. // Utils::throwError('20003:保存剧本内容失败');
  2717. // }
  2718. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2719. 'start_episode_number' => $start_episode_sequence,
  2720. 'end_episode_number' => $end_episode_sequence,
  2721. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2722. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2723. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2724. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2725. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2726. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2727. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2728. 'status' => '解析完成',
  2729. 'content' => $content,
  2730. 'updated_at' => date('Y-m-d H:i:s')
  2731. ]);
  2732. if (!$boolen1) {
  2733. Utils::throwError('20003:保存分集失败');
  2734. }
  2735. // $episodes = [];
  2736. // foreach ($script_arr['episodes'] as $item) {
  2737. // $episodes[] = [
  2738. // 'script_id' => $script_id,
  2739. // 'episode_number' => $item['episode_number'],
  2740. // 'episode_name' => $item['episode_name'],
  2741. // 'episode_content' => $item['episode_content'],
  2742. // 'created_at' => date('Y-m-d H:i:s'),
  2743. // 'updated_at' => date('Y-m-d H:i:s'),
  2744. // ];
  2745. // }
  2746. // if ($episodes) {
  2747. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2748. // if (!$boolen2) {
  2749. // Utils::throwError('20003:保存分集内容失败');
  2750. // }
  2751. // }else {
  2752. // Utils::throwError('20003:分集剧本解析失败');
  2753. // }
  2754. }catch (\Exception $e) {
  2755. DB::rollBack();
  2756. Utils::throwError('20003:'.$e->getMessage());
  2757. }
  2758. DB::commit();
  2759. yield [
  2760. 'type' => 'done',
  2761. 'script' => $script_arr,
  2762. 'answer' => $fullContent,
  2763. 'reasoning' => $fullReasoningContent,
  2764. 'usage' => $usage
  2765. ];
  2766. }
  2767. /**
  2768. * 上传文件识别文字内容并与 DeepSeek 进行对话
  2769. *
  2770. * @param array $data 包含以下参数:
  2771. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2772. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  2773. * - model: 使用的模型(r1 或 v3,默认 v3)
  2774. * @return array
  2775. */
  2776. public function chatWithFile($data) {
  2777. $script_id = getProp($data, 'script_id');
  2778. $file = getProp($data, 'file');
  2779. $content = getProp($data, 'content', '');
  2780. $bid = getProp($data, 'bid', 0);
  2781. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2782. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2783. $prompt = getProp($data, 'prompt');
  2784. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2785. if (!empty($prompt)) {
  2786. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2787. }
  2788. $question = getProp($data, 'question', $baseQuestion);
  2789. // 处理文本模型
  2790. $model = getProp($data, 'model');
  2791. if (!$model) {
  2792. // 用户没有输入,使用默认值
  2793. $model = 'doubao-seed-2-0-mini-260215';
  2794. }
  2795. // 验证模型是否在可用模型表中
  2796. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2797. $model = 'doubao-seed-2-0-mini-260215';
  2798. }
  2799. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2800. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2801. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2802. if ($model === 'deepseek-chat') {
  2803. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2804. $model = 'deepseek-v4-flash';
  2805. $thinkingMode = 'disabled';
  2806. } elseif ($model === 'deepseek-reasoner') {
  2807. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2808. $model = 'deepseek-v4-flash';
  2809. $thinkingMode = 'enabled';
  2810. }
  2811. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2812. if (!$script) {
  2813. Utils::throwError('20003:剧本不存在');
  2814. }
  2815. if (!$file && !$content && !$bid) {
  2816. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2817. }
  2818. // 提取文件内容
  2819. if ($file) {
  2820. $content = $this->extractFileContent($file);
  2821. if (!$content) {
  2822. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2823. }
  2824. } elseif ($bid) {
  2825. $content = $this->getContentByBid($bid);
  2826. if (!$content) {
  2827. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2828. }
  2829. } elseif ($content) {
  2830. $content = filterContent($content);
  2831. } elseif ($prompt) {
  2832. $content = filterContent($prompt);
  2833. } else {
  2834. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2835. }
  2836. // 构建消息
  2837. $messages = [
  2838. $this->sys_message,
  2839. [
  2840. 'role' => 'user',
  2841. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2842. ]
  2843. ];
  2844. $post_data = [
  2845. 'model' => $model,
  2846. 'messages' => $messages,
  2847. // 'max_tokens' => 8192,
  2848. 'temperature' => 0.7,
  2849. 'frequency_penalty' => 0,
  2850. 'presence_penalty' => 0,
  2851. 'thinking' => ['type' => $thinkingMode],
  2852. 'response_format' => ['type' => 'text'],
  2853. 'stream' => false
  2854. ];
  2855. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2856. // 根据模型类型选择调用方法
  2857. $fullContent = '';
  2858. $usage = [];
  2859. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2860. // DeepSeek 官方模型使用 DeepSeek API
  2861. $chatResult = $this->chatOnly($post_data);
  2862. } else if (in_array($model, $this->gpt_text_models)) {
  2863. // GPT-5.4 模型使用 TokenRouter API
  2864. $chatResult = $this->gpt54ChatOnly($post_data);
  2865. } else {
  2866. // 其他模型使用火山引擎API
  2867. $chatResult = $this->volcEngineChatCompletion($post_data);
  2868. }
  2869. if (is_array($chatResult)) {
  2870. $fullContent = $chatResult['fullContent'];
  2871. $usage = $chatResult['usage'];
  2872. }
  2873. $script_arr = [];
  2874. // 处理结果
  2875. if ($fullContent) {
  2876. $script_arr = extractScriptContent($fullContent);
  2877. }
  2878. // 返回前保存剧本内容
  2879. DB::table('mp_scripts')->where('id', $script_id)->update([
  2880. 'content' => $content,
  2881. 'updated_at' => date('Y-m-d H:i:s')
  2882. ]);
  2883. return [
  2884. 'script' => $script_arr,
  2885. 'answer' => $fullContent,
  2886. 'usage' => $usage
  2887. ];
  2888. }
  2889. public function getEpisodeContent($data) {
  2890. $group_id = getProp($data, 'group_id');
  2891. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  2892. }
  2893. public function saveEpisodeContent($data) {
  2894. $script_id = getProp($data, 'script_id');
  2895. $group_id = getProp($data, 'group_id');
  2896. $start_episode_sequence = getProp($data, 'start_episode_number');
  2897. $end_episode_sequence = getProp($data, 'end_episode_number');
  2898. // 检查是否存在重叠的剧集序号范围
  2899. $exists_groups = DB::table('mp_script_episode_group')
  2900. ->where('script_id', $script_id)
  2901. ->where('id', '<>', $group_id) // 排除当前组
  2902. ->where('is_deleted', 0)
  2903. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2904. // 检查新范围是否与现有范围重叠
  2905. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2906. // 新范围的开始在现有范围内
  2907. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2908. ->where('end_episode_number', '>=', $start_episode_sequence);
  2909. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2910. // 新范围的结束在现有范围内
  2911. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2912. ->where('end_episode_number', '>=', $end_episode_sequence);
  2913. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2914. // 新范围完全包含现有范围
  2915. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2916. ->where('end_episode_number', '<=', $end_episode_sequence);
  2917. });
  2918. })
  2919. ->select('start_episode_number', 'end_episode_number')
  2920. ->get();
  2921. if ($exists_groups->isNotEmpty()) {
  2922. $conflict_ranges = [];
  2923. foreach ($exists_groups as $group) {
  2924. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2925. }
  2926. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2927. }
  2928. $episode_content = getProp($data, 'episode_content');
  2929. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  2930. 'content' => $episode_content,
  2931. 'start_episode_number' => $start_episode_sequence,
  2932. 'end_episode_number' => $end_episode_sequence,
  2933. 'updated_at' => date('Y-m-d H:i:s')
  2934. ]);
  2935. $script_arr =getProp($data, 'script', []);
  2936. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  2937. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2938. $script_id = getProp($data, 'script_id');
  2939. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  2940. try {
  2941. DB::beginTransaction();
  2942. $update_data = [
  2943. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2944. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2945. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2946. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2947. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2948. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2949. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2950. 'status' => 3,
  2951. 'start_episode_sequence' => $start_episode_sequence,
  2952. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  2953. 'episode_num' => count($script_arr['episodes']),
  2954. 'updated_at' => date('Y-m-d H:i:s')
  2955. ];
  2956. // 保存剧本内容
  2957. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  2958. if (!$boolen) {
  2959. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  2960. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  2961. Utils::throwError('20003:剧本内容保存失败');
  2962. }
  2963. // 保存分集内容
  2964. // 删除历史分集内容
  2965. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  2966. $episodes = [];
  2967. $sequence = 1;
  2968. foreach ($script_arr['episodes'] as $episode) {
  2969. $segment_number = 1;
  2970. foreach($episode['segments'] as $segment) {
  2971. $episodes[] = [
  2972. 'script_id' => $script_id,
  2973. 'episode_number' => $episode['episode_number'],
  2974. 'title' => $episode['title'],
  2975. // 'content' => $episode['content'],
  2976. 'content' => '',
  2977. 'segment_number' => $segment_number,
  2978. 'segment_content' => $segment['segment_content'],
  2979. 'sequence' => $sequence,
  2980. 'created_at' => date('Y-m-d H:i:s'),
  2981. 'updated_at' => date('Y-m-d H:i:s')
  2982. ];
  2983. $sequence++;
  2984. $segment_number++;
  2985. }
  2986. }
  2987. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2988. if (!$boolen2) {
  2989. dLog('deepseek')->info('分集内容保存失败', $episodes);
  2990. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  2991. Utils::throwError('20003:分集内容保存失败');
  2992. }
  2993. } catch (\Exception $e) {
  2994. DB::rollBack();
  2995. Utils::throwError('20003:'.$e->getMessage());
  2996. }
  2997. DB::commit();
  2998. return true;
  2999. }
  3000. public function getBookContent($data) {
  3001. $bid = getProp($data, 'bid');
  3002. $start_sequence = getProp($data, 'start_sequence');
  3003. $end_sequence = getProp($data, 'end_sequence');
  3004. $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])
  3005. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  3006. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  3007. return $return_content;
  3008. }
  3009. public function exportScript($data) {
  3010. $filename = getProp($data, 'filename');
  3011. $script_id = getProp($data, 'script_id');
  3012. $group_id = getProp($data, 'group_id');
  3013. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  3014. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  3015. if (!$script) Utils::throwError('20003:该剧本不存在!');
  3016. $script = (array)$script;
  3017. // 获取分集组信息
  3018. if ($group_id) {
  3019. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  3020. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  3021. ->get()->map(function($value) {
  3022. return (array)$value;
  3023. })->toArray();
  3024. }else {
  3025. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  3026. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  3027. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  3028. return (array)$value;
  3029. })->toArray();
  3030. }
  3031. if (!$groups) Utils::throwError('20003:分集不存在');
  3032. $script['group'] = $groups;
  3033. $export_type = getProp($data, 'export_type', 'txt');
  3034. // 生成文件名
  3035. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  3036. // 根据导出类型生成不同格式的文件
  3037. switch ($export_type) {
  3038. case 'txt':
  3039. return $this->exportScriptAsTxt($script, $filename);
  3040. case 'pdf':
  3041. return $this->exportScriptAsPdf($script, $filename);
  3042. default:
  3043. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  3044. }
  3045. }
  3046. /**
  3047. * 导出剧本为TXT格式
  3048. */
  3049. private function exportScriptAsTxt($script, $filename) {
  3050. // 构建TXT内容
  3051. $content = $this->buildScriptContent($script);
  3052. // 设置响应头,直接下载
  3053. header('Content-Type: text/plain; charset=utf-8');
  3054. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  3055. header('Content-Length: ' . strlen($content));
  3056. // 输出内容并结束
  3057. echo $content;
  3058. exit();
  3059. }
  3060. /**
  3061. * 导出剧本为PDF格式
  3062. */
  3063. private function exportScriptAsPdf($script, $filename) {
  3064. // 使用HTML转PDF的方式来更好地支持中文
  3065. $htmlContent = $this->buildScriptHtmlForPdf($script);
  3066. // 创建PDF实例
  3067. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  3068. // 设置文档信息
  3069. $pdf->SetCreator('剧本导出系统');
  3070. $pdf->SetAuthor('系统');
  3071. $pdf->SetTitle($script['script_name']);
  3072. $pdf->SetSubject('剧本导出');
  3073. // 设置边距
  3074. $pdf->SetMargins(15, 15, 15);
  3075. $pdf->SetAutoPageBreak(TRUE, 15);
  3076. // 添加页面
  3077. $pdf->AddPage();
  3078. // 注册并使用 simsun.ttf 字体
  3079. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  3080. // 使用HTML内容生成PDF
  3081. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  3082. // 直接输出PDF文件供下载
  3083. header('Content-Type: application/pdf');
  3084. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  3085. // 直接输出PDF内容
  3086. $pdf->Output($filename . '.pdf', 'D');
  3087. exit();
  3088. }
  3089. /**
  3090. * 构建用于PDF的HTML内容
  3091. */
  3092. private function buildScriptHtmlForPdf($script) {
  3093. $html = '<style>
  3094. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  3095. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  3096. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  3097. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  3098. .info { margin-bottom: 8px; }
  3099. .group { margin-bottom: 30px; page-break-inside: avoid; }
  3100. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  3101. .segment { margin-bottom: 10px; margin-left: 20px; }
  3102. .episode-content { white-space: pre-wrap; }
  3103. </style>';
  3104. // 标题
  3105. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  3106. // 处理分组数据
  3107. if (!empty($script['group']) && is_array($script['group'])) {
  3108. $groups = (array)$script['group'];
  3109. foreach ($groups as $group) {
  3110. $html .= '<div class="group">';
  3111. // 分组标题
  3112. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  3113. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  3114. // 故事梗概
  3115. if (!empty($group['intro'])) {
  3116. $html .= '<h3>故事梗概</h3>';
  3117. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  3118. }
  3119. // 剧本亮点
  3120. if (!empty($group['highlights'])) {
  3121. $html .= '<h3>剧本亮点</h3>';
  3122. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  3123. }
  3124. // 人物关系
  3125. if (!empty($group['role_relationship'])) {
  3126. $html .= '<h3>人物关系</h3>';
  3127. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  3128. }
  3129. // 核心矛盾
  3130. if (!empty($group['core_contradiction'])) {
  3131. $html .= '<h3>核心矛盾</h3>';
  3132. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  3133. }
  3134. // 主体列表
  3135. if (!empty($group['roles']) && is_array($group['roles'])) {
  3136. $html .= '<h3>主体列表</h3>';
  3137. $html .= '<ul>';
  3138. foreach ($group['roles'] as $role) {
  3139. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  3140. }
  3141. $html .= '</ul>';
  3142. }
  3143. // 美术风格
  3144. if (!empty($group['art_style'])) {
  3145. $html .= '<h3>美术风格</h3>';
  3146. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  3147. }
  3148. // 场景列表
  3149. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3150. $html .= '<h3>场景列表</h3>';
  3151. $html .= '<ul>';
  3152. foreach ($group['scenes'] as $scene) {
  3153. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  3154. }
  3155. $html .= '</ul>';
  3156. }
  3157. // 分集剧本
  3158. if (!empty($group['episode_content'])) {
  3159. $html .= '<h3>分集剧本</h3>';
  3160. // 去除零宽字符和其他不可见字符
  3161. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  3162. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  3163. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  3164. }
  3165. $html .= '</div>';
  3166. }
  3167. }
  3168. return $html;
  3169. }
  3170. /**
  3171. * 构建PDF内容
  3172. */
  3173. private function buildPdfContent($pdf, $script) {
  3174. // 标题
  3175. $pdf->SetFont('dejavusans', 'B', 18);
  3176. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  3177. $pdf->Ln(5);
  3178. // 基本信息
  3179. $pdf->SetFont('dejavusans', '', 12);
  3180. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  3181. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  3182. $pdf->Ln(5);
  3183. // 剧本简介
  3184. if (!empty($script['intro'])) {
  3185. $pdf->SetFont('dejavusans', 'B', 14);
  3186. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  3187. $pdf->SetFont('dejavusans', '', 12);
  3188. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  3189. $pdf->Ln(3);
  3190. }
  3191. // 亮点
  3192. if (!empty($script['highlights'])) {
  3193. $pdf->SetFont('dejavusans', 'B', 14);
  3194. $pdf->Cell(0, 10, '亮点', 0, 1);
  3195. $pdf->SetFont('dejavusans', '', 12);
  3196. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  3197. $pdf->Ln(3);
  3198. }
  3199. // 核心矛盾
  3200. if (!empty($script['core_contradiction'])) {
  3201. $pdf->SetFont('dejavusans', 'B', 14);
  3202. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  3203. $pdf->SetFont('dejavusans', '', 12);
  3204. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  3205. $pdf->Ln(3);
  3206. }
  3207. // 艺术风格
  3208. if (!empty($script['art_style'])) {
  3209. $pdf->SetFont('dejavusans', 'B', 14);
  3210. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  3211. $pdf->SetFont('dejavusans', '', 12);
  3212. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  3213. $pdf->Ln(3);
  3214. }
  3215. // 备注
  3216. if (!empty($script['remark'])) {
  3217. $pdf->SetFont('dejavusans', 'B', 14);
  3218. $pdf->Cell(0, 10, '备注', 0, 1);
  3219. $pdf->SetFont('dejavusans', '', 12);
  3220. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  3221. $pdf->Ln(3);
  3222. }
  3223. // 角色列表
  3224. if (!empty($script['roles']) && is_array($script['roles'])) {
  3225. $pdf->SetFont('dejavusans', 'B', 14);
  3226. $pdf->Cell(0, 10, '角色列表', 0, 1);
  3227. $pdf->SetFont('dejavusans', '', 12);
  3228. foreach ($script['roles'] as $index => $role) {
  3229. if (is_array($role) || is_object($role)) {
  3230. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  3231. } else {
  3232. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  3233. }
  3234. }
  3235. $pdf->Ln(3);
  3236. }
  3237. // 角色关系
  3238. if (!empty($script['role_relationship'])) {
  3239. $pdf->SetFont('dejavusans', 'B', 14);
  3240. $pdf->Cell(0, 10, '角色关系', 0, 1);
  3241. $pdf->SetFont('dejavusans', '', 12);
  3242. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  3243. $pdf->Ln(3);
  3244. }
  3245. // 场景列表
  3246. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  3247. $pdf->SetFont('dejavusans', 'B', 14);
  3248. $pdf->Cell(0, 10, '场景列表', 0, 1);
  3249. $pdf->SetFont('dejavusans', '', 12);
  3250. foreach ($script['scenes'] as $index => $scene) {
  3251. if (is_array($scene) || is_object($scene)) {
  3252. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  3253. } else {
  3254. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  3255. }
  3256. }
  3257. $pdf->Ln(5);
  3258. }
  3259. // 分集内容
  3260. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  3261. $pdf->SetFont('dejavusans', 'B', 16);
  3262. $pdf->Cell(0, 12, '分集内容', 0, 1);
  3263. $pdf->Ln(3);
  3264. foreach ($script['episodes'] as $episode) {
  3265. // 检查是否需要新页面
  3266. if ($pdf->GetY() > 250) {
  3267. $pdf->AddPage();
  3268. }
  3269. $pdf->SetFont('dejavusans', 'B', 14);
  3270. $episodeTitle = '第' . $episode['episode_number'] . '集';
  3271. if (!empty($episode['title'])) {
  3272. $episodeTitle .= ':' . $episode['title'];
  3273. }
  3274. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  3275. // 处理分段内容
  3276. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  3277. $pdf->SetFont('dejavusans', '', 12);
  3278. foreach ($episode['segments'] as $segment) {
  3279. if (!empty($segment['segment_content'])) {
  3280. // 如果有分段编号,显示分段标题
  3281. if (!empty($segment['segment_number'])) {
  3282. $pdf->SetFont('dejavusans', 'B', 12);
  3283. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  3284. $pdf->SetFont('dejavusans', '', 12);
  3285. }
  3286. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  3287. $pdf->Ln(2);
  3288. }
  3289. }
  3290. }
  3291. $pdf->Ln(5);
  3292. }
  3293. }
  3294. }
  3295. /**
  3296. * 构建剧本文本内容
  3297. */
  3298. private function buildScriptContent($script) {
  3299. $content = '';
  3300. $groups = $script['group'];
  3301. $groups = (array)$groups;
  3302. foreach ($groups as $group) {
  3303. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  3304. // 剧本基本信息
  3305. if (!empty($group['intro'])) {
  3306. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  3307. }
  3308. if (!empty($group['highlights'])) {
  3309. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  3310. }
  3311. if (!empty($group['role_relationship'])) {
  3312. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  3313. }
  3314. if (!empty($group['core_contradiction'])) {
  3315. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  3316. }
  3317. if (!empty($group['roles']) && is_array($group['roles'])) {
  3318. $content .= "###主体列表\n";
  3319. foreach ($group['roles'] as $role) {
  3320. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  3321. }
  3322. $content .= "\n\n";
  3323. }
  3324. if (!empty($group['art_style'])) {
  3325. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  3326. }
  3327. // 场景信息
  3328. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3329. $content .= "###场景列表\n";
  3330. foreach ($group['scenes'] as $scene) {
  3331. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  3332. }
  3333. $content .= "\n\n";
  3334. }
  3335. // 分集内容
  3336. if (!empty($group['episode_content'])) {
  3337. $content .= "###分集剧本\n";
  3338. $content .= $group['episode_content'];
  3339. // foreach ($script['episodes'] as $episode) {
  3340. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  3341. // // if (!empty($episode['episode_name'])) {
  3342. // // $content .= ":" . $episode['episode_name'];
  3343. // // }
  3344. // // $content .= "\n";
  3345. // $content .= $episode['episode_content'] . "\n\n";
  3346. // }
  3347. }
  3348. }
  3349. return $content;
  3350. }
  3351. /**
  3352. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3353. *
  3354. * @param array $data 包含以下参数:
  3355. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3356. * - question: 用户问题(可选)
  3357. * - model: 使用的模型(r1 或 v3,默认 v3)
  3358. * @return \Generator 返回生成器,用于流式输出
  3359. */
  3360. public function addChat($data) {
  3361. $uid = Site::getUid();
  3362. $anime_id = getProp($data, 'anime_id');
  3363. if (!$anime_id) Utils::throwError('20003:请选择对话');
  3364. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3365. if (!$anime) Utils::throwError('20003:对话不存在');
  3366. $file = getProp($data, 'file');
  3367. $content = getProp($data, 'content', '');
  3368. $bid = getProp($data, 'bid', 0);
  3369. $script_id = getProp($data, 'script_id', 0);
  3370. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  3371. $prompt = getProp($data, 'prompt');
  3372. $user_anime_name = getProp($anime, 'anime_name');
  3373. // 处理文本模型
  3374. $model = getProp($data, 'model');
  3375. if (!$model) {
  3376. // 用户没有输入,从anime表获取
  3377. $model = getProp($anime, 'model');
  3378. if (!$model) {
  3379. // anime表也没有,使用默认值
  3380. $model = 'doubao-seed-2-0-mini-260215';
  3381. }
  3382. }
  3383. // 验证模型是否在可用模型表中
  3384. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3385. $model = 'doubao-seed-2-0-mini-260215';
  3386. }
  3387. $is_multi = getProp($anime, 'is_multi');
  3388. $is_single = (int)$is_multi !== 1;
  3389. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3390. if ($prompt) {
  3391. $question .= "本次修改要求如下:\n{$prompt}";
  3392. }
  3393. // if (!$file && !$content && !$bid) {
  3394. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3395. // }
  3396. // 提取文件内容
  3397. if ($file) {
  3398. $content = $this->extractFileContent($file);
  3399. if (!$content) {
  3400. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3401. }
  3402. } elseif ($script_id) {
  3403. $content = $this->getContentByScriptId($script_id);
  3404. if (!$content) {
  3405. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3406. }
  3407. } elseif ($bid) {
  3408. $content = $this->getContentByBid($bid);
  3409. if (!$content) {
  3410. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3411. }
  3412. } elseif ($content) {
  3413. $content = filterContent($content);
  3414. } else {
  3415. $content = getProp($anime, 'content');
  3416. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3417. $need_generate_content = true;
  3418. }
  3419. }
  3420. // 美术风格
  3421. $input_art_style = getProp($data, 'art_style');
  3422. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3423. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3424. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3425. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3426. 中年女:邻居阿姨
  3427. 老年男:幽默大爷
  3428. 老年女:婆婆
  3429. 萌娃:奶气萌娃";
  3430. // 判断是否需要生成原文内容
  3431. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3432. // 如果需要生成原文内容,添加额外的要求
  3433. $content_generation_requirement = $need_generate_content
  3434. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3435. : "";
  3436. // 美术风格
  3437. if (!$mappedArtStyle) {
  3438. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3439. }else {
  3440. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3441. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3442. }else {
  3443. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3444. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3445. }
  3446. }
  3447. $systemPrompt = $is_single
  3448. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3449. 强制要求:
  3450. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3451. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3452. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3453. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3454. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3455. 普通要求:
  3456. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3457. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3458. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  3459. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3460. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3461. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3462. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3463. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3464. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3465. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3466. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3467. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3468. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3469. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3470. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3471. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3472. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3473. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3474. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3475. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3476. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3477. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3478. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3479. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3480. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3481. 5.{$mappedArtStyle_prompt}\n\n
  3482. 示例如下:\n
  3483. ###剧本名:西昆仑
  3484. ###故事梗概
  3485. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3486. ###剧本亮点
  3487. 亮点1:绝境奇药,生死一线
  3488. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3489. 亮点2:结拜兄妹,化解尴尬
  3490. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3491. 亮点3:纤发夺命,情愫暗涌
  3492. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3493. ###人物关系
  3494. 阿雪与梁萧之间存在兄妹之情。
  3495. ###核心矛盾
  3496. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3497. ###主体列表
  3498. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3499. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3500. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3501. 姿态:站立。}{{甜心小美}}
  3502. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3503. 全景,正面拍摄,青年女性,亚洲人。
  3504. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3505. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3506. 姿态:站立。}{{阳光青年}}
  3507. ###美术风格
  3508. 基础画风风格词:厚涂古风
  3509. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3510. ###场景列表
  3511. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3512. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3513. 无人物。}
  3514. ###分镜剧本
  3515. ##第1幕:徐家老旧厨房 白天 室内
  3516. 分镜1
  3517. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3518. 场景:徐家老旧厨房
  3519. 构图设计:全景,低角度仰视
  3520. 运镜调度:手持拍摄
  3521. 配音角色:旁白
  3522. 出镜角色:许芸-校服装、徐母
  3523. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3524. 画面类型:普通画面
  3525. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3526. 分镜2
  3527. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3528. 场景:徐家老旧厨房
  3529. 构图设计:近景,徐母面部特写
  3530. 运镜调度:固定镜头
  3531. 配音角色:徐母
  3532. 出镜角色:徐母
  3533. 台词内容:问我夜不归宿死哪儿去了。
  3534. 画面类型:对口型
  3535. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3536. ##第2幕:徐家简陋客厅 黄昏 室内
  3537. 分镜3
  3538. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3539. 场景:徐家简陋客厅
  3540. 构图设计:全景,景深虚化
  3541. 运镜调度:固定镜头
  3542. 配音角色:旁白
  3543. 出镜角色:无
  3544. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3545. 画面类型:普通画面
  3546. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3547. 分镜4
  3548. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3549. 场景:徐家简陋客厅
  3550. 构图设计:特写,火车票
  3551. 运镜调度:固定镜头
  3552. 配音角色:旁白
  3553. 出镜角色:无
  3554. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3555. 画面类型:普通画面
  3556. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  3557. "
  3558. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3559. 强制要求:\n
  3560. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3561. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3562. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3563. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3564. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3565. 普通要求:\n
  3566. 1.剧本名(必须生成)必须与文档内容高度相关
  3567. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3568. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3569. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3570. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3571. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3572. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3573. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3574. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3575. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3576. 4.{$mappedArtStyle_prompt}\n\n
  3577. 示例如下:\n
  3578. ###剧本名:西昆仑
  3579. ###故事梗概
  3580. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3581. ###剧本亮点
  3582. 亮点1:绝境奇药,生死一线
  3583. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3584. 亮点2:结拜兄妹,化解尴尬
  3585. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3586. 亮点3:纤发夺命,情愫暗涌
  3587. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3588. ###人物关系
  3589. 阿雪与梁萧之间存在兄妹之情。
  3590. ###核心矛盾
  3591. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3592. ###主体列表
  3593. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3594. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3595. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3596. 姿态:站立。}{{甜心小美}}
  3597. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3598. 全景,正面拍摄,青年女性,亚洲人。
  3599. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3600. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3601. 姿态:站立。}{{阳光青年}}
  3602. ###美术风格
  3603. 基础画风风格词:厚涂古风
  3604. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3605. ###场景列表
  3606. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3607. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3608. 无人物。}";
  3609. // 构建消息
  3610. $messages = [
  3611. [
  3612. 'role' => 'system',
  3613. 'content' => $systemPrompt
  3614. ],
  3615. [
  3616. 'role' => 'user',
  3617. 'content' => "以下是文档内容:
  3618. {$content}
  3619. 用户问题:
  3620. {$question}"
  3621. ]
  3622. ];
  3623. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3624. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3625. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3626. if ($model === 'deepseek-chat') {
  3627. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3628. $model = 'deepseek-v4-flash';
  3629. $thinkingMode = 'disabled';
  3630. } elseif ($model === 'deepseek-reasoner') {
  3631. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3632. $model = 'deepseek-v4-flash';
  3633. $thinkingMode = 'enabled';
  3634. }
  3635. $post_data = [
  3636. 'model' => $model,
  3637. 'messages' => $messages,
  3638. // 'max_tokens' => 8192,
  3639. 'temperature' => 0.7,
  3640. 'frequency_penalty' => 0,
  3641. 'presence_penalty' => 0,
  3642. 'response_format' => ['type' => 'text'],
  3643. 'thinking' => ['type'=>$thinkingMode],
  3644. 'stream' => true // 启用流式输出
  3645. ];
  3646. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3647. // 根据模型类型选择调用方法
  3648. $fullContent = '';
  3649. $fullReasoningContent = '';
  3650. $usage = [];
  3651. try {
  3652. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3653. // DeepSeek 官方模型使用 DeepSeek API
  3654. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3655. } else if (in_array($model, $this->gpt_text_models)) {
  3656. // GPT-5.4 模型使用 TokenRouter API
  3657. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3658. } else {
  3659. // 其他模型使用火山引擎API
  3660. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3661. }
  3662. // 验证返回值类型
  3663. if (!is_iterable($streamGenerator)) {
  3664. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  3665. dLog('deepseek')->error('addChat流式生成器无效', [
  3666. 'generator_type' => $errorType,
  3667. 'model' => $model,
  3668. 'anime_id' => $anime_id
  3669. ]);
  3670. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  3671. 'type' => $errorType,
  3672. 'model' => $model
  3673. ]);
  3674. yield [
  3675. 'type' => 'error',
  3676. 'script' => [],
  3677. 'episode' => [],
  3678. 'answer' => '',
  3679. 'reasoning' => '',
  3680. 'usage' => [],
  3681. 'error' => '接口返回数据异常,请重新请求'
  3682. ];
  3683. return;
  3684. }
  3685. // 处理流式输出
  3686. foreach ($streamGenerator as $chunk) {
  3687. if (isset($chunk['type'])) {
  3688. if ($chunk['type'] === 'done') {
  3689. // 最终结果
  3690. $fullContent = $chunk['full_content'];
  3691. $fullReasoningContent = $chunk['full_reasoning'];
  3692. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3693. } else {
  3694. // 逐块yield数据
  3695. yield $chunk;
  3696. }
  3697. }
  3698. }
  3699. } catch (\Exception $e) {
  3700. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  3701. 'model' => $model,
  3702. 'anime_id' => $anime_id,
  3703. 'trace' => $e->getTraceAsString()
  3704. ]);
  3705. logDB('deepseek', 'error', 'addChat流式处理失败', [
  3706. 'error' => $e->getMessage(),
  3707. 'model' => $model
  3708. ]);
  3709. yield [
  3710. 'type' => 'error',
  3711. 'script' => [],
  3712. 'episode' => [],
  3713. 'answer' => '',
  3714. 'reasoning' => '',
  3715. 'usage' => [],
  3716. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  3717. ];
  3718. return;
  3719. }
  3720. dLog('deepseek')->info('完整内容: '.$fullContent);
  3721. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3722. // 处理完整内容并返回最终结果
  3723. $script_arr = [];
  3724. if ($fullContent) {
  3725. $script_arr = handleScriptContent($fullContent);
  3726. dLog('deepseek')->info('解析内容', $script_arr);
  3727. logDB('deepseek', 'info', '解析内容', $script_arr);
  3728. }
  3729. if (empty($script_arr['roles'])) {
  3730. // 未生成剧本相关内容,保存对话记录并返回提示
  3731. dLog('deepseek')->info('未生成剧本相关的内容');
  3732. try {
  3733. DB::beginTransaction();
  3734. $now = date('Y-m-d H:i:s');
  3735. // 保存对话记录
  3736. $records = [
  3737. [
  3738. 'uid' => $uid,
  3739. 'anime_id' => $anime_id,
  3740. 'sequence' => 0,
  3741. 'role' => 'user',
  3742. 'content' => $prompt,
  3743. 'created_at' => $now,
  3744. 'updated_at' => $now
  3745. ],
  3746. [
  3747. 'uid' => $uid,
  3748. 'anime_id' => $anime_id,
  3749. 'sequence' => 0,
  3750. 'role' => 'assistant',
  3751. // 'content' => $fullContent,
  3752. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  3753. 'created_at' => $now,
  3754. 'updated_at' => $now
  3755. ]
  3756. ];
  3757. DB::table('mp_anime_records')->insert($records);
  3758. DB::commit();
  3759. } catch (\Exception $e) {
  3760. DB::rollBack();
  3761. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3762. }
  3763. yield [
  3764. 'type' => 'done',
  3765. 'script' => [],
  3766. 'episode' => [],
  3767. 'answer' => $fullContent,
  3768. 'reasoning' => $fullReasoningContent,
  3769. 'usage' => $usage,
  3770. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  3771. ];
  3772. return;
  3773. }
  3774. // 如果需要生成原文内容,从script_arr中提取
  3775. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  3776. $content = $script_arr['content'];
  3777. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  3778. if (!$content) {
  3779. yield [
  3780. 'type' => 'done',
  3781. 'script' => [],
  3782. 'episode' => [],
  3783. 'answer' => $fullContent,
  3784. 'reasoning' => $fullReasoningContent,
  3785. 'usage' => $usage,
  3786. 'error' => '未生成剧本内容,请调整提示词再试'
  3787. ];
  3788. return;
  3789. }
  3790. }
  3791. // 替换美术风格
  3792. if ($mappedArtStyle !== '') {
  3793. $script_arr['art_style'] = $mappedArtStyle;
  3794. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  3795. }
  3796. // 新建动漫
  3797. if ($user_anime_name == '新剧本策划') {
  3798. $anime_name = getProp($script_arr, 'script_name');
  3799. // if (!$anime_name) {
  3800. // // 未识别到剧本名,保存对话记录并返回提示
  3801. // dLog('deepseek')->info('未能识别到剧本名称');
  3802. // try {
  3803. // DB::beginTransaction();
  3804. // $now = date('Y-m-d H:i:s');
  3805. // // 保存对话记录
  3806. // $records = [
  3807. // [
  3808. // 'uid' => $uid,
  3809. // 'anime_id' => $anime_id,
  3810. // 'sequence' => 0,
  3811. // 'role' => 'user',
  3812. // 'content' => $prompt,
  3813. // 'created_at' => $now,
  3814. // 'updated_at' => $now
  3815. // ],
  3816. // [
  3817. // 'uid' => $uid,
  3818. // 'anime_id' => $anime_id,
  3819. // 'sequence' => 0,
  3820. // 'role' => 'assistant',
  3821. // 'content' => '未能生成剧本名称,请重试',
  3822. // 'created_at' => $now,
  3823. // 'updated_at' => $now
  3824. // ]
  3825. // ];
  3826. // DB::table('mp_anime_records')->insert($records);
  3827. // DB::commit();
  3828. // } catch (\Exception $e) {
  3829. // DB::rollBack();
  3830. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3831. // }
  3832. // yield [
  3833. // 'type' => 'done',
  3834. // 'script' => [],
  3835. // 'episode' => [],
  3836. // 'answer' => $fullContent,
  3837. // 'reasoning' => $fullReasoningContent,
  3838. // 'usage' => $usage,
  3839. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  3840. // ];
  3841. // return;
  3842. // }
  3843. // 确认对话名称唯一性
  3844. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  3845. $anime_name = $anime_name . '_' . date('YmdHis');
  3846. }
  3847. }else {
  3848. $anime_name = $user_anime_name;
  3849. }
  3850. $table_data = [
  3851. 'user_id' => $uid,
  3852. 'anime_name' => $anime_name,
  3853. 'model' => $model,
  3854. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3855. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3856. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3857. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3858. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3859. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3860. 'art_style_type' => $input_art_style,
  3861. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3862. 'status' => '解析完成',
  3863. 'content' => $content,
  3864. 'is_multi' => $is_multi,
  3865. 'ace_mode' => $ace_mode,
  3866. 'generate_status' => '待执行',
  3867. 'updated_at' => date('Y-m-d H:i:s')
  3868. ];
  3869. if ($table_data['content']) {
  3870. $chapters = splitContent($table_data['content']);
  3871. $chapter_count = count($chapters);
  3872. if ($chapter_count > 0) {
  3873. $table_data['start_episode_sequence'] = 1;
  3874. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  3875. }
  3876. }
  3877. // 如果有剧本ID则进行绑定
  3878. if ($script_id) {
  3879. $table_data['script_id'] = $script_id;
  3880. }
  3881. $single_episode = [];
  3882. try {
  3883. DB::beginTransaction();
  3884. $now = date('Y-m-d H:i:s');
  3885. // 更新动漫大纲
  3886. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3887. if (!$boolen) {
  3888. dLog('deepseek')->info('动漫保存失败', $table_data);
  3889. Utils::throwError('20003:动漫保存失败');
  3890. }
  3891. // 保存对话记录
  3892. $records = [
  3893. [
  3894. 'uid' => $uid,
  3895. 'anime_id' => $anime_id,
  3896. 'sequence' => 0,
  3897. 'role' => 'user',
  3898. 'content' => $prompt,
  3899. 'created_at' => date('Y-m-d H:i:s'),
  3900. 'updated_at' => date('Y-m-d H:i:s')
  3901. ],
  3902. [
  3903. 'uid' => $uid,
  3904. 'anime_id' => $anime_id,
  3905. 'sequence' => 0,
  3906. 'role' => 'assistant',
  3907. 'content' => $fullContent,
  3908. 'created_at' => date('Y-m-d H:i:s'),
  3909. 'updated_at' => date('Y-m-d H:i:s')
  3910. ]
  3911. ];
  3912. // 保存对话记录
  3913. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3914. if (!$boolen3) {
  3915. Utils::throwError('20003:对话记录保存失败');
  3916. }
  3917. if ($is_single) {
  3918. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3919. if (empty($episode_arr['acts'])) {
  3920. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3921. }
  3922. $saveResult = $this->saveEpisodeVersionData(
  3923. $anime_id,
  3924. 1,
  3925. $episode_arr,
  3926. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3927. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3928. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  3929. null,
  3930. null,
  3931. false,
  3932. $content,
  3933. $now
  3934. );
  3935. $single_episode = $saveResult['episode'];
  3936. $episode_id = $saveResult['episode_id'];
  3937. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3938. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3939. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3940. 'props' => json_encode($saveResult['merged_props'], 256),
  3941. 'updated_at' => $now
  3942. ]);
  3943. if ($boolen5 === false) {
  3944. Utils::throwError('20003:单剧集主表资源同步失败');
  3945. }
  3946. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3947. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3948. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  3949. $episode_record_content = '确认分镜大纲';
  3950. if ($content !== '') {
  3951. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  3952. }
  3953. $episode_records = [
  3954. [
  3955. 'uid' => $uid,
  3956. 'anime_id' => $anime_id,
  3957. 'role' => 'user',
  3958. 'content' => $episode_record_content,
  3959. 'sequence' => 1,
  3960. 'episode_id' => $episode_id,
  3961. 'created_at' => $now,
  3962. 'updated_at' => $now
  3963. ],
  3964. [
  3965. 'uid' => $uid,
  3966. 'anime_id' => $anime_id,
  3967. 'role' => 'assistant',
  3968. 'content' => $fullContent,
  3969. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3970. 'sequence' => 1,
  3971. 'episode_id' => $episode_id,
  3972. 'created_at' => $now,
  3973. 'updated_at' => $now
  3974. ]
  3975. ];
  3976. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3977. if (!$boolen4) {
  3978. Utils::throwError('20003:单剧集分镜记录保存失败');
  3979. }
  3980. }
  3981. }catch (\Exception $e) {
  3982. DB::rollBack();
  3983. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  3984. yield [
  3985. 'type' => 'done',
  3986. 'answer' => $fullContent,
  3987. 'reasoning' => $fullReasoningContent,
  3988. 'usage' => $usage,
  3989. 'error' => $e->getMessage(),
  3990. ];
  3991. return;
  3992. }
  3993. DB::commit();
  3994. dLog('deepseek')->info('保存完毕');
  3995. if ($is_single && !empty($single_episode)) {
  3996. // $this->batchSetGlobalRoleImg([
  3997. // 'anime_id' => $anime_id,
  3998. // ]);
  3999. // $this->batchSetGlobalSceneImg([
  4000. // 'anime_id' => $anime_id,
  4001. // ]);
  4002. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4003. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4004. }
  4005. $table_data['anime_id'] = $anime_id;
  4006. $table_data['roles'] = json_decode($table_data['roles'], true);
  4007. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4008. // $table_data['episodes'] = $script_arr['episodes'];
  4009. unset($table_data['created_at']);
  4010. unset($table_data['updated_at']);
  4011. unset($table_data['status']);
  4012. dLog('deepseek')->info('开始返回');
  4013. yield [
  4014. 'type' => 'done',
  4015. 'script' => $table_data,
  4016. 'episode' => $single_episode,
  4017. 'answer' => $fullContent,
  4018. 'reasoning' => $fullReasoningContent,
  4019. 'usage' => $usage
  4020. ];
  4021. }
  4022. public function reGenerateAnime($data) {
  4023. $uid = Site::getUid();
  4024. $file = getProp($data, 'file');
  4025. $content = getProp($data, 'content', '');
  4026. $bid = getProp($data, 'bid', 0);
  4027. $script_id = getProp($data, 'script_id', 0);
  4028. $anime_id = getProp($data, 'anime_id');
  4029. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4030. if (!$anime) {
  4031. Utils::throwError('20003:该对话不存在');
  4032. }
  4033. $user_anime_name = getProp($anime, 'anime_name');
  4034. $prompt = getProp($data, 'prompt');
  4035. // 处理文本模型
  4036. $model = getProp($data, 'model');
  4037. if (!$model) {
  4038. // 用户没有输入,从anime表获取
  4039. $model = getProp($anime, 'model');
  4040. if (!$model) {
  4041. // anime表也没有,使用默认值
  4042. $model = 'doubao-seed-2-0-mini-260215';
  4043. }
  4044. }
  4045. // 验证模型是否在可用模型表中
  4046. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4047. $model = 'doubao-seed-2-0-mini-260215';
  4048. }
  4049. $is_multi = getProp($anime, 'is_multi', 1);
  4050. $is_single = (int)$is_multi !== 1;
  4051. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  4052. if ($is_single) {
  4053. $episode_exists = DB::table('mp_anime_episodes')
  4054. ->where('anime_id', $anime_id)
  4055. ->where('sequence', 1)
  4056. ->exists();
  4057. if ($episode_exists) {
  4058. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  4059. }
  4060. }
  4061. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  4062. if ($prompt) {
  4063. $question .= "本次修改要求如下:\n{$prompt}";
  4064. }
  4065. // 提取文件内容
  4066. if ($file) {
  4067. $content = $this->extractFileContent($file);
  4068. if (!$content) {
  4069. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4070. }
  4071. } elseif ($script_id) {
  4072. $content = $this->getContentByScriptId($script_id);
  4073. if (!$content) {
  4074. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4075. }
  4076. } elseif ($bid) {
  4077. $content = $this->getContentByBid($bid);
  4078. if (!$content) {
  4079. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4080. }
  4081. } elseif ($content) {
  4082. $content = filterContent($content);
  4083. }else {
  4084. $content = filterContent(getProp($anime, 'content'));
  4085. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  4086. $need_generate_content = true;
  4087. }
  4088. }
  4089. // 判断是否需要生成原文内容
  4090. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  4091. // 如果需要生成原文内容,添加额外的要求
  4092. $content_generation_requirement = $need_generate_content
  4093. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  4094. : "";
  4095. // 美术风格
  4096. $input_art_style = getProp($anime, 'art_style');
  4097. if (!$input_art_style) {
  4098. $input_art_style = getProp($data, 'art_style');
  4099. }
  4100. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4101. // 美术风格
  4102. if (!$mappedArtStyle) {
  4103. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4104. }else {
  4105. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4106. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4107. }else {
  4108. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4109. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4110. }
  4111. }
  4112. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4113. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4114. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4115. 中年女:邻居阿姨
  4116. 老年男:幽默大爷
  4117. 老年女:婆婆
  4118. 萌娃:奶气萌娃";
  4119. $system_message = ['role'=>'system', 'content'=>$is_single
  4120. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  4121. 强制要求:
  4122. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4123. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4124. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4125. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4126. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4127. 普通要求:
  4128. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  4129. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4130. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4131. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4132. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4133. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4134. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4135. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4136. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4137. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4138. 3.$mappedArtStyle_prompt\n\n
  4139. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4140. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4141. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4142. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4143. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  4144. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4145. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4146. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4147. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4148. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4149. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4150. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4151. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4152. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4153. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  4154. 示例如下:\n
  4155. ###剧本名:西昆仑
  4156. ###故事梗概
  4157. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4158. ###剧本亮点
  4159. 亮点1:绝境奇药,生死一线
  4160. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4161. 亮点2:结拜兄妹,化解尴尬
  4162. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4163. 亮点3:纤发夺命,情愫暗涌
  4164. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4165. ###人物关系
  4166. 阿雪与梁萧之间存在兄妹之情。
  4167. ###核心矛盾
  4168. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4169. ###主体列表
  4170. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4171. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4172. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4173. 姿态:站立。}{{甜心小美}}
  4174. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4175. 全景,正面拍摄,青年女性,亚洲人。
  4176. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4177. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4178. 姿态:站立。}{{阳光青年}}
  4179. ###美术风格
  4180. 基础画风风格词:厚涂古风
  4181. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4182. ###场景列表
  4183. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4184. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4185. 无人物。}
  4186. ###分镜剧本
  4187. ##第1幕:徐家老旧厨房 白天 室内
  4188. 分镜1
  4189. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4190. 场景:徐家老旧厨房
  4191. 构图设计:全景,低角度仰视
  4192. 运镜调度:手持拍摄
  4193. 配音角色:旁白
  4194. 出镜角色:许芸-校服装、徐母
  4195. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4196. 画面类型:普通画面
  4197. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4198. 分镜2
  4199. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4200. 场景:徐家老旧厨房
  4201. 构图设计:近景,徐母面部特写
  4202. 运镜调度:固定镜头
  4203. 配音角色:徐母
  4204. 出镜角色:徐母
  4205. 台词内容:问我夜不归宿死哪儿去了。
  4206. 画面类型:对口型
  4207. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4208. ##第2幕:徐家简陋客厅 黄昏 室内
  4209. 分镜3
  4210. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4211. 场景:徐家简陋客厅
  4212. 构图设计:全景,景深虚化
  4213. 运镜调度:固定镜头
  4214. 配音角色:旁白
  4215. 出镜角色:无
  4216. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4217. 画面类型:普通画面
  4218. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4219. 分镜4
  4220. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4221. 场景:徐家简陋客厅
  4222. 构图设计:特写,火车票
  4223. 运镜调度:固定镜头
  4224. 配音角色:旁白
  4225. 出镜角色:无
  4226. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4227. 画面类型:普通画面
  4228. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4229. "
  4230. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4231. 强制要求:\n
  4232. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4233. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4234. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4235. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4236. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4237. 普通要求:\n
  4238. 1.剧本名(必须生成)必须与文档内容高度相关
  4239. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4240. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4241. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4242. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4243. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4244. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4245. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4246. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4247. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4248. 4.$mappedArtStyle_prompt\n\n
  4249. 示例如下:\n
  4250. ###剧本名:西昆仑
  4251. ###故事梗概
  4252. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4253. ###剧本亮点
  4254. 亮点1:绝境奇药,生死一线
  4255. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4256. 亮点2:结拜兄妹,化解尴尬
  4257. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4258. 亮点3:纤发夺命,情愫暗涌
  4259. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4260. ###人物关系
  4261. 阿雪与梁萧之间存在兄妹之情。
  4262. ###核心矛盾
  4263. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4264. ###主体列表
  4265. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4266. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4267. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4268. 姿态:站立。}{{甜心小美}}
  4269. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4270. 全景,正面拍摄,青年女性,亚洲人。
  4271. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4272. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4273. 姿态:站立。}{{阳光青年}}
  4274. ###美术风格
  4275. 基础画风风格词:厚涂古风
  4276. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4277. ###场景列表
  4278. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4279. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4280. 无人物。}"];
  4281. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  4282. $episode_count = $this->extractEpisodeNumber($prompt);
  4283. if ((int)getProp($anime, 'is_multi') !== 1) {
  4284. yield [
  4285. 'type' => 'done',
  4286. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  4287. 'reasoning' => '',
  4288. 'usage' => []
  4289. ];
  4290. return;
  4291. }
  4292. if ($episode_count) {
  4293. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  4294. $system_message = [
  4295. 'role' => 'system',
  4296. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4297. 强制要求:\n
  4298. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4299. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4300. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4301. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4302. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4303. 普通要求:\n
  4304. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4305. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4306. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4307. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4308. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4309. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4310. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4311. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4312. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4313. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  4314. 示例如下:\n
  4315. ###剧本名:西昆仑
  4316. ###故事梗概
  4317. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4318. ###剧本亮点
  4319. 亮点1:绝境奇药,生死一线
  4320. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4321. 亮点2:结拜兄妹,化解尴尬
  4322. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4323. 亮点3:纤发夺命,情愫暗涌
  4324. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4325. ###人物关系
  4326. 阿雪与梁萧之间存在兄妹之情。
  4327. ###核心矛盾
  4328. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4329. ###主体列表
  4330. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4331. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4332. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4333. 姿态:站立。}{{甜心小美}}
  4334. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4335. 全景,正面拍摄,青年女性,亚洲人。
  4336. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4337. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4338. 姿态:站立。}{{阳光青年}}
  4339. ###美术风格
  4340. 基础画风风格词:厚涂古风
  4341. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4342. ###场景列表
  4343. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4344. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4345. 无人物。}
  4346. ###分集详细内容
  4347. ##第1章 重生
  4348. 我重生了。
  4349. 源于一个男人偏执的暗恋。
  4350. ##第2章 相救
  4351. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  4352. 我眼睛扫向站在锅炉后的卞大伟。"
  4353. ];
  4354. // 构建消息
  4355. $messages = [
  4356. $system_message,
  4357. [
  4358. 'role' => 'user',
  4359. 'content' => "以下是文档内容:
  4360. {$content}
  4361. 用户问题:
  4362. {$question}"
  4363. ]
  4364. ];
  4365. }else {
  4366. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  4367. // 构建消息
  4368. $messages = [
  4369. $system_message,
  4370. [
  4371. 'role' => 'user',
  4372. 'content' => "以下是文档内容:
  4373. {$content}
  4374. 用户问题:
  4375. {$question}"
  4376. ]
  4377. ];
  4378. }else {
  4379. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  4380. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  4381. return (array)$value;
  4382. })->toArray();
  4383. array_unshift($messages, $system_message);
  4384. $messages[] = [
  4385. 'role' => 'user',
  4386. 'content' => $prompt
  4387. ];
  4388. }
  4389. }
  4390. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4391. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4392. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4393. if ($model === 'deepseek-chat') {
  4394. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4395. $model = 'deepseek-v4-flash';
  4396. $thinkingMode = 'disabled';
  4397. } elseif ($model === 'deepseek-reasoner') {
  4398. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4399. $model = 'deepseek-v4-flash';
  4400. $thinkingMode = 'enabled';
  4401. }
  4402. $post_data = [
  4403. 'model' => $model,
  4404. 'messages' => $messages,
  4405. // 'max_tokens' => 8192,
  4406. 'temperature' => 0.7,
  4407. 'frequency_penalty' => 0,
  4408. 'presence_penalty' => 0,
  4409. 'response_format' => ['type' => 'text'],
  4410. 'thinking' => ['type' => $thinkingMode],
  4411. 'stream' => true // 启用流式输出
  4412. ];
  4413. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4414. // 根据模型类型选择调用方法
  4415. $fullContent = '';
  4416. $fullReasoningContent = '';
  4417. $usage = [];
  4418. // dd($post_data);
  4419. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  4420. try {
  4421. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4422. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4423. } else if (in_array($model, $this->gpt_text_models)) {
  4424. // GPT-5.4 模型使用 TokenRouter API
  4425. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4426. } else {
  4427. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4428. }
  4429. // 验证返回值类型
  4430. if (!is_iterable($streamGenerator)) {
  4431. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4432. dLog('deepseek')->error('方法名流式生成器无效', [
  4433. 'generator_type' => $errorType,
  4434. 'model' => $model,
  4435. // 添加其他上下文信息
  4436. ]);
  4437. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  4438. 'type' => $errorType,
  4439. 'model' => $model
  4440. ]);
  4441. yield [
  4442. 'type' => 'error',
  4443. // 根据方法返回相应的空数据结构
  4444. 'answer' => '',
  4445. 'reasoning' => '',
  4446. 'usage' => [],
  4447. 'error' => '接口返回数据异常,请重新请求'
  4448. ];
  4449. return;
  4450. }
  4451. // 处理流式输出
  4452. foreach ($streamGenerator as $chunk) {
  4453. if (isset($chunk['type'])) {
  4454. if ($chunk['type'] === 'done') {
  4455. $fullContent = $chunk['full_content'];
  4456. $fullReasoningContent = $chunk['full_reasoning'];
  4457. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4458. } else {
  4459. yield $chunk;
  4460. }
  4461. }
  4462. }
  4463. } catch (\Exception $e) {
  4464. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  4465. 'model' => $model,
  4466. 'trace' => $e->getTraceAsString()
  4467. ]);
  4468. logDB('deepseek', 'error', '方法名流式处理失败', [
  4469. 'error' => $e->getMessage(),
  4470. 'model' => $model
  4471. ]);
  4472. yield [
  4473. 'type' => 'error',
  4474. // 根据方法返回相应的空数据结构
  4475. 'answer' => '',
  4476. 'reasoning' => '',
  4477. 'usage' => [],
  4478. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4479. ];
  4480. return;
  4481. }
  4482. dLog('deepseek')->info('完整内容: '.$fullContent);
  4483. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4484. // 处理完整内容并返回最终结果
  4485. $script_arr = [];
  4486. if ($fullContent) {
  4487. $script_arr = handleScriptContent($fullContent);
  4488. dLog('deepseek')->info('解析内容', $script_arr);
  4489. logDB('deepseek', 'info', '解析内容', $script_arr);
  4490. }
  4491. if (empty($script_arr['roles'])) {
  4492. // 未生成剧本相关内容,保存对话记录并返回提示
  4493. dLog('deepseek')->info('未生成剧本相关的内容');
  4494. try {
  4495. $now = date('Y-m-d H:i:s');
  4496. // 保存对话记录
  4497. $records = [
  4498. [
  4499. 'uid' => $uid,
  4500. 'anime_id' => $anime_id,
  4501. 'sequence' => 0,
  4502. 'role' => 'user',
  4503. 'content' => $prompt,
  4504. 'created_at' => $now,
  4505. 'updated_at' => $now
  4506. ],
  4507. [
  4508. 'uid' => $uid,
  4509. 'anime_id' => $anime_id,
  4510. 'sequence' => 0,
  4511. 'role' => 'assistant',
  4512. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  4513. 'created_at' => $now,
  4514. 'updated_at' => $now
  4515. ]
  4516. ];
  4517. DB::table('mp_anime_records')->insert($records);
  4518. } catch (\Exception $e) {
  4519. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4520. }
  4521. yield [
  4522. 'type' => 'done',
  4523. 'script' => [],
  4524. 'episode' => [],
  4525. 'answer' => $fullContent,
  4526. 'reasoning' => $fullReasoningContent,
  4527. 'usage' => $usage,
  4528. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4529. ];
  4530. return;
  4531. }
  4532. // 替换美术风格
  4533. if ($mappedArtStyle !== '') {
  4534. $script_arr['art_style'] = $mappedArtStyle;
  4535. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4536. }
  4537. if ($user_anime_name != '新剧本策划') {
  4538. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  4539. // 确认对话名称唯一性
  4540. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4541. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  4542. }
  4543. }else {
  4544. $anime_name = $user_anime_name;
  4545. }
  4546. $table_data = [
  4547. 'user_id' => $uid,
  4548. 'model' => $model,
  4549. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4550. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4551. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4552. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4553. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4554. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4555. 'art_style_type' => $input_art_style,
  4556. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4557. 'status' => '解析完成',
  4558. 'generate_status' => '待执行',
  4559. 'updated_at' => date('Y-m-d H:i:s')
  4560. ];
  4561. if ($anime_name) $table_data['anime_name'] = $anime_name;
  4562. // 如果是修改集数,则将content内容更新(会改变原文)
  4563. if (isset($episode_count) && $episode_count > 0) {
  4564. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  4565. $table_data['start_episode_sequence'] = 1;
  4566. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  4567. }else {
  4568. // 如果需要生成原文内容,从script_arr中提取
  4569. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4570. $table_data['content'] = $script_arr['content'];
  4571. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  4572. if (!$table_data['content']) {
  4573. yield [
  4574. 'type' => 'done',
  4575. 'script' => [],
  4576. 'episode' => [],
  4577. 'answer' => $fullContent,
  4578. 'reasoning' => $fullReasoningContent,
  4579. 'usage' => $usage,
  4580. 'error' => '未生成剧本内容,请调整提示词再试'
  4581. ];
  4582. return;
  4583. }
  4584. }
  4585. if (isset($table_data['content']) && $table_data['content']) {
  4586. $chapters = splitContent($table_data['content']);
  4587. $chapter_count = count($chapters);
  4588. if ($chapter_count > 0) {
  4589. $table_data['start_episode_sequence'] = 1;
  4590. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4591. }
  4592. }
  4593. }
  4594. $single_episode = [];
  4595. try {
  4596. DB::beginTransaction();
  4597. $now = date('Y-m-d H:i:s');
  4598. // 更新动漫大纲
  4599. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4600. if (!$boolen) {
  4601. dLog('deepseek')->info('对话修改失败', $table_data);
  4602. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  4603. Utils::throwError('20003:对话修改失败');
  4604. }
  4605. // 保存对话记录
  4606. $records = [
  4607. [
  4608. 'uid' => $uid,
  4609. 'anime_id' => $anime_id,
  4610. 'sequence' => 0,
  4611. 'role' => 'user',
  4612. 'content' => $prompt,
  4613. 'created_at' => $now,
  4614. 'updated_at' => $now
  4615. ],
  4616. [
  4617. 'uid' => $uid,
  4618. 'anime_id' => $anime_id,
  4619. 'sequence' => 0,
  4620. 'role' => 'assistant',
  4621. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4622. 'content' => $fullContent,
  4623. 'created_at' => $now,
  4624. 'updated_at' => $now
  4625. ]
  4626. ];
  4627. // 保存对话记录
  4628. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4629. if (!$boolen3) {
  4630. Utils::throwError('20003:对话记录保存失败');
  4631. }
  4632. // 单剧集模式:生成并保存剧集信息
  4633. if ($is_single) {
  4634. $anime_name = getProp($anime, 'anime_name', '未命名');
  4635. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4636. if (empty($episode_arr['acts'])) {
  4637. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4638. }
  4639. $saveResult = $this->saveEpisodeVersionData(
  4640. $anime_id,
  4641. 1,
  4642. $episode_arr,
  4643. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4644. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4645. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  4646. null,
  4647. null,
  4648. false,
  4649. $content,
  4650. $now
  4651. );
  4652. $single_episode = $saveResult['episode'];
  4653. $episode_id = $saveResult['episode_id'];
  4654. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4655. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4656. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4657. 'props' => json_encode($saveResult['merged_props'], 256),
  4658. 'updated_at' => $now
  4659. ]);
  4660. if ($boolen5 === false) {
  4661. Utils::throwError('20003:单剧集主表资源同步失败');
  4662. }
  4663. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4664. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4665. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  4666. $episode_record_content = '确认分镜大纲';
  4667. if ($content !== '') {
  4668. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4669. }
  4670. $episode_records = [
  4671. [
  4672. 'uid' => $uid,
  4673. 'anime_id' => $anime_id,
  4674. 'role' => 'user',
  4675. 'content' => $episode_record_content,
  4676. 'sequence' => 1,
  4677. 'episode_id' => $episode_id,
  4678. 'created_at' => $now,
  4679. 'updated_at' => $now
  4680. ],
  4681. [
  4682. 'uid' => $uid,
  4683. 'anime_id' => $anime_id,
  4684. 'role' => 'assistant',
  4685. 'content' => $fullContent,
  4686. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4687. 'sequence' => 1,
  4688. 'episode_id' => $episode_id,
  4689. 'created_at' => $now,
  4690. 'updated_at' => $now
  4691. ]
  4692. ];
  4693. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4694. if (!$boolen4) {
  4695. Utils::throwError('20003:单剧集分镜记录保存失败');
  4696. }
  4697. }
  4698. }catch (\Exception $e) {
  4699. DB::rollBack();
  4700. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  4701. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  4702. yield [
  4703. 'type' => 'done',
  4704. 'answer' => $fullContent,
  4705. 'reasoning' => $fullReasoningContent,
  4706. 'usage' => $usage,
  4707. 'error' => $e->getMessage(),
  4708. ];
  4709. return;
  4710. }
  4711. DB::commit();
  4712. dLog('deepseek')->info('保存完毕');
  4713. if ($is_single && !empty($single_episode)) {
  4714. // $this->batchSetGlobalRoleImg([
  4715. // 'anime_id' => $anime_id,
  4716. // ]);
  4717. // $this->batchSetGlobalSceneImg([
  4718. // 'anime_id' => $anime_id,
  4719. // ]);
  4720. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4721. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4722. }
  4723. $table_data['anime_id'] = $anime_id;
  4724. $table_data['roles'] = json_decode($table_data['roles'], true);
  4725. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4726. unset($table_data['updated_at']);
  4727. unset($table_data['status']);
  4728. yield [
  4729. 'type' => 'done',
  4730. 'script' => $table_data,
  4731. 'episode' => $single_episode,
  4732. 'answer' => $fullContent,
  4733. 'reasoning' => $fullReasoningContent,
  4734. 'usage' => $usage
  4735. ];
  4736. }
  4737. public function chat($data) {
  4738. $uid = Site::getUid();
  4739. $anime_id = getProp($data, 'anime_id');
  4740. $file = getProp($data, 'file');
  4741. $content = getProp($data, 'content', '');
  4742. $bid = getProp($data, 'bid', 0);
  4743. $script_id = getProp($data, 'script_id', 0);
  4744. $episode_number = getProp($data, 'episode_number', 1);
  4745. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4746. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4747. if (!$anime) Utils::throwError('20003:该对话不存在!');
  4748. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  4749. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  4750. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  4751. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  4752. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  4753. $roles = is_array($roles) ? $roles : [];
  4754. $scenes = is_array($scenes) ? $scenes : [];
  4755. // 获取最后一集序号
  4756. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  4757. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  4758. // 转换主体列表和场景列表的格式
  4759. // 获取参考主体或场景
  4760. if ((int)$episode_number === 1) {
  4761. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  4762. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  4763. }else {
  4764. $prev_episode_number = $episode_number - 1;
  4765. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  4766. }
  4767. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  4768. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  4769. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  4770. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  4771. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4772. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4773. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4774. 中年女:邻居阿姨
  4775. 老年男:幽默大爷
  4776. 老年女:婆婆
  4777. 萌娃:奶气萌娃";
  4778. if ($roles_content) {
  4779. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  4780. 主体范围:\n {$roles_content}\n
  4781. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  4782. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4783. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4784. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4785. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4786. }else {
  4787. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4788. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4789. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4790. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4791. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4792. }
  4793. if ($scenes_content) {
  4794. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  4795. 场景范围:\n {$scenes_content}\n
  4796. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  4797. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4798. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4799. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4800. }else {
  4801. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4802. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4803. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4804. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4805. }
  4806. // 提取文件内容
  4807. if ($file) {
  4808. $uploaded_content = $this->extractFileContent($file);
  4809. if (!$uploaded_content) {
  4810. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4811. }
  4812. } elseif ($script_id) {
  4813. $uploaded_content = $this->getContentByScriptId($script_id);
  4814. if (!$uploaded_content) {
  4815. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4816. }
  4817. } elseif ($bid) {
  4818. $uploaded_content = $this->getContentByBid($bid);
  4819. if (!$uploaded_content) {
  4820. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4821. }
  4822. } elseif ($content) {
  4823. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  4824. }
  4825. // elseif ($prompt) {
  4826. // $uploaded_content = filterContent($prompt);
  4827. // }
  4828. else {
  4829. $uploaded_content = '';
  4830. }
  4831. $input_art_style = getProp($anime, 'art_style');
  4832. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4833. // 美术风格
  4834. if (!$mappedArtStyle) {
  4835. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4836. }else {
  4837. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4838. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4839. }else {
  4840. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4841. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4842. }
  4843. }
  4844. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4845. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4846. // 强制要求:
  4847. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4848. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4849. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4850. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4851. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  4852. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  4853. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  4854. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  4855. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  4856. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  4857. // - 分镜要和场景列表、人物主体保持一致\n
  4858. // 普通要求:
  4859. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4860. // {$role_demo}
  4861. // {$scene_demo}
  4862. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4863. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4864. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4865. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4866. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4867. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4868. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4869. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4870. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4871. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4872. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4873. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4874. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4875. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4876. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4877. // 5.$mappedArtStyle_prompt\n\n
  4878. // 示例格式:\n
  4879. // 第1集:隐形的守护者
  4880. // ###故事梗概
  4881. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4882. // ###美术风格
  4883. // 基础画风风格词:韩漫二次元
  4884. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4885. // ###主体列表
  4886. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4887. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4888. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4889. // ###场景列表
  4890. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4891. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4892. // 无人物。}
  4893. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4894. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4895. // 无人物。}
  4896. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4897. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4898. // 无人物。}
  4899. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4900. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4901. // 无人物。}
  4902. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4903. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4904. // 无人物。}
  4905. // ###分镜剧本
  4906. // ##第1幕:徐家老旧厨房 白天 室内
  4907. // 分镜1
  4908. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4909. // 场景:徐家老旧厨房
  4910. // 构图设计:全景,低角度仰视
  4911. // 运镜调度:手持拍摄
  4912. // 配音角色:旁白
  4913. // 出镜角色:许芸-校服装、徐母
  4914. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4915. // 画面类型:普通画面
  4916. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4917. // 分镜2
  4918. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4919. // 场景:徐家老旧厨房
  4920. // 构图设计:近景,徐母面部特写
  4921. // 运镜调度:固定镜头
  4922. // 配音角色:徐母
  4923. // 出镜角色:徐母
  4924. // 台词内容:问我夜不归宿死哪儿去了。
  4925. // 画面类型:对口型
  4926. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4927. // ##第2幕:徐家简陋客厅 黄昏 室内
  4928. // 分镜3
  4929. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4930. // 场景:徐家简陋客厅
  4931. // 构图设计:全景,景深虚化
  4932. // 运镜调度:固定镜头
  4933. // 配音角色:旁白
  4934. // 出镜角色:无
  4935. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4936. // 画面类型:普通画面
  4937. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4938. // 分镜4
  4939. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4940. // 场景:徐家简陋客厅
  4941. // 构图设计:特写,火车票
  4942. // 运镜调度:固定镜头
  4943. // 配音角色:旁白
  4944. // 出镜角色:无
  4945. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4946. // 画面类型:普通画面
  4947. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4948. // \n\n";
  4949. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  4950. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  4951. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  4952. 普通要求:
  4953. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4954. {$role_demo}
  4955. {$scene_demo}
  4956. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4957. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4958. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4959. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  4960. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4961. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4962. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4963. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4964. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4965. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4966. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4967. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4968. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4969. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4970. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4971. 5.$mappedArtStyle_prompt
  4972. 6.《情绪-视听语言映射表》:
  4973. 6.1 场景空间与时间心理学 (Scene & Temporality)
  4974. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4975. -----|---------|------------|----------------
  4976. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  4977. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  4978. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  4979. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  4980. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  4981. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4982. -----|---------|------------|----------------
  4983. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  4984. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  4985. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  4986. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  4987. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  4988. --------|---------|--------------|-------------
  4989. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  4990. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  4991. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  4992. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  4993. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  4994. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  4995. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  4996. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  4997. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  4998. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  4999. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  5000. -----|---------|------------|------------
  5001. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  5002. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  5003. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  5004. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  5005. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  5006. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  5007. --------|---------|--------------|----------
  5008. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  5009. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  5010. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  5011. 6.6 声音设计与潜意识影响 (Soundscape)
  5012. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  5013. -----|---------|------------|------------------
  5014. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  5015. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  5016. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  5017. 理论基石:
  5018. - The Five C's of Cinematography by Joseph V. Mascelli
  5019. - Film Art: An Introduction by David Bordwell
  5020. - Sight, Sound, Motion by Herbert Zettl
  5021. - Notes on the Cinematograph by Robert Bresson
  5022. \n\n
  5023. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  5024. 示例格式:\n
  5025. 第1集:隐形的守护者
  5026. ###故事梗概
  5027. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5028. ###美术风格
  5029. 基础画风风格词:韩漫二次元
  5030. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  5031. ###主体列表
  5032. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  5033. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  5034. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  5035. ###场景列表
  5036. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  5037. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5038. 无人物。}
  5039. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  5040. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  5041. 无人物。}
  5042. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  5043. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  5044. 无人物。}
  5045. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  5046. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  5047. 无人物。}
  5048. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  5049. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  5050. 无人物。}
  5051. ###分镜剧本
  5052. ##第1幕:徐家老旧厨房 白天 室内
  5053. 分镜1
  5054. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  5055. 场景:徐家老旧厨房
  5056. 构图设计:全景,低角度仰视
  5057. 运镜调度:手持拍摄
  5058. 配音角色:旁白
  5059. 出镜角色:许芸-校服装、徐母
  5060. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  5061. 画面类型:普通画面
  5062. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  5063. 分镜2
  5064. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  5065. 场景:徐家老旧厨房
  5066. 构图设计:近景,徐母面部特写
  5067. 运镜调度:固定镜头
  5068. 配音角色:徐母
  5069. 出镜角色:徐母
  5070. 台词内容:问我夜不归宿死哪儿去了。
  5071. 画面类型:对口型
  5072. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  5073. ##第2幕:徐家简陋客厅 黄昏 室内
  5074. 分镜3
  5075. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  5076. 场景:徐家简陋客厅
  5077. 构图设计:全景,景深虚化
  5078. 运镜调度:固定镜头
  5079. 配音角色:旁白
  5080. 出镜角色:无
  5081. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  5082. 画面类型:普通画面
  5083. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  5084. 分镜4
  5085. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  5086. 场景:徐家简陋客厅
  5087. 构图设计:特写,火车票
  5088. 运镜调度:固定镜头
  5089. 配音角色:旁白
  5090. 出镜角色:无
  5091. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  5092. 画面类型:普通画面
  5093. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  5094. \n\n";
  5095. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  5096. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  5097. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  5098. $prompt = $origin_prompt;
  5099. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  5100. // 获取章节内容
  5101. $full_content = getProp($anime, 'content');
  5102. if ($uploaded_content) {
  5103. $full_content = $uploaded_content;
  5104. }
  5105. // 根据章节内容拆分章节
  5106. $chapters = splitContent($full_content);
  5107. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  5108. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  5109. $messages = [];
  5110. if ($prompt == '确认分镜大纲') {
  5111. // 暂时保留
  5112. $content = $chapter_content;
  5113. if ($is_single) $content = $full_content; // 单剧集使用全文
  5114. if (!$content) {
  5115. Utils::throwError('20003:章节内容无法获取,请确认');
  5116. }
  5117. $question = $is_single
  5118. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  5119. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  5120. // 构建消息
  5121. $messages[] =
  5122. [
  5123. 'role' => 'user',
  5124. 'content' => $question
  5125. ];
  5126. }else if ($prompt == '继续策划下一集') {
  5127. if ($is_single) {
  5128. Utils::throwError('20003:单剧集不支持继续策划下一集');
  5129. }
  5130. $content = $chapter_content;
  5131. if (!$content) {
  5132. Utils::throwError('20003:章节内容无法获取,请确认');
  5133. }
  5134. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  5135. // 获取上一集最后记录
  5136. $prev_sequence = $episode_number - 1;
  5137. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  5138. // 构建消息
  5139. $messages[] =
  5140. [
  5141. 'role' => 'user',
  5142. 'content' => $question
  5143. ];
  5144. }else {
  5145. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  5146. if (!$content) {
  5147. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  5148. }
  5149. if (!$content) {
  5150. Utils::throwError('20003:章节内容无法获取,请确认');
  5151. }
  5152. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  5153. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  5154. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  5155. if ($origin_prompt) {
  5156. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  5157. }
  5158. $messages[] =
  5159. [
  5160. 'role' => 'user',
  5161. 'content' => $question
  5162. ];
  5163. }
  5164. // 处理文本模型
  5165. $model = getProp($data, 'model');
  5166. if (!$model) {
  5167. // 用户没有输入,从anime表获取
  5168. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5169. $model = getProp($anime, 'model');
  5170. if (!$model) {
  5171. // anime表也没有,使用默认值
  5172. $model = 'doubao-seed-2-0-mini-260215';
  5173. }
  5174. }
  5175. // 验证模型是否在可用模型表中
  5176. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5177. $model = 'doubao-seed-2-0-mini-260215';
  5178. }
  5179. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5180. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5181. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5182. if ($model === 'deepseek-chat') {
  5183. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5184. $model = 'deepseek-v4-flash';
  5185. $thinkingMode = 'disabled';
  5186. } elseif ($model === 'deepseek-reasoner') {
  5187. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5188. $model = 'deepseek-v4-flash';
  5189. $thinkingMode = 'enabled';
  5190. }
  5191. $post_data = [
  5192. 'model' => $model,
  5193. 'messages' => $messages,
  5194. // 'max_tokens' => 8192,
  5195. 'temperature' => 0.2,
  5196. 'frequency_penalty' => 0,
  5197. 'presence_penalty' => 0,
  5198. 'response_format' => ['type' => 'text'],
  5199. 'thinking' => ['type' => $thinkingMode],
  5200. 'stream' => true // 启用流式输出
  5201. ];
  5202. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5203. // 根据模型类型选择调用方法
  5204. $fullContent = '';
  5205. $fullReasoningContent = '';
  5206. $usage = [];
  5207. try {
  5208. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5209. // DeepSeek 官方模型使用 DeepSeek API
  5210. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5211. } else if (in_array($model, $this->gpt_text_models)) {
  5212. // GPT-5.4 模型使用 TokenRouter API
  5213. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5214. } else {
  5215. // 其他模型使用火山引擎API
  5216. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5217. }
  5218. // 验证返回值类型
  5219. if (!is_iterable($streamGenerator)) {
  5220. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5221. dLog('deepseek')->error('chat流式生成器无效', [
  5222. 'generator_type' => $errorType,
  5223. 'model' => $model,
  5224. 'anime_id' => $anime_id,
  5225. 'episode_number' => $episode_number
  5226. ]);
  5227. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  5228. 'type' => $errorType,
  5229. 'model' => $model
  5230. ]);
  5231. yield [
  5232. 'type' => 'error',
  5233. 'episode' => [],
  5234. 'answer' => '',
  5235. 'reasoning' => '',
  5236. 'usage' => [],
  5237. 'error' => '接口返回数据异常,请重新请求'
  5238. ];
  5239. return;
  5240. }
  5241. // 处理流式输出
  5242. foreach ($streamGenerator as $chunk) {
  5243. if (isset($chunk['type'])) {
  5244. if ($chunk['type'] === 'done') {
  5245. // 最终结果
  5246. $fullContent = $chunk['full_content'];
  5247. $fullReasoningContent = $chunk['full_reasoning'];
  5248. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5249. } else {
  5250. // 逐块yield数据
  5251. yield $chunk;
  5252. }
  5253. }
  5254. }
  5255. } catch (\Exception $e) {
  5256. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  5257. 'model' => $model,
  5258. 'anime_id' => $anime_id,
  5259. 'episode_number' => $episode_number,
  5260. 'trace' => $e->getTraceAsString()
  5261. ]);
  5262. logDB('deepseek', 'error', 'chat流式处理失败', [
  5263. 'error' => $e->getMessage(),
  5264. 'model' => $model
  5265. ]);
  5266. yield [
  5267. 'type' => 'error',
  5268. 'episode' => [],
  5269. 'answer' => '',
  5270. 'reasoning' => '',
  5271. 'usage' => [],
  5272. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5273. ];
  5274. return;
  5275. }
  5276. dLog('deepseek')->info('完整内容: '.$fullContent);
  5277. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5278. // 处理完整内容并返回最终结果
  5279. $episode_arr = handleEpisodeContent($fullContent);
  5280. logDB('deepseek', 'info', '解析内容', $episode_arr);
  5281. if (empty($episode_arr['acts'])) {
  5282. // 未生成剧本相关内容,保存对话记录并返回提示
  5283. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  5284. try {
  5285. $now = date('Y-m-d H:i:s');
  5286. // 保存对话记录
  5287. $records = [
  5288. [
  5289. 'uid' => $uid,
  5290. 'anime_id' => $anime_id,
  5291. 'sequence' => $episode_number,
  5292. 'role' => 'user',
  5293. 'content' => $prompt,
  5294. 'created_at' => $now,
  5295. 'updated_at' => $now
  5296. ],
  5297. [
  5298. 'uid' => $uid,
  5299. 'anime_id' => $anime_id,
  5300. 'sequence' => $episode_number,
  5301. 'role' => 'assistant',
  5302. 'content' => $fullContent,
  5303. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5304. 'created_at' => $now,
  5305. 'updated_at' => $now
  5306. ]
  5307. ];
  5308. DB::table('mp_anime_records')->insert($records);
  5309. } catch (\Exception $e) {
  5310. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5311. }
  5312. yield [
  5313. 'type' => 'done',
  5314. 'episode' => [],
  5315. 'answer' => $fullContent,
  5316. 'reasoning' => $fullReasoningContent,
  5317. 'usage' => $usage,
  5318. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  5319. ];
  5320. return;
  5321. }
  5322. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  5323. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  5324. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  5325. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  5326. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  5327. $existing_props = is_array($existing_props) ? $existing_props : [];
  5328. $now = date('Y-m-d H:i:s');
  5329. try {
  5330. DB::beginTransaction();
  5331. $saveResult = $this->saveEpisodeVersionData(
  5332. $anime_id,
  5333. $episode_number,
  5334. $episode_arr,
  5335. $existing_roles,
  5336. $existing_scenes,
  5337. $existing_props,
  5338. $current_episode,
  5339. $base_episode,
  5340. $is_regenerate_version,
  5341. $content,
  5342. $now
  5343. );
  5344. $episode = $saveResult['episode'];
  5345. $episode_id = $saveResult['episode_id'];
  5346. $merged_roles = $saveResult['merged_roles'];
  5347. $merged_scenes = $saveResult['merged_scenes'];
  5348. $merged_props = $saveResult['merged_props'];
  5349. $record_content = $origin_prompt;
  5350. if ($uploaded_content !== '') {
  5351. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  5352. }
  5353. $records = [
  5354. [
  5355. 'uid' => $uid,
  5356. 'anime_id' => $anime_id,
  5357. 'role' => 'user',
  5358. 'content' => $record_content,
  5359. 'sequence' => $episode_number,
  5360. 'episode_id' => $episode_id,
  5361. 'created_at' => $now,
  5362. 'updated_at' => $now
  5363. ],
  5364. [
  5365. 'uid' => $uid,
  5366. 'anime_id' => $anime_id,
  5367. 'role' => 'assistant',
  5368. 'content' => $fullContent,
  5369. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5370. 'sequence' => $episode_number,
  5371. 'episode_id' => $episode_id,
  5372. 'created_at' => $now,
  5373. 'updated_at' => $now
  5374. ]
  5375. ];
  5376. $boolen4 = DB::table('mp_anime_records')->insert($records);
  5377. if (!$boolen4) {
  5378. Utils::throwError('20003:对话记录保存失败');
  5379. }
  5380. // 保存模型和内容到anime表
  5381. $update_anime_data = [
  5382. 'model' => $model,
  5383. 'updated_at' => $now
  5384. ];
  5385. if ($uploaded_content) {
  5386. $update_anime_data['content'] = $uploaded_content;
  5387. }
  5388. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  5389. }catch (\Exception $e) {
  5390. DB::rollBack();
  5391. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5392. yield [
  5393. 'type' => 'done',
  5394. 'answer' => $fullContent,
  5395. 'reasoning' => $fullReasoningContent,
  5396. 'usage' => $usage,
  5397. 'error' => $e->getMessage(),
  5398. ];
  5399. return;
  5400. }
  5401. DB::commit();
  5402. if ($is_global_generate_pics) {
  5403. // // 批量生成全局角色图片
  5404. // $this->batchSetGlobalRoleImg([
  5405. // 'anime_id' => $anime_id,
  5406. // ], true);
  5407. // // 批量生成全局场景图片
  5408. // $this->batchSetGlobalSceneImg([
  5409. // 'anime_id' => $anime_id,
  5410. // ], true);
  5411. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5412. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5413. }
  5414. $episode['episode_id'] = $episode_id;
  5415. $episode['roles'] = $merged_roles;
  5416. $episode['scenes'] = $merged_scenes;
  5417. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  5418. yield [
  5419. 'type' => 'done',
  5420. 'episode' => $episode,
  5421. 'answer' => $fullContent,
  5422. 'reasoning' => $fullReasoningContent,
  5423. 'usage' => $usage
  5424. ];
  5425. }
  5426. public function addChatForAce($data) {
  5427. $uid = Site::getUid();
  5428. $anime_id = getProp($data, 'anime_id');
  5429. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5430. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5431. if (!$anime) Utils::throwError('20003:对话不存在');
  5432. $file = getProp($data, 'file');
  5433. $content = getProp($data, 'content', '');
  5434. $bid = getProp($data, 'bid', 0);
  5435. $script_id = getProp($data, 'script_id', 0);
  5436. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5437. $prompt = getProp($data, 'prompt');
  5438. $is_multi = getProp($anime, 'is_multi');
  5439. $is_single = (int)$is_multi !== 1;
  5440. // 积分余额预检(仅单剧集模式收费)
  5441. if ($is_single) {
  5442. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  5443. }
  5444. $extra_products = getProp($data, 'products', []);
  5445. if (!$extra_products) {
  5446. $extra_products = getProp($anime, 'extra_products');
  5447. if ($extra_products) {
  5448. $extra_products = json_decode($extra_products, true);
  5449. }else {
  5450. $extra_products = [];
  5451. }
  5452. }else {
  5453. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  5454. }
  5455. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  5456. $anime_script_id = getProp($anime, 'script_id');
  5457. if ($anime_script_id && $is_single) { // 单剧集模式下才使用全部资产库
  5458. $cpid = Site::getCpid();
  5459. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  5460. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  5461. ->where('mapping.script_id', $anime_script_id)
  5462. ->where('product.cpid', $cpid)
  5463. ->where('product.is_deleted', 0);
  5464. $mappings = $script_products_mappings->select(
  5465. 'mapping.product_id',
  5466. 'mapping.episode_number',
  5467. 'product.product_name',
  5468. 'product.type',
  5469. 'product.product',
  5470. 'product.pic_prompt',
  5471. 'product.url',
  5472. 'product.pic_task_id',
  5473. 'product.pic_task_status',
  5474. 'product.three_view_image_url'
  5475. )
  5476. ->get();
  5477. // 按 product_id 分组,合并 episode_number
  5478. $productMap = [];
  5479. foreach ($mappings as $item) {
  5480. $product_id = $item->product_id;
  5481. $product_name = $item->product_name;
  5482. // 处理product_name两边的符号
  5483. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  5484. if (!isset($productMap[$product_id])) {
  5485. $productMap[$product_id] = [
  5486. 'product_id' => $product_id,
  5487. 'product_name' => $product_name,
  5488. 'type' => (int)$item->type,
  5489. 'product' => (int)$item->product,
  5490. 'pic_prompt' => $item->pic_prompt,
  5491. 'url' => $item->url,
  5492. 'pic_task_id' => $item->pic_task_id,
  5493. 'pic_task_status' => $item->pic_task_status,
  5494. 'episode_numbers' => [],
  5495. ];
  5496. }
  5497. // 添加 episode_number(去重)
  5498. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  5499. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  5500. }
  5501. }
  5502. // 将查询到的剧本资产合并到extra_products中
  5503. // 先构建extra_products的索引(以product_id为key,用于去重)
  5504. $extraProductsMap = [];
  5505. foreach ($extra_products as $item) {
  5506. $key = getProp($item, 'product_id');
  5507. if ($key) {
  5508. $extraProductsMap[$key] = $item;
  5509. }
  5510. }
  5511. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  5512. foreach ($productMap as $product) {
  5513. $product_id = $product['product_id'];
  5514. // 如果不存在则添加(不带episode_number信息)
  5515. if (!isset($extraProductsMap[$product_id])) {
  5516. $extraProductsMap[$product_id] = [
  5517. 'product_id' => $product['product_id'],
  5518. 'product_name' => $product['product_name'],
  5519. 'type' => $product['type'],
  5520. 'product' => $product['product'],
  5521. 'pic_prompt' => $product['pic_prompt'],
  5522. 'url' => $product['url'],
  5523. 'pic_task_id' => $product['pic_task_id'],
  5524. 'pic_task_status' => $product['pic_task_status'],
  5525. ];
  5526. }
  5527. }
  5528. // 重新赋值给extra_products
  5529. $extra_products = array_values($extraProductsMap);
  5530. }
  5531. $user_anime_name = getProp($anime, 'anime_name');
  5532. // 处理提示词
  5533. if ($prompt && $extra_products) {
  5534. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  5535. foreach($extra_products as $item) {
  5536. $product_name = getProp($item, 'product_name');
  5537. if ($product_name) {
  5538. // 替换 {product_name} 为 product_name
  5539. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  5540. }
  5541. }
  5542. }
  5543. // 处理文本模型
  5544. $model = getProp($data, 'model');
  5545. if (!$model) {
  5546. // 用户没有输入,从anime表获取
  5547. $model = getProp($anime, 'model');
  5548. if (!$model) {
  5549. // anime表也没有,使用默认值
  5550. $model = 'deepseek-v4-pro';
  5551. }
  5552. }
  5553. // 验证模型是否在可用模型表中
  5554. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5555. $model = 'deepseek-v4-pro';
  5556. }
  5557. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  5558. if ($prompt) {
  5559. $question .= "本次修改要求如下:\n{$prompt}";
  5560. }
  5561. // if (!$file && !$content && !$bid) {
  5562. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5563. // }
  5564. // 提取文件内容
  5565. if ($file) {
  5566. $content = $this->extractFileContent($file);
  5567. if (!$content) {
  5568. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5569. }
  5570. } elseif ($script_id) {
  5571. $content = $this->getContentByScriptId($script_id);
  5572. if (!$content) {
  5573. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5574. }
  5575. } elseif ($bid) {
  5576. $content = $this->getContentByBid($bid);
  5577. if (!$content) {
  5578. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5579. }
  5580. } elseif ($content) {
  5581. $content = filterContent($content);
  5582. } else {
  5583. $content = getProp($anime, 'content');
  5584. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5585. $need_generate_content = true;
  5586. }
  5587. }
  5588. // 美术风格
  5589. $input_art_style = getProp($data, 'art_style');
  5590. if (!$input_art_style) {
  5591. $mappedArtStyle = getProp($anime, 'art_style');
  5592. }else {
  5593. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5594. }
  5595. // 判断是否需要生成原文内容
  5596. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5597. // 如果需要生成原文内容,添加额外的要求
  5598. $content_generation_requirement = $need_generate_content
  5599. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5600. : "";
  5601. // 美术风格
  5602. if (!$mappedArtStyle) {
  5603. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5604. }else {
  5605. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5606. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5607. }else {
  5608. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5609. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5610. }
  5611. }
  5612. // 构建主体、场景和道具提示词
  5613. $extra_role_prompt = "\n";
  5614. $extra_scene_prompt = "\n";
  5615. $extra_prop_prompt = "\n";
  5616. $ref_products = []; // 参考资产
  5617. if ($extra_products) {
  5618. foreach($extra_products as $item) {
  5619. $product = getProp($item, 'product');
  5620. $product_name = getProp($item, 'product_name');
  5621. if ($product_name == '旁白') continue;
  5622. $ref_products[$product_name] = $item;
  5623. $pic_prompt = getProp($item, 'pic_prompt');
  5624. if ((int)$product === 1) {
  5625. // 拼接角色信息
  5626. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5627. } elseif ((int)$product === 2) {
  5628. // 拼接场景信息
  5629. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5630. } elseif ((int)$product === 3) {
  5631. // 拼接道具信息
  5632. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5633. }
  5634. }
  5635. // 优化提示词,融入剧本
  5636. if (!empty(trim($extra_role_prompt))) {
  5637. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  5638. }
  5639. if (!empty(trim($extra_scene_prompt))) {
  5640. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  5641. }
  5642. if (!empty(trim($extra_prop_prompt))) {
  5643. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  5644. }
  5645. }
  5646. if ($anime_script_id && $is_single) {
  5647. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  5648. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  5649. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  5650. }else {
  5651. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5652. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5653. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5654. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5655. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5656. {$extra_role_prompt}";
  5657. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5658. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5659. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5660. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5661. {$extra_scene_prompt}";
  5662. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5663. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5664. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5665. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5666. {$extra_prop_prompt}";
  5667. }
  5668. $systemPrompt = $is_single
  5669. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5670. 强制要求:
  5671. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5672. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5673. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5674. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5675. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5676. 普通要求:
  5677. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5678. $role_demo
  5679. $scene_demo
  5680. $prop_demo
  5681. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  5682. 5.1片段分割逻辑(优先级从高到低):
  5683. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  5684. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  5685. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  5686. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  5687. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  5688. - 片段数量格式为: 片段数量:8
  5689. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5690. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  5691. 5.3分镜结构:每个分镜包含以下字段:
  5692. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  5693. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5694. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5695. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5696. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  5697. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5698. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  5699. - 运镜:场景+画面描述+运镜
  5700. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  5701. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  5702. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  5703. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  5704. 6.{$mappedArtStyle_prompt}\n\n
  5705. 示例如下:\n
  5706. ###剧本名:西昆仑
  5707. ###故事梗概
  5708. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5709. ###剧本亮点
  5710. 亮点1:绝境奇药,生死一线
  5711. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5712. 亮点2:结拜兄妹,化解尴尬
  5713. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5714. 亮点3:纤发夺命,情愫暗涌
  5715. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5716. ###人物关系
  5717. 阿雪与梁萧之间存在兄妹之情。
  5718. ###核心矛盾
  5719. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5720. ###主体列表
  5721. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5722. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5723. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5724. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5725. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5726. 全景,正面拍摄,青年女性,亚洲人。
  5727. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5728. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5729. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5730. ###美术风格
  5731. 基础画风风格词:厚涂古风
  5732. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5733. ###场景列表
  5734. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5735. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5736. 无人物。}
  5737. ###分段剧本
  5738. 片段数量:8
  5739. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  5740. ##片段1
  5741. 时长:12s
  5742. 分镜1
  5743. 出场角色:刀疤脸
  5744. 场景:边境小镇街道
  5745. 出场道具:酒杯-高脚杯
  5746. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  5747. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  5748. 配音台词:
  5749. 背景音效:
  5750. 分镜2
  5751. 出场角色:刀疤脸
  5752. 场景:悦来酒馆
  5753. 出场道具:酒杯-高脚杯
  5754. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  5755. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  5756. 配音台词:
  5757. 背景音效:
  5758. 分镜3
  5759. 出场角色:刀疤脸
  5760. 场景:悦来酒馆
  5761. 出场道具:酒杯-高脚杯
  5762. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  5763. 运镜:从中景推向令牌特写。
  5764. 配音台词:
  5765. 背景音效:
  5766. 分镜4
  5767. 出场角色:刀疤脸
  5768. 场景:悦来酒馆
  5769. 出场道具:酒杯-高脚杯
  5770. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  5771. 运镜:极速推向酒水溅起的瞬间。
  5772. 配音台词:
  5773. 背景音效:
  5774. 分镜5
  5775. 出场角色:刀疤脸
  5776. 场景:悦来酒馆
  5777. 出场道具:酒杯-高脚杯
  5778. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  5779. 运镜:固定机位,利用倾斜构图制造压迫感。
  5780. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  5781. 背景音效:
  5782. \n\n"
  5783. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5784. 强制要求:\n
  5785. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5786. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5787. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5788. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5789. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5790. 普通要求:\n
  5791. 1.剧本名(必须生成)必须与文档内容高度相关
  5792. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5793. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5794. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5795. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5796. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5797. {$extra_role_prompt}
  5798. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5799. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5800. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5801. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5802. {$extra_scene_prompt}
  5803. 4.<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5804. 3.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  5805. 3.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  5806. 3.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  5807. {$extra_prop_prompt}
  5808. 5.{$mappedArtStyle_prompt}\n\n
  5809. 示例如下:\n
  5810. ###剧本名:西昆仑
  5811. ###故事梗概
  5812. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5813. ###剧本亮点
  5814. 亮点1:绝境奇药,生死一线
  5815. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5816. 亮点2:结拜兄妹,化解尴尬
  5817. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5818. 亮点3:纤发夺命,情愫暗涌
  5819. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5820. ###人物关系
  5821. 阿雪与梁萧之间存在兄妹之情。
  5822. ###核心矛盾
  5823. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5824. ###主体列表
  5825. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5826. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5827. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5828. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5829. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5830. 全景,正面拍摄,青年女性,亚洲人。
  5831. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5832. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5833. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5834. ###美术风格
  5835. 基础画风风格词:厚涂古风
  5836. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5837. ###场景列表
  5838. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5839. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5840. 无人物。}
  5841. ###道具列表
  5842. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}";
  5843. // 构建消息
  5844. $messages = [
  5845. [
  5846. 'role' => 'system',
  5847. 'content' => $systemPrompt
  5848. ],
  5849. [
  5850. 'role' => 'user',
  5851. 'content' => "以下是文档内容:
  5852. {$content}
  5853. 用户问题:
  5854. {$question}"
  5855. ]
  5856. ];
  5857. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5858. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5859. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5860. if ($model === 'deepseek-chat') {
  5861. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5862. $model = 'deepseek-v4-flash';
  5863. $thinkingMode = 'disabled';
  5864. } elseif ($model === 'deepseek-reasoner') {
  5865. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5866. $model = 'deepseek-v4-flash';
  5867. $thinkingMode = 'enabled';
  5868. }
  5869. $post_data = [
  5870. 'model' => $model,
  5871. 'messages' => $messages,
  5872. // 'max_tokens' => 8192,
  5873. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  5874. 'frequency_penalty' => 0,
  5875. 'presence_penalty' => 0,
  5876. 'response_format' => ['type' => 'text'],
  5877. 'thinking' => ['type'=>$thinkingMode],
  5878. 'stream' => true // 启用流式输出
  5879. ];
  5880. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5881. // 根据模型类型选择调用方法
  5882. $fullContent = '';
  5883. $fullReasoningContent = '';
  5884. $usage = [];
  5885. try {
  5886. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5887. // DeepSeek 官方模型使用 DeepSeek API
  5888. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5889. } else if (in_array($model, $this->gpt_text_models)) {
  5890. // GPT-5.4 模型使用 TokenRouter API
  5891. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5892. } else {
  5893. // 其他模型使用火山引擎API
  5894. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5895. }
  5896. // 验证返回值类型
  5897. if (!is_iterable($streamGenerator)) {
  5898. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5899. dLog('deepseek')->error('addChat流式生成器无效', [
  5900. 'generator_type' => $errorType,
  5901. 'model' => $model,
  5902. 'anime_id' => $anime_id
  5903. ]);
  5904. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5905. 'type' => $errorType,
  5906. 'model' => $model
  5907. ]);
  5908. yield [
  5909. 'type' => 'error',
  5910. 'script' => [],
  5911. 'episode' => [],
  5912. 'answer' => '',
  5913. 'reasoning' => '',
  5914. 'usage' => [],
  5915. 'error' => '接口返回数据异常,请重新请求'
  5916. ];
  5917. return;
  5918. }
  5919. // 处理流式输出
  5920. foreach ($streamGenerator as $chunk) {
  5921. if (isset($chunk['type'])) {
  5922. if ($chunk['type'] === 'done') {
  5923. // 最终结果
  5924. $fullContent = $chunk['full_content'];
  5925. $fullReasoningContent = $chunk['full_reasoning'];
  5926. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5927. } else {
  5928. // 逐块yield数据
  5929. yield $chunk;
  5930. }
  5931. }
  5932. }
  5933. } catch (\Exception $e) {
  5934. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5935. 'model' => $model,
  5936. 'anime_id' => $anime_id,
  5937. 'trace' => $e->getTraceAsString()
  5938. ]);
  5939. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5940. 'error' => $e->getMessage(),
  5941. 'model' => $model
  5942. ]);
  5943. yield [
  5944. 'type' => 'error',
  5945. 'script' => [],
  5946. 'episode' => [],
  5947. 'answer' => '',
  5948. 'reasoning' => '',
  5949. 'usage' => [],
  5950. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5951. ];
  5952. return;
  5953. }
  5954. dLog('deepseek')->info('完整内容: '.$fullContent);
  5955. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5956. // 处理完整内容并返回最终结果
  5957. $script_arr = [];
  5958. if ($fullContent) {
  5959. $script_arr = handleScriptContentForAce($fullContent);
  5960. dLog('deepseek')->info('解析内容', $script_arr);
  5961. logDB('deepseek', 'info', '解析内容', $script_arr);
  5962. }
  5963. if (empty($script_arr['roles'])) {
  5964. // 未生成剧本相关内容,保存对话记录并返回提示
  5965. dLog('deepseek')->info('未生成剧本相关的内容');
  5966. try {
  5967. DB::beginTransaction();
  5968. $now = date('Y-m-d H:i:s');
  5969. // 保存对话记录
  5970. $records = [
  5971. [
  5972. 'uid' => $uid,
  5973. 'anime_id' => $anime_id,
  5974. 'sequence' => 0,
  5975. 'role' => 'user',
  5976. 'content' => $prompt,
  5977. 'created_at' => $now,
  5978. 'updated_at' => $now
  5979. ],
  5980. [
  5981. 'uid' => $uid,
  5982. 'anime_id' => $anime_id,
  5983. 'sequence' => 0,
  5984. 'role' => 'assistant',
  5985. // 'content' => $fullContent,
  5986. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5987. 'created_at' => $now,
  5988. 'updated_at' => $now
  5989. ]
  5990. ];
  5991. DB::table('mp_anime_records')->insert($records);
  5992. DB::commit();
  5993. } catch (\Exception $e) {
  5994. DB::rollBack();
  5995. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5996. }
  5997. yield [
  5998. 'type' => 'done',
  5999. 'script' => [],
  6000. 'episode' => [],
  6001. 'answer' => $fullContent,
  6002. 'reasoning' => $fullReasoningContent,
  6003. 'usage' => $usage,
  6004. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6005. ];
  6006. return;
  6007. }
  6008. // 如果需要生成原文内容,从script_arr中提取
  6009. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6010. $content = $script_arr['content'];
  6011. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  6012. if (!$content) {
  6013. yield [
  6014. 'type' => 'done',
  6015. 'script' => [],
  6016. 'episode' => [],
  6017. 'answer' => $fullContent,
  6018. 'reasoning' => $fullReasoningContent,
  6019. 'usage' => $usage,
  6020. 'error' => '未生成剧本内容,请调整提示词再试'
  6021. ];
  6022. return;
  6023. }
  6024. }
  6025. // 替换美术风格
  6026. if ($mappedArtStyle !== '') {
  6027. $script_arr['art_style'] = $mappedArtStyle;
  6028. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6029. }
  6030. // 新建动漫
  6031. if ($user_anime_name == '新剧本策划') {
  6032. $anime_name = getProp($script_arr, 'script_name');
  6033. // if (!$anime_name) {
  6034. // // 未识别到剧本名,保存对话记录并返回提示
  6035. // dLog('deepseek')->info('未能识别到剧本名称');
  6036. // try {
  6037. // DB::beginTransaction();
  6038. // $now = date('Y-m-d H:i:s');
  6039. // // 保存对话记录
  6040. // $records = [
  6041. // [
  6042. // 'uid' => $uid,
  6043. // 'anime_id' => $anime_id,
  6044. // 'sequence' => 0,
  6045. // 'role' => 'user',
  6046. // 'content' => $prompt,
  6047. // 'created_at' => $now,
  6048. // 'updated_at' => $now
  6049. // ],
  6050. // [
  6051. // 'uid' => $uid,
  6052. // 'anime_id' => $anime_id,
  6053. // 'sequence' => 0,
  6054. // 'role' => 'assistant',
  6055. // 'content' => '未能生成剧本名称,请重试',
  6056. // 'created_at' => $now,
  6057. // 'updated_at' => $now
  6058. // ]
  6059. // ];
  6060. // DB::table('mp_anime_records')->insert($records);
  6061. // DB::commit();
  6062. // } catch (\Exception $e) {
  6063. // DB::rollBack();
  6064. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6065. // }
  6066. // yield [
  6067. // 'type' => 'done',
  6068. // 'script' => [],
  6069. // 'episode' => [],
  6070. // 'answer' => $fullContent,
  6071. // 'reasoning' => $fullReasoningContent,
  6072. // 'usage' => $usage,
  6073. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  6074. // ];
  6075. // return;
  6076. // }
  6077. // 确认对话名称唯一性
  6078. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6079. $anime_name = $anime_name . '_' . date('YmdHis');
  6080. }
  6081. }else {
  6082. $anime_name = $user_anime_name;
  6083. }
  6084. $table_data = [
  6085. 'user_id' => $uid,
  6086. 'anime_name' => $anime_name,
  6087. 'model' => $model,
  6088. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6089. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6090. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6091. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6092. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6093. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6094. 'art_style_type' => $input_art_style,
  6095. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6096. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6097. 'status' => '解析完成',
  6098. 'content' => $content,
  6099. 'is_multi' => $is_multi,
  6100. 'ace_mode' => $ace_mode,
  6101. 'generate_status' => '待执行',
  6102. 'updated_at' => date('Y-m-d H:i:s')
  6103. ];
  6104. if ($table_data['content']) {
  6105. $chapters = splitContent($table_data['content']);
  6106. $chapter_count = count($chapters);
  6107. if ($chapter_count > 0) {
  6108. $table_data['start_episode_sequence'] = 1;
  6109. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6110. }
  6111. }
  6112. if ($extra_products) {
  6113. $table_data['extra_products'] = json_encode($extra_products, 256);
  6114. }
  6115. // 如果有剧本ID则进行绑定
  6116. if ($script_id) {
  6117. $table_data['script_id'] = $script_id;
  6118. }
  6119. $single_episode = [];
  6120. try {
  6121. DB::beginTransaction();
  6122. $now = date('Y-m-d H:i:s');
  6123. // 更新动漫大纲
  6124. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6125. if (!$boolen) {
  6126. dLog('deepseek')->info('动漫保存失败', $table_data);
  6127. Utils::throwError('20003:动漫保存失败');
  6128. }
  6129. // 保存对话记录
  6130. $records = [
  6131. [
  6132. 'uid' => $uid,
  6133. 'anime_id' => $anime_id,
  6134. 'sequence' => 0,
  6135. 'role' => 'user',
  6136. 'content' => $prompt,
  6137. 'created_at' => date('Y-m-d H:i:s'),
  6138. 'updated_at' => date('Y-m-d H:i:s')
  6139. ],
  6140. [
  6141. 'uid' => $uid,
  6142. 'anime_id' => $anime_id,
  6143. 'sequence' => 0,
  6144. 'role' => 'assistant',
  6145. 'content' => $fullContent,
  6146. 'created_at' => date('Y-m-d H:i:s'),
  6147. 'updated_at' => date('Y-m-d H:i:s')
  6148. ]
  6149. ];
  6150. // 保存对话记录
  6151. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6152. if (!$boolen3) {
  6153. Utils::throwError('20003:对话记录保存失败');
  6154. }
  6155. if ($is_single) {
  6156. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6157. if (empty($episode_arr['acts'])) {
  6158. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6159. }
  6160. $saveResult = $this->saveEpisodeVersionData(
  6161. $anime_id,
  6162. 1,
  6163. $episode_arr,
  6164. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6165. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6166. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6167. null,
  6168. null,
  6169. false,
  6170. $content,
  6171. $now,
  6172. $ref_products
  6173. );
  6174. $single_episode = $saveResult['episode'];
  6175. $episode_id = $saveResult['episode_id'];
  6176. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6177. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6178. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6179. 'props' => json_encode($saveResult['merged_props'], 256),
  6180. 'updated_at' => $now
  6181. ]);
  6182. if ($boolen5 === false) {
  6183. Utils::throwError('20003:单剧集主表资源同步失败');
  6184. }
  6185. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6186. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6187. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  6188. $episode_record_content = '确认分镜大纲';
  6189. if ($content !== '') {
  6190. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6191. }
  6192. $episode_records = [
  6193. [
  6194. 'uid' => $uid,
  6195. 'anime_id' => $anime_id,
  6196. 'role' => 'user',
  6197. 'content' => $episode_record_content,
  6198. 'sequence' => 1,
  6199. 'episode_id' => $episode_id,
  6200. 'created_at' => $now,
  6201. 'updated_at' => $now
  6202. ],
  6203. [
  6204. 'uid' => $uid,
  6205. 'anime_id' => $anime_id,
  6206. 'role' => 'assistant',
  6207. 'content' => $fullContent,
  6208. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6209. 'sequence' => 1,
  6210. 'episode_id' => $episode_id,
  6211. 'created_at' => $now,
  6212. 'updated_at' => $now
  6213. ]
  6214. ];
  6215. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6216. if (!$boolen4) {
  6217. Utils::throwError('20003:单剧集分镜记录保存失败');
  6218. }
  6219. }
  6220. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  6221. if ($is_single && !empty($single_episode)) {
  6222. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  6223. 'anime_id' => $anime_id,
  6224. 'episode_id' => $episode_id ?? 0,
  6225. ]);
  6226. }
  6227. }catch (\Exception $e) {
  6228. DB::rollBack();
  6229. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  6230. yield [
  6231. 'type' => 'done',
  6232. 'answer' => $fullContent,
  6233. 'reasoning' => $fullReasoningContent,
  6234. 'usage' => $usage,
  6235. 'error' => $e->getMessage(),
  6236. ];
  6237. return;
  6238. }
  6239. DB::commit();
  6240. dLog('deepseek')->info('保存完毕');
  6241. if ($is_single && !empty($single_episode)) {
  6242. // $this->batchSetGlobalRoleImg([
  6243. // 'anime_id' => $anime_id,
  6244. // ]);
  6245. // $this->batchSetGlobalSceneImg([
  6246. // 'anime_id' => $anime_id,
  6247. // ]);
  6248. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6249. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6250. }
  6251. $table_data['anime_id'] = $anime_id;
  6252. $table_data['roles'] = json_decode($table_data['roles'], true);
  6253. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6254. // $table_data['episodes'] = $script_arr['episodes'];
  6255. unset($table_data['created_at']);
  6256. unset($table_data['updated_at']);
  6257. unset($table_data['status']);
  6258. dLog('deepseek')->info('开始返回');
  6259. yield [
  6260. 'type' => 'done',
  6261. 'script' => $table_data,
  6262. 'episode' => $single_episode,
  6263. 'answer' => $fullContent,
  6264. 'reasoning' => $fullReasoningContent,
  6265. 'usage' => $usage
  6266. ];
  6267. }
  6268. public function reGenerateAnimeForAce($data) {
  6269. $uid = Site::getUid();
  6270. $file = getProp($data, 'file');
  6271. $content = getProp($data, 'content', '');
  6272. $bid = getProp($data, 'bid', 0);
  6273. $script_id = getProp($data, 'script_id', 0);
  6274. $anime_id = getProp($data, 'anime_id');
  6275. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6276. if (!$anime) {
  6277. Utils::throwError('20003:该对话不存在');
  6278. }
  6279. $is_multi = getProp($anime, 'is_multi', 1);
  6280. $is_single = (int)$is_multi !== 1;
  6281. // 积分余额预检(仅单剧集模式收费)
  6282. if ($is_single) {
  6283. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  6284. }
  6285. $extra_products = getProp($data, 'products', []);
  6286. if (!$extra_products) {
  6287. $extra_products = getProp($anime, 'extra_products');
  6288. if ($extra_products) {
  6289. $extra_products = json_decode($extra_products, true);
  6290. }else {
  6291. $extra_products = [];
  6292. }
  6293. }else {
  6294. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6295. }
  6296. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6297. $anime_script_id = getProp($anime, 'script_id');
  6298. if ($anime_script_id && $is_single) {
  6299. $cpid = Site::getCpid();
  6300. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6301. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6302. ->where('mapping.script_id', $anime_script_id)
  6303. ->where('product.cpid', $cpid)
  6304. ->where('product.is_deleted', 0);
  6305. $mappings = $script_products_mappings->select(
  6306. 'mapping.product_id',
  6307. 'mapping.episode_number',
  6308. 'product.product_name',
  6309. 'product.type',
  6310. 'product.product',
  6311. 'product.pic_prompt',
  6312. 'product.url',
  6313. 'product.pic_task_id',
  6314. 'product.pic_task_status',
  6315. 'product.three_view_image_url'
  6316. )
  6317. ->get();
  6318. // 按 product_id 分组,合并 episode_number
  6319. $productMap = [];
  6320. foreach ($mappings as $item) {
  6321. $product_id = $item->product_id;
  6322. $product_name = $item->product_name;
  6323. // 处理product_name两边的符号
  6324. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6325. if (!isset($productMap[$product_id])) {
  6326. $productMap[$product_id] = [
  6327. 'product_id' => $product_id,
  6328. 'product_name' => $product_name,
  6329. 'type' => (int)$item->type,
  6330. 'product' => (int)$item->product,
  6331. 'pic_prompt' => $item->pic_prompt,
  6332. 'url' => $item->url,
  6333. 'pic_task_id' => $item->pic_task_id,
  6334. 'pic_task_status' => $item->pic_task_status,
  6335. 'episode_numbers' => [],
  6336. ];
  6337. }
  6338. // 添加 episode_number(去重)
  6339. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6340. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6341. }
  6342. }
  6343. // 将查询到的剧本资产合并到extra_products中
  6344. // 先构建extra_products的索引(以product_id为key,用于去重)
  6345. $extraProductsMap = [];
  6346. foreach ($extra_products as $item) {
  6347. $key = getProp($item, 'product_id');
  6348. if ($key) {
  6349. $extraProductsMap[$key] = $item;
  6350. }
  6351. }
  6352. // 合并剧本资产(去重:仅按product_id去重,不考虑episode_number)
  6353. foreach ($productMap as $product) {
  6354. $product_id = $product['product_id'];
  6355. // 如果不存在则添加(不带episode_number信息)
  6356. if (!isset($extraProductsMap[$product_id])) {
  6357. $extraProductsMap[$product_id] = [
  6358. 'product_id' => $product['product_id'],
  6359. 'product_name' => $product['product_name'],
  6360. 'type' => $product['type'],
  6361. 'product' => $product['product'],
  6362. 'pic_prompt' => $product['pic_prompt'],
  6363. 'url' => $product['url'],
  6364. 'pic_task_id' => $product['pic_task_id'],
  6365. 'pic_task_status' => $product['pic_task_status'],
  6366. ];
  6367. }
  6368. }
  6369. // 重新赋值给extra_products
  6370. $extra_products = array_values($extraProductsMap);
  6371. }
  6372. $user_anime_name = getProp($anime, 'anime_name');
  6373. $prompt = getProp($data, 'prompt');
  6374. // 处理提示词
  6375. if ($prompt && $extra_products) {
  6376. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6377. foreach($extra_products as $item) {
  6378. $product_name = getProp($item, 'product_name');
  6379. if ($product_name) {
  6380. // 替换 {product_name} 为 product_name
  6381. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6382. }
  6383. }
  6384. }
  6385. // 处理文本模型
  6386. $model = getProp($data, 'model');
  6387. if (!$model) {
  6388. // 用户没有输入,从anime表获取
  6389. $model = getProp($anime, 'model');
  6390. if (!$model) {
  6391. // anime表也没有,使用默认值
  6392. $model = 'deepseek-v4-pro';
  6393. }
  6394. }
  6395. // 验证模型是否在可用模型表中
  6396. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  6397. $model = 'deepseek-v4-pro';
  6398. }
  6399. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  6400. if ($is_single) {
  6401. $episode_exists = DB::table('mp_anime_episodes')
  6402. ->where('anime_id', $anime_id)
  6403. ->where('sequence', 1)
  6404. ->exists();
  6405. if ($episode_exists) {
  6406. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  6407. }
  6408. }
  6409. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  6410. if ($prompt) {
  6411. $question .= "本次修改要求如下:\n{$prompt}";
  6412. }
  6413. // 提取文件内容
  6414. if ($file) {
  6415. $content = $this->extractFileContent($file);
  6416. if (!$content) {
  6417. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6418. }
  6419. } elseif ($script_id) {
  6420. $content = $this->getContentByScriptId($script_id);
  6421. if (!$content) {
  6422. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6423. }
  6424. } elseif ($bid) {
  6425. $content = $this->getContentByBid($bid);
  6426. if (!$content) {
  6427. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6428. }
  6429. } elseif ($content) {
  6430. $content = filterContent($content);
  6431. }else {
  6432. $content = filterContent(getProp($anime, 'content'));
  6433. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6434. $need_generate_content = true;
  6435. }
  6436. }
  6437. // 判断是否需要生成原文内容
  6438. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6439. // 如果需要生成原文内容,添加额外的要求
  6440. $content_generation_requirement = $need_generate_content
  6441. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6442. : "";
  6443. // 美术风格
  6444. $input_art_style = getProp($data, 'art_style');
  6445. if (!$input_art_style) {
  6446. $mappedArtStyle = getProp($anime, 'art_style');
  6447. }else {
  6448. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6449. }
  6450. if (!$mappedArtStyle) {
  6451. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6452. }else {
  6453. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6454. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6455. }else {
  6456. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6457. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6458. }
  6459. }
  6460. // 构建主体、场景和道具提示词
  6461. $extra_role_prompt = "\n";
  6462. $extra_scene_prompt = "\n";
  6463. $extra_prop_prompt = "\n";
  6464. $ref_products = []; // 参考资产
  6465. if ($extra_products) {
  6466. foreach($extra_products as $item) {
  6467. $product = getProp($item, 'product');
  6468. $product_name = getProp($item, 'product_name');
  6469. if ($product_name == '旁白') continue;
  6470. $ref_products[$product_name] = $item;
  6471. $pic_prompt = getProp($item, 'pic_prompt');
  6472. if ((int)$product === 1) {
  6473. // 拼接角色信息
  6474. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6475. } elseif ((int)$product === 2) {
  6476. // 拼接场景信息
  6477. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6478. } elseif ((int)$product === 3) {
  6479. // 拼接道具信息
  6480. $extra_prop_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6481. }
  6482. }
  6483. // 优化提示词,融入剧本
  6484. if (!empty(trim($extra_role_prompt))) {
  6485. $extra_role_prompt = "\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6486. }
  6487. if (!empty(trim($extra_scene_prompt))) {
  6488. $extra_scene_prompt = "\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6489. }
  6490. if (!empty(trim($extra_prop_prompt))) {
  6491. $extra_prop_prompt = "\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,必须包含:\n" . $extra_prop_prompt . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n必须包含的道具列表:\n" . $extra_prop_prompt . "\n【重要提示】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6492. }
  6493. }
  6494. if ($anime_script_id && $is_single) {
  6495. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_role_prompt}";
  6496. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_scene_prompt}";
  6497. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$extra_prop_prompt}";
  6498. }else {
  6499. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6500. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6501. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6502. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6503. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6504. {$extra_role_prompt}";
  6505. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6506. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6507. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6508. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6509. {$extra_scene_prompt}";
  6510. $prop_demo = "4<道具列表>与场景列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6511. 4.1<道具列表>分以下两部分(强制格式):道具描述和道具提示词,格式必须为:道具描述{道具提示词}
  6512. 4.2<道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6513. 4.3<道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。\n
  6514. {$extra_prop_prompt}";
  6515. }
  6516. $system_message = ['role'=>'system', 'content'=>$is_single
  6517. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6518. 强制要求:
  6519. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6520. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6521. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6522. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6523. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6524. 普通要求:
  6525. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6526. $role_demo
  6527. $scene_demo
  6528. $prop_demo
  6529. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6530. 5.1片段分割逻辑(优先级从高到低):
  6531. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6532. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6533. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6534. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6535. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6536. - 片段数量格式为: 片段数量:8
  6537. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6538. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6539. 5.3分镜结构:每个分镜包含以下字段:
  6540. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  6541. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6542. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6543. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6544. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6545. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6546. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  6547. - 运镜:场景+画面描述+运镜
  6548. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  6549. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  6550. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6551. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6552. 6.{$mappedArtStyle_prompt}\n\n
  6553. 示例如下:\n
  6554. ###剧本名:西昆仑
  6555. ###故事梗概
  6556. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6557. ###剧本亮点
  6558. 亮点1:绝境奇药,生死一线
  6559. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6560. 亮点2:结拜兄妹,化解尴尬
  6561. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6562. 亮点3:纤发夺命,情愫暗涌
  6563. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6564. ###人物关系
  6565. 阿雪与梁萧之间存在兄妹之情。
  6566. ###核心矛盾
  6567. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6568. ###主体列表
  6569. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6570. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6571. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6572. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6573. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6574. 全景,正面拍摄,青年女性,亚洲人。
  6575. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6576. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6577. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6578. ###美术风格
  6579. 基础画风风格词:厚涂古风
  6580. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6581. ###场景列表
  6582. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6583. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6584. 无人物。}
  6585. ###分段剧本
  6586. 片段数量:8
  6587. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6588. ##片段1
  6589. 时长:12s
  6590. 分镜1
  6591. 出场角色:刀疤脸
  6592. 场景:边境小镇街道
  6593. 出场道具:酒杯-高脚杯
  6594. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6595. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6596. 配音台词:
  6597. 背景音效:
  6598. 分镜2
  6599. 出场角色:刀疤脸
  6600. 场景:悦来酒馆
  6601. 出场道具:酒杯-高脚杯
  6602. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6603. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6604. 配音台词:
  6605. 背景音效:
  6606. 分镜3
  6607. 出场角色:刀疤脸
  6608. 场景:悦来酒馆
  6609. 出场道具:酒杯-高脚杯
  6610. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6611. 运镜:从中景推向令牌特写。
  6612. 配音台词:
  6613. 背景音效:
  6614. 分镜4
  6615. 出场角色:刀疤脸
  6616. 场景:悦来酒馆
  6617. 出场道具:酒杯-高脚杯
  6618. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6619. 运镜:极速推向酒水溅起的瞬间。
  6620. 配音台词:
  6621. 背景音效:
  6622. 分镜5
  6623. 出场角色:刀疤脸
  6624. 场景:悦来酒馆
  6625. 出场道具:酒杯-高脚杯
  6626. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6627. 运镜:固定机位,利用倾斜构图制造压迫感。
  6628. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6629. 背景音效:
  6630. \n\n"
  6631. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><道具列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6632. 强制要求:\n
  6633. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6634. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6635. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6636. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6637. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6638. 普通要求:\n
  6639. 1.剧本名(必须生成)必须与文档内容高度相关
  6640. $role_demo
  6641. $scene_demo
  6642. $prop_demo
  6643. 5.{$mappedArtStyle_prompt}\n\n
  6644. 示例如下:\n
  6645. ###剧本名:西昆仑
  6646. ###故事梗概
  6647. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6648. ###剧本亮点
  6649. 亮点1:绝境奇药,生死一线
  6650. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6651. 亮点2:结拜兄妹,化解尴尬
  6652. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6653. 亮点3:纤发夺命,情愫暗涌
  6654. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6655. ###人物关系
  6656. 阿雪与梁萧之间存在兄妹之情。
  6657. ###核心矛盾
  6658. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6659. ###主体列表
  6660. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6661. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6662. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6663. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6664. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6665. 全景,正面拍摄,青年女性,亚洲人。
  6666. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6667. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6668. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6669. ###美术风格
  6670. 基础画风风格词:厚涂古风
  6671. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6672. ###场景列表
  6673. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6674. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6675. 无人物。}
  6676. ###道具列表
  6677. 酒杯-高脚杯:高脚杯,盛有少量酒液。{高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}"];
  6678. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6679. $episode_count = $this->extractEpisodeNumber($prompt);
  6680. if ((int)getProp($anime, 'is_multi') !== 1) {
  6681. yield [
  6682. 'type' => 'done',
  6683. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6684. 'reasoning' => '',
  6685. 'usage' => []
  6686. ];
  6687. return;
  6688. }
  6689. if ($episode_count) {
  6690. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6691. $system_message = [
  6692. 'role' => 'system',
  6693. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6694. 强制要求:\n
  6695. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6696. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6697. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6698. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6699. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6700. 普通要求:\n
  6701. 1.<故事梗概>控制在200-300字左右
  6702. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6703. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6704. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6705. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6706. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6707. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6708. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6709. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6710. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6711. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6712. 示例如下:\n
  6713. ###剧本名:西昆仑
  6714. ###故事梗概
  6715. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6716. ###剧本亮点
  6717. 亮点1:绝境奇药,生死一线
  6718. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6719. 亮点2:结拜兄妹,化解尴尬
  6720. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6721. 亮点3:纤发夺命,情愫暗涌
  6722. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6723. ###人物关系
  6724. 阿雪与梁萧之间存在兄妹之情。
  6725. ###核心矛盾
  6726. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6727. ###主体列表
  6728. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6729. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6730. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6731. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6732. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6733. 全景,正面拍摄,青年女性,亚洲人。
  6734. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6735. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6736. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6737. ###美术风格
  6738. 基础画风风格词:厚涂古风
  6739. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6740. ###场景列表
  6741. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6742. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6743. 无人物。}
  6744. ###分集详细内容
  6745. ##第1章 重生
  6746. 我重生了。
  6747. 源于一个男人偏执的暗恋。
  6748. ##第2章 相救
  6749. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6750. 我眼睛扫向站在锅炉后的卞大伟。"
  6751. ];
  6752. // 构建消息
  6753. $messages = [
  6754. $system_message,
  6755. [
  6756. 'role' => 'user',
  6757. 'content' => "以下是文档内容:
  6758. {$content}
  6759. 用户问题:
  6760. {$question}"
  6761. ]
  6762. ];
  6763. }else {
  6764. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6765. // 构建消息
  6766. $messages = [
  6767. $system_message,
  6768. [
  6769. 'role' => 'user',
  6770. 'content' => "以下是文档内容:
  6771. {$content}
  6772. 用户问题:
  6773. {$question}"
  6774. ]
  6775. ];
  6776. }else {
  6777. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6778. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6779. return (array)$value;
  6780. })->toArray();
  6781. array_unshift($messages, $system_message);
  6782. $messages[] = [
  6783. 'role' => 'user',
  6784. 'content' => $prompt
  6785. ];
  6786. }
  6787. }
  6788. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6789. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6790. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6791. if ($model === 'deepseek-chat') {
  6792. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6793. $model = 'deepseek-v4-flash';
  6794. $thinkingMode = 'disabled';
  6795. } elseif ($model === 'deepseek-reasoner') {
  6796. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6797. $model = 'deepseek-v4-flash';
  6798. $thinkingMode = 'enabled';
  6799. }
  6800. $post_data = [
  6801. 'model' => $model,
  6802. 'messages' => $messages,
  6803. // 'max_tokens' => 8192,
  6804. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  6805. 'frequency_penalty' => 0,
  6806. 'presence_penalty' => 0,
  6807. 'response_format' => ['type' => 'text'],
  6808. 'thinking' => ['type' => $thinkingMode],
  6809. 'stream' => true // 启用流式输出
  6810. ];
  6811. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6812. // 根据模型类型选择调用方法
  6813. $fullContent = '';
  6814. $fullReasoningContent = '';
  6815. $usage = [];
  6816. // dd($post_data);
  6817. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6818. try {
  6819. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6820. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6821. } else if (in_array($model, $this->gpt_text_models)) {
  6822. // GPT-5.4 模型使用 TokenRouter API
  6823. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6824. } else {
  6825. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6826. }
  6827. // 验证返回值类型
  6828. if (!is_iterable($streamGenerator)) {
  6829. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6830. dLog('deepseek')->error('方法名流式生成器无效', [
  6831. 'generator_type' => $errorType,
  6832. 'model' => $model,
  6833. // 添加其他上下文信息
  6834. ]);
  6835. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6836. 'type' => $errorType,
  6837. 'model' => $model
  6838. ]);
  6839. yield [
  6840. 'type' => 'error',
  6841. // 根据方法返回相应的空数据结构
  6842. 'answer' => '',
  6843. 'reasoning' => '',
  6844. 'usage' => [],
  6845. 'error' => '接口返回数据异常,请重新请求'
  6846. ];
  6847. return;
  6848. }
  6849. // 处理流式输出
  6850. foreach ($streamGenerator as $chunk) {
  6851. if (isset($chunk['type'])) {
  6852. if ($chunk['type'] === 'done') {
  6853. $fullContent = $chunk['full_content'];
  6854. $fullReasoningContent = $chunk['full_reasoning'];
  6855. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6856. } else {
  6857. yield $chunk;
  6858. }
  6859. }
  6860. }
  6861. } catch (\Exception $e) {
  6862. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6863. 'model' => $model,
  6864. 'trace' => $e->getTraceAsString()
  6865. ]);
  6866. logDB('deepseek', 'error', '方法名流式处理失败', [
  6867. 'error' => $e->getMessage(),
  6868. 'model' => $model
  6869. ]);
  6870. yield [
  6871. 'type' => 'error',
  6872. // 根据方法返回相应的空数据结构
  6873. 'answer' => '',
  6874. 'reasoning' => '',
  6875. 'usage' => [],
  6876. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6877. ];
  6878. return;
  6879. }
  6880. dLog('deepseek')->info('完整内容: '.$fullContent);
  6881. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6882. // 处理完整内容并返回最终结果
  6883. $script_arr = [];
  6884. if ($fullContent) {
  6885. $script_arr = handleScriptContentForAce($fullContent);
  6886. dLog('deepseek')->info('解析内容', $script_arr);
  6887. logDB('deepseek', 'info', '解析内容', $script_arr);
  6888. }
  6889. if (empty($script_arr['roles'])) {
  6890. // 未生成剧本相关内容,保存对话记录并返回提示
  6891. dLog('deepseek')->info('未生成剧本相关的内容');
  6892. try {
  6893. $now = date('Y-m-d H:i:s');
  6894. // 保存对话记录
  6895. $records = [
  6896. [
  6897. 'uid' => $uid,
  6898. 'anime_id' => $anime_id,
  6899. 'sequence' => 0,
  6900. 'role' => 'user',
  6901. 'content' => $prompt,
  6902. 'created_at' => $now,
  6903. 'updated_at' => $now
  6904. ],
  6905. [
  6906. 'uid' => $uid,
  6907. 'anime_id' => $anime_id,
  6908. 'sequence' => 0,
  6909. 'role' => 'assistant',
  6910. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6911. 'created_at' => $now,
  6912. 'updated_at' => $now
  6913. ]
  6914. ];
  6915. DB::table('mp_anime_records')->insert($records);
  6916. } catch (\Exception $e) {
  6917. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6918. }
  6919. yield [
  6920. 'type' => 'done',
  6921. 'script' => [],
  6922. 'episode' => [],
  6923. 'answer' => $fullContent,
  6924. 'reasoning' => $fullReasoningContent,
  6925. 'usage' => $usage,
  6926. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6927. ];
  6928. return;
  6929. }
  6930. // 替换美术风格
  6931. if ($mappedArtStyle !== '') {
  6932. $script_arr['art_style'] = $mappedArtStyle;
  6933. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6934. }
  6935. if ($user_anime_name != '新剧本策划') {
  6936. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  6937. // 确认对话名称唯一性
  6938. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6939. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6940. }
  6941. }else {
  6942. $anime_name = $user_anime_name;
  6943. }
  6944. $table_data = [
  6945. 'user_id' => $uid,
  6946. 'model' => $model,
  6947. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6948. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6949. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6950. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6951. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6952. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6953. 'art_style_type' => $input_art_style,
  6954. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6955. 'props' => isset($script_arr['props']) && is_array($script_arr['props']) ? json_encode($script_arr['props'], 256) : '[]',
  6956. 'status' => '解析完成',
  6957. 'generate_status' => '待执行',
  6958. 'updated_at' => date('Y-m-d H:i:s')
  6959. ];
  6960. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6961. // 如果是修改集数,则将content内容更新(会改变原文)
  6962. if (isset($episode_count) && $episode_count > 0) {
  6963. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6964. $table_data['start_episode_sequence'] = 1;
  6965. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6966. }else {
  6967. // 如果需要生成原文内容,从script_arr中提取
  6968. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6969. $table_data['content'] = $script_arr['content'];
  6970. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6971. if (!$table_data['content']) {
  6972. yield [
  6973. 'type' => 'done',
  6974. 'script' => [],
  6975. 'episode' => [],
  6976. 'answer' => $fullContent,
  6977. 'reasoning' => $fullReasoningContent,
  6978. 'usage' => $usage,
  6979. 'error' => '未生成剧本内容,请调整提示词再试'
  6980. ];
  6981. return;
  6982. }
  6983. }
  6984. if (isset($table_data['content']) && $table_data['content']) {
  6985. $chapters = splitContent($table_data['content']);
  6986. $chapter_count = count($chapters);
  6987. if ($chapter_count > 0) {
  6988. $table_data['start_episode_sequence'] = 1;
  6989. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6990. }
  6991. }
  6992. }
  6993. if ($extra_products) {
  6994. $table_data['extra_products'] = json_encode($extra_products, 256);
  6995. }
  6996. $single_episode = [];
  6997. try {
  6998. DB::beginTransaction();
  6999. $now = date('Y-m-d H:i:s');
  7000. // 更新动漫大纲
  7001. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  7002. if (!$boolen) {
  7003. dLog('deepseek')->info('对话修改失败', $table_data);
  7004. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  7005. Utils::throwError('20003:对话修改失败');
  7006. }
  7007. // 保存对话记录
  7008. $records = [
  7009. [
  7010. 'uid' => $uid,
  7011. 'anime_id' => $anime_id,
  7012. 'sequence' => 0,
  7013. 'role' => 'user',
  7014. 'content' => $prompt,
  7015. 'created_at' => $now,
  7016. 'updated_at' => $now
  7017. ],
  7018. [
  7019. 'uid' => $uid,
  7020. 'anime_id' => $anime_id,
  7021. 'sequence' => 0,
  7022. 'role' => 'assistant',
  7023. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7024. 'content' => $fullContent,
  7025. 'created_at' => $now,
  7026. 'updated_at' => $now
  7027. ]
  7028. ];
  7029. // 保存对话记录
  7030. $boolen3 = DB::table('mp_anime_records')->insert($records);
  7031. if (!$boolen3) {
  7032. Utils::throwError('20003:对话记录保存失败');
  7033. }
  7034. // 单剧集模式:生成并保存剧集信息
  7035. if ($is_single) {
  7036. $anime_name = getProp($anime, 'anime_name', '未命名');
  7037. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  7038. if (empty($episode_arr['acts'])) {
  7039. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  7040. }
  7041. $saveResult = $this->saveEpisodeVersionData(
  7042. $anime_id,
  7043. 1,
  7044. $episode_arr,
  7045. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  7046. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  7047. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  7048. null,
  7049. null,
  7050. false,
  7051. $content,
  7052. $now,
  7053. $ref_products
  7054. );
  7055. $single_episode = $saveResult['episode'];
  7056. $episode_id = $saveResult['episode_id'];
  7057. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  7058. 'roles' => json_encode($saveResult['merged_roles'], 256),
  7059. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  7060. 'props' => json_encode($saveResult['merged_props'], 256),
  7061. 'updated_at' => $now
  7062. ]);
  7063. if ($boolen5 === false) {
  7064. Utils::throwError('20003:单剧集主表资源同步失败');
  7065. }
  7066. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  7067. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  7068. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  7069. $episode_record_content = '确认分镜大纲';
  7070. if ($content !== '') {
  7071. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  7072. }
  7073. $episode_records = [
  7074. [
  7075. 'uid' => $uid,
  7076. 'anime_id' => $anime_id,
  7077. 'role' => 'user',
  7078. 'content' => $episode_record_content,
  7079. 'sequence' => 1,
  7080. 'episode_id' => $episode_id,
  7081. 'created_at' => $now,
  7082. 'updated_at' => $now
  7083. ],
  7084. [
  7085. 'uid' => $uid,
  7086. 'anime_id' => $anime_id,
  7087. 'role' => 'assistant',
  7088. 'content' => $fullContent,
  7089. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7090. 'sequence' => 1,
  7091. 'episode_id' => $episode_id,
  7092. 'created_at' => $now,
  7093. 'updated_at' => $now
  7094. ]
  7095. ];
  7096. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  7097. if (!$boolen4) {
  7098. Utils::throwError('20003:单剧集分镜记录保存失败');
  7099. }
  7100. }
  7101. // 单剧集模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  7102. if ($is_single && !empty($single_episode)) {
  7103. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  7104. 'anime_id' => $anime_id,
  7105. 'episode_id' => $episode_id ?? 0,
  7106. ]);
  7107. }
  7108. }catch (\Exception $e) {
  7109. DB::rollBack();
  7110. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  7111. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  7112. yield [
  7113. 'type' => 'done',
  7114. 'answer' => $fullContent,
  7115. 'reasoning' => $fullReasoningContent,
  7116. 'usage' => $usage,
  7117. 'error' => $e->getMessage(),
  7118. ];
  7119. return;
  7120. }
  7121. DB::commit();
  7122. dLog('deepseek')->info('保存完毕');
  7123. if ($is_single && !empty($single_episode)) {
  7124. // $this->batchSetGlobalRoleImg([
  7125. // 'anime_id' => $anime_id,
  7126. // ]);
  7127. // $this->batchSetGlobalSceneImg([
  7128. // 'anime_id' => $anime_id,
  7129. // ]);
  7130. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7131. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7132. }
  7133. $table_data['anime_id'] = $anime_id;
  7134. $table_data['roles'] = json_decode($table_data['roles'], true);
  7135. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  7136. $table_data['props'] = json_decode($table_data['props'], true);
  7137. unset($table_data['updated_at']);
  7138. unset($table_data['status']);
  7139. yield [
  7140. 'type' => 'done',
  7141. 'script' => $table_data,
  7142. 'episode' => $single_episode,
  7143. 'answer' => $fullContent,
  7144. 'reasoning' => $fullReasoningContent,
  7145. 'usage' => $usage
  7146. ];
  7147. }
  7148. public function chatForAce($data) {
  7149. $uid = Site::getUid();
  7150. // 积分余额预检(不足直接报错)
  7151. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  7152. $anime_id = getProp($data, 'anime_id');
  7153. $file = getProp($data, 'file');
  7154. $content = getProp($data, 'content', '');
  7155. $bid = getProp($data, 'bid', 0);
  7156. $script_id = getProp($data, 'script_id', 0);
  7157. $episode_number = getProp($data, 'episode_number', 1);
  7158. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7159. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7160. if (!$anime) Utils::throwError('20003:该对话不存在!');
  7161. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  7162. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  7163. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  7164. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  7165. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  7166. $roles = is_array($roles) ? $roles : [];
  7167. $scenes = is_array($scenes) ? $scenes : [];
  7168. $extra_products = getProp($data, 'products', []);
  7169. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  7170. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  7171. $anime_script_id = getProp($anime, 'script_id');
  7172. if ($anime_script_id) {
  7173. $cpid = Site::getCpid();
  7174. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  7175. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  7176. ->where('mapping.script_id', $anime_script_id)
  7177. ->where('product.cpid', $cpid)
  7178. ->where('product.is_deleted', 0);
  7179. // 如果提供了 episode_number,则过滤指定集数
  7180. if ($episode_number !== null && $episode_number !== '') {
  7181. $script_products_mappings->where('mapping.episode_number', $episode_number);
  7182. }
  7183. $mappings = $script_products_mappings->select(
  7184. 'mapping.product_id',
  7185. 'mapping.episode_number',
  7186. 'product.product_name',
  7187. 'product.type',
  7188. 'product.product',
  7189. 'product.pic_prompt',
  7190. 'product.url',
  7191. 'product.pic_task_id',
  7192. 'product.pic_task_status',
  7193. 'product.three_view_image_url'
  7194. )
  7195. ->get();
  7196. // 按 product_id 分组,合并 episode_number
  7197. $productMap = [];
  7198. foreach ($mappings as $item) {
  7199. $product_id = $item->product_id;
  7200. $product_name = $item->product_name;
  7201. // 处理product_name两边的符号
  7202. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  7203. if (!isset($productMap[$product_id])) {
  7204. $productMap[$product_id] = [
  7205. 'product_id' => $product_id,
  7206. 'product_name' => $product_name,
  7207. 'type' => (int)$item->type,
  7208. 'product' => (int)$item->product,
  7209. 'pic_prompt' => $item->pic_prompt,
  7210. 'url' => $item->url,
  7211. 'pic_task_id' => $item->pic_task_id,
  7212. 'pic_task_status' => $item->pic_task_status,
  7213. 'episode_numbers' => [],
  7214. ];
  7215. }
  7216. // 添加 episode_number(去重)
  7217. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  7218. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  7219. }
  7220. }
  7221. // 将查询到的剧本资产合并到extra_products中
  7222. // 先构建extra_products的索引(以product_id+episode_number为key)
  7223. $extraProductsMap = [];
  7224. foreach ($extra_products as $item) {
  7225. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  7226. $extraProductsMap[$key] = $item;
  7227. }
  7228. // 合并剧本资产(去重:product_id+episode_number)
  7229. foreach ($productMap as $product) {
  7230. foreach ($product['episode_numbers'] as $ep_num) {
  7231. $key = $product['product_id'] . '_' . $ep_num;
  7232. // 如果不存在则添加
  7233. if (!isset($extraProductsMap[$key])) {
  7234. $extraProductsMap[$key] = [
  7235. 'product_id' => $product['product_id'],
  7236. 'product_name' => $product['product_name'],
  7237. 'type' => $product['type'],
  7238. 'product' => $product['product'],
  7239. 'pic_prompt' => $product['pic_prompt'],
  7240. 'url' => $product['url'],
  7241. 'pic_task_id' => $product['pic_task_id'],
  7242. 'pic_task_status' => $product['pic_task_status'],
  7243. 'episode_number' => $ep_num,
  7244. ];
  7245. }
  7246. }
  7247. }
  7248. // 重新赋值给extra_products
  7249. $extra_products = array_values($extraProductsMap);
  7250. }
  7251. // 处理提示词
  7252. if ($prompt && $extra_products) {
  7253. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  7254. foreach($extra_products as $item) {
  7255. $product_name = getProp($item, 'product_name');
  7256. if ($product_name) {
  7257. // 替换 {product_name} 为 product_name
  7258. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  7259. }
  7260. }
  7261. }
  7262. // 获取最后一集序号
  7263. $end_episode_sequence = getProp($anime, 'end_episode_sequence', 0);
  7264. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  7265. // 转换主体列表和场景列表的格式
  7266. // 获取参考主体或场景
  7267. if ((int)$episode_number === 1) {
  7268. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  7269. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  7270. }else {
  7271. $prev_episode_number = $episode_number - 1;
  7272. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  7273. }
  7274. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  7275. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  7276. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  7277. // 合并anime_products和extra_products(extra_products优先,去重)
  7278. $anime_products = getProp($anime, 'extra_products');
  7279. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  7280. $ref_products = [];
  7281. foreach($anime_products as $item) {
  7282. $product_name = getProp($item, 'product_name');
  7283. $ref_products[$product_name] = $item;
  7284. }
  7285. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  7286. $extra_roles = []; // 从extra_products中提取的角色
  7287. $extra_scenes = []; // 从extra_products中提取的场景
  7288. $extra_props = []; // 从extra_products中提取的道具
  7289. if ($extra_products && is_array($extra_products)) {
  7290. foreach($extra_products as $item) {
  7291. $product = (int)getProp($item, 'product');
  7292. $product_name = getProp($item, 'product_name');
  7293. if ($product_name == '旁白') continue;
  7294. $pic_prompt = getProp($item, 'pic_prompt');
  7295. $ref_products[$product_name] = $item;
  7296. if ($product === 1) {
  7297. // 角色
  7298. $extra_roles[$product_name] = [
  7299. 'role' => $product_name,
  7300. 'pic_prompt' => $pic_prompt,
  7301. 'url' => getProp($item, 'url', ''),
  7302. ];
  7303. } elseif ($product === 2) {
  7304. // 场景
  7305. $extra_scenes[$product_name] = [
  7306. 'scene' => $product_name,
  7307. 'pic_prompt' => $pic_prompt,
  7308. 'url' => getProp($item, 'url', ''),
  7309. ];
  7310. } elseif ($product === 3) {
  7311. // 道具
  7312. $extra_props[$product_name] = [
  7313. 'prop' => $product_name,
  7314. 'pic_prompt' => $pic_prompt,
  7315. 'url' => getProp($item, 'url', ''),
  7316. ];
  7317. }
  7318. }
  7319. }
  7320. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  7321. $merged_roles = [];
  7322. foreach($ref_roles as $role) {
  7323. $role_name = getProp($role, 'role');
  7324. if (!isset($extra_roles[$role_name])) {
  7325. $merged_roles[$role_name] = $role;
  7326. }
  7327. }
  7328. // 添加extra_roles
  7329. foreach($extra_roles as $role_name => $role) {
  7330. $merged_roles[$role_name] = $role;
  7331. }
  7332. $ref_roles = array_values($merged_roles);
  7333. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  7334. $merged_scenes = [];
  7335. foreach($ref_scenes as $scene) {
  7336. $scene_name = getProp($scene, 'scene');
  7337. if (!isset($extra_scenes[$scene_name])) {
  7338. $merged_scenes[$scene_name] = $scene;
  7339. }
  7340. }
  7341. // 添加extra_scenes
  7342. foreach($extra_scenes as $scene_name => $scene) {
  7343. $merged_scenes[$scene_name] = $scene;
  7344. }
  7345. $ref_scenes = array_values($merged_scenes);
  7346. // 合并ref_props和extra_props(extra_props优先,去重)
  7347. $merged_props = [];
  7348. foreach($ref_props as $prop) {
  7349. $prop_name = getProp($prop, 'prop');
  7350. if (!isset($extra_props[$prop_name])) {
  7351. $merged_props[$prop_name] = $prop;
  7352. }
  7353. }
  7354. // 添加extra_props
  7355. foreach($extra_props as $prop_name => $prop) {
  7356. $merged_props[$prop_name] = $prop;
  7357. }
  7358. $ref_props = array_values($merged_props);
  7359. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  7360. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  7361. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  7362. // 构建强制主体、场景和道具提示词
  7363. $forced_roles_prompt = "";
  7364. $forced_scenes_prompt = "";
  7365. $forced_props_prompt = "";
  7366. if (!empty($extra_roles)) {
  7367. $forced_roles_list = "";
  7368. foreach($extra_roles as $role_name => $role) {
  7369. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  7370. }
  7371. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  7372. }
  7373. if (!empty($extra_scenes)) {
  7374. $forced_scenes_list = "";
  7375. foreach($extra_scenes as $scene_name => $scene) {
  7376. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  7377. }
  7378. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  7379. }
  7380. if (!empty($extra_props)) {
  7381. $forced_props_list = "";
  7382. foreach($extra_props as $prop_name => $prop) {
  7383. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  7384. }
  7385. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  7386. }
  7387. if ($anime_script_id) {
  7388. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  7389. }else if ($roles_content) {
  7390. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  7391. 主体范围:\n {$roles_content}\n
  7392. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  7393. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7394. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7395. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7396. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7397. }else {
  7398. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  7399. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  7400. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  7401. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  7402. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  7403. }
  7404. if ($anime_script_id) {
  7405. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  7406. }else if ($scenes_content) {
  7407. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7408. 场景范围:\n {$scenes_content}\n
  7409. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  7410. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  7411. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7412. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7413. }else {
  7414. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7415. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  7416. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  7417. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  7418. }
  7419. if ($anime_script_id) {
  7420. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  7421. }else if ($props_content) {
  7422. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  7423. 道具范围:\n {$props_content}\n
  7424. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  7425. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  7426. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7427. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7428. }else {
  7429. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  7430. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  7431. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  7432. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  7433. }
  7434. // 提取文件内容
  7435. if ($file) {
  7436. $uploaded_content = $this->extractFileContent($file);
  7437. if (!$uploaded_content) {
  7438. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  7439. }
  7440. } elseif ($script_id) {
  7441. $uploaded_content = $this->getContentByScriptId($script_id);
  7442. if (!$uploaded_content) {
  7443. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  7444. }
  7445. } elseif ($bid) {
  7446. $uploaded_content = $this->getContentByBid($bid);
  7447. if (!$uploaded_content) {
  7448. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  7449. }
  7450. } elseif ($content) {
  7451. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  7452. }
  7453. // elseif ($prompt) {
  7454. // $uploaded_content = filterContent($prompt);
  7455. // }
  7456. else {
  7457. $uploaded_content = '';
  7458. }
  7459. // 美术风格
  7460. $input_art_style = getProp($data, 'art_style');
  7461. if (!$input_art_style) {
  7462. $mappedArtStyle = getProp($anime, 'art_style');
  7463. }else {
  7464. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  7465. }
  7466. if (!$mappedArtStyle) {
  7467. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  7468. }else {
  7469. if (strstr($mappedArtStyle, '基础画风风格词')) {
  7470. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  7471. }else {
  7472. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7473. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7474. }
  7475. }
  7476. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7477. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7478. // 强制要求:
  7479. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7480. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7481. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7482. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  7483. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  7484. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  7485. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  7486. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  7487. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  7488. // 10.分镜要和场景列表、人物主体保持一致\n
  7489. // 普通要求:
  7490. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7491. // {$role_demo}
  7492. // {$scene_demo}
  7493. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7494. // 4.1片段分割逻辑(优先级从高到低):
  7495. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7496. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7497. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7498. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7499. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7500. // - 片段数量格式为: 片段数量:8
  7501. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7502. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7503. // 4.3分镜结构:每个分镜包含以下字段:
  7504. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  7505. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  7506. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7507. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  7508. // - 运镜:场景+画面描述+运镜
  7509. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  7510. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7511. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7512. // 5.$mappedArtStyle_prompt\n\n
  7513. // 示例格式:\n
  7514. // 第1集:隐形的守护者
  7515. // ###故事梗概
  7516. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7517. // ###美术风格
  7518. // 基础画风风格词:胡金铨武侠
  7519. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7520. // ###主体列表
  7521. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7522. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7523. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7524. // ###场景列表
  7525. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7526. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7527. // ###分段剧本
  7528. // 片段数量:8
  7529. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7530. // ##片段1
  7531. // 时长:12s
  7532. // 分镜1
  7533. // 场景:边境小镇街道
  7534. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7535. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7536. // 配音台词:
  7537. // 背景音效:
  7538. // 分镜2
  7539. // 场景:悦来酒馆
  7540. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7541. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7542. // 配音台词:
  7543. // 背景音效:
  7544. // 分镜3
  7545. // 场景:悦来酒馆
  7546. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7547. // 运镜:从中景推向令牌特写。
  7548. // 配音台词:
  7549. // 背景音效:
  7550. // 分镜4
  7551. // 场景:悦来酒馆
  7552. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7553. // 运镜:极速推向酒水溅起的瞬间。
  7554. // 配音台词:
  7555. // 背景音效:
  7556. // 分镜5
  7557. // 镜头描述
  7558. // 场景:悦来酒馆
  7559. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7560. // 运镜:固定机位,利用倾斜构图制造压迫感。
  7561. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7562. // 背景音效:
  7563. // \n\n";
  7564. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7565. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7566. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  7567. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  7568. 普通要求:
  7569. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7570. {$role_demo}
  7571. {$scene_demo}
  7572. {$prop_demo}
  7573. 5.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7574. 5.1片段分割逻辑(优先级从高到低):
  7575. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7576. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7577. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7578. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7579. 5.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7580. - 片段数量格式为: 片段数量:8
  7581. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7582. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7583. 5.3分镜结构:每个分镜包含以下字段:
  7584. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7585. - 出场角色: 如果有主体出现在本镜,则必须选择本集中的<主体列表>中的一个(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7586. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7587. - 出场道具:如果有道具出现在本镜,则必须选择本集中的<道具列表>中的一个(如需使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7588. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7589. - 【强制要求-非常关键】画面中如果出现主体,只能选择上述<主体列表>中的一个,主体的名称也必须保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7590. - 【强制要求-非常关键】画面中如果出现道具,只能选择上述<道具列表>中的一个,道具的名称也必须保持一致(如必须使用“酒杯-高脚杯”,而不是“酒杯”或“高脚杯”,不得缺少“-”前后和“:”前面的任何内容,不能自创)
  7591. - 运镜:场景+画面描述+运镜
  7592. - 【强制要求-非常关键】运镜描述中如果出现主体或道具,逻辑需同画面一直,必须选择<主体列表>或<道具列表>中的一个,名称也必须保持一致
  7593. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创)
  7594. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7595. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7596. 6.《情绪-视听语言映射表》:
  7597. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7598. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7599. -----|---------|------------|----------------
  7600. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7601. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7602. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7603. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7604. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7605. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7606. -----|---------|------------|----------------
  7607. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7608. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7609. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7610. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7611. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7612. --------|---------|--------------|-------------
  7613. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7614. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7615. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7616. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7617. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7618. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7619. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7620. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7621. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7622. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7623. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7624. -----|---------|------------|------------
  7625. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7626. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7627. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7628. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7629. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7630. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7631. --------|---------|--------------|----------
  7632. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7633. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7634. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7635. 6.6 声音设计与潜意识影响 (Soundscape)
  7636. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7637. -----|---------|------------|------------------
  7638. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7639. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7640. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7641. 理论基石:
  7642. - The Five C's of Cinematography by Joseph V. Mascelli
  7643. - Film Art: An Introduction by David Bordwell
  7644. - Sight, Sound, Motion by Herbert Zettl
  7645. - Notes on the Cinematograph by Robert Bresson
  7646. \n\n
  7647. 7.{$mappedArtStyle_prompt}
  7648. 示例格式:\n
  7649. 第1集:隐形的守护者
  7650. ###故事梗概
  7651. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7652. ###美术风格
  7653. 基础画风风格词:胡金铨武侠
  7654. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7655. ###主体列表
  7656. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7657. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7658. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7659. ###场景列表
  7660. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7661. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7662. ###道具列表
  7663. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  7664. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  7665. ###分段剧本
  7666. 片段数量:8
  7667. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7668. ##片段1
  7669. 时长:12s
  7670. 分镜1
  7671. 出场角色:刀疤脸
  7672. 场景:边境小镇街道
  7673. 出场道具:酒杯-高脚杯
  7674. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7675. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7676. 配音台词:
  7677. 背景音效:
  7678. 分镜2
  7679. 出场角色:刀疤脸
  7680. 场景:悦来酒馆
  7681. 出场道具:酒杯-高脚杯
  7682. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7683. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7684. 配音台词:
  7685. 背景音效:
  7686. 分镜3
  7687. 出场角色:刀疤脸
  7688. 场景:悦来酒馆
  7689. 出场道具:酒杯-高脚杯
  7690. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7691. 运镜:从中景推向令牌特写。
  7692. 配音台词:
  7693. 背景音效:
  7694. 分镜4
  7695. 出场角色:刀疤脸
  7696. 场景:悦来酒馆
  7697. 出场道具:酒杯-高脚杯
  7698. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7699. 运镜:极速推向酒水溅起的瞬间。
  7700. 配音台词:
  7701. 背景音效:
  7702. 分镜5
  7703. 出场角色:刀疤脸
  7704. 场景:悦来酒馆
  7705. 出场道具:酒杯-高脚杯
  7706. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7707. 运镜:固定机位,利用倾斜构图制造压迫感。
  7708. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7709. 背景音效:
  7710. \n\n";
  7711. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7712. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  7713. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7714. $prompt = $origin_prompt;
  7715. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7716. // 获取章节内容
  7717. $full_content = getProp($anime, 'content');
  7718. if ($uploaded_content) {
  7719. $full_content = $uploaded_content;
  7720. }
  7721. // 根据章节内容拆分章节
  7722. $chapters = splitContent($full_content);
  7723. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7724. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7725. $messages = [];
  7726. if ($prompt == '确认分镜大纲') {
  7727. // 暂时保留
  7728. $content = $chapter_content;
  7729. if ($is_single) $content = $full_content; // 单剧集使用全文
  7730. if (!$content) {
  7731. Utils::throwError('20003:章节内容无法获取,请确认');
  7732. }
  7733. $question = $is_single
  7734. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7735. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7736. // 构建消息
  7737. $messages[] =
  7738. [
  7739. 'role' => 'user',
  7740. 'content' => $question
  7741. ];
  7742. }else if ($prompt == '继续策划下一集') {
  7743. if ($is_single) {
  7744. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7745. }
  7746. $content = $chapter_content;
  7747. if (!$content) {
  7748. Utils::throwError('20003:章节内容无法获取,请确认');
  7749. }
  7750. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7751. // 获取上一集最后记录
  7752. $prev_sequence = $episode_number - 1;
  7753. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7754. // 构建消息
  7755. $messages[] =
  7756. [
  7757. 'role' => 'user',
  7758. 'content' => $question
  7759. ];
  7760. // dd($messages);
  7761. }else {
  7762. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7763. if (!$content) {
  7764. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7765. }
  7766. if (!$content) {
  7767. Utils::throwError('20003:章节内容无法获取,请确认');
  7768. }
  7769. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7770. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7771. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7772. if ($origin_prompt) {
  7773. $question .= "本次修改要求如下:\n{$origin_prompt}";
  7774. }
  7775. $messages[] =
  7776. [
  7777. 'role' => 'user',
  7778. 'content' => $question
  7779. ];
  7780. }
  7781. // 处理文本模型
  7782. $model = getProp($data, 'model');
  7783. if (!$model) {
  7784. // 用户没有输入,从anime表获取
  7785. $model = getProp($anime, 'model');
  7786. if (!$model) {
  7787. // anime表也没有,使用默认值
  7788. $model = 'deepseek-v4-pro';
  7789. }
  7790. }
  7791. // 验证模型是否在可用模型表中
  7792. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7793. $model = 'deepseek-v4-pro';
  7794. }
  7795. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7796. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7797. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7798. if ($model === 'deepseek-chat') {
  7799. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7800. $model = 'deepseek-v4-flash';
  7801. $thinkingMode = 'disabled';
  7802. } elseif ($model === 'deepseek-reasoner') {
  7803. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7804. $model = 'deepseek-v4-flash';
  7805. $thinkingMode = 'enabled';
  7806. }
  7807. $post_data = [
  7808. 'model' => $model,
  7809. 'messages' => $messages,
  7810. // 'max_tokens' => 8192,
  7811. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  7812. 'frequency_penalty' => 0,
  7813. 'presence_penalty' => 0,
  7814. 'response_format' => ['type' => 'text'],
  7815. 'thinking' => ['type' => $thinkingMode],
  7816. 'stream' => true // 启用流式输出
  7817. ];
  7818. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7819. // 根据模型类型选择调用方法
  7820. $fullContent = '';
  7821. $fullReasoningContent = '';
  7822. $usage = [];
  7823. try {
  7824. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7825. // DeepSeek 官方模型使用 DeepSeek API
  7826. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7827. } else if (in_array($model, $this->gpt_text_models)) {
  7828. // GPT-5.4 模型使用 TokenRouter API
  7829. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7830. } else {
  7831. // 其他模型使用火山引擎API
  7832. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7833. }
  7834. // 验证返回值类型
  7835. if (!is_iterable($streamGenerator)) {
  7836. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7837. dLog('deepseek')->error('chat流式生成器无效', [
  7838. 'generator_type' => $errorType,
  7839. 'model' => $model,
  7840. 'anime_id' => $anime_id,
  7841. 'episode_number' => $episode_number
  7842. ]);
  7843. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7844. 'type' => $errorType,
  7845. 'model' => $model
  7846. ]);
  7847. yield [
  7848. 'type' => 'error',
  7849. 'episode' => [],
  7850. 'answer' => '',
  7851. 'reasoning' => '',
  7852. 'usage' => [],
  7853. 'error' => '接口返回数据异常,请重新请求'
  7854. ];
  7855. return;
  7856. }
  7857. // 处理流式输出
  7858. foreach ($streamGenerator as $chunk) {
  7859. if (isset($chunk['type'])) {
  7860. if ($chunk['type'] === 'done') {
  7861. // 最终结果
  7862. $fullContent = $chunk['full_content'];
  7863. $fullReasoningContent = $chunk['full_reasoning'];
  7864. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7865. } else {
  7866. // 逐块yield数据
  7867. yield $chunk;
  7868. }
  7869. }
  7870. }
  7871. } catch (\Exception $e) {
  7872. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7873. 'model' => $model,
  7874. 'anime_id' => $anime_id,
  7875. 'episode_number' => $episode_number,
  7876. 'trace' => $e->getTraceAsString()
  7877. ]);
  7878. logDB('deepseek', 'error', 'chat流式处理失败', [
  7879. 'error' => $e->getMessage(),
  7880. 'model' => $model
  7881. ]);
  7882. yield [
  7883. 'type' => 'error',
  7884. 'episode' => [],
  7885. 'answer' => '',
  7886. 'reasoning' => '',
  7887. 'usage' => [],
  7888. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7889. ];
  7890. return;
  7891. }
  7892. dLog('deepseek')->info('完整内容: '.$fullContent);
  7893. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7894. // 处理完整内容并返回最终结果
  7895. $episode_arr = handleEpisodeContentForAce($fullContent);
  7896. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7897. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  7898. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7899. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7900. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  7901. // }
  7902. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  7903. $max_retries = 3;
  7904. $retry_count = 0;
  7905. $validation_failed = false;
  7906. $validation_error_msg = '';
  7907. // 验证生成的内容
  7908. if ($anime_script_id) {
  7909. // 检查是否有acts数据
  7910. if (empty($episode_arr['acts'])) {
  7911. $validation_failed = true;
  7912. $validation_error_msg = '未生成分镜剧本相关的内容';
  7913. } else {
  7914. // 检查主体列表是否匹配 - 只验证生成的主体名是否都在预期列表中
  7915. $generated_roles = array_column($episode_arr['roles'], 'role');
  7916. // 过滤掉"旁白"角色
  7917. $generated_roles = array_filter($generated_roles, function($role) {
  7918. return $role !== '旁白';
  7919. });
  7920. $expected_roles = array_keys($extra_roles);
  7921. // 找出生成的主体中不在预期列表中的主体
  7922. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7923. if (!empty($invalid_roles)) {
  7924. $validation_failed = true;
  7925. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7926. }
  7927. // 检查场景列表是否匹配 - 只验证生成的场景名是否都在预期列表中
  7928. if (!$validation_failed) {
  7929. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7930. $expected_scenes = array_keys($extra_scenes);
  7931. // 找出生成的场景中不在预期列表中的场景
  7932. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7933. if (!empty($invalid_scenes)) {
  7934. $validation_failed = true;
  7935. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7936. }
  7937. }
  7938. }
  7939. } else {
  7940. // 如果没有anime_script_id,只检查是否有acts数据
  7941. if (empty($episode_arr['acts'])) {
  7942. $validation_failed = true;
  7943. $validation_error_msg = '未生成分镜剧本相关的内容';
  7944. }
  7945. }
  7946. // 重试逻辑
  7947. while ($validation_failed && $retry_count < $max_retries) {
  7948. $retry_count++;
  7949. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  7950. 'reason' => $validation_error_msg,
  7951. 'anime_id' => $anime_id,
  7952. 'episode_number' => $episode_number
  7953. ]);
  7954. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  7955. 'reason' => $validation_error_msg,
  7956. 'anime_id' => $anime_id
  7957. ]);
  7958. // 发送流式重试提示
  7959. yield [
  7960. 'type' => 'retry',
  7961. 'retry_count' => $retry_count,
  7962. 'reason' => $validation_error_msg
  7963. ];
  7964. // 构建重试提示词
  7965. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  7966. if ($anime_script_id) {
  7967. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  7968. $retry_prompt .= "2. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  7969. $retry_prompt .= "3. 必须包含完整的分镜剧本内容\n";
  7970. } else {
  7971. $retry_prompt .= "1. 必须包含完整的分镜剧本内容\n";
  7972. }
  7973. // 添加重试消息到messages
  7974. $messages[] = [
  7975. 'role' => 'assistant',
  7976. 'content' => $fullContent
  7977. ];
  7978. $messages[] = [
  7979. 'role' => 'user',
  7980. 'content' => $retry_prompt
  7981. ];
  7982. // 更新post_data的messages
  7983. $post_data['messages'] = $messages;
  7984. // 重新调用API
  7985. try {
  7986. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7987. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7988. } else if (in_array($model, $this->gpt_text_models)) {
  7989. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7990. } else {
  7991. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7992. }
  7993. // 处理流式输出
  7994. $fullContent = '';
  7995. $fullReasoningContent = '';
  7996. foreach ($streamGenerator as $chunk) {
  7997. if (isset($chunk['type'])) {
  7998. if ($chunk['type'] === 'done') {
  7999. $fullContent = $chunk['full_content'];
  8000. $fullReasoningContent = $chunk['full_reasoning'];
  8001. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  8002. } else {
  8003. yield $chunk;
  8004. }
  8005. }
  8006. }
  8007. // 重新解析内容
  8008. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  8009. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  8010. $episode_arr = handleEpisodeContentForAce($fullContent);
  8011. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  8012. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  8013. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  8014. // }
  8015. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  8016. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  8017. // 重新验证
  8018. $validation_failed = false;
  8019. $validation_error_msg = '';
  8020. if ($anime_script_id) {
  8021. if (empty($episode_arr['acts'])) {
  8022. $validation_failed = true;
  8023. $validation_error_msg = '未生成分镜剧本相关的内容';
  8024. } else {
  8025. // 检查主体列表 - 只验证生成的主体名是否都在预期列表中
  8026. $generated_roles = array_column($episode_arr['roles'], 'role');
  8027. // 过滤掉"旁白"角色
  8028. $generated_roles = array_filter($generated_roles, function($role) {
  8029. return $role !== '旁白';
  8030. });
  8031. $expected_roles = array_keys($extra_roles);
  8032. $invalid_roles = array_diff($generated_roles, $expected_roles);
  8033. if (!empty($invalid_roles)) {
  8034. $validation_failed = true;
  8035. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  8036. }
  8037. // 检查场景列表 - 只验证生成的场景名是否都在预期列表中
  8038. if (!$validation_failed) {
  8039. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  8040. $expected_scenes = array_keys($extra_scenes);
  8041. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  8042. if (!empty($invalid_scenes)) {
  8043. $validation_failed = true;
  8044. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  8045. }
  8046. }
  8047. }
  8048. } else {
  8049. if (empty($episode_arr['acts'])) {
  8050. $validation_failed = true;
  8051. $validation_error_msg = '未生成分镜剧本相关的内容';
  8052. }
  8053. }
  8054. } catch (\Exception $e) {
  8055. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  8056. 'trace' => $e->getTraceAsString()
  8057. ]);
  8058. break;
  8059. }
  8060. }
  8061. // 如果重试后仍然失败
  8062. if ($validation_failed) {
  8063. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  8064. 'retry_count' => $retry_count,
  8065. 'last_error' => $validation_error_msg
  8066. ]);
  8067. try {
  8068. $now = date('Y-m-d H:i:s');
  8069. $records = [
  8070. [
  8071. 'uid' => $uid,
  8072. 'anime_id' => $anime_id,
  8073. 'sequence' => $episode_number,
  8074. 'role' => 'user',
  8075. 'content' => $prompt,
  8076. 'created_at' => $now,
  8077. 'updated_at' => $now
  8078. ],
  8079. [
  8080. 'uid' => $uid,
  8081. 'anime_id' => $anime_id,
  8082. 'sequence' => $episode_number,
  8083. 'role' => 'assistant',
  8084. 'content' => $fullContent,
  8085. 'created_at' => $now,
  8086. 'updated_at' => $now
  8087. ]
  8088. ];
  8089. DB::table('mp_anime_records')->insert($records);
  8090. } catch (\Exception $e) {
  8091. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  8092. }
  8093. yield [
  8094. 'type' => 'done',
  8095. 'episode' => [],
  8096. 'answer' => $fullContent,
  8097. 'reasoning' => $fullReasoningContent,
  8098. 'usage' => $usage,
  8099. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  8100. ];
  8101. return;
  8102. }
  8103. // 验证成功,记录日志
  8104. if ($retry_count > 0) {
  8105. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  8106. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  8107. }
  8108. // 老逻辑
  8109. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  8110. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  8111. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  8112. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  8113. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  8114. $existing_props = is_array($existing_props) ? $existing_props : [];
  8115. $now = date('Y-m-d H:i:s');
  8116. try {
  8117. DB::beginTransaction();
  8118. $saveResult = $this->saveEpisodeVersionData(
  8119. $anime_id,
  8120. $episode_number,
  8121. $episode_arr,
  8122. $existing_roles,
  8123. $existing_scenes,
  8124. $existing_props,
  8125. $current_episode,
  8126. $base_episode,
  8127. $is_regenerate_version,
  8128. $content,
  8129. $now,
  8130. $ref_products
  8131. );
  8132. $episode = $saveResult['episode'];
  8133. $episode_id = $saveResult['episode_id'];
  8134. $merged_roles = $saveResult['merged_roles'];
  8135. $merged_scenes = $saveResult['merged_scenes'];
  8136. $merged_props = $saveResult['merged_props'];
  8137. $record_content = $origin_prompt;
  8138. if ($uploaded_content !== '') {
  8139. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  8140. }
  8141. $records = [
  8142. [
  8143. 'uid' => $uid,
  8144. 'anime_id' => $anime_id,
  8145. 'role' => 'user',
  8146. 'content' => $record_content,
  8147. 'sequence' => $episode_number,
  8148. 'episode_id' => $episode_id,
  8149. 'created_at' => $now,
  8150. 'updated_at' => $now
  8151. ],
  8152. [
  8153. 'uid' => $uid,
  8154. 'anime_id' => $anime_id,
  8155. 'role' => 'assistant',
  8156. 'content' => $fullContent,
  8157. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  8158. 'sequence' => $episode_number,
  8159. 'episode_id' => $episode_id,
  8160. 'created_at' => $now,
  8161. 'updated_at' => $now
  8162. ]
  8163. ];
  8164. $boolen4 = DB::table('mp_anime_records')->insert($records);
  8165. if (!$boolen4) {
  8166. Utils::throwError('20003:对话记录保存失败');
  8167. }
  8168. // 保存模型到anime表
  8169. $update_anime_data = [
  8170. 'model' => $model,
  8171. 'updated_at' => $now
  8172. ];
  8173. if ($uploaded_content) {
  8174. $update_anime_data['content'] = $uploaded_content;
  8175. }
  8176. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  8177. // 调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  8178. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  8179. 'anime_id' => $anime_id,
  8180. 'episode_number' => $episode_number,
  8181. 'model' => $model,
  8182. ]);
  8183. }catch (\Exception $e) {
  8184. DB::rollBack();
  8185. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  8186. yield [
  8187. 'type' => 'done',
  8188. 'answer' => $fullContent,
  8189. 'reasoning' => $fullReasoningContent,
  8190. 'usage' => $usage,
  8191. 'error' => $e->getMessage(),
  8192. ];
  8193. return;
  8194. }
  8195. DB::commit();
  8196. if ($is_global_generate_pics) {
  8197. // // 批量生成全局角色图片
  8198. // $this->batchSetGlobalRoleImg([
  8199. // 'anime_id' => $anime_id,
  8200. // ], true);
  8201. // // 批量生成全局场景图片
  8202. // $this->batchSetGlobalSceneImg([
  8203. // 'anime_id' => $anime_id,
  8204. // ], true);
  8205. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  8206. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  8207. }
  8208. $episode['episode_id'] = $episode_id;
  8209. $episode['roles'] = $merged_roles;
  8210. $episode['scenes'] = $merged_scenes;
  8211. $episode['props'] = $merged_props;
  8212. $episode['end_episode_sequence'] = $end_episode_sequence;
  8213. // 获取mp_animes表中的视频参数
  8214. $episode['video_params'] = [
  8215. 'video_model' => getProp($anime, 'video_model'),
  8216. 'video_resolution' => getProp($anime, 'video_resolution'),
  8217. 'ratio' => getProp($anime, 'video_ratio'),
  8218. ];
  8219. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  8220. yield [
  8221. 'type' => 'done',
  8222. 'episode' => $episode,
  8223. 'answer' => $fullContent,
  8224. 'reasoning' => $fullReasoningContent,
  8225. 'usage' => $usage
  8226. ];
  8227. }
  8228. /**
  8229. * chatForAce的非流式版本 - 用于定时任务
  8230. * 只获取最终 type=done 的数据,并验证必要字段
  8231. *
  8232. * @param array $data 请求数据
  8233. * @return array 生成结果
  8234. */
  8235. public function chatForAceNonStream($data) {
  8236. $finalResult = null;
  8237. // 调用流式方法,只保存 type=done 的数据
  8238. foreach ($this->chatForAce($data) as $chunk) {
  8239. // 只关注最终结果
  8240. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  8241. $finalResult = $chunk;
  8242. break; // 找到 done 就退出循环
  8243. }
  8244. }
  8245. // 验证最终结果
  8246. if (!$finalResult) {
  8247. return ['error' => '生成失败:未获取到最终结果'];
  8248. }
  8249. // 检查是否有错误
  8250. if (isset($finalResult['error']) && $finalResult['error']) {
  8251. return $finalResult;
  8252. }
  8253. // 验证必要字段
  8254. $episode = $finalResult['episode'] ?? [];
  8255. // 验证 roles
  8256. if (empty($episode['roles']) || !is_array($episode['roles'])) {
  8257. return ['error' => '生成失败:主体列表(roles)为空或格式错误'];
  8258. }
  8259. // 验证 scenes
  8260. if (empty($episode['scenes']) || !is_array($episode['scenes'])) {
  8261. return ['error' => '生成失败:场景列表(scenes)为空或格式错误'];
  8262. }
  8263. // 验证 props(道具可以为空,但必须存在且为数组)
  8264. if (!isset($episode['props']) || !is_array($episode['props'])) {
  8265. $episode['props'] = [];
  8266. }
  8267. // 验证 acts(分镜剧本)
  8268. if (empty($episode['acts']) || !is_array($episode['acts'])) {
  8269. return ['error' => '生成失败:分镜剧本(acts)为空或格式错误'];
  8270. }
  8271. // 更新验证后的 episode 数据
  8272. $finalResult['episode'] = $episode;
  8273. // 记录验证成功日志
  8274. dLog('deepseek')->info('chatForAceNonStream 验证通过', [
  8275. 'roles_count' => count($episode['roles']),
  8276. 'scenes_count' => count($episode['scenes']),
  8277. 'props_count' => count($episode['props']),
  8278. 'acts_count' => count($episode['acts'])
  8279. ]);
  8280. return $finalResult;
  8281. }
  8282. /**
  8283. * 批量生成多个分集
  8284. *
  8285. * @param array $data 请求数据
  8286. * @return array 任务信息
  8287. */
  8288. public function batchGenerateEpisodes($data) {
  8289. $uid = Site::getUid();
  8290. $cpid = Site::getCpid();
  8291. $anime_id = getProp($data, 'anime_id');
  8292. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  8293. if (!$anime_id) {
  8294. Utils::throwError('20003:anime_id参数缺失');
  8295. }
  8296. if ($generate_episode_number < 1) {
  8297. Utils::throwError('20003:生成集数必须大于0');
  8298. }
  8299. // 获取动漫信息
  8300. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8301. if (!$anime) {
  8302. Utils::throwError('20003:该剧集不存在');
  8303. }
  8304. // 检查是否是全能模式
  8305. if ((int)getProp($anime, 'ace_mode') !== 1) {
  8306. Utils::throwError('20003:只有全能模式才支持批量生成');
  8307. }
  8308. // 检查是否是多剧集模式
  8309. if ((int)getProp($anime, 'is_multi') !== 1) {
  8310. Utils::throwError('20003:单剧集不支持批量生成');
  8311. }
  8312. // 获取当前已生成的最大集数
  8313. $currentMaxEpisode = DB::table('mp_anime_episodes')
  8314. ->where('anime_id', $anime_id)
  8315. ->where('is_default', 1)
  8316. ->max('episode_number');
  8317. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  8318. // 确定起始集数
  8319. $startEpisodeNumber = $currentMaxEpisode + 1;
  8320. // 计算结束集数
  8321. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  8322. // 检查是否超过总集数限制
  8323. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  8324. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  8325. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  8326. }
  8327. // 计算本次实际需要创建的任务数(跳过已存在且未失败的任务;失败任务会删除重建,算作创建)
  8328. $existingSkippedCount = DB::table('mp_batch_episode_generation_details')
  8329. ->where('anime_id', $anime_id)
  8330. ->whereBetween('episode_number', [$startEpisodeNumber, $endEpisodeNumber])
  8331. ->whereIn('status', ['pending', 'processing', 'completed'])
  8332. ->count();
  8333. $needEpisodeCount = ($endEpisodeNumber - $startEpisodeNumber + 1) - $existingSkippedCount;
  8334. // 积分余额预检:每个剧集生成成功将扣 CHAT_CHARGE_POINTS 积分。
  8335. // 此处仅预检不扣费,实际扣费由定时任务调用 chatForAce(经 chatForAceNonStream)时按集扣取,避免重复扣费。
  8336. if ($needEpisodeCount > 0) {
  8337. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS * $needEpisodeCount, $uid);
  8338. }
  8339. $now = date('Y-m-d H:i:s');
  8340. $createdTasks = [];
  8341. $skippedTasks = [];
  8342. // 为每一集创建详情记录
  8343. for ($episodeNumber = $startEpisodeNumber; $episodeNumber <= $endEpisodeNumber; $episodeNumber++) {
  8344. // 检查是否已有该集的任务记录
  8345. $existingTask = DB::table('mp_batch_episode_generation_details')
  8346. ->where('anime_id', $anime_id)
  8347. ->where('episode_number', $episodeNumber)
  8348. ->first();
  8349. if ($existingTask) {
  8350. // 如果已存在且未完成,跳过
  8351. if (in_array($existingTask->status, ['pending', 'processing'])) {
  8352. $skippedTasks[] = $episodeNumber;
  8353. continue;
  8354. }
  8355. // 如果是失败状态,可以重新创建(删除旧记录)
  8356. if ($existingTask->status === 'failed') {
  8357. DB::table('mp_batch_episode_generation_details')
  8358. ->where('id', $existingTask->id)
  8359. ->delete();
  8360. }
  8361. // 如果是已完成状态,也跳过
  8362. if ($existingTask->status === 'completed') {
  8363. $skippedTasks[] = $episodeNumber;
  8364. continue;
  8365. }
  8366. }
  8367. // 准备任务数据
  8368. $taskData = [
  8369. 'anime_id' => $anime_id,
  8370. 'uid' => $uid,
  8371. 'cpid' => $cpid,
  8372. 'episode_number' => $episodeNumber,
  8373. 'status' => 'pending',
  8374. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  8375. 'retry_count' => 0,
  8376. 'created_at' => $now,
  8377. 'updated_at' => $now
  8378. ];
  8379. // 创建任务记录
  8380. $taskId = DB::table('mp_batch_episode_generation_details')->insertGetId($taskData);
  8381. if ($taskId) {
  8382. $createdTasks[] = $episodeNumber;
  8383. }
  8384. }
  8385. if (empty($createdTasks)) {
  8386. if (!empty($skippedTasks)) {
  8387. Utils::throwError('20003:所有集数都已存在任务记录,无需重复创建。已跳过集数:' . implode(',', $skippedTasks));
  8388. } else {
  8389. Utils::throwError('20003:创建批量生成任务失败');
  8390. }
  8391. }
  8392. return [
  8393. 'anime_id' => $anime_id,
  8394. 'start_episode' => $startEpisodeNumber,
  8395. 'end_episode' => $endEpisodeNumber,
  8396. 'total_episodes' => $generate_episode_number,
  8397. 'created_episodes' => $createdTasks,
  8398. 'skipped_episodes' => $skippedTasks,
  8399. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集。" .
  8400. "已创建: " . implode(',', $createdTasks) .
  8401. (!empty($skippedTasks) ? ";已跳过: " . implode(',', $skippedTasks) : "")
  8402. ];
  8403. }
  8404. /**
  8405. * 获取批量生成任务状态
  8406. *
  8407. * @param array $data 请求数据
  8408. * @return array 任务状态信息
  8409. */
  8410. public function getBatchGenerationTaskStatus($data) {
  8411. $anime_id = getProp($data, 'anime_id');
  8412. if (!$anime_id) {
  8413. Utils::throwError('20003:anime_id参数缺失');
  8414. }
  8415. // 获取该anime的所有任务
  8416. $tasks = DB::table('mp_batch_episode_generation_details')
  8417. ->where('anime_id', $anime_id)
  8418. ->orderBy('episode_number')
  8419. ->get()
  8420. ->map(function($item) {
  8421. return [
  8422. 'id' => $item->id,
  8423. 'episode_number' => $item->episode_number,
  8424. 'status' => $item->status,
  8425. 'error_message' => $item->error_message,
  8426. 'retry_count' => $item->retry_count,
  8427. 'created_at' => $item->created_at,
  8428. 'updated_at' => $item->updated_at,
  8429. 'completed_at' => $item->completed_at
  8430. ];
  8431. })
  8432. ->toArray();
  8433. if (empty($tasks)) {
  8434. Utils::throwError('20003:该剧集没有批量生成任务');
  8435. }
  8436. // 统计各状态数量
  8437. $totalCount = count($tasks);
  8438. $pendingCount = 0;
  8439. $processingCount = 0;
  8440. $completedCount = 0;
  8441. $failedCount = 0;
  8442. foreach ($tasks as $task) {
  8443. switch ($task['status']) {
  8444. case 'pending':
  8445. $pendingCount++;
  8446. break;
  8447. case 'processing':
  8448. $processingCount++;
  8449. break;
  8450. case 'completed':
  8451. $completedCount++;
  8452. break;
  8453. case 'failed':
  8454. $failedCount++;
  8455. break;
  8456. }
  8457. }
  8458. // 计算进度百分比
  8459. $progress = 0;
  8460. if ($totalCount > 0) {
  8461. $progress = round(($completedCount / $totalCount) * 100, 2);
  8462. }
  8463. // 判断整体状态
  8464. $overallStatus = 'processing';
  8465. if ($completedCount === $totalCount) {
  8466. $overallStatus = 'completed';
  8467. } elseif ($pendingCount === $totalCount) {
  8468. $overallStatus = 'pending';
  8469. } elseif ($failedCount > 0 && ($pendingCount + $processingCount) === 0) {
  8470. $overallStatus = 'failed';
  8471. }
  8472. return [
  8473. 'anime_id' => $anime_id,
  8474. 'total_episodes' => $totalCount,
  8475. 'pending_count' => $pendingCount,
  8476. 'processing_count' => $processingCount,
  8477. 'completed_count' => $completedCount,
  8478. 'failed_count' => $failedCount,
  8479. 'progress' => $progress,
  8480. 'overall_status' => $overallStatus,
  8481. 'tasks' => $tasks
  8482. ];
  8483. }
  8484. /**
  8485. * 智能匹配并替换主体和场景名称
  8486. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  8487. *
  8488. * @param array $episode_arr 解析后的剧集数据
  8489. * @param array $extra_roles 强制主体设定(key为主体名称)
  8490. * @param array $extra_scenes 强制场景设定(key为场景名称)
  8491. * @return array 替换后的剧集数据
  8492. */
  8493. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  8494. $replaced_count = 0;
  8495. // 1. 处理主体列表
  8496. if (!empty($episode_arr['roles'])) {
  8497. foreach ($episode_arr['roles'] as &$role) {
  8498. $generated_role_name = $role['role'] ?? '';
  8499. // 跳过旁白
  8500. if ($generated_role_name === '旁白') {
  8501. continue;
  8502. }
  8503. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  8504. if (!isset($extra_roles[$generated_role_name])) {
  8505. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  8506. if ($matched_role) {
  8507. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  8508. $role['role'] = $matched_role;
  8509. $replaced_count++;
  8510. }
  8511. }
  8512. }
  8513. }
  8514. // 2. 处理场景列表
  8515. if (!empty($episode_arr['scenes'])) {
  8516. foreach ($episode_arr['scenes'] as &$scene) {
  8517. $generated_scene_name = $scene['scene'] ?? '';
  8518. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  8519. if (!isset($extra_scenes[$generated_scene_name])) {
  8520. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  8521. if ($matched_scene) {
  8522. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  8523. $scene['scene'] = $matched_scene;
  8524. $replaced_count++;
  8525. }
  8526. }
  8527. }
  8528. }
  8529. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  8530. if (!empty($episode_arr['acts'])) {
  8531. foreach ($episode_arr['acts'] as &$act) {
  8532. if (!empty($act['segments'])) {
  8533. foreach ($act['segments'] as &$segment) {
  8534. if (!empty($segment['segment_content'])) {
  8535. $original_content = $segment['segment_content'];
  8536. $replaced_content = $original_content;
  8537. // 替换场景名 - 在文本中查找并替换
  8538. foreach (array_keys($extra_scenes) as $full_scene_name) {
  8539. // 尝试找到可能的短名称
  8540. $potential_short_names = [];
  8541. // 提取场景名的主要部分(冒号之前)
  8542. if (mb_strpos($full_scene_name, ':') !== false) {
  8543. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8544. $potential_short_names[] = $short_name;
  8545. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  8546. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  8547. $potential_short_names[] = $short_name;
  8548. }
  8549. // 替换场景字段中的短名称
  8550. foreach ($potential_short_names as $short_name) {
  8551. if ($short_name !== $full_scene_name) {
  8552. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  8553. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  8554. if ($new_content !== $replaced_content) {
  8555. $replaced_content = $new_content;
  8556. $replaced_count++;
  8557. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  8558. }
  8559. }
  8560. }
  8561. }
  8562. // 替换配音角色名(跳过旁白)
  8563. foreach (array_keys($extra_roles) as $full_role_name) {
  8564. if ($full_role_name === '旁白') {
  8565. continue;
  8566. }
  8567. // 尝试找到可能的短名称
  8568. $potential_short_names = [];
  8569. // 提取角色名的主要部分(短横线之前)
  8570. if (mb_strpos($full_role_name, '-') !== false) {
  8571. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  8572. $potential_short_names[] = $short_name;
  8573. }
  8574. // 替换配音台词中的短名称
  8575. foreach ($potential_short_names as $short_name) {
  8576. if ($short_name !== $full_role_name) {
  8577. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  8578. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  8579. if ($new_content !== $replaced_content) {
  8580. $replaced_content = $new_content;
  8581. $replaced_count++;
  8582. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  8583. }
  8584. }
  8585. }
  8586. }
  8587. // 如果有替换,更新segment_content
  8588. if ($replaced_content !== $original_content) {
  8589. $segment['segment_content'] = $replaced_content;
  8590. }
  8591. }
  8592. }
  8593. }
  8594. }
  8595. }
  8596. if ($replaced_count > 0) {
  8597. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  8598. 'replaced_count' => $replaced_count
  8599. ]);
  8600. }
  8601. return $episode_arr;
  8602. }
  8603. /**
  8604. * 查找匹配的名称
  8605. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  8606. *
  8607. * @param string $generated_name 生成的名称
  8608. * @param array $expected_names 预期的名称列表
  8609. * @return string|null 匹配到的名称,如果没有匹配则返回null
  8610. */
  8611. private function findMatchingName($generated_name, $expected_names) {
  8612. if (empty($generated_name)) {
  8613. return null;
  8614. }
  8615. // 尝试精确匹配
  8616. if (in_array($generated_name, $expected_names)) {
  8617. return $generated_name;
  8618. }
  8619. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  8620. foreach ($expected_names as $expected_name) {
  8621. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  8622. if (mb_strpos($expected_name, $generated_name) === 0) {
  8623. return $expected_name;
  8624. }
  8625. }
  8626. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  8627. // 这样可以处理一些变体,但优先级较低
  8628. foreach ($expected_names as $expected_name) {
  8629. if (mb_strpos($expected_name, $generated_name) !== false) {
  8630. return $expected_name;
  8631. }
  8632. }
  8633. return null;
  8634. }
  8635. /**
  8636. * 重新生成分段剧本
  8637. * @param array $data 包含以下字段:
  8638. * - prompt: string|null 用户修改要求(可选)
  8639. * - template_id: int|null 提示词模板ID(可选)
  8640. * - act_id: int|null 单个片段ID(与episode_id二选一)
  8641. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  8642. * @return array 返回生成结果
  8643. */
  8644. public function regenerateSegmentScript($data) {
  8645. $uid = Site::getUid();
  8646. $prompt = trim((string)getProp($data, 'prompt', ''));
  8647. $template_id = getProp($data, 'template_id', 0);
  8648. $act_id = getProp($data, 'act_id', 0);
  8649. $episode_id = getProp($data, 'episode_id', 0);
  8650. // 验证:prompt和template_id至少提供一个
  8651. if (empty($prompt) && empty($template_id)) {
  8652. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  8653. }
  8654. // 验证:act_id和episode_id二选一
  8655. if (empty($act_id) && empty($episode_id)) {
  8656. Utils::throwError('20003:请提供片段ID或剧集ID');
  8657. }
  8658. if (!empty($act_id) && !empty($episode_id)) {
  8659. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  8660. }
  8661. // 积分余额预检(仅剧集ID模式收费)
  8662. if (!empty($episode_id)) {
  8663. $this->pointsService->checkUserPointsEnough(PointsService::CHAT_CHARGE_POINTS, $uid);
  8664. }
  8665. // 如果提供了template_id,获取模板提示词
  8666. $template_prompt = '';
  8667. if ($template_id > 0) {
  8668. $template = DB::table('mp_prompt_templates')
  8669. ->where('id', $template_id)
  8670. ->where('is_deleted', 0)
  8671. ->first();
  8672. if (!$template) {
  8673. Utils::throwError('20003:提示词模板不存在或已删除');
  8674. }
  8675. $template_prompt = $template->template_prompt ?? '';
  8676. }
  8677. // 合并用户提示词和模板提示词
  8678. $final_prompt = '';
  8679. if (!empty($template_prompt)) {
  8680. $final_prompt = $template_prompt;
  8681. if (!empty($prompt)) {
  8682. $final_prompt .= "\n\n补充要求:" . $prompt;
  8683. }
  8684. } else {
  8685. $final_prompt = $prompt;
  8686. }
  8687. // 获取需要重新生成的内容参考
  8688. $reference_content = '';
  8689. $target_episode_id = 0;
  8690. $target_anime_id = 0;
  8691. $target_episode_number = 0;
  8692. if ($act_id > 0) {
  8693. // 单个片段模式:获取该片段的内容
  8694. $segment = DB::table('mp_episode_segments')
  8695. ->where('id', $act_id)
  8696. ->first();
  8697. if (!$segment) {
  8698. Utils::throwError('20003:片段不存在');
  8699. }
  8700. $target_episode_id = $segment->episode_id;
  8701. $target_anime_id = $segment->anime_id;
  8702. $target_episode_number = $segment->episode_number;
  8703. $reference_content = $segment->act_content ?? '';
  8704. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8705. } else {
  8706. // 整个剧集模式:获取所有片段的内容
  8707. $segments = DB::table('mp_episode_segments')
  8708. ->where('episode_id', $episode_id)
  8709. ->orderBy('act_number')
  8710. ->get();
  8711. if ($segments->isEmpty()) {
  8712. Utils::throwError('20003:该剧集没有片段数据');
  8713. }
  8714. $target_episode_id = $episode_id;
  8715. $target_anime_id = $segments[0]->anime_id;
  8716. $target_episode_number = $segments[0]->episode_number;
  8717. // 拼接所有片段内容,保留格式用于AI理解
  8718. $act_contents = [];
  8719. foreach ($segments as $seg) {
  8720. $act_number = $seg->act_number;
  8721. $act_content = $seg->act_content ?? '';
  8722. if (!empty($act_content)) {
  8723. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  8724. }
  8725. }
  8726. $reference_content = implode("\n\n", $act_contents);
  8727. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  8728. if ($episode_content) {
  8729. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  8730. }else {
  8731. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8732. }
  8733. }
  8734. if (empty($reference_content)) {
  8735. Utils::throwError('20003:没有可参考的片段内容');
  8736. }
  8737. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  8738. $episode = DB::table('mp_anime_episodes')
  8739. ->where('id', $target_episode_id)
  8740. ->first();
  8741. if (!$episode) {
  8742. Utils::throwError('20003:剧集不存在');
  8743. }
  8744. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  8745. $anime_script_id = getProp($anime, 'script_id');
  8746. $intro = $episode->intro ?? '';
  8747. $art_style = $episode->art_style ?? '';
  8748. $roles = json_decode($episode->roles ?? '[]', true);
  8749. $scenes = json_decode($episode->scenes ?? '[]', true);
  8750. $props = json_decode($episode->props ?? '[]', true);
  8751. // 构建提示词中的主体列表和场景列表参考
  8752. $roles_ref = '';
  8753. if (!empty($roles) && is_array($roles)) {
  8754. $roles_list = [];
  8755. foreach ($roles as $role) {
  8756. $role_name = getProp($role, 'role', '');
  8757. $role_desc = getProp($role, 'description', '');
  8758. $pic_prompt = getProp($role, 'pic_prompt', '');
  8759. $voice_prompt = getProp($role, 'voice_prompt', '');
  8760. if (!empty($role_name)) {
  8761. $role_line = $role_name;
  8762. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  8763. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  8764. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  8765. $roles_list[] = $role_line;
  8766. }
  8767. }
  8768. if (!empty($roles_list)) {
  8769. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  8770. }
  8771. }
  8772. $scenes_ref = '';
  8773. if (!empty($scenes) && is_array($scenes)) {
  8774. $scenes_list = [];
  8775. foreach ($scenes as $scene) {
  8776. $scene_name = getProp($scene, 'scene', '');
  8777. $scene_desc = getProp($scene, 'description', '');
  8778. $pic_prompt = getProp($scene, 'pic_prompt', '');
  8779. if (!empty($scene_name)) {
  8780. $scene_line = $scene_name;
  8781. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  8782. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  8783. $scenes_list[] = $scene_line;
  8784. }
  8785. }
  8786. if (!empty($scenes_list)) {
  8787. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  8788. }
  8789. }
  8790. $props_ref = '';
  8791. if (!empty($props) && is_array($props)) {
  8792. $props_list = [];
  8793. foreach ($props as $prop) {
  8794. $prop_name = getProp($prop, 'prop', '');
  8795. $prop_desc = getProp($prop, 'description', '');
  8796. $pic_prompt = getProp($prop, 'pic_prompt', '');
  8797. if (!empty($prop_name)) {
  8798. $prop_line = $prop_name;
  8799. if (!empty($prop_desc)) $prop_line .= ":" . $prop_desc;
  8800. if (!empty($pic_prompt)) $prop_line .= "{" . $pic_prompt . "}";
  8801. $props_list[] = $prop_line;
  8802. }
  8803. }
  8804. if (!empty($props_list)) {
  8805. $props_ref = "\n\n【道具列表参考】\n" . implode("\n", $props_list);
  8806. }
  8807. }
  8808. // 构建美术风格参考
  8809. $art_style_ref = '';
  8810. if (!empty($art_style)) {
  8811. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  8812. }
  8813. // 构建内容简介参考
  8814. $intro_ref = '';
  8815. if (!empty($intro)) {
  8816. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  8817. }
  8818. // 构建完整的AI提示词
  8819. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  8820. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  8821. $user_prompt .= $intro_ref;
  8822. $user_prompt .= $art_style_ref;
  8823. $user_prompt .= $reference_content;
  8824. // $user_prompt .= $roles_ref;
  8825. // $user_prompt .= $scenes_ref;
  8826. $system_prompt = "\n\n【强制要求】\n";
  8827. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  8828. $system_prompt .= "- 第一优先级:片段时长上限(单个片段不超过15秒,超过必须切为新片段)";
  8829. $system_prompt .= "- 每个分镜包含:分镜序号、出场角色、场景、出场道具、画面、运镜、配音台词、背景音效\n";
  8830. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$scenes_ref}\n";
  8831. $system_prompt .= "- 出场角色(如果有出现在本分镜)必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$roles_ref}\n";
  8832. $system_prompt .= "- 出场道具(如果有出现在本分镜)必须从【道具列表参考】中选择(如果提供了道具列表),道具名必须精准匹配【道具列表参考】中的名称(如需匹配“智能手机-黑色版”,而不是“智能手机”,不得缺少“-”前后和“:”前面的任何内容,不能自创,不能自创){$props_ref}\n";
  8833. $system_prompt .= "- 【重要】在“画面:”和“运镜:”描述中,如果提到角色或道具,必须使用【主体列表参考】或【道具列表参考】中的完整名称,一个字都不能少,一个字都不能改。例如:正确写法“运镜:镜头推向{林启明-黑色大衣七爷造型}”,错误写法“运镜:镜头推向林启明”(缺少造型后缀)。必须包含“-”及其后面的所有内容,不得简化、不得省略、不得自行修改\n";
  8834. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  8835. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  8836. ###分段剧本
  8837. 片段数量:8
  8838. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8839. ##片段1
  8840. 时长:12s
  8841. 分镜1
  8842. 出场角色:刀疤脸
  8843. 场景:边境小镇街道
  8844. 出场道具:酒杯-高脚杯
  8845. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8846. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8847. 配音台词:
  8848. 背景音效:
  8849. 分镜2
  8850. 出场角色:刀疤脸
  8851. 场景:悦来酒馆
  8852. 出场道具:酒杯-高脚杯
  8853. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8854. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8855. 配音台词:
  8856. 背景音效:
  8857. 分镜3
  8858. 出场角色:刀疤脸
  8859. 场景:悦来酒馆
  8860. 出场道具:酒杯-高脚杯
  8861. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8862. 运镜:从中景推向令牌特写。
  8863. 配音台词:
  8864. 背景音效:
  8865. 分镜4
  8866. 出场角色:刀疤脸
  8867. 场景:悦来酒馆
  8868. 出场道具:酒杯-高脚杯
  8869. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8870. 运镜:极速推向酒水溅起的瞬间。
  8871. 配音台词:
  8872. 背景音效:
  8873. 分镜5
  8874. 出场角色:刀疤脸
  8875. 场景:悦来酒馆
  8876. 出场道具:酒杯-高脚杯
  8877. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8878. 运镜:固定机位,利用倾斜构图制造压迫感。
  8879. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8880. 背景音效:";
  8881. // 获取模型配置
  8882. $model = getProp($data, 'model');
  8883. if (!$model) {
  8884. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  8885. }
  8886. // 验证模型是否在可用模型表中
  8887. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8888. $model = 'deepseek-v4-pro';
  8889. }
  8890. // 模型兼容性处理
  8891. $thinkingMode = 'disabled';
  8892. $reasoningEffort = 'high';
  8893. if ($model === 'deepseek-chat') {
  8894. $model = 'deepseek-v4-flash';
  8895. $thinkingMode = 'disabled';
  8896. } elseif ($model === 'deepseek-reasoner') {
  8897. $model = 'deepseek-v4-flash';
  8898. $thinkingMode = 'enabled';
  8899. }
  8900. // 构建消息
  8901. $messages = [
  8902. [
  8903. 'role' => 'system',
  8904. 'content' => $system_prompt
  8905. ],
  8906. [
  8907. 'role' => 'user',
  8908. 'content' => $user_prompt
  8909. ]
  8910. ];
  8911. // dd($messages);
  8912. // 构建请求参数
  8913. $post_data = [
  8914. 'model' => $model,
  8915. 'messages' => $messages,
  8916. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  8917. 'frequency_penalty' => 0,
  8918. 'presence_penalty' => 0,
  8919. 'response_format' => ['type' => 'text'],
  8920. 'thinking' => ['type' => $thinkingMode],
  8921. 'stream' => false // 非流式输出
  8922. ];
  8923. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8924. // 调用AI生成新的分段剧本
  8925. try {
  8926. $fullContent = '';
  8927. $usage = [];
  8928. // 根据模型类型选择调用方法
  8929. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8930. // DeepSeek 官方模型使用 DeepSeek API
  8931. $chatResult = $this->chatOnly($post_data);
  8932. } else if (in_array($model, $this->gpt_text_models)) {
  8933. // GPT 模型使用 TokenRouter API
  8934. $chatResult = $this->gpt54ChatOnly($post_data);
  8935. } else {
  8936. // 其他模型使用火山引擎API
  8937. $chatResult = $this->volcEngineChatCompletion($post_data);
  8938. }
  8939. if (is_array($chatResult)) {
  8940. $fullContent = $chatResult['fullContent'] ?? '';
  8941. $usage = $chatResult['usage'] ?? [];
  8942. }
  8943. $generated_content = $fullContent;
  8944. if (empty($generated_content)) {
  8945. Utils::throwError('20003:AI生成内容为空,请重试');
  8946. }
  8947. // 解析生成的内容 - 按片段分割
  8948. $parsed_segments = [];
  8949. // 先在开头添加换行符,确保第1片段也能被正确分割
  8950. $normalizedText = "\n" . $generated_content;
  8951. $parts = preg_split('/\n\s*##/', $normalizedText);
  8952. foreach ($parts as $part) {
  8953. $part = trim($part);
  8954. if (empty($part)) continue;
  8955. // 匹配"片段X"格式
  8956. if (!preg_match('/^片段\d+/', $part)) {
  8957. continue;
  8958. }
  8959. // 分离标题和内容
  8960. $lines = explode("\n", $part, 2);
  8961. $actTitle = trim($lines[0]);
  8962. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  8963. // 解析标题,提取序号
  8964. $actNumber = 0;
  8965. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  8966. $actNumber = intval($segmentTitleMatch[1]);
  8967. } else {
  8968. $actNumber = count($parsed_segments) + 1;
  8969. }
  8970. // 提取时长(仅保留数字)
  8971. $actDuration = 0;
  8972. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  8973. $actDurationStr = trim($actDurationMatch[1]);
  8974. // 提取数字部分(支持整数和小数)
  8975. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  8976. $actDuration = (float)$numMatch[1];
  8977. }
  8978. }
  8979. // 清理act_content:去除时长、旁白音色等非分镜内容行
  8980. // 只保留分镜内容,并确保分镜标记使用【】格式
  8981. $cleaned_content = '';
  8982. $content_lines = explode("\n", $actContent);
  8983. $is_capturing = false; // 标记是否开始捕获分镜内容
  8984. $count = 0;
  8985. foreach ($content_lines as $line) {
  8986. $trimmed_line = trim($line);
  8987. // 跳过时长和旁白音色行
  8988. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  8989. continue;
  8990. }
  8991. // 检测是否是分镜开始
  8992. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  8993. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  8994. $count++;
  8995. $is_capturing = true;
  8996. // 如果没有【】,则添加
  8997. if (!preg_match('/^【/u', $trimmed_line)) {
  8998. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  8999. }
  9000. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  9001. }
  9002. // 如果已经开始捕获,则添加该行
  9003. if ($is_capturing && !empty($trimmed_line)) {
  9004. $cleaned_content .= $trimmed_line."\n";
  9005. }
  9006. }
  9007. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  9008. $parsed_segments[] = [
  9009. 'act_number' => $actNumber,
  9010. 'act_title' => $actTitle,
  9011. 'act_duration' => $actDuration,
  9012. 'act_content' => $cleaned_content,
  9013. ];
  9014. }
  9015. if (empty($parsed_segments)) {
  9016. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  9017. }
  9018. // 收集所有资产名称(角色、场景、道具)
  9019. $product_names = [];
  9020. // 收集角色名称
  9021. if (!empty($roles) && is_array($roles)) {
  9022. foreach ($roles as $role) {
  9023. $role_name = getProp($role, 'role', '');
  9024. if (!empty($role_name)) {
  9025. $product_names[] = $role_name;
  9026. }
  9027. }
  9028. }
  9029. // 收集场景名称
  9030. if (!empty($scenes) && is_array($scenes)) {
  9031. foreach ($scenes as $scene) {
  9032. $scene_name = getProp($scene, 'scene', '');
  9033. if (!empty($scene_name)) {
  9034. $product_names[] = $scene_name;
  9035. }
  9036. }
  9037. }
  9038. // 收集道具名称
  9039. if (!empty($props) && is_array($props)) {
  9040. foreach ($props as $prop) {
  9041. $prop_name = getProp($prop, 'prop', '');
  9042. if (!empty($prop_name)) {
  9043. $product_names[] = $prop_name;
  9044. }
  9045. }
  9046. }
  9047. // 去重并按长度降序排序(避免短名称先匹配到长名称的一部分)
  9048. $product_names = array_unique($product_names);
  9049. usort($product_names, function($a, $b) {
  9050. return mb_strlen($b) - mb_strlen($a);
  9051. });
  9052. // 处理每个片段的 act_show_content
  9053. foreach ($parsed_segments as &$segment) {
  9054. $act_content = getProp($segment, 'act_content', '');
  9055. if (empty($act_content)) {
  9056. $segment['act_show_content'] = '';
  9057. continue;
  9058. }
  9059. $processed_content = $act_content;
  9060. // 统一替换所有资产名称为 {资产名} 格式
  9061. // 使用占位符避免嵌套替换问题
  9062. $placeholder_map = [];
  9063. $placeholder_index = 0;
  9064. foreach ($product_names as $product_name) {
  9065. // 转义特殊字符
  9066. $escaped_product = preg_quote($product_name, '/');
  9067. // 检查是否匹配且未被 {} 包裹
  9068. $processed_content = preg_replace_callback(
  9069. '/(?<![{])(' . $escaped_product . ')(?![}])/u',
  9070. function($matches) use (&$placeholder_map, &$placeholder_index) {
  9071. // 使用唯一占位符
  9072. $placeholder = '<<<PLACEHOLDER_' . $placeholder_index . '>>>';
  9073. $placeholder_map[$placeholder] = '{' . $matches[1] . '}';
  9074. $placeholder_index++;
  9075. return $placeholder;
  9076. },
  9077. $processed_content
  9078. );
  9079. }
  9080. // 将所有占位符替换回实际内容
  9081. foreach ($placeholder_map as $placeholder => $replacement) {
  9082. $processed_content = str_replace($placeholder, $replacement, $processed_content);
  9083. }
  9084. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  9085. $shot_counter = 0;
  9086. $processed_content = preg_replace_callback(
  9087. '/【(?:镜头|分镜)(\d+)】/u',
  9088. function($matches) use (&$shot_counter) {
  9089. $shot_counter++;
  9090. return '【镜头' . $shot_counter . '】';
  9091. },
  9092. $processed_content
  9093. );
  9094. $segment['act_show_content'] = $processed_content;
  9095. }
  9096. unset($segment); // 解除引用
  9097. // 保存到数据库
  9098. $now = date('Y-m-d H:i:s');
  9099. $saved_acts = []; // 用于记录保存后的片段信息
  9100. if ($act_id > 0) {
  9101. // 单个片段模式:更新单条记录
  9102. if (count($parsed_segments) > 0) {
  9103. $new_segment = $parsed_segments[0];
  9104. $update_data = [
  9105. 'act_content' => getProp($new_segment, 'act_content', ''),
  9106. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  9107. 'act_title' => getProp($new_segment, 'act_title', ''),
  9108. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  9109. 'updated_at' => $now,
  9110. ];
  9111. DB::table('mp_episode_segments')
  9112. ->where('id', $act_id)
  9113. ->update($update_data);
  9114. // 获取更新后的记录
  9115. $updated_act = DB::table('mp_episode_segments')
  9116. ->where('id', $act_id)
  9117. ->first();
  9118. if ($updated_act) {
  9119. $saved_acts[] = [
  9120. 'act_id' => $updated_act->id,
  9121. 'act_number' => $updated_act->act_number,
  9122. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  9123. 'act_content' => $updated_act->act_content,
  9124. 'act_show_content' => $updated_act->act_show_content,
  9125. 'video_url' => $updated_act->video_url ?? '',
  9126. 'video_duration' => $updated_act->video_duration ?? 0,
  9127. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  9128. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  9129. ];
  9130. }
  9131. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  9132. }
  9133. } else {
  9134. // 整个剧集模式:删除原有记录并批量保存新记录
  9135. DB::beginTransaction();
  9136. try {
  9137. // 删除原有的所有片段记录
  9138. DB::table('mp_episode_segments')
  9139. ->where('episode_id', $target_episode_id)
  9140. ->delete();
  9141. // 批量插入新的片段记录
  9142. $segments_to_insert = [];
  9143. foreach ($parsed_segments as $index => $segment) {
  9144. $act_number = $index + 1;
  9145. $segments_to_insert[] = [
  9146. 'anime_id' => $target_anime_id,
  9147. 'episode_id' => $target_episode_id,
  9148. 'episode_number' => $target_episode_number,
  9149. 'act_number' => $act_number,
  9150. 'act_title' => getProp($segment, 'act_title', ''),
  9151. 'act_duration' => getProp($segment, 'act_duration', 0),
  9152. 'act_content' => getProp($segment, 'act_content', ''),
  9153. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  9154. 'created_at' => $now,
  9155. 'updated_at' => $now,
  9156. ];
  9157. }
  9158. if (!empty($segments_to_insert)) {
  9159. DB::table('mp_episode_segments')->insert($segments_to_insert);
  9160. }
  9161. // 剧集ID模式调用成功,返回结果前扣除积分并记录明细(与保存同事务)
  9162. $this->chargeChatSuccess($uid, $this->pointsService->getTokensFromUsage($usage), [
  9163. 'anime_id' => $target_anime_id,
  9164. 'episode_id' => $target_episode_id,
  9165. ]);
  9166. DB::commit();
  9167. // 查询保存后的所有片段记录
  9168. $saved_segments = DB::table('mp_episode_segments')
  9169. ->where('episode_id', $target_episode_id)
  9170. ->orderBy('act_number')
  9171. ->get();
  9172. foreach ($saved_segments as $saved_segment) {
  9173. $saved_acts[] = [
  9174. 'act_id' => $saved_segment->id,
  9175. 'act_number' => $saved_segment->act_number,
  9176. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  9177. 'act_content' => $saved_segment->act_content,
  9178. 'act_show_content' => $saved_segment->act_show_content,
  9179. 'video_url' => $saved_segment->video_url ?? '',
  9180. 'video_duration' => $saved_segment->video_duration ?? 0,
  9181. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  9182. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  9183. ];
  9184. }
  9185. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  9186. 'episode_id' => $target_episode_id,
  9187. 'segments_count' => count($segments_to_insert)
  9188. ]);
  9189. } catch (\Exception $e) {
  9190. DB::rollBack();
  9191. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  9192. Utils::throwError('20003:保存失败,请重试');
  9193. }
  9194. }
  9195. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  9196. return [
  9197. 'anime_id' => $target_anime_id,
  9198. 'episode_id' => $target_episode_id,
  9199. 'title' => getProp($episode, 'title', ''),
  9200. 'episode_number' => $target_episode_number,
  9201. 'is_generated' => getProp($episode, 'is_generated', 0),
  9202. 'acts' => $saved_acts,
  9203. ];
  9204. } catch (\Exception $e) {
  9205. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  9206. throw $e;
  9207. }
  9208. }
  9209. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  9210. {
  9211. $episode_arr = [
  9212. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  9213. 'intro' => getProp($script_arr, 'intro'),
  9214. 'art_style' => getProp($script_arr, 'art_style'),
  9215. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  9216. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  9217. 'props' => is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  9218. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  9219. ];
  9220. if (empty($episode_arr['acts'])) {
  9221. $fallback_episode_arr = handleEpisodeContent($fullContent);
  9222. if (!empty($fallback_episode_arr['acts'])) {
  9223. $episode_arr = array_merge($fallback_episode_arr, [
  9224. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  9225. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  9226. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  9227. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  9228. ]);
  9229. }
  9230. }
  9231. // if (!getProp($episode_arr, 'episode_title')) {
  9232. // $episode_title = '';
  9233. // $episodes = getProp($script_arr, 'episodes', []);
  9234. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  9235. // $episode_title = '第1集:' . $episodes[0]['title'];
  9236. // }
  9237. // if (!$episode_title) {
  9238. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  9239. // }
  9240. // $episode_arr['episode_title'] = $episode_title;
  9241. // }
  9242. return $episode_arr;
  9243. }
  9244. private function saveEpisodeVersionData(
  9245. int $anime_id,
  9246. int $episode_number,
  9247. array $episode_arr,
  9248. array $existing_roles,
  9249. array $existing_scenes,
  9250. array $existing_props,
  9251. $current_episode,
  9252. $base_episode,
  9253. bool $is_regenerate_version,
  9254. string $content,
  9255. string $now,
  9256. array $ref_products = []
  9257. ): array {
  9258. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  9259. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  9260. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  9261. // 过滤掉关键字段为空的条目
  9262. $merged_roles = array_values(array_filter($generated_roles, function ($item) {
  9263. return !empty($item['role'] ?? null);
  9264. }));
  9265. $merged_scenes = array_values(array_filter($generated_scenes, function ($item) {
  9266. return !empty($item['scene'] ?? null);
  9267. }));
  9268. $merged_props = array_values(array_filter($generated_props, function ($item) {
  9269. return !empty($item['prop'] ?? null);
  9270. }));
  9271. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  9272. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  9273. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  9274. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  9275. $ace_mode = getProp($anime, 'ace_mode');
  9276. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  9277. $global_roles = json_decode(getProp($anime, 'roles'), true);
  9278. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  9279. $global_roles = is_array($global_roles) ? $global_roles : [];
  9280. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  9281. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  9282. $art_style_type = getProp($anime, 'art_style_type');
  9283. // 检查并创建 roles 的图片生成任务
  9284. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  9285. // 检查并创建 scenes 的图片生成任务
  9286. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  9287. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  9288. if ($arr && is_array($arr)) {
  9289. $merged_roles = $arr['roles'];
  9290. $merged_scenes = $arr['scenes'];
  9291. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  9292. }
  9293. // 确保数据是数组类型
  9294. if (!is_array($merged_roles)) {
  9295. dLog('deepseek')->error('merged_roles不是数组类型', [
  9296. 'type' => gettype($merged_roles),
  9297. 'value' => $merged_roles
  9298. ]);
  9299. $merged_roles = [];
  9300. }
  9301. if (!is_array($merged_scenes)) {
  9302. dLog('deepseek')->error('merged_scenes不是数组类型', [
  9303. 'type' => gettype($merged_scenes),
  9304. 'value' => $merged_scenes
  9305. ]);
  9306. $merged_scenes = [];
  9307. }
  9308. if (!is_array($merged_props)) {
  9309. dLog('deepseek')->error('merged_props不是数组类型', [
  9310. 'type' => gettype($merged_props),
  9311. 'value' => $merged_props
  9312. ]);
  9313. $merged_props = [];
  9314. }
  9315. // 同步新出现的主体和场景到全局
  9316. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  9317. $role_arr = [];
  9318. foreach ($merged_roles as $item) {
  9319. $role_arr[$item['role']] = $item;
  9320. }
  9321. $version_count = DB::table('mp_anime_episodes')
  9322. ->where('anime_id', $anime_id)
  9323. ->where('episode_number', $episode_number)
  9324. ->count('id');
  9325. $episode = [
  9326. 'anime_id' => $anime_id,
  9327. 'episode_number' => $episode_number,
  9328. 'title' => getProp($episode_arr, 'episode_title'),
  9329. 'content' => $content,
  9330. 'intro' => getProp($episode_arr, 'intro'),
  9331. 'art_style' => getProp($episode_arr, 'art_style'),
  9332. 'roles' => json_encode($merged_roles, 256),
  9333. 'scenes' => json_encode($merged_scenes, 256),
  9334. 'props' => json_encode($merged_props, 256),
  9335. 'generate_status' => '待执行',
  9336. 'generate_at' => $now,
  9337. 'is_default' => 1,
  9338. 'updated_at' => $now,
  9339. ];
  9340. $del_flag = false;
  9341. if ($is_regenerate_version) {
  9342. DB::table('mp_anime_episodes')
  9343. ->where('anime_id', $anime_id)
  9344. ->where('episode_number', $episode_number)
  9345. ->update(['is_default' => 0, 'updated_at' => $now]);
  9346. $episode['sequence'] = $version_count + 1;
  9347. $episode['created_at'] = $now;
  9348. $episode['cpid'] = Site::getCpid();
  9349. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9350. if (!$episode_id) {
  9351. Utils::throwError('20003:创建剧集版本失败');
  9352. }
  9353. } else {
  9354. $target_episode = $current_episode ?: $base_episode;
  9355. if ($target_episode) {
  9356. $episode_id = getProp($target_episode, 'id');
  9357. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  9358. DB::table('mp_anime_episodes')
  9359. ->where('anime_id', $anime_id)
  9360. ->where('episode_number', $episode_number)
  9361. ->where('id', '<>', $episode_id)
  9362. ->update(['is_default' => 0, 'updated_at' => $now]);
  9363. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  9364. if ($boolen === false) {
  9365. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  9366. Utils::throwError('20003:分集内容保存失败');
  9367. }
  9368. $del_flag = true;
  9369. } else {
  9370. DB::table('mp_anime_episodes')
  9371. ->where('anime_id', $anime_id)
  9372. ->where('episode_number', $episode_number)
  9373. ->update(['is_default' => 0, 'updated_at' => $now]);
  9374. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  9375. $episode['created_at'] = $now;
  9376. $episode['cpid'] = Site::getCpid();
  9377. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  9378. if (!$episode_id) {
  9379. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  9380. Utils::throwError('20003:分集内容保存失败');
  9381. }
  9382. }
  9383. }
  9384. $segments = [];
  9385. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  9386. // 如果是第2集及以后,获取上一集的主体音色数据
  9387. $previous_roles_voice = [];
  9388. if ($episode_number >= 2) {
  9389. $previous_episode = DB::table('mp_anime_episodes')
  9390. ->where('anime_id', $anime_id)
  9391. ->where('episode_number', $episode_number - 1)
  9392. ->where('is_default', 1)
  9393. ->first();
  9394. if ($previous_episode) {
  9395. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  9396. if (is_array($previous_roles)) {
  9397. foreach ($previous_roles as $prev_role) {
  9398. $role_name = getProp($prev_role, 'role');
  9399. if ($role_name) {
  9400. $previous_roles_voice[$role_name] = [
  9401. 'voice_name' => getProp($prev_role, 'voice_name'),
  9402. 'voice_type' => getProp($prev_role, 'voice_type'),
  9403. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  9404. ];
  9405. $voice_prompt = getProp($prev_role, 'voice_prompt');
  9406. if ($voice_prompt) {
  9407. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  9408. }
  9409. }
  9410. }
  9411. }
  9412. }
  9413. }
  9414. // 将继承的音色数据同步到当前集的主体列表
  9415. if (!empty($previous_roles_voice)) {
  9416. foreach ($merged_roles as &$role) {
  9417. $role_name = getProp($role, 'role');
  9418. if ($role_name && isset($previous_roles_voice[$role_name])) {
  9419. // 强制继承上一集的音色数据
  9420. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  9421. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  9422. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  9423. // 如果上一集有 voice_prompt 则继承,否则跳过
  9424. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  9425. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  9426. }
  9427. }
  9428. }
  9429. unset($role); // 解除引用
  9430. // 更新 role_arr 以便后续使用
  9431. $role_arr = [];
  9432. foreach ($merged_roles as $item) {
  9433. $role_arr[$item['role']] = $item;
  9434. }
  9435. }
  9436. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  9437. $emotion_list = array_flip($emotion_list);
  9438. foreach ($acts as $act) {
  9439. $act_segments = getProp($act, 'segments', []);
  9440. if (!is_array($act_segments)) {
  9441. continue;
  9442. }
  9443. if ((int)$ace_mode === 1) {
  9444. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  9445. $merged_parts = [];
  9446. foreach ($act_segments as $seg) {
  9447. $seg_num = getProp($seg, 'segment_number');
  9448. $seg_content = getProp($seg, 'segment_content');
  9449. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  9450. }
  9451. $act_content = implode("\n", $merged_parts);
  9452. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9453. $segments[] = [
  9454. 'anime_id' => $anime_id,
  9455. 'episode_id' => $episode_id,
  9456. 'episode_number' => $episode_number,
  9457. 'act_number' => getProp($act, 'act_number'),
  9458. 'act_title' => getProp($act, 'act_title'),
  9459. 'act_duration' => getProp($act, 'act_duration'),
  9460. 'act_content' => $act_content,
  9461. 'created_at' => $now,
  9462. 'updated_at' => $now
  9463. ];
  9464. } else {
  9465. foreach ($act_segments as $segment) {
  9466. $voice_actor = getProp($segment, 'voice_actor');
  9467. // 优先从上一集继承音色数据
  9468. $timbre_info = [];
  9469. if (isset($previous_roles_voice[$voice_actor])) {
  9470. // 从上一集继承音色数据
  9471. $timbre_info = $previous_roles_voice[$voice_actor];
  9472. } elseif (isset($role_arr[$voice_actor])) {
  9473. // 使用当前集的主体音色数据
  9474. $timbre_info = $role_arr[$voice_actor];
  9475. }
  9476. $voice_type = getProp($timbre_info, 'voice_type');
  9477. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  9478. if ($timbre_emotion) {
  9479. $timbre_emotion = explode(',', $timbre_emotion);
  9480. } else {
  9481. $timbre_emotion = [];
  9482. }
  9483. $emotion = getProp($segment, 'emotion', '中性');
  9484. if (!in_array($emotion, $timbre_emotion)) {
  9485. $emotion = '中性';
  9486. }
  9487. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  9488. $segments[] = [
  9489. 'anime_id' => $anime_id,
  9490. 'episode_id' => $episode_id,
  9491. 'episode_number' => $episode_number,
  9492. 'act_number' => getProp($act, 'act_number'),
  9493. 'act_title' => getProp($act, 'act_title'),
  9494. 'act_duration' => getProp($act, 'act_duration'),
  9495. 'segment_id' => getProp($segment, 'segment_id'),
  9496. 'segment_number' => getProp($segment, 'segment_number'),
  9497. 'segment_content' => getProp($segment, 'segment_content'),
  9498. 'description' => getProp($segment, 'description'),
  9499. 'composition' => getProp($segment, 'composition'),
  9500. 'camera_movement' => getProp($segment, 'camera_movement'),
  9501. 'voice_actor' => $voice_actor,
  9502. 'dialogue' => getProp($segment, 'dialogue'),
  9503. 'frame_type' => getProp($segment, 'frame_type'),
  9504. 'scene' => getProp($segment, 'scene'),
  9505. 'characters' => getProp($segment, 'characters'),
  9506. 'tail_frame' => getProp($segment, 'tail_frame'),
  9507. 'voice_name' => getProp($timbre_info, 'voice_name'),
  9508. 'voice_type' => $voice_type,
  9509. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  9510. 'emotion' => $emotion,
  9511. 'emotion_type' => $emotion_type,
  9512. 'gender' => getProp($segment, 'gender', '0'),
  9513. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  9514. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  9515. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  9516. 'pitch' => getProp($segment, 'pitch', 0),
  9517. 'created_at' => $now,
  9518. 'updated_at' => $now
  9519. ];
  9520. }
  9521. }
  9522. }
  9523. if ($segments) {
  9524. if ($del_flag) {
  9525. DB::table('mp_episode_segments')
  9526. ->where('anime_id', $anime_id)
  9527. ->where('episode_id', $episode_id)
  9528. ->delete();
  9529. }
  9530. $boolen = DB::table('mp_episode_segments')->insert($segments);
  9531. if (!$boolen) {
  9532. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  9533. Utils::throwError('20003:分镜内容保存失败');
  9534. }
  9535. }
  9536. dLog('deepseek')->info('segments', $segments);
  9537. // ace_mode=1: acts 返回值按合并格式调整
  9538. if ((int)$ace_mode === 1) {
  9539. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  9540. $act_map = [];
  9541. foreach ($table_act_data as $item) {
  9542. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  9543. }
  9544. $restructured_acts = [];
  9545. foreach ($acts as $act) {
  9546. $act_segments = getProp($act, 'segments', []);
  9547. if (!is_array($act_segments)) {
  9548. continue;
  9549. }
  9550. $merged_parts = [];
  9551. foreach ($act_segments as $seg) {
  9552. $seg_num = getProp($seg, 'segment_number');
  9553. $seg_content = getProp($seg, 'segment_content');
  9554. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  9555. }
  9556. $act_content = implode("\n", $merged_parts);
  9557. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  9558. $restructured_acts[] = [
  9559. 'anime_id' => $anime_id,
  9560. 'episode_id' => $episode_id,
  9561. 'episode_number' => $episode_number,
  9562. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  9563. 'act_number' => getProp($act, 'act_number'),
  9564. 'act_title' => getProp($act, 'act_title'),
  9565. 'act_duration' => getProp($act, 'act_duration'),
  9566. 'act_content' => $act_content,
  9567. 'created_at' => $now,
  9568. 'updated_at' => $now,
  9569. ];
  9570. }
  9571. $acts = $restructured_acts;
  9572. }
  9573. $episode['episode_id'] = $episode_id;
  9574. $episode['roles'] = $merged_roles;
  9575. $episode['scenes'] = $merged_scenes;
  9576. $episode['props'] = $merged_props;
  9577. $episode['acts'] = $acts;
  9578. return [
  9579. 'episode' => $episode,
  9580. 'episode_id' => $episode_id,
  9581. 'merged_roles' => $merged_roles,
  9582. 'merged_scenes' => $merged_scenes,
  9583. 'merged_props' => $merged_props,
  9584. ];
  9585. }
  9586. private function buildEpisodeItemContent(array $items, string $nameKey): string
  9587. {
  9588. $content = '';
  9589. foreach ($items as $item) {
  9590. $name = trim((string)getProp($item, $nameKey));
  9591. if ($name === '' || $name === '旁白') {
  9592. continue;
  9593. }
  9594. $description = trim((string)getProp($item, 'description'));
  9595. $content .= $name . ': ' . $description;
  9596. if ($nameKey == 'role') {
  9597. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9598. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9599. $voice_name = trim(getProp($item, 'voice_name'));
  9600. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9601. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  9602. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9603. }else {
  9604. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  9605. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9606. }
  9607. $content .= "\n";
  9608. }
  9609. return trim($content);
  9610. }
  9611. private function getEpisodeChatContent($animeId, $sequence, $content) {
  9612. if ((int)$sequence <= 0) {
  9613. return [];
  9614. }
  9615. $origin_content = '';
  9616. if ($content) {
  9617. $origin_content = '本集剧情内容:'.$content;
  9618. }else {
  9619. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  9620. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  9621. }
  9622. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  9623. // 获取分集信息
  9624. $episode = DB::table('mp_anime_episodes')
  9625. ->where('anime_id', $animeId)
  9626. ->where('episode_number', $sequence)
  9627. ->where('is_default', 1)
  9628. ->first();
  9629. if (!$episode) {
  9630. return [];
  9631. }
  9632. $episode_id = getProp($episode, 'id');
  9633. $episode_number = getProp($episode, 'episode_number');
  9634. $title = getProp($episode, 'title');
  9635. $intro = getProp($episode, 'intro');
  9636. $art_style = getProp($episode, 'art_style');
  9637. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9638. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9639. // 组装纯文本内容
  9640. $content = '';
  9641. // 添加分集标题和梗概
  9642. $content .= "###第{$episode_number}集:{$title}\n\n";
  9643. $content .= "###故事梗概\n";
  9644. $content .= trim($intro) . "\n\n";
  9645. // 添加美术风格
  9646. $content .= "###美术风格\n";
  9647. $content .= trim($art_style) . "\n\n";
  9648. // 添加主体列表
  9649. $content .= "###主体列表\n";
  9650. $pangbai_voice_prompt = "";
  9651. foreach ($roles as $role) {
  9652. $name = getProp($role, 'role');
  9653. $description = getProp($role, 'description');
  9654. $pic_prompt = getProp($role, 'pic_prompt');
  9655. $voice_prompt = getProp($role, 'voice_prompt');
  9656. $voice_name = getProp($role, 'voice_name');
  9657. $content .= "{$name}: {$description}";
  9658. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9659. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9660. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9661. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  9662. $content .= "\n";
  9663. }
  9664. $content .= "\n";
  9665. // 添加场景列表
  9666. $content .= "###场景列表\n";
  9667. foreach ($scenes as $scene) {
  9668. $name = getProp($scene, 'scene');
  9669. $description = getProp($scene, 'description');
  9670. $pic_prompt = getProp($scene, 'pic_prompt');
  9671. $content .= "{$name}: {$description}";
  9672. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9673. $content .= "\n";
  9674. }
  9675. $content .= "\n";
  9676. // 获取分镜信息
  9677. $segments = DB::table('mp_episode_segments')
  9678. ->where('anime_id', $animeId)
  9679. ->where('episode_id', $episode_id)
  9680. ->orderBy('segment_number')
  9681. ->get();
  9682. if ($segments && count($segments) > 0) {
  9683. if ((int)$ace_mode === 1) {
  9684. $content .= "###分段剧本\n";
  9685. // 获取片段数量
  9686. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  9687. $content .= "片段数量:{$act_count}\n";
  9688. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  9689. $content .= "\n";
  9690. }else {
  9691. $content .= "###分镜剧本\n";
  9692. }
  9693. // 按幕分组
  9694. $currentAct = null;
  9695. foreach ($segments as $segment) {
  9696. $act_number = getProp($segment, 'act_number');
  9697. $act_title = getProp($segment, 'act_title');
  9698. $act_duration = getProp($segment, 'act_duration');
  9699. $segment_number = getProp($segment, 'segment_number');
  9700. $segment_content = getProp($segment, 'segment_content');
  9701. $scene_description = getProp($segment, 'scene_description');
  9702. $scene_name = getProp($segment, 'scene_name');
  9703. $composition = getProp($segment, 'composition');
  9704. $camera_movement = getProp($segment, 'camera_movement');
  9705. $voice_type = getProp($segment, 'voice_type');
  9706. $characters = getProp($segment, 'characters');
  9707. $dialogue = getProp($segment, 'dialogue');
  9708. $frame_type = getProp($segment, 'frame_type');
  9709. $tail_frame_description = getProp($segment, 'tail_frame_description');
  9710. // 判断是否是全能模式
  9711. if ((int)$ace_mode === 1) { // 全能模式
  9712. // 如果是新的分段,添加分段标题
  9713. if ($act_number !== $currentAct) {
  9714. $currentAct = $act_number;
  9715. $content .= "##{$act_title}\n";
  9716. $content .= "时长:{$act_duration}s\n";
  9717. }
  9718. }else {
  9719. // 如果是新的幕,添加幕标题
  9720. if ($act_number !== $currentAct) {
  9721. $currentAct = $act_number;
  9722. $content .= "##第{$act_number}幕:{$scene_name}\n";
  9723. }
  9724. }
  9725. // 添加分镜信息
  9726. $content .= "分镜{$segment_number}\n";
  9727. $content .= "分镜内容:\n{$segment_content}\n";
  9728. // $content .= "画面描述:{$scene_description}\n";
  9729. // $content .= "场景:{$scene_name}\n";
  9730. // $content .= "构图设计:{$composition}\n";
  9731. // $content .= "运镜调度:{$camera_movement}\n";
  9732. // if (!empty($voice_type)) {
  9733. // $content .= "配音角色:{$voice_type}\n";
  9734. // }
  9735. // if (!empty($characters)) {
  9736. // $content .= "出镜角色:{$characters}\n";
  9737. // }
  9738. // if (!empty($dialogue)) {
  9739. // $content .= "台词内容:\"{$dialogue}\"\n";
  9740. // }
  9741. // $content .= "画面类型:{$frame_type}\n";
  9742. // $content .= "尾帧描述:{$tail_frame_description}\n";
  9743. $content .= "\n";
  9744. }
  9745. }
  9746. $content = trim($content);
  9747. if($content) $content = "上集剧本内容:\n{$content}";
  9748. return [
  9749. [
  9750. 'role' => 'user',
  9751. 'content' => $origin_content
  9752. ],
  9753. [
  9754. 'role' => 'assistant',
  9755. 'content' => $content
  9756. ]
  9757. ];
  9758. }
  9759. private function getEpisodeChatMessages($animeId, $sequence): array
  9760. {
  9761. if ((int)$sequence <= 0) {
  9762. return [];
  9763. }
  9764. return DB::table('mp_anime_records')
  9765. ->where('anime_id', $animeId)
  9766. ->where('sequence', $sequence)
  9767. ->where('episode_id', '>', 0)
  9768. ->select('role', 'content')
  9769. ->orderBy('created_at')
  9770. ->orderBy('id')
  9771. ->get()
  9772. ->map(function ($value) {
  9773. return (array)$value;
  9774. })
  9775. ->toArray();
  9776. }
  9777. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  9778. {
  9779. $existingMap = [];
  9780. foreach ($existingItems as $item) {
  9781. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9782. if ($itemKey === '') {
  9783. continue;
  9784. }
  9785. $existingMap[$itemKey] = $item;
  9786. }
  9787. if (!$generatedItems) {
  9788. return array_values($existingItems);
  9789. }
  9790. $merged = [];
  9791. foreach ($generatedItems as $item) {
  9792. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9793. if ($itemKey === '') {
  9794. continue;
  9795. }
  9796. if (isset($existingMap[$itemKey])) {
  9797. if (trim((string)getProp($item, 'description')) === '') {
  9798. $merged[] = $existingMap[$itemKey];
  9799. continue;
  9800. }
  9801. // 检查内容是否发生变化
  9802. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  9803. if (!$isChanged) {
  9804. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  9805. $mergedItem = [
  9806. $nameKey => trim((string)getProp($item, $nameKey)),
  9807. 'description' => trim((string)getProp($item, 'description')),
  9808. ];
  9809. // 如果有 pic_prompt,添加到合并项中
  9810. $picPrompt = getProp($item, 'pic_prompt');
  9811. if (!empty($picPrompt)) {
  9812. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9813. }
  9814. // 继承现有项的 URL
  9815. $existingUrl = getProp($existingMap[$itemKey], 'url');
  9816. if (!empty($existingUrl)) {
  9817. $mergedItem['url'] = $existingUrl;
  9818. }
  9819. // 继承现有项的 task_id
  9820. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  9821. if (!empty($existingTaskId)) {
  9822. $mergedItem['task_id'] = $existingTaskId;
  9823. }
  9824. // 继承现有项的 task_status
  9825. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  9826. if (!empty($existingTaskStatus)) {
  9827. $mergedItem['task_status'] = $existingTaskStatus;
  9828. }
  9829. // 保留生成项的音色字段
  9830. $voiceName = getProp($item, 'voice_name');
  9831. if (!empty($voiceName)) {
  9832. $mergedItem['voice_name'] = $voiceName;
  9833. }
  9834. $voiceType = getProp($item, 'voice_type');
  9835. if (!empty($voiceType)) {
  9836. $mergedItem['voice_type'] = $voiceType;
  9837. }
  9838. $audioUrl = getProp($item, 'voice_audio_url');
  9839. if (!empty($audioUrl)) {
  9840. $mergedItem['voice_audio_url'] = $audioUrl;
  9841. }
  9842. $merged[] = $mergedItem;
  9843. } else {
  9844. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  9845. $mergedItem = [
  9846. $nameKey => trim((string)getProp($item, $nameKey)),
  9847. 'description' => trim((string)getProp($item, 'description')),
  9848. ];
  9849. // 如果有 pic_prompt,添加到合并项中
  9850. $picPrompt = getProp($item, 'pic_prompt');
  9851. if (!empty($picPrompt)) {
  9852. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9853. }
  9854. // 保留生成项的音色字段
  9855. $voiceName = getProp($item, 'voice_name');
  9856. if (!empty($voiceName)) {
  9857. $mergedItem['voice_name'] = $voiceName;
  9858. }
  9859. $voiceType = getProp($item, 'voice_type');
  9860. if (!empty($voiceType)) {
  9861. $mergedItem['voice_type'] = $voiceType;
  9862. }
  9863. $audioUrl = getProp($item, 'voice_audio_url');
  9864. if (!empty($audioUrl)) {
  9865. $mergedItem['voice_audio_url'] = $audioUrl;
  9866. }
  9867. // 不继承 URL、task_id 和 task_status(重置状态)
  9868. $merged[] = $mergedItem;
  9869. }
  9870. } else {
  9871. // 新增项,保留生成项的所有字段
  9872. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  9873. }
  9874. }
  9875. return $merged ?: array_values($existingItems);
  9876. }
  9877. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  9878. {
  9879. $resetItem = [
  9880. $nameKey => trim((string)getProp($item, $nameKey)),
  9881. 'description' => trim((string)getProp($item, 'description')),
  9882. ];
  9883. // 保留指定的字段
  9884. foreach ($preserveFields as $field) {
  9885. $value = getProp($item, $field);
  9886. if (!empty($value)) {
  9887. $resetItem[$field] = $value;
  9888. }
  9889. }
  9890. return $resetItem;
  9891. }
  9892. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  9893. {
  9894. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  9895. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  9896. if ($existingKey !== $generatedKey) {
  9897. return true;
  9898. }
  9899. // 比较 description 是否变化
  9900. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  9901. return true;
  9902. }
  9903. // 比较 pic_prompt 是否变化
  9904. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  9905. }
  9906. private function normalizeEpisodeResourceKey($value): string
  9907. {
  9908. $value = trim((string)$value);
  9909. if ($value === '') {
  9910. return '';
  9911. }
  9912. return strtolower((string)preg_replace('/\s+/u', '', $value));
  9913. }
  9914. // 生成全局角色图片
  9915. private function batchSetGlobalRoleImg($data, $is_force=false) {
  9916. $anime_id = getProp($data, 'anime_id');
  9917. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9918. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9919. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9920. $art_style = getProp($anime, 'art_style');
  9921. $update_flag = false;
  9922. foreach ($roles as &$role) {
  9923. $role_name = getProp($role, 'role');
  9924. if ($role_name == '旁白') continue;
  9925. // 优先使用 pic_prompt,如果没有则使用 description
  9926. $pic_prompt = getProp($role, 'pic_prompt');
  9927. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  9928. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9929. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9930. // 参考图地址
  9931. $ref_img_url = getProp($role, 'url');
  9932. if (!$is_force && $ref_img_url) continue;
  9933. $update_flag = true;
  9934. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9935. try {
  9936. $params = [
  9937. 'prompt' => $description,
  9938. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  9939. 'ref_img_urls' => []
  9940. ];
  9941. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9942. $task_id = $task->id;
  9943. if (!$task_id) {
  9944. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  9945. }
  9946. $role['task_id'] = $task_id;
  9947. $role['task_status'] = 'processing';
  9948. } catch (\Exception $e) {
  9949. Utils::throwError("20003:" . $e->getMessage());
  9950. }
  9951. }
  9952. if (!$update_flag) return true;
  9953. // 保存角色信息
  9954. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9955. 'roles' => json_encode($roles, 256),
  9956. 'generate_status' => '执行中',
  9957. 'generate_at' => date('Y-m-d H:i:s'),
  9958. 'updated_at' => date('Y-m-d H:i:s')
  9959. ]);
  9960. if (!$boolen) {
  9961. Utils::throwError('20003:保存角色信息失败');
  9962. }
  9963. return $boolen;
  9964. }
  9965. // 生成全局场景图片
  9966. private function batchSetGlobalSceneImg($data, $is_force=false) {
  9967. $anime_id = getProp($data, 'anime_id');
  9968. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9969. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9970. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  9971. $art_style = getProp($anime, 'art_style');
  9972. $update_flag = false;
  9973. foreach ($scenes as &$scene) {
  9974. $scene_name = getProp($scene, 'scene');
  9975. // 优先使用 pic_prompt,如果没有则使用 description
  9976. $pic_prompt = getProp($scene, 'pic_prompt');
  9977. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  9978. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  9979. // 参考图地址
  9980. $ref_img_url = getProp($scene, 'url');
  9981. if (!$is_force && $ref_img_url) continue;
  9982. $update_flag = true;
  9983. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9984. try {
  9985. $params = [
  9986. 'prompt' => $description,
  9987. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  9988. 'ref_img_urls' => []
  9989. ];
  9990. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9991. $task_id = $task->id;
  9992. if (!$task_id) {
  9993. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  9994. }
  9995. $scene['task_id'] = $task_id;
  9996. $scene['task_status'] = 'processing';
  9997. } catch (\Exception $e) {
  9998. Utils::throwError("20003:" . $e->getMessage());
  9999. }
  10000. }
  10001. if (!$update_flag) return true;
  10002. // 保存角色信息
  10003. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  10004. 'scenes' => json_encode($scenes, 256),
  10005. 'generate_status' => '执行中',
  10006. 'generate_at' => date('Y-m-d H:i:s'),
  10007. 'updated_at' => date('Y-m-d H:i:s')
  10008. ]);
  10009. if (!$boolen) {
  10010. Utils::throwError('20003:保存角色信息失败');
  10011. }
  10012. return $boolen;
  10013. }
  10014. // 生成分镜主体、场景和道具图片
  10015. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  10016. $character_prefix = '';
  10017. $scene_prefix = '';
  10018. $prop_prefix = '';
  10019. if ($art_style_type) {
  10020. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  10021. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  10022. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  10023. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  10024. }
  10025. $update_flag = false;
  10026. // 获取上一集的roles、scenes和props数据
  10027. $prev_roles = [];
  10028. $prev_scenes = [];
  10029. $prev_props = [];
  10030. if ($episode_number > 1) {
  10031. $prev_episode = DB::table('mp_anime_episodes')
  10032. ->where('anime_id', $anime_id)
  10033. ->where('episode_number', $episode_number - 1)
  10034. ->where('is_default', 1)
  10035. ->first();
  10036. if ($prev_episode) {
  10037. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  10038. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  10039. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  10040. dLog('deepseek')->info("获取上一集数据成功", [
  10041. 'anime_id' => $anime_id,
  10042. 'prev_episode_number' => $episode_number - 1,
  10043. 'prev_roles_count' => count($prev_roles),
  10044. 'prev_scenes_count' => count($prev_scenes),
  10045. 'prev_props_count' => count($prev_props)
  10046. ]);
  10047. }
  10048. }
  10049. // 处理角色图片生成
  10050. foreach ($roles as &$role) {
  10051. $role_name = getProp($role, 'role');
  10052. if ($role_name == '旁白') continue;
  10053. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  10054. if (isset($ref_products[$role_name])) {
  10055. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  10056. if ($role['url']) continue;
  10057. }
  10058. $role_description = getProp($role, 'description');
  10059. $role_pic_prompt = getProp($role, 'pic_prompt');
  10060. $role_url = getProp($role, 'url');
  10061. // 检查是否可以从上一集继承
  10062. $inherited = false;
  10063. if (!$is_force && !empty($prev_roles)) {
  10064. foreach ($prev_roles as $prev_role) {
  10065. $prev_role_name = getProp($prev_role, 'role');
  10066. $prev_description = getProp($prev_role, 'description');
  10067. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  10068. $prev_url = getProp($prev_role, 'url');
  10069. $prev_task_id = getProp($prev_role, 'task_id');
  10070. $prev_task_status = getProp($prev_role, 'task_status');
  10071. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  10072. if ($role_name == $prev_role_name
  10073. && $role_description == $prev_description
  10074. && $role_pic_prompt == $prev_pic_prompt
  10075. && !empty($prev_url)) {
  10076. $role['task_id'] = $prev_task_id;
  10077. $role['task_status'] = $prev_task_status;
  10078. $role['url'] = $prev_url;
  10079. $inherited = true;
  10080. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  10081. 'anime_id' => $anime_id,
  10082. 'episode_number' => $episode_number,
  10083. 'task_id' => $prev_task_id,
  10084. 'url' => $prev_url
  10085. ]);
  10086. break;
  10087. }
  10088. }
  10089. }
  10090. // 如果已继承或已有url,跳过生成
  10091. if ($inherited || (!$is_force && $role_url)) {
  10092. continue;
  10093. }
  10094. // 优先使用 pic_prompt,如果没有则使用 description
  10095. $pic_prompt = getProp($role, 'pic_prompt');
  10096. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  10097. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10098. $update_flag = true;
  10099. // 调用AIImageGenerationService的生成图片任务接口
  10100. try {
  10101. $params = [
  10102. 'prompt' => $description,
  10103. 'ref_img_urls' => []
  10104. ];
  10105. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10106. $task_id = $task->id;
  10107. if (!$task_id) {
  10108. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  10109. continue; // 不中断,继续处理其他角色
  10110. }
  10111. $role['task_id'] = $task_id;
  10112. $role['task_status'] = 'processing';
  10113. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  10114. 'anime_id' => $anime_id,
  10115. 'episode_number' => $episode_number,
  10116. 'task_id' => $task_id
  10117. ]);
  10118. } catch (\Exception $e) {
  10119. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  10120. // 不抛出异常,继续处理其他角色
  10121. }
  10122. }
  10123. // 处理场景图片生成
  10124. foreach ($scenes as &$scene) {
  10125. $scene_name = getProp($scene, 'scene');
  10126. $scene_description = getProp($scene, 'description');
  10127. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  10128. $scene_url = getProp($scene, 'url');
  10129. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  10130. if (isset($ref_products[$scene_name])) {
  10131. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  10132. if ($scene['url']) continue;
  10133. }
  10134. // 检查是否可以从上一集继承
  10135. $inherited = false;
  10136. if (!$is_force && !empty($prev_scenes)) {
  10137. foreach ($prev_scenes as $prev_scene) {
  10138. $prev_scene_name = getProp($prev_scene, 'scene');
  10139. $prev_description = getProp($prev_scene, 'description');
  10140. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  10141. $prev_url = getProp($prev_scene, 'url');
  10142. $prev_task_id = getProp($prev_scene, 'task_id');
  10143. $prev_task_status = getProp($prev_scene, 'task_status');
  10144. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  10145. if ($scene_name == $prev_scene_name
  10146. && $scene_description == $prev_description
  10147. && $scene_pic_prompt == $prev_pic_prompt
  10148. && !empty($prev_url)) {
  10149. $scene['task_id'] = $prev_task_id;
  10150. $scene['task_status'] = $prev_task_status;
  10151. $scene['url'] = $prev_url;
  10152. $inherited = true;
  10153. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  10154. 'anime_id' => $anime_id,
  10155. 'episode_number' => $episode_number,
  10156. 'task_id' => $prev_task_id,
  10157. 'url' => $prev_url
  10158. ]);
  10159. break;
  10160. }
  10161. }
  10162. }
  10163. // 如果已继承或已有url,跳过生成
  10164. if ($inherited || (!$is_force && $scene_url)) {
  10165. continue;
  10166. }
  10167. // 优先使用 pic_prompt,如果没有则使用 description
  10168. $pic_prompt = getProp($scene, 'pic_prompt');
  10169. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  10170. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10171. $update_flag = true;
  10172. // 调用AIImageGenerationService的生成图片任务接口
  10173. try {
  10174. $params = [
  10175. 'prompt' => $description,
  10176. 'ref_img_urls' => []
  10177. ];
  10178. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10179. $task_id = $task->id;
  10180. if (!$task_id) {
  10181. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  10182. continue; // 不中断,继续处理其他场景
  10183. }
  10184. $scene['task_id'] = $task_id;
  10185. $scene['task_status'] = 'processing';
  10186. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  10187. 'anime_id' => $anime_id,
  10188. 'episode_number' => $episode_number,
  10189. 'task_id' => $task_id
  10190. ]);
  10191. } catch (\Exception $e) {
  10192. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  10193. // 不抛出异常,继续处理其他场景
  10194. }
  10195. }
  10196. // 处理道具图片生成(逻辑与场景一致)
  10197. foreach ($props as &$prop) {
  10198. $prop_name = getProp($prop, 'prop');
  10199. $prop_description = getProp($prop, 'description');
  10200. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  10201. $prop_url = getProp($prop, 'url');
  10202. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  10203. if (isset($ref_products[$prop_name])) {
  10204. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  10205. if ($prop['url']) continue;
  10206. }
  10207. // 检查是否可以从上一集继承
  10208. $inherited = false;
  10209. if (!$is_force && !empty($prev_props)) {
  10210. foreach ($prev_props as $prev_prop) {
  10211. $prev_prop_name = getProp($prev_prop, 'prop');
  10212. $prev_description = getProp($prev_prop, 'description');
  10213. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  10214. $prev_url = getProp($prev_prop, 'url');
  10215. $prev_task_id = getProp($prev_prop, 'task_id');
  10216. $prev_task_status = getProp($prev_prop, 'task_status');
  10217. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  10218. if ($prop_name == $prev_prop_name
  10219. && $prop_description == $prev_description
  10220. && $prop_pic_prompt == $prev_pic_prompt
  10221. && !empty($prev_url)) {
  10222. $prop['task_id'] = $prev_task_id;
  10223. $prop['task_status'] = $prev_task_status;
  10224. $prop['url'] = $prev_url;
  10225. $inherited = true;
  10226. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  10227. 'anime_id' => $anime_id,
  10228. 'episode_number' => $episode_number,
  10229. 'task_id' => $prev_task_id,
  10230. 'url' => $prev_url
  10231. ]);
  10232. break;
  10233. }
  10234. }
  10235. }
  10236. // 如果已继承或已有url,跳过生成
  10237. if ($inherited || (!$is_force && $prop_url)) {
  10238. continue;
  10239. }
  10240. // 优先使用 pic_prompt,如果没有则使用 description
  10241. $pic_prompt = getProp($prop, 'pic_prompt');
  10242. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  10243. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  10244. $update_flag = true;
  10245. // 调用AIImageGenerationService的生成图片任务接口
  10246. try {
  10247. $params = [
  10248. 'prompt' => $description,
  10249. 'ref_img_urls' => []
  10250. ];
  10251. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10252. $task_id = $task->id;
  10253. if (!$task_id) {
  10254. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  10255. continue; // 不中断,继续处理其他道具
  10256. }
  10257. $prop['task_id'] = $task_id;
  10258. $prop['task_status'] = 'processing';
  10259. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  10260. 'anime_id' => $anime_id,
  10261. 'episode_number' => $episode_number,
  10262. 'task_id' => $task_id
  10263. ]);
  10264. } catch (\Exception $e) {
  10265. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  10266. // 不抛出异常,继续处理其他道具
  10267. }
  10268. }
  10269. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10270. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  10271. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  10272. // // 保存剧集的角色和场景信息
  10273. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  10274. // 'roles' => json_encode($roles, 256),
  10275. // 'scenes' => json_encode($scenes, 256),
  10276. // 'generate_status' => '执行中',
  10277. // 'generate_at' => date('Y-m-d H:i:s'),
  10278. // 'updated_at' => date('Y-m-d H:i:s')
  10279. // ]);
  10280. // if (!$boolen) {
  10281. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  10282. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  10283. // }
  10284. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  10285. // 'episode_id' => $episode_id,
  10286. 'roles_count' => count($roles),
  10287. 'scenes_count' => count($scenes),
  10288. 'props_count' => count($props)
  10289. ]);
  10290. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  10291. }
  10292. /**
  10293. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  10294. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  10295. *
  10296. * @param int $anime_id 动漫对话ID
  10297. * @param array $episode_roles 剧集角色数据
  10298. * @param array $episode_scenes 剧集场景数据
  10299. * @param array $episode_props 剧集道具数据
  10300. * @return bool
  10301. */
  10302. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  10303. // 获取全局数据
  10304. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10305. if (!$anime) {
  10306. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10307. return false;
  10308. }
  10309. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10310. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10311. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  10312. $roles_added = false;
  10313. $roles_updated = false;
  10314. $scenes_added = false;
  10315. $props_added = false;
  10316. // 处理角色同步
  10317. foreach ($episode_roles as $episode_role) {
  10318. $episode_role_name = getProp($episode_role, 'role');
  10319. $episode_description = getProp($episode_role, 'description');
  10320. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10321. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  10322. // 跳过旁白
  10323. if ($episode_role_name == '旁白') {
  10324. continue;
  10325. }
  10326. // 检查全局中是否已存在相同的角色
  10327. $exists = false;
  10328. $global_role_index = -1;
  10329. foreach ($global_roles as $index => $global_role) {
  10330. $global_role_name = getProp($global_role, 'role');
  10331. $global_description = getProp($global_role, 'description');
  10332. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10333. // 如果role、description、pic_prompt三项都一致,则认为已存在
  10334. if ($episode_role_name == $global_role_name
  10335. && $episode_description == $global_description
  10336. && $episode_pic_prompt == $global_pic_prompt) {
  10337. $exists = true;
  10338. $global_role_index = $index;
  10339. break;
  10340. }
  10341. }
  10342. // 如果不存在,则添加到全局
  10343. if (!$exists) {
  10344. $global_roles[] = $episode_role;
  10345. $roles_added = true;
  10346. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  10347. 'anime_id' => $anime_id,
  10348. 'role' => $episode_role_name
  10349. ]);
  10350. } else {
  10351. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  10352. if (!empty($episode_voice_prompt)) {
  10353. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  10354. // 如果全局没有voice_prompt或与剧集不一致,则更新
  10355. if ($global_voice_prompt !== $episode_voice_prompt) {
  10356. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  10357. $roles_updated = true;
  10358. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  10359. 'anime_id' => $anime_id,
  10360. 'role' => $episode_role_name,
  10361. 'voice_prompt' => $episode_voice_prompt
  10362. ]);
  10363. }
  10364. }
  10365. }
  10366. }
  10367. // 处理场景同步
  10368. foreach ($episode_scenes as $episode_scene) {
  10369. $episode_scene_name = getProp($episode_scene, 'scene');
  10370. $episode_description = getProp($episode_scene, 'description');
  10371. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10372. // 检查全局中是否已存在相同的场景
  10373. $exists = false;
  10374. foreach ($global_scenes as $global_scene) {
  10375. $global_scene_name = getProp($global_scene, 'scene');
  10376. $global_description = getProp($global_scene, 'description');
  10377. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10378. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  10379. if ($episode_scene_name == $global_scene_name
  10380. && $episode_description == $global_description
  10381. && $episode_pic_prompt == $global_pic_prompt) {
  10382. $exists = true;
  10383. break;
  10384. }
  10385. }
  10386. // 如果不存在,则添加到全局
  10387. if (!$exists) {
  10388. $global_scenes[] = $episode_scene;
  10389. $scenes_added = true;
  10390. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  10391. 'anime_id' => $anime_id,
  10392. 'scene' => $episode_scene_name
  10393. ]);
  10394. }
  10395. }
  10396. // 处理道具同步(逻辑与场景一致)
  10397. foreach ($episode_props as $episode_prop) {
  10398. $episode_prop_name = getProp($episode_prop, 'prop');
  10399. $episode_description = getProp($episode_prop, 'description');
  10400. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  10401. // 检查全局中是否已存在相同的道具
  10402. $exists = false;
  10403. foreach ($global_props as $global_prop) {
  10404. $global_prop_name = getProp($global_prop, 'prop');
  10405. $global_description = getProp($global_prop, 'description');
  10406. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  10407. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  10408. if ($episode_prop_name == $global_prop_name
  10409. && $episode_description == $global_description
  10410. && $episode_pic_prompt == $global_pic_prompt) {
  10411. $exists = true;
  10412. break;
  10413. }
  10414. }
  10415. // 如果不存在,则添加到全局
  10416. if (!$exists) {
  10417. $global_props[] = $episode_prop;
  10418. $props_added = true;
  10419. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  10420. 'anime_id' => $anime_id,
  10421. 'prop' => $episode_prop_name
  10422. ]);
  10423. }
  10424. }
  10425. // 如果有新增或更新,则更新全局数据
  10426. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  10427. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10428. if ($roles_added || $roles_updated) {
  10429. $update_data['roles'] = json_encode($global_roles, 256);
  10430. }
  10431. if ($scenes_added) {
  10432. $update_data['scenes'] = json_encode($global_scenes, 256);
  10433. }
  10434. if ($props_added) {
  10435. $update_data['props'] = json_encode($global_props, 256);
  10436. }
  10437. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  10438. dLog('deepseek')->info('剧集数据同步到全局完成', [
  10439. 'anime_id' => $anime_id,
  10440. 'roles_added' => $roles_added,
  10441. 'roles_updated' => $roles_updated,
  10442. 'scenes_added' => $scenes_added,
  10443. 'props_added' => $props_added,
  10444. 'global_roles_count' => count($global_roles),
  10445. 'global_scenes_count' => count($global_scenes),
  10446. 'global_props_count' => count($global_props)
  10447. ]);
  10448. }
  10449. return true;
  10450. }
  10451. /**
  10452. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  10453. *
  10454. * @param int $anime_id 动漫对话ID
  10455. * @param int $episode_id 分集ID
  10456. * @return bool
  10457. */
  10458. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  10459. // 获取全局角色和场景数据
  10460. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  10461. if (!$anime) {
  10462. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  10463. return false;
  10464. }
  10465. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  10466. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  10467. // 获取指定的分集
  10468. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  10469. if (!$episode) {
  10470. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  10471. return false;
  10472. }
  10473. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  10474. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  10475. $roles_updated = false;
  10476. $scenes_updated = false;
  10477. // 继承角色的task_id、task_status和url
  10478. foreach ($episode_roles as &$episode_role) {
  10479. $episode_role_name = getProp($episode_role, 'role');
  10480. $episode_description = getProp($episode_role, 'description');
  10481. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  10482. $episode_url = getProp($episode_role, 'url');
  10483. // 跳过旁白角色
  10484. if ($episode_role_name == '旁白') {
  10485. continue;
  10486. }
  10487. // 如果剧集中已有URL,跳过
  10488. if (!empty($episode_url)) {
  10489. continue;
  10490. }
  10491. // 遍历全局角色数据,查找匹配的角色
  10492. foreach ($global_roles as $global_role) {
  10493. $global_role_name = getProp($global_role, 'role');
  10494. $global_description = getProp($global_role, 'description');
  10495. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  10496. $global_url = getProp($global_role, 'url');
  10497. $global_task_id = getProp($global_role, 'task_id');
  10498. $global_task_status = getProp($global_role, 'task_status');
  10499. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10500. if ($episode_role_name == $global_role_name
  10501. && $episode_description == $global_description
  10502. && $episode_pic_prompt == $global_pic_prompt) {
  10503. // 继承 task_id、task_status 和 url
  10504. if (!empty($global_task_id)) {
  10505. $episode_role['task_id'] = $global_task_id;
  10506. $episode_role['task_status'] = $global_task_status;
  10507. $roles_updated = true;
  10508. dLog('deepseek')->info('剧集角色继承全局task_id', [
  10509. 'episode_id' => $episode_id,
  10510. 'role' => $episode_role_name,
  10511. 'task_id' => $global_task_id,
  10512. 'task_status' => $global_task_status
  10513. ]);
  10514. }
  10515. if (!empty($global_url)) {
  10516. $episode_role['url'] = $global_url;
  10517. $roles_updated = true;
  10518. dLog('deepseek')->info('剧集角色继承全局url', [
  10519. 'episode_id' => $episode_id,
  10520. 'role' => $episode_role_name,
  10521. 'url' => $global_url
  10522. ]);
  10523. }
  10524. break;
  10525. }
  10526. }
  10527. }
  10528. // 继承场景的task_id、task_status和url
  10529. foreach ($episode_scenes as &$episode_scene) {
  10530. $episode_scene_name = getProp($episode_scene, 'scene');
  10531. $episode_description = getProp($episode_scene, 'description');
  10532. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  10533. $episode_url = getProp($episode_scene, 'url');
  10534. // 如果剧集中已有URL,跳过
  10535. if (!empty($episode_url)) {
  10536. continue;
  10537. }
  10538. // 遍历全局场景数据,查找匹配的场景
  10539. foreach ($global_scenes as $global_scene) {
  10540. $global_scene_name = getProp($global_scene, 'scene');
  10541. $global_description = getProp($global_scene, 'description');
  10542. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  10543. $global_url = getProp($global_scene, 'url');
  10544. $global_task_id = getProp($global_scene, 'task_id');
  10545. $global_task_status = getProp($global_scene, 'task_status');
  10546. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  10547. if ($episode_scene_name == $global_scene_name
  10548. && $episode_description == $global_description
  10549. && $episode_pic_prompt == $global_pic_prompt) {
  10550. // 继承 task_id、task_status 和 url
  10551. if (!empty($global_task_id)) {
  10552. $episode_scene['task_id'] = $global_task_id;
  10553. $episode_scene['task_status'] = $global_task_status;
  10554. $scenes_updated = true;
  10555. dLog('deepseek')->info('剧集场景继承全局task_id', [
  10556. 'episode_id' => $episode_id,
  10557. 'scene' => $episode_scene_name,
  10558. 'task_id' => $global_task_id,
  10559. 'task_status' => $global_task_status
  10560. ]);
  10561. }
  10562. if (!empty($global_url)) {
  10563. $episode_scene['url'] = $global_url;
  10564. $scenes_updated = true;
  10565. dLog('deepseek')->info('剧集场景继承全局url', [
  10566. 'episode_id' => $episode_id,
  10567. 'scene' => $episode_scene_name,
  10568. 'url' => $global_url
  10569. ]);
  10570. }
  10571. break;
  10572. }
  10573. }
  10574. }
  10575. // 如果有更新,则保存到数据库
  10576. if ($roles_updated || $scenes_updated) {
  10577. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  10578. if ($roles_updated) {
  10579. $update_data['roles'] = json_encode($episode_roles, 256);
  10580. }
  10581. if ($scenes_updated) {
  10582. $update_data['scenes'] = json_encode($episode_scenes, 256);
  10583. }
  10584. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  10585. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  10586. 'episode_id' => $episode_id,
  10587. 'roles_updated' => $roles_updated,
  10588. 'scenes_updated' => $scenes_updated
  10589. ]);
  10590. }
  10591. return true;
  10592. }
  10593. public function chatChangeImg($data) {
  10594. $segment = getProp($data, 'segment');
  10595. $segment_content = getProp($segment, 'segment_content');
  10596. $prompt = getProp($data, 'prompt');
  10597. $ref_img = getProp($data, 'ref_img');
  10598. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  10599. // 处理文本模型
  10600. $model = getProp($data, 'model');
  10601. if (!$model) {
  10602. // 用户没有输入,从anime表获取
  10603. $segment_id = getProp($segment, 'segment_id');
  10604. if ($segment_id) {
  10605. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  10606. if ($episode_id) {
  10607. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  10608. if ($anime_id) {
  10609. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  10610. }
  10611. }
  10612. }
  10613. if (!$model) {
  10614. // anime表也没有,使用默认值
  10615. $model = 'doubao-seed-2-0-mini-260215';
  10616. }
  10617. }
  10618. // 验证模型是否在可用模型表中
  10619. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10620. $model = 'doubao-seed-2-0-mini-260215';
  10621. }
  10622. $messages[] =
  10623. [
  10624. 'role' => 'user',
  10625. 'content' => $question
  10626. ];
  10627. $post_data = [
  10628. 'model' => $model,
  10629. 'messages' => $messages,
  10630. // 'max_tokens' => 8192,
  10631. 'temperature' => 0.7,
  10632. 'frequency_penalty' => 0,
  10633. 'presence_penalty' => 0,
  10634. 'response_format' => ['type' => 'text'],
  10635. 'stream' => false // 是否启用流式输出
  10636. ];
  10637. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10638. // DeepSeek 官方模型使用 DeepSeek API
  10639. $chatResult = $this->chatOnly($post_data);
  10640. } else if (in_array($model, $this->gpt_text_models)) {
  10641. // GPT-5.4 模型使用 TokenRouter API
  10642. $chatResult = $this->gpt54ChatOnly($post_data);
  10643. } else {
  10644. // 其他模型使用火山引擎API
  10645. $chatResult = $this->volcEngineChatCompletion($post_data);
  10646. }
  10647. if (is_array($chatResult)) {
  10648. extract($chatResult);
  10649. }else {
  10650. Utils::throwError('20003: 接口调用失败!');
  10651. }
  10652. return [
  10653. 'type' => 'done',
  10654. // 'episode' => $episode,
  10655. 'answer' => $fullContent,
  10656. 'reasoning' => $fullReasoningContent,
  10657. 'usage' => $usage
  10658. ];
  10659. }
  10660. // 仅调用deepseek对话接口
  10661. private function chatOnly($post_data) {
  10662. $post_data['max_tokens'] = 300000;
  10663. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10664. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  10665. $response = $result->getBody()->getContents();
  10666. $response_arr = json_decode($response, true);
  10667. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  10668. $fullContent = '';
  10669. $fullReasoningContent = [];
  10670. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10671. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10672. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10673. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  10674. }
  10675. return [
  10676. 'fullContent' => $fullContent,
  10677. 'fullReasoningContent' => $fullReasoningContent,
  10678. 'usage' => $usage
  10679. ];
  10680. }
  10681. // 仅调用 GPT-5.4 对话接口(非流式)
  10682. private function gpt54ChatOnly($post_data) {
  10683. $apiKey = env('GPT_54_API_KEY');
  10684. if (empty($apiKey)) {
  10685. Utils::throwError('20003:GPT-5.4 API Key未配置');
  10686. }
  10687. // 先探活,服务不可用时自动重试
  10688. $this->ensureGptServiceAvailable();
  10689. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10690. $headers = [
  10691. 'Authorization' => 'Bearer ' . $apiKey,
  10692. 'Content-Type' => 'application/json'
  10693. ];
  10694. // 移除 thinking 参数,GPT-5.4 不支持
  10695. if (isset($post_data['thinking'])) {
  10696. unset($post_data['thinking']);
  10697. }
  10698. if (isset($post_data['reasoning_effort'])) {
  10699. unset($post_data['reasoning_effort']);
  10700. }
  10701. $post_data['max_completion_tokens'] = 100000;
  10702. // 确保 stream 为 false
  10703. $post_data['stream'] = false;
  10704. $maxRetries = $this->gptRetryTimes();
  10705. $interval = $this->gptRetryInterval();
  10706. $attempt = 0;
  10707. while (true) {
  10708. try {
  10709. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  10710. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  10711. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  10712. 'json' => $post_data,
  10713. 'headers' => $headers
  10714. ]);
  10715. $response = $result->getBody()->getContents();
  10716. $response_arr = json_decode($response, true);
  10717. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  10718. $fullContent = '';
  10719. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10720. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10721. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10722. }
  10723. return [
  10724. 'fullContent' => $fullContent,
  10725. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  10726. 'usage' => $usage
  10727. ];
  10728. } catch (\Exception $e) {
  10729. if (!$this->isGptRetryableException($e) || $attempt >= $maxRetries) {
  10730. dLog('deepseek')->error('GPT-5.4 请求失败: ' . $e->getMessage());
  10731. logDB('deepseek', 'error', 'GPT-5.4 请求失败', ['error' => $e->getMessage()]);
  10732. throw $e;
  10733. }
  10734. dLog('deepseek')->warning('GPT-5.4 请求失败,准备重试', [
  10735. 'retry' => $attempt + 1,
  10736. 'max_retries' => $maxRetries,
  10737. 'error' => $e->getMessage()
  10738. ]);
  10739. sleep($interval);
  10740. $attempt++;
  10741. }
  10742. }
  10743. }
  10744. private function splitContent($content) {
  10745. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  10746. $chapters = [];
  10747. // 匹配章节标题格式:
  10748. // 1. 标题可能独占一行,也可能在正文末尾或中间
  10749. // 2. 格式支持:
  10750. // - **第一集**
  10751. // - 第一集:
  10752. // - ###第1章 重生
  10753. // - ##第2章 相救
  10754. // - 第三章 共处一室
  10755. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  10756. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  10757. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  10758. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  10759. // 先预处理:将标题前后添加换行符,确保标题能被正确识别和拆分
  10760. // 匹配模式:可能有前缀符号 + "第" + 空格(可选) + 数字 + 空格(可选) + 章节关键字 + 可能的标题内容
  10761. $pattern = '/([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])([^第\n]*?)(?=第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场回话]|$)/u';
  10762. // 先在每个标题前插入换行符(如果前面不是换行的话)
  10763. $content = preg_replace('/([^\n])([#*·\-_=\s]*)第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话])/u', "$1\n\n$2第$3$4", $content);
  10764. // 现在用修改后的模式匹配(标题应该在行首或接近行首)
  10765. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  10766. // 用正则找出所有章节标题的位置
  10767. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  10768. $titleCount = count($matches[0]);
  10769. for ($i = 0; $i < $titleCount; $i++) {
  10770. // 获取当前章节标题
  10771. $titleLine = trim($matches[0][$i][0]);
  10772. // 去除标题开头的特殊符号
  10773. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  10774. // 去除标题结尾的冒号和特殊符号
  10775. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  10776. $cleanTitle = trim($cleanTitle);
  10777. // 获取当前标题的结束位置
  10778. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  10779. // 获取下一个章节标题的开始位置(如果存在)
  10780. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  10781. // 提取章节内容(从标题结束到下一个标题开始)
  10782. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  10783. // 清理内容:去除前后空白和分隔线
  10784. $chapterContent = trim($chapterContent);
  10785. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  10786. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  10787. if (!empty($cleanTitle) && !empty($chapterContent)) {
  10788. $chapters[] = [
  10789. 'title' => $cleanTitle,
  10790. 'content' => $chapterContent
  10791. ];
  10792. }
  10793. }
  10794. } else {
  10795. // 如果没有匹配到章节,返回整个内容
  10796. $chapters[] = [
  10797. 'title' => '',
  10798. 'content' => $content
  10799. ];
  10800. }
  10801. return $chapters;
  10802. }
  10803. public function getContentByBid($bid) {
  10804. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  10805. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  10806. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  10807. $content = '';
  10808. foreach ($chapters as $chapter) {
  10809. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  10810. }
  10811. return $content;
  10812. }
  10813. public function getContentByScriptId($script_id) {
  10814. $content = '';
  10815. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  10816. if ($contents) {
  10817. $content = implode(PHP_EOL, $contents);
  10818. }else {
  10819. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  10820. }
  10821. return $content;
  10822. }
  10823. /**
  10824. * 根据文件类型提取文本内容
  10825. *
  10826. * @param mixed $file 文件对象或文件路径
  10827. * @return string
  10828. */
  10829. public function extractFileContent($file) {
  10830. // 获取文件路径和扩展名
  10831. if (is_string($file)) {
  10832. $filePath = $file;
  10833. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  10834. } else {
  10835. // Laravel UploadedFile 对象
  10836. $filePath = $file->getRealPath();
  10837. $extension = strtolower($file->getClientOriginalExtension());
  10838. }
  10839. $content = '';
  10840. switch ($extension) {
  10841. case 'txt':
  10842. $content = $this->extractTxtContent($filePath);
  10843. break;
  10844. case 'pdf':
  10845. $content = $this->extractPdfContent($filePath);
  10846. break;
  10847. case 'doc':
  10848. case 'docx':
  10849. $content = $this->extractWordContent($filePath);
  10850. break;
  10851. // case 'jpg':
  10852. // case 'jpeg':
  10853. // case 'png':
  10854. // case 'gif':
  10855. // case 'bmp':
  10856. // case 'webp':
  10857. // $content = $this->extractImageContent($filePath);
  10858. // break;
  10859. default:
  10860. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  10861. }
  10862. return $content;
  10863. }
  10864. /**
  10865. * 提取 TXT 文件内容
  10866. */
  10867. private function extractTxtContent($filePath) {
  10868. if (!file_exists($filePath)) {
  10869. Utils::throwError('20003:文件不存在');
  10870. }
  10871. $content = file_get_contents($filePath);
  10872. // 尝试检测并转换编码
  10873. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  10874. if ($encoding && $encoding !== 'UTF-8') {
  10875. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  10876. }
  10877. return trim($content);
  10878. }
  10879. /**
  10880. * 提取 PDF 文件内容
  10881. */
  10882. private function extractPdfContent($filePath) {
  10883. if (!file_exists($filePath)) {
  10884. Utils::throwError('20003:文件不存在');
  10885. }
  10886. try {
  10887. $parser = new PdfParser();
  10888. $pdf = $parser->parseFile($filePath);
  10889. $content = $pdf->getText();
  10890. return trim($content);
  10891. } catch (\Exception $e) {
  10892. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  10893. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  10894. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  10895. }
  10896. }
  10897. /**
  10898. * 提取 Word 文件内容(支持 doc 和 docx)
  10899. */
  10900. private function extractWordContent($filePath) {
  10901. if (!file_exists($filePath)) {
  10902. Utils::throwError('20003:文件不存在');
  10903. }
  10904. try {
  10905. $phpWord = WordIOFactory::load($filePath);
  10906. $content = '';
  10907. foreach ($phpWord->getSections() as $section) {
  10908. foreach ($section->getElements() as $element) {
  10909. $content .= $this->extractWordElementText($element);
  10910. }
  10911. }
  10912. return trim($content);
  10913. } catch (\Exception $e) {
  10914. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  10915. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  10916. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  10917. }
  10918. }
  10919. /**
  10920. * 递归提取 Word 元素中的文本
  10921. */
  10922. private function extractWordElementText($element) {
  10923. $text = '';
  10924. if (method_exists($element, 'getText')) {
  10925. $text .= $element->getText() . "\n";
  10926. } elseif (method_exists($element, 'getElements')) {
  10927. foreach ($element->getElements() as $childElement) {
  10928. $text .= $this->extractWordElementText($childElement);
  10929. }
  10930. }
  10931. return $text;
  10932. }
  10933. /**
  10934. * 提取图片内容(使用火山引擎 OCR)
  10935. */
  10936. private function extractImageContent($filePath) {
  10937. if (!file_exists($filePath)) {
  10938. Utils::throwError('20003:文件不存在');
  10939. }
  10940. try {
  10941. // 读取图片并转换为 base64
  10942. $imageData = file_get_contents($filePath);
  10943. $base64Image = base64_encode($imageData);
  10944. // 调用火山引擎 OCR 服务
  10945. $content = $this->callVolcEngineOCR($base64Image);
  10946. return trim($content);
  10947. } catch (\Exception $e) {
  10948. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  10949. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  10950. Utils::throwError('20003:图片识别失败');
  10951. }
  10952. }
  10953. /**
  10954. * 调用火山引擎 OCR 服务识别图片文字
  10955. *
  10956. * @param string $base64Image base64 编码的图片数据
  10957. * @return string 识别的文字内容
  10958. */
  10959. private function callVolcEngineOCR($base64Image) {
  10960. $method = 'POST';
  10961. $service = 'cv';
  10962. $host = 'visual.volcengineapi.com';
  10963. $region = env('VOLC_REGION', 'cn-north-1');
  10964. $access_key = env('VOLC_AK');
  10965. $secret_key = env('VOLC_SK');
  10966. $action = 'OCRNormal';
  10967. $version = '2020-08-26';
  10968. if (!$access_key || !$secret_key) {
  10969. Utils::throwError('20003:请配置火山引擎 AK/SK');
  10970. }
  10971. // 请求体
  10972. $body = json_encode([
  10973. 'image_base64' => $base64Image
  10974. ]);
  10975. // 生成签名
  10976. $headers = $this->getVolcEngineSignHeaders(
  10977. $method, $service, $host, $region,
  10978. "Action={$action}&Version={$version}",
  10979. $access_key, $secret_key, $body
  10980. );
  10981. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10982. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  10983. 'headers' => $headers,
  10984. 'body' => $body
  10985. ]);
  10986. $response_arr = json_decode($response->getBody()->getContents(), true);
  10987. // 提取识别的文字
  10988. $textLines = [];
  10989. if (isset($response_arr['data']['line_texts'])) {
  10990. $textLines = $response_arr['data']['line_texts'];
  10991. } elseif (isset($response_arr['data']['ocr_infos'])) {
  10992. foreach ($response_arr['data']['ocr_infos'] as $info) {
  10993. if (isset($info['text'])) {
  10994. $textLines[] = $info['text'];
  10995. }
  10996. }
  10997. }
  10998. if (empty($textLines)) {
  10999. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  11000. return '';
  11001. }
  11002. return implode("\n", $textLines);
  11003. }
  11004. /**
  11005. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  11006. */
  11007. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  11008. $contentType = 'application/json';
  11009. $accept = 'application/json';
  11010. // 获取当前UTC时间
  11011. $t = new DateTime('now', new DateTimeZone('UTC'));
  11012. $xDate = $t->format('Ymd\THis\Z');
  11013. $dateStamp = $t->format('Ymd');
  11014. // 计算 body 的 sha256 哈希
  11015. $payloadHash = hash('sha256', $body);
  11016. // 1. 拼接规范请求串
  11017. $canonicalUri = '/';
  11018. $canonicalQueryString = $queryString;
  11019. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  11020. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  11021. $canonicalRequest = implode("\n", [
  11022. $method,
  11023. $canonicalUri,
  11024. $canonicalQueryString,
  11025. $canonicalHeaders,
  11026. $signedHeaders,
  11027. $payloadHash
  11028. ]);
  11029. // 2. 拼接待签名字符串
  11030. $algorithm = 'HMAC-SHA256';
  11031. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  11032. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  11033. $stringToSign = implode("\n", [
  11034. $algorithm,
  11035. $xDate,
  11036. $credentialScope,
  11037. $hashedCanonicalRequest
  11038. ]);
  11039. // 3. 计算签名
  11040. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  11041. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  11042. // 4. 添加签名到请求头
  11043. $authorizationHeader = sprintf(
  11044. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  11045. $algorithm,
  11046. $access_key,
  11047. $credentialScope,
  11048. $signedHeaders,
  11049. $signature
  11050. );
  11051. return [
  11052. 'Accept' => $accept,
  11053. 'Content-Type' => $contentType,
  11054. 'Host' => $host,
  11055. 'X-Date' => $xDate,
  11056. 'X-Content-Sha256'=> $payloadHash,
  11057. 'Authorization' => $authorizationHeader
  11058. ];
  11059. }
  11060. public function generateScriptWords($cid, $model = 'r1') {
  11061. ini_set('max_execution_time', 0);
  11062. if (!$cid) Utils::throwError('20003: 请选择章节!');
  11063. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  11064. // 模型兼容性处理和思考模式设置
  11065. $thinkingMode = 'disabled';
  11066. $reasoningEffort = 'high';
  11067. if ($model == 'r1') {
  11068. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  11069. $thinkingMode = 'enabled';
  11070. } else {
  11071. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  11072. $thinkingMode = 'disabled';
  11073. }
  11074. $messages = [
  11075. [
  11076. 'role' => 'system',
  11077. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  11078. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  11079. 2.非对话部分请全部用旁白角色代替
  11080. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  11081. ],
  11082. [
  11083. 'role' => 'user',
  11084. 'content' => $content
  11085. ]
  11086. ];
  11087. $post_data = [
  11088. 'model' => $model,
  11089. 'messages' => $messages,
  11090. // 'max_tokens' => 8192,
  11091. 'temperature' => (float)env('TEXT_TEMPERATURE'),
  11092. 'frequency_penalty' => 0,
  11093. 'presence_penalty' => 0,
  11094. 'thinking' => ['type' => $thinkingMode],
  11095. 'response_format' => [
  11096. 'type' => 'text'
  11097. ],
  11098. 'stream' => false
  11099. ];
  11100. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  11101. // 根据模型类型选择调用方法
  11102. $fullContent = '';
  11103. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  11104. // DeepSeek 官方模型使用 DeepSeek API
  11105. $chatResult = $this->chatOnly($post_data);
  11106. } else if (in_array($model, $this->gpt_text_models)) {
  11107. // GPT-5.4 模型使用 TokenRouter API
  11108. $chatResult = $this->gpt54ChatOnly($post_data);
  11109. } else {
  11110. // 其他模型使用火山引擎API
  11111. $chatResult = $this->volcEngineChatCompletion($post_data);
  11112. }
  11113. if (is_array($chatResult)) {
  11114. $fullContent = $chatResult['fullContent'];
  11115. }
  11116. return $fullContent;
  11117. }
  11118. /**
  11119. * 智能化解析集数信息
  11120. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  11121. *
  11122. * @param string $prompt 用户输入的提示词
  11123. * @return int|null 解析出的集数,如果没有找到则返回null
  11124. */
  11125. private function extractEpisodeNumber($prompt)
  11126. {
  11127. if (empty($prompt)) {
  11128. return null;
  11129. }
  11130. // 定义各种可能的表达模式
  11131. $patterns = [
  11132. // 基本模式:改成N集、调整成N集、修改成N集
  11133. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  11134. // 扩展模式:分成N集、拆分成N集、分割成N集
  11135. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  11136. // 数量模式:N集、共N集、总共N集
  11137. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  11138. // 制作模式:制作N集、生成N集、创建N集
  11139. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  11140. // 计划模式:计划N集、预计N集、打算N集
  11141. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  11142. // 需要模式:需要N集、要N集
  11143. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  11144. // 中文数字模式:改成三集、调整成五集等
  11145. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  11146. // 英文数字模式
  11147. '/(?: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',
  11148. ];
  11149. // 中文数字转阿拉伯数字的映射
  11150. $chineseNumbers = [
  11151. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  11152. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  11153. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  11154. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  11155. ];
  11156. // 逐个尝试匹配模式
  11157. foreach ($patterns as $pattern) {
  11158. if (preg_match($pattern, $prompt, $matches)) {
  11159. $number = trim($matches[1]);
  11160. // 如果是中文数字,转换为阿拉伯数字
  11161. if (isset($chineseNumbers[$number])) {
  11162. return $chineseNumbers[$number];
  11163. }
  11164. // 如果是阿拉伯数字,直接返回
  11165. if (is_numeric($number)) {
  11166. $episodeNum = intval($number);
  11167. // 合理性检查:集数应该在1-100之间
  11168. if ($episodeNum >= 1 && $episodeNum <= 100) {
  11169. return $episodeNum;
  11170. }
  11171. }
  11172. }
  11173. }
  11174. return null;
  11175. }
  11176. /**
  11177. * 调用火山引擎对话(Chat) API
  11178. *
  11179. * @param array $params 包含以下参数:
  11180. * - model: 模型ID(必填)
  11181. * - messages: 消息列表(必填)
  11182. * - stream: 是否流式输出(可选,默认false)
  11183. * - max_tokens: 最大输出token数(可选)
  11184. * - temperature: 采样温度(可选,默认1)
  11185. * - top_p: 核采样概率(可选,默认0.7)
  11186. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  11187. * - presence_penalty: 存在惩罚系数(可选,默认0)
  11188. * - stop: 停止词(可选)
  11189. * - tools: 工具列表(可选)
  11190. * @return array|Generator 非流式返回数组,流式返回生成器
  11191. */
  11192. public function volcEngineChatCompletion(array $params)
  11193. {
  11194. $apiKey = env('VOLC_AI_API_KEY');
  11195. if (empty($apiKey)) {
  11196. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  11197. }
  11198. // 构建请求参数
  11199. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  11200. $requestData = [
  11201. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  11202. 'messages' => $params['messages'] ?? [],
  11203. ];
  11204. if (!in_array($originalModel, $this->valid_text_models)) {
  11205. Utils::throwError('20003:该模型不支持!');
  11206. }
  11207. // 添加可选参数
  11208. if (isset($params['stream'])) {
  11209. $requestData['stream'] = $params['stream'];
  11210. }
  11211. if (isset($params['stream_options'])) {
  11212. $requestData['stream_options'] = $params['stream_options'];
  11213. }
  11214. if (isset($params['max_tokens'])) {
  11215. $requestData['max_tokens'] = $params['max_tokens'];
  11216. }else if (isset($params['max_completion_tokens'])) {
  11217. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  11218. }else {
  11219. $requestData['max_completion_tokens'] = 100000;
  11220. }
  11221. if (isset($params['temperature'])) {
  11222. $requestData['temperature'] = $params['temperature'];
  11223. }
  11224. if (isset($params['top_p'])) {
  11225. $requestData['top_p'] = $params['top_p'];
  11226. }
  11227. if (isset($params['frequency_penalty'])) {
  11228. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  11229. }
  11230. if (isset($params['presence_penalty'])) {
  11231. $requestData['presence_penalty'] = $params['presence_penalty'];
  11232. }
  11233. if (isset($params['stop'])) {
  11234. $requestData['stop'] = $params['stop'];
  11235. }
  11236. if (isset($params['tools'])) {
  11237. $requestData['tools'] = $params['tools'];
  11238. }
  11239. if (isset($params['tool_choice'])) {
  11240. $requestData['tool_choice'] = $params['tool_choice'];
  11241. }
  11242. if (isset($params['response_format'])) {
  11243. $requestData['response_format'] = $params['response_format'];
  11244. }
  11245. if (isset($params['thinking'])) {
  11246. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  11247. if (is_array($params['thinking'])) {
  11248. $requestData['thinking'] = $params['thinking'];
  11249. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  11250. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11251. }
  11252. } else {
  11253. $requestData['thinking'] = ['type' => $params['thinking']];
  11254. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  11255. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  11256. }
  11257. }
  11258. } else {
  11259. $requestData['thinking'] = ['type' => 'disabled'];
  11260. }
  11261. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  11262. $client = new Client(['verify' => false, 'timeout' => 1800]);
  11263. try {
  11264. // 判断是否为流式输出
  11265. $isStream = isset($params['stream']) && $params['stream'] === true;
  11266. if ($isStream) {
  11267. // 流式输出
  11268. // 流式请求默认声明返回 usage(未显式传参时)
  11269. $requestData['stream_options'] = $requestData['stream_options'] ?? ['include_usage' => true];
  11270. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  11271. } else {
  11272. // 非流式输出
  11273. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11274. 'headers' => [
  11275. 'Authorization' => 'Bearer ' . $apiKey,
  11276. 'Content-Type' => 'application/json',
  11277. ],
  11278. 'json' => $requestData
  11279. ]);
  11280. $responseData = json_decode($response->getBody(), true);
  11281. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  11282. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  11283. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  11284. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  11285. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  11286. }
  11287. return [
  11288. 'fullContent' => $fullContent,
  11289. 'fullReasoningContent' => $fullReasoningContent,
  11290. 'usage' => $usage
  11291. ];
  11292. }
  11293. } catch (\Exception $e) {
  11294. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  11295. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  11296. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  11297. }
  11298. }
  11299. /**
  11300. * 火山引擎对话API流式输出
  11301. *
  11302. * @param Client $client HTTP客户端
  11303. * @param string $apiKey API密钥
  11304. * @param array $requestData 请求数据
  11305. * @return Generator
  11306. */
  11307. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  11308. {
  11309. try {
  11310. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  11311. 'headers' => [
  11312. 'Authorization' => 'Bearer ' . $apiKey,
  11313. 'Content-Type' => 'application/json',
  11314. ],
  11315. 'json' => $requestData,
  11316. 'stream' => true
  11317. ]);
  11318. $body = $response->getBody();
  11319. $buffer = '';
  11320. $fullContent = '';
  11321. $fullReasoningContent = '';
  11322. $usage = [];
  11323. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  11324. // 逐行读取流式响应
  11325. while (!$body->eof()) {
  11326. $chunk = $body->read(1024);
  11327. $buffer .= $chunk;
  11328. // 按行分割
  11329. $lines = explode("\n", $buffer);
  11330. $buffer = array_pop($lines);
  11331. foreach ($lines as $line) {
  11332. $line = trim($line);
  11333. if (empty($line)) {
  11334. continue;
  11335. }
  11336. // 检查是否是SSE数据行
  11337. if (strpos($line, 'data: ') !== 0) {
  11338. continue;
  11339. }
  11340. $data = substr($line, 6);
  11341. if ($data === '[DONE]') {
  11342. dLog('deepseek')->info('收到结束标记');
  11343. break 2;
  11344. }
  11345. try {
  11346. $json = json_decode($data, true);
  11347. if (json_last_error() !== JSON_ERROR_NONE) {
  11348. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  11349. continue;
  11350. }
  11351. if (isset($json['choices'][0]['delta'])) {
  11352. $delta = $json['choices'][0]['delta'];
  11353. // 处理思维链内容
  11354. if (isset($delta['reasoning_content'])) {
  11355. $fullReasoningContent .= $delta['reasoning_content'];
  11356. yield [
  11357. 'type' => 'reasoning',
  11358. 'content' => $delta['reasoning_content'],
  11359. 'full_reasoning' => $fullReasoningContent
  11360. ];
  11361. }
  11362. // 处理回答内容
  11363. if (isset($delta['content'])) {
  11364. $fullContent .= $delta['content'];
  11365. yield [
  11366. 'type' => 'content',
  11367. 'content' => $delta['content'],
  11368. ];
  11369. }
  11370. }
  11371. // 获取使用统计信息
  11372. if (isset($json['usage'])) {
  11373. $usage = $json['usage'];
  11374. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  11375. }
  11376. } catch (\Exception $e) {
  11377. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  11378. continue;
  11379. }
  11380. }
  11381. }
  11382. dLog('deepseek')->info('流式读取完成', [
  11383. 'content_length' => strlen($fullContent),
  11384. 'reasoning_length' => strlen($fullReasoningContent)
  11385. ]);
  11386. yield [
  11387. 'type' => 'done',
  11388. 'full_content' => $fullContent,
  11389. 'full_reasoning' => $fullReasoningContent,
  11390. 'usage' => $usage
  11391. ];
  11392. } catch (\Exception $e) {
  11393. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  11394. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  11395. throw $e;
  11396. }
  11397. }
  11398. /**
  11399. * 检查并创建图片生成任务
  11400. *
  11401. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  11402. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  11403. * @param string $nameKey 资源名称字段('role' 或 'scene')
  11404. * @param string $art_style 美术风格
  11405. * @return array 更新后的资源列表
  11406. */
  11407. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  11408. {
  11409. // 确保参数为数组
  11410. $merged_items = is_array($merged_items) ? $merged_items : [];
  11411. $global_items = is_array($global_items) ? $global_items : [];
  11412. // 构建全局资源映射表,用于快速查找
  11413. $global_map = [];
  11414. foreach ($global_items as $item) {
  11415. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  11416. if ($itemKey === '') {
  11417. continue;
  11418. }
  11419. $global_map[$itemKey] = $item;
  11420. }
  11421. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  11422. foreach ($merged_items as &$item) {
  11423. $item_name = getProp($item, $nameKey);
  11424. $item_description = getProp($item, 'description');
  11425. // $item_url = getProp($item, 'url');
  11426. // // 如果已有图片URL,跳过
  11427. // if (!empty($item_url)) {
  11428. // continue;
  11429. // }
  11430. // 如果是旁白角色,跳过
  11431. if ($nameKey === 'role' && $item_name === '旁白') {
  11432. continue;
  11433. }
  11434. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  11435. if ($itemKey === '') {
  11436. continue;
  11437. }
  11438. $need_create_task = false;
  11439. // 条件1:在全局资源中找不到匹配的名称
  11440. if (!isset($global_map[$itemKey])) {
  11441. $need_create_task = true;
  11442. } else {
  11443. // 条件2:名称匹配但描述或 pic_prompt 不一致
  11444. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  11445. $current_description = trim((string)$item_description);
  11446. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  11447. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  11448. // 如果 description 或 pic_prompt 有变化,需要重新生成
  11449. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  11450. $need_create_task = true;
  11451. }
  11452. }
  11453. // 如果需要创建任务,调用图片生成服务
  11454. if ($need_create_task) {
  11455. try {
  11456. // 优先使用 pic_prompt,如果没有则使用 description
  11457. $pic_prompt = getProp($item, 'pic_prompt');
  11458. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  11459. // 添加美术风格前缀
  11460. if ($art_style) {
  11461. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  11462. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  11463. $description = "{$prefix}:{$description}";
  11464. }
  11465. $params = [
  11466. 'prompt' => $description,
  11467. 'ref_img_urls' => []
  11468. ];
  11469. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  11470. $task_id = $task->id;
  11471. if ($task_id) {
  11472. $item['task_id'] = $task_id;
  11473. $item['task_status'] = 'processing';
  11474. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11475. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  11476. }
  11477. } catch (\Exception $e) {
  11478. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  11479. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  11480. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  11481. // 不抛出异常,继续处理其他资源
  11482. }
  11483. }
  11484. }
  11485. return $merged_items;
  11486. }
  11487. /**
  11488. * 同步新出现的主体和场景到全局
  11489. *
  11490. * @param int $anime_id 动漫ID
  11491. * @param array $merged_roles 合并后的角色列表
  11492. * @param array $merged_scenes 合并后的场景列表
  11493. * @param array $global_roles 全局角色列表
  11494. * @param array $global_scenes 全局场景列表
  11495. * @return void
  11496. */
  11497. private function syncNewResourcesToGlobal(
  11498. int $anime_id,
  11499. array $merged_roles,
  11500. array $merged_scenes,
  11501. array $global_roles,
  11502. array $global_scenes
  11503. ): void {
  11504. // 构建全局角色映射表
  11505. $global_role_map = [];
  11506. foreach ($global_roles as $role) {
  11507. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  11508. if ($roleKey !== '') {
  11509. $global_role_map[$roleKey] = $role;
  11510. }
  11511. }
  11512. // 构建全局场景映射表
  11513. $global_scene_map = [];
  11514. foreach ($global_scenes as $scene) {
  11515. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  11516. if ($sceneKey !== '') {
  11517. $global_scene_map[$sceneKey] = $scene;
  11518. }
  11519. }
  11520. $need_update = false;
  11521. $new_global_roles = $global_roles;
  11522. $new_global_scenes = $global_scenes;
  11523. // 检查并添加新角色到全局
  11524. foreach ($merged_roles as $role) {
  11525. $role_name = getProp($role, 'role');
  11526. // 跳过旁白
  11527. if ($role_name === '旁白') {
  11528. continue;
  11529. }
  11530. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  11531. if ($roleKey === '') {
  11532. continue;
  11533. }
  11534. // 如果全局中不存在该角色,添加到全局
  11535. if (!isset($global_role_map[$roleKey])) {
  11536. $new_global_roles[] = [
  11537. 'role' => $role_name,
  11538. 'description' => getProp($role, 'description', ''),
  11539. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  11540. 'voice_name' => getProp($role, 'voice_name', ''),
  11541. 'voice_type' => getProp($role, 'voice_type', ''),
  11542. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  11543. 'url' => getProp($role, 'url', ''),
  11544. 'task_id' => getProp($role, 'task_id', ''),
  11545. 'task_status' => getProp($role, 'task_status', ''),
  11546. ];
  11547. $global_role_map[$roleKey] = true; // 标记已添加
  11548. $need_update = true;
  11549. dLog('deepseek')->info("新角色同步到全局", [
  11550. 'anime_id' => $anime_id,
  11551. 'role' => $role_name,
  11552. 'task_id' => getProp($role, 'task_id', ''),
  11553. ]);
  11554. }
  11555. // else {
  11556. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11557. // $global_role = $global_role_map[$roleKey];
  11558. // if (is_array($global_role)) {
  11559. // $updated = false;
  11560. // $update_fields = [];
  11561. // // 检查描述是否更新
  11562. // $current_description = trim((string)getProp($role, 'description'));
  11563. // $global_description = trim((string)getProp($global_role, 'description'));
  11564. // if ($current_description !== '' && $current_description !== $global_description) {
  11565. // $updated = true;
  11566. // $update_fields[] = 'description';
  11567. // }
  11568. // // 检查pic_prompt是否更新
  11569. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  11570. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  11571. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11572. // $updated = true;
  11573. // $update_fields[] = 'pic_prompt';
  11574. // }
  11575. // // 检查图片任务信息是否更新
  11576. // $current_task_id = getProp($role, 'task_id');
  11577. // $global_task_id = getProp($global_role, 'task_id');
  11578. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11579. // $updated = true;
  11580. // $update_fields[] = 'task_id';
  11581. // }
  11582. // // 如果有更新,同步到全局
  11583. // if ($updated) {
  11584. // foreach ($new_global_roles as &$global_role_item) {
  11585. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  11586. // if ($global_role_key === $roleKey) {
  11587. // if (in_array('description', $update_fields)) {
  11588. // $global_role_item['description'] = $current_description;
  11589. // }
  11590. // if (in_array('pic_prompt', $update_fields)) {
  11591. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  11592. // }
  11593. // if (in_array('task_id', $update_fields)) {
  11594. // $global_role_item['task_id'] = $current_task_id;
  11595. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  11596. // $global_role_item['url'] = getProp($role, 'url', '');
  11597. // }
  11598. // break;
  11599. // }
  11600. // }
  11601. // $need_update = true;
  11602. // dLog('deepseek')->info("角色信息更新到全局", [
  11603. // 'anime_id' => $anime_id,
  11604. // 'role' => $role_name,
  11605. // 'update_fields' => implode(',', $update_fields),
  11606. // ]);
  11607. // }
  11608. // }
  11609. // }
  11610. }
  11611. // 检查并添加新场景到全局
  11612. foreach ($merged_scenes as $scene) {
  11613. $scene_name = getProp($scene, 'scene');
  11614. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  11615. if ($sceneKey === '') {
  11616. continue;
  11617. }
  11618. // 如果全局中不存在该场景,添加到全局
  11619. if (!isset($global_scene_map[$sceneKey])) {
  11620. $new_global_scenes[] = [
  11621. 'scene' => $scene_name,
  11622. 'description' => getProp($scene, 'description', ''),
  11623. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  11624. 'url' => getProp($scene, 'url', ''),
  11625. 'task_id' => getProp($scene, 'task_id', ''),
  11626. 'task_status' => getProp($scene, 'task_status', ''),
  11627. ];
  11628. $global_scene_map[$sceneKey] = true; // 标记已添加
  11629. $need_update = true;
  11630. dLog('deepseek')->info("新场景同步到全局", [
  11631. 'anime_id' => $anime_id,
  11632. 'scene' => $scene_name,
  11633. 'task_id' => getProp($scene, 'task_id', ''),
  11634. ]);
  11635. }
  11636. // else {
  11637. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  11638. // $global_scene = $global_scene_map[$sceneKey];
  11639. // if (is_array($global_scene)) {
  11640. // $updated = false;
  11641. // $update_fields = [];
  11642. // // 检查描述是否更新
  11643. // $current_description = trim((string)getProp($scene, 'description'));
  11644. // $global_description = trim((string)getProp($global_scene, 'description'));
  11645. // if ($current_description !== '' && $current_description !== $global_description) {
  11646. // $updated = true;
  11647. // $update_fields[] = 'description';
  11648. // }
  11649. // // 检查pic_prompt是否更新
  11650. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  11651. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  11652. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11653. // $updated = true;
  11654. // $update_fields[] = 'pic_prompt';
  11655. // }
  11656. // // 检查图片任务信息是否更新
  11657. // $current_task_id = getProp($scene, 'task_id');
  11658. // $global_task_id = getProp($global_scene, 'task_id');
  11659. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11660. // $updated = true;
  11661. // $update_fields[] = 'task_id';
  11662. // }
  11663. // // 如果有更新,同步到全局
  11664. // if ($updated) {
  11665. // foreach ($new_global_scenes as &$global_scene_item) {
  11666. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  11667. // if ($global_scene_key === $sceneKey) {
  11668. // if (in_array('description', $update_fields)) {
  11669. // $global_scene_item['description'] = $current_description;
  11670. // }
  11671. // if (in_array('pic_prompt', $update_fields)) {
  11672. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  11673. // }
  11674. // if (in_array('task_id', $update_fields)) {
  11675. // $global_scene_item['task_id'] = $current_task_id;
  11676. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  11677. // $global_scene_item['url'] = getProp($scene, 'url', '');
  11678. // }
  11679. // break;
  11680. // }
  11681. // }
  11682. // $need_update = true;
  11683. // dLog('deepseek')->info("场景信息更新到全局", [
  11684. // 'anime_id' => $anime_id,
  11685. // 'scene' => $scene_name,
  11686. // 'update_fields' => implode(',', $update_fields),
  11687. // ]);
  11688. // }
  11689. // }
  11690. // }
  11691. }
  11692. // 如果有新增或更新,更新数据库
  11693. if ($need_update) {
  11694. $update_data = [
  11695. 'roles' => json_encode($new_global_roles, 256),
  11696. 'scenes' => json_encode($new_global_scenes, 256),
  11697. 'updated_at' => date('Y-m-d H:i:s'),
  11698. ];
  11699. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  11700. if ($result !== false) {
  11701. dLog('deepseek')->info("全局角色和场景更新成功", [
  11702. 'anime_id' => $anime_id,
  11703. 'roles_count' => count($new_global_roles),
  11704. 'scenes_count' => count($new_global_scenes),
  11705. ]);
  11706. } else {
  11707. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  11708. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  11709. }
  11710. }
  11711. }
  11712. }