DeepSeekService.php 694 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533
  1. <?php
  2. namespace App\Services\DeepSeek;
  3. use App\Consts\ErrorConst;
  4. use App\Consts\BaseConst;
  5. use App\Facade\Site;
  6. use App\Libs\Utils;
  7. use GuzzleHttp\Client;
  8. use DateTime;
  9. use DateTimeZone;
  10. use App\Services\AIGeneration\AIImageGenerationService;
  11. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Log;
  13. use Illuminate\Support\Facades\Redis;
  14. use OSS\Core\OssException;
  15. use OSS\OssClient;
  16. use Smalot\PdfParser\Parser as PdfParser;
  17. use TCPDF;
  18. use PhpOffice\PhpWord\IOFactory as WordIOFactory;
  19. use Predis\Command\Traits\Get\Get;
  20. class DeepSeekService
  21. {
  22. private $url;
  23. private $api_key;
  24. private $sys_message;
  25. private $headers;
  26. private $valid_text_models;
  27. private $gpt_text_models;
  28. protected $aiImageGenerationService;
  29. public function __construct(AIImageGenerationService $aiImageGenerationService) {
  30. $this->aiImageGenerationService = $aiImageGenerationService;
  31. $this->url = 'https://api.deepseek.com/chat/completions'; // DeepSeek API请求地址
  32. $this->api_key = env('DEEPSEEK_API_KEY');
  33. $this->headers = [
  34. 'Authorization' => 'Bearer '.$this->api_key,
  35. 'Content-Type' => 'application/json; charset=UTF-8'
  36. ];
  37. // 火山引擎模型列表
  38. $this->valid_text_models = DB::table('mp_text_models')->where('is_enabled', 1)->pluck('model')->toArray();
  39. // GPT文本模型列表
  40. $this->gpt_text_models = BaseConst::GPT_TEXT_MODELS;
  41. $this->sys_message = [
  42. 'role' => 'system',
  43. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  44. 强制要求:\n
  45. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  46. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  47. 3.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  48. 普通要求:\n
  49. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n
  50. 2.<分集剧本>的要求如下:
  51.  2.1包含“分集序号”、“分集标题”以及“分集信息”,“分集信息”需包含“场景描述”、“运镜”、“出场角色”和“台词内容”这几个部分,其中“出场角色”和“场景描述”必须在前面的板块<主体列表>和<场景列表>中选取,不得自定义。
  52.  2.2.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  53.  2.3.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  54.  2.4.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  55. \n\n
  56. 示例如下:\n
  57. ###剧本名:西昆仑
  58. ###故事梗概
  59. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  60. ###剧本亮点
  61. 亮点1:绝境奇药,生死一线
  62. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  63. 亮点2:结拜兄妹,化解尴尬
  64. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  65. 亮点3:纤发夺命,情愫暗涌
  66. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  67. ###人物关系
  68. 阿雪与梁萧之间存在兄妹之情。
  69. ###核心矛盾
  70. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  71. ###主体列表
  72. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  73. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  74. 阴阳球:天地异宝,能化生精气,救人于危难。
  75. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  76. ###美术风格
  77. 基础画风风格词:厚涂古风
  78. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  79. ###场景列表
  80. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。
  81. ###分集剧本
  82. ##分集01
  83. 第1集: 第一集的标题
  84. 场景描述:地点、时间、场景
  85. 运镜:固定近距离
  86. 出场角色:男主、女主
  87. 台词内容:
  88. 女主: 女主对话
  89. 男主:男主对话
  90. 女主: 女主对话
  91. 男主: 男主对话
  92. ##分集02
  93. 第2集: 第二集的标题
  94. 场景描述:地点、时间、场景
  95. 运镜:固定近距离
  96. 出场角色:男主、女主
  97. 台词内容:
  98. 女主: 女主对话
  99. 男主:男主对话
  100. 女主: 女主对话
  101. 男主: 男主对话"
  102. ];
  103. }
  104. /**
  105. * 通用文生文方法 - 支持多模型流式输出和图片输入
  106. *
  107. * @param array $data 请求参数
  108. * @return \Generator 返回生成器,用于流式输出
  109. */
  110. public function generateText($data) {
  111. // 获取请求参数
  112. $model = getProp($data, 'model', 'deepseek-v3-2-251201'); // 默认使用deepseek-v3
  113. $messages = getProp($data, 'messages', []);
  114. $systemPrompt = getProp($data, 'system_prompt', '');
  115. $prompt = getProp($data, 'prompt', '');
  116. $images = getProp($data, 'images', []); // 支持多张图片
  117. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  118. // 如果没有提供messages,则根据system_prompt、content和images构建
  119. if (empty($messages)) {
  120. $messages = [];
  121. // 添加系统提示词
  122. if (!empty($systemPrompt)) {
  123. $messages[] = [
  124. 'role' => 'system',
  125. 'content' => $systemPrompt
  126. ];
  127. }
  128. // 构建用户消息内容(支持文本+图片)
  129. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  130. $userMessage = [
  131. 'role' => 'user',
  132. 'content' => []
  133. ];
  134. // 添加文本内容
  135. if (!empty($prompt)) {
  136. $userMessage['content'][] = [
  137. 'type' => 'text',
  138. 'text' => $prompt
  139. ];
  140. }
  141. // 处理上传的图片文件
  142. if (!empty($images)) {
  143. if (!is_array($images)) {
  144. $images = [$images];
  145. }
  146. foreach ($images as $image) {
  147. $imageBase64 = $this->processImageToBase64($image);
  148. if ($imageBase64) {
  149. $userMessage['content'][] = [
  150. 'type' => 'image_url',
  151. 'image_url' => [
  152. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  153. ]
  154. ];
  155. }
  156. }
  157. }
  158. // 处理图片URL
  159. if (!empty($imageUrls)) {
  160. if (!is_array($imageUrls)) {
  161. $imageUrls = [$imageUrls];
  162. }
  163. foreach ($imageUrls as $url) {
  164. if (!empty($url)) {
  165. $userMessage['content'][] = [
  166. 'type' => 'image_url',
  167. 'image_url' => [
  168. 'url' => $url
  169. ]
  170. ];
  171. }
  172. }
  173. }
  174. // 如果只有文本内容,简化为字符串格式
  175. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  176. $userMessage['content'] = $userMessage['content'][0]['text'];
  177. }
  178. $messages[] = $userMessage;
  179. }
  180. }
  181. // 验证messages不为空
  182. if (empty($messages)) {
  183. Utils::throwError('20003:请提供有效的对话内容');
  184. }
  185. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  186. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  187. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  188. if ($model === 'deepseek-chat') {
  189. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  190. $model = 'deepseek-v4-flash';
  191. $thinkingMode = 'disabled';
  192. } elseif ($model === 'deepseek-reasoner') {
  193. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  194. $model = 'deepseek-v4-flash';
  195. $thinkingMode = 'enabled';
  196. }
  197. // 构建请求参数
  198. $post_data = [
  199. 'model' => $model,
  200. 'messages' => $messages,
  201. // 'max_tokens' => getProp($data, 'max_tokens', 8192),
  202. 'temperature' => getProp($data, 'temperature', 1),
  203. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  204. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  205. 'thinking' => ['type' => $thinkingMode],
  206. 'stream' => true // 启用流式输出
  207. ];
  208. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  209. // 添加可选参数
  210. if (isset($data['top_p'])) {
  211. $post_data['top_p'] = $data['top_p'];
  212. }
  213. if (isset($data['response_format'])) {
  214. $post_data['response_format'] = $data['response_format'];
  215. }
  216. // 根据模型类型选择调用方法
  217. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  218. // DeepSeek 官方模型使用 DeepSeek API
  219. return $this->deepSeekStreamResponse($post_data);
  220. } else if (in_array($model, $this->gpt_text_models)) {
  221. // GPT 模型使用 TokenRouter API
  222. return $this->gpt54StreamResponse($post_data);
  223. } else if (in_array($model, $this->valid_text_models)) {
  224. // 火山引擎支持的模型使用火山引擎 API
  225. return $this->volcEngineChatCompletion($post_data);
  226. } else {
  227. Utils::throwError('20003:不支持的模型: ' . $model);
  228. }
  229. }
  230. public function createGenerateText($data) {
  231. $file = getProp($data, 'file');
  232. $uid = Site::getUid();
  233. $cpid = Site::getCpid();
  234. if (!$file) {
  235. Utils::throwError('20003:请上传文件');
  236. }
  237. // 提取文件内容
  238. $content = $this->extractFileContent($file);
  239. if (!$content) {
  240. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  241. }
  242. // 获取原始文件名(不含扩展名)作为script_name
  243. $originalName = $file->getClientOriginalName();
  244. $script_name = pathinfo($originalName, PATHINFO_FILENAME);
  245. if (!$script_name) {
  246. $script_name = '剧本_' . date('YmdHis');
  247. }
  248. // 如果剧本名称已存在,添加时间戳后缀
  249. if (DB::table('mp_scripts')->where('script_name', $script_name)->where('is_deleted', 0)->exists()) {
  250. $script_name .= '_' . date('YmdHis');
  251. }
  252. // 插入数据到mp_scripts表
  253. $script_id = DB::table('mp_scripts')->insertGetId([
  254. 'script_name' => $script_name,
  255. 'user_id' => $uid,
  256. 'cpid' => $cpid,
  257. 'content' => $content,
  258. 'created_at' => date('Y-m-d H:i:s'),
  259. 'updated_at' => date('Y-m-d H:i:s')
  260. ]);
  261. return [
  262. 'script_id' => $script_id,
  263. 'script_name' => $script_name
  264. ];
  265. }
  266. /**
  267. * 通用文生文方法(非流式版本)- 支持多模型、图片输入、JSON输出和模板提示词
  268. *
  269. * @param array $data 请求参数
  270. * @return array 返回结果数组
  271. */
  272. public function newGenerateText($data) {
  273. // 获取请求参数
  274. $model = getProp($data, 'model', 'deepseek-v4-pro'); // 默认使用deepseek-v4
  275. $messages = getProp($data, 'messages', []);
  276. $systemPrompt = getProp($data, 'system_prompt', '');
  277. $prompt = getProp($data, 'prompt', '');
  278. $images = getProp($data, 'images', []); // 支持多张图片
  279. $imageUrls = getProp($data, 'image_urls', []); // 支持图片URL
  280. $responseFormat = getProp($data, 'response_format', 'text'); // 新增: 响应格式,默认text,可选json
  281. $templateId = getProp($data, 'template_id', 0); // 新增: 模板ID
  282. $script_id = getProp($data, 'script_id', 0); // 新增: 剧本ID
  283. $sequence = getProp($data, 'sequence', 0); // 新增: 剧集序号
  284. // 新增: 如果提供了script_id,从数据库获取剧本内容作为原文
  285. $originalContent = '';
  286. if ($script_id > 0) {
  287. $script = DB::table('mp_scripts')
  288. ->where('id', $script_id)
  289. ->where('is_deleted', 0)
  290. ->first();
  291. if (!$script) {
  292. Utils::throwError('20003:剧本不存在或已删除');
  293. }
  294. $originalContent = $script->content ?? '';
  295. if (empty($originalContent)) {
  296. Utils::throwError('20003:剧本内容为空');
  297. }
  298. // 将剧本内容添加到提示词前面
  299. if (!empty($originalContent)) {
  300. if (!empty($prompt)) {
  301. $prompt = "原文内容:\n" . $originalContent . "\n\n用户要求:\n" . $prompt;
  302. } else {
  303. $prompt = "原文内容:\n" . $originalContent;
  304. }
  305. }
  306. }
  307. // 新增: 如果提供了template_id,从数据库获取template_prompt
  308. if ($templateId > 0) {
  309. $template = DB::table('mp_prompt_templates')
  310. ->where('id', $templateId)
  311. ->where('is_deleted', 0)
  312. ->first();
  313. if (!$template) {
  314. Utils::throwError('20003:模板不存在或已删除');
  315. }
  316. $templatePrompt = $template->template_prompt ?? '';
  317. // 将模板提示词和用户输入的prompt组合
  318. // 模板为准,用户输入作为补充要求
  319. if (!empty($templatePrompt)) {
  320. if (!empty($prompt)) {
  321. $prompt = $templatePrompt . "\n\n" . $prompt;
  322. } else {
  323. $prompt = $templatePrompt;
  324. }
  325. }
  326. }
  327. // 如果没有提供messages,则根据system_prompt、prompt和images构建
  328. if (empty($messages)) {
  329. $messages = [];
  330. // 添加系统提示词
  331. if (!empty($systemPrompt)) {
  332. $messages[] = [
  333. 'role' => 'system',
  334. 'content' => $systemPrompt
  335. ];
  336. }
  337. // 构建用户消息内容(支持文本+图片)
  338. if (!empty($prompt) || !empty($images) || !empty($imageUrls)) {
  339. $userMessage = [
  340. 'role' => 'user',
  341. 'content' => []
  342. ];
  343. // 添加文本内容
  344. if (!empty($prompt)) {
  345. $userMessage['content'][] = [
  346. 'type' => 'text',
  347. 'text' => $prompt
  348. ];
  349. }
  350. // 处理上传的图片文件
  351. if (!empty($images)) {
  352. if (!is_array($images)) {
  353. $images = [$images];
  354. }
  355. foreach ($images as $image) {
  356. $imageBase64 = $this->processImageToBase64($image);
  357. if ($imageBase64) {
  358. $userMessage['content'][] = [
  359. 'type' => 'image_url',
  360. 'image_url' => [
  361. 'url' => "data:image/jpeg;base64,{$imageBase64}"
  362. ]
  363. ];
  364. }
  365. }
  366. }
  367. // 处理图片URL
  368. if (!empty($imageUrls)) {
  369. if (!is_array($imageUrls)) {
  370. $imageUrls = [$imageUrls];
  371. }
  372. foreach ($imageUrls as $url) {
  373. if (!empty($url)) {
  374. $userMessage['content'][] = [
  375. 'type' => 'image_url',
  376. 'image_url' => [
  377. 'url' => $url
  378. ]
  379. ];
  380. }
  381. }
  382. }
  383. // 如果只有文本内容,简化为字符串格式
  384. if (count($userMessage['content']) === 1 && $userMessage['content'][0]['type'] === 'text') {
  385. $userMessage['content'] = $userMessage['content'][0]['text'];
  386. }
  387. $messages[] = $userMessage;
  388. }
  389. }
  390. // 验证messages不为空
  391. if (empty($messages)) {
  392. Utils::throwError('20003:请提供有效的对话内容');
  393. }
  394. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  395. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  396. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  397. if ($model === 'deepseek-chat') {
  398. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  399. $model = 'deepseek-v4-flash';
  400. $thinkingMode = 'disabled';
  401. } elseif ($model === 'deepseek-reasoner') {
  402. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  403. $model = 'deepseek-v4-flash';
  404. $thinkingMode = 'enabled';
  405. }
  406. // 构建请求参数(非流式)
  407. $post_data = [
  408. 'model' => $model,
  409. 'messages' => $messages,
  410. 'temperature' => getProp($data, 'temperature', 1),
  411. 'frequency_penalty' => getProp($data, 'frequency_penalty', 0),
  412. 'presence_penalty' => getProp($data, 'presence_penalty', 0),
  413. 'thinking' => ['type' => $thinkingMode],
  414. 'stream' => false // 非流式输出
  415. ];
  416. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  417. // 添加可选参数
  418. if (isset($data['top_p'])) {
  419. $post_data['top_p'] = $data['top_p'];
  420. }
  421. // 新增: 根据response_format设置响应格式
  422. if ($responseFormat === 'json') {
  423. // 检查提示词中是否包含"json"关键词,如果没有则自动添加
  424. $hasJsonKeyword = false;
  425. foreach ($post_data['messages'] as $message) {
  426. if (isset($message['content'])) {
  427. $content = is_array($message['content']) ? json_encode($message['content']) : $message['content'];
  428. if (stripos($content, 'json') !== false) {
  429. $hasJsonKeyword = true;
  430. break;
  431. }
  432. }
  433. }
  434. // 如果提示词中没有"json"关键词,在最后一条用户消息中添加JSON格式说明
  435. // 这对所有模型都适用,确保模型理解需要返回JSON格式
  436. if (!$hasJsonKeyword) {
  437. $lastMessageIndex = count($post_data['messages']) - 1;
  438. if ($lastMessageIndex >= 0 && $post_data['messages'][$lastMessageIndex]['role'] === 'user') {
  439. $lastContent = $post_data['messages'][$lastMessageIndex]['content'];
  440. // 如果content是字符串,直接追加
  441. if (is_string($lastContent)) {
  442. $post_data['messages'][$lastMessageIndex]['content'] .= "\n\n请以JSON格式返回结果。";
  443. }
  444. // 如果content是数组(包含文本和图片),在文本部分追加
  445. else if (is_array($lastContent)) {
  446. foreach ($post_data['messages'][$lastMessageIndex]['content'] as &$contentPart) {
  447. if ($contentPart['type'] === 'text') {
  448. $contentPart['text'] .= "\n\n请以JSON格式返回结果。";
  449. break;
  450. }
  451. }
  452. }
  453. dLog('deepseek')->info('自动添加JSON格式提示词', ['model' => $model]);
  454. }
  455. }
  456. // 设置response_format参数(所有支持的模型)
  457. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  458. // DeepSeek模型
  459. $post_data['response_format'] = ['type' => 'json_object'];
  460. } else if (in_array($model, $this->gpt_text_models)) {
  461. // GPT模型
  462. $post_data['response_format'] = ['type' => 'json_object'];
  463. } else if (in_array($model, $this->valid_text_models)) {
  464. // 火山引擎模型
  465. $post_data['response_format'] = ['type' => 'json_object'];
  466. }
  467. }
  468. // 根据模型类型选择调用方法(复用现有的chatOnly方法)
  469. $aiResult = null;
  470. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  471. // DeepSeek 官方模型使用现有的 chatOnly 方法
  472. $result = $this->chatOnly($post_data);
  473. // 记录实际使用的模型
  474. dLog('deepseek')->info('newGenerateText使用DeepSeek模型', ['requested_model' => $model, 'actual_model' => $model]);
  475. $aiResult = [
  476. 'content' => $result['fullContent'],
  477. 'reasoning_content' => $result['fullReasoningContent'],
  478. 'usage' => $result['usage'],
  479. 'model' => $model,
  480. 'finish_reason' => 'stop'
  481. ];
  482. } else if (in_array($model, $this->gpt_text_models)) {
  483. // GPT 模型使用现有的 gpt54ChatOnly 方法
  484. $result = $this->gpt54ChatOnly($post_data);
  485. dLog('deepseek')->info('newGenerateText使用GPT模型', ['requested_model' => $model]);
  486. $aiResult = [
  487. 'content' => $result['fullContent'],
  488. 'reasoning_content' => '',
  489. 'usage' => $result['usage'],
  490. 'model' => $model,
  491. 'finish_reason' => 'stop'
  492. ];
  493. } else if (in_array($model, $this->valid_text_models)) {
  494. // 火山引擎支持的模型使用火山引擎 API(非流式)
  495. $post_data['stream'] = false;
  496. $result = $this->volcEngineChatCompletion($post_data);
  497. dLog('deepseek')->info('newGenerateText使用火山引擎模型', [
  498. 'requested_model' => $model,
  499. 'result_keys' => array_keys($result),
  500. 'has_fullContent' => isset($result['fullContent']),
  501. 'has_content' => isset($result['content'])
  502. ]);
  503. // 火山引擎返回的数据结构使用 fullContent 和 fullReasoningContent
  504. $aiResult = [
  505. 'content' => $result['fullContent'] ?? $result['content'] ?? '',
  506. 'reasoning_content' => $result['fullReasoningContent'] ?? $result['reasoning_content'] ?? '',
  507. 'usage' => $result['usage'] ?? [],
  508. 'model' => $model,
  509. 'finish_reason' => $result['finish_reason'] ?? 'stop'
  510. ];
  511. } else {
  512. Utils::throwError('20003:不支持的模型: ' . $model);
  513. }
  514. // 新增: 如果提供了script_id,保存对话记录
  515. if ($script_id > 0 && $aiResult) {
  516. try {
  517. $uid = Site::getUid();
  518. $now = now();
  519. // 获取用户原始的prompt(不包含剧本内容)
  520. $originalPrompt = getProp($data, 'prompt', '');
  521. $recordsToInsert = [
  522. [
  523. 'uid' => $uid,
  524. 'script_id' => $script_id,
  525. 'sequence' => $sequence,
  526. 'role' => 'user',
  527. 'content' => $originalPrompt,
  528. 'created_at' => $now,
  529. 'updated_at' => $now,
  530. ],
  531. [
  532. 'uid' => $uid,
  533. 'script_id' => $script_id,
  534. 'sequence' => $sequence,
  535. 'role' => 'assistant',
  536. 'content' => $aiResult['content'],
  537. 'created_at' => $now,
  538. 'updated_at' => $now,
  539. ]
  540. ];
  541. DB::table('mp_script_records')->insert($recordsToInsert);
  542. // 获取刚插入的记录ID(假设按插入顺序返回)
  543. $insertedRecords = DB::table('mp_script_records')
  544. ->where('uid', $uid)
  545. ->where('script_id', $script_id)
  546. ->where('sequence', $sequence)
  547. ->orderBy('id', 'desc')
  548. ->limit(2)
  549. ->get()
  550. ->map(function ($record) {
  551. return [
  552. 'rid' => $record->id,
  553. 'script_id' => $record->script_id,
  554. 'sequence' => $record->sequence,
  555. 'role' => $record->role,
  556. 'content' => $record->content,
  557. 'created_at' => $record->created_at,
  558. ];
  559. })
  560. ->reverse()
  561. ->values()
  562. ->toArray();
  563. // 将记录信息添加到返回结果中
  564. $aiResult['records'] = $insertedRecords;
  565. dLog('deepseek')->info('保存剧本对话记录成功', ['script_id' => $script_id, 'sequence' => $sequence, 'record_ids' => array_column($insertedRecords, 'rid')]);
  566. } catch (\Exception $e) {
  567. // 记录错误但不影响主流程
  568. dLog('deepseek')->error('保存剧本对话记录失败: ' . $e->getMessage());
  569. }
  570. }
  571. return $aiResult;
  572. }
  573. public function saveScriptChatHistory($data) {
  574. $uid = Site::getUid();
  575. $rid = getProp($data, 'rid');
  576. $script_id = getProp($data, 'script_id');
  577. $sequence = getProp($data, 'sequence', 0);
  578. $content = getProp($data, 'content');
  579. if (!$rid) {
  580. Utils::throwError('20003:请选择对话记录ID');
  581. }
  582. $record = DB::table('mp_script_records')->where('id', $rid)->first();
  583. if (!$record) {
  584. Utils::throwError('20003:对话记录不存在');
  585. }
  586. if (!$script_id) {
  587. Utils::throwError('20003:请选择剧本');
  588. }
  589. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->first();
  590. if (!$script) {
  591. Utils::throwError('20003:剧本不存在');
  592. }
  593. // 批量插入数据
  594. return DB::table('mp_script_records')->where('id', $rid)->update([
  595. 'content' => $content,
  596. 'updated_at' => date('Y-m-d H:i:s')
  597. ]);
  598. }
  599. /**
  600. * 获取剧本的历史对话记录
  601. *
  602. * @param array $data 请求参数
  603. * @return array 返回历史记录数组
  604. */
  605. public function getScriptChatHistory($data) {
  606. $uid = Site::getUid();
  607. $script_id = getProp($data, 'script_id');
  608. $rid = getProp($data, 'rid');
  609. $sequence = getProp($data, 'sequence', null);
  610. if (!$script_id) {
  611. Utils::throwError('20003:请提供剧本ID');
  612. }
  613. // 验证剧本是否存在
  614. $script = DB::table('mp_scripts')
  615. ->where('id', $script_id)
  616. ->where('is_deleted', 0)
  617. ->first();
  618. if (!$script) {
  619. Utils::throwError('20003:剧本不存在');
  620. }
  621. // 构建查询
  622. $query = DB::table('mp_script_records')
  623. ->where('script_id', $script_id);
  624. // ->where('uid', $uid);
  625. // 如果提供了 sequence,则过滤指定剧集
  626. if ($sequence !== null) {
  627. $query->where('sequence', $sequence);
  628. }
  629. // 记录ID筛选
  630. if ($rid) {
  631. $query->where('id', $rid);
  632. }
  633. // 查询记录并按 id 正序排序
  634. $records = $query->select('id', 'script_id', 'sequence', 'role', 'content', 'products', 'created_at')
  635. ->orderBy('created_at', 'asc')
  636. ->orderBy('id', 'asc')
  637. ->get()
  638. ->map(function ($record) {
  639. return [
  640. 'rid' => $record->id,
  641. 'script_id' => $record->script_id,
  642. 'sequence' => $record->sequence,
  643. 'role' => $record->role,
  644. 'content' => $record->content,
  645. 'products' => $record->products ? json_decode($record->products) : [],
  646. 'created_at' => $record->created_at,
  647. ];
  648. })
  649. ->toArray();
  650. return $records;
  651. }
  652. /**
  653. * 处理图片转换为base64
  654. *
  655. * @param mixed $image 图片文件对象或文件路径
  656. * @return string|null base64编码的图片数据
  657. */
  658. private function processImageToBase64($image) {
  659. try {
  660. // 获取文件路径
  661. if (is_string($image)) {
  662. $filePath = $image;
  663. } else {
  664. // Laravel UploadedFile 对象
  665. $filePath = $image->getRealPath();
  666. }
  667. if (!file_exists($filePath)) {
  668. dLog('deepseek')->warning('图片文件不存在', ['path' => $filePath]);
  669. return null;
  670. }
  671. // 验证是否为图片文件
  672. $imageInfo = @getimagesize($filePath);
  673. if ($imageInfo === false) {
  674. dLog('deepseek')->warning('无效的图片文件', ['path' => $filePath]);
  675. return null;
  676. }
  677. // 读取图片并转换为base64
  678. $imageData = file_get_contents($filePath);
  679. $base64Image = base64_encode($imageData);
  680. dLog('deepseek')->info('图片转换成功', [
  681. 'size' => strlen($imageData),
  682. 'type' => $imageInfo['mime']
  683. ]);
  684. return $base64Image;
  685. } catch (\Exception $e) {
  686. dLog('deepseek')->error('图片处理失败: ' . $e->getMessage());
  687. return null;
  688. }
  689. }
  690. private function getArtStylePromptMappings($art_style='')
  691. {
  692. $arr = [
  693. '唯美真人风格' => [
  694. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  695. 'prompt' => "唯美真人风格,电影级摄影,真实光影,高级质感,自然色彩,细节丰富,氛围感强,超高清,8K画质"
  696. ],
  697. '真人古风风格' => [
  698. 'aliases' => ['真人古风风格', '真人古风'],
  699. 'prompt' => "真人古风风格,东方古典美学,国风质感,古韵氛围,电影级摄影,精致细节,高级光影,超高清"
  700. ],
  701. '日系动漫风格' => [
  702. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  703. 'prompt' => "日系动漫风格,高质量二次元画风,精致线稿,细腻上色,动画电影质感,高细节,唯美光影"
  704. ],
  705. '国漫风格' => [
  706. 'aliases' => ['国漫风格', '国漫'],
  707. 'prompt' => "国漫风格,东方幻想美学,高品质角色设计,精致渲染,细腻刻画,电影级光影,高细节"
  708. ],
  709. 'Q版卡通风格' => [
  710. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  711. 'prompt' => "Q版卡通风格,可爱萌系画风,大头小身比例,圆润造型,鲜艳色彩,童趣氛围,高品质插画"
  712. ],
  713. '简约扁平风格' => [
  714. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  715. 'prompt' => "简约扁平风格,矢量插画,现代设计感,几何构图,简洁线条,干净配色,视觉清爽"
  716. ],
  717. '武侠风格' => [
  718. 'aliases' => ['武侠风格', '武侠'],
  719. 'prompt' => "武侠风格,东方江湖美学,侠义氛围,飘逸意境,大气构图,电影级光影,高细节绘制"
  720. ],
  721. '古风仙侠风格' => [
  722. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  723. 'prompt' => "古风仙侠风格,东方幻想美学,仙气缭绕,灵气氛围,梦幻光效,电影级渲染,高品质画面"
  724. ],
  725. '新中式水墨风格' => [
  726. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  727. 'prompt' => "新中式水墨风格,东方水墨美学,写意表达,墨韵渲染,留白构图,诗意氛围,高级艺术感"
  728. ],
  729. '写实插画风格' => [
  730. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  731. 'prompt' => "写实插画风格,数字绘画,真实质感,细节丰富,光影自然,电影感构图,高品质渲染"
  732. ],
  733. '3D卡通风格' => [
  734. 'aliases' => ['3D卡通风格', '3D卡通'],
  735. 'prompt' => "3D卡通风格,高品质三维渲染,动画电影质感,角色生动,色彩明快,细节丰富"
  736. ],
  737. '条漫风格' => [
  738. 'aliases' => ['条漫风格', '条漫'],
  739. 'prompt' => "条漫风格,韩漫质感,精致线稿,细腻上色,剧情感强,视觉表现突出,高质量绘制"
  740. ],
  741. '赛博朋克风格' => [
  742. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  743. 'prompt' => "赛博朋克风格,未来科技感,霓虹光效,高对比色彩,机械元素,科幻都市氛围,电影级渲染"
  744. ],
  745. '暗黑悬疑风格' => [
  746. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  747. 'prompt' => "暗黑悬疑风格,低饱和色调,神秘氛围,压抑光影,电影级灯光,悬念感强,高细节表现"
  748. ],
  749. '治愈清新风格' => [
  750. 'aliases' => ['治愈清新风格', '治愈清新'],
  751. 'prompt' => "治愈清新风格,温暖柔和色调,自然光线,清新配色,舒适氛围,细腻绘制,疗愈感十足"
  752. ],
  753. ];
  754. if($art_style) {
  755. return isset($arr[$art_style]) ? $arr[$art_style]['prompt'] : '';
  756. }
  757. return $arr;
  758. $arr = [
  759. '唯美真人风格' => [
  760. 'aliases' => ['唯美真人风格', '唯美真人', '唯美', '真人'],
  761. 'prompt' => "1,柔光漫射,侧颜光影,日落氛围感光线,室内温柔打光,自然天光,电影逆光,层次光影
  762. 2. 色彩色调
  763. 莫兰迪色系,低饱和柔色,高级清透配色,自然原生色彩,氛围感调色
  764. 3. 画质精度
  765. 8K超清,极致细节,质感通透,画面层次丰富,构图高级,商用影视级画质
  766. 4. 画面观感
  767. 意境唯美,氛围感拉满,镜头叙事感,自然真实不僵硬
  768. 专业全画幅相机拍摄,85mm/50mm定焦镜头,f1.4大光圈,极浅景深,背景柔和散景虚化
  769. 高清8K,RAW原片画质,超高细节,自然色彩还原,低饱和高级色调,电影级光影质感,真实透视,自然景深,生活化氛围感,镜头无畸变"
  770. ],
  771. '真人古风风格' => [
  772. 'aliases' => ['真人古风风格', '真人古风'],
  773. 'prompt' => "色彩沉稳典雅,配色和谐统一,明暗层次分明,画面质感细腻,整体画风统一协调,东方古典审美体系,非动漫非CG,原生真实皮肤肌理,保留皮肤毛孔与细微纹理,皮肤通透自然,不假面、无过度磨皮,原生流畅骨相,五官自然舒展,神态松弛生动,眼神灵动有情绪
  774. 传统古风造型,形制端正的古装汉服/古风侠客服/清雅古风常服,面料垂坠有质感,布料细腻纹理、刺绣暗纹清晰可见,发型古典雅致,发饰精致简约
  775. 柔和高级自然光,漫射柔光/清晨薄雾柔光/傍晚温润天光,光影层次细腻柔和,明暗过渡自然,氛围感光影勾勒轮廓
  776. 全画幅专业相机拍摄,85mm f1.4大光圈定焦镜头,浅景深,背景柔和虚化
  777. 8K超高清,RAW原片画质,真实透视,电影级光影色调,中式低饱和雅致配色,古风意境拉满,无AI失真,细节拉满"
  778. ],
  779. '日系动漫风格' => [
  780. 'aliases' => ['日系动漫风格', '日系动漫', '日系', '动漫', '日漫'],
  781. 'prompt' => "风格说明:经典二次元画风,线条干净、色彩明亮、人物精致柔和
  782. 正向提示词(中文)
  783. 日系动漫风格,线条清晰流畅,色彩明亮柔和,光影细腻,人物五官精致,整体二次元质感,画面干净清晰,风格统一稳定
  784. 必须遵守规则
  785. • 全程保持日系动漫风格,不混入其他画风
  786. • 角色形象、五官、发型、服饰前后统一,不崩脸、不变形
  787. • 画面适配所选画面比例,构图居中,主体突出
  788. • 线条干净、色彩统一,不杂乱、不突兀
  789. 禁止/避免词汇:水印、文字、logo、签名、模糊、低画质、畸形、多手、多脚、写实风格、水墨风格、3D 风格、杂乱背景、血腥、暴露、诡异表情"
  790. ],
  791. '国漫风格' => [
  792. 'aliases' => ['国漫风格', '国漫'],
  793. 'prompt' => "风格说明:中式动漫,线条硬朗,人物偏成熟,光影对比强
  794. 正向提示词(中文):国漫风格,线条硬朗有力,人物成熟大气,色彩浓郁,光影对比强烈,画面精致,整体风格统一
  795. 必须遵守规则
  796. • 严格保持国漫画风,不串风格、不混画风
  797. • 角色形象统一,不随意改变五官、身材、服饰
  798. • 画面构图稳定,适合漫剧叙事展示
  799. • 色调统一,不出现脏色、杂色
  800. 禁止/避免词汇
  801. 水印、文字、标题、模糊、低分辨率、Q版、日系萌系、水墨、扁平风、畸形、肢体错乱、血腥、低俗"
  802. ],
  803. 'Q版卡通风格' => [
  804. 'aliases' => ['Q版卡通风格', 'Q版卡通', 'Q版', '卡通'],
  805. 'prompt' => "风格说明
  806. 头大身小,造型可爱圆润,简约干净
  807. 正向提示词(中文)
  808. Q版卡通风格,头大身小,造型圆润可爱,线条简单,色彩明快干净,无复杂阴影,整体萌系简约
  809. 必须遵守规则
  810. • 全程保持Q版比例与风格,不突然变写实、变正常比例
  811. • 角色造型统一,表情可爱,不诡异
  812. • 画面简洁清爽,无多余复杂元素
  813. • 色彩明亮柔和,不刺眼
  814. 禁止/避免词汇
  815. 水印、文字、写实、成人向、恐怖、惊悚、畸形、复杂光影、杂乱背景、高饱和度刺眼颜色"
  816. ],
  817. '简约扁平风格' => [
  818. 'aliases' => ['简约扁平风格', '简约扁平', '扁平', '简约'],
  819. 'prompt' => "风格说明
  820. 色块简洁、无复杂渐变,现代极简风
  821. 正向提示词(中文)
  822. 简约扁平风格,大块纯色,无复杂阴影与渐变,线条简洁,现代简约,画面干净清爽
  823. 必须遵守规则
  824. • 严格保持扁平简约,不出现写实、厚涂、复杂光影
  825. • 构图简洁,主体突出,无多余装饰
  826. • 色彩统一、干净,不杂乱
  827. 禁止/避免词汇
  828. 水印、文字、复杂纹理、写实质感、3D效果、水墨、赛博朋克、凌乱线条、模糊、低画质"
  829. ],
  830. '武侠风格' => [
  831. 'aliases' => ['武侠风格', '武侠'],
  832. 'prompt' => "风格说明
  833. 江湖气息,线条硬朗,动作感强
  834. 正向提示词(中文)
  835. 武侠风格,中式古装,线条干练硬朗,江湖氛围浓厚,动态感强,色调沉稳大气
  836. 必须遵守规则
  837. • 保持武侠画风统一,不混入仙侠、卡通、科幻
  838. • 角色形象、服饰、身材比例统一
  839. • 画面动作自然,不扭曲、不畸形
  840. 禁止/避免词汇
  841. 水印、文字、Q版、萌系、仙侠仙气、赛博朋克、恐怖、血腥、低俗、模糊"
  842. ],
  843. '古风仙侠风格' => [
  844. 'aliases' => ['古风仙侠', '古风', '仙侠'],
  845. 'prompt' => "风格说明
  846. 飘逸汉服、云雾仙气、唯美空灵
  847. 正向提示词(中文)
  848. 古风仙侠风格,飘逸汉服,轻纱罗裙,云雾缭绕,仙气空灵,光影唯美柔和,色调清雅,国风仙侠氛围浓厚
  849. 必须遵守规则
  850. • 保持古风仙侠统一画风,不混入现代、科幻元素
  851. • 角色服饰、发型、形象前后一致
  852. • 场景仙气飘逸,色调清雅统一
  853. • 画面唯美柔和,不阴暗、不诡异
  854. 禁止/避免词汇
  855. 水印、文字、现代服饰、赛博朋克、写实恐怖、畸形、暴露、血腥、杂乱场景、低画质"
  856. ],
  857. '新中式水墨风格' => [
  858. 'aliases' => ['新中式水墨风格', '新中式', '水墨'],
  859. 'prompt' => "风格说明
  860. 淡墨渲染,毛笔笔触,留白意境
  861. 正向提示词(中文)
  862. 新中式水墨风格,淡墨渲染,毛笔笔触,留白意境,色调清雅,国风美学,画面简洁雅致
  863. 必须遵守规则
  864. • 严格保持水墨质感,不混入厚涂、写实、卡通
  865. • 色调淡雅统一,不浓艳杂乱
  866. • 画面干净有意境,不堆砌元素
  867. 禁止/避免词汇
  868. 水印、文字、高饱和色彩、赛博朋克、3D、Q版、写实厚涂、血腥、恐怖、杂乱"
  869. ],
  870. '写实插画风格' => [
  871. 'aliases' => ['写实插画风格', '写实插画', '写实', '插画'],
  872. 'prompt' => "风格说明
  873. 接近真人比例,光影真实,质感细腻
  874. 正向提示词(中文)
  875. 写实插画风格,真实人体比例,光影自然,皮肤质感细腻,画面真实,风格统一不卡通
  876. 必须遵守规则
  877. • 保持写实统一风格,不突然变卡通、变Q版、变水墨
  878. • 角色五官、身材、服饰高度统一
  879. • 画面清晰、光影自然、不扭曲
  880. 禁止/避免词汇
  881. 水印、文字、Q版、卡通、水墨、赛博朋克、畸形、多手指、肢体错乱、模糊、低画质"
  882. ],
  883. '3D卡通风格' => [
  884. 'aliases' => ['3D卡通风格', '3D卡通'],
  885. 'prompt' => "风格说明
  886. 3D建模质感,柔和渲染,圆润可爱
  887. 正向提示词(中文)
  888. 3D卡通风格,立体建模质感,渲染柔和,造型圆润光滑,光影干净,整体风格统一
  889. 必须遵守规则
  890. • 保持3D卡通统一质感,不出现2D杂乱线条
  891. • 角色模型、比例、形象前后一致
  892. • 画面干净,不模糊、不穿模
  893. 禁止/避免词汇
  894. 水印、文字、水墨、扁平风、写实恐怖、畸形、暴露、血腥、杂乱纹理"
  895. ],
  896. '条漫风格' => [
  897. 'aliases' => ['条漫风格', '条漫'],
  898. 'prompt' => "风格说明
  899. 纵向分镜,上下滑动阅读,轻量化
  900. 正向提示词(中文)
  901. 条漫风格,纵向分镜,布局简洁,色彩清淡,适合上下滑动阅读,整体轻量化、统一
  902. 必须遵守规则
  903. • 保持条漫纵向阅读逻辑,构图简洁
  904. • 画风统一,不混写实、3D、水墨
  905. • 画面干净,不杂乱
  906. 禁止/避免词汇
  907. 水印、文字、复杂光影、3D效果、赛博朋克、恐怖、血腥、杂乱背景"
  908. ],
  909. '赛博朋克风格' => [
  910. 'aliases' => ['赛博朋克风格', '赛博朋克'],
  911. 'prompt' => "风格说明
  912. 霓虹灯光、未来都市、暗色调、科技机械
  913. 正向提示词(中文)
  914. 赛博朋克风格,霓虹灯光,未来都市,暗色调,科技机械元素,高对比光影,风格统一强烈
  915. 必须遵守规则
  916. • 保持赛博朋克统一氛围,不混入古风、仙侠、水墨
  917. • 色调以暗调+霓虹为主,色彩统一
  918. • 画面科技感强,不杂乱
  919. 禁止/避免词汇
  920. 水印、文字、古风、仙侠、水墨、Q版、清新治愈、血腥过度、低俗"
  921. ],
  922. '暗黑悬疑风格' => [
  923. 'aliases' => ['暗黑悬疑风格', '暗黑悬疑'],
  924. 'prompt' => "风格说明
  925. 低饱和、冷色调、阴影重、神秘压抑
  926. 正向提示词(中文)
  927. 暗黑悬疑风格,低饱和度,冷色调,强阴影,光线昏暗,氛围神秘压抑,整体色调统一
  928. 必须遵守规则
  929. • 保持暗黑悬疑统一色调与氛围,不突然明亮清新
  930. • 画面氛围压抑神秘,但不低俗、不血腥
  931. • 角色形象统一,不崩坏
  932. 禁止/避免词汇
  933. 水印、文字、高饱和色彩、清新治愈、Q版、古风仙侠、过度血腥、恐怖猎奇"
  934. ],
  935. '治愈清新风格' => [
  936. 'aliases' => ['治愈清新风格', '治愈清新'],
  937. 'prompt' => "风格说明
  938. 马卡龙色系、柔光、温暖干净
  939. 正向提示词(中文)
  940. 治愈清新风格,马卡龙色系,柔光暖调,画面干净柔和,氛围温暖舒适,风格统一
  941. 必须遵守规则
  942. • 保持治愈清新统一色调,不阴暗、不诡异
  943. • 画面柔和干净,无杂乱元素
  944. • 角色形象柔和可爱,不狰狞
  945. 禁止/避免词汇
  946. 水印、文字、暗黑、恐怖、血腥、赛博朋克、高饱和刺眼色、畸形、杂乱"
  947. ],
  948. ];
  949. return $arr;
  950. }
  951. public function getArtStylePromptByInput($inputArtStyle): string
  952. {
  953. $normalizedInput = $this->normalizeArtStyleInput($inputArtStyle);
  954. if ($normalizedInput === '') {
  955. return '';
  956. }
  957. return $this->getArtStylePromptMappings($normalizedInput);
  958. // foreach ($this->getArtStylePromptMappings() as $mapping) {
  959. // foreach ($mapping['aliases'] as $alias) {
  960. // $normalizedAlias = $this->normalizeArtStyleInput($alias);
  961. // if ($normalizedAlias === '') {
  962. // continue;
  963. // }
  964. // if (strpos($normalizedInput, $normalizedAlias) !== false || strpos($normalizedAlias, $normalizedInput) !== false) {
  965. // return $mapping['prompt'];
  966. // }
  967. // }
  968. // }
  969. return '';
  970. }
  971. public function getArtStyleShortPromptByInput($inputArtStyle) {
  972. $stylePrefixes = [
  973. '唯美真人风格' => [
  974. 'character_prefix' => '唯美真人风格,电影级摄影,真实人物,高级质感,自然光影,肤质细腻,景深虚化,超高清,8K画质,情绪表达丰富',
  975. 'scene_prefix' => '唯美真人风格,电影感场景,真实环境,自然光影,高级色彩,细节丰富,超高清摄影,氛围感强'
  976. ],
  977. '真人古风风格' => [
  978. 'character_prefix' => '真人古风风格,东方古典美学,真实人物,古代服饰,精致妆容,电影级摄影,国风质感,超高清',
  979. 'scene_prefix' => '真人古风风格,东方建筑,古典园林,电影级光影,国风美学,真实场景,高细节,超高清'
  980. ],
  981. '日系动漫风格' => [
  982. 'character_prefix' => '日系动漫风格,二次元角色,精致线稿,高质量赛璐璐上色,细腻表情,动画电影质感,高细节',
  983. 'scene_prefix' => '日系动漫风格,动画电影场景,唯美背景,细腻光影,高质量绘制,色彩丰富,氛围感强'
  984. ],
  985. '国漫风格' => [
  986. 'character_prefix' => '国漫风格,高品质角色设计,东方审美,精致建模感,细腻刻画,动态表现强,电影级渲染',
  987. 'scene_prefix' => '国漫风格,东方幻想场景,精细绘制,大气构图,电影级光影,高品质渲染'
  988. ],
  989. 'Q版卡通风格' => [
  990. 'character_prefix' => 'Q版卡通风格,大头小身比例,可爱造型,圆润线条,丰富表情,萌系设计,高质量插画',
  991. 'scene_prefix' => 'Q版卡通风格,可爱场景,色彩鲜艳,童趣氛围,简洁细腻,绘本质感'
  992. ],
  993. '简约扁平风格' => [
  994. 'character_prefix' => '简约扁平风格,矢量插画,几何造型,简洁线条,干净配色,现代设计感',
  995. 'scene_prefix' => '简约扁平风格,矢量场景,几何构图,色彩简洁,现代感设计,视觉清爽'
  996. ],
  997. '武侠风格' => [
  998. 'character_prefix' => '武侠风格,东方侠客气质,江湖人物,飘逸服饰,凌厉气场,电影级光影,高细节绘制',
  999. 'scene_prefix' => '武侠风格,江湖场景,古道山林,客栈酒馆,刀光剑影,大气构图,东方美学'
  1000. ],
  1001. '古风仙侠风格' => [
  1002. 'character_prefix' => '古风仙侠风格,仙气飘逸,东方幻想角色,精致古装,灵气环绕,电影级特效,高品质渲染',
  1003. 'scene_prefix' => '古风仙侠风格,仙境场景,云海仙山,灵气缭绕,梦幻光效,东方幻想美学'
  1004. ],
  1005. '新中式水墨风格' => [
  1006. 'character_prefix' => '新中式水墨风格,国风写意,水墨晕染,留白艺术,东方韵味,诗意氛围,高级插画',
  1007. 'scene_prefix' => '新中式水墨风格,山水意境,墨韵渲染,留白构图,东方美学,诗意场景'
  1008. ],
  1009. '写实插画风格' => [
  1010. 'character_prefix' => '写实插画风格,半写实人物,细节丰富,真实比例,数字绘画,高质量渲染,电影级质感',
  1011. 'scene_prefix' => '写实插画风格,高细节环境,数字绘景,真实光影,层次丰富,电影感构图'
  1012. ],
  1013. '3D卡通风格' => [
  1014. 'character_prefix' => '3D卡通风格,高品质三维建模,皮克斯动画质感,表情生动,角色可爱,细腻渲染',
  1015. 'scene_prefix' => '3D卡通风格,动画电影场景,三维建模,色彩明快,光影柔和,高品质渲染'
  1016. ],
  1017. '条漫风格' => [
  1018. 'character_prefix' => '条漫风格,韩漫质感,精致线稿,人物颜值高,细腻上色,剧情漫画风,高质量绘制',
  1019. 'scene_prefix' => '条漫风格,漫画背景,剧情分镜感,细腻光影,现代漫画质感'
  1020. ],
  1021. '赛博朋克风格' => [
  1022. 'character_prefix' => '赛博朋克风格,未来科技感,机械义体,霓虹光效,高对比色彩,科幻都市氛围,电影级渲染',
  1023. 'scene_prefix' => '赛博朋克风格,未来都市,霓虹街道,全息广告,机械科技元素,夜景氛围,电影级光影'
  1024. ],
  1025. '暗黑悬疑风格' => [
  1026. 'character_prefix' => '暗黑悬疑风格,神秘压抑氛围,强烈明暗对比,电影级灯光,细腻刻画,悬疑感十足',
  1027. 'scene_prefix' => '暗黑悬疑风格,阴郁环境,低饱和色调,迷雾光影,神秘气氛,电影感构图'
  1028. ],
  1029. '治愈清新风格' => [
  1030. 'character_prefix' => '治愈清新风格,温暖柔和色调,干净画面,自然光线,亲和气质,轻松愉悦氛围,高品质插画',
  1031. 'scene_prefix' => '治愈清新风格,阳光明亮,自然环境,温暖色彩,舒适氛围,细腻绘制,疗愈感强'
  1032. ]
  1033. ];
  1034. return isset($stylePrefixes[$inputArtStyle]) ? $stylePrefixes[$inputArtStyle] : [];
  1035. }
  1036. private function normalizeArtStyleInput($value): string
  1037. {
  1038. $value = trim((string)$value);
  1039. if ($value === '') {
  1040. return '';
  1041. }
  1042. $value = str_replace(["\r", "\n", "\t", ' ', ' ', '-', '_', ':', ':', ',', ',', '。', '.'], '', $value);
  1043. return mb_strtolower($value, 'UTF-8');
  1044. }
  1045. private function replaceArtStyleSection(string $content, string $artStyle): string
  1046. {
  1047. if ($content === '' || $artStyle === '') {
  1048. return $content;
  1049. }
  1050. $pattern = '/###美术风格\s*\R(.*?)(?=\R###|$)/su';
  1051. if (!preg_match($pattern, $content)) {
  1052. return $content;
  1053. }
  1054. return preg_replace($pattern, "###美术风格\n" . trim($artStyle), $content, 1);
  1055. }
  1056. /**
  1057. * DeepSeek流式输出处理方法
  1058. *
  1059. * @param array $post_data DeepSeek API请求参数
  1060. * @return \Generator 返回生成器,用于流式输出
  1061. */
  1062. private function deepSeekStreamResponse($post_data) {
  1063. // 设置最大输出tokens
  1064. $post_data['max_tokens'] = 300000;
  1065. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1066. $response = $client->post($this->url, [
  1067. 'json' => $post_data,
  1068. 'headers' => $this->headers,
  1069. 'stream' => true // 启用流式响应
  1070. ]);
  1071. $body = $response->getBody();
  1072. $fullContent = '';
  1073. $fullReasoningContent = '';
  1074. $usage = [];
  1075. $buffer = '';
  1076. dLog('deepseek')->info('开始读取 DeepSeek 流式响应');
  1077. // 逐行读取流式响应
  1078. while (!$body->eof()) {
  1079. $chunk = $body->read(1024); // 每次读取 1KB
  1080. $buffer .= $chunk;
  1081. // 按行分割
  1082. $lines = explode("\n", $buffer);
  1083. // 保留最后一个不完整的行
  1084. $buffer = array_pop($lines);
  1085. foreach ($lines as $line) {
  1086. $line = trim($line);
  1087. // 跳过空行
  1088. if (empty($line)) {
  1089. continue;
  1090. }
  1091. // 检查是否是 SSE 数据行
  1092. if (strpos($line, 'data: ') !== 0) {
  1093. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1094. continue;
  1095. }
  1096. $data = substr($line, 6); // 移除 "data: " 前缀
  1097. if ($data === '[DONE]') {
  1098. dLog('deepseek')->info('收到结束标记');
  1099. break 2; // 跳出两层循环
  1100. }
  1101. try {
  1102. $json = json_decode($data, true);
  1103. if (json_last_error() !== JSON_ERROR_NONE) {
  1104. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1105. continue;
  1106. }
  1107. if (isset($json['choices'][0]['delta'])) {
  1108. $delta = $json['choices'][0]['delta'];
  1109. // 处理思维链内容(仅 deepseek-reasoner 模型)
  1110. if (isset($delta['reasoning_content'])) {
  1111. $fullReasoningContent .= $delta['reasoning_content'];
  1112. yield [
  1113. 'type' => 'reasoning',
  1114. 'content' => $delta['reasoning_content'],
  1115. 'full_reasoning' => $fullReasoningContent
  1116. ];
  1117. }
  1118. // 处理最终回答内容
  1119. if (isset($delta['content'])) {
  1120. $fullContent .= $delta['content'];
  1121. yield [
  1122. 'type' => 'content',
  1123. 'content' => $delta['content'],
  1124. ];
  1125. }
  1126. }
  1127. // 获取使用统计信息
  1128. if (isset($json['usage'])) {
  1129. $usage = $json['usage'];
  1130. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1131. }
  1132. } catch (\Exception $e) {
  1133. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1134. continue;
  1135. }
  1136. }
  1137. }
  1138. dLog('deepseek')->info('流式读取完成', [
  1139. 'content_length' => strlen($fullContent),
  1140. 'reasoning_length' => strlen($fullReasoningContent)
  1141. ]);
  1142. yield [
  1143. 'type' => 'done',
  1144. 'full_content' => $fullContent,
  1145. 'full_reasoning' => $fullReasoningContent,
  1146. 'usage' => $usage
  1147. ];
  1148. }
  1149. /**
  1150. * GPT 流式输出处理方法
  1151. *
  1152. * @param array $post_data GPT API请求参数
  1153. * @return \Generator 返回生成器,用于流式输出
  1154. */
  1155. private function gpt54StreamResponse($post_data) {
  1156. $apiKey = env('GPT_54_API_KEY');
  1157. if (empty($apiKey)) {
  1158. Utils::throwError('20003:GPT API Key未配置');
  1159. }
  1160. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1161. $headers = [
  1162. 'Authorization' => 'Bearer ' . $apiKey,
  1163. 'Content-Type' => 'application/json'
  1164. ];
  1165. // 移除 thinking 参数,GPT-5.4 不支持
  1166. if (isset($post_data['thinking'])) {
  1167. unset($post_data['thinking']);
  1168. }
  1169. if (isset($post_data['reasoning_effort'])) {
  1170. unset($post_data['reasoning_effort']);
  1171. }
  1172. $post_data['max_completion_tokens'] = 100000;
  1173. // 备用中转站地址1: https://token.ithinkai.cn/v1/chat/completions
  1174. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  1175. $response = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  1176. 'json' => $post_data,
  1177. 'headers' => $headers,
  1178. 'stream' => true // 启用流式响应
  1179. ]);
  1180. $body = $response->getBody();
  1181. $fullContent = '';
  1182. $usage = [];
  1183. $buffer = '';
  1184. dLog('deepseek')->info('开始读取 GPT 流式响应');
  1185. // 逐行读取流式响应
  1186. while (!$body->eof()) {
  1187. $chunk = $body->read(1024); // 每次读取 1KB
  1188. $buffer .= $chunk;
  1189. // 按行分割
  1190. $lines = explode("\n", $buffer);
  1191. // 保留最后一个不完整的行
  1192. $buffer = array_pop($lines);
  1193. foreach ($lines as $line) {
  1194. $line = trim($line);
  1195. // 跳过空行
  1196. if (empty($line)) {
  1197. continue;
  1198. }
  1199. // 检查是否是 SSE 数据行
  1200. if (strpos($line, 'data: ') !== 0) {
  1201. dLog('deepseek')->warning('非 SSE 数据行', ['line' => $line]);
  1202. continue;
  1203. }
  1204. $data = substr($line, 6); // 移除 "data: " 前缀
  1205. if ($data === '[DONE]') {
  1206. dLog('deepseek')->info('收到结束标记');
  1207. break 2; // 跳出两层循环
  1208. }
  1209. try {
  1210. $json = json_decode($data, true);
  1211. if (json_last_error() !== JSON_ERROR_NONE) {
  1212. dLog('deepseek')->warning('JSON 解析错误: ' . json_last_error_msg(), ['data' => $data]);
  1213. continue;
  1214. }
  1215. if (isset($json['choices'][0]['delta'])) {
  1216. $delta = $json['choices'][0]['delta'];
  1217. // 处理回答内容
  1218. if (isset($delta['content'])) {
  1219. $fullContent .= $delta['content'];
  1220. yield [
  1221. 'type' => 'content',
  1222. 'content' => $delta['content'],
  1223. ];
  1224. }
  1225. }
  1226. // 获取使用统计信息
  1227. if (isset($json['usage'])) {
  1228. $usage = $json['usage'];
  1229. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  1230. }
  1231. } catch (\Exception $e) {
  1232. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage(), ['line' => $line]);
  1233. continue;
  1234. }
  1235. }
  1236. }
  1237. dLog('deepseek')->info('流式读取完成', [
  1238. 'content_length' => strlen($fullContent)
  1239. ]);
  1240. yield [
  1241. 'type' => 'done',
  1242. 'full_content' => $fullContent,
  1243. 'full_reasoning' => '',
  1244. 'usage' => $usage
  1245. ];
  1246. }
  1247. // 与推理模型对话
  1248. public function chatWithReasoner($data) {
  1249. $content = getProp($data, 'content');
  1250. $model = getProp($data, 'model', 'r1');
  1251. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  1252. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  1253. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  1254. if ($model == 'r1') {
  1255. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  1256. $thinkingMode = 'disabled';
  1257. } else {
  1258. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  1259. $thinkingMode = 'disabled';
  1260. }
  1261. // 获取可选情感(根据音色可支持情感选)
  1262. $timbre_emotion = DB::table('mp_timbres')->where('is_enabled', 1)->pluck('emotion')->toArray();
  1263. $emotion_list = [];
  1264. foreach ($timbre_emotion as $emotion) {
  1265. $tmp = explode(',', $emotion);
  1266. $emotion_list = array_merge($emotion_list, $tmp);
  1267. }
  1268. $emotion_list = array_unique($emotion_list);
  1269. $emotion_str = implode('、', $emotion_list);
  1270. // // 获取可选情感
  1271. // $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->select('emotion_name')->orderBy('id')->get()->pluck('emotion_name')->toArray();
  1272. // $emotion_str = implode('、', $emotion_list);
  1273. // 是否启用情感
  1274. $enable_emotion = getProp($data, 'enable_emotion', 0);
  1275. if ($enable_emotion) {
  1276. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词{情感}”输出,需要注意以下几点要求:
  1277. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1278. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性
  1279. 3.情感必须在【{$emotion_str}】中选一个,不得使用其他词语";
  1280. }else {
  1281. $sys_content = "下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男、女、中性):台词”输出,需要注意以下几点要求:
  1282. 1.角色名后不要加入任何其他词语,只能加性别,在男、女或中性中选
  1283. 2.非对话部分请全部用旁白角色代替,旁白的情感统一选择中性";
  1284. }
  1285. $messages = [
  1286. [
  1287. 'role' => 'system',
  1288. 'content' => $sys_content
  1289. ],
  1290. [
  1291. 'role' => 'user',
  1292. 'content' => $content
  1293. ]
  1294. ];
  1295. $post_data = [
  1296. 'model' => $model,
  1297. 'messages' => $messages,
  1298. // 'max_tokens' => 8192,
  1299. 'temperature' => 1,
  1300. 'frequency_penalty' => 0,
  1301. 'presence_penalty' => 0,
  1302. 'thinking' => ['type' => $thinkingMode],
  1303. 'response_format' => [
  1304. 'type' => 'text'
  1305. ],
  1306. 'stream' => false
  1307. ];
  1308. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  1309. // 根据模型类型选择调用方法
  1310. $fullContent = '';
  1311. $usage = [];
  1312. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  1313. // DeepSeek 官方模型使用 DeepSeek API
  1314. $chatResult = $this->chatOnly($post_data);
  1315. } else if (in_array($model, $this->gpt_text_models)) {
  1316. // GPT-5.4 模型使用 TokenRouter API
  1317. $chatResult = $this->gpt54ChatOnly($post_data);
  1318. } else {
  1319. // 其他模型使用火山引擎API
  1320. $chatResult = $this->volcEngineChatCompletion($post_data);
  1321. }
  1322. if (is_array($chatResult)) {
  1323. $fullContent = $chatResult['fullContent'];
  1324. $usage = $chatResult['usage'];
  1325. }
  1326. // 处理获取到的剧本数据
  1327. $script_content = handleScriptWords($fullContent, $enable_emotion);
  1328. $result = [
  1329. 'origin_content' => $fullContent,
  1330. 'roles' => getProp($script_content, 'roles'),
  1331. 'words' => getProp($script_content, 'words'),
  1332. ];
  1333. return $result;
  1334. }
  1335. public function resetParagraphAudio($data) {
  1336. $bid = getProp($data, 'bid');
  1337. $cid = getProp($data, 'cid');
  1338. $version_id = getProp($data, 'version_id');
  1339. if (!DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->value('id')) return true;
  1340. return DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->update([
  1341. 'generate_status' => '待制作',
  1342. 'updated_at' => date('Y-m-d H:i:s')
  1343. ]);
  1344. }
  1345. public function saveParagraphAudio($data) {
  1346. $bid = getProp($data, 'bid');
  1347. $cid = getProp($data, 'cid');
  1348. $version_id = getProp($data, 'version_id');
  1349. $sequence = getProp($data, 'sequence');
  1350. $id = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->where('sequence', $sequence)->value('id');
  1351. // 获取所有情感
  1352. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1353. $emotion_list = array_flip($emotion_list);
  1354. // 获取音色支持情感
  1355. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', getProp($data, 'voice_type'))->value('emotion');
  1356. $timbre_emotion = explode(',', $timbre_emotion);
  1357. $emotion = getProp($data, 'emotion');
  1358. if (!in_array($emotion, $timbre_emotion)) $emotion = '中性';
  1359. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  1360. $list = [
  1361. 'bid' => $bid,
  1362. 'cid' => $cid,
  1363. 'version_id' => $version_id,
  1364. 'sequence' => $sequence,
  1365. 'role' => getProp($data, 'role'),
  1366. 'gender' => getProp($data, 'gender'),
  1367. 'text' => trim(getProp($data, 'text')),
  1368. 'emotion' => $emotion,
  1369. 'emotion_type' => $emotion_type,
  1370. 'voice_type' => getProp($data, 'voice_type'),
  1371. 'voice_name' => getProp($data, 'voice_name'),
  1372. 'speed_ratio' => getProp($data, 'speed_ratio', 0),
  1373. 'loudness_ratio'=> getProp($data, 'loudness_ratio', 0),
  1374. 'emotion_scale' => getProp($data, 'emotion_scale', 4),
  1375. 'pitch' => getProp($data, 'pitch', 0),
  1376. // 'paragraph_audio_url' => '',
  1377. 'generate_status' => '制作中',
  1378. 'error_msg' => '',
  1379. 'updated_at' => date('Y-m-d H:i:s')
  1380. ];
  1381. $continue = false;
  1382. // 判断是否含有中文、数字或英文,如果没有则跳过合成
  1383. if (!preg_match('/[\x{4e00}-\x{9fa5}]+/u', $list['text']) && !preg_match('/[0-9]+/', $list['text']) && !preg_match('/[a-zA-Z]+/', $list['text'])) {
  1384. $list['generate_status'] = '制作成功';
  1385. $list['paragraph_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/effects/ellipses_2s.mp3';
  1386. $list['subtitle_info'] = '{"duration": 2.0, "words": []}';
  1387. $continue = true;
  1388. }
  1389. // if (getProp($data, 'paragraph_audio_url')) $list['paragraph_audio_url'] = getProp($data, 'paragraph_audio_url');
  1390. if ($id) {
  1391. $boolen = DB::table('mp_chapter_paragraph_audios')->where('id', $id)->update($list);
  1392. }else {
  1393. $list['created_at'] = date('Y-m-d H:i:s');
  1394. $id = DB::table('mp_chapter_paragraph_audios')->insertGetId($list);
  1395. $boolen = $id ? true : false;
  1396. }
  1397. // 如果更新成功则加入查询队列
  1398. if ($boolen) {
  1399. $redis_key = "select-{$bid}-{$version_id}-{$cid}";
  1400. Redis::sadd($redis_key, $id);
  1401. }
  1402. if ($boolen && !$continue) {
  1403. $boolen = false;
  1404. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1405. // 根据ID通过API通知合成音频
  1406. // $result = $client->get("http://47.240.171.155:5000/api/previewTask?taskId={$id}");
  1407. $result = $client->get("http://122.9.129.83:5000/api/previewTask?taskId={$id}");
  1408. $response = $result->getBody()->getContents();
  1409. $response_arr = json_decode($response, true);
  1410. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1411. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1412. Log::info('通知火山生成段落音频失败: '.$error_msg);
  1413. Utils::throwError('20003:通知火山生成段落音频失败');
  1414. }
  1415. $boolen = true;
  1416. }
  1417. return $boolen;
  1418. }
  1419. public function insertAudioEffect($data) {
  1420. $audio_id = getProp($data, 'audio_id');
  1421. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1422. $bid = getProp($chapter_audio, 'bid');
  1423. $version_id = getProp($chapter_audio, 'version_id');
  1424. $cid = getProp($chapter_audio, 'cid');
  1425. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1426. $audio_effect_json = getProp($data, 'audio_effect_json');
  1427. if (!is_string($audio_effect_json)) $audio_effect_json = json_encode($audio_effect_json, 256);
  1428. try {
  1429. DB::beginTransaction();
  1430. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1431. if (!$count) {
  1432. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1433. }else {
  1434. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1435. }
  1436. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1437. 'audio_effect_status' => '添加中',
  1438. 'audio_effect_json' => $audio_effect_json,
  1439. 'updated_at' => date('Y-m-d H:i:s')
  1440. ]);
  1441. if (!$boolen1) {
  1442. DB::rollBack();
  1443. Utils::throwError('20003:更新生成数据失败');
  1444. }
  1445. $id = DB::table('mp_audio_tasks')->insertGetId([
  1446. 'audio_id' => $audio_id,
  1447. 'generate_status' => '执行中',
  1448. 'generate_json' => json_encode([], 256),
  1449. 'bid' => $bid,
  1450. 'book_name' => getProp($chapter_audio, 'book_name'),
  1451. 'version_id' => $version_id,
  1452. 'version_name' => getProp($chapter_audio, 'version_name'),
  1453. 'cid' => $cid,
  1454. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1455. 'task_name' => $task_name,
  1456. 'created_at' => date('Y-m-d H:i:s'),
  1457. 'updated_at' => date('Y-m-d H:i:s')
  1458. ]);
  1459. if (!$id) {
  1460. DB::rollBack();
  1461. Utils::throwError('20003:创建任务失败');
  1462. }
  1463. }catch (\Exception $e) {
  1464. DB::rollBack();
  1465. Utils::throwError('20003:'.$e->getMessage());
  1466. }
  1467. DB::commit();
  1468. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1469. // 根据ID通过API通知合成音频
  1470. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1471. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1472. $response = $result->getBody()->getContents();
  1473. $response_arr = json_decode($response, true);
  1474. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1475. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1476. Log::info('通知火山插入音效失败: '.$error_msg);
  1477. Utils::throwError('20003:通知火山插入音效失败');
  1478. }
  1479. return true;
  1480. }
  1481. public function insertBgm($data) {
  1482. $audio_id = getProp($data, 'audio_id');
  1483. $chapter_audio = DB::table('mp_chapter_audios')->where('id', $audio_id)->first();
  1484. $bid = getProp($chapter_audio, 'bid');
  1485. $version_id = getProp($chapter_audio, 'version_id');
  1486. $cid = getProp($chapter_audio, 'cid');
  1487. if (getProp($chapter_audio, 'generate_status') != '制作成功') Utils::throwError('20003:请先完成有声制作');
  1488. $bgm_json = getProp($data, 'bgm_json');
  1489. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1490. if (!$bgm_json) {
  1491. $bgm_json = getProp($data, 'audio_effect_json');
  1492. if (!is_string($bgm_json)) $bgm_json = json_encode($bgm_json, 256);
  1493. }
  1494. try {
  1495. DB::beginTransaction();
  1496. $count = DB::table('mp_audio_tasks')->where('audio_id', $audio_id)->count('id');
  1497. if (!$count) {
  1498. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1499. }else {
  1500. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1501. }
  1502. $boolen1 = DB::table('mp_chapter_audios')->where('id', $audio_id)->update([
  1503. 'bgm_status' => '添加中',
  1504. 'bgm_json' => $bgm_json,
  1505. 'updated_at' => date('Y-m-d H:i:s')
  1506. ]);
  1507. if (!$boolen1) {
  1508. DB::rollBack();
  1509. Utils::throwError('20003:更新生成数据失败');
  1510. }
  1511. $id = DB::table('mp_audio_tasks')->insertGetId([
  1512. 'audio_id' => $audio_id,
  1513. 'generate_status' => '执行中',
  1514. 'generate_json' => json_encode([], 256),
  1515. 'bid' => $bid,
  1516. 'book_name' => getProp($chapter_audio, 'book_name'),
  1517. 'version_id' => $version_id,
  1518. 'version_name' => getProp($chapter_audio, 'version_name'),
  1519. 'cid' => $cid,
  1520. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1521. 'task_name' => $task_name,
  1522. 'created_at' => date('Y-m-d H:i:s'),
  1523. 'updated_at' => date('Y-m-d H:i:s')
  1524. ]);
  1525. if (!$id) {
  1526. DB::rollBack();
  1527. Utils::throwError('20003:创建任务失败');
  1528. }
  1529. }catch (\Exception $e) {
  1530. DB::rollBack();
  1531. Utils::throwError('20003:'.$e->getMessage());
  1532. }
  1533. DB::commit();
  1534. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1535. // 根据ID通过API通知合成音频
  1536. // $result = $client->get("http://47.240.171.155:5000/api/postTask?taskId={$id}");
  1537. $result = $client->get("http://122.9.129.83:5000/api/postTask?taskId={$id}");
  1538. $response = $result->getBody()->getContents();
  1539. $response_arr = json_decode($response, true);
  1540. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1541. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1542. Log::info('通知火山插入bgm失败: '.$error_msg);
  1543. Utils::throwError('20003:通知火山插入bgm失败');
  1544. }
  1545. return true;
  1546. }
  1547. public function getParagraphAudios($data) {
  1548. $bid = getProp($data, 'bid');
  1549. $cid = getProp($data, 'cid');
  1550. $version_id = getProp($data, 'version_id');
  1551. $sequence = getProp($data, 'sequence');
  1552. // 获取已生成的音频
  1553. $query = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id);
  1554. if ($sequence) $query->where('sequence', $sequence);
  1555. $paragraph_audios = $query->orderBy('sequence')->get();
  1556. $result = [];
  1557. foreach($paragraph_audios as $item) {
  1558. $result[] = [
  1559. 'sequence' => getProp($item, 'sequence'),
  1560. 'role' => getProp($item, 'role'),
  1561. 'gender' => getProp($item, 'gender'),
  1562. 'text' => trim(getProp($item, 'text')),
  1563. 'emotion' => getProp($item, 'emotion'),
  1564. 'emotion_type' => getProp($item, 'emotion_type'),
  1565. 'voice_type' => getProp($item, 'voice_type'),
  1566. 'voice_name' => getProp($item, 'voice_name'),
  1567. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1568. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1569. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1570. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1571. 'subtitle_info' => json_decode(getProp($item, 'subtitle_info'), true),
  1572. ];
  1573. }
  1574. return $result;
  1575. }
  1576. // 新增合成任务
  1577. public function addGenerateTask($data) {
  1578. $bid = getProp($data, 'bid');
  1579. $cid = getProp($data, 'cid');
  1580. $version_id = getProp($data, 'version_id');
  1581. $generate_json = getProp($data, 'generate_json');
  1582. // 获取已生成的音频
  1583. $paragraph_audios = DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('cid', $cid)->where('version_id', $version_id)->get();
  1584. $paragraph_list = [];
  1585. foreach($paragraph_audios as $item) {
  1586. $paragraph_list[getProp($item, 'sequence')] = [
  1587. 'role' => getProp($item, 'role'),
  1588. 'gender' => getProp($item, 'gender'),
  1589. 'text' => trim(getProp($item, 'text')),
  1590. 'emotion' => getProp($item, 'emotion'),
  1591. 'emotion_type' => getProp($item, 'emotion_type'),
  1592. 'voice_type' => getProp($item, 'voice_type'),
  1593. 'voice_name' => getProp($item, 'voice_name'),
  1594. 'speed_ratio' => getProp($item, 'speed_ratio'),
  1595. 'loudness_ratio' => getProp($item, 'loudness_ratio'),
  1596. 'emotion_scale' => getProp($item, 'emotion_scale'),
  1597. 'paragraph_audio_url' => getProp($item, 'paragraph_audio_url'),
  1598. ];
  1599. }
  1600. // 更新角色-音色信息
  1601. $existed_role_info = DB::table('mp_book_version')->where('bid', $bid)->where('id', $version_id)->value('role_info');
  1602. $existed_role_info = json_decode($existed_role_info, true);
  1603. if (!$existed_role_info) $existed_role_info = [];
  1604. // 获取情感信息
  1605. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  1606. $emotion_list = array_flip($emotion_list);
  1607. // 获取音色对应情感组
  1608. $timbre_emotions = DB::table('mp_timbres')->where('is_enabled', 1)->select('timbre_type', 'emotion')->get();
  1609. $timbre_emotion_list = [];
  1610. foreach($timbre_emotions as $item) {
  1611. $timbre_emotion_list[getProp($item, 'timbre_type')] = explode(',', getProp($item, 'emotion'));
  1612. }
  1613. // 构造生成音频的json
  1614. $words = json_decode($generate_json, true);
  1615. // 最终合成前的参数组
  1616. $mp_chapter_paragraph_audios = [];
  1617. $sequence = 1;
  1618. $complete_paragraph_sequences = [];
  1619. foreach($words as &$word) {
  1620. 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:参数格式有误');
  1621. if (!($word['text']) || !($word['voice_type']) || !($word['voice_name'])) Utils::throwError('20003:参数不得为空');
  1622. $role = getProp($word, 'role');
  1623. $word['gender'] = (int)$word['gender'];
  1624. // 判断音色对应情感是否支持,不支持则调整为中性
  1625. $access_emotion = isset($timbre_emotion_list[$word['voice_type']]) ? $timbre_emotion_list[$word['voice_type']] : [];
  1626. if (!in_array($word['emotion'], $access_emotion)) $word['emotion'] = '中性';
  1627. // 如果有对应情感则赋值,没有则默认为中性(neutral)
  1628. if (isset($emotion_list[getProp($word, 'emotion')])) {
  1629. $word['emotion_type'] = $emotion_list[getProp($word, 'emotion')];
  1630. }else {
  1631. $word['emotion'] = '中性';
  1632. $word['emotion_type'] = 'neutral';
  1633. }
  1634. $existed_role_info[$role] = [
  1635. 'timbre_type' => $word['voice_type'],
  1636. 'timbre_name' => $word['voice_name'],
  1637. 'emotion' => $word['emotion'],
  1638. 'emotion_type' => $word['emotion_type'],
  1639. 'speed_ratio' => $word['speed_ratio'],
  1640. 'loudness_ratio'=> $word['loudness_ratio'],
  1641. 'emotion_scale' => $word['emotion_scale'],
  1642. 'pitch' => $word['pitch']
  1643. ];
  1644. $word['paragraph_audio_url'] = '';
  1645. // 判断生成参数是否相同,相同则直接使用已生成的音频
  1646. $paragraph = isset($paragraph_list[$sequence]) ? $paragraph_list[$sequence] : [];
  1647. // 如果音频存在并且参数都未改变则使用已生成的音频
  1648. if (getProp($paragraph, 'paragraph_audio_url')) {
  1649. // if (getProp($paragraph, 'role') == getProp($word, 'role') && getProp($paragraph, 'text') == getProp($word, 'text') &&
  1650. // getProp($paragraph, 'voice_type') == getProp($word, 'voice_type') &&
  1651. // getProp($paragraph, 'speed_ratio') == getProp($word, 'speed_ratio') && getProp($paragraph, 'loudness_ratio') == getProp($word, 'loudness_ratio') &&
  1652. // getProp($paragraph, 'emotion_scale') == getProp($word, 'emotion_scale'))
  1653. // {
  1654. // $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1655. // }
  1656. $word['paragraph_audio_url'] = getProp($paragraph, 'paragraph_audio_url');
  1657. }
  1658. $tmp = $word;
  1659. // 组装章节分句音频数据
  1660. // $tmp['sequence'] = getProp($word, 'sequence');
  1661. // $tmp['text'] = getProp($word, 'text');
  1662. // $tmp['emotion'] = getProp($word, 'emotion');
  1663. // $tmp['emotion_type'] = getProp($word, 'emotion_type');
  1664. // $tmp['voice_name'] = getProp($word, 'voice_name');
  1665. // $tmp['voice_type'] = getProp($word, 'voice_type');
  1666. // $tmp['speed_ratio'] = getProp($word, 'speed_ratio');
  1667. // $tmp['loudness_ratio'] = getProp($word, 'loudness_ratio');
  1668. // $tmp['emotion_scale'] = getProp($word, 'emotion_scale');
  1669. $tmp['bid'] = $bid;
  1670. $tmp['version_id'] = $version_id;
  1671. $tmp['cid'] = $cid;
  1672. $tmp['sequence'] = $sequence;
  1673. $tmp['created_at'] = date('Y-m-d H:i:s');
  1674. $tmp['updated_at'] = date('Y-m-d H:i:s');
  1675. if (!getProp($tmp, 'paragraph_audio_url')) Utils::throwError('20003:段落未生成音频,请等待完成后提交');
  1676. $mp_chapter_paragraph_audios[] = $tmp;
  1677. $complete_paragraph_sequences[] = $sequence;
  1678. $sequence++;
  1679. }
  1680. $generate_json = json_encode($words, 256);
  1681. // 判断是否有未生成字幕的段落
  1682. $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();
  1683. if ($no_subtitle_sequences) {
  1684. Utils::throwError('20003:请先将以下段落序号生成字幕('.implode('、', $no_subtitle_sequences).')');
  1685. }
  1686. try {
  1687. DB::beginTransaction();
  1688. $role_info = json_encode($existed_role_info, 256);
  1689. $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')]);
  1690. if (!$boolen) {
  1691. DB::rollBack();
  1692. Utils::throwError('20003:更新角色信息失败');
  1693. }
  1694. $count = DB::table('mp_audio_tasks')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->count('id');
  1695. $chapter_audio = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->first();
  1696. if (!$count) {
  1697. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】';
  1698. }else {
  1699. $task_name = getProp($chapter_audio, 'book_name').' '.getProp($chapter_audio, 'chapter_name').'【'.getProp($chapter_audio, 'version_name').'】('.($count+1).')';
  1700. }
  1701. $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')]);
  1702. if (!$boolen1) {
  1703. DB::rollBack();
  1704. Utils::throwError('20003:更新生成数据失败');
  1705. }
  1706. $id = DB::table('mp_audio_tasks')->insertGetId([
  1707. 'audio_id' => getProp($chapter_audio, 'id'),
  1708. 'generate_status' => '执行中',
  1709. 'generate_json' => $generate_json,
  1710. 'bid' => $bid,
  1711. 'book_name' => getProp($chapter_audio, 'book_name'),
  1712. 'version_id' => $version_id,
  1713. 'version_name' => getProp($chapter_audio, 'version_name'),
  1714. 'cid' => $cid,
  1715. 'chapter_name' => getProp($chapter_audio, 'chapter_name'),
  1716. 'task_name' => $task_name,
  1717. 'created_at' => date('Y-m-d H:i:s'),
  1718. 'updated_at' => date('Y-m-d H:i:s')
  1719. ]);
  1720. if (!$id) {
  1721. DB::rollBack();
  1722. Utils::throwError('20003:创建任务失败');
  1723. }
  1724. // 删除不在段落序号范围内的其他数据
  1725. if ($complete_paragraph_sequences) {
  1726. DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->whereNotIn('sequence', $complete_paragraph_sequences)->delete();
  1727. }
  1728. // // 删除章节分句音频数据并重新插入
  1729. // DB::table('mp_chapter_paragraph_audios')->where('bid', $bid)->where('version_id', $version_id)->where('cid', $cid)->delete();
  1730. // $boolen3 = DB::table('mp_chapter_paragraph_audios')->insert($mp_chapter_paragraph_audios);
  1731. // if (!$boolen3) {
  1732. // DB::rollBack();
  1733. // Utils::throwError('20003:更新章节分句音频失败');
  1734. // }
  1735. } catch (\Exception $e) {
  1736. DB::rollBack();
  1737. Utils::throwError('20003:'.$e->getMessage());
  1738. }
  1739. DB::commit();
  1740. // 通知火山生成音频
  1741. $client = new Client(['timeout' => 1800, 'verify' => false]);
  1742. // 根据ID通过API通知合成音频
  1743. // $result = $client->get("http://47.240.171.155:5000/api/chapterTask?taskId={$id}");
  1744. $result = $client->get("http://122.9.129.83:5000/api/chapterTask?taskId={$id}");
  1745. $response = $result->getBody()->getContents();
  1746. $response_arr = json_decode($response, true);
  1747. if (!isset($response_arr['code']) || (int)$response_arr['code'] !== 0) {
  1748. $error_msg = isset($response_arr['msg']) ? $response_arr['msg'] : '未知错误';
  1749. Log::info('通知火山生成音频失败: '.$error_msg);
  1750. Utils::throwError('20003:通知火山生成音频失败');
  1751. }
  1752. return true;
  1753. }
  1754. public function timbreList($data) {
  1755. $gender = getProp($data, 'gender');
  1756. $timbre_name = getProp($data, 'voice_name');
  1757. $category_id = getProp($data, 'category_id');
  1758. $age_stage = getProp($data, 'age_stage');
  1759. $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');
  1760. if ($gender) {
  1761. $query->where('gender', $gender);
  1762. }
  1763. if ($timbre_name) {
  1764. $query->where('timbre_name', 'like', "%{$timbre_name}%");
  1765. }
  1766. if ($category_id) {
  1767. $query->where(function ($query) use ($category_id) {
  1768. $query->where('first_category_id', $category_id)->orWhere('second_category_id', $category_id)->orWhere('third_category_id', $category_id);
  1769. });
  1770. }
  1771. if ($age_stage) {
  1772. $query->where('age_stage', $age_stage);
  1773. }
  1774. $list = $query->get()->map(function ($value) {
  1775. $value = (array)$value;
  1776. $value['voice_name'] = str_replace('(多情感)', '', $value['voice_name']);
  1777. return $value;
  1778. })->toArray();
  1779. return $list;
  1780. }
  1781. // 生成火山临时token
  1782. public function setStsToken() {
  1783. // ************* 配置参数 *************
  1784. $method = 'GET';
  1785. $service = 'sts';
  1786. $host = 'open.volcengineapi.com';
  1787. $region = env('VOLC_REGION');
  1788. $endpoint = 'https://open.volcengineapi.com';
  1789. // $endpoint = 'https://tos-cn-beijing.volces.com';
  1790. $access_key = env('VOLC_AK');
  1791. $secret_key = env('VOLC_SK');
  1792. // 获取缓存中的token,如果没有则请求接口
  1793. $token = Redis::get('volc_sts_token');
  1794. if (!$token) {
  1795. // 查询参数
  1796. $query_parameters = [
  1797. 'Action' => 'AssumeRole',
  1798. 'RoleSessionName' => 'user@zw',
  1799. 'RoleTrn' => 'trn:iam::2102575520:role/tos_role',
  1800. 'Version' => '2018-01-01'
  1801. ];
  1802. // 生成URL编码的查询字符串
  1803. $request_parameters = http_build_query($query_parameters, '', '&', PHP_QUERY_RFC3986);
  1804. // 获取签名头信息
  1805. $headers = $this->getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key);
  1806. // 构建完整URL
  1807. $request_url = $endpoint . '?' . $request_parameters;
  1808. $client = new Client(['verify' => false]);
  1809. $response = $client->get($request_url, ['headers' => $headers]);
  1810. $response_arr = json_decode($response->getBody()->getContents(), true);
  1811. $result = [
  1812. 'SessionToken' => isset($response_arr['Result']['Credentials']['SessionToken']) ? $response_arr['Result']['Credentials']['SessionToken'] : '',
  1813. 'AccessKeyId' => isset($response_arr['Result']['Credentials']['AccessKeyId']) ? $response_arr['Result']['Credentials']['AccessKeyId'] : '',
  1814. 'SecretAccessKey' => isset($response_arr['Result']['Credentials']['SecretAccessKey']) ? $response_arr['Result']['Credentials']['SecretAccessKey'] : '',
  1815. 'Region' => env('VOLC_REGION'),
  1816. 'Endpoint' => env('VOLC_END_POINT'),
  1817. 'Bucket' => env('VOLC_BUCKET'),
  1818. ];
  1819. // 缓存token
  1820. Redis::setex('volc_sts_token', 3000, json_encode($result));
  1821. return $result;
  1822. } else {
  1823. return json_decode($token, true);
  1824. }
  1825. // $response = $response['Response'];
  1826. // $access_key = $response['Credentials']['AccessKeyId'];
  1827. // $secret_key = $response['Credentials']['AccessKeySecret'];
  1828. // $security_token = $response['Credentials']['SecurityToken'];
  1829. // $expiration = $response['Credentials']['Expiration'];
  1830. // dd($response_arr);
  1831. }
  1832. public function emotionGroups($data) {
  1833. $id = getProp($data, 'group_id');
  1834. $group_name = getProp($data, 'group_name');
  1835. $voice_type = getProp($data, 'voice_type');
  1836. $query = DB::table('mp_emotion_groups')->where('is_enabled', 1)->select('id as group_id', 'group_name',
  1837. 'emotion', 'emotion_type', 'voice_name', 'voice_type', 'speed_ratio', 'loudness_ratio', 'emotion_scale',
  1838. 'pitch', 'generate_status', 'audio_url', 'error_msg');
  1839. if ($group_name) {
  1840. $query->where('group_name', 'like', "%{$group_name}%");
  1841. }
  1842. if ($id) {
  1843. $query->where('id', $id);
  1844. }
  1845. if ($voice_type) {
  1846. $query->where('voice_type', $voice_type);
  1847. }
  1848. return $query->orderBy('id')->get()->map(function ($value) {
  1849. return (array)$value;
  1850. })->toArray();
  1851. }
  1852. private function sign($key, $msg) {
  1853. return hash_hmac('sha256', $msg, $key, true);
  1854. }
  1855. // 生成签名密钥
  1856. private function getSignatureKey($key, $dateStamp, $regionName, $serviceName) {
  1857. $kDate = $this->sign($key, $dateStamp);
  1858. $kRegion = $this->sign($kDate, $regionName);
  1859. $kService = $this->sign($kRegion, $serviceName);
  1860. $kSigning = $this->sign($kService, 'request');
  1861. return $kSigning;
  1862. }
  1863. // 获取签名头信息
  1864. private function getSignHeaders($method, $service, $host, $region, $request_parameters, $access_key, $secret_key) {
  1865. $contenttype = 'application/x-www-form-urlencoded';
  1866. $accept = 'application/json';
  1867. // 获取当前UTC时间
  1868. $t = new DateTime('now', new DateTimeZone('UTC'));
  1869. $xdate = $t->format('Ymd\THis\Z');
  1870. $datestamp = $t->format('Ymd');
  1871. // 1. 拼接规范请求串
  1872. $canonical_uri = '/';
  1873. $canonical_querystring = $request_parameters;
  1874. $canonical_headers = "content-type:{$contenttype}\nhost:{$host}\nx-date:{$xdate}\n";
  1875. $signed_headers = 'content-type;host;x-date';
  1876. // 空请求体的SHA256哈希
  1877. $payload_hash = hash('sha256', '');
  1878. $canonical_request = implode("\n", [
  1879. $method,
  1880. $canonical_uri,
  1881. $canonical_querystring,
  1882. $canonical_headers,
  1883. $signed_headers,
  1884. $payload_hash
  1885. ]);
  1886. // 2. 拼接待签名字符串
  1887. $algorithm = 'HMAC-SHA256';
  1888. $credential_scope = implode('/', [$datestamp, $region, $service, 'request']);
  1889. $hashed_canonical_request = hash('sha256', $canonical_request);
  1890. $string_to_sign = implode("\n", [
  1891. $algorithm,
  1892. $xdate,
  1893. $credential_scope,
  1894. $hashed_canonical_request
  1895. ]);
  1896. // 3. 计算签名
  1897. $signing_key = $this->getSignatureKey($secret_key, $datestamp, $region, $service);
  1898. $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
  1899. // 4. 添加签名到请求头
  1900. $authorization_header = sprintf(
  1901. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  1902. $algorithm,
  1903. $access_key,
  1904. $credential_scope,
  1905. $signed_headers,
  1906. $signature
  1907. );
  1908. return [
  1909. 'Accept' => $accept,
  1910. 'Content-Type' => $contenttype,
  1911. 'X-Date' => $xdate,
  1912. 'Authorization' => $authorization_header
  1913. ];
  1914. }
  1915. // 文字合成语音(火山引擎)
  1916. public function tts($data) {
  1917. $url = 'https://openspeech.bytedance.com/api/v1/tts';
  1918. $headers = [
  1919. 'Authorization' => 'Bearer;'.env('VOLC_TOKEN'),
  1920. 'Content-Type' => 'application/json; charset=UTF-8'
  1921. ];
  1922. $post_data = [
  1923. 'app' => [
  1924. 'appid' => env('VOLC_APPID'),
  1925. 'token' => env('VOLC_TOKEN'),
  1926. 'cluster' => 'volcano_tts'
  1927. ],
  1928. 'user' => [
  1929. 'uid' => 'mp_audio'
  1930. ],
  1931. // 'audio' => [
  1932. // 'voice_type' =>
  1933. // ],
  1934. ];
  1935. }
  1936. public function scriptList($data) {
  1937. $uid = Site::getUid();
  1938. $script_id = getProp($data, 'script_id');
  1939. $script_name = getProp($data, 'script_name');
  1940. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('*');
  1941. if ($script_id) {
  1942. $query->where('id', $script_id);
  1943. }
  1944. if ($script_name) {
  1945. $query->where('script_name', 'like', "%{$script_name}%");
  1946. }
  1947. return $query->orderBy('created_at', 'desc')->paginate(12);
  1948. }
  1949. public function scripts($data) {
  1950. $uid = Site::getUid();
  1951. $script_id = getProp($data, 'script_id');
  1952. $script_name = getProp($data, 'script_name');
  1953. $query = DB::table('mp_scripts')->where('is_deleted', 0)->where('user_id', $uid)->select('id as script_id', 'script_name');
  1954. if ($script_id) {
  1955. $query->where('id', $script_id);
  1956. }
  1957. if ($script_name) {
  1958. $query->where('script_name', 'like', "%{$script_name}%");
  1959. }
  1960. return $query->orderBy('created_at', 'desc')->get()->map(function ($value) {
  1961. return (array)$value;
  1962. })->toArray();
  1963. }
  1964. public function scriptInfo($data) {
  1965. $uid = Site::getUid();
  1966. $script_id = getProp($data, 'script_id');
  1967. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)->where('user_id', $uid)
  1968. // ->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();
  1969. ->selectRaw('id as script_id, script_name')->first();
  1970. if (!$script) Utils::throwError('20003:该剧本不存在!');
  1971. $script = (array)$script;
  1972. // 获取分集组信息
  1973. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)
  1974. ->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')
  1975. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function ($value) {
  1976. $value = (array)$value;
  1977. $value['episode_content'] = mb_substr($value['episode_content'], 0, 200);
  1978. return (array)$value;
  1979. })->toArray();
  1980. $script['group'] = $groups;
  1981. return $script;
  1982. }
  1983. public function createScript($data) {
  1984. $script_name = getProp($data, 'script_name');
  1985. $uid = Site::getUid(); // 获取当前用户ID
  1986. $cpid = Site::getCpid(); // 获取当前公司组ID
  1987. if (!$script_name) Utils::throwError('20003:剧本名称不能为空');
  1988. if (DB::table('mp_scripts')->where('script_name', $script_name)->exists()) {
  1989. $script_name .= '_'.date('YmdHis');
  1990. }
  1991. return DB::table('mp_scripts')->insertGetId([
  1992. 'script_name' => $script_name,
  1993. 'user_id' => $uid,
  1994. 'cpid' => $cpid,
  1995. 'created_at' => date('Y-m-d H:i:s'),
  1996. 'updated_at' => date('Y-m-d H:i:s')
  1997. ]);
  1998. }
  1999. public function editScript($data) {
  2000. $script_id = getProp($data, 'script_id');
  2001. $script_name = getProp($data, 'script_name');
  2002. $uid = Site::getUid(); // 获取当前用户ID
  2003. if (!$script_id || !$script_name) Utils::throwError('20003:参数异常');
  2004. $id = DB::table('mp_scripts')->where('script_name', $script_name)->value('id');
  2005. if ($id && (int)$id !== (int)$script_id) {
  2006. $script_name .= '_'.date('YmdHis');
  2007. }
  2008. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2009. 'script_name' => $script_name,
  2010. 'updated_at' => date('Y-m-d H:i:s')
  2011. ]);
  2012. }
  2013. public function delScript($data) {
  2014. $script_id = getProp($data, 'script_id');
  2015. $uid = Site::getUid(); // 获取当前用户ID
  2016. if (!$script_id) Utils::throwError('20003:请选择剧本');
  2017. return DB::table('mp_scripts')->where('id', $script_id)->update([
  2018. 'is_deleted' => 1,
  2019. 'updated_at' => date('Y-m-d H:i:s')
  2020. ]);
  2021. }
  2022. public function createEpisode($data) {
  2023. $script_id = getProp($data, 'script_id');
  2024. $group_name = getProp($data, 'group_name');
  2025. $remark = getProp($data, 'remark');
  2026. if (!DB::table('mp_scripts')->where('id', $script_id)->value('id')) Utils::throwError('20003:剧本不存在!');
  2027. $uid = Site::getUid(); // 获取当前用户ID
  2028. if (!$group_name) Utils::throwError('20003:分集名称不能为空');
  2029. if (DB::table('mp_script_episode_group')->where('group_name', $group_name)->exists()) {
  2030. $group_name .= '_'.date('YmdHis');
  2031. }
  2032. return DB::table('mp_script_episode_group')->insertGetId([
  2033. 'script_id' => $script_id,
  2034. 'group_name' => $group_name,
  2035. 'user_id' => $uid,
  2036. 'remark' => $remark,
  2037. 'created_at' => date('Y-m-d H:i:s'),
  2038. 'updated_at' => date('Y-m-d H:i:s')
  2039. ]);
  2040. }
  2041. public function editEpisode($data) {
  2042. $group_id = getProp($data, 'group_id');
  2043. $start_episode_number = getProp($data, 'start_episode_number');
  2044. $end_episode_number = getProp($data, 'end_episode_number');
  2045. $group_name = getProp($data, 'group_name');
  2046. $uid = Site::getUid(); // 获取当前用户ID
  2047. if (!$group_id || !$group_name || !$start_episode_number || !$end_episode_number) Utils::throwError('20003:参数异常');
  2048. $id = DB::table('mp_script_episode_group')->where('group_name', $group_name)->value('id');
  2049. if ($id && (int)$id !== (int)$group_id) {
  2050. $group_name .= '_'.date('YmdHis');
  2051. }
  2052. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2053. 'group_name' => $group_name,
  2054. 'start_episode_number' => $start_episode_number,
  2055. 'end_episode_number' => $end_episode_number,
  2056. 'updated_at' => date('Y-m-d H:i:s')
  2057. ]);
  2058. }
  2059. public function delEpisode($data) {
  2060. $group_id = getProp($data, 'group_id');
  2061. $uid = Site::getUid(); // 获取当前用户ID
  2062. if (!$group_id) Utils::throwError('20003:请选择分集');
  2063. return DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2064. 'is_deleted' => 1,
  2065. 'updated_at' => date('Y-m-d H:i:s')
  2066. ]);
  2067. }
  2068. /**
  2069. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  2070. *
  2071. * @param array $data 包含以下参数:
  2072. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2073. * - question: 用户问题(可选)
  2074. * - model: 使用的模型(r1 或 v3,默认 v3)
  2075. * @return \Generator 返回生成器,用于流式输出
  2076. */
  2077. public function generateEpisodes($data) {
  2078. $script_id = getProp($data, 'script_id');
  2079. $group_id = getProp($data, 'group_id');
  2080. // $file = getProp($data, 'file');
  2081. $file = '';
  2082. $content = getProp($data, 'content', '');
  2083. // $bid = getProp($data, 'bid', 0);
  2084. $bid = 0;
  2085. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2086. if (!$group) {
  2087. Utils::throwError('20003:剧本分集不存在');
  2088. }
  2089. $start_episode_sequence = getProp($group, 'start_episode_number', 1);
  2090. $end_episode_sequence = getProp($group, 'end_episode_number', 30);
  2091. $total_episode_num = $end_episode_sequence - $start_episode_sequence + 1;
  2092. $prompt = getProp($data, 'prompt');
  2093. $question = getProp($data, 'question', "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。\n");
  2094. $model = getProp($data, 'model');
  2095. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2096. Utils::throwError('20003:该模型不存在!');
  2097. }
  2098. // 检查是否存在重叠的剧集序号范围
  2099. $exists_groups = DB::table('mp_script_episode_group')
  2100. ->where('script_id', $script_id)
  2101. ->where('id', '<>', $group_id) // 排除当前组
  2102. ->where('is_deleted', 0)
  2103. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2104. // 检查新范围是否与现有范围重叠
  2105. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2106. // 新范围的开始在现有范围内
  2107. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2108. ->where('end_episode_number', '>=', $start_episode_sequence);
  2109. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2110. // 新范围的结束在现有范围内
  2111. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2112. ->where('end_episode_number', '>=', $end_episode_sequence);
  2113. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2114. // 新范围完全包含现有范围
  2115. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2116. ->where('end_episode_number', '<=', $end_episode_sequence);
  2117. });
  2118. })
  2119. ->select('start_episode_number', 'end_episode_number')
  2120. ->get();
  2121. if ($exists_groups->isNotEmpty()) {
  2122. $conflict_ranges = [];
  2123. foreach ($exists_groups as $group) {
  2124. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2125. }
  2126. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2127. }
  2128. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2129. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2130. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2131. if ($model === 'deepseek-chat') {
  2132. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2133. $model = 'deepseek-v4-flash';
  2134. $thinkingMode = 'disabled';
  2135. } elseif ($model === 'deepseek-reasoner') {
  2136. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2137. $model = 'deepseek-v4-flash';
  2138. $thinkingMode = 'enabled';
  2139. }
  2140. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2141. if (!$script) {
  2142. Utils::throwError('20003:剧本不存在');
  2143. }
  2144. $content = getProp($group, 'content');
  2145. if (!$file && !$content && !$bid) {
  2146. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2147. }
  2148. // 提取文件内容
  2149. if ($file) {
  2150. $content = $this->extractFileContent($file);
  2151. if (!$content) {
  2152. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2153. }
  2154. } elseif ($bid) {
  2155. $content = $this->getContentByBid($bid);
  2156. if (!$content) {
  2157. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2158. }
  2159. } elseif ($content) {
  2160. $content = filterContent($content);
  2161. } elseif ($prompt) {
  2162. $content = filterContent($prompt);
  2163. } else {
  2164. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2165. }
  2166. // 构建消息
  2167. $messages = [
  2168. $this->sys_message,
  2169. [
  2170. 'role' => 'user',
  2171. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2172. ]
  2173. ];
  2174. $post_data = [
  2175. 'model' => $model,
  2176. 'messages' => $messages,
  2177. // 'max_tokens' => 8192,
  2178. 'temperature' => 0.7,
  2179. 'frequency_penalty' => 0,
  2180. 'presence_penalty' => 0,
  2181. 'thinking' => ['type' => $thinkingMode],
  2182. 'response_format' => ['type' => 'text'],
  2183. 'stream' => true
  2184. ];
  2185. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2186. // 根据模型类型选择调用方法
  2187. $fullContent = '';
  2188. $fullReasoningContent = '';
  2189. $usage = [];
  2190. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2191. // DeepSeek 官方模型使用 DeepSeek API
  2192. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2193. } else if (in_array($model, $this->gpt_text_models)) {
  2194. // GPT-5.4 模型使用 TokenRouter API
  2195. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2196. } else {
  2197. // 其他模型使用火山引擎API
  2198. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2199. }
  2200. // 处理流式输出
  2201. foreach ($streamGenerator as $chunk) {
  2202. if (isset($chunk['type'])) {
  2203. if ($chunk['type'] === 'done') {
  2204. // 最终结果
  2205. $fullContent = $chunk['full_content'];
  2206. $fullReasoningContent = $chunk['full_reasoning'];
  2207. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2208. } else {
  2209. // 逐块yield数据
  2210. yield $chunk;
  2211. }
  2212. }
  2213. }
  2214. dLog('deepseek')->info('完整内容: '.$fullContent);
  2215. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2216. // 处理完整内容并返回最终结果
  2217. $script_arr = [];
  2218. if ($fullContent) {
  2219. $script_arr = extractScriptContent($fullContent);
  2220. }
  2221. logDB('deepseek', 'info', '解析内容', $script_arr);
  2222. if (!$script_arr['episodes']) {
  2223. Utils::throwError('20003:未生成剧本相关信息');
  2224. // yield [
  2225. // 'type' => 'done',
  2226. // 'script' => $script_arr,
  2227. // 'msg' => '未生成剧本相关信息',
  2228. // 'answer' => $fullContent,
  2229. // 'reasoning' => $fullReasoningContent,
  2230. // 'usage' => $usage
  2231. // ];
  2232. // return ;
  2233. }
  2234. try {
  2235. DB::beginTransaction();
  2236. // // 返回前保存剧本内容
  2237. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2238. // 'content' => $content,
  2239. // 'updated_at' => date('Y-m-d H:i:s')
  2240. // ]);
  2241. // if (!$boolen) {
  2242. // Utils::throwError('20003:保存剧本内容失败');
  2243. // }
  2244. // $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2245. // 'start_episode_number' => $start_episode_sequence,
  2246. // 'end_episode_number' => $end_episode_sequence,
  2247. // 'updated_at' => date('Y-m-d H:i:s')
  2248. // ]);
  2249. // if (!$boolen1) {
  2250. // Utils::throwError('20003:保存分集失败');
  2251. // }
  2252. $episode_content = '';
  2253. $episodes = [];
  2254. foreach ($script_arr['episodes'] as $item) {
  2255. $episode_content .= "\u{200D}\u{200D}\u{200D}" . $item['episode_content'] . "\r\n\r\n";
  2256. // $episodes[] = [
  2257. // 'script_id' => $script_id,
  2258. // 'episode_number' => $item['episode_number'],
  2259. // 'episode_name' => $item['episode_name'],
  2260. // 'episode_content' => $item['episode_content'],
  2261. // 'created_at' => date('Y-m-d H:i:s'),
  2262. // 'updated_at' => date('Y-m-d H:i:s'),
  2263. // ];
  2264. }
  2265. if ($episode_content) {
  2266. $boolen2 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2267. 'episode_content' => $episode_content,
  2268. 'updated_at' => date('Y-m-d H:i:s')
  2269. ]);
  2270. if (!$boolen2) {
  2271. Utils::throwError('20003:保存分集内容失败');
  2272. }
  2273. }else {
  2274. Utils::throwError('20003:分集剧本解析失败');
  2275. }
  2276. }catch (\Exception $e) {
  2277. DB::rollBack();
  2278. Utils::throwError('20003:'.$e->getMessage());
  2279. }
  2280. DB::commit();
  2281. yield [
  2282. 'type' => 'done',
  2283. 'script' => $script_arr,
  2284. 'episode_content' => $episode_content,
  2285. 'answer' => $fullContent,
  2286. 'reasoning' => $fullReasoningContent,
  2287. 'usage' => $usage
  2288. ];
  2289. }
  2290. public function chatWithFileStream($data) {
  2291. $script_id = getProp($data, 'script_id');
  2292. $group_id = getProp($data, 'group_id');
  2293. $file = getProp($data, 'file');
  2294. $content = getProp($data, 'content', '');
  2295. $bid = getProp($data, 'bid', 0);
  2296. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2297. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2298. $end_episode_sequence = $start_episode_sequence + $total_episode_num - 1;
  2299. $prompt = getProp($data, 'prompt');
  2300. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.强制要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2301. if (!empty($prompt)) {
  2302. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2303. }
  2304. $question = getProp($data, 'question', $baseQuestion);
  2305. $model = getProp($data, 'model');
  2306. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->value('id')) {
  2307. Utils::throwError('20003:该模型不存在!');
  2308. }
  2309. // 检查是否存在重叠的剧集序号范围
  2310. $exists_groups = DB::table('mp_script_episode_group')
  2311. ->where('script_id', $script_id)
  2312. ->where('id', '<>', $group_id)
  2313. ->where('is_deleted', 0)
  2314. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2315. // 检查新范围是否与现有范围重叠
  2316. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2317. // 新范围的开始在现有范围内
  2318. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2319. ->where('end_episode_number', '>=', $start_episode_sequence);
  2320. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2321. // 新范围的结束在现有范围内
  2322. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2323. ->where('end_episode_number', '>=', $end_episode_sequence);
  2324. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2325. // 新范围完全包含现有范围
  2326. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2327. ->where('end_episode_number', '<=', $end_episode_sequence);
  2328. });
  2329. })
  2330. ->select('start_episode_number', 'end_episode_number')
  2331. ->get();
  2332. if ($exists_groups->isNotEmpty()) {
  2333. $conflict_ranges = [];
  2334. foreach ($exists_groups as $group) {
  2335. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2336. }
  2337. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2338. }
  2339. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2340. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2341. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2342. if ($model === 'deepseek-chat') {
  2343. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2344. $model = 'deepseek-v4-flash';
  2345. $thinkingMode = 'disabled';
  2346. } elseif ($model === 'deepseek-reasoner') {
  2347. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2348. $model = 'deepseek-v4-flash';
  2349. $thinkingMode = 'enabled';
  2350. }
  2351. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2352. if (!$script) {
  2353. Utils::throwError('20003:剧本不存在');
  2354. }
  2355. $group = DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->where('is_deleted', 0)->first();
  2356. if (!$group) {
  2357. Utils::throwError('20003:剧本分集不存在');
  2358. }
  2359. if (!$file && !$content && !$bid) {
  2360. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2361. }
  2362. // 提取文件内容
  2363. if ($file) {
  2364. $content = $this->extractFileContent($file);
  2365. if (!$content) {
  2366. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2367. }
  2368. } elseif ($bid) {
  2369. $content = $this->getContentByBid($bid);
  2370. if (!$content) {
  2371. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2372. }
  2373. } elseif ($content) {
  2374. $content = filterContent($content);
  2375. } elseif ($prompt) {
  2376. $content = filterContent($prompt);
  2377. } else {
  2378. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2379. }
  2380. // 构建消息
  2381. $messages = [
  2382. [
  2383. 'role' => 'system',
  2384. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  2385. 强制要求:\n
  2386. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  2387. 2.用户如果直接给了你一本小说或者要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  2388. 3.请严格按照示例格式返回内容,不要更改格式或随意增加符号\n
  2389. 普通要求:\n
  2390. 1.<主体列表>中出现的主体必须尽可能统一,只允许同一个角色年龄段相差较大的情况下可重复,比如梁萧-少年、梁萧-青年、梁萧-中年、梁萧-老年这种情况,不得出现梁萧-愤怒、梁萧-隐忍、梁萧-求生等情绪和状态变化的同一角色;并且角色的样貌、形体及穿着描述尽可能详细\n\n
  2391. 2.不要出现分集内容,只保留剧本大纲的格式,格式要求和示例如下,请强制按该示例输出
  2392. 3.分集序号可能不是从 1 开始,也可能是跳跃的(例如直接从第 3 集、第 5 集开始)。你只需要基于下面给出的“当前集内容要点”来创作这一集即可。
  2393. 4.不需要强行补齐前面未提供的集数,也不需要预测后面未提供的集数,但请保持本集内部故事的完整性和节奏。
  2394. 5.总集数将作为本季整体篇幅的参考,你可以根据它调整本集的情节推进速度(例如:如果总集数很少,本集应更紧凑;如果总集数很多,本集可以适当展开细节)
  2395. 示例如下:\n
  2396. ###剧本名:西昆仑
  2397. ###故事梗概
  2398. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2399. ###剧本亮点
  2400. 亮点1:绝境奇药,生死一线
  2401. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  2402. 亮点2:结拜兄妹,化解尴尬
  2403. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  2404. 亮点3:纤发夺命,情愫暗涌
  2405. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  2406. ###人物关系
  2407. 阿雪与梁萧之间存在兄妹之情。
  2408. ###核心矛盾
  2409. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  2410. ###主体列表
  2411. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。
  2412. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。
  2413. 阴阳球:天地异宝,能化生精气,救人于危难。
  2414. 问心刺:一根诡异的女子秀发,细长泛寒光,是致命的奇毒。
  2415. ###美术风格
  2416. 基础画风风格词:厚涂古风
  2417. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  2418. ###场景列表
  2419. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。"],
  2420. [
  2421. 'role' => 'user',
  2422. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2423. ]
  2424. ];
  2425. $post_data = [
  2426. 'model' => $model,
  2427. 'messages' => $messages,
  2428. // 'max_tokens' => 8192,
  2429. 'temperature' => 0.7,
  2430. 'frequency_penalty' => 0,
  2431. 'presence_penalty' => 0,
  2432. 'thinking' => ['type' => $thinkingMode],
  2433. 'response_format' => ['type' => 'text'],
  2434. 'stream' => true
  2435. ];
  2436. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2437. // 根据模型类型选择调用方法
  2438. $fullContent = '';
  2439. $fullReasoningContent = '';
  2440. $usage = [];
  2441. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2442. // DeepSeek 官方模型使用 DeepSeek API
  2443. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  2444. } else if (in_array($model, $this->gpt_text_models)) {
  2445. // GPT-5.4 模型使用 TokenRouter API
  2446. $streamGenerator = $this->gpt54StreamResponse($post_data);
  2447. } else {
  2448. // 其他模型使用火山引擎API
  2449. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  2450. }
  2451. // 处理流式输出
  2452. foreach ($streamGenerator as $chunk) {
  2453. if (isset($chunk['type'])) {
  2454. if ($chunk['type'] === 'done') {
  2455. // 最终结果
  2456. $fullContent = $chunk['full_content'];
  2457. $fullReasoningContent = $chunk['full_reasoning'];
  2458. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  2459. } else {
  2460. // 逐块yield数据
  2461. yield $chunk;
  2462. }
  2463. }
  2464. }
  2465. dLog('deepseek')->info('完整内容: '.$fullContent);
  2466. logDB('deepseek', 'info', '完整内容', ['fullContent'=>$fullContent]);
  2467. // 处理完整内容并返回最终结果
  2468. $script_arr = [];
  2469. if ($fullContent) {
  2470. $script_arr = extractScriptContent($fullContent);
  2471. }
  2472. logDB('deepseek', 'info', '解析内容', $script_arr);
  2473. if (!$script_arr['roles']) {
  2474. Utils::throwError('20003:未生成剧本相关信息');
  2475. // yield [
  2476. // 'type' => 'done',
  2477. // 'script' => $script_arr,
  2478. // 'msg' => '未生成剧本相关信息',
  2479. // 'answer' => $fullContent,
  2480. // 'reasoning' => $fullReasoningContent,
  2481. // 'usage' => $usage
  2482. // ];
  2483. }
  2484. try {
  2485. DB::beginTransaction();
  2486. // // 返回前保存剧本内容
  2487. // $boolen = DB::table('mp_scripts')->where('id', $script_id)->update([
  2488. // 'content' => $content,
  2489. // 'status' => '解析完成',
  2490. // 'updated_at' => date('Y-m-d H:i:s')
  2491. // ]);
  2492. // if (!$boolen) {
  2493. // Utils::throwError('20003:保存剧本内容失败');
  2494. // }
  2495. $boolen1 = DB::table('mp_script_episode_group')->where('id', $group_id)->update([
  2496. 'start_episode_number' => $start_episode_sequence,
  2497. 'end_episode_number' => $end_episode_sequence,
  2498. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2499. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2500. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2501. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2502. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2503. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2504. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2505. 'status' => '解析完成',
  2506. 'content' => $content,
  2507. 'updated_at' => date('Y-m-d H:i:s')
  2508. ]);
  2509. if (!$boolen1) {
  2510. Utils::throwError('20003:保存分集失败');
  2511. }
  2512. // $episodes = [];
  2513. // foreach ($script_arr['episodes'] as $item) {
  2514. // $episodes[] = [
  2515. // 'script_id' => $script_id,
  2516. // 'episode_number' => $item['episode_number'],
  2517. // 'episode_name' => $item['episode_name'],
  2518. // 'episode_content' => $item['episode_content'],
  2519. // 'created_at' => date('Y-m-d H:i:s'),
  2520. // 'updated_at' => date('Y-m-d H:i:s'),
  2521. // ];
  2522. // }
  2523. // if ($episodes) {
  2524. // $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2525. // if (!$boolen2) {
  2526. // Utils::throwError('20003:保存分集内容失败');
  2527. // }
  2528. // }else {
  2529. // Utils::throwError('20003:分集剧本解析失败');
  2530. // }
  2531. }catch (\Exception $e) {
  2532. DB::rollBack();
  2533. Utils::throwError('20003:'.$e->getMessage());
  2534. }
  2535. DB::commit();
  2536. yield [
  2537. 'type' => 'done',
  2538. 'script' => $script_arr,
  2539. 'answer' => $fullContent,
  2540. 'reasoning' => $fullReasoningContent,
  2541. 'usage' => $usage
  2542. ];
  2543. }
  2544. /**
  2545. * 上传文件识别文字内容并与 DeepSeek 进行对话
  2546. *
  2547. * @param array $data 包含以下参数:
  2548. * - file: 上传的文件(UploadedFile 对象)或文件路径
  2549. * - question: 用户问题(可选,默认为"请总结这个文件的内容")
  2550. * - model: 使用的模型(r1 或 v3,默认 v3)
  2551. * @return array
  2552. */
  2553. public function chatWithFile($data) {
  2554. $script_id = getProp($data, 'script_id');
  2555. $file = getProp($data, 'file');
  2556. $content = getProp($data, 'content', '');
  2557. $bid = getProp($data, 'bid', 0);
  2558. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2559. $total_episode_num = getProp($data, 'total_episode_num', 30);
  2560. $prompt = getProp($data, 'prompt');
  2561. $baseQuestion = "请根据实例完成一个{$total_episode_num}集的剧本,要求: 1.从第{$start_episode_sequence}集开始; 2.每集内容独立成章; 3.避免重复内容; 4.确保内容连贯且逻辑清晰; 5.所有章节合起来是给出的文档内容全文大概剧情。6.要求一定要给出我需要的分镜集数,不能少7.分集序号用01、02、03显示,不得使用01-1等子集序号,并且需要匹配开始集数的序号并往后顺序显示。";
  2562. if (!empty($prompt)) {
  2563. $baseQuestion .= "\n本次修改要求如下:\n{$prompt}";
  2564. }
  2565. $question = getProp($data, 'question', $baseQuestion);
  2566. // 处理文本模型
  2567. $model = getProp($data, 'model');
  2568. if (!$model) {
  2569. // 用户没有输入,使用默认值
  2570. $model = 'doubao-seed-2-0-mini-260215';
  2571. }
  2572. // 验证模型是否在可用模型表中
  2573. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  2574. $model = 'doubao-seed-2-0-mini-260215';
  2575. }
  2576. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  2577. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  2578. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  2579. if ($model === 'deepseek-chat') {
  2580. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  2581. $model = 'deepseek-v4-flash';
  2582. $thinkingMode = 'disabled';
  2583. } elseif ($model === 'deepseek-reasoner') {
  2584. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  2585. $model = 'deepseek-v4-flash';
  2586. $thinkingMode = 'enabled';
  2587. }
  2588. $script = DB::table('mp_scripts')->where('id', $script_id)->first();
  2589. if (!$script) {
  2590. Utils::throwError('20003:剧本不存在');
  2591. }
  2592. if (!$file && !$content && !$bid) {
  2593. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2594. }
  2595. // 提取文件内容
  2596. if ($file) {
  2597. $content = $this->extractFileContent($file);
  2598. if (!$content) {
  2599. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  2600. }
  2601. } elseif ($bid) {
  2602. $content = $this->getContentByBid($bid);
  2603. if (!$content) {
  2604. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  2605. }
  2606. } elseif ($content) {
  2607. $content = filterContent($content);
  2608. } elseif ($prompt) {
  2609. $content = filterContent($prompt);
  2610. } else {
  2611. Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  2612. }
  2613. // 构建消息
  2614. $messages = [
  2615. $this->sys_message,
  2616. [
  2617. 'role' => 'user',
  2618. 'content' => "以下是文档内容:\n\n{$content}\n\n用户问题:{$question}"
  2619. ]
  2620. ];
  2621. $post_data = [
  2622. 'model' => $model,
  2623. 'messages' => $messages,
  2624. // 'max_tokens' => 8192,
  2625. 'temperature' => 0.7,
  2626. 'frequency_penalty' => 0,
  2627. 'presence_penalty' => 0,
  2628. 'thinking' => ['type' => $thinkingMode],
  2629. 'response_format' => ['type' => 'text'],
  2630. 'stream' => false
  2631. ];
  2632. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  2633. // 根据模型类型选择调用方法
  2634. $fullContent = '';
  2635. $usage = [];
  2636. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  2637. // DeepSeek 官方模型使用 DeepSeek API
  2638. $chatResult = $this->chatOnly($post_data);
  2639. } else if (in_array($model, $this->gpt_text_models)) {
  2640. // GPT-5.4 模型使用 TokenRouter API
  2641. $chatResult = $this->gpt54ChatOnly($post_data);
  2642. } else {
  2643. // 其他模型使用火山引擎API
  2644. $chatResult = $this->volcEngineChatCompletion($post_data);
  2645. }
  2646. if (is_array($chatResult)) {
  2647. $fullContent = $chatResult['fullContent'];
  2648. $usage = $chatResult['usage'];
  2649. }
  2650. $script_arr = [];
  2651. // 处理结果
  2652. if ($fullContent) {
  2653. $script_arr = extractScriptContent($fullContent);
  2654. }
  2655. // 返回前保存剧本内容
  2656. DB::table('mp_scripts')->where('id', $script_id)->update([
  2657. 'content' => $content,
  2658. 'updated_at' => date('Y-m-d H:i:s')
  2659. ]);
  2660. return [
  2661. 'script' => $script_arr,
  2662. 'answer' => $fullContent,
  2663. 'usage' => $usage
  2664. ];
  2665. }
  2666. public function getEpisodeContent($data) {
  2667. $group_id = getProp($data, 'group_id');
  2668. return DB::table('mp_script_episode_group')->where('id', $group_id)->value('episode_content');
  2669. }
  2670. public function saveEpisodeContent($data) {
  2671. $script_id = getProp($data, 'script_id');
  2672. $group_id = getProp($data, 'group_id');
  2673. $start_episode_sequence = getProp($data, 'start_episode_number');
  2674. $end_episode_sequence = getProp($data, 'end_episode_number');
  2675. // 检查是否存在重叠的剧集序号范围
  2676. $exists_groups = DB::table('mp_script_episode_group')
  2677. ->where('script_id', $script_id)
  2678. ->where('id', '<>', $group_id) // 排除当前组
  2679. ->where('is_deleted', 0)
  2680. ->where(function($query) use ($start_episode_sequence, $end_episode_sequence) {
  2681. // 检查新范围是否与现有范围重叠
  2682. $query->where(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2683. // 新范围的开始在现有范围内
  2684. $q->where('start_episode_number', '<=', $start_episode_sequence)
  2685. ->where('end_episode_number', '>=', $start_episode_sequence);
  2686. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2687. // 新范围的结束在现有范围内
  2688. $q->where('start_episode_number', '<=', $end_episode_sequence)
  2689. ->where('end_episode_number', '>=', $end_episode_sequence);
  2690. })->orWhere(function($q) use ($start_episode_sequence, $end_episode_sequence) {
  2691. // 新范围完全包含现有范围
  2692. $q->where('start_episode_number', '>=', $start_episode_sequence)
  2693. ->where('end_episode_number', '<=', $end_episode_sequence);
  2694. });
  2695. })
  2696. ->select('start_episode_number', 'end_episode_number')
  2697. ->get();
  2698. if ($exists_groups->isNotEmpty()) {
  2699. $conflict_ranges = [];
  2700. foreach ($exists_groups as $group) {
  2701. $conflict_ranges[] = "第{$group->start_episode_number}-{$group->end_episode_number}集";
  2702. }
  2703. Utils::throwError('20003:剧集序号范围与已存在的剧集组重叠: '.implode('、', $conflict_ranges).',不得创建!');
  2704. }
  2705. $episode_content = getProp($data, 'episode_content');
  2706. return DB::table('mp_script_episode_group')->where('id', $group_id)->where('script_id', $script_id)->update([
  2707. 'content' => $episode_content,
  2708. 'start_episode_number' => $start_episode_sequence,
  2709. 'end_episode_number' => $end_episode_sequence,
  2710. 'updated_at' => date('Y-m-d H:i:s')
  2711. ]);
  2712. $script_arr =getProp($data, 'script', []);
  2713. if (!$script_arr) Utils::throwError('20003:剧本内容不能为空');
  2714. $start_episode_sequence = getProp($data, 'start_episode_sequence', 1);
  2715. $script_id = getProp($data, 'script_id');
  2716. if (!$script_id) Utils::throwError('20003:剧本ID不能为空');
  2717. try {
  2718. DB::beginTransaction();
  2719. $update_data = [
  2720. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  2721. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  2722. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  2723. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  2724. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  2725. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  2726. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  2727. 'status' => 3,
  2728. 'start_episode_sequence' => $start_episode_sequence,
  2729. 'end_episode_sequence' => $start_episode_sequence + count($script_arr['episodes']) - 1,
  2730. 'episode_num' => count($script_arr['episodes']),
  2731. 'updated_at' => date('Y-m-d H:i:s')
  2732. ];
  2733. // 保存剧本内容
  2734. $boolen = DB::table('mp_scripts')->where('id', $script_id)->update($update_data);
  2735. if (!$boolen) {
  2736. dLog('deepseek')->info('剧本内容保存失败', $update_data);
  2737. logDB('deepseek', 'error', '剧本内容保存失败', ['script_id' => $script_id]);
  2738. Utils::throwError('20003:剧本内容保存失败');
  2739. }
  2740. // 保存分集内容
  2741. // 删除历史分集内容
  2742. $boolen1 = DB::table('mp_script_episodes')->where('script_id', $script_id)->delete();
  2743. $episodes = [];
  2744. $sequence = 1;
  2745. foreach ($script_arr['episodes'] as $episode) {
  2746. $segment_number = 1;
  2747. foreach($episode['segments'] as $segment) {
  2748. $episodes[] = [
  2749. 'script_id' => $script_id,
  2750. 'episode_number' => $episode['episode_number'],
  2751. 'title' => $episode['title'],
  2752. // 'content' => $episode['content'],
  2753. 'content' => '',
  2754. 'segment_number' => $segment_number,
  2755. 'segment_content' => $segment['segment_content'],
  2756. 'sequence' => $sequence,
  2757. 'created_at' => date('Y-m-d H:i:s'),
  2758. 'updated_at' => date('Y-m-d H:i:s')
  2759. ];
  2760. $sequence++;
  2761. $segment_number++;
  2762. }
  2763. }
  2764. $boolen2 = DB::table('mp_script_episodes')->insert($episodes);
  2765. if (!$boolen2) {
  2766. dLog('deepseek')->info('分集内容保存失败', $episodes);
  2767. logDB('deepseek', 'error', '分集内容保存失败', ['episodes_count' => count($episodes)]);
  2768. Utils::throwError('20003:分集内容保存失败');
  2769. }
  2770. } catch (\Exception $e) {
  2771. DB::rollBack();
  2772. Utils::throwError('20003:'.$e->getMessage());
  2773. }
  2774. DB::commit();
  2775. return true;
  2776. }
  2777. public function getBookContent($data) {
  2778. $bid = getProp($data, 'bid');
  2779. $start_sequence = getProp($data, 'start_sequence');
  2780. $end_sequence = getProp($data, 'end_sequence');
  2781. $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])
  2782. ->orderBy('c.sequence')->pluck('cc.content')->toArray();
  2783. $return_content = filterContent(implode(PHP_EOL, $chapter_contents));
  2784. return $return_content;
  2785. }
  2786. public function exportScript($data) {
  2787. $filename = getProp($data, 'filename');
  2788. $script_id = getProp($data, 'script_id');
  2789. $group_id = getProp($data, 'group_id');
  2790. $script = DB::table('mp_scripts')->where('id', $script_id)->where('is_deleted', 0)
  2791. ->selectRaw('id as script_id, script_name, episode_num, remark, created_at')->first();
  2792. if (!$script) Utils::throwError('20003:该剧本不存在!');
  2793. $script = (array)$script;
  2794. // 获取分集组信息
  2795. if ($group_id) {
  2796. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('id', $group_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2797. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2798. ->get()->map(function($value) {
  2799. return (array)$value;
  2800. })->toArray();
  2801. }else {
  2802. $groups = DB::table('mp_script_episode_group')->where('script_id', $script_id)->where('is_deleted', 0)->whereNotNull('episode_content')
  2803. ->selectRaw('intro, highlights, roles, role_relationship, core_contradiction, art_style, scenes, status, start_episode_number, end_episode_number, episode_content')
  2804. ->orderBy('start_episode_number')->orderBy('id')->get()->map(function($value) {
  2805. return (array)$value;
  2806. })->toArray();
  2807. }
  2808. if (!$groups) Utils::throwError('20003:分集不存在');
  2809. $script['group'] = $groups;
  2810. $export_type = getProp($data, 'export_type', 'txt');
  2811. // 生成文件名
  2812. $filename = $filename ? $filename : $script['script_name'] . '_' . date('YmdHis');
  2813. // 根据导出类型生成不同格式的文件
  2814. switch ($export_type) {
  2815. case 'txt':
  2816. return $this->exportScriptAsTxt($script, $filename);
  2817. case 'pdf':
  2818. return $this->exportScriptAsPdf($script, $filename);
  2819. default:
  2820. Utils::throwError('20003:不支持的导出格式,支持:txt、pdf');
  2821. }
  2822. }
  2823. /**
  2824. * 导出剧本为TXT格式
  2825. */
  2826. private function exportScriptAsTxt($script, $filename) {
  2827. // 构建TXT内容
  2828. $content = $this->buildScriptContent($script);
  2829. // 设置响应头,直接下载
  2830. header('Content-Type: text/plain; charset=utf-8');
  2831. header('Content-Disposition: attachment; filename="' . $filename . '.txt"');
  2832. header('Content-Length: ' . strlen($content));
  2833. // 输出内容并结束
  2834. echo $content;
  2835. exit();
  2836. }
  2837. /**
  2838. * 导出剧本为PDF格式
  2839. */
  2840. private function exportScriptAsPdf($script, $filename) {
  2841. // 使用HTML转PDF的方式来更好地支持中文
  2842. $htmlContent = $this->buildScriptHtmlForPdf($script);
  2843. // 创建PDF实例
  2844. $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  2845. // 设置文档信息
  2846. $pdf->SetCreator('剧本导出系统');
  2847. $pdf->SetAuthor('系统');
  2848. $pdf->SetTitle($script['script_name']);
  2849. $pdf->SetSubject('剧本导出');
  2850. // 设置边距
  2851. $pdf->SetMargins(15, 15, 15);
  2852. $pdf->SetAutoPageBreak(TRUE, 15);
  2853. // 添加页面
  2854. $pdf->AddPage();
  2855. // 注册并使用 simsun.ttf 字体
  2856. $pdf->SetFont('simsun', '', 12); // 设置字体和大小
  2857. // 使用HTML内容生成PDF
  2858. $pdf->writeHTML($htmlContent, true, false, true, false, '');
  2859. // 直接输出PDF文件供下载
  2860. header('Content-Type: application/pdf');
  2861. header('Content-Disposition: attachment; filename="' . $filename . '.pdf"');
  2862. // 直接输出PDF内容
  2863. $pdf->Output($filename . '.pdf', 'D');
  2864. exit();
  2865. }
  2866. /**
  2867. * 构建用于PDF的HTML内容
  2868. */
  2869. private function buildScriptHtmlForPdf($script) {
  2870. $html = '<style>
  2871. body { font-family: "SimSun", "宋体", sans-serif; font-size: 12px; line-height: 1.6; }
  2872. h1 { font-size: 18px; text-align: center; margin-bottom: 20px; }
  2873. h2 { font-size: 16px; margin-top: 20px; margin-bottom: 10px; border-bottom: 1px solid #ccc; }
  2874. h3 { font-size: 14px; margin-top: 15px; margin-bottom: 8px; }
  2875. .info { margin-bottom: 8px; }
  2876. .group { margin-bottom: 30px; page-break-inside: avoid; }
  2877. .group-header { text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 20px; border-bottom: 1px solid #333; padding: 10px; }
  2878. .segment { margin-bottom: 10px; margin-left: 20px; }
  2879. .episode-content { white-space: pre-wrap; }
  2880. </style>';
  2881. // 标题
  2882. $html .= '<h1>' . htmlspecialchars($script['script_name']) . '</h1>';
  2883. // 处理分组数据
  2884. if (!empty($script['group']) && is_array($script['group'])) {
  2885. $groups = (array)$script['group'];
  2886. foreach ($groups as $group) {
  2887. $html .= '<div class="group">';
  2888. // 分组标题
  2889. $groupTitle = '第' . $group['start_episode_number'] . '-' . $group['end_episode_number'] . '集';
  2890. $html .= '<div class="group-header">' . htmlspecialchars($groupTitle) . '</div>';
  2891. // 故事梗概
  2892. if (!empty($group['intro'])) {
  2893. $html .= '<h3>故事梗概</h3>';
  2894. $html .= '<p>' . nl2br(htmlspecialchars($group['intro'])) . '</p>';
  2895. }
  2896. // 剧本亮点
  2897. if (!empty($group['highlights'])) {
  2898. $html .= '<h3>剧本亮点</h3>';
  2899. $html .= '<p>' . nl2br(htmlspecialchars($group['highlights'])) . '</p>';
  2900. }
  2901. // 人物关系
  2902. if (!empty($group['role_relationship'])) {
  2903. $html .= '<h3>人物关系</h3>';
  2904. $html .= '<p>' . nl2br(htmlspecialchars($group['role_relationship'])) . '</p>';
  2905. }
  2906. // 核心矛盾
  2907. if (!empty($group['core_contradiction'])) {
  2908. $html .= '<h3>核心矛盾</h3>';
  2909. $html .= '<p>' . nl2br(htmlspecialchars($group['core_contradiction'])) . '</p>';
  2910. }
  2911. // 主体列表
  2912. if (!empty($group['roles']) && is_array($group['roles'])) {
  2913. $html .= '<h3>主体列表</h3>';
  2914. $html .= '<ul>';
  2915. foreach ($group['roles'] as $role) {
  2916. $html .= '<li>' . htmlspecialchars(getProp($role, 'role')) . ':' . htmlspecialchars(getProp($role, 'description')) . '</li>';
  2917. }
  2918. $html .= '</ul>';
  2919. }
  2920. // 美术风格
  2921. if (!empty($group['art_style'])) {
  2922. $html .= '<h3>美术风格</h3>';
  2923. $html .= '<p>' . nl2br(htmlspecialchars($group['art_style'])) . '</p>';
  2924. }
  2925. // 场景列表
  2926. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  2927. $html .= '<h3>场景列表</h3>';
  2928. $html .= '<ul>';
  2929. foreach ($group['scenes'] as $scene) {
  2930. $html .= '<li>' . htmlspecialchars(getProp($scene, 'scene')) . ':' . htmlspecialchars(getProp($scene, 'description')) . '</li>';
  2931. }
  2932. $html .= '</ul>';
  2933. }
  2934. // 分集剧本
  2935. if (!empty($group['episode_content'])) {
  2936. $html .= '<h3>分集剧本</h3>';
  2937. // 去除零宽字符和其他不可见字符
  2938. $cleanContent = preg_replace('/[\x{200B}-\x{200D}\x{FEFF}]/u', '', $group['episode_content']);
  2939. $cleanContent = preg_replace('/[\x{00}-\x{08}\x{0B}\x{0C}\x{0E}-\x{1F}\x{7F}]/u', '', $cleanContent);
  2940. $html .= '<div class="episode-content">' . nl2br(htmlspecialchars($cleanContent)) . '</div>';
  2941. }
  2942. $html .= '</div>';
  2943. }
  2944. }
  2945. return $html;
  2946. }
  2947. /**
  2948. * 构建PDF内容
  2949. */
  2950. private function buildPdfContent($pdf, $script) {
  2951. // 标题
  2952. $pdf->SetFont('dejavusans', 'B', 18);
  2953. $pdf->Cell(0, 15, $script['script_name'], 0, 1, 'C');
  2954. $pdf->Ln(5);
  2955. // 基本信息
  2956. $pdf->SetFont('dejavusans', '', 12);
  2957. $pdf->Cell(0, 8, '创建时间:' . $script['created_at'], 0, 1);
  2958. $pdf->Cell(0, 8, '状态:' . $script['status_info'], 0, 1);
  2959. $pdf->Ln(5);
  2960. // 剧本简介
  2961. if (!empty($script['intro'])) {
  2962. $pdf->SetFont('dejavusans', 'B', 14);
  2963. $pdf->Cell(0, 10, '剧本简介', 0, 1);
  2964. $pdf->SetFont('dejavusans', '', 12);
  2965. $pdf->MultiCell(0, 8, $script['intro'], 0, 'L');
  2966. $pdf->Ln(3);
  2967. }
  2968. // 亮点
  2969. if (!empty($script['highlights'])) {
  2970. $pdf->SetFont('dejavusans', 'B', 14);
  2971. $pdf->Cell(0, 10, '亮点', 0, 1);
  2972. $pdf->SetFont('dejavusans', '', 12);
  2973. $pdf->MultiCell(0, 8, $script['highlights'], 0, 'L');
  2974. $pdf->Ln(3);
  2975. }
  2976. // 核心矛盾
  2977. if (!empty($script['core_contradiction'])) {
  2978. $pdf->SetFont('dejavusans', 'B', 14);
  2979. $pdf->Cell(0, 10, '核心矛盾', 0, 1);
  2980. $pdf->SetFont('dejavusans', '', 12);
  2981. $pdf->MultiCell(0, 8, $script['core_contradiction'], 0, 'L');
  2982. $pdf->Ln(3);
  2983. }
  2984. // 艺术风格
  2985. if (!empty($script['art_style'])) {
  2986. $pdf->SetFont('dejavusans', 'B', 14);
  2987. $pdf->Cell(0, 10, '艺术风格', 0, 1);
  2988. $pdf->SetFont('dejavusans', '', 12);
  2989. $pdf->MultiCell(0, 8, $script['art_style'], 0, 'L');
  2990. $pdf->Ln(3);
  2991. }
  2992. // 备注
  2993. if (!empty($script['remark'])) {
  2994. $pdf->SetFont('dejavusans', 'B', 14);
  2995. $pdf->Cell(0, 10, '备注', 0, 1);
  2996. $pdf->SetFont('dejavusans', '', 12);
  2997. $pdf->MultiCell(0, 8, $script['remark'], 0, 'L');
  2998. $pdf->Ln(3);
  2999. }
  3000. // 角色列表
  3001. if (!empty($script['roles']) && is_array($script['roles'])) {
  3002. $pdf->SetFont('dejavusans', 'B', 14);
  3003. $pdf->Cell(0, 10, '角色列表', 0, 1);
  3004. $pdf->SetFont('dejavusans', '', 12);
  3005. foreach ($script['roles'] as $index => $role) {
  3006. if (is_array($role) || is_object($role)) {
  3007. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($role, 'role', '') . ':' . getProp($role, 'description', ''), 0, 1);
  3008. } else {
  3009. $pdf->Cell(0, 8, ($index + 1) . '. ' . $role, 0, 1);
  3010. }
  3011. }
  3012. $pdf->Ln(3);
  3013. }
  3014. // 角色关系
  3015. if (!empty($script['role_relationship'])) {
  3016. $pdf->SetFont('dejavusans', 'B', 14);
  3017. $pdf->Cell(0, 10, '角色关系', 0, 1);
  3018. $pdf->SetFont('dejavusans', '', 12);
  3019. $pdf->MultiCell(0, 8, $script['role_relationship'], 0, 'L');
  3020. $pdf->Ln(3);
  3021. }
  3022. // 场景列表
  3023. if (!empty($script['scenes']) && is_array($script['scenes'])) {
  3024. $pdf->SetFont('dejavusans', 'B', 14);
  3025. $pdf->Cell(0, 10, '场景列表', 0, 1);
  3026. $pdf->SetFont('dejavusans', '', 12);
  3027. foreach ($script['scenes'] as $index => $scene) {
  3028. if (is_array($scene) || is_object($scene)) {
  3029. $pdf->Cell(0, 8, ($index + 1) . '. ' . getProp($scene, 'scene', '') . ':' . getProp($scene, 'description', ''), 0, 1);
  3030. } else {
  3031. $pdf->Cell(0, 8, ($index + 1) . '. ' . $scene, 0, 1);
  3032. }
  3033. }
  3034. $pdf->Ln(5);
  3035. }
  3036. // 分集内容
  3037. if (!empty($script['episodes']) && is_array($script['episodes'])) {
  3038. $pdf->SetFont('dejavusans', 'B', 16);
  3039. $pdf->Cell(0, 12, '分集内容', 0, 1);
  3040. $pdf->Ln(3);
  3041. foreach ($script['episodes'] as $episode) {
  3042. // 检查是否需要新页面
  3043. if ($pdf->GetY() > 250) {
  3044. $pdf->AddPage();
  3045. }
  3046. $pdf->SetFont('dejavusans', 'B', 14);
  3047. $episodeTitle = '第' . $episode['episode_number'] . '集';
  3048. if (!empty($episode['title'])) {
  3049. $episodeTitle .= ':' . $episode['title'];
  3050. }
  3051. $pdf->Cell(0, 10, $episodeTitle, 0, 1);
  3052. // 处理分段内容
  3053. if (!empty($episode['segments']) && is_array($episode['segments'])) {
  3054. $pdf->SetFont('dejavusans', '', 12);
  3055. foreach ($episode['segments'] as $segment) {
  3056. if (!empty($segment['segment_content'])) {
  3057. // 如果有分段编号,显示分段标题
  3058. if (!empty($segment['segment_number'])) {
  3059. $pdf->SetFont('dejavusans', 'B', 12);
  3060. $pdf->Cell(0, 8, '第' . $segment['segment_number'] . '段', 0, 1);
  3061. $pdf->SetFont('dejavusans', '', 12);
  3062. }
  3063. $pdf->MultiCell(0, 8, $segment['segment_content'], 0, 'L');
  3064. $pdf->Ln(2);
  3065. }
  3066. }
  3067. }
  3068. $pdf->Ln(5);
  3069. }
  3070. }
  3071. }
  3072. /**
  3073. * 构建剧本文本内容
  3074. */
  3075. private function buildScriptContent($script) {
  3076. $content = '';
  3077. $groups = $script['group'];
  3078. $groups = (array)$groups;
  3079. foreach ($groups as $group) {
  3080. $content .= str_repeat('→', 40).' 第'.$group['start_episode_number'].'-'.$group['end_episode_number']."集 ".str_repeat('←', 40)."\n\n";
  3081. // 剧本基本信息
  3082. if (!empty($group['intro'])) {
  3083. $content .= "###故事梗概\n" . $group['intro'] . "\n\n";
  3084. }
  3085. if (!empty($group['highlights'])) {
  3086. $content .= "###剧本亮点\n" . $group['highlights'] . "\n\n";
  3087. }
  3088. if (!empty($group['role_relationship'])) {
  3089. $content .= "###人物关系\n" . $group['role_relationship'] . "\n\n";
  3090. }
  3091. if (!empty($group['core_contradiction'])) {
  3092. $content .= "###核心矛盾\n" . $group['core_contradiction'] . "\n\n";
  3093. }
  3094. if (!empty($group['roles']) && is_array($group['roles'])) {
  3095. $content .= "###主体列表\n";
  3096. foreach ($group['roles'] as $role) {
  3097. $content .= getProp($role, 'role') . ":" . getProp($role, 'description') . "\n";
  3098. }
  3099. $content .= "\n\n";
  3100. }
  3101. if (!empty($group['art_style'])) {
  3102. $content .= "###美术风格\n" . $group['art_style'] . "\n\n";
  3103. }
  3104. // 场景信息
  3105. if (!empty($group['scenes']) && is_array($group['scenes'])) {
  3106. $content .= "###场景列表\n";
  3107. foreach ($group['scenes'] as $scene) {
  3108. $content .= getProp($scene, 'scene') . ":" . getProp($scene, 'description') . "\n";
  3109. }
  3110. $content .= "\n\n";
  3111. }
  3112. // 分集内容
  3113. if (!empty($group['episode_content'])) {
  3114. $content .= "###分集剧本\n";
  3115. $content .= $group['episode_content'];
  3116. // foreach ($script['episodes'] as $episode) {
  3117. // // $content .= "##分集" . $episode['episode_number'] . "\n分集名";
  3118. // // if (!empty($episode['episode_name'])) {
  3119. // // $content .= ":" . $episode['episode_name'];
  3120. // // }
  3121. // // $content .= "\n";
  3122. // $content .= $episode['episode_content'] . "\n\n";
  3123. // }
  3124. }
  3125. }
  3126. return $content;
  3127. }
  3128. /**
  3129. * 上传文件识别文字内容并与 DeepSeek 进行对话(流式输出版本)
  3130. *
  3131. * @param array $data 包含以下参数:
  3132. * - file: 上传的文件(UploadedFile 对象)或文件路径
  3133. * - question: 用户问题(可选)
  3134. * - model: 使用的模型(r1 或 v3,默认 v3)
  3135. * @return \Generator 返回生成器,用于流式输出
  3136. */
  3137. public function addChat($data) {
  3138. $uid = Site::getUid();
  3139. $anime_id = getProp($data, 'anime_id');
  3140. if (!$anime_id) Utils::throwError('20003:请选择对话');
  3141. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  3142. if (!$anime) Utils::throwError('20003:对话不存在');
  3143. $file = getProp($data, 'file');
  3144. $content = getProp($data, 'content', '');
  3145. $bid = getProp($data, 'bid', 0);
  3146. $script_id = getProp($data, 'script_id', 0);
  3147. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  3148. $prompt = getProp($data, 'prompt');
  3149. $user_anime_name = getProp($anime, 'anime_name');
  3150. // 处理文本模型
  3151. $model = getProp($data, 'model');
  3152. if (!$model) {
  3153. // 用户没有输入,从anime表获取
  3154. $model = getProp($anime, 'model');
  3155. if (!$model) {
  3156. // anime表也没有,使用默认值
  3157. $model = 'doubao-seed-2-0-mini-260215';
  3158. }
  3159. }
  3160. // 验证模型是否在可用模型表中
  3161. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3162. $model = 'doubao-seed-2-0-mini-260215';
  3163. }
  3164. $is_multi = getProp($anime, 'is_multi');
  3165. $is_single = (int)$is_multi !== 1;
  3166. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3167. if ($prompt) {
  3168. $question .= "本次修改要求如下:\n{$prompt}";
  3169. }
  3170. // if (!$file && !$content && !$bid) {
  3171. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  3172. // }
  3173. // 提取文件内容
  3174. if ($file) {
  3175. $content = $this->extractFileContent($file);
  3176. if (!$content) {
  3177. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3178. }
  3179. } elseif ($script_id) {
  3180. $content = $this->getContentByScriptId($script_id);
  3181. if (!$content) {
  3182. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3183. }
  3184. } elseif ($bid) {
  3185. $content = $this->getContentByBid($bid);
  3186. if (!$content) {
  3187. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3188. }
  3189. } elseif ($content) {
  3190. $content = filterContent($content);
  3191. } else {
  3192. $content = getProp($anime, 'content');
  3193. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3194. $need_generate_content = true;
  3195. }
  3196. }
  3197. // 美术风格
  3198. $input_art_style = getProp($data, 'art_style');
  3199. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3200. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3201. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3202. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3203. 中年女:邻居阿姨
  3204. 老年男:幽默大爷
  3205. 老年女:婆婆
  3206. 萌娃:奶气萌娃";
  3207. // 判断是否需要生成原文内容
  3208. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3209. // 如果需要生成原文内容,添加额外的要求
  3210. $content_generation_requirement = $need_generate_content
  3211. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3212. : "";
  3213. // 美术风格
  3214. if (!$mappedArtStyle) {
  3215. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3216. }else {
  3217. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3218. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3219. }else {
  3220. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3221. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3222. }
  3223. }
  3224. $systemPrompt = $is_single
  3225. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3226. 强制要求:
  3227. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3228. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3229. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3230. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3231. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3232. 普通要求:
  3233. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3234. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3235. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体描述{人物提示词}{{音色}}
  3236. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3237. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3238. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3239. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3240. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3241. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3242. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3243. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3244. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3245. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3246. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3247. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3248. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3249. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3250. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3251. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3252. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3253. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3254. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3255. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3256. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3257. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3258. 5.{$mappedArtStyle_prompt}\n\n
  3259. 示例如下:\n
  3260. ###剧本名:西昆仑
  3261. ###故事梗概
  3262. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3263. ###剧本亮点
  3264. 亮点1:绝境奇药,生死一线
  3265. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3266. 亮点2:结拜兄妹,化解尴尬
  3267. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3268. 亮点3:纤发夺命,情愫暗涌
  3269. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3270. ###人物关系
  3271. 阿雪与梁萧之间存在兄妹之情。
  3272. ###核心矛盾
  3273. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3274. ###主体列表
  3275. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3276. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3277. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3278. 姿态:站立。}{{甜心小美}}
  3279. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3280. 全景,正面拍摄,青年女性,亚洲人。
  3281. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3282. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3283. 姿态:站立。}{{阳光青年}}
  3284. ###美术风格
  3285. 基础画风风格词:厚涂古风
  3286. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3287. ###场景列表
  3288. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3289. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3290. 无人物。}
  3291. ###分镜剧本
  3292. ##第1幕:徐家老旧厨房 白天 室内
  3293. 分镜1
  3294. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3295. 场景:徐家老旧厨房
  3296. 构图设计:全景,低角度仰视
  3297. 运镜调度:手持拍摄
  3298. 配音角色:旁白
  3299. 出镜角色:许芸-校服装、徐母
  3300. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3301. 画面类型:普通画面
  3302. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3303. 分镜2
  3304. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3305. 场景:徐家老旧厨房
  3306. 构图设计:近景,徐母面部特写
  3307. 运镜调度:固定镜头
  3308. 配音角色:徐母
  3309. 出镜角色:徐母
  3310. 台词内容:问我夜不归宿死哪儿去了。
  3311. 画面类型:对口型
  3312. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3313. ##第2幕:徐家简陋客厅 黄昏 室内
  3314. 分镜3
  3315. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3316. 场景:徐家简陋客厅
  3317. 构图设计:全景,景深虚化
  3318. 运镜调度:固定镜头
  3319. 配音角色:旁白
  3320. 出镜角色:无
  3321. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3322. 画面类型:普通画面
  3323. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3324. 分镜4
  3325. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3326. 场景:徐家简陋客厅
  3327. 构图设计:特写,火车票
  3328. 运镜调度:固定镜头
  3329. 配音角色:旁白
  3330. 出镜角色:无
  3331. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  3332. 画面类型:普通画面
  3333. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  3334. "
  3335. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  3336. 强制要求:\n
  3337. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3338. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3339. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3340. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3341. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3342. 普通要求:\n
  3343. 1.剧本名(必须生成)必须与文档内容高度相关
  3344. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3345. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3346. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3347. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3348. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3349. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3350. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3351. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3352. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3353. 4.{$mappedArtStyle_prompt}\n\n
  3354. 示例如下:\n
  3355. ###剧本名:西昆仑
  3356. ###故事梗概
  3357. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3358. ###剧本亮点
  3359. 亮点1:绝境奇药,生死一线
  3360. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3361. 亮点2:结拜兄妹,化解尴尬
  3362. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3363. 亮点3:纤发夺命,情愫暗涌
  3364. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3365. ###人物关系
  3366. 阿雪与梁萧之间存在兄妹之情。
  3367. ###核心矛盾
  3368. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3369. ###主体列表
  3370. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3371. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3372. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3373. 姿态:站立。}{{甜心小美}}
  3374. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3375. 全景,正面拍摄,青年女性,亚洲人。
  3376. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3377. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3378. 姿态:站立。}{{阳光青年}}
  3379. ###美术风格
  3380. 基础画风风格词:厚涂古风
  3381. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3382. ###场景列表
  3383. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3384. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3385. 无人物。}";
  3386. // 构建消息
  3387. $messages = [
  3388. [
  3389. 'role' => 'system',
  3390. 'content' => $systemPrompt
  3391. ],
  3392. [
  3393. 'role' => 'user',
  3394. 'content' => "以下是文档内容:
  3395. {$content}
  3396. 用户问题:
  3397. {$question}"
  3398. ]
  3399. ];
  3400. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  3401. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  3402. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  3403. if ($model === 'deepseek-chat') {
  3404. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  3405. $model = 'deepseek-v4-flash';
  3406. $thinkingMode = 'disabled';
  3407. } elseif ($model === 'deepseek-reasoner') {
  3408. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  3409. $model = 'deepseek-v4-flash';
  3410. $thinkingMode = 'enabled';
  3411. }
  3412. $post_data = [
  3413. 'model' => $model,
  3414. 'messages' => $messages,
  3415. // 'max_tokens' => 8192,
  3416. 'temperature' => 0.7,
  3417. 'frequency_penalty' => 0,
  3418. 'presence_penalty' => 0,
  3419. 'response_format' => ['type' => 'text'],
  3420. 'thinking' => ['type'=>$thinkingMode],
  3421. 'stream' => true // 启用流式输出
  3422. ];
  3423. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  3424. // 根据模型类型选择调用方法
  3425. $fullContent = '';
  3426. $fullReasoningContent = '';
  3427. $usage = [];
  3428. try {
  3429. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  3430. // DeepSeek 官方模型使用 DeepSeek API
  3431. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  3432. } else if (in_array($model, $this->gpt_text_models)) {
  3433. // GPT-5.4 模型使用 TokenRouter API
  3434. $streamGenerator = $this->gpt54StreamResponse($post_data);
  3435. } else {
  3436. // 其他模型使用火山引擎API
  3437. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  3438. }
  3439. // 验证返回值类型
  3440. if (!is_iterable($streamGenerator)) {
  3441. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  3442. dLog('deepseek')->error('addChat流式生成器无效', [
  3443. 'generator_type' => $errorType,
  3444. 'model' => $model,
  3445. 'anime_id' => $anime_id
  3446. ]);
  3447. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  3448. 'type' => $errorType,
  3449. 'model' => $model
  3450. ]);
  3451. yield [
  3452. 'type' => 'error',
  3453. 'script' => [],
  3454. 'episode' => [],
  3455. 'answer' => '',
  3456. 'reasoning' => '',
  3457. 'usage' => [],
  3458. 'error' => '接口返回数据异常,请重新请求'
  3459. ];
  3460. return;
  3461. }
  3462. // 处理流式输出
  3463. foreach ($streamGenerator as $chunk) {
  3464. if (isset($chunk['type'])) {
  3465. if ($chunk['type'] === 'done') {
  3466. // 最终结果
  3467. $fullContent = $chunk['full_content'];
  3468. $fullReasoningContent = $chunk['full_reasoning'];
  3469. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  3470. } else {
  3471. // 逐块yield数据
  3472. yield $chunk;
  3473. }
  3474. }
  3475. }
  3476. } catch (\Exception $e) {
  3477. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  3478. 'model' => $model,
  3479. 'anime_id' => $anime_id,
  3480. 'trace' => $e->getTraceAsString()
  3481. ]);
  3482. logDB('deepseek', 'error', 'addChat流式处理失败', [
  3483. 'error' => $e->getMessage(),
  3484. 'model' => $model
  3485. ]);
  3486. yield [
  3487. 'type' => 'error',
  3488. 'script' => [],
  3489. 'episode' => [],
  3490. 'answer' => '',
  3491. 'reasoning' => '',
  3492. 'usage' => [],
  3493. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  3494. ];
  3495. return;
  3496. }
  3497. dLog('deepseek')->info('完整内容: '.$fullContent);
  3498. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  3499. // 处理完整内容并返回最终结果
  3500. $script_arr = [];
  3501. if ($fullContent) {
  3502. $script_arr = handleScriptContent($fullContent);
  3503. dLog('deepseek')->info('解析内容', $script_arr);
  3504. logDB('deepseek', 'info', '解析内容', $script_arr);
  3505. }
  3506. if (empty($script_arr['roles'])) {
  3507. // 未生成剧本相关内容,保存对话记录并返回提示
  3508. dLog('deepseek')->info('未生成剧本相关的内容');
  3509. try {
  3510. DB::beginTransaction();
  3511. $now = date('Y-m-d H:i:s');
  3512. // 保存对话记录
  3513. $records = [
  3514. [
  3515. 'uid' => $uid,
  3516. 'anime_id' => $anime_id,
  3517. 'sequence' => 0,
  3518. 'role' => 'user',
  3519. 'content' => $prompt,
  3520. 'created_at' => $now,
  3521. 'updated_at' => $now
  3522. ],
  3523. [
  3524. 'uid' => $uid,
  3525. 'anime_id' => $anime_id,
  3526. 'sequence' => 0,
  3527. 'role' => 'assistant',
  3528. // 'content' => $fullContent,
  3529. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  3530. 'created_at' => $now,
  3531. 'updated_at' => $now
  3532. ]
  3533. ];
  3534. DB::table('mp_anime_records')->insert($records);
  3535. DB::commit();
  3536. } catch (\Exception $e) {
  3537. DB::rollBack();
  3538. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3539. }
  3540. yield [
  3541. 'type' => 'done',
  3542. 'script' => [],
  3543. 'episode' => [],
  3544. 'answer' => $fullContent,
  3545. 'reasoning' => $fullReasoningContent,
  3546. 'usage' => $usage,
  3547. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  3548. ];
  3549. return;
  3550. }
  3551. // 如果需要生成原文内容,从script_arr中提取
  3552. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  3553. $content = $script_arr['content'];
  3554. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  3555. if (!$content) {
  3556. yield [
  3557. 'type' => 'done',
  3558. 'script' => [],
  3559. 'episode' => [],
  3560. 'answer' => $fullContent,
  3561. 'reasoning' => $fullReasoningContent,
  3562. 'usage' => $usage,
  3563. 'error' => '未生成剧本内容,请调整提示词再试'
  3564. ];
  3565. return;
  3566. }
  3567. }
  3568. // 替换美术风格
  3569. if ($mappedArtStyle !== '') {
  3570. $script_arr['art_style'] = $mappedArtStyle;
  3571. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  3572. }
  3573. // 新建动漫
  3574. if ($user_anime_name == '新剧本策划') {
  3575. $anime_name = getProp($script_arr, 'script_name');
  3576. // if (!$anime_name) {
  3577. // // 未识别到剧本名,保存对话记录并返回提示
  3578. // dLog('deepseek')->info('未能识别到剧本名称');
  3579. // try {
  3580. // DB::beginTransaction();
  3581. // $now = date('Y-m-d H:i:s');
  3582. // // 保存对话记录
  3583. // $records = [
  3584. // [
  3585. // 'uid' => $uid,
  3586. // 'anime_id' => $anime_id,
  3587. // 'sequence' => 0,
  3588. // 'role' => 'user',
  3589. // 'content' => $prompt,
  3590. // 'created_at' => $now,
  3591. // 'updated_at' => $now
  3592. // ],
  3593. // [
  3594. // 'uid' => $uid,
  3595. // 'anime_id' => $anime_id,
  3596. // 'sequence' => 0,
  3597. // 'role' => 'assistant',
  3598. // 'content' => '未能生成剧本名称,请重试',
  3599. // 'created_at' => $now,
  3600. // 'updated_at' => $now
  3601. // ]
  3602. // ];
  3603. // DB::table('mp_anime_records')->insert($records);
  3604. // DB::commit();
  3605. // } catch (\Exception $e) {
  3606. // DB::rollBack();
  3607. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  3608. // }
  3609. // yield [
  3610. // 'type' => 'done',
  3611. // 'script' => [],
  3612. // 'episode' => [],
  3613. // 'answer' => $fullContent,
  3614. // 'reasoning' => $fullReasoningContent,
  3615. // 'usage' => $usage,
  3616. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  3617. // ];
  3618. // return;
  3619. // }
  3620. // 确认对话名称唯一性
  3621. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  3622. $anime_name = $anime_name . '_' . date('YmdHis');
  3623. }
  3624. }else {
  3625. $anime_name = $user_anime_name;
  3626. }
  3627. $table_data = [
  3628. 'user_id' => $uid,
  3629. 'anime_name' => $anime_name,
  3630. 'model' => $model,
  3631. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  3632. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  3633. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  3634. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  3635. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  3636. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  3637. 'art_style_type' => $input_art_style,
  3638. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  3639. 'status' => '解析完成',
  3640. 'content' => $content,
  3641. 'is_multi' => $is_multi,
  3642. 'ace_mode' => $ace_mode,
  3643. 'generate_status' => '待执行',
  3644. 'updated_at' => date('Y-m-d H:i:s')
  3645. ];
  3646. if ($table_data['content']) {
  3647. $chapters = $this->splitContent($table_data['content']);
  3648. $chapter_count = count($chapters);
  3649. if ($chapter_count > 0) {
  3650. $table_data['start_episode_sequence'] = 1;
  3651. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  3652. }
  3653. }
  3654. // 如果有剧本ID则进行绑定
  3655. if ($script_id) {
  3656. $table_data['script_id'] = $script_id;
  3657. }
  3658. $single_episode = [];
  3659. try {
  3660. DB::beginTransaction();
  3661. $now = date('Y-m-d H:i:s');
  3662. // 更新动漫大纲
  3663. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  3664. if (!$boolen) {
  3665. dLog('deepseek')->info('动漫保存失败', $table_data);
  3666. Utils::throwError('20003:动漫保存失败');
  3667. }
  3668. // 保存对话记录
  3669. $records = [
  3670. [
  3671. 'uid' => $uid,
  3672. 'anime_id' => $anime_id,
  3673. 'sequence' => 0,
  3674. 'role' => 'user',
  3675. 'content' => $prompt,
  3676. 'created_at' => date('Y-m-d H:i:s'),
  3677. 'updated_at' => date('Y-m-d H:i:s')
  3678. ],
  3679. [
  3680. 'uid' => $uid,
  3681. 'anime_id' => $anime_id,
  3682. 'sequence' => 0,
  3683. 'role' => 'assistant',
  3684. 'content' => $fullContent,
  3685. 'created_at' => date('Y-m-d H:i:s'),
  3686. 'updated_at' => date('Y-m-d H:i:s')
  3687. ]
  3688. ];
  3689. // 保存对话记录
  3690. $boolen3 = DB::table('mp_anime_records')->insert($records);
  3691. if (!$boolen3) {
  3692. Utils::throwError('20003:对话记录保存失败');
  3693. }
  3694. if ($is_single) {
  3695. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  3696. if (empty($episode_arr['acts'])) {
  3697. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  3698. }
  3699. $saveResult = $this->saveEpisodeVersionData(
  3700. $anime_id,
  3701. 1,
  3702. $episode_arr,
  3703. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  3704. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  3705. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  3706. null,
  3707. null,
  3708. false,
  3709. $content,
  3710. $now
  3711. );
  3712. $single_episode = $saveResult['episode'];
  3713. $episode_id = $saveResult['episode_id'];
  3714. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  3715. 'roles' => json_encode($saveResult['merged_roles'], 256),
  3716. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  3717. 'props' => json_encode($saveResult['merged_props'], 256),
  3718. 'updated_at' => $now
  3719. ]);
  3720. if ($boolen5 === false) {
  3721. Utils::throwError('20003:单剧集主表资源同步失败');
  3722. }
  3723. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  3724. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  3725. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  3726. $episode_record_content = '确认分镜大纲';
  3727. if ($content !== '') {
  3728. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  3729. }
  3730. $episode_records = [
  3731. [
  3732. 'uid' => $uid,
  3733. 'anime_id' => $anime_id,
  3734. 'role' => 'user',
  3735. 'content' => $episode_record_content,
  3736. 'sequence' => 1,
  3737. 'episode_id' => $episode_id,
  3738. 'created_at' => $now,
  3739. 'updated_at' => $now
  3740. ],
  3741. [
  3742. 'uid' => $uid,
  3743. 'anime_id' => $anime_id,
  3744. 'role' => 'assistant',
  3745. 'content' => $fullContent,
  3746. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  3747. 'sequence' => 1,
  3748. 'episode_id' => $episode_id,
  3749. 'created_at' => $now,
  3750. 'updated_at' => $now
  3751. ]
  3752. ];
  3753. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  3754. if (!$boolen4) {
  3755. Utils::throwError('20003:单剧集分镜记录保存失败');
  3756. }
  3757. }
  3758. }catch (\Exception $e) {
  3759. DB::rollBack();
  3760. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  3761. yield [
  3762. 'type' => 'done',
  3763. 'answer' => $fullContent,
  3764. 'reasoning' => $fullReasoningContent,
  3765. 'usage' => $usage,
  3766. 'error' => $e->getMessage(),
  3767. ];
  3768. return;
  3769. }
  3770. DB::commit();
  3771. dLog('deepseek')->info('保存完毕');
  3772. if ($is_single && !empty($single_episode)) {
  3773. // $this->batchSetGlobalRoleImg([
  3774. // 'anime_id' => $anime_id,
  3775. // ]);
  3776. // $this->batchSetGlobalSceneImg([
  3777. // 'anime_id' => $anime_id,
  3778. // ]);
  3779. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  3780. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  3781. }
  3782. $table_data['anime_id'] = $anime_id;
  3783. $table_data['roles'] = json_decode($table_data['roles'], true);
  3784. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  3785. // $table_data['episodes'] = $script_arr['episodes'];
  3786. unset($table_data['created_at']);
  3787. unset($table_data['updated_at']);
  3788. unset($table_data['status']);
  3789. dLog('deepseek')->info('开始返回');
  3790. yield [
  3791. 'type' => 'done',
  3792. 'script' => $table_data,
  3793. 'episode' => $single_episode,
  3794. 'answer' => $fullContent,
  3795. 'reasoning' => $fullReasoningContent,
  3796. 'usage' => $usage
  3797. ];
  3798. }
  3799. public function reGenerateAnime($data) {
  3800. $uid = Site::getUid();
  3801. $file = getProp($data, 'file');
  3802. $content = getProp($data, 'content', '');
  3803. $bid = getProp($data, 'bid', 0);
  3804. $script_id = getProp($data, 'script_id', 0);
  3805. $anime_id = getProp($data, 'anime_id');
  3806. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  3807. if (!$anime) {
  3808. Utils::throwError('20003:该对话不存在');
  3809. }
  3810. $user_anime_name = getProp($anime, 'anime_name');
  3811. $prompt = getProp($data, 'prompt');
  3812. // 处理文本模型
  3813. $model = getProp($data, 'model');
  3814. if (!$model) {
  3815. // 用户没有输入,从anime表获取
  3816. $model = getProp($anime, 'model');
  3817. if (!$model) {
  3818. // anime表也没有,使用默认值
  3819. $model = 'doubao-seed-2-0-mini-260215';
  3820. }
  3821. }
  3822. // 验证模型是否在可用模型表中
  3823. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  3824. $model = 'doubao-seed-2-0-mini-260215';
  3825. }
  3826. $is_multi = getProp($anime, 'is_multi', 1);
  3827. $is_single = (int)$is_multi !== 1;
  3828. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  3829. if ($is_single) {
  3830. $episode_exists = DB::table('mp_anime_episodes')
  3831. ->where('anime_id', $anime_id)
  3832. ->where('sequence', 1)
  3833. ->exists();
  3834. if ($episode_exists) {
  3835. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  3836. }
  3837. }
  3838. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分镜\n" : "请根据实例格式完成剧本大纲\n");
  3839. if ($prompt) {
  3840. $question .= "本次修改要求如下:\n{$prompt}";
  3841. }
  3842. // 提取文件内容
  3843. if ($file) {
  3844. $content = $this->extractFileContent($file);
  3845. if (!$content) {
  3846. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  3847. }
  3848. } elseif ($script_id) {
  3849. $content = $this->getContentByScriptId($script_id);
  3850. if (!$content) {
  3851. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  3852. }
  3853. } elseif ($bid) {
  3854. $content = $this->getContentByBid($bid);
  3855. if (!$content) {
  3856. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  3857. }
  3858. } elseif ($content) {
  3859. $content = filterContent($content);
  3860. }else {
  3861. $content = filterContent(getProp($anime, 'content'));
  3862. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  3863. $need_generate_content = true;
  3864. }
  3865. }
  3866. // 判断是否需要生成原文内容
  3867. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  3868. // 如果需要生成原文内容,添加额外的要求
  3869. $content_generation_requirement = $need_generate_content
  3870. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  3871. : "";
  3872. // 美术风格
  3873. $input_art_style = getProp($anime, 'art_style');
  3874. if (!$input_art_style) {
  3875. $input_art_style = getProp($data, 'art_style');
  3876. }
  3877. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  3878. // 美术风格
  3879. if (!$mappedArtStyle) {
  3880. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  3881. }else {
  3882. if (strstr($mappedArtStyle, '基础画风风格词')) {
  3883. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  3884. }else {
  3885. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  3886. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  3887. }
  3888. }
  3889. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  3890. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  3891. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  3892. 中年女:邻居阿姨
  3893. 老年男:幽默大爷
  3894. 老年女:婆婆
  3895. 萌娃:奶气萌娃";
  3896. $system_message = ['role'=>'system', 'content'=>$is_single
  3897. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  3898. 强制要求:
  3899. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  3900. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  3901. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  3902. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  3903. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  3904. 普通要求:
  3905. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  3906. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  3907. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  3908. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  3909. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  3910. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  3911. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  3912. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  3913. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  3914. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  3915. 3.$mappedArtStyle_prompt\n\n
  3916. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  3917. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  3918. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  3919. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  3920. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。)
  3921. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  3922. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  3923. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  3924. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  3925. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  3926. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  3927. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  3928. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  3929. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  3930. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。\n
  3931. 示例如下:\n
  3932. ###剧本名:西昆仑
  3933. ###故事梗概
  3934. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3935. ###剧本亮点
  3936. 亮点1:绝境奇药,生死一线
  3937. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  3938. 亮点2:结拜兄妹,化解尴尬
  3939. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  3940. 亮点3:纤发夺命,情愫暗涌
  3941. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  3942. ###人物关系
  3943. 阿雪与梁萧之间存在兄妹之情。
  3944. ###核心矛盾
  3945. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  3946. ###主体列表
  3947. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  3948. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  3949. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  3950. 姿态:站立。}{{甜心小美}}
  3951. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  3952. 全景,正面拍摄,青年女性,亚洲人。
  3953. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  3954. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  3955. 姿态:站立。}{{阳光青年}}
  3956. ###美术风格
  3957. 基础画风风格词:厚涂古风
  3958. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  3959. ###场景列表
  3960. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  3961. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  3962. 无人物。}
  3963. ###分镜剧本
  3964. ##第1幕:徐家老旧厨房 白天 室内
  3965. 分镜1
  3966. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  3967. 场景:徐家老旧厨房
  3968. 构图设计:全景,低角度仰视
  3969. 运镜调度:手持拍摄
  3970. 配音角色:旁白
  3971. 出镜角色:许芸-校服装、徐母
  3972. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  3973. 画面类型:普通画面
  3974. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  3975. 分镜2
  3976. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  3977. 场景:徐家老旧厨房
  3978. 构图设计:近景,徐母面部特写
  3979. 运镜调度:固定镜头
  3980. 配音角色:徐母
  3981. 出镜角色:徐母
  3982. 台词内容:问我夜不归宿死哪儿去了。
  3983. 画面类型:对口型
  3984. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  3985. ##第2幕:徐家简陋客厅 黄昏 室内
  3986. 分镜3
  3987. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  3988. 场景:徐家简陋客厅
  3989. 构图设计:全景,景深虚化
  3990. 运镜调度:固定镜头
  3991. 配音角色:旁白
  3992. 出镜角色:无
  3993. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  3994. 画面类型:普通画面
  3995. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  3996. 分镜4
  3997. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  3998. 场景:徐家简陋客厅
  3999. 构图设计:特写,火车票
  4000. 运镜调度:固定镜头
  4001. 配音角色:旁白
  4002. 出镜角色:无
  4003. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4004. 画面类型:普通画面
  4005. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。\n
  4006. "
  4007. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4008. 强制要求:\n
  4009. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4010. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4011. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4012. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4013. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4014. 普通要求:\n
  4015. 1.剧本名(必须生成)必须与文档内容高度相关
  4016. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4017. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4018. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4019. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4020. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4021. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4022. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4023. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4024. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4025. 4.$mappedArtStyle_prompt\n\n
  4026. 示例如下:\n
  4027. ###剧本名:西昆仑
  4028. ###故事梗概
  4029. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4030. ###剧本亮点
  4031. 亮点1:绝境奇药,生死一线
  4032. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4033. 亮点2:结拜兄妹,化解尴尬
  4034. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4035. 亮点3:纤发夺命,情愫暗涌
  4036. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4037. ###人物关系
  4038. 阿雪与梁萧之间存在兄妹之情。
  4039. ###核心矛盾
  4040. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4041. ###主体列表
  4042. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4043. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4044. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4045. 姿态:站立。}{{甜心小美}}
  4046. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4047. 全景,正面拍摄,青年女性,亚洲人。
  4048. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4049. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4050. 姿态:站立。}{{阳光青年}}
  4051. ###美术风格
  4052. 基础画风风格词:厚涂古风
  4053. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4054. ###场景列表
  4055. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4056. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4057. 无人物。}"];
  4058. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  4059. $episode_count = $this->extractEpisodeNumber($prompt);
  4060. if ((int)getProp($anime, 'is_multi') !== 1) {
  4061. yield [
  4062. 'type' => 'done',
  4063. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  4064. 'reasoning' => '',
  4065. 'usage' => []
  4066. ];
  4067. return;
  4068. }
  4069. if ($episode_count) {
  4070. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  4071. $system_message = [
  4072. 'role' => 'system',
  4073. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4074. 强制要求:\n
  4075. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4076. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4077. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4078. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  4079. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  4080. 普通要求:\n
  4081. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4082. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4083. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  4084. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4085. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。
  4086. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4087. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4088. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4089. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  4090. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  4091. 示例如下:\n
  4092. ###剧本名:西昆仑
  4093. ###故事梗概
  4094. 内容梗概:古风厚涂的世界中,少女阿雪身中奇毒“问心刺”,气息奄奄。少年梁萧心急如焚,用奇珍“阴阳球”稳住阿雪性命,却发现必须解衣拔刺。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4095. ###剧本亮点
  4096. 亮点1:绝境奇药,生死一线
  4097. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  4098. 亮点2:结拜兄妹,化解尴尬
  4099. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  4100. 亮点3:纤发夺命,情愫暗涌
  4101. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  4102. ###人物关系
  4103. 阿雪与梁萧之间存在兄妹之情。
  4104. ###核心矛盾
  4105. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  4106. ###主体列表
  4107. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  4108. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  4109. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  4110. 姿态:站立。}{{甜心小美}}
  4111. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  4112. 全景,正面拍摄,青年女性,亚洲人。
  4113. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  4114. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  4115. 姿态:站立。}{{阳光青年}}
  4116. ###美术风格
  4117. 基础画风风格词:厚涂古风
  4118. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  4119. ###场景列表
  4120. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  4121. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4122. 无人物。}
  4123. ###分集详细内容
  4124. ##第1章 重生
  4125. 我重生了。
  4126. 源于一个男人偏执的暗恋。
  4127. ##第2章 相救
  4128. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  4129. 我眼睛扫向站在锅炉后的卞大伟。"
  4130. ];
  4131. // 构建消息
  4132. $messages = [
  4133. $system_message,
  4134. [
  4135. 'role' => 'user',
  4136. 'content' => "以下是文档内容:
  4137. {$content}
  4138. 用户问题:
  4139. {$question}"
  4140. ]
  4141. ];
  4142. }else {
  4143. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  4144. // 构建消息
  4145. $messages = [
  4146. $system_message,
  4147. [
  4148. 'role' => 'user',
  4149. 'content' => "以下是文档内容:
  4150. {$content}
  4151. 用户问题:
  4152. {$question}"
  4153. ]
  4154. ];
  4155. }else {
  4156. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  4157. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  4158. return (array)$value;
  4159. })->toArray();
  4160. array_unshift($messages, $system_message);
  4161. $messages[] = [
  4162. 'role' => 'user',
  4163. 'content' => $prompt
  4164. ];
  4165. }
  4166. }
  4167. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4168. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4169. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4170. if ($model === 'deepseek-chat') {
  4171. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4172. $model = 'deepseek-v4-flash';
  4173. $thinkingMode = 'disabled';
  4174. } elseif ($model === 'deepseek-reasoner') {
  4175. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4176. $model = 'deepseek-v4-flash';
  4177. $thinkingMode = 'enabled';
  4178. }
  4179. $post_data = [
  4180. 'model' => $model,
  4181. 'messages' => $messages,
  4182. // 'max_tokens' => 8192,
  4183. 'temperature' => 0.7,
  4184. 'frequency_penalty' => 0,
  4185. 'presence_penalty' => 0,
  4186. 'response_format' => ['type' => 'text'],
  4187. 'thinking' => ['type' => $thinkingMode],
  4188. 'stream' => true // 启用流式输出
  4189. ];
  4190. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4191. // 根据模型类型选择调用方法
  4192. $fullContent = '';
  4193. $fullReasoningContent = '';
  4194. $usage = [];
  4195. // dd($post_data);
  4196. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  4197. try {
  4198. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4199. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4200. } else if (in_array($model, $this->gpt_text_models)) {
  4201. // GPT-5.4 模型使用 TokenRouter API
  4202. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4203. } else {
  4204. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4205. }
  4206. // 验证返回值类型
  4207. if (!is_iterable($streamGenerator)) {
  4208. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4209. dLog('deepseek')->error('方法名流式生成器无效', [
  4210. 'generator_type' => $errorType,
  4211. 'model' => $model,
  4212. // 添加其他上下文信息
  4213. ]);
  4214. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  4215. 'type' => $errorType,
  4216. 'model' => $model
  4217. ]);
  4218. yield [
  4219. 'type' => 'error',
  4220. // 根据方法返回相应的空数据结构
  4221. 'answer' => '',
  4222. 'reasoning' => '',
  4223. 'usage' => [],
  4224. 'error' => '接口返回数据异常,请重新请求'
  4225. ];
  4226. return;
  4227. }
  4228. // 处理流式输出
  4229. foreach ($streamGenerator as $chunk) {
  4230. if (isset($chunk['type'])) {
  4231. if ($chunk['type'] === 'done') {
  4232. $fullContent = $chunk['full_content'];
  4233. $fullReasoningContent = $chunk['full_reasoning'];
  4234. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  4235. } else {
  4236. yield $chunk;
  4237. }
  4238. }
  4239. }
  4240. } catch (\Exception $e) {
  4241. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  4242. 'model' => $model,
  4243. 'trace' => $e->getTraceAsString()
  4244. ]);
  4245. logDB('deepseek', 'error', '方法名流式处理失败', [
  4246. 'error' => $e->getMessage(),
  4247. 'model' => $model
  4248. ]);
  4249. yield [
  4250. 'type' => 'error',
  4251. // 根据方法返回相应的空数据结构
  4252. 'answer' => '',
  4253. 'reasoning' => '',
  4254. 'usage' => [],
  4255. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  4256. ];
  4257. return;
  4258. }
  4259. dLog('deepseek')->info('完整内容: '.$fullContent);
  4260. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  4261. // 处理完整内容并返回最终结果
  4262. $script_arr = [];
  4263. if ($fullContent) {
  4264. $script_arr = handleScriptContent($fullContent);
  4265. dLog('deepseek')->info('解析内容', $script_arr);
  4266. logDB('deepseek', 'info', '解析内容', $script_arr);
  4267. }
  4268. if (empty($script_arr['roles'])) {
  4269. // 未生成剧本相关内容,保存对话记录并返回提示
  4270. dLog('deepseek')->info('未生成剧本相关的内容');
  4271. try {
  4272. $now = date('Y-m-d H:i:s');
  4273. // 保存对话记录
  4274. $records = [
  4275. [
  4276. 'uid' => $uid,
  4277. 'anime_id' => $anime_id,
  4278. 'sequence' => 0,
  4279. 'role' => 'user',
  4280. 'content' => $prompt,
  4281. 'created_at' => $now,
  4282. 'updated_at' => $now
  4283. ],
  4284. [
  4285. 'uid' => $uid,
  4286. 'anime_id' => $anime_id,
  4287. 'sequence' => 0,
  4288. 'role' => 'assistant',
  4289. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  4290. 'created_at' => $now,
  4291. 'updated_at' => $now
  4292. ]
  4293. ];
  4294. DB::table('mp_anime_records')->insert($records);
  4295. } catch (\Exception $e) {
  4296. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  4297. }
  4298. yield [
  4299. 'type' => 'done',
  4300. 'script' => [],
  4301. 'episode' => [],
  4302. 'answer' => $fullContent,
  4303. 'reasoning' => $fullReasoningContent,
  4304. 'usage' => $usage,
  4305. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  4306. ];
  4307. return;
  4308. }
  4309. // 替换美术风格
  4310. if ($mappedArtStyle !== '') {
  4311. $script_arr['art_style'] = $mappedArtStyle;
  4312. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  4313. }
  4314. if ($user_anime_name != '新剧本策划') {
  4315. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  4316. // 确认对话名称唯一性
  4317. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  4318. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  4319. }
  4320. }else {
  4321. $anime_name = $user_anime_name;
  4322. }
  4323. $table_data = [
  4324. 'user_id' => $uid,
  4325. 'model' => $model,
  4326. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  4327. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  4328. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  4329. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  4330. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  4331. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  4332. 'art_style_type' => $input_art_style,
  4333. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  4334. 'status' => '解析完成',
  4335. 'generate_status' => '待执行',
  4336. 'updated_at' => date('Y-m-d H:i:s')
  4337. ];
  4338. if ($anime_name) $table_data['anime_name'] = $anime_name;
  4339. // 如果是修改集数,则将content内容更新(会改变原文)
  4340. if (isset($episode_count) && $episode_count > 0) {
  4341. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  4342. $table_data['start_episode_sequence'] = 1;
  4343. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  4344. }else {
  4345. // 如果需要生成原文内容,从script_arr中提取
  4346. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  4347. $table_data['content'] = $script_arr['content'];
  4348. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  4349. if (!$table_data['content']) {
  4350. yield [
  4351. 'type' => 'done',
  4352. 'script' => [],
  4353. 'episode' => [],
  4354. 'answer' => $fullContent,
  4355. 'reasoning' => $fullReasoningContent,
  4356. 'usage' => $usage,
  4357. 'error' => '未生成剧本内容,请调整提示词再试'
  4358. ];
  4359. return;
  4360. }
  4361. }
  4362. if (isset($table_data['content']) && $table_data['content']) {
  4363. $chapters = $this->splitContent($table_data['content']);
  4364. $chapter_count = count($chapters);
  4365. if ($chapter_count > 0) {
  4366. $table_data['start_episode_sequence'] = 1;
  4367. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  4368. }
  4369. }
  4370. }
  4371. $single_episode = [];
  4372. try {
  4373. DB::beginTransaction();
  4374. $now = date('Y-m-d H:i:s');
  4375. // 更新动漫大纲
  4376. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  4377. if (!$boolen) {
  4378. dLog('deepseek')->info('对话修改失败', $table_data);
  4379. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  4380. Utils::throwError('20003:对话修改失败');
  4381. }
  4382. // 保存对话记录
  4383. $records = [
  4384. [
  4385. 'uid' => $uid,
  4386. 'anime_id' => $anime_id,
  4387. 'sequence' => 0,
  4388. 'role' => 'user',
  4389. 'content' => $prompt,
  4390. 'created_at' => $now,
  4391. 'updated_at' => $now
  4392. ],
  4393. [
  4394. 'uid' => $uid,
  4395. 'anime_id' => $anime_id,
  4396. 'sequence' => 0,
  4397. 'role' => 'assistant',
  4398. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4399. 'content' => $fullContent,
  4400. 'created_at' => $now,
  4401. 'updated_at' => $now
  4402. ]
  4403. ];
  4404. // 保存对话记录
  4405. $boolen3 = DB::table('mp_anime_records')->insert($records);
  4406. if (!$boolen3) {
  4407. Utils::throwError('20003:对话记录保存失败');
  4408. }
  4409. // 单剧集模式:生成并保存剧集信息
  4410. if ($is_single) {
  4411. $anime_name = getProp($anime, 'anime_name', '未命名');
  4412. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  4413. if (empty($episode_arr['acts'])) {
  4414. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  4415. }
  4416. $saveResult = $this->saveEpisodeVersionData(
  4417. $anime_id,
  4418. 1,
  4419. $episode_arr,
  4420. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  4421. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  4422. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  4423. null,
  4424. null,
  4425. false,
  4426. $content,
  4427. $now
  4428. );
  4429. $single_episode = $saveResult['episode'];
  4430. $episode_id = $saveResult['episode_id'];
  4431. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  4432. 'roles' => json_encode($saveResult['merged_roles'], 256),
  4433. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  4434. 'props' => json_encode($saveResult['merged_props'], 256),
  4435. 'updated_at' => $now
  4436. ]);
  4437. if ($boolen5 === false) {
  4438. Utils::throwError('20003:单剧集主表资源同步失败');
  4439. }
  4440. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  4441. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  4442. $table_data['props'] = json_encode($saveResult['merged_props'], 256);
  4443. $episode_record_content = '确认分镜大纲';
  4444. if ($content !== '') {
  4445. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  4446. }
  4447. $episode_records = [
  4448. [
  4449. 'uid' => $uid,
  4450. 'anime_id' => $anime_id,
  4451. 'role' => 'user',
  4452. 'content' => $episode_record_content,
  4453. 'sequence' => 1,
  4454. 'episode_id' => $episode_id,
  4455. 'created_at' => $now,
  4456. 'updated_at' => $now
  4457. ],
  4458. [
  4459. 'uid' => $uid,
  4460. 'anime_id' => $anime_id,
  4461. 'role' => 'assistant',
  4462. 'content' => $fullContent,
  4463. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  4464. 'sequence' => 1,
  4465. 'episode_id' => $episode_id,
  4466. 'created_at' => $now,
  4467. 'updated_at' => $now
  4468. ]
  4469. ];
  4470. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  4471. if (!$boolen4) {
  4472. Utils::throwError('20003:单剧集分镜记录保存失败');
  4473. }
  4474. }
  4475. }catch (\Exception $e) {
  4476. DB::rollBack();
  4477. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  4478. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  4479. yield [
  4480. 'type' => 'done',
  4481. 'answer' => $fullContent,
  4482. 'reasoning' => $fullReasoningContent,
  4483. 'usage' => $usage,
  4484. 'error' => $e->getMessage(),
  4485. ];
  4486. return;
  4487. }
  4488. DB::commit();
  4489. dLog('deepseek')->info('保存完毕');
  4490. if ($is_single && !empty($single_episode)) {
  4491. // $this->batchSetGlobalRoleImg([
  4492. // 'anime_id' => $anime_id,
  4493. // ]);
  4494. // $this->batchSetGlobalSceneImg([
  4495. // 'anime_id' => $anime_id,
  4496. // ]);
  4497. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  4498. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  4499. }
  4500. $table_data['anime_id'] = $anime_id;
  4501. $table_data['roles'] = json_decode($table_data['roles'], true);
  4502. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  4503. unset($table_data['updated_at']);
  4504. unset($table_data['status']);
  4505. yield [
  4506. 'type' => 'done',
  4507. 'script' => $table_data,
  4508. 'episode' => $single_episode,
  4509. 'answer' => $fullContent,
  4510. 'reasoning' => $fullReasoningContent,
  4511. 'usage' => $usage
  4512. ];
  4513. }
  4514. public function chat($data) {
  4515. $uid = Site::getUid();
  4516. $anime_id = getProp($data, 'anime_id');
  4517. $file = getProp($data, 'file');
  4518. $content = getProp($data, 'content', '');
  4519. $bid = getProp($data, 'bid', 0);
  4520. $script_id = getProp($data, 'script_id', 0);
  4521. $episode_number = getProp($data, 'episode_number', 1);
  4522. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4523. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4524. if (!$anime) Utils::throwError('20003:该对话不存在!');
  4525. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  4526. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  4527. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  4528. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  4529. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  4530. $roles = is_array($roles) ? $roles : [];
  4531. $scenes = is_array($scenes) ? $scenes : [];
  4532. // 获取最后一集序号
  4533. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  4534. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  4535. // 转换主体列表和场景列表的格式
  4536. // 获取参考主体或场景
  4537. if ((int)$episode_number === 1) {
  4538. // $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  4539. $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  4540. }else {
  4541. $prev_episode_number = $episode_number - 1;
  4542. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  4543. }
  4544. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  4545. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  4546. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  4547. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  4548. $timbres_content = "青年男:北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年
  4549. 青年女:柔美女友、魅力女友、爽快思思、高冷御姐、知性温婉、甜心小美、清新女声、甜美桃子、温柔文雅、甜美小源、贴心闺蜜
  4550. 中年男:胡子叔叔、油腻大叔、神秘法师、优柔帮主
  4551. 中年女:邻居阿姨
  4552. 老年男:幽默大爷
  4553. 老年女:婆婆
  4554. 萌娃:奶气萌娃";
  4555. if ($roles_content) {
  4556. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  4557. 主体范围:\n {$roles_content}\n
  4558. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  4559. → 新主体分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4560. → 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4561. → 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4562. → 新主体的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4563. }else {
  4564. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  4565. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色,格式必须为:主体名:主体描述{人物提示词}{{音色}}
  4566. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  4567. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  4568. 2.4<主体列表>的音色必须在以下音色中($timbres_content)选择,需要根据角色描述的年纪和性别选择,比如角色是青年男性就只能在北京小爷、阳光青年、傲娇霸总、优柔公子、解说小明、青涩小生、低音沉郁、亲切青年中选择,选好的音色放在描述的最后用{{}}框起来。";
  4569. }
  4570. if ($scenes_content) {
  4571. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  4572. 场景范围:\n {$scenes_content}\n
  4573. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  4574. → 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  4575. → 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4576. → 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4577. }else {
  4578. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  4579. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  4580. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  4581. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n";
  4582. }
  4583. // 提取文件内容
  4584. if ($file) {
  4585. $uploaded_content = $this->extractFileContent($file);
  4586. if (!$uploaded_content) {
  4587. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  4588. }
  4589. } elseif ($script_id) {
  4590. $uploaded_content = $this->getContentByScriptId($script_id);
  4591. if (!$uploaded_content) {
  4592. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  4593. }
  4594. } elseif ($bid) {
  4595. $uploaded_content = $this->getContentByBid($bid);
  4596. if (!$uploaded_content) {
  4597. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  4598. }
  4599. } elseif ($content) {
  4600. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  4601. }
  4602. // elseif ($prompt) {
  4603. // $uploaded_content = filterContent($prompt);
  4604. // }
  4605. else {
  4606. $uploaded_content = '';
  4607. }
  4608. $input_art_style = getProp($anime, 'art_style');
  4609. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  4610. // 美术风格
  4611. if (!$mappedArtStyle) {
  4612. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  4613. }else {
  4614. if (strstr($mappedArtStyle, '基础画风风格词')) {
  4615. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  4616. }else {
  4617. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  4618. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  4619. }
  4620. }
  4621. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4622. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  4623. // 强制要求:
  4624. // - 你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  4625. // - 如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  4626. // - 以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  4627. // - 用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  4628. // - 强制按照示例格式返回内容,不要更改格式或随意增加符号
  4629. // - 分镜剧本必须严格按照给出的“本集剧情内容”进行拆分,一个字都不要漏掉,同时也不要新增原文没有的内容
  4630. // - 如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  4631. // - 分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  4632. // - 画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  4633. // - 不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  4634. // - 分镜要和场景列表、人物主体保持一致\n
  4635. // 普通要求:
  4636. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4637. // {$role_demo}
  4638. // {$scene_demo}
  4639. // 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4640. // 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4641. // 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4642. // 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始)。
  4643. // 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4644. // 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4645. // 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4646. // 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4647. // 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4648. // 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4649. // 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4650. // 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4651. // 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4652. // 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4653. // 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4654. // 5.$mappedArtStyle_prompt\n\n
  4655. // 示例格式:\n
  4656. // 第1集:隐形的守护者
  4657. // ###故事梗概
  4658. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4659. // ###美术风格
  4660. // 基础画风风格词:韩漫二次元
  4661. // 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4662. // ###主体列表
  4663. // 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4664. // 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4665. // 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4666. // ###场景列表
  4667. // 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4668. // 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4669. // 无人物。}
  4670. // 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4671. // 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4672. // 无人物。}
  4673. // 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4674. // 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4675. // 无人物。}
  4676. // 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4677. // 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4678. // 无人物。}
  4679. // 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4680. // 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4681. // 无人物。}
  4682. // ###分镜剧本
  4683. // ##第1幕:徐家老旧厨房 白天 室内
  4684. // 分镜1
  4685. // 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4686. // 场景:徐家老旧厨房
  4687. // 构图设计:全景,低角度仰视
  4688. // 运镜调度:手持拍摄
  4689. // 配音角色:旁白
  4690. // 出镜角色:许芸-校服装、徐母
  4691. // 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4692. // 画面类型:普通画面
  4693. // 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4694. // 分镜2
  4695. // 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4696. // 场景:徐家老旧厨房
  4697. // 构图设计:近景,徐母面部特写
  4698. // 运镜调度:固定镜头
  4699. // 配音角色:徐母
  4700. // 出镜角色:徐母
  4701. // 台词内容:问我夜不归宿死哪儿去了。
  4702. // 画面类型:对口型
  4703. // 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4704. // ##第2幕:徐家简陋客厅 黄昏 室内
  4705. // 分镜3
  4706. // 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4707. // 场景:徐家简陋客厅
  4708. // 构图设计:全景,景深虚化
  4709. // 运镜调度:固定镜头
  4710. // 配音角色:旁白
  4711. // 出镜角色:无
  4712. // 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4713. // 画面类型:普通画面
  4714. // 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4715. // 分镜4
  4716. // 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4717. // 场景:徐家简陋客厅
  4718. // 构图设计:特写,火车票
  4719. // 运镜调度:固定镜头
  4720. // 配音角色:旁白
  4721. // 出镜角色:无
  4722. // 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4723. // 画面类型:普通画面
  4724. // 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4725. // \n\n";
  4726. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><主体列表><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  4727. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「画面描述」「场景/场景时间(白天/晚上/傍晚等)」「构图设计(全景/近景/中景/远景,仰视/平视/俯视等)」「运镜调度」「配音角色」「出境角色」「台词内容」「画面类型」「尾帧描述」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  4728. 每一个分镜的「画面描述」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。\n
  4729. 普通要求:
  4730. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  4731. {$role_demo}
  4732. {$scene_demo}
  4733. 4.<分镜剧本>要求包含“分幕标题”以及“分镜信息”:
  4734. 4.1“分幕标题”是根据章节中的场景进行拆分,类似于“第1幕 场景、时间及室内或室外”的信息,其中场景只能在所给出的场景列表中选(不带场景详细描述)。
  4735. 4.2“分镜信息”需同一场景内的对话内容完成分镜(每一幕分镜尽量不得低于5个),需包含“画面描述”、“构图设计”、“运镜调度”、“配音角色”、“台词内容”、“画面类型”、“尾帧描述”、“情感”、“性别”、“语速”、“音量”、“情感强度”、“音调”这几个部分,其中“画面描述”如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)。
  4736. 4.3分镜序号用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨分幕中的分镜序号需连续,但跨剧集中的不需要连续,如第2集的第1幕分镜序号从1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  4737. 4.4“分镜信息”中的“台词内容”需满足以下要求: (1. 台词来源规则:- 台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容)。- 不允许改写、总结、压缩、扩写或拼接原文对白。- 不允许生成原文中不存在的对话。2. 非对话过滤:- 旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:- 如果该分镜中没有人物对话,则“台词内容”必须返回“无”。- 严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:- 不得根据语境补全人物可能说的话。5.如果没有找到原文内容,直接返回无)
  4738. 4.5“分镜信息”中的“配音角色”需对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色),不得自己生成。
  4739. 4.6“分镜信息”中的“场景”必须选择本集中的<场景列表>中的一个(不带详细表述)。
  4740. 4.7“分镜信息”中的“出镜角色”需对应本集中的<主体列表>中的一个或多个(不带详细描述),如果没有出镜角色则填无。
  4741. 4.8“分镜信息”中的“尾帧描述”需根据本镜和下一镜的剧本信息进行过渡生成,用于后续转视频进行衔接上下镜头的画面。
  4742. 4.9“分镜信息”中的“情感”需根据台词内容和剧情氛围分析得出,可选值为:开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦,不要在情感可选词后加任何解释性的词语,比如(对自己)、(对别人)等,不要自定义情感,必须在可选值中选择。
  4743. 4.10“分镜信息”中的“性别”需根据配音角色的性别确定,可选值为:1(男)、2(女)、0(中性)。
  4744. 4.11“分镜信息”中的“语速”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍速,-50代表0.5倍数,负值表示减慢,正值表示加快,0表示正常语速。
  4745. 4.12“分镜信息”中的“音量”需根据台词内容和情感氛围确定,可选值范围为:-50到100之间的整数,100代表2.0倍音量,-50代表0.5倍音量,负值表示降低音量,正值表示提高音量,0表示正常音量。
  4746. 4.13“分镜信息”中的“情感强度”需根据情感的强烈程度确定,可选值范围为:1到5之间的整数,默认情况下选择4。
  4747. 4.14“分镜信息”中的“音调”需根据台词内容和情感氛围确定,可选值范围为:-12到12之间的整数,负值表示降低音调,正值表示提高音调,0表示正常音调。
  4748. 5.$mappedArtStyle_prompt
  4749. 6.《情绪-视听语言映射表》:
  4750. 6.1 场景空间与时间心理学 (Scene & Temporality)
  4751. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4752. -----|---------|------------|----------------
  4753. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  4754. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  4755. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  4756. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  4757. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  4758. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  4759. -----|---------|------------|----------------
  4760. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  4761. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  4762. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  4763. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  4764. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  4765. --------|---------|--------------|-------------
  4766. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  4767. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  4768. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  4769. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  4770. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  4771. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  4772. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  4773. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  4774. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  4775. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  4776. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  4777. -----|---------|------------|------------
  4778. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  4779. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  4780. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  4781. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  4782. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  4783. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  4784. --------|---------|--------------|----------
  4785. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  4786. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  4787. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  4788. 6.6 声音设计与潜意识影响 (Soundscape)
  4789. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  4790. -----|---------|------------|------------------
  4791. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  4792. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  4793. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  4794. 理论基石:
  4795. - The Five C's of Cinematography by Joseph V. Mascelli
  4796. - Film Art: An Introduction by David Bordwell
  4797. - Sight, Sound, Motion by Herbert Zettl
  4798. - Notes on the Cinematograph by Robert Bresson
  4799. \n\n
  4800. 7.必须严格按照以下示例格式返回剧本,不得添加其他符号
  4801. 示例格式:\n
  4802. 第1集:隐形的守护者
  4803. ###故事梗概
  4804. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  4805. ###美术风格
  4806. 基础画风风格词:韩漫二次元
  4807. 视觉风格描述:整体采用精致的韩漫厚涂风格,以浅灰冷调为基调,营造出重生复仇的清冷与压抑感。画面强调高对比度的光影处理,网吧场景通过低饱和度的杂乱色调表现颓废感,而清晨车祸瞬间则利用强烈的动态模糊与局部高光,突显“透明守护者”存在的神秘感与宿命感。人物形象细腻,眼神充满坚毅与破碎交织的故事感,完美契合偏执救赎的主题。
  4808. ###主体列表
  4809. 许芸-校服装:重生后的“假千金”,清醒果敢,不再任人唯亲。她是一名高中生,身材纤细,留着乌黑齐肩短发,眼神坚定。{18岁年轻女生,黑色长发,红色眼睛,五官精致,皮肤白皙,身材纤细,穿着日系校园制服,白色衬衫,黑色百褶裙,红色领带,表情悲伤,眼含泪水}{{甜心小美}}
  4810. 许芸-卫衣装:半个月后居家或外出时的装扮,在清冷的环境中透着一丝坚毅与破碎感。{绝美年轻女子,白色长发,金色眼睛,五官精致,皮肤白皙,身材纤细,穿着淡蓝色古风汉服,气质清冷,神情平静,高细节人物刻画}{{爽快思思}}
  4811. 程景:偏执深情的学霸,为救许芸变得“不可见”,是始终默默守护的隐形爱人。他身材高大挺拔,面容英俊。{年轻男性反派,银白色短发,红色眼睛,面容冷峻,皮肤苍白,身穿黑色长袍,嘴角冷笑,气质危险,高细节人物刻画}{{阳光青年}{{阳光青年}}
  4812. ###场景列表
  4813. 徐家老旧厨房:这是徐母劳作和惩罚许芸的地方。空间狭窄阴暗,充满了生活琐碎的压抑感。室内有一个旧式锅炉,案板上散落着面粉和包好的馄饨,光影对比强烈,凸显出家庭环境的冷酷。{影视质感。广角。
  4814. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  4815. 无人物。}
  4816. 徐家简陋客厅:半个月后冲突爆发的中心。陈设简单且陈旧,只有几把木凳和一张方桌。窗帘半掩,透进微弱的冷光,营造出一种暴风雨前的宁静与不安感。{影视质感。冷青色调,浓雾弥漫。
  4817. 一条通往西北方向的崎岖山间土路,两旁是枯萎的灌木和怪石嶙峋。地面湿滑,反光强烈。远方山峦在阴雨中若隐若现,营造出一种穷追不舍的紧张感。
  4818. 无人物。}
  4819. 老旧公寓门口:许芸逃出家门后回望的视点。门框斑驳,透出屋内昏暗压抑的光线,与室外略显空旷的走廊形成对比,象征着逃离与未知的守护。{
  4820. 豪华游轮内部宽敞的大堂或公共休息区。设计奢华,天花板高挑,有精致的装饰和柔和的暖色灯光。地面铺设着光洁的大理石,远处有巨大的落地窗,窗外是蓝色的海洋。自然光线充足,色彩明亮且饱和度适中,展现豪华游轮的质感。
  4821. 无人物。}
  4822. 破败巷弄与臭水沟:家门外的外部环境。一条狭窄、潮湿的巷弄,旁边是散发着冷气的臭水沟,水面偶尔泛起涟漪。这里是“透明守护者”受伤后经过的地方,氛围凄清。{
  4823. 宽敞明亮的现代风格客厅,家具摆放整齐,色调偏向冷灰与深蓝,营造一种沉静而略带压抑的氛围。窗外光线柔和,室内光影对比不强烈,整体干净整洁。
  4824. 无人物。}
  4825. 潮湿的巷弄地面:特写视角。灰色的水泥地面湿迹斑斑,这是许芸发现血脚印并进行最后告白的地方。强调地面的质感和清冷的基调。{
  4826. 一个现代居民小区的入口,有门卫岗亭和自动栏杆。道路宽阔,两旁绿化整齐,阳光明媚,整体色调略显冷峻,但光线清晰。
  4827. 无人物。}
  4828. ###分镜剧本
  4829. ##第1幕:徐家老旧厨房 白天 室内
  4830. 分镜1
  4831. 画面描述:许芸-校服装站在厨房门口,书包背在肩上,徐母手持扫帚,正对着许芸的背部猛烈挥打。卞大伟站在锅炉后方,双手抱胸,阴沉的目光落在许芸身上。
  4832. 场景:徐家老旧厨房
  4833. 构图设计:全景,低角度仰视
  4834. 运镜调度:手持拍摄
  4835. 配音角色:旁白
  4836. 出镜角色:许芸-校服装、徐母
  4837. 台词内容:我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,
  4838. 画面类型:普通画面
  4839. 尾帧描述:手持拍摄微晃镜头,中年妇女猛力挥动扫帚击打少女背部,少女身体因冲击微颤,阴影中的肥胖男子目光冷冷跟随。
  4840. 分镜2
  4841. 画面描述:徐母面容扭曲,嘴唇快速开合,扫帚挥舞在空中。
  4842. 场景:徐家老旧厨房
  4843. 构图设计:近景,徐母面部特写
  4844. 运镜调度:固定镜头
  4845. 配音角色:徐母
  4846. 出镜角色:徐母
  4847. 台词内容:问我夜不归宿死哪儿去了。
  4848. 画面类型:对口型
  4849. 尾帧描述:固定镜头,中年妇女面部肌肉剧烈抖动,嘴唇快速开合进行辱骂,背景中的扫帚在空中上下挥动。
  4850. ##第2幕:徐家简陋客厅 黄昏 室内
  4851. 分镜3
  4852. 画面描述:客厅窗户透出昏黄的夕阳余晖,空荡荡的客厅中央只有几把木凳和一张方桌,显得异常安静。
  4853. 场景:徐家简陋客厅
  4854. 构图设计:全景,景深虚化
  4855. 运镜调度:固定镜头
  4856. 配音角色:旁白
  4857. 出镜角色:无
  4858. 台词内容:可我没想到,半个月后,徐母居然再一次外出,
  4859. 画面类型:普通画面
  4860. 尾帧描述:固定镜头。昏黄的夕阳余晖在地面上缓慢移动,空气中的浮尘在光束中跳动,室内维持着死寂的安静。
  4861. 分镜4
  4862. 画面描述:一张泛黄的火车票特写,上面显示着隔壁市的站名和日期。
  4863. 场景:徐家简陋客厅
  4864. 构图设计:特写,火车票
  4865. 运镜调度:固定镜头
  4866. 配音角色:旁白
  4867. 出镜角色:无
  4868. 台词内容:这次是去隔壁市看望她生病的好姐妹。
  4869. 画面类型:普通画面
  4870. 尾帧描述:固定镜头。光影在火车票表面微微晃动,强调其陈旧的纸张纹理与关键的行程信息。
  4871. \n\n";
  4872. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  4873. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  4874. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  4875. $prompt = $origin_prompt;
  4876. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  4877. // 获取章节内容
  4878. $full_content = getProp($anime, 'content');
  4879. if ($uploaded_content) {
  4880. $full_content = $uploaded_content;
  4881. }
  4882. // 根据章节内容拆分章节
  4883. $chapters = $this->splitContent($full_content);
  4884. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  4885. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  4886. $messages = [];
  4887. if ($prompt == '确认分镜大纲') {
  4888. // 暂时保留
  4889. $content = $chapter_content;
  4890. if ($is_single) $content = $full_content; // 单剧集使用全文
  4891. if (!$content) {
  4892. Utils::throwError('20003:章节内容无法获取,请确认');
  4893. }
  4894. $question = $is_single
  4895. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  4896. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  4897. // 构建消息
  4898. $messages[] =
  4899. [
  4900. 'role' => 'user',
  4901. 'content' => $question
  4902. ];
  4903. }else if ($prompt == '继续策划下一集') {
  4904. if ($is_single) {
  4905. Utils::throwError('20003:单剧集不支持继续策划下一集');
  4906. }
  4907. $content = $chapter_content;
  4908. if (!$content) {
  4909. Utils::throwError('20003:章节内容无法获取,请确认');
  4910. }
  4911. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  4912. // 获取上一集最后记录
  4913. $prev_sequence = $episode_number - 1;
  4914. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  4915. // 构建消息
  4916. $messages[] =
  4917. [
  4918. 'role' => 'user',
  4919. 'content' => $question
  4920. ];
  4921. }else {
  4922. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  4923. if (!$content) {
  4924. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  4925. }
  4926. if (!$content) {
  4927. Utils::throwError('20003:章节内容无法获取,请确认');
  4928. }
  4929. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  4930. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  4931. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  4932. if ($origin_prompt) {
  4933. $question .= "\n本次修改要求如下:\n{$origin_prompt}";
  4934. }
  4935. $messages[] =
  4936. [
  4937. 'role' => 'user',
  4938. 'content' => $question
  4939. ];
  4940. }
  4941. // 处理文本模型
  4942. $model = getProp($data, 'model');
  4943. if (!$model) {
  4944. // 用户没有输入,从anime表获取
  4945. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  4946. $model = getProp($anime, 'model');
  4947. if (!$model) {
  4948. // anime表也没有,使用默认值
  4949. $model = 'doubao-seed-2-0-mini-260215';
  4950. }
  4951. }
  4952. // 验证模型是否在可用模型表中
  4953. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  4954. $model = 'doubao-seed-2-0-mini-260215';
  4955. }
  4956. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  4957. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  4958. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  4959. if ($model === 'deepseek-chat') {
  4960. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  4961. $model = 'deepseek-v4-flash';
  4962. $thinkingMode = 'disabled';
  4963. } elseif ($model === 'deepseek-reasoner') {
  4964. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  4965. $model = 'deepseek-v4-flash';
  4966. $thinkingMode = 'enabled';
  4967. }
  4968. $post_data = [
  4969. 'model' => $model,
  4970. 'messages' => $messages,
  4971. // 'max_tokens' => 8192,
  4972. 'temperature' => 0.2,
  4973. 'frequency_penalty' => 0,
  4974. 'presence_penalty' => 0,
  4975. 'response_format' => ['type' => 'text'],
  4976. 'thinking' => ['type' => $thinkingMode],
  4977. 'stream' => true // 启用流式输出
  4978. ];
  4979. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  4980. // 根据模型类型选择调用方法
  4981. $fullContent = '';
  4982. $fullReasoningContent = '';
  4983. $usage = [];
  4984. try {
  4985. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  4986. // DeepSeek 官方模型使用 DeepSeek API
  4987. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  4988. } else if (in_array($model, $this->gpt_text_models)) {
  4989. // GPT-5.4 模型使用 TokenRouter API
  4990. $streamGenerator = $this->gpt54StreamResponse($post_data);
  4991. } else {
  4992. // 其他模型使用火山引擎API
  4993. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  4994. }
  4995. // 验证返回值类型
  4996. if (!is_iterable($streamGenerator)) {
  4997. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  4998. dLog('deepseek')->error('chat流式生成器无效', [
  4999. 'generator_type' => $errorType,
  5000. 'model' => $model,
  5001. 'anime_id' => $anime_id,
  5002. 'episode_number' => $episode_number
  5003. ]);
  5004. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  5005. 'type' => $errorType,
  5006. 'model' => $model
  5007. ]);
  5008. yield [
  5009. 'type' => 'error',
  5010. 'episode' => [],
  5011. 'answer' => '',
  5012. 'reasoning' => '',
  5013. 'usage' => [],
  5014. 'error' => '接口返回数据异常,请重新请求'
  5015. ];
  5016. return;
  5017. }
  5018. // 处理流式输出
  5019. foreach ($streamGenerator as $chunk) {
  5020. if (isset($chunk['type'])) {
  5021. if ($chunk['type'] === 'done') {
  5022. // 最终结果
  5023. $fullContent = $chunk['full_content'];
  5024. $fullReasoningContent = $chunk['full_reasoning'];
  5025. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5026. } else {
  5027. // 逐块yield数据
  5028. yield $chunk;
  5029. }
  5030. }
  5031. }
  5032. } catch (\Exception $e) {
  5033. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  5034. 'model' => $model,
  5035. 'anime_id' => $anime_id,
  5036. 'episode_number' => $episode_number,
  5037. 'trace' => $e->getTraceAsString()
  5038. ]);
  5039. logDB('deepseek', 'error', 'chat流式处理失败', [
  5040. 'error' => $e->getMessage(),
  5041. 'model' => $model
  5042. ]);
  5043. yield [
  5044. 'type' => 'error',
  5045. 'episode' => [],
  5046. 'answer' => '',
  5047. 'reasoning' => '',
  5048. 'usage' => [],
  5049. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5050. ];
  5051. return;
  5052. }
  5053. dLog('deepseek')->info('完整内容: '.$fullContent);
  5054. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5055. // 处理完整内容并返回最终结果
  5056. $episode_arr = handleEpisodeContent($fullContent);
  5057. logDB('deepseek', 'info', '解析内容', $episode_arr);
  5058. if (empty($episode_arr['acts'])) {
  5059. // 未生成剧本相关内容,保存对话记录并返回提示
  5060. dLog('deepseek')->info('未生成分镜剧本相关的内容');
  5061. try {
  5062. $now = date('Y-m-d H:i:s');
  5063. // 保存对话记录
  5064. $records = [
  5065. [
  5066. 'uid' => $uid,
  5067. 'anime_id' => $anime_id,
  5068. 'sequence' => $episode_number,
  5069. 'role' => 'user',
  5070. 'content' => $prompt,
  5071. 'created_at' => $now,
  5072. 'updated_at' => $now
  5073. ],
  5074. [
  5075. 'uid' => $uid,
  5076. 'anime_id' => $anime_id,
  5077. 'sequence' => $episode_number,
  5078. 'role' => 'assistant',
  5079. 'content' => $fullContent,
  5080. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5081. 'created_at' => $now,
  5082. 'updated_at' => $now
  5083. ]
  5084. ];
  5085. DB::table('mp_anime_records')->insert($records);
  5086. } catch (\Exception $e) {
  5087. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5088. }
  5089. yield [
  5090. 'type' => 'done',
  5091. 'episode' => [],
  5092. 'answer' => $fullContent,
  5093. 'reasoning' => $fullReasoningContent,
  5094. 'usage' => $usage,
  5095. 'error' => '未生成分镜剧本相关的内容,请调整提示词再试'
  5096. ];
  5097. return;
  5098. }
  5099. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  5100. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  5101. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  5102. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  5103. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  5104. $existing_props = is_array($existing_props) ? $existing_props : [];
  5105. $now = date('Y-m-d H:i:s');
  5106. try {
  5107. DB::beginTransaction();
  5108. $saveResult = $this->saveEpisodeVersionData(
  5109. $anime_id,
  5110. $episode_number,
  5111. $episode_arr,
  5112. $existing_roles,
  5113. $existing_scenes,
  5114. $existing_props,
  5115. $current_episode,
  5116. $base_episode,
  5117. $is_regenerate_version,
  5118. $content,
  5119. $now
  5120. );
  5121. $episode = $saveResult['episode'];
  5122. $episode_id = $saveResult['episode_id'];
  5123. $merged_roles = $saveResult['merged_roles'];
  5124. $merged_scenes = $saveResult['merged_scenes'];
  5125. $merged_props = $saveResult['merged_props'];
  5126. $record_content = $origin_prompt;
  5127. if ($uploaded_content !== '') {
  5128. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  5129. }
  5130. $records = [
  5131. [
  5132. 'uid' => $uid,
  5133. 'anime_id' => $anime_id,
  5134. 'role' => 'user',
  5135. 'content' => $record_content,
  5136. 'sequence' => $episode_number,
  5137. 'episode_id' => $episode_id,
  5138. 'created_at' => $now,
  5139. 'updated_at' => $now
  5140. ],
  5141. [
  5142. 'uid' => $uid,
  5143. 'anime_id' => $anime_id,
  5144. 'role' => 'assistant',
  5145. 'content' => $fullContent,
  5146. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5147. 'sequence' => $episode_number,
  5148. 'episode_id' => $episode_id,
  5149. 'created_at' => $now,
  5150. 'updated_at' => $now
  5151. ]
  5152. ];
  5153. $boolen4 = DB::table('mp_anime_records')->insert($records);
  5154. if (!$boolen4) {
  5155. Utils::throwError('20003:对话记录保存失败');
  5156. }
  5157. // 保存模型和内容到anime表
  5158. $update_anime_data = [
  5159. 'model' => $model,
  5160. 'updated_at' => $now
  5161. ];
  5162. if ($uploaded_content) {
  5163. $update_anime_data['content'] = $uploaded_content;
  5164. }
  5165. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  5166. }catch (\Exception $e) {
  5167. DB::rollBack();
  5168. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5169. yield [
  5170. 'type' => 'done',
  5171. 'answer' => $fullContent,
  5172. 'reasoning' => $fullReasoningContent,
  5173. 'usage' => $usage,
  5174. 'error' => $e->getMessage(),
  5175. ];
  5176. return;
  5177. }
  5178. DB::commit();
  5179. if ($is_global_generate_pics) {
  5180. // // 批量生成全局角色图片
  5181. // $this->batchSetGlobalRoleImg([
  5182. // 'anime_id' => $anime_id,
  5183. // ], true);
  5184. // // 批量生成全局场景图片
  5185. // $this->batchSetGlobalSceneImg([
  5186. // 'anime_id' => $anime_id,
  5187. // ], true);
  5188. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5189. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5190. }
  5191. $episode['episode_id'] = $episode_id;
  5192. $episode['roles'] = $merged_roles;
  5193. $episode['scenes'] = $merged_scenes;
  5194. $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  5195. yield [
  5196. 'type' => 'done',
  5197. 'episode' => $episode,
  5198. 'answer' => $fullContent,
  5199. 'reasoning' => $fullReasoningContent,
  5200. 'usage' => $usage
  5201. ];
  5202. }
  5203. public function addChatForAce($data) {
  5204. $uid = Site::getUid();
  5205. $anime_id = getProp($data, 'anime_id');
  5206. if (!$anime_id) Utils::throwError('20003:请选择对话');
  5207. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  5208. if (!$anime) Utils::throwError('20003:对话不存在');
  5209. $file = getProp($data, 'file');
  5210. $content = getProp($data, 'content', '');
  5211. $bid = getProp($data, 'bid', 0);
  5212. $script_id = getProp($data, 'script_id', 0);
  5213. $ace_mode = getProp($data, 'ace_mode', 0) ? getProp($data, 'ace_mode', 0) : getProp($anime, 'ace_mode', 0);
  5214. $prompt = getProp($data, 'prompt');
  5215. $extra_products = getProp($data, 'products', []);
  5216. if (!$extra_products) {
  5217. $extra_products = getProp($anime, 'extra_products');
  5218. if ($extra_products) {
  5219. $extra_products = json_decode($extra_products, true);
  5220. }else {
  5221. $extra_products = [];
  5222. }
  5223. }else {
  5224. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  5225. }
  5226. $user_anime_name = getProp($anime, 'anime_name');
  5227. // 处理提示词
  5228. if ($prompt && $extra_products) {
  5229. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  5230. foreach($extra_products as $item) {
  5231. $product_name = getProp($item, 'product_name');
  5232. if ($product_name) {
  5233. // 替换 {product_name} 为 product_name
  5234. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  5235. }
  5236. }
  5237. }
  5238. // 处理文本模型
  5239. $model = getProp($data, 'model');
  5240. if (!$model) {
  5241. // 用户没有输入,从anime表获取
  5242. $model = getProp($anime, 'model');
  5243. if (!$model) {
  5244. // anime表也没有,使用默认值
  5245. $model = 'doubao-seed-2-0-mini-260215';
  5246. }
  5247. }
  5248. // 验证模型是否在可用模型表中
  5249. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5250. $model = 'doubao-seed-2-0-mini-260215';
  5251. }
  5252. $is_multi = getProp($anime, 'is_multi');
  5253. $is_single = (int)$is_multi !== 1;
  5254. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  5255. if ($prompt) {
  5256. $question .= "本次修改要求如下:\n{$prompt}";
  5257. }
  5258. // if (!$file && !$content && !$bid) {
  5259. // Utils::throwError('20003:请上传文件或选择书籍或输入内容');
  5260. // }
  5261. // 提取文件内容
  5262. if ($file) {
  5263. $content = $this->extractFileContent($file);
  5264. if (!$content) {
  5265. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5266. }
  5267. } elseif ($script_id) {
  5268. $content = $this->getContentByScriptId($script_id);
  5269. if (!$content) {
  5270. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5271. }
  5272. } elseif ($bid) {
  5273. $content = $this->getContentByBid($bid);
  5274. if (!$content) {
  5275. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5276. }
  5277. } elseif ($content) {
  5278. $content = filterContent($content);
  5279. } else {
  5280. $content = getProp($anime, 'content');
  5281. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  5282. $need_generate_content = true;
  5283. }
  5284. }
  5285. // 美术风格
  5286. $input_art_style = getProp($data, 'art_style');
  5287. if (!$input_art_style) {
  5288. $mappedArtStyle = getProp($anime, 'art_style');
  5289. }else {
  5290. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  5291. }
  5292. // 判断是否需要生成原文内容
  5293. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  5294. // 如果需要生成原文内容,添加额外的要求
  5295. $content_generation_requirement = $need_generate_content
  5296. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  5297. : "";
  5298. // 美术风格
  5299. if (!$mappedArtStyle) {
  5300. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  5301. }else {
  5302. if (strstr($mappedArtStyle, '基础画风风格词')) {
  5303. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  5304. }else {
  5305. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  5306. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  5307. }
  5308. }
  5309. // 构建主体和场景提示词
  5310. $extra_role_prompt = "\n";
  5311. $extra_scene_prompt = "\n";
  5312. $ref_products = []; // 参考资产
  5313. if ($extra_products) {
  5314. foreach($extra_products as $item) {
  5315. $product = getProp($item, 'product');
  5316. $product_name = getProp($item, 'product_name');
  5317. if ($product_name == '旁白') continue;
  5318. $ref_products[$product_name] = $item;
  5319. $pic_prompt = getProp($item, 'pic_prompt');
  5320. if ((int)$product === 1) {
  5321. // 拼接角色信息
  5322. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5323. } elseif ((int)$product === 2) {
  5324. // 拼接场景信息
  5325. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  5326. }
  5327. }
  5328. // 优化提示词,融入剧本
  5329. if (!empty(trim($extra_role_prompt))) {
  5330. $extra_role_prompt = "\n2.5【强制主体设定-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  5331. }
  5332. if (!empty(trim($extra_scene_prompt))) {
  5333. $extra_scene_prompt = "\n3.4【强制场景设定-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  5334. }
  5335. }
  5336. $systemPrompt = $is_single
  5337. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  5338. 强制要求:
  5339. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5340. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5341. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5342. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5343. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5344. 普通要求:
  5345. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  5346. 3.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5347. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5348. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5349. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5350. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5351. {$extra_role_prompt}
  5352. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5353. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5354. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5355. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5356. {$extra_scene_prompt}
  5357. 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  5358. 4.1片段分割逻辑(优先级从高到低):
  5359. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  5360. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  5361. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  5362. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  5363. 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  5364. - 片段数量格式为: 片段数量:8
  5365. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5366. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  5367. 4.3分镜结构:每个分镜包含以下字段:
  5368. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  5369. - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  5370. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  5371. - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  5372. - 运镜:场景+画面描述+运镜
  5373. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  5374. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  5375. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  5376. 5.{$mappedArtStyle_prompt}\n\n
  5377. 示例如下:\n
  5378. ###剧本名:西昆仑
  5379. ###故事梗概
  5380. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5381. ###剧本亮点
  5382. 亮点1:绝境奇药,生死一线
  5383. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5384. 亮点2:结拜兄妹,化解尴尬
  5385. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5386. 亮点3:纤发夺命,情愫暗涌
  5387. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5388. ###人物关系
  5389. 阿雪与梁萧之间存在兄妹之情。
  5390. ###核心矛盾
  5391. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5392. ###主体列表
  5393. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5394. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5395. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5396. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5397. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5398. 全景,正面拍摄,青年女性,亚洲人。
  5399. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5400. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5401. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5402. ###美术风格
  5403. 基础画风风格词:厚涂古风
  5404. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5405. ###场景列表
  5406. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5407. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5408. 无人物。}
  5409. ###分段剧本
  5410. 片段数量:8
  5411. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  5412. ##片段1
  5413. 时长:12s
  5414. 分镜1
  5415. 场景:边境小镇街道
  5416. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  5417. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  5418. 配音台词:
  5419. 背景音效:
  5420. 分镜2
  5421. 场景:悦来酒馆
  5422. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  5423. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  5424. 配音台词:
  5425. 背景音效:
  5426. 分镜3
  5427. 场景:悦来酒馆
  5428. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  5429. 运镜:从中景推向令牌特写。
  5430. 配音台词:
  5431. 背景音效:
  5432. 分镜4
  5433. 场景:悦来酒馆
  5434. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  5435. 运镜:极速推向酒水溅起的瞬间。
  5436. 配音台词:
  5437. 背景音效:
  5438. 分镜5
  5439. 镜头描述
  5440. 场景:悦来酒馆
  5441. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  5442. 运镜:固定机位,利用倾斜构图制造压迫感。
  5443. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  5444. 背景音效:
  5445. \n\n"
  5446. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  5447. 强制要求:\n
  5448. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  5449. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  5450. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  5451. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  5452. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  5453. 普通要求:\n
  5454. 1.剧本名(必须生成)必须与文档内容高度相关
  5455. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  5456. 2.1<主体列表>分以下三部分(强制格式):主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  5457. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  5458. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  5459. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  5460. {$extra_role_prompt}
  5461. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  5462. 3.1<场景列表>分以下两部分(强制格式):场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  5463. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  5464. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  5465. {$extra_scene_prompt}
  5466. 4.{$mappedArtStyle_prompt}\n\n
  5467. 示例如下:\n
  5468. ###剧本名:西昆仑
  5469. ###故事梗概
  5470. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  5471. ###剧本亮点
  5472. 亮点1:绝境奇药,生死一线
  5473. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  5474. 亮点2:结拜兄妹,化解尴尬
  5475. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  5476. 亮点3:纤发夺命,情愫暗涌
  5477. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  5478. ###人物关系
  5479. 阿雪与梁萧之间存在兄妹之情。
  5480. ###核心矛盾
  5481. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  5482. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5483. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  5484. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  5485. ###主体列表
  5486. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  5487. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  5488. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  5489. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  5490. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  5491. 全景,正面拍摄,青年女性,亚洲人。
  5492. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  5493. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  5494. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  5495. ###美术风格
  5496. 基础画风风格词:厚涂古风
  5497. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  5498. ###场景列表
  5499. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  5500. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  5501. 无人物。}";
  5502. // 构建消息
  5503. $messages = [
  5504. [
  5505. 'role' => 'system',
  5506. 'content' => $systemPrompt
  5507. ],
  5508. [
  5509. 'role' => 'user',
  5510. 'content' => "以下是文档内容:
  5511. {$content}
  5512. 用户问题:
  5513. {$question}"
  5514. ]
  5515. ];
  5516. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  5517. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  5518. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  5519. if ($model === 'deepseek-chat') {
  5520. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  5521. $model = 'deepseek-v4-flash';
  5522. $thinkingMode = 'disabled';
  5523. } elseif ($model === 'deepseek-reasoner') {
  5524. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  5525. $model = 'deepseek-v4-flash';
  5526. $thinkingMode = 'enabled';
  5527. }
  5528. $post_data = [
  5529. 'model' => $model,
  5530. 'messages' => $messages,
  5531. // 'max_tokens' => 8192,
  5532. 'temperature' => 0.7,
  5533. 'frequency_penalty' => 0,
  5534. 'presence_penalty' => 0,
  5535. 'response_format' => ['type' => 'text'],
  5536. 'thinking' => ['type'=>$thinkingMode],
  5537. 'stream' => true // 启用流式输出
  5538. ];
  5539. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  5540. // 根据模型类型选择调用方法
  5541. $fullContent = '';
  5542. $fullReasoningContent = '';
  5543. $usage = [];
  5544. try {
  5545. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  5546. // DeepSeek 官方模型使用 DeepSeek API
  5547. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  5548. } else if (in_array($model, $this->gpt_text_models)) {
  5549. // GPT-5.4 模型使用 TokenRouter API
  5550. $streamGenerator = $this->gpt54StreamResponse($post_data);
  5551. } else {
  5552. // 其他模型使用火山引擎API
  5553. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  5554. }
  5555. // 验证返回值类型
  5556. if (!is_iterable($streamGenerator)) {
  5557. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  5558. dLog('deepseek')->error('addChat流式生成器无效', [
  5559. 'generator_type' => $errorType,
  5560. 'model' => $model,
  5561. 'anime_id' => $anime_id
  5562. ]);
  5563. logDB('deepseek', 'error', 'addChat流式生成器类型错误', [
  5564. 'type' => $errorType,
  5565. 'model' => $model
  5566. ]);
  5567. yield [
  5568. 'type' => 'error',
  5569. 'script' => [],
  5570. 'episode' => [],
  5571. 'answer' => '',
  5572. 'reasoning' => '',
  5573. 'usage' => [],
  5574. 'error' => '接口返回数据异常,请重新请求'
  5575. ];
  5576. return;
  5577. }
  5578. // 处理流式输出
  5579. foreach ($streamGenerator as $chunk) {
  5580. if (isset($chunk['type'])) {
  5581. if ($chunk['type'] === 'done') {
  5582. // 最终结果
  5583. $fullContent = $chunk['full_content'];
  5584. $fullReasoningContent = $chunk['full_reasoning'];
  5585. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  5586. } else {
  5587. // 逐块yield数据
  5588. yield $chunk;
  5589. }
  5590. }
  5591. }
  5592. } catch (\Exception $e) {
  5593. dLog('deepseek')->error('addChat流式处理异常: ' . $e->getMessage(), [
  5594. 'model' => $model,
  5595. 'anime_id' => $anime_id,
  5596. 'trace' => $e->getTraceAsString()
  5597. ]);
  5598. logDB('deepseek', 'error', 'addChat流式处理失败', [
  5599. 'error' => $e->getMessage(),
  5600. 'model' => $model
  5601. ]);
  5602. yield [
  5603. 'type' => 'error',
  5604. 'script' => [],
  5605. 'episode' => [],
  5606. 'answer' => '',
  5607. 'reasoning' => '',
  5608. 'usage' => [],
  5609. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  5610. ];
  5611. return;
  5612. }
  5613. dLog('deepseek')->info('完整内容: '.$fullContent);
  5614. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  5615. // 处理完整内容并返回最终结果
  5616. $script_arr = [];
  5617. if ($fullContent) {
  5618. $script_arr = handleScriptContentForAce($fullContent);
  5619. dLog('deepseek')->info('解析内容', $script_arr);
  5620. logDB('deepseek', 'info', '解析内容', $script_arr);
  5621. }
  5622. if (empty($script_arr['roles'])) {
  5623. // 未生成剧本相关内容,保存对话记录并返回提示
  5624. dLog('deepseek')->info('未生成剧本相关的内容');
  5625. try {
  5626. DB::beginTransaction();
  5627. $now = date('Y-m-d H:i:s');
  5628. // 保存对话记录
  5629. $records = [
  5630. [
  5631. 'uid' => $uid,
  5632. 'anime_id' => $anime_id,
  5633. 'sequence' => 0,
  5634. 'role' => 'user',
  5635. 'content' => $prompt,
  5636. 'created_at' => $now,
  5637. 'updated_at' => $now
  5638. ],
  5639. [
  5640. 'uid' => $uid,
  5641. 'anime_id' => $anime_id,
  5642. 'sequence' => 0,
  5643. 'role' => 'assistant',
  5644. // 'content' => $fullContent,
  5645. 'content' => '未生成剧本相关的内容,请调整提示词再试',
  5646. 'created_at' => $now,
  5647. 'updated_at' => $now
  5648. ]
  5649. ];
  5650. DB::table('mp_anime_records')->insert($records);
  5651. DB::commit();
  5652. } catch (\Exception $e) {
  5653. DB::rollBack();
  5654. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5655. }
  5656. yield [
  5657. 'type' => 'done',
  5658. 'script' => [],
  5659. 'episode' => [],
  5660. 'answer' => $fullContent,
  5661. 'reasoning' => $fullReasoningContent,
  5662. 'usage' => $usage,
  5663. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  5664. ];
  5665. return;
  5666. }
  5667. // 如果需要生成原文内容,从script_arr中提取
  5668. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  5669. $content = $script_arr['content'];
  5670. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($content)]);
  5671. if (!$content) {
  5672. yield [
  5673. 'type' => 'done',
  5674. 'script' => [],
  5675. 'episode' => [],
  5676. 'answer' => $fullContent,
  5677. 'reasoning' => $fullReasoningContent,
  5678. 'usage' => $usage,
  5679. 'error' => '未生成剧本内容,请调整提示词再试'
  5680. ];
  5681. return;
  5682. }
  5683. }
  5684. // 替换美术风格
  5685. if ($mappedArtStyle !== '') {
  5686. $script_arr['art_style'] = $mappedArtStyle;
  5687. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  5688. }
  5689. // 新建动漫
  5690. if ($user_anime_name == '新剧本策划') {
  5691. $anime_name = getProp($script_arr, 'script_name');
  5692. // if (!$anime_name) {
  5693. // // 未识别到剧本名,保存对话记录并返回提示
  5694. // dLog('deepseek')->info('未能识别到剧本名称');
  5695. // try {
  5696. // DB::beginTransaction();
  5697. // $now = date('Y-m-d H:i:s');
  5698. // // 保存对话记录
  5699. // $records = [
  5700. // [
  5701. // 'uid' => $uid,
  5702. // 'anime_id' => $anime_id,
  5703. // 'sequence' => 0,
  5704. // 'role' => 'user',
  5705. // 'content' => $prompt,
  5706. // 'created_at' => $now,
  5707. // 'updated_at' => $now
  5708. // ],
  5709. // [
  5710. // 'uid' => $uid,
  5711. // 'anime_id' => $anime_id,
  5712. // 'sequence' => 0,
  5713. // 'role' => 'assistant',
  5714. // 'content' => '未能生成剧本名称,请重试',
  5715. // 'created_at' => $now,
  5716. // 'updated_at' => $now
  5717. // ]
  5718. // ];
  5719. // DB::table('mp_anime_records')->insert($records);
  5720. // DB::commit();
  5721. // } catch (\Exception $e) {
  5722. // DB::rollBack();
  5723. // dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  5724. // }
  5725. // yield [
  5726. // 'type' => 'done',
  5727. // 'script' => [],
  5728. // 'episode' => [],
  5729. // 'answer' => $fullContent,
  5730. // 'reasoning' => $fullReasoningContent,
  5731. // 'usage' => $usage,
  5732. // 'error' => '未能识别到剧本名称,请调整提示词再试'
  5733. // ];
  5734. // return;
  5735. // }
  5736. // 确认对话名称唯一性
  5737. if ($anime_name && DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  5738. $anime_name = $anime_name . '_' . date('YmdHis');
  5739. }
  5740. }else {
  5741. $anime_name = $user_anime_name;
  5742. }
  5743. $table_data = [
  5744. 'user_id' => $uid,
  5745. 'anime_name' => $anime_name,
  5746. 'model' => $model,
  5747. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  5748. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  5749. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  5750. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  5751. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  5752. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  5753. 'art_style_type' => $input_art_style,
  5754. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  5755. 'status' => '解析完成',
  5756. 'content' => $content,
  5757. 'is_multi' => $is_multi,
  5758. 'ace_mode' => $ace_mode,
  5759. 'generate_status' => '待执行',
  5760. 'updated_at' => date('Y-m-d H:i:s')
  5761. ];
  5762. if ($table_data['content']) {
  5763. $chapters = $this->splitContent($table_data['content']);
  5764. $chapter_count = count($chapters);
  5765. if ($chapter_count > 0) {
  5766. $table_data['start_episode_sequence'] = 1;
  5767. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  5768. }
  5769. }
  5770. if ($extra_products) {
  5771. $table_data['extra_products'] = json_encode($extra_products, 256);
  5772. }
  5773. // 如果有剧本ID则进行绑定
  5774. if ($script_id) {
  5775. $table_data['script_id'] = $script_id;
  5776. }
  5777. $single_episode = [];
  5778. try {
  5779. DB::beginTransaction();
  5780. $now = date('Y-m-d H:i:s');
  5781. // 更新动漫大纲
  5782. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  5783. if (!$boolen) {
  5784. dLog('deepseek')->info('动漫保存失败', $table_data);
  5785. Utils::throwError('20003:动漫保存失败');
  5786. }
  5787. // 保存对话记录
  5788. $records = [
  5789. [
  5790. 'uid' => $uid,
  5791. 'anime_id' => $anime_id,
  5792. 'sequence' => 0,
  5793. 'role' => 'user',
  5794. 'content' => $prompt,
  5795. 'created_at' => date('Y-m-d H:i:s'),
  5796. 'updated_at' => date('Y-m-d H:i:s')
  5797. ],
  5798. [
  5799. 'uid' => $uid,
  5800. 'anime_id' => $anime_id,
  5801. 'sequence' => 0,
  5802. 'role' => 'assistant',
  5803. 'content' => $fullContent,
  5804. 'created_at' => date('Y-m-d H:i:s'),
  5805. 'updated_at' => date('Y-m-d H:i:s')
  5806. ]
  5807. ];
  5808. // 保存对话记录
  5809. $boolen3 = DB::table('mp_anime_records')->insert($records);
  5810. if (!$boolen3) {
  5811. Utils::throwError('20003:对话记录保存失败');
  5812. }
  5813. if ($is_single) {
  5814. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  5815. if (empty($episode_arr['acts'])) {
  5816. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  5817. }
  5818. $saveResult = $this->saveEpisodeVersionData(
  5819. $anime_id,
  5820. 1,
  5821. $episode_arr,
  5822. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  5823. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  5824. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  5825. null,
  5826. null,
  5827. false,
  5828. $content,
  5829. $now,
  5830. $ref_products
  5831. );
  5832. $single_episode = $saveResult['episode'];
  5833. $episode_id = $saveResult['episode_id'];
  5834. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  5835. 'roles' => json_encode($saveResult['merged_roles'], 256),
  5836. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  5837. 'updated_at' => $now
  5838. ]);
  5839. if ($boolen5 === false) {
  5840. Utils::throwError('20003:单剧集主表资源同步失败');
  5841. }
  5842. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  5843. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  5844. $episode_record_content = '确认分镜大纲';
  5845. if ($content !== '') {
  5846. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  5847. }
  5848. $episode_records = [
  5849. [
  5850. 'uid' => $uid,
  5851. 'anime_id' => $anime_id,
  5852. 'role' => 'user',
  5853. 'content' => $episode_record_content,
  5854. 'sequence' => 1,
  5855. 'episode_id' => $episode_id,
  5856. 'created_at' => $now,
  5857. 'updated_at' => $now
  5858. ],
  5859. [
  5860. 'uid' => $uid,
  5861. 'anime_id' => $anime_id,
  5862. 'role' => 'assistant',
  5863. 'content' => $fullContent,
  5864. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  5865. 'sequence' => 1,
  5866. 'episode_id' => $episode_id,
  5867. 'created_at' => $now,
  5868. 'updated_at' => $now
  5869. ]
  5870. ];
  5871. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  5872. if (!$boolen4) {
  5873. Utils::throwError('20003:单剧集分镜记录保存失败');
  5874. }
  5875. }
  5876. }catch (\Exception $e) {
  5877. DB::rollBack();
  5878. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  5879. yield [
  5880. 'type' => 'done',
  5881. 'answer' => $fullContent,
  5882. 'reasoning' => $fullReasoningContent,
  5883. 'usage' => $usage,
  5884. 'error' => $e->getMessage(),
  5885. ];
  5886. return;
  5887. }
  5888. DB::commit();
  5889. dLog('deepseek')->info('保存完毕');
  5890. if ($is_single && !empty($single_episode)) {
  5891. // $this->batchSetGlobalRoleImg([
  5892. // 'anime_id' => $anime_id,
  5893. // ]);
  5894. // $this->batchSetGlobalSceneImg([
  5895. // 'anime_id' => $anime_id,
  5896. // ]);
  5897. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  5898. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  5899. }
  5900. $table_data['anime_id'] = $anime_id;
  5901. $table_data['roles'] = json_decode($table_data['roles'], true);
  5902. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  5903. // $table_data['episodes'] = $script_arr['episodes'];
  5904. unset($table_data['created_at']);
  5905. unset($table_data['updated_at']);
  5906. unset($table_data['status']);
  5907. dLog('deepseek')->info('开始返回');
  5908. yield [
  5909. 'type' => 'done',
  5910. 'script' => $table_data,
  5911. 'episode' => $single_episode,
  5912. 'answer' => $fullContent,
  5913. 'reasoning' => $fullReasoningContent,
  5914. 'usage' => $usage
  5915. ];
  5916. }
  5917. public function reGenerateAnimeForAce($data) {
  5918. $uid = Site::getUid();
  5919. $file = getProp($data, 'file');
  5920. $content = getProp($data, 'content', '');
  5921. $bid = getProp($data, 'bid', 0);
  5922. $script_id = getProp($data, 'script_id', 0);
  5923. $anime_id = getProp($data, 'anime_id');
  5924. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  5925. if (!$anime) {
  5926. Utils::throwError('20003:该对话不存在');
  5927. }
  5928. $extra_products = getProp($data, 'products', []);
  5929. if (!$extra_products) {
  5930. $extra_products = getProp($anime, 'extra_products');
  5931. if ($extra_products) {
  5932. $extra_products = json_decode($extra_products, true);
  5933. }else {
  5934. $extra_products = [];
  5935. }
  5936. }else {
  5937. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  5938. }
  5939. $user_anime_name = getProp($anime, 'anime_name');
  5940. $prompt = getProp($data, 'prompt');
  5941. // 处理提示词
  5942. if ($prompt && $extra_products) {
  5943. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  5944. foreach($extra_products as $item) {
  5945. $product_name = getProp($item, 'product_name');
  5946. if ($product_name) {
  5947. // 替换 {product_name} 为 product_name
  5948. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  5949. }
  5950. }
  5951. }
  5952. // 处理文本模型
  5953. $model = getProp($data, 'model');
  5954. if (!$model) {
  5955. // 用户没有输入,从anime表获取
  5956. $model = getProp($anime, 'model');
  5957. if (!$model) {
  5958. // anime表也没有,使用默认值
  5959. $model = 'doubao-seed-2-0-mini-260215';
  5960. }
  5961. }
  5962. // 验证模型是否在可用模型表中
  5963. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  5964. $model = 'doubao-seed-2-0-mini-260215';
  5965. }
  5966. $is_multi = getProp($anime, 'is_multi', 1);
  5967. $is_single = (int)$is_multi !== 1;
  5968. // 单剧集模式下,如果已经生成了剧集,则不允许继续调整大纲
  5969. if ($is_single) {
  5970. $episode_exists = DB::table('mp_anime_episodes')
  5971. ->where('anime_id', $anime_id)
  5972. ->where('sequence', 1)
  5973. ->exists();
  5974. if ($episode_exists) {
  5975. Utils::throwError('20003:单剧集模式下已生成剧集,不可继续调整大纲,请去策划剧集');
  5976. }
  5977. }
  5978. $question = getProp($data, 'question', $is_single ? "请根据实例格式完成单剧集剧本及分段\n" : "请根据实例格式完成剧本大纲\n");
  5979. if ($prompt) {
  5980. $question .= "本次修改要求如下:\n{$prompt}";
  5981. }
  5982. // 提取文件内容
  5983. if ($file) {
  5984. $content = $this->extractFileContent($file);
  5985. if (!$content) {
  5986. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  5987. }
  5988. } elseif ($script_id) {
  5989. $content = $this->getContentByScriptId($script_id);
  5990. if (!$content) {
  5991. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  5992. }
  5993. } elseif ($bid) {
  5994. $content = $this->getContentByBid($bid);
  5995. if (!$content) {
  5996. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  5997. }
  5998. } elseif ($content) {
  5999. $content = filterContent($content);
  6000. }else {
  6001. $content = filterContent(getProp($anime, 'content'));
  6002. if (!$content && $prompt) { // 如果动漫记录中没有内容则根据提示词生成
  6003. $need_generate_content = true;
  6004. }
  6005. }
  6006. // 判断是否需要生成原文内容
  6007. $need_generate_content = isset($need_generate_content) && $need_generate_content;
  6008. // 如果需要生成原文内容,添加额外的要求
  6009. $content_generation_requirement = $need_generate_content
  6010. ? "\n5.如果用户只提供了创作要求而没有提供具体文档内容,你需要根据要求创作完整的原文内容(小说形式,包含对话和叙述),并将原文内容放在最后一个板块###原文内容中输出。原文内容应该详细、生动,如果用户没有明确生成的字数,则字数不少于1000字。"
  6011. : "";
  6012. // 美术风格
  6013. $input_art_style = getProp($data, 'art_style');
  6014. if (!$input_art_style) {
  6015. $mappedArtStyle = getProp($anime, 'art_style');
  6016. }else {
  6017. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6018. }
  6019. if (!$mappedArtStyle) {
  6020. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6021. }else {
  6022. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6023. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6024. }else {
  6025. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  6026. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  6027. }
  6028. }
  6029. // 构建主体和场景提示词
  6030. $extra_role_prompt = "\n";
  6031. $extra_scene_prompt = "\n";
  6032. $ref_products = []; // 参考资产
  6033. if ($extra_products) {
  6034. foreach($extra_products as $item) {
  6035. $product = getProp($item, 'product');
  6036. $product_name = getProp($item, 'product_name');
  6037. if ($product_name == '旁白') continue;
  6038. $ref_products[$product_name] = $item;
  6039. $pic_prompt = getProp($item, 'pic_prompt');
  6040. if ((int)$product === 1) {
  6041. // 拼接角色信息
  6042. $extra_role_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6043. } elseif ((int)$product === 2) {
  6044. // 拼接场景信息
  6045. $extra_scene_prompt .= $product_name . ":" . $pic_prompt . "\n";
  6046. }
  6047. }
  6048. // 优化提示词,融入剧本
  6049. if (!empty(trim($extra_role_prompt))) {
  6050. $extra_role_prompt = "\n2.5【强制主体设定-不可修改】\n以下主体必须全部出现在<主体列表>中,必须包含:\n" . $extra_role_prompt . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6051. }
  6052. if (!empty(trim($extra_scene_prompt))) {
  6053. $extra_scene_prompt = "\n3.4【强制场景设定-不可修改】\n以下场景必须全部出现在<场景列表>中,必须包含:\n" . $extra_scene_prompt . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成符合<普通要求3.2>的场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n必须包含的场景列表:\n" . $extra_scene_prompt . "\n【重要提示】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6054. }
  6055. }
  6056. $system_message = ['role'=>'system', 'content'=>$is_single
  6057. ? "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容输出单剧集完整策划稿(剧本大纲包括: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分镜剧本>,每个板块之间必须使用###分隔,#不能多也不能少)。单剧集模式下,必须一次性输出可直接保存的大纲与完整分镜,不允许只输出大纲。
  6058. 强制要求:
  6059. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6060. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6061. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6062. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6063. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6064. 普通要求:
  6065. 1.剧本名(必须生成)和剧集标题必须与文档内容高度相关,(其中剧集序号是1)。
  6066. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6067. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6068. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6069. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6070. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6071. {$extra_role_prompt}
  6072. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6073. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6074. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6075. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6076. {$extra_scene_prompt}
  6077. 3.$mappedArtStyle_prompt\n\n
  6078. 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  6079. 4.1片段分割逻辑(优先级从高到低):
  6080. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  6081. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  6082. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  6083. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  6084. 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  6085. - 片段数量格式为: 片段数量:8
  6086. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6087. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  6088. 4.3分镜结构:每个分镜包含以下字段:
  6089. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  6090. - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  6091. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  6092. - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  6093. - 运镜:场景+画面描述+运镜
  6094. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  6095. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  6096. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声\n
  6097. 示例如下:\n
  6098. ###剧本名:西昆仑
  6099. ###故事梗概
  6100. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6101. ###剧本亮点
  6102. 亮点1:绝境奇药,生死一线
  6103. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6104. 亮点2:结拜兄妹,化解尴尬
  6105. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6106. 亮点3:纤发夺命,情愫暗涌
  6107. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6108. ###人物关系
  6109. 阿雪与梁萧之间存在兄妹之情。
  6110. ###核心矛盾
  6111. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6112. ###主体列表
  6113. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6114. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6115. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6116. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6117. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6118. 全景,正面拍摄,青年女性,亚洲人。
  6119. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6120. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6121. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6122. ###美术风格
  6123. 基础画风风格词:厚涂古风
  6124. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6125. ###场景列表
  6126. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6127. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6128. 无人物。}
  6129. ###分段剧本
  6130. 片段数量:8
  6131. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  6132. ##片段1
  6133. 时长:12s
  6134. 分镜1
  6135. 场景:边境小镇街道
  6136. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  6137. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  6138. 配音台词:
  6139. 背景音效:
  6140. 分镜2
  6141. 场景:悦来酒馆
  6142. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  6143. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  6144. 配音台词:
  6145. 背景音效:
  6146. 分镜3
  6147. 场景:悦来酒馆
  6148. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  6149. 运镜:从中景推向令牌特写。
  6150. 配音台词:
  6151. 背景音效:
  6152. 分镜4
  6153. 场景:悦来酒馆
  6154. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  6155. 运镜:极速推向酒水溅起的瞬间。
  6156. 配音台词:
  6157. 背景音效:
  6158. 分镜5
  6159. 镜头描述
  6160. 场景:悦来酒馆
  6161. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  6162. 运镜:固定机位,利用倾斜构图制造压迫感。
  6163. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  6164. 背景音效:
  6165. \n\n"
  6166. : "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6167. 强制要求:\n
  6168. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6169. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6170. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6171. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6172. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6173. 普通要求:\n
  6174. 1.剧本名(必须生成)必须与文档内容高度相关
  6175. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6176. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6177. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6178. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6179. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6180. {$extra_role_prompt}
  6181. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6182. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词}
  6183. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6184. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6185. {$extra_scene_prompt}
  6186. 4.$mappedArtStyle_prompt\n\n
  6187. 示例如下:\n
  6188. ###剧本名:西昆仑
  6189. ###故事梗概
  6190. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6191. ###剧本亮点
  6192. 亮点1:绝境奇药,生死一线
  6193. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6194. 亮点2:结拜兄妹,化解尴尬
  6195. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6196. 亮点3:纤发夺命,情愫暗涌
  6197. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6198. ###人物关系
  6199. 阿雪与梁萧之间存在兄妹之情。
  6200. ###核心矛盾
  6201. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6202. ###主体列表
  6203. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6204. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6205. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6206. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6207. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6208. 全景,正面拍摄,青年女性,亚洲人。
  6209. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6210. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6211. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6212. ###美术风格
  6213. 基础画风风格词:厚涂古风
  6214. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6215. ###场景列表
  6216. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6217. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6218. 无人物。}"];
  6219. // 如果提示词$prompt有类似于改成N集或调整成N集这类的文字信息,则提取出N这个集数
  6220. $episode_count = $this->extractEpisodeNumber($prompt);
  6221. if ((int)getProp($anime, 'is_multi') !== 1) {
  6222. yield [
  6223. 'type' => 'done',
  6224. 'answer' => '当前剧本是单剧集,不支持修改剧集数',
  6225. 'reasoning' => '',
  6226. 'usage' => []
  6227. ];
  6228. return;
  6229. }
  6230. if ($episode_count) {
  6231. $question = "请根据实例格式完成{$episode_count}集剧本大纲";
  6232. $system_message = [
  6233. 'role' => 'system',
  6234. 'content' => "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容及下面提供的示例格式完成剧本大纲(需通过以下几个板块进行回复: <故事梗概><剧本亮点><人物关系><核心矛盾><主体列表><美术风格><场景列表><分集详细内容>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  6235. 强制要求:\n
  6236. 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  6237. 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  6238. 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  6239. 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求{$content_generation_requirement}
  6240. 5.强制按照示例格式返回内容,不要更改格式或随意增加符号\n
  6241. 普通要求:\n
  6242. 1.<故事梗概>控制在200-300字左右
  6243. 2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6244. 2.1<主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6245. 2.2<主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能,并且用一句话进行总结。
  6246. 2.3<主体列表>的人物提示词需要根据当前分析出来的美术风格生成,包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6247. 2.4<主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  6248. 3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6249. 3.1<场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6250. 3.2<场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6251. 3.3<场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。\n
  6252. 4.<分集详细内容>中每一集的内容需尽可能的详细,保留对话内容(使用原文内容,不得自己生成),一般每集字数尽量不低于500字,每集结尾需以##第N章 作为章节标题\n\n
  6253. 示例如下:\n
  6254. ###剧本名:西昆仑
  6255. ###故事梗概
  6256. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  6257. ###剧本亮点
  6258. 亮点1:绝境奇药,生死一线
  6259. 画面开场即是阿雪苍白无力的脸庞,梁萧眼中泪光闪烁,急促的呼吸声与心跳声烘托紧张气氛。特写梁萧将“阴阳球”塞入阿雪舌底,球体散发微光,阿雪气息从若有若无到逐渐平稳,生死逆转的瞬间,视觉与听觉冲击力十足。
  6260. 亮点2:结拜兄妹,化解尴尬
  6261. 阿雪因解衣拔刺而羞愤欲绝的特写,梁萧眼神中的挣扎与无奈。在紧迫的背景音下,梁萧急中生智,牵起阿雪颤抖的手,跪地匆匆结拜,阿雪眼神从惊惶到迷茫,最终一句“我……我愿意的”带着哭腔,将救命与羞耻的矛盾推向高潮,又以出人意料的方式解决。
  6262. 亮点3:纤发夺命,情愫暗涌
  6263. 拔刺过程的紧张特写,梁萧指尖小心翼翼地捏住细丝,缓慢抽出。当“问心刺”被完全拔出,特写它竟是一根细长、泛着寒光的女子秀发,诡异而令人震惊。阿雪苏醒后,两人眼神交汇,阿雪低头羞涩,梁萧眼中复杂的情绪,无声地传递出超越兄妹的微妙情愫。
  6264. ###人物关系
  6265. 阿雪与梁萧之间存在兄妹之情。
  6266. ###核心矛盾
  6267. 阿雪与梁萧之间存在兄妹之情,但因情愫暗生而产生微妙的矛盾。阿雪羞涩难当,梁萧情急之下提出结拜兄妹,以化解尴尬。两人匆匆结拜后,梁萧小心翼翼地拔出“问心刺”,竟发现它是一根诡异的女子秀发。阿雪转危为安,两人之间,在生死与羞涩交织的瞬间,情愫暗生,却又被兄妹之名束缚,留下无尽遐想。
  6268. ###主体列表
  6269. 阿雪:身中奇毒“问心刺”,气息奄奄,面色苍白,身体虚弱。{全景,正面拍摄,青年女性,亚洲人。
  6270. 黑色短发扎成利落的高马尾,五官精致且轮廓清晰。
  6271. 服饰穿搭:身着红白相间的专业田径运动背心与超短跑步裤,皮肤呈现健康的小麦色,四肢肌肉线条紧致有力。
  6272. 姿态:站立。}{{青年女性(约25-30岁),音色亲切、温柔,语速平稳缓慢}}
  6273. 梁萧:少年侠士,心系阿雪安危,沉着冷静,内心挣扎于情义之间。{8k超高清,电影级光效,大气透视,中国传统艺术美学,空灵光泽,深度景深,复杂精细的纹理,史诗级构图,电影胶片颗粒。
  6274. 全景,正面拍摄,青年女性,亚洲人。
  6275. 佩戴精致繁复的金丝凤冠,黑色长发整齐盘起。
  6276. 服饰穿搭:身着大红色正装嫁衣,上面绣有精细的金色凤凰纹样,质感厚重华贵。
  6277. 姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  6278. ###美术风格
  6279. 基础画风风格词:厚涂古风
  6280. 整体采用精致细腻的厚涂古风,色彩浓郁而富有层次感,注重光影对比,营造出古典而富有戏剧张力的氛围。色调以深沉的蓝绿、灰调为主,衬托阿雪病弱的苍白,同时用温暖的金色、琥珀色光晕突出“阴阳球”的生命力。拔刺与结拜场景则以柔和的暖色调为主,辅以人物脸颊的红晕,烘托羞涩与情愫暗生的微妙感。人物造型飘逸,服饰细节考究,背景虚实结合,既有古韵,又不失奇幻色彩。
  6281. ###场景列表
  6282. 林间疗伤地:幽静的古风林间空地,一棵高大古树下,是梁萧为阿雪疗伤的地点。环境清幽,光影斑驳,既有古韵又不失奇幻色彩。{影视质感。广角。
  6283. 宽敞的天然山洞内部,石壁上错落有致地镶嵌着发光的萤石,散发出冷色调的微光,照亮了整个空间。洞顶有钟乳石垂下。光影层次丰富,营造出一种宁静而神圣的氛围。
  6284. 无人物。}
  6285. ###分集详细内容
  6286. ##第1章 重生
  6287. 我重生了。
  6288. 源于一个男人偏执的暗恋。
  6289. ##第2章 相救
  6290. 我一到家,徐母的扫帚就落在我身上,嘴里一个劲地骂我,问我夜不归宿死哪儿去了。
  6291. 我眼睛扫向站在锅炉后的卞大伟。"
  6292. ];
  6293. // 构建消息
  6294. $messages = [
  6295. $system_message,
  6296. [
  6297. 'role' => 'user',
  6298. 'content' => "以下是文档内容:
  6299. {$content}
  6300. 用户问题:
  6301. {$question}"
  6302. ]
  6303. ];
  6304. }else {
  6305. if (strstr($prompt, '重新生成') || strstr($prompt, '再生成')) {
  6306. // 构建消息
  6307. $messages = [
  6308. $system_message,
  6309. [
  6310. 'role' => 'user',
  6311. 'content' => "以下是文档内容:
  6312. {$content}
  6313. 用户问题:
  6314. {$question}"
  6315. ]
  6316. ];
  6317. }else {
  6318. $messages = DB::table('mp_anime_records')->where('anime_id', $anime_id)->where('sequence', 0)
  6319. ->orderBy('id')->select('role', 'content')->get()->map(function ($value) {
  6320. return (array)$value;
  6321. })->toArray();
  6322. array_unshift($messages, $system_message);
  6323. $messages[] = [
  6324. 'role' => 'user',
  6325. 'content' => $prompt
  6326. ];
  6327. }
  6328. }
  6329. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  6330. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  6331. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  6332. if ($model === 'deepseek-chat') {
  6333. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  6334. $model = 'deepseek-v4-flash';
  6335. $thinkingMode = 'disabled';
  6336. } elseif ($model === 'deepseek-reasoner') {
  6337. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  6338. $model = 'deepseek-v4-flash';
  6339. $thinkingMode = 'enabled';
  6340. }
  6341. $post_data = [
  6342. 'model' => $model,
  6343. 'messages' => $messages,
  6344. // 'max_tokens' => 8192,
  6345. 'temperature' => 0.7,
  6346. 'frequency_penalty' => 0,
  6347. 'presence_penalty' => 0,
  6348. 'response_format' => ['type' => 'text'],
  6349. 'thinking' => ['type' => $thinkingMode],
  6350. 'stream' => true // 启用流式输出
  6351. ];
  6352. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  6353. // 根据模型类型选择调用方法
  6354. $fullContent = '';
  6355. $fullReasoningContent = '';
  6356. $usage = [];
  6357. // dd($post_data);
  6358. // dLog('deepseek')->info('请求参数: '.json_encode($post_data, 256));
  6359. try {
  6360. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  6361. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  6362. } else if (in_array($model, $this->gpt_text_models)) {
  6363. // GPT-5.4 模型使用 TokenRouter API
  6364. $streamGenerator = $this->gpt54StreamResponse($post_data);
  6365. } else {
  6366. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  6367. }
  6368. // 验证返回值类型
  6369. if (!is_iterable($streamGenerator)) {
  6370. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  6371. dLog('deepseek')->error('方法名流式生成器无效', [
  6372. 'generator_type' => $errorType,
  6373. 'model' => $model,
  6374. // 添加其他上下文信息
  6375. ]);
  6376. logDB('deepseek', 'error', '方法名流式生成器类型错误', [
  6377. 'type' => $errorType,
  6378. 'model' => $model
  6379. ]);
  6380. yield [
  6381. 'type' => 'error',
  6382. // 根据方法返回相应的空数据结构
  6383. 'answer' => '',
  6384. 'reasoning' => '',
  6385. 'usage' => [],
  6386. 'error' => '接口返回数据异常,请重新请求'
  6387. ];
  6388. return;
  6389. }
  6390. // 处理流式输出
  6391. foreach ($streamGenerator as $chunk) {
  6392. if (isset($chunk['type'])) {
  6393. if ($chunk['type'] === 'done') {
  6394. $fullContent = $chunk['full_content'];
  6395. $fullReasoningContent = $chunk['full_reasoning'];
  6396. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  6397. } else {
  6398. yield $chunk;
  6399. }
  6400. }
  6401. }
  6402. } catch (\Exception $e) {
  6403. dLog('deepseek')->error('方法名流式处理异常: ' . $e->getMessage(), [
  6404. 'model' => $model,
  6405. 'trace' => $e->getTraceAsString()
  6406. ]);
  6407. logDB('deepseek', 'error', '方法名流式处理失败', [
  6408. 'error' => $e->getMessage(),
  6409. 'model' => $model
  6410. ]);
  6411. yield [
  6412. 'type' => 'error',
  6413. // 根据方法返回相应的空数据结构
  6414. 'answer' => '',
  6415. 'reasoning' => '',
  6416. 'usage' => [],
  6417. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  6418. ];
  6419. return;
  6420. }
  6421. dLog('deepseek')->info('完整内容: '.$fullContent);
  6422. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  6423. // 处理完整内容并返回最终结果
  6424. $script_arr = [];
  6425. if ($fullContent) {
  6426. $script_arr = handleScriptContentForAce($fullContent);
  6427. dLog('deepseek')->info('解析内容', $script_arr);
  6428. logDB('deepseek', 'info', '解析内容', $script_arr);
  6429. }
  6430. if (empty($script_arr['roles'])) {
  6431. // 未生成剧本相关内容,保存对话记录并返回提示
  6432. dLog('deepseek')->info('未生成剧本相关的内容');
  6433. try {
  6434. $now = date('Y-m-d H:i:s');
  6435. // 保存对话记录
  6436. $records = [
  6437. [
  6438. 'uid' => $uid,
  6439. 'anime_id' => $anime_id,
  6440. 'sequence' => 0,
  6441. 'role' => 'user',
  6442. 'content' => $prompt,
  6443. 'created_at' => $now,
  6444. 'updated_at' => $now
  6445. ],
  6446. [
  6447. 'uid' => $uid,
  6448. 'anime_id' => $anime_id,
  6449. 'sequence' => 0,
  6450. 'role' => 'assistant',
  6451. 'content' => '未生成剧本相关的内容,请调整提示词后重试',
  6452. 'created_at' => $now,
  6453. 'updated_at' => $now
  6454. ]
  6455. ];
  6456. DB::table('mp_anime_records')->insert($records);
  6457. } catch (\Exception $e) {
  6458. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  6459. }
  6460. yield [
  6461. 'type' => 'done',
  6462. 'script' => [],
  6463. 'episode' => [],
  6464. 'answer' => $fullContent,
  6465. 'reasoning' => $fullReasoningContent,
  6466. 'usage' => $usage,
  6467. 'error' => '未生成剧本相关的内容,请调整提示词再试'
  6468. ];
  6469. return;
  6470. }
  6471. // 替换美术风格
  6472. if ($mappedArtStyle !== '') {
  6473. $script_arr['art_style'] = $mappedArtStyle;
  6474. $fullContent = $this->replaceArtStyleSection($fullContent, $mappedArtStyle);
  6475. }
  6476. if ($user_anime_name != '新剧本策划') {
  6477. $anime_name = isset($script_arr['script_name']) ? $script_arr['script_name'] : '';
  6478. // 确认对话名称唯一性
  6479. if ($anime_name && $id = DB::table('mp_animes')->where('anime_name', $anime_name)->value('id')) {
  6480. if ($id != $anime_id) $anime_name = $anime_name . '_' . date('YmdHis');
  6481. }
  6482. }else {
  6483. $anime_name = $user_anime_name;
  6484. }
  6485. $table_data = [
  6486. 'user_id' => $uid,
  6487. 'model' => $model,
  6488. 'intro' => isset($script_arr['intro']) ? $script_arr['intro'] : '',
  6489. 'highlights' => isset($script_arr['highlights']) ? $script_arr['highlights'] : '',
  6490. 'role_relationship' => isset($script_arr['role_relationship']) ? $script_arr['role_relationship'] : '',
  6491. 'core_contradiction' => isset($script_arr['core_contradiction']) ? $script_arr['core_contradiction'] : '',
  6492. 'roles' => isset($script_arr['roles']) && is_array($script_arr['roles']) ? json_encode($script_arr['roles'], 256) : '[]',
  6493. 'art_style' => isset($script_arr['art_style']) ? $script_arr['art_style'] : '',
  6494. 'art_style_type' => $input_art_style,
  6495. 'scenes' => isset($script_arr['scenes']) && is_array($script_arr['scenes']) ? json_encode($script_arr['scenes'], 256) : '[]',
  6496. 'status' => '解析完成',
  6497. 'generate_status' => '待执行',
  6498. 'updated_at' => date('Y-m-d H:i:s')
  6499. ];
  6500. if ($anime_name) $table_data['anime_name'] = $anime_name;
  6501. // 如果是修改集数,则将content内容更新(会改变原文)
  6502. if (isset($episode_count) && $episode_count > 0) {
  6503. if (isset($script_arr['content']) && $script_arr['content']) $table_data['content'] = $script_arr['content'];
  6504. $table_data['start_episode_sequence'] = 1;
  6505. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $episode_count;
  6506. }else {
  6507. // 如果需要生成原文内容,从script_arr中提取
  6508. if ($need_generate_content && isset($script_arr['content']) && $script_arr['content']) {
  6509. $table_data['content'] = $script_arr['content'];
  6510. dLog('deepseek')->info('从AI生成结果中提取原文内容', ['content_length' => strlen($script_arr['content'])]);
  6511. if (!$table_data['content']) {
  6512. yield [
  6513. 'type' => 'done',
  6514. 'script' => [],
  6515. 'episode' => [],
  6516. 'answer' => $fullContent,
  6517. 'reasoning' => $fullReasoningContent,
  6518. 'usage' => $usage,
  6519. 'error' => '未生成剧本内容,请调整提示词再试'
  6520. ];
  6521. return;
  6522. }
  6523. }
  6524. if (isset($table_data['content']) && $table_data['content']) {
  6525. $chapters = $this->splitContent($table_data['content']);
  6526. $chapter_count = count($chapters);
  6527. if ($chapter_count > 0) {
  6528. $table_data['start_episode_sequence'] = 1;
  6529. $table_data['end_episode_sequence'] = $table_data['episode_num'] = $chapter_count;
  6530. }
  6531. }
  6532. }
  6533. if ($extra_products) {
  6534. $table_data['extra_products'] = json_encode($extra_products, 256);
  6535. }
  6536. $single_episode = [];
  6537. try {
  6538. DB::beginTransaction();
  6539. $now = date('Y-m-d H:i:s');
  6540. // 更新动漫大纲
  6541. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update($table_data);
  6542. if (!$boolen) {
  6543. dLog('deepseek')->info('对话修改失败', $table_data);
  6544. logDB('deepseek', 'error', '对话修改失败', ['anime_id' => $anime_id]);
  6545. Utils::throwError('20003:对话修改失败');
  6546. }
  6547. // 保存对话记录
  6548. $records = [
  6549. [
  6550. 'uid' => $uid,
  6551. 'anime_id' => $anime_id,
  6552. 'sequence' => 0,
  6553. 'role' => 'user',
  6554. 'content' => $prompt,
  6555. 'created_at' => $now,
  6556. 'updated_at' => $now
  6557. ],
  6558. [
  6559. 'uid' => $uid,
  6560. 'anime_id' => $anime_id,
  6561. 'sequence' => 0,
  6562. 'role' => 'assistant',
  6563. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6564. 'content' => $fullContent,
  6565. 'created_at' => $now,
  6566. 'updated_at' => $now
  6567. ]
  6568. ];
  6569. // 保存对话记录
  6570. $boolen3 = DB::table('mp_anime_records')->insert($records);
  6571. if (!$boolen3) {
  6572. Utils::throwError('20003:对话记录保存失败');
  6573. }
  6574. // 单剧集模式:生成并保存剧集信息
  6575. if ($is_single) {
  6576. $anime_name = getProp($anime, 'anime_name', '未命名');
  6577. $episode_arr = $this->buildSingleEpisodeFromScript($script_arr, $fullContent, $anime_name);
  6578. if (empty($episode_arr['acts'])) {
  6579. Utils::throwError('20003:单剧集分镜内容解析失败,请确认输出格式');
  6580. }
  6581. $saveResult = $this->saveEpisodeVersionData(
  6582. $anime_id,
  6583. 1,
  6584. $episode_arr,
  6585. is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  6586. is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  6587. is_array(getProp($script_arr, 'props')) ? getProp($script_arr, 'props') : [],
  6588. null,
  6589. null,
  6590. false,
  6591. $content,
  6592. $now,
  6593. $ref_products
  6594. );
  6595. $single_episode = $saveResult['episode'];
  6596. $episode_id = $saveResult['episode_id'];
  6597. $boolen5 = DB::table('mp_animes')->where('id', $anime_id)->update([
  6598. 'roles' => json_encode($saveResult['merged_roles'], 256),
  6599. 'scenes' => json_encode($saveResult['merged_scenes'], 256),
  6600. 'updated_at' => $now
  6601. ]);
  6602. if ($boolen5 === false) {
  6603. Utils::throwError('20003:单剧集主表资源同步失败');
  6604. }
  6605. $table_data['roles'] = json_encode($saveResult['merged_roles'], 256);
  6606. $table_data['scenes'] = json_encode($saveResult['merged_scenes'], 256);
  6607. $episode_record_content = '确认分镜大纲';
  6608. if ($content !== '') {
  6609. // $episode_record_content .= "\n\n###上传内容\n" . $content;
  6610. }
  6611. $episode_records = [
  6612. [
  6613. 'uid' => $uid,
  6614. 'anime_id' => $anime_id,
  6615. 'role' => 'user',
  6616. 'content' => $episode_record_content,
  6617. 'sequence' => 1,
  6618. 'episode_id' => $episode_id,
  6619. 'created_at' => $now,
  6620. 'updated_at' => $now
  6621. ],
  6622. [
  6623. 'uid' => $uid,
  6624. 'anime_id' => $anime_id,
  6625. 'role' => 'assistant',
  6626. 'content' => $fullContent,
  6627. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  6628. 'sequence' => 1,
  6629. 'episode_id' => $episode_id,
  6630. 'created_at' => $now,
  6631. 'updated_at' => $now
  6632. ]
  6633. ];
  6634. $boolen4 = DB::table('mp_anime_records')->insert($episode_records);
  6635. if (!$boolen4) {
  6636. Utils::throwError('20003:单剧集分镜记录保存失败');
  6637. }
  6638. }
  6639. }catch (\Exception $e) {
  6640. DB::rollBack();
  6641. dLog('deepseek')->info('修改对话错误信息: '.$e->getMessage());
  6642. logDB('deepseek', 'error', '修改对话失败', ['error' => $e->getMessage(), 'anime_id' => $anime_id]);
  6643. yield [
  6644. 'type' => 'done',
  6645. 'answer' => $fullContent,
  6646. 'reasoning' => $fullReasoningContent,
  6647. 'usage' => $usage,
  6648. 'error' => $e->getMessage(),
  6649. ];
  6650. return;
  6651. }
  6652. DB::commit();
  6653. dLog('deepseek')->info('保存完毕');
  6654. if ($is_single && !empty($single_episode)) {
  6655. // $this->batchSetGlobalRoleImg([
  6656. // 'anime_id' => $anime_id,
  6657. // ]);
  6658. // $this->batchSetGlobalSceneImg([
  6659. // 'anime_id' => $anime_id,
  6660. // ]);
  6661. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  6662. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  6663. }
  6664. $table_data['anime_id'] = $anime_id;
  6665. $table_data['roles'] = json_decode($table_data['roles'], true);
  6666. $table_data['scenes'] = json_decode($table_data['scenes'], true);
  6667. unset($table_data['updated_at']);
  6668. unset($table_data['status']);
  6669. yield [
  6670. 'type' => 'done',
  6671. 'script' => $table_data,
  6672. 'episode' => $single_episode,
  6673. 'answer' => $fullContent,
  6674. 'reasoning' => $fullReasoningContent,
  6675. 'usage' => $usage
  6676. ];
  6677. }
  6678. public function chatForAce($data) {
  6679. $uid = Site::getUid();
  6680. $anime_id = getProp($data, 'anime_id');
  6681. $file = getProp($data, 'file');
  6682. $content = getProp($data, 'content', '');
  6683. $bid = getProp($data, 'bid', 0);
  6684. $script_id = getProp($data, 'script_id', 0);
  6685. $episode_number = getProp($data, 'episode_number', 1);
  6686. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  6687. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  6688. if (!$anime) Utils::throwError('20003:该对话不存在!');
  6689. if ((int)getProp($anime, 'is_multi') !== 1 && (int)$episode_number !== 1) Utils::throwError('20003:单剧集不支持其他剧集序号');
  6690. $current_episode = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->where('is_default', 1)->first();
  6691. $base_episode = $current_episode ?: DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $episode_number)->orderByDesc('id')->first();
  6692. $roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : json_decode((string)getProp($anime, 'roles'), true);
  6693. $scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : json_decode((string)getProp($anime, 'scenes'), true);
  6694. $roles = is_array($roles) ? $roles : [];
  6695. $scenes = is_array($scenes) ? $scenes : [];
  6696. $extra_products = getProp($data, 'products', []);
  6697. if (is_string($extra_products)) $extra_products = json_decode($extra_products, true);
  6698. // 如果anime有关联的script_id,则从mp_script_product_mappings中查询资产并合并到extra_products
  6699. $anime_script_id = getProp($anime, 'script_id');
  6700. if ($anime_script_id) {
  6701. $cpid = Site::getCpid();
  6702. $script_products_mappings = DB::table('mp_script_product_mappings as mapping')
  6703. ->join('mp_products as product', 'mapping.product_id', '=', 'product.id')
  6704. ->where('mapping.script_id', $anime_script_id)
  6705. ->where('product.cpid', $cpid)
  6706. ->where('product.is_deleted', 0);
  6707. // 如果提供了 episode_number,则过滤指定集数
  6708. if ($episode_number !== null && $episode_number !== '') {
  6709. $script_products_mappings->where('mapping.episode_number', $episode_number);
  6710. }
  6711. $mappings = $script_products_mappings->select(
  6712. 'mapping.product_id',
  6713. 'mapping.episode_number',
  6714. 'product.product_name',
  6715. 'product.type',
  6716. 'product.product',
  6717. 'product.pic_prompt',
  6718. 'product.url',
  6719. 'product.pic_task_id',
  6720. 'product.pic_task_status',
  6721. 'product.three_view_image_url'
  6722. )
  6723. ->get();
  6724. // 按 product_id 分组,合并 episode_number
  6725. $productMap = [];
  6726. foreach ($mappings as $item) {
  6727. $product_id = $item->product_id;
  6728. $product_name = $item->product_name;
  6729. // 处理product_name两边的符号
  6730. $product_name = preg_replace('/^[\s*\[\]【】[]{}{}\x{3000}]+|[\s*\[\]【】[]{}{}\x{3000}]+$/u', '', $product_name);
  6731. if (!isset($productMap[$product_id])) {
  6732. $productMap[$product_id] = [
  6733. 'product_id' => $product_id,
  6734. 'product_name' => $product_name,
  6735. 'type' => (int)$item->type,
  6736. 'product' => (int)$item->product,
  6737. 'pic_prompt' => $item->pic_prompt,
  6738. 'url' => $item->url,
  6739. 'pic_task_id' => $item->pic_task_id,
  6740. 'pic_task_status' => $item->pic_task_status,
  6741. 'episode_numbers' => [],
  6742. ];
  6743. }
  6744. // 添加 episode_number(去重)
  6745. if (!in_array($item->episode_number, $productMap[$product_id]['episode_numbers'])) {
  6746. $productMap[$product_id]['episode_numbers'][] = $item->episode_number;
  6747. }
  6748. }
  6749. // 将查询到的剧本资产合并到extra_products中
  6750. // 先构建extra_products的索引(以product_id+episode_number为key)
  6751. $extraProductsMap = [];
  6752. foreach ($extra_products as $item) {
  6753. $key = getProp($item, 'product_id') . '_' . getProp($item, 'episode_number', '');
  6754. $extraProductsMap[$key] = $item;
  6755. }
  6756. // 合并剧本资产(去重:product_id+episode_number)
  6757. foreach ($productMap as $product) {
  6758. foreach ($product['episode_numbers'] as $ep_num) {
  6759. $key = $product['product_id'] . '_' . $ep_num;
  6760. // 如果不存在则添加
  6761. if (!isset($extraProductsMap[$key])) {
  6762. $extraProductsMap[$key] = [
  6763. 'product_id' => $product['product_id'],
  6764. 'product_name' => $product['product_name'],
  6765. 'type' => $product['type'],
  6766. 'product' => $product['product'],
  6767. 'pic_prompt' => $product['pic_prompt'],
  6768. 'url' => $product['url'],
  6769. 'pic_task_id' => $product['pic_task_id'],
  6770. 'pic_task_status' => $product['pic_task_status'],
  6771. 'episode_number' => $ep_num,
  6772. ];
  6773. }
  6774. }
  6775. }
  6776. // 重新赋值给extra_products
  6777. $extra_products = array_values($extraProductsMap);
  6778. }
  6779. // 处理提示词
  6780. if ($prompt && $extra_products) {
  6781. // 遍历extra_products,将prompt中的{product_name}替换为实际的product_name
  6782. foreach($extra_products as $item) {
  6783. $product_name = getProp($item, 'product_name');
  6784. if ($product_name) {
  6785. // 替换 {product_name} 为 product_name
  6786. $prompt = str_replace('{' . $product_name . '}', $product_name, $prompt);
  6787. }
  6788. }
  6789. }
  6790. // 获取最后一集序号
  6791. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  6792. if ($end_episode_sequence && $episode_number > $end_episode_sequence) Utils::throwError("20003:总集数只有{$end_episode_sequence}集,不允许继续策划下一集!");
  6793. // 转换主体列表和场景列表的格式
  6794. // 获取参考主体或场景
  6795. if ((int)$episode_number === 1) {
  6796. $ref_data = DB::table('mp_animes')->where('id', $anime_id)->first();
  6797. // $ref_data = []; // 第一集让AI自由发挥不再使用全局主体(会影响后续分集的继承问题)
  6798. }else {
  6799. $prev_episode_number = $episode_number - 1;
  6800. $ref_data = DB::table('mp_anime_episodes')->where('anime_id', $anime_id)->where('episode_number', $prev_episode_number)->where('is_default', 1)->first();
  6801. }
  6802. $ref_roles = getProp($ref_data, 'roles') ? json_decode(getProp($ref_data, 'roles'), true) : [];
  6803. $ref_scenes = getProp($ref_data, 'scenes') ? json_decode(getProp($ref_data, 'scenes'), true) : [];
  6804. $ref_props = getProp($ref_data, 'props') ? json_decode(getProp($ref_data, 'props'), true) : [];
  6805. // 合并anime_products和extra_products(extra_products优先,去重)
  6806. $anime_products = getProp($anime, 'extra_products');
  6807. $anime_products = $anime_products ? json_decode($anime_products, true) : [];
  6808. $ref_products = [];
  6809. foreach($anime_products as $item) {
  6810. $product_name = getProp($item, 'product_name');
  6811. $ref_products[$product_name] = $item;
  6812. }
  6813. // 处理extra_products,将其合并到ref_roles和ref_scenes中(入参优先)
  6814. $extra_roles = []; // 从extra_products中提取的角色
  6815. $extra_scenes = []; // 从extra_products中提取的场景
  6816. $extra_props = []; // 从extra_products中提取的道具
  6817. if ($extra_products && is_array($extra_products)) {
  6818. foreach($extra_products as $item) {
  6819. $product = (int)getProp($item, 'product');
  6820. $product_name = getProp($item, 'product_name');
  6821. if ($product_name == '旁白') continue;
  6822. $pic_prompt = getProp($item, 'pic_prompt');
  6823. $ref_products[$product_name] = $item;
  6824. if ($product === 1) {
  6825. // 角色
  6826. $extra_roles[$product_name] = [
  6827. 'role' => $product_name,
  6828. 'pic_prompt' => $pic_prompt,
  6829. 'url' => getProp($item, 'url', ''),
  6830. ];
  6831. } elseif ($product === 2) {
  6832. // 场景
  6833. $extra_scenes[$product_name] = [
  6834. 'scene' => $product_name,
  6835. 'pic_prompt' => $pic_prompt,
  6836. 'url' => getProp($item, 'url', ''),
  6837. ];
  6838. } elseif ($product === 3) {
  6839. // 道具
  6840. $extra_props[$product_name] = [
  6841. 'prop' => $product_name,
  6842. 'pic_prompt' => $pic_prompt,
  6843. 'url' => getProp($item, 'url', ''),
  6844. ];
  6845. }
  6846. }
  6847. }
  6848. // 合并ref_roles和extra_roles(extra_roles优先,去重)
  6849. $merged_roles = [];
  6850. foreach($ref_roles as $role) {
  6851. $role_name = getProp($role, 'role');
  6852. if (!isset($extra_roles[$role_name])) {
  6853. $merged_roles[$role_name] = $role;
  6854. }
  6855. }
  6856. // 添加extra_roles
  6857. foreach($extra_roles as $role_name => $role) {
  6858. $merged_roles[$role_name] = $role;
  6859. }
  6860. $ref_roles = array_values($merged_roles);
  6861. // 合并ref_scenes和extra_scenes(extra_scenes优先,去重)
  6862. $merged_scenes = [];
  6863. foreach($ref_scenes as $scene) {
  6864. $scene_name = getProp($scene, 'scene');
  6865. if (!isset($extra_scenes[$scene_name])) {
  6866. $merged_scenes[$scene_name] = $scene;
  6867. }
  6868. }
  6869. // 添加extra_scenes
  6870. foreach($extra_scenes as $scene_name => $scene) {
  6871. $merged_scenes[$scene_name] = $scene;
  6872. }
  6873. $ref_scenes = array_values($merged_scenes);
  6874. // 合并ref_props和extra_props(extra_props优先,去重)
  6875. $merged_props = [];
  6876. foreach($ref_props as $prop) {
  6877. $prop_name = getProp($prop, 'prop');
  6878. if (!isset($extra_props[$prop_name])) {
  6879. $merged_props[$prop_name] = $prop;
  6880. }
  6881. }
  6882. // 添加extra_props
  6883. foreach($extra_props as $prop_name => $prop) {
  6884. $merged_props[$prop_name] = $prop;
  6885. }
  6886. $ref_props = array_values($merged_props);
  6887. $roles_content = $this->buildEpisodeItemContent($ref_roles, 'role');
  6888. $scenes_content = $this->buildEpisodeItemContent($ref_scenes, 'scene');
  6889. $props_content = $this->buildEpisodeItemContent($ref_props, 'prop');
  6890. // 构建强制主体、场景和道具提示词
  6891. $forced_roles_prompt = "";
  6892. $forced_scenes_prompt = "";
  6893. $forced_props_prompt = "";
  6894. if (!empty($extra_roles)) {
  6895. $forced_roles_list = "";
  6896. foreach($extra_roles as $role_name => $role) {
  6897. $forced_roles_list .= $role_name . ":{" . getProp($role, 'pic_prompt') . "}\n";
  6898. }
  6899. $forced_roles_prompt = "\n\n【强制主体设定-优先级最高-不可修改】\n以下主体必须全部出现在<主体列表>中,这些主体的优先级最高,必须包含:\n" . $forced_roles_list . "\n格式要求:\n1. 主体名称:必须保持不变\n2. 主体描述:你必须根据剧情为每个主体生成主体描述(分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,用一句话进行总结)\n3. 人物提示词:{}中的内容必须完整保留,不得修改\n4. 音色提示词:你必须根据角色特征生成音色提示词(描述角色的整体音色特征,包含:性别、年龄、音质、表达形式、情绪氛围,字数控制在80字以内),用{{}}框起来\n\n最终格式必须为:主体名:[你生成的主体描述]{人物提示词-保持不变}{{你生成的音色提示词}}\n\n【重要】以上每个主体在<主体列表>中的完整格式必须是:主体名:主体描述{人物提示词}{{音色提示词}},其中主体描述和音色提示词是你必须生成的内容,{}中的人物提示词必须原样保留。";
  6900. }
  6901. if (!empty($extra_scenes)) {
  6902. $forced_scenes_list = "";
  6903. foreach($extra_scenes as $scene_name => $scene) {
  6904. $forced_scenes_list .= $scene_name . ":{" . getProp($scene, 'pic_prompt') . "}\n";
  6905. }
  6906. $forced_scenes_prompt = "\n\n【强制场景设定-优先级最高-不可修改】\n以下场景必须全部出现在<场景列表>中,这些场景的优先级最高,必须包含:\n" . $forced_scenes_list . "\n格式要求:\n1. 场景名称:必须保持不变\n2. 场景描述:你必须根据剧情为每个场景生成场景描述(分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文)\n3. 场景提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:场景名:[你生成的场景描述]{场景提示词-保持不变}\n\n【重要】以上每个场景在<场景列表>中的完整格式必须是:场景名:场景描述{场景提示词},其中场景描述是你必须生成的内容,{}中的场景提示词必须原样保留。";
  6907. }
  6908. if (!empty($extra_props)) {
  6909. $forced_props_list = "";
  6910. foreach($extra_props as $prop_name => $prop) {
  6911. $forced_props_list .= $prop_name . ":{" . getProp($prop, 'pic_prompt') . "}\n";
  6912. }
  6913. $forced_props_prompt = "\n\n【强制道具设定-优先级最高-不可修改】\n以下道具必须全部出现在<道具列表>中,这些道具的优先级最高,必须包含:\n" . $forced_props_list . "\n格式要求:\n1. 道具名称:必须保持不变\n2. 道具描述:你必须根据剧情为每个道具生成道具描述(分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文)\n3. 道具提示词:{}中的内容必须完整保留,不得修改\n\n最终格式必须为:道具名:[你生成的道具描述]{道具提示词-保持不变}\n\n【重要】以上每个道具在<道具列表>中的完整格式必须是:道具名:道具描述{道具提示词},其中道具描述是你必须生成的内容,{}中的道具提示词必须原样保留。";
  6914. }
  6915. if ($anime_script_id) {
  6916. $role_demo = "2.<主体列表>只能使用以下主体,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_roles_prompt}";
  6917. }else if ($roles_content) {
  6918. $role_demo = "2.<主体列表>可在以下主体中选择多个(根据拆分出的分镜剧本来确认具体几个,不要出现旁白角色),不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。
  6919. 主体范围:\n {$roles_content}\n
  6920. 2.1如果本集剧情内容中出现了和给出的<主体列表>中不存在的新主体(或原主体发生了比较大的年龄、服装或身体变化),则不用在上述主体中选择,而是按照相同的格式新增一个主体显示在<主体列表>中。(以下是格式要求和生成要求,仅适用新出现的主体):
  6921. - 新主体分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6922. - 新主体的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6923. - 新主体的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6924. - 新主体的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  6925. }else {
  6926. $role_demo = "2.<主体列表>中出现的“主体名”必须尽可能统一,严禁出现角色-科学家、角色-复仇者、角色-领导者等带有身份、职业、标签类的命名,只能使用服装差异(如校服装、卫衣装、西装)来区分同一角色,如角色-校服装等。
  6927. - <主体列表>分以下三部分:主体描述、人物提示词和音色提示词,格式必须为:主体名:主体描述{人物提示词}{{音色提示词}}
  6928. - <主体列表>的主体描述是分析人物在整部剧中的姓名、年龄、性格特征、社会身份或职业背景、个人成长经历或核心故事动机,以及在剧情中的目标与行为驱动力,不需要描述外貌、穿着或身体特征,重点突出心理结构、行为模式与叙事功能(缩略成一句话讲述完毕)。
  6929. - <主体列表>的人物提示词需要根据当前分析出来的美术风格生成(每个人物都只允许一套服装,如果多套服装则需区分主体名),包含性别(男、女)、大概年龄或年龄段(少年、中年、老年等)、人种(亚洲人、欧洲人)、发型(直发卷发等)、发色(黑色、棕色、红色、白色等)、整体视觉风格,以及详细的穿着风格和服装细节、面部特征(戴金丝眼镜、脸上有刀疤等,无面部特征可忽略)。描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合人物身份设定。该提示词(字数50-100字左右)在主体描述后用{}框起来。
  6930. - <主体列表>的音色提示词放在描述的最后用{{}}框起来。音色提示词需描述角色的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。{$forced_roles_prompt}";
  6931. }
  6932. if ($anime_script_id) {
  6933. $scene_demo = "3.<场景列表>只能使用以下场景,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_scenes_prompt}";
  6934. }else if ($scenes_content) {
  6935. $scene_demo = "3.<场景列表>可在以下场景中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  6936. 场景范围:\n {$scenes_content}\n
  6937. 3.1如果本集剧情内容中出现了和给出的<场景列表>中不存在的新场景,则不用在上述场景中选择,而是按照相同的格式新增一个场景显示在<场景列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的场景):。
  6938. - 新场景分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词}
  6939. - 新场景的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6940. - 新场景的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  6941. }else {
  6942. $scene_demo = "3.<场景列表>与主体列表同理,需尽可能的对场景环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6943. - <场景列表>分以下两部分:场景描述和场景提示词,格式必须为:场景名:场景描述{场景提示词},注意不要出现{{}}这样的双大括号。
  6944. - <场景列表>的场景描述是分析在整部剧中出现过的场景,场景描述尽量简洁贴合原文。
  6945. - <场景列表>的场景提示词用于视觉呈现的场景环境描述,该场景需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的场景列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在场景描述后用{}框起来。{$forced_scenes_prompt}\n";
  6946. }
  6947. if ($anime_script_id) {
  6948. $prop_demo = "4.<道具列表>只能使用以下道具,不得自定义内容(必需带上冒号后的具体描述以及{}和{{}}中的内容,原样输出)。{$forced_props_prompt}";
  6949. }else if ($props_content) {
  6950. $prop_demo = "4.<道具列表>可在以下道具中选择多个(需带上冒号后的具体描述),根据拆分出的分镜剧本来确认具体几个,不得自定义(必需带上冒号后的具体描述以及{}中的内容,原样输出)。
  6951. 道具范围:\n {$props_content}\n
  6952. 4.1如果本集剧情内容中出现了和给出的<道具列表>中不存在的新道具,则不用在上述道具中选择,而是按照相同的格式新增一个道具显示在<道具列表>中,必须严格注意不要出现任何角色和人物。(以下是格式要求和生成要求,仅适用新出现的道具):。
  6953. - 新道具分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词}
  6954. - 新道具的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6955. - 新道具的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  6956. }else {
  6957. $prop_demo = "4.<道具列表>与主体列表同理,需尽可能的对道具环境进行详细描述,必须严格注意不要出现任何角色和人物。
  6958. - <道具列表>分以下两部分:道具描述和道具提示词,格式必须为:道具名:道具描述{道具提示词},注意不要出现{{}}这样的双大括号。
  6959. - <道具列表>的道具描述是分析在整部剧中出现过的道具,道具描述尽量简洁贴合原文。
  6960. - <道具列表>的道具提示词用于视觉呈现的道具环境描述,该道具需包含环境氛围、光线效果、空间布局、色彩基调、视觉风格等,描述需具有镜头感与画面表现力,适合直接用于AI图像生成模型,避免抽象词汇,强调具体可视化细节与整体视觉一致性,同时保证风格统一且符合剧情设定(可参考以下示例的道具列表中使用{}框起来的提示词,字数150-200字,需带上提炼出来的美术风格)。该提示词在道具描述后用{}框起来。{$forced_scenes_prompt}\n";
  6961. }
  6962. // 提取文件内容
  6963. if ($file) {
  6964. $uploaded_content = $this->extractFileContent($file);
  6965. if (!$uploaded_content) {
  6966. Utils::throwError('20003:无法提取文件内容,请检查文件格式');
  6967. }
  6968. } elseif ($script_id) {
  6969. $uploaded_content = $this->getContentByScriptId($script_id);
  6970. if (!$uploaded_content) {
  6971. Utils::throwError('20003:无法获取剧本内容,请检查剧本');
  6972. }
  6973. } elseif ($bid) {
  6974. $uploaded_content = $this->getContentByBid($bid);
  6975. if (!$uploaded_content) {
  6976. Utils::throwError('20003:无法获取书籍内容,请检查书籍');
  6977. }
  6978. } elseif ($content) {
  6979. $uploaded_content = filterContent((string)getProp($data, 'content', ''));
  6980. }
  6981. // elseif ($prompt) {
  6982. // $uploaded_content = filterContent($prompt);
  6983. // }
  6984. else {
  6985. $uploaded_content = '';
  6986. }
  6987. // 美术风格
  6988. $input_art_style = getProp($data, 'art_style');
  6989. if (!$input_art_style) {
  6990. $mappedArtStyle = getProp($anime, 'art_style');
  6991. }else {
  6992. $mappedArtStyle = $this->getArtStylePromptByInput($input_art_style);
  6993. }
  6994. if (!$mappedArtStyle) {
  6995. $mappedArtStyle_prompt = '美术风格:根据剧本内容自定义美术风格';
  6996. }else {
  6997. if (strstr($mappedArtStyle, '基础画风风格词')) {
  6998. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n{$mappedArtStyle}\n";
  6999. }else {
  7000. $art_style_type = $input_art_style ? $input_art_style : getProp($anime, 'art_style_type');
  7001. $mappedArtStyle_prompt = "美术风格强制设置如下(原样输出,不得更改任何内容):\n基础画风风格词: {$art_style_type}\n{$mappedArtStyle}\n";
  7002. }
  7003. }
  7004. $prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7005. // $demo = "你是一个专业的文档分析助手及资深编剧,请根据用户提供的文档内容完成示例格式的内容输出(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少;同时板块之间需满足以下要求:\n
  7006. // 强制要求:
  7007. // 1.你只负责与剧本相关的内容,如果用户输入与剧本无关的内容,请告知用户并拒绝继续回答,此为第一优先原则,不满足此原则就忽略其他要求并停止继续输出
  7008. // 2.如果用户输入修改美术风格、修改画风这类内容,请告知用户不可修改美术风格,并拒绝继续回答
  7009. // 3.以上两条要求对修改主体角色或场景不生效,允许用户调整主体角色说明和场景描述等
  7010. // 4.用户如果要求你帮忙写一个故事或者剧本,此类要求不属于与剧本无关,请帮助用户完成请求
  7011. // 5.强制按照示例格式返回内容,不要更改格式或随意增加符号
  7012. // 6.如果给出的本集剧情内容是剧本格式,则不要改动剧本内容(必须强制使用原文内容),严格按照剧本的旁白和台词进行分镜的策划,不要跳过任何剧情
  7013. // 7.分镜不是二次创作,必须严格“原文拆句”。优先把原文中可直接成镜头的句子拆成分镜,禁止把两句合并后再脑补过渡。
  7014. // 8.画面描述必须直接使用,禁止新增任何原文没有写出的动作、人物、道具、地点、气氛、结果或因果。
  7015. // 9.不要把“打开衣柜”扩写成“伸手轻抚嫁衣”,不要把“管家拎着两个箱子跟在后面”改成“沈耀和管家一起拎箱子”。主语、动作、数量、先后顺序必须完全按原文。
  7016. // 10.分镜要和场景列表、人物主体保持一致\n
  7017. // 普通要求:
  7018. // 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7019. // {$role_demo}
  7020. // {$scene_demo}
  7021. // 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7022. // 4.1片段分割逻辑(优先级从高到低):
  7023. // - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7024. // - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7025. // - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7026. // - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7027. // 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7028. // - 片段数量格式为: 片段数量:8
  7029. // - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7030. // - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7031. // 4.3分镜结构:每个分镜包含以下字段:
  7032. // - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始)
  7033. // - 场景:必须选择本集中的<场景列表>中的一个(不带详细表述)
  7034. // - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7035. // - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(不带主体具体描述)
  7036. // - 运镜:场景+画面描述+运镜
  7037. // - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色)
  7038. // - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7039. // - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7040. // 5.$mappedArtStyle_prompt\n\n
  7041. // 示例格式:\n
  7042. // 第1集:隐形的守护者
  7043. // ###故事梗概
  7044. // 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7045. // ###美术风格
  7046. // 基础画风风格词:胡金铨武侠
  7047. // 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7048. // ###主体列表
  7049. // 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7050. // 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7051. // 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7052. // ###场景列表
  7053. // 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7054. // 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7055. // ###分段剧本
  7056. // 片段数量:8
  7057. // 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7058. // ##片段1
  7059. // 时长:12s
  7060. // 分镜1
  7061. // 场景:边境小镇街道
  7062. // 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7063. // 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7064. // 配音台词:
  7065. // 背景音效:
  7066. // 分镜2
  7067. // 场景:悦来酒馆
  7068. // 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7069. // 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7070. // 配音台词:
  7071. // 背景音效:
  7072. // 分镜3
  7073. // 场景:悦来酒馆
  7074. // 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7075. // 运镜:从中景推向令牌特写。
  7076. // 配音台词:
  7077. // 背景音效:
  7078. // 分镜4
  7079. // 场景:悦来酒馆
  7080. // 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7081. // 运镜:极速推向酒水溅起的瞬间。
  7082. // 配音台词:
  7083. // 背景音效:
  7084. // 分镜5
  7085. // 镜头描述
  7086. // 场景:悦来酒馆
  7087. // 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7088. // 运镜:固定机位,利用倾斜构图制造压迫感。
  7089. // 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7090. // 背景音效:
  7091. // \n\n";
  7092. $demo = "你是一个国际顶尖的执行导演/编剧,熟悉各种风格的影视化落地,我需要你将这个剧本调整一下,将其变成一个高质量的影视分镜剧本(需包含以下几个板块: <剧集标题><故事梗概><美术风格><旁白音色提示词><主体列表><场景列表><道具列表><分段剧本>,每个板块之间必须使用###分隔,#不能多也不能少),要求画面和构图等进行高质量影视化改编,快节奏,改编的格式为先建立主体角色库、场景建库(其中场景建库的时候请分析故事发生的时候场景为白天还是晚上,建库的时候一起标注出来)以及关键的道具库。
  7093. 与此同时请将这个文本的情绪做一个分析,并且根据我下面提供的《情绪-视听语言映射表》进行一个文本情绪与视听语言的内容匹配。然后将每一个分镜按照「场景/场景时间(白天/晚上/傍晚等)」「画面」「运镜」「配音台词」「背景音效」的格式来划分,请按照每分钟25个左右的分镜的节奏帮我生成(这是一个整体性的标准,如果文本的情绪分析需要更多或者更少的镜头数量,请根据具体情况调整),分镜头请细腻的拆分文本中的内容,将动作、场景转换、事件的逻辑关系等内容清晰的交代出来,分镜之间需要呈现场景之间的转换逻辑,不要突然跳到下一个场景之中。于此同时保持镜头剪辑的顿挫感,节奏不要太平均。
  7094. 每一个分镜的「画面」请参考上一个分镜中人物的状态/动作和位置来写,保持人物状态以及在场景中的位置的一致性,不要断裂感,同时也不要直接在内容里写“参考上个分镜”这种话,因为视频模型无法识别,使用模型可以直接识别的文本内容。每一个分镜中需要出现的内容都请标出,例如出场角色,出场道具等等。请尽可能详细的描述画面内容。
  7095. 「背景音效」层面不要生成背景音乐,只需要生成音效和角色台词或者旁白,台词请先标注说台词的角色,旁白和角色心理活动时注明角色不要张嘴说话。\n
  7096. 普通要求:
  7097. 1.剧集标题必须与文档内容高度相关,剧集序号是{$episode_number}。
  7098. {$role_demo}
  7099. {$scene_demo}
  7100. {$prop_demo}
  7101. 4.<分段剧本>按照“分段模式”进行拆分和组织,要求如下:
  7102. 4.1片段分割逻辑(优先级从高到低):
  7103. - 第一优先级:时长上限(单个片段不超过15秒,超过必须切为新片段)
  7104. - 第二优先级:叙事节拍Beat(一个完整的事件/动作/情绪起落单元,如一段对话的来回、一个动作序列:推门→看见→震惊、一次闪回/回忆、旁白+画面组合)
  7105. - 第三优先级:语义块(按“谁、在哪、做什么、情绪怎样”聚合,如同一段旁白/独白、同一个角色的连续动作、同一个视角的连续镜头)
  7106. - 只要事件没结束、情绪没断,哪怕换场景,也留在同一个片段里
  7107. 4.2片段结构:片段数量+旁白音色+多个片段(每个片段由多个分镜组合而成(片段序号格式:片段1、片段2...))
  7108. - 片段数量格式为: 片段数量:8
  7109. - 旁白音色需描述旁白的整体音色特征,包含:性别、年龄(约XX岁)、音质(如清冷、沉稳、磁性等)、表达形式(如叙述感、旁白式等)、情绪氛围(如空灵韵味、看透世事的清冷等),字数控制在80字以内。举例:成年女性(约25-35岁),音色清冷且富有叙述感,语速平缓,带有仙侠剧特有的空灵韵味。
  7110. - 片段序号格式必须如下: ##片段+片段序号\n时长:xxs,例如: ##片段1\n时长:12s
  7111. 4.3分镜结构:每个分镜包含以下字段:
  7112. - 分镜序号在片段内用1、2、3显示,如分镜1、分镜2,并且分镜序号需连续(跨片段中的分镜序号需连续,如片段2中的分镜序号从片段1的最大序号+1开始),分镜序号前后不要带任何其他符号,特别是*符号。
  7113. - 场景:必须选择本集中的<场景列表>中的一个(如需使用“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”后面“:”前面的任何内容,不能自创)
  7114. - 画面:【构图/视角】+画面描述(越简单越好,对视觉场景/实景的描述,不描述氛围,比如紧张、压抑的氛围)。举例:[近景特写,浅景深]季潇握着手机贴在耳边,指关节因为用力而泛白。她的眼眶微红,睫毛在狂风中颤抖,嘴唇紧抿,眼神中闪烁着最后一点希冀的微光。
  7115. - 画面中如果出现主体,只能选择上述主体列表中的一个,主体的名称也需要保持一致(如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”后面“:”前面的任何内容,不能自创)
  7116. - 运镜:场景+画面描述+运镜
  7117. - 配音台词:格式为“中文配音:[角色]台词”,角色配音台词和语言由模型匹配生成,角色必须对应本集中的<主体列表>中的一个(非对话内容则统一固定为“旁白”角色,[角色]的角色名必须完整使用主体列表的主体名,如必须使用“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”后面“:”前面的任何内容,不能自创)
  7118. - 台词内容需满足以下要求: (1. 台词来源规则:台词内容必须逐字摘录自小说原文中的人物直接对话(带引号的内容),不允许改写、总结、压缩、扩写或拼接原文对白,不允许生成原文中不存在的对话。2. 非对话过滤:旁白、心理描写、环境描写、动作描写等内容,禁止出现在台词内容中。3. 空台词规则:如果该分镜中没有人物对话,则“台词内容”必须返回“无”,严禁输出“无台词”、“没有”等任何替代文本。4. 禁止推测:不得根据语境补全人物可能说的话。5.如果没有原文,直接返回空)
  7119. - 背景音效:背景音效需根据内容和画面生成,贴合当前画面描述和动作,例如:背景音效:高跟鞋的脚本声
  7120. 6.《情绪-视听语言映射表》:
  7121. 6.1 场景空间与时间心理学 (Scene & Temporality)
  7122. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7123. -----|---------|------------|----------------
  7124. 场景空间 | 封闭狭小 (Corridors/Closets) | 压抑、幽闭恐惧 | 物理限制映射心理自由的剥夺。
  7125. 场景空间 | 极度开阔 (Empty Plains/Desert) | 孤独、渺小、疏离 | 剥离社会性支撑,强化个体的虚无感。
  7126. 时间选择 | 黄金时刻 (Golden Hour) | 怀旧、温情、希望 | 柔和漫反射光线符合大脑对“美好记忆”的视觉加工。
  7127. 时间选择 | 蓝调时刻/深夜 (Blue/Night) | 冷漠、忧郁、未知危险 | 冷色调抑制血清素,增强感官的不安全感。
  7128. 6.2 剪辑节奏与感知阈值 (Shot Duration & Rhythm)
  7129. 维度 | 视听特征 | 对应核心情绪 | 心理学/叙事原理
  7130. -----|---------|------------|----------------
  7131. 长镜头 | >15秒的静止或缓慢移动 | 沉思、肃穆、煎熬 | 强迫观众进入实时流逝,产生生理性的存在感。
  7132. 快切剪辑 | <2秒的频繁切换 | 混乱、亢奋、惊恐 | 模拟高肾上腺素下的视觉捕捉,剥夺深度思考时间。
  7133. 节奏错位 | 非同步切分 (L-cut/J-cut) | 扭曲、不协调 | 破坏连续性假定,产生心理上的不适与悬疑感。
  7134. 6.3 运镜调度与情绪调动 (Cinematic Movement & Affect)
  7135. 运镜方式 | 物理特征 | 心理/情绪功能 | 专业应用场景
  7136. --------|---------|--------------|-------------
  7137. 推镜头 (Dolly In) | 摄影机物理接近主体 | 专注、发现、心理逼近。通过压缩背景空间,强制观众忽略环境,进入主体的内心世界。 | 角色顿悟、秘密揭晓、情感升温。
  7138. 拉镜头 (Dolly Out) | 摄影机物理远离主体 | 疏离、解脱、宿命感。将主体置于广阔背景中,显示主体的渺小或强调事情已成定局。 | 悲剧结尾、孤独的告别、审视全局。
  7139. 摇镜头 (Pan/Tilt) | 轴心转动,视点改变 | 观察、审读、惊奇感。模拟人眼转头,用于揭示空间关系或进行逻辑上的“连接”。 | 发现潜伏的危机、环视战场、建立空间地理志。
  7140. 跟拍 (Tracking Shot) | 保持与主体同速移动 | 强烈的参与感、伴随性焦虑。让观众感觉自己是角色的共谋者或影子,产生“实时感”。 | 逃亡、快步穿行于走廊、展示角色的行动力。
  7141. 横移 (Truck/Side Track) | 与主体平行横向移动 | 客观审视、叙事流逝。像卷轴画一样展开,产生一种冷静、观察者的旁白视角。 | 展示环境细节、两个角色在边走边谈时的心理博弈。
  7142. 手持/肩扛 (Handheld) | 生理性不规则晃动 | 不安、真实感、心理动荡。模拟肉眼观察,通过不稳定性唤起观众的本能警觉。 | 冲突现场、纪录片式纪实感、角色精神崩溃。
  7143. 斯坦尼康 (Steadicam) | 流畅、近乎滑行的移动 | 全知感、梦幻、无缝观察。消除物理重力感,产生一种“上帝视角”或“游魂般”的观察。 | 漫长而复杂的转场、舞会等优雅场景的穿梭。
  7144. 希区柯克变焦 (Dolly Zoom) | 推进同时反向变焦 | 眩晕、世界崩塌、极度惊骇。空间透视的物理扭曲直接引发生理性失衡。 | 角色得知真相的瞬间、高度恐惧。
  7145. 升降/摇臂 (Crane Shot) | 垂直或斜向空间位移 | 释放、崇高、超越性。打破二维平面的限制,将情绪从微观拉向宏观。 | 史诗感的结局、战场全景、情绪的爆发式升华。
  7146. 6.4 构图、色彩与符号学 (Composition & Aesthetics)
  7147. 维度 | 视听特征 | 对应核心情绪 | 心理学原理
  7148. -----|---------|------------|------------
  7149. 角度 | 仰角 (Low Angle) | 威严、恐惧、崇高 | 模拟幼年视角,确立权力层级。
  7150. 角度 | 俯角 (High Angle) | 脆弱、无助、卑微 | 模拟审视感,削弱主体力量。
  7151. 构图 | 荷兰坡 (Dutch Tilt) | 疯狂、崩溃、失衡 | 重力轴偏离导致前庭系统产生失衡反应。
  7152. 色彩 | 极高饱和度/冷暖撞色 | 狂喜、冲突、超现实 | 强烈的视觉刺激诱发情绪阈值波动。
  7153. 6.5 进阶视听修辞与认知干预 (Advanced AV Rhetoric)
  7154. 修辞策略 | 技术实现 | 心理/情绪效应 | 理论基石
  7155. --------|---------|--------------|----------
  7156. 声画对位 (Contrapuntal AV) | 在极端残酷/激烈的画面中配以极其舒缓优雅的音乐(如古典乐)。 | 荒诞恐怖感、神圣的残酷、间离效果。通过感官冲突迫使观众从原始情绪中抽离,进入形而上的思考。 | 安德烈·塔可夫斯基《雕刻时光》、库布里克式美学。
  7157. 非平衡构图 (Compositional Tension) | 突破平衡法则,将视觉重点(Eye-tracking)置于画面边缘或极端角落。 | 本能警觉、不安全感、期待感。利用大脑对“视觉缺失”的补充本能,暗示画面外存在不可见的威胁。 | 格式塔心理学、眼动追踪实验。
  7158. 认知负荷调控 (Neurocinematics) | 利用快速剪辑抑制前额叶皮层(理性区),激活杏仁核(情绪区)。 | 纯粹感官化、生存模式切换。若要观众思考,则延长镜头以激活认知分析;若要观众受惊,则通过视觉过载切断其逻辑判断。 | 神经电影学 (Neurocinematics)。
  7159. 6.6 声音设计与潜意识影响 (Soundscape)
  7160. 维度 | 视听特征 | 对应核心情绪 | 心理学/生理学原理
  7161. -----|---------|------------|------------------
  7162. 音色 | 极低频音 (Infra-sound) | 潜伏恐惧、生理不安 | 模仿自然灾害频率,唤醒生物避害本能。
  7163. 环境声 | 极度死寂 (Silence) | 震惊、神圣、虚无 | 听觉剥夺放大视觉信号,产生心理张力。
  7164. 非现场音 | 不和谐音/尖锐音效 | 精神紧绷、躁郁 | 高频声音直接刺激杏仁核,引发防御机制。
  7165. 理论基石:
  7166. - The Five C's of Cinematography by Joseph V. Mascelli
  7167. - Film Art: An Introduction by David Bordwell
  7168. - Sight, Sound, Motion by Herbert Zettl
  7169. - Notes on the Cinematograph by Robert Bresson
  7170. \n\n
  7171. 7.{$mappedArtStyle_prompt}
  7172. 示例格式:\n
  7173. 第1集:隐形的守护者
  7174. ###故事梗概
  7175. 内容梗概:许芸归家遭徐母毒打,她冷静周旋并编造谎言掩盖行踪,引得一旁阴沉的卞大伟愈发急躁。半个月后,徐母离家,卞大伟兽性大发欲行不轨。生死关头,隐形的程景现身肉搏,屋内家具横飞,卞大伟被“空气”重创。许芸趁乱逃出,却惊见地面凭空浮现一串血脚印。意识到守护者为救自己负伤,许芸不再逃避,对着虚无的空气执拗告白,誓要与这看不见的爱人共进退。
  7176. ###美术风格
  7177. 基础画风风格词:胡金铨武侠
  7178. 视觉风格描述:整体采用复古武侠电影美学,以低饱和度的青灰与墨色调为主,营造冷峻、肃杀的江湖意境。光影上运用强烈的侧逆光与深邃硬阴影,完美契合“墨影剑客”神秘莫测的特质。画面带有35mm胶片的粗粝质感,构图简约且富有张力,展现出深沉的复仇叙事氛围。
  7179. ###主体列表
  7180. 陆沉:冷酷神秘的复仇剑客,陆家庄唯一幸存者,身负绝世武功与血海深仇。{全景,正面拍摄,青年男性,亚洲人,黑色长发束起,五官轮廓深邃。服饰穿搭:黑色连帽斗篷,深灰色交领劲装,黑色束腰,背负一柄漆黑宽大的无锋重剑。姿态:站立。}{{青年男性(约25-30岁),音色冷峻、低沉,语速平稳缓慢,透着一股拒人于千里之外的孤傲与肃杀。}}
  7181. 刀疤脸:武林盟的嚣张爪牙,性格暴戾、欺软怕硬,是赵无极麾下的打手。{全景,正面拍摄,中年男性,亚洲人,短发,左脸有一道明显的深长刀疤。服饰穿搭:土黄色粗布武士服,腰间挂着一枚古铜色的“武林盟”令牌。姿态:站立。}{{中年男性(约35-45岁),音色粗犷、沙哑,语气嚣张跋扈,带有明显的威胁感和市井痞气。}}
  7182. 老李:悦来酒馆的老板,胆小卑微的底层百姓,在乱世中艰难求生。{全景,正面拍摄,老年男性,亚洲人,灰白乱发,面容消瘦且布满皱纹。服饰穿搭:破旧的深蓝色粗布长袍,腰间系着一条带有污渍的灰色围裙。姿态:站立。}{{老年男性(约60岁以上),音色苍老、沙哑且带有颤抖,语气唯唯诺诺,充满了卑微与惊恐。}}
  7183. ###场景列表
  7184. 边境小镇街道:夜幕笼罩下的边陲小镇,风沙肆虐,街道两旁是破旧的木质建筑,透着一股荒凉与肃杀的气息,是故事发生的地理背景。{远景,夜幕下的边境小镇,破败的木质建筑错落有致,风沙在空旷的街道上飞扬,远处有微弱的灯火。无人物。}
  7185. 悦来酒馆:酒馆内部陈设简陋,木质桌椅散乱分布,柜台上摆放着酒坛。室内光线昏暗,只有几盏摇曳的油灯提供微弱的暖光,与室外的冷调形成对比。{室内场景,昏暗的古风酒馆内部,粗糙的木质桌椅,木质柜台与酒坛,空气中浮动着尘埃,强烈的侧逆光勾勒出环境轮廓,深邃的硬阴影。无人物。}
  7186. ###道具列表
  7187. 全家福照片:一张全家福照片{AI真人短剧,横屏16:9,8K电影级写实,无人物实体出镜的道具参考图,家庭全家福相框,多角度视角图,正面、背面、侧面、局部细节,木质或金属相框,照片内容可模糊表现多人合影构图,重点展示边缘站位感,相框尺寸标注25厘米×20厘米×2厘米,白底产品级干净展示}
  7188. 酒杯-高脚杯:一个高脚杯{AI真人短剧,横屏16:9,8K电影级写实,高脚酒杯,道具多角度视角图,正面、背面、侧面、局部细节,透明玻璃材质,细长杯柄,尺寸标注高24厘米杯口6厘米,白底干净展示,无人物}
  7189. ###分段剧本
  7190. 片段数量:8
  7191. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  7192. ##片段1
  7193. 时长:12s
  7194. 分镜1
  7195. 场景:边境小镇街道
  7196. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  7197. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  7198. 配音台词:
  7199. 背景音效:
  7200. 分镜2
  7201. 场景:悦来酒馆
  7202. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  7203. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  7204. 配音台词:
  7205. 背景音效:
  7206. 分镜3
  7207. 场景:悦来酒馆
  7208. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  7209. 运镜:从中景推向令牌特写。
  7210. 配音台词:
  7211. 背景音效:
  7212. 分镜4
  7213. 场景:悦来酒馆
  7214. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  7215. 运镜:极速推向酒水溅起的瞬间。
  7216. 配音台词:
  7217. 背景音效:
  7218. 分镜5
  7219. 镜头描述
  7220. 场景:悦来酒馆
  7221. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  7222. 运镜:固定机位,利用倾斜构图制造压迫感。
  7223. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  7224. 背景音效:
  7225. \n\n";
  7226. $origin_prompt = trim((string)getProp($data, 'prompt', '确认分镜大纲'));
  7227. $is_regenerate_version = !in_array($origin_prompt, ['确认分镜大纲', '继续策划下一集'], true);
  7228. $is_global_generate_pics = $origin_prompt == '确认分镜大纲' ? 1 : 0;
  7229. $prompt = $origin_prompt;
  7230. $is_single = (int)getProp($anime, 'is_multi') !== 1;
  7231. // 获取章节内容
  7232. $full_content = getProp($anime, 'content');
  7233. if ($uploaded_content) {
  7234. $full_content = $uploaded_content;
  7235. }
  7236. // 根据章节内容拆分章节
  7237. $chapters = $this->splitContent($full_content);
  7238. $chapter_content = isset($chapters[($episode_number-1)]['content']) ? $chapters[($episode_number-1)]['content'] : '';
  7239. if (!$chapter_content) $chapter_content = $full_content; // 如果无法拆分章节则直接用原文
  7240. $messages = [];
  7241. if ($prompt == '确认分镜大纲') {
  7242. // 暂时保留
  7243. $content = $chapter_content;
  7244. if ($is_single) $content = $full_content; // 单剧集使用全文
  7245. if (!$content) {
  7246. Utils::throwError('20003:章节内容无法获取,请确认');
  7247. }
  7248. $question = $is_single
  7249. ? $demo . "请根据以上要求分析完整剧情,直接输出第1集完整单剧集分镜剧本,需一次性生成并可直接保存,剧情内容如下: \n\n$content"
  7250. : $demo . "请根据以上要求分析本章剧情,完成分镜剧本,本集剧情内容如下: \n\n$content";
  7251. // 构建消息
  7252. $messages[] =
  7253. [
  7254. 'role' => 'user',
  7255. 'content' => $question
  7256. ];
  7257. }else if ($prompt == '继续策划下一集') {
  7258. if ($is_single) {
  7259. Utils::throwError('20003:单剧集不支持继续策划下一集');
  7260. }
  7261. $content = $chapter_content;
  7262. if (!$content) {
  7263. Utils::throwError('20003:章节内容无法获取,请确认');
  7264. }
  7265. $question = $demo."请根据以上要求分析本集剧情内容,完成本集分镜剧本(需衔接上一集内容)";
  7266. // 获取上一集最后记录
  7267. $prev_sequence = $episode_number - 1;
  7268. $messages = $this->getEpisodeChatContent($anime_id, $prev_sequence, $content);
  7269. // 构建消息
  7270. $messages[] =
  7271. [
  7272. 'role' => 'user',
  7273. 'content' => $question
  7274. ];
  7275. // dd($messages);
  7276. }else {
  7277. $content = $uploaded_content ? $chapter_content : trim((string)getProp($base_episode, 'content'));
  7278. if (!$content) {
  7279. $content = $is_single ? $full_content : ($chapter_content ?: $full_content);
  7280. }
  7281. if (!$content) {
  7282. Utils::throwError('20003:章节内容无法获取,请确认');
  7283. }
  7284. $messages = $this->getEpisodeChatMessages($anime_id, $episode_number);
  7285. $targetEpisodeText = $is_single ? '第1集完整单剧集版本' : "第{$episode_number}集完整的新版本剧集";
  7286. $question = $demo . "\n请基于以上历史对话记录,重新生成{$targetEpisodeText},并严格按示例格式输出完整内容。\n";
  7287. if ($origin_prompt) {
  7288. $question .= "本次修改要求如下:\n{$origin_prompt}";
  7289. }
  7290. $messages[] =
  7291. [
  7292. 'role' => 'user',
  7293. 'content' => $question
  7294. ];
  7295. }
  7296. // 处理文本模型
  7297. $model = getProp($data, 'model');
  7298. if (!$model) {
  7299. // 用户没有输入,从anime表获取
  7300. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7301. $model = getProp($anime, 'model');
  7302. if (!$model) {
  7303. // anime表也没有,使用默认值
  7304. $model = 'doubao-seed-2-0-mini-260215';
  7305. }
  7306. }
  7307. // 验证模型是否在可用模型表中
  7308. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  7309. $model = 'doubao-seed-2-0-mini-260215';
  7310. }
  7311. // 模型兼容性处理:deepseek-chat 和 deepseek-reasoner 映射到 deepseek-v4-flash
  7312. $thinkingMode = getProp($data, 'thinking', 'disabled'); // 默认非思考模式
  7313. $reasoningEffort = getProp($data, 'reasoning_effort', 'high'); // 默认思考强度
  7314. if ($model === 'deepseek-chat') {
  7315. // deepseek-chat 映射到 deepseek-v4-flash,非思考模式
  7316. $model = 'deepseek-v4-flash';
  7317. $thinkingMode = 'disabled';
  7318. } elseif ($model === 'deepseek-reasoner') {
  7319. // deepseek-reasoner 映射到 deepseek-v4-flash,思考模式
  7320. $model = 'deepseek-v4-flash';
  7321. $thinkingMode = 'enabled';
  7322. }
  7323. $post_data = [
  7324. 'model' => $model,
  7325. 'messages' => $messages,
  7326. // 'max_tokens' => 8192,
  7327. 'temperature' => 0.7,
  7328. 'frequency_penalty' => 0,
  7329. 'presence_penalty' => 0,
  7330. 'response_format' => ['type' => 'text'],
  7331. 'thinking' => ['type' => $thinkingMode],
  7332. 'stream' => true // 启用流式输出
  7333. ];
  7334. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  7335. // 根据模型类型选择调用方法
  7336. $fullContent = '';
  7337. $fullReasoningContent = '';
  7338. $usage = [];
  7339. try {
  7340. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7341. // DeepSeek 官方模型使用 DeepSeek API
  7342. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7343. } else if (in_array($model, $this->gpt_text_models)) {
  7344. // GPT-5.4 模型使用 TokenRouter API
  7345. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7346. } else {
  7347. // 其他模型使用火山引擎API
  7348. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7349. }
  7350. // 验证返回值类型
  7351. if (!is_iterable($streamGenerator)) {
  7352. $errorType = is_object($streamGenerator) ? get_class($streamGenerator) : gettype($streamGenerator);
  7353. dLog('deepseek')->error('chat流式生成器无效', [
  7354. 'generator_type' => $errorType,
  7355. 'model' => $model,
  7356. 'anime_id' => $anime_id,
  7357. 'episode_number' => $episode_number
  7358. ]);
  7359. logDB('deepseek', 'error', 'chat流式生成器类型错误', [
  7360. 'type' => $errorType,
  7361. 'model' => $model
  7362. ]);
  7363. yield [
  7364. 'type' => 'error',
  7365. 'episode' => [],
  7366. 'answer' => '',
  7367. 'reasoning' => '',
  7368. 'usage' => [],
  7369. 'error' => '接口返回数据异常,请重新请求'
  7370. ];
  7371. return;
  7372. }
  7373. // 处理流式输出
  7374. foreach ($streamGenerator as $chunk) {
  7375. if (isset($chunk['type'])) {
  7376. if ($chunk['type'] === 'done') {
  7377. // 最终结果
  7378. $fullContent = $chunk['full_content'];
  7379. $fullReasoningContent = $chunk['full_reasoning'];
  7380. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7381. } else {
  7382. // 逐块yield数据
  7383. yield $chunk;
  7384. }
  7385. }
  7386. }
  7387. } catch (\Exception $e) {
  7388. dLog('deepseek')->error('chat流式处理异常: ' . $e->getMessage(), [
  7389. 'model' => $model,
  7390. 'anime_id' => $anime_id,
  7391. 'episode_number' => $episode_number,
  7392. 'trace' => $e->getTraceAsString()
  7393. ]);
  7394. logDB('deepseek', 'error', 'chat流式处理失败', [
  7395. 'error' => $e->getMessage(),
  7396. 'model' => $model
  7397. ]);
  7398. yield [
  7399. 'type' => 'error',
  7400. 'episode' => [],
  7401. 'answer' => '',
  7402. 'reasoning' => '',
  7403. 'usage' => [],
  7404. 'error' => '处理请求时发生异常: ' . $e->getMessage()
  7405. ];
  7406. return;
  7407. }
  7408. dLog('deepseek')->info('完整内容: '.$fullContent);
  7409. logDB('deepseek', 'info', '完整内容', ['content' => $fullContent, 'anime_id' => $anime_id]);
  7410. // 处理完整内容并返回最终结果
  7411. $episode_arr = handleEpisodeContentForAce($fullContent);
  7412. logDB('deepseek', 'info', '解析内容', $episode_arr);
  7413. // // 如果有anime_script_id,进行主体和场景名称的智能匹配和替换(激进策略)
  7414. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7415. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7416. // logDB('deepseek', 'info', '匹配替换后的解析内容', $episode_arr);
  7417. // }
  7418. // 验证逻辑:如果anime_script_id有值,需要验证生成的主体和场景是否匹配
  7419. $max_retries = 3;
  7420. $retry_count = 0;
  7421. $validation_failed = false;
  7422. $validation_error_msg = '';
  7423. // 验证生成的内容
  7424. if ($anime_script_id) {
  7425. // 检查是否有acts数据
  7426. if (empty($episode_arr['acts'])) {
  7427. $validation_failed = true;
  7428. $validation_error_msg = '未生成分镜剧本相关的内容';
  7429. } else {
  7430. // 检查主体列表是否匹配 - 只验证生成的主体名是否都在预期列表中
  7431. $generated_roles = array_column($episode_arr['roles'], 'role');
  7432. // 过滤掉"旁白"角色
  7433. $generated_roles = array_filter($generated_roles, function($role) {
  7434. return $role !== '旁白';
  7435. });
  7436. $expected_roles = array_keys($extra_roles);
  7437. // 找出生成的主体中不在预期列表中的主体
  7438. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7439. if (!empty($invalid_roles)) {
  7440. $validation_failed = true;
  7441. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7442. }
  7443. // 检查场景列表是否匹配 - 只验证生成的场景名是否都在预期列表中
  7444. if (!$validation_failed) {
  7445. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7446. $expected_scenes = array_keys($extra_scenes);
  7447. // 找出生成的场景中不在预期列表中的场景
  7448. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7449. if (!empty($invalid_scenes)) {
  7450. $validation_failed = true;
  7451. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7452. }
  7453. }
  7454. }
  7455. } else {
  7456. // 如果没有anime_script_id,只检查是否有acts数据
  7457. if (empty($episode_arr['acts'])) {
  7458. $validation_failed = true;
  7459. $validation_error_msg = '未生成分镜剧本相关的内容';
  7460. }
  7461. }
  7462. // 重试逻辑
  7463. while ($validation_failed && $retry_count < $max_retries) {
  7464. $retry_count++;
  7465. dLog('deepseek')->warning("验证失败,开始第{$retry_count}次重试", [
  7466. 'reason' => $validation_error_msg,
  7467. 'anime_id' => $anime_id,
  7468. 'episode_number' => $episode_number
  7469. ]);
  7470. logDB('deepseek', 'warning', "第{$retry_count}次重试", [
  7471. 'reason' => $validation_error_msg,
  7472. 'anime_id' => $anime_id
  7473. ]);
  7474. // 发送流式重试提示
  7475. yield [
  7476. 'type' => 'retry',
  7477. 'retry_count' => $retry_count,
  7478. 'reason' => $validation_error_msg
  7479. ];
  7480. // 构建重试提示词
  7481. $retry_prompt = "生成的剧本存在问题:{$validation_error_msg}。\n\n请严格按照要求重新生成,确保:\n";
  7482. if ($anime_script_id) {
  7483. $retry_prompt .= "1. 主体列表中的所有主体名称必须从【强制主体设定】中选择,不得使用其他主体名称\n";
  7484. $retry_prompt .= "2. 场景列表中的所有场景名称必须从【强制场景设定】中选择,不得使用其他场景名称\n";
  7485. $retry_prompt .= "3. 必须包含完整的分镜剧本内容\n";
  7486. } else {
  7487. $retry_prompt .= "1. 必须包含完整的分镜剧本内容\n";
  7488. }
  7489. // 添加重试消息到messages
  7490. $messages[] = [
  7491. 'role' => 'assistant',
  7492. 'content' => $fullContent
  7493. ];
  7494. $messages[] = [
  7495. 'role' => 'user',
  7496. 'content' => $retry_prompt
  7497. ];
  7498. // 更新post_data的messages
  7499. $post_data['messages'] = $messages;
  7500. // 重新调用API
  7501. try {
  7502. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  7503. $streamGenerator = $this->deepSeekStreamResponse($post_data);
  7504. } else if (in_array($model, $this->gpt_text_models)) {
  7505. $streamGenerator = $this->gpt54StreamResponse($post_data);
  7506. } else {
  7507. $streamGenerator = $this->volcEngineChatCompletion($post_data);
  7508. }
  7509. // 处理流式输出
  7510. $fullContent = '';
  7511. $fullReasoningContent = '';
  7512. foreach ($streamGenerator as $chunk) {
  7513. if (isset($chunk['type'])) {
  7514. if ($chunk['type'] === 'done') {
  7515. $fullContent = $chunk['full_content'];
  7516. $fullReasoningContent = $chunk['full_reasoning'];
  7517. $usage = isset($chunk['usage']) ? $chunk['usage'] : [];
  7518. } else {
  7519. yield $chunk;
  7520. }
  7521. }
  7522. }
  7523. // 重新解析内容
  7524. dLog('deepseek')->info("第{$retry_count}次重试完整内容: " . $fullContent);
  7525. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", ['content' => $fullContent, 'anime_id' => $anime_id]);
  7526. $episode_arr = handleEpisodeContentForAce($fullContent);
  7527. // // 进行主体和场景名称的智能匹配和替换(激进策略)
  7528. // if ($anime_script_id && !empty($extra_roles) && !empty($extra_scenes)) {
  7529. // $episode_arr = $this->matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes);
  7530. // }
  7531. dLog('deepseek')->info('第'.$retry_count.'次重试后内容: '.$fullContent);
  7532. logDB('deepseek', 'info', "第{$retry_count}次重试解析内容", $episode_arr);
  7533. // 重新验证
  7534. $validation_failed = false;
  7535. $validation_error_msg = '';
  7536. if ($anime_script_id) {
  7537. if (empty($episode_arr['acts'])) {
  7538. $validation_failed = true;
  7539. $validation_error_msg = '未生成分镜剧本相关的内容';
  7540. } else {
  7541. // 检查主体列表 - 只验证生成的主体名是否都在预期列表中
  7542. $generated_roles = array_column($episode_arr['roles'], 'role');
  7543. // 过滤掉"旁白"角色
  7544. $generated_roles = array_filter($generated_roles, function($role) {
  7545. return $role !== '旁白';
  7546. });
  7547. $expected_roles = array_keys($extra_roles);
  7548. $invalid_roles = array_diff($generated_roles, $expected_roles);
  7549. if (!empty($invalid_roles)) {
  7550. $validation_failed = true;
  7551. $validation_error_msg = '生成的主体列表包含不在【强制主体设定】中的主体:' . implode('、', $invalid_roles);
  7552. }
  7553. // 检查场景列表 - 只验证生成的场景名是否都在预期列表中
  7554. if (!$validation_failed) {
  7555. $generated_scenes = array_column($episode_arr['scenes'], 'scene');
  7556. $expected_scenes = array_keys($extra_scenes);
  7557. $invalid_scenes = array_diff($generated_scenes, $expected_scenes);
  7558. if (!empty($invalid_scenes)) {
  7559. $validation_failed = true;
  7560. $validation_error_msg = '生成的场景列表包含不在【强制场景设定】中的场景:' . implode('、', $invalid_scenes);
  7561. }
  7562. }
  7563. }
  7564. } else {
  7565. if (empty($episode_arr['acts'])) {
  7566. $validation_failed = true;
  7567. $validation_error_msg = '未生成分镜剧本相关的内容';
  7568. }
  7569. }
  7570. } catch (\Exception $e) {
  7571. dLog('deepseek')->error("第{$retry_count}次重试异常: " . $e->getMessage(), [
  7572. 'trace' => $e->getTraceAsString()
  7573. ]);
  7574. break;
  7575. }
  7576. }
  7577. // 如果重试后仍然失败
  7578. if ($validation_failed) {
  7579. dLog('deepseek')->error('达到最大重试次数,仍未生成有效内容', [
  7580. 'retry_count' => $retry_count,
  7581. 'last_error' => $validation_error_msg
  7582. ]);
  7583. try {
  7584. $now = date('Y-m-d H:i:s');
  7585. $records = [
  7586. [
  7587. 'uid' => $uid,
  7588. 'anime_id' => $anime_id,
  7589. 'sequence' => $episode_number,
  7590. 'role' => 'user',
  7591. 'content' => $prompt,
  7592. 'created_at' => $now,
  7593. 'updated_at' => $now
  7594. ],
  7595. [
  7596. 'uid' => $uid,
  7597. 'anime_id' => $anime_id,
  7598. 'sequence' => $episode_number,
  7599. 'role' => 'assistant',
  7600. 'content' => $fullContent,
  7601. 'created_at' => $now,
  7602. 'updated_at' => $now
  7603. ]
  7604. ];
  7605. DB::table('mp_anime_records')->insert($records);
  7606. } catch (\Exception $e) {
  7607. dLog('deepseek')->error('保存对话记录失败', ['error' => $e->getMessage()]);
  7608. }
  7609. yield [
  7610. 'type' => 'done',
  7611. 'episode' => [],
  7612. 'answer' => $fullContent,
  7613. 'reasoning' => $fullReasoningContent,
  7614. 'usage' => $usage,
  7615. 'error' => "生成剧本有误,已重试{$retry_count}次仍失败,请稍后重试。错误原因:{$validation_error_msg}"
  7616. ];
  7617. return;
  7618. }
  7619. // 验证成功,记录日志
  7620. if ($retry_count > 0) {
  7621. dLog('deepseek')->info("经过{$retry_count}次重试后验证成功");
  7622. logDB('deepseek', 'info', '重试成功', ['retry_count' => $retry_count, 'anime_id' => $anime_id]);
  7623. }
  7624. // 老逻辑
  7625. $existing_roles = $base_episode ? json_decode((string)getProp($base_episode, 'roles'), true) : [];
  7626. $existing_scenes = $base_episode ? json_decode((string)getProp($base_episode, 'scenes'), true) : [];
  7627. $existing_props = $base_episode ? json_decode((string)getProp($base_episode, 'props'), true) : [];
  7628. $existing_roles = is_array($existing_roles) ? $existing_roles : [];
  7629. $existing_scenes = is_array($existing_scenes) ? $existing_scenes : [];
  7630. $existing_props = is_array($existing_props) ? $existing_props : [];
  7631. $now = date('Y-m-d H:i:s');
  7632. try {
  7633. DB::beginTransaction();
  7634. $saveResult = $this->saveEpisodeVersionData(
  7635. $anime_id,
  7636. $episode_number,
  7637. $episode_arr,
  7638. $existing_roles,
  7639. $existing_scenes,
  7640. $existing_props,
  7641. $current_episode,
  7642. $base_episode,
  7643. $is_regenerate_version,
  7644. $content,
  7645. $now,
  7646. $ref_products
  7647. );
  7648. $episode = $saveResult['episode'];
  7649. $episode_id = $saveResult['episode_id'];
  7650. $merged_roles = $saveResult['merged_roles'];
  7651. $merged_scenes = $saveResult['merged_scenes'];
  7652. $merged_props = $saveResult['merged_props'];
  7653. $record_content = $origin_prompt;
  7654. if ($uploaded_content !== '') {
  7655. // $record_content .= "\n\n###上传内容\n" . $uploaded_content;
  7656. }
  7657. $records = [
  7658. [
  7659. 'uid' => $uid,
  7660. 'anime_id' => $anime_id,
  7661. 'role' => 'user',
  7662. 'content' => $record_content,
  7663. 'sequence' => $episode_number,
  7664. 'episode_id' => $episode_id,
  7665. 'created_at' => $now,
  7666. 'updated_at' => $now
  7667. ],
  7668. [
  7669. 'uid' => $uid,
  7670. 'anime_id' => $anime_id,
  7671. 'role' => 'assistant',
  7672. 'content' => $fullContent,
  7673. // 'content' => '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。',
  7674. 'sequence' => $episode_number,
  7675. 'episode_id' => $episode_id,
  7676. 'created_at' => $now,
  7677. 'updated_at' => $now
  7678. ]
  7679. ];
  7680. $boolen4 = DB::table('mp_anime_records')->insert($records);
  7681. if (!$boolen4) {
  7682. Utils::throwError('20003:对话记录保存失败');
  7683. }
  7684. // 保存模型到anime表
  7685. $update_anime_data = [
  7686. 'model' => $model,
  7687. 'updated_at' => $now
  7688. ];
  7689. if ($uploaded_content) {
  7690. $update_anime_data['content'] = $uploaded_content;
  7691. }
  7692. DB::table('mp_animes')->where('id', $anime_id)->update($update_anime_data);
  7693. }catch (\Exception $e) {
  7694. DB::rollBack();
  7695. dLog('deepseek')->info('新建对话错误信息: '.$e->getMessage());
  7696. yield [
  7697. 'type' => 'done',
  7698. 'answer' => $fullContent,
  7699. 'reasoning' => $fullReasoningContent,
  7700. 'usage' => $usage,
  7701. 'error' => $e->getMessage(),
  7702. ];
  7703. return;
  7704. }
  7705. DB::commit();
  7706. if ($is_global_generate_pics) {
  7707. // // 批量生成全局角色图片
  7708. // $this->batchSetGlobalRoleImg([
  7709. // 'anime_id' => $anime_id,
  7710. // ], true);
  7711. // // 批量生成全局场景图片
  7712. // $this->batchSetGlobalSceneImg([
  7713. // 'anime_id' => $anime_id,
  7714. // ], true);
  7715. // // 将全局角色和场景的task_id、task_status和url继承给当前分集
  7716. // $this->inheritGlobalImagesToEpisodes($anime_id, $episode_id);
  7717. }
  7718. $episode['episode_id'] = $episode_id;
  7719. $episode['roles'] = $merged_roles;
  7720. $episode['scenes'] = $merged_scenes;
  7721. // $episode['acts'] = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  7722. yield [
  7723. 'type' => 'done',
  7724. 'episode' => $episode,
  7725. 'answer' => $fullContent,
  7726. 'reasoning' => $fullReasoningContent,
  7727. 'usage' => $usage
  7728. ];
  7729. }
  7730. /**
  7731. * chatForAce的非流式版本 - 用于队列任务
  7732. * 与chatForAce逻辑完全一致,但不使用流式输出
  7733. *
  7734. * @param array $data 请求数据
  7735. * @return array 生成结果
  7736. */
  7737. public function chatForAceNonStream($data) {
  7738. $allChunks = [];
  7739. $finalResult = null;
  7740. // 调用流式方法并收集所有数据
  7741. foreach ($this->chatForAce($data) as $chunk) {
  7742. $allChunks[] = $chunk;
  7743. // 保存最终结果
  7744. if (isset($chunk['type']) && $chunk['type'] === 'done') {
  7745. $finalResult = $chunk;
  7746. }
  7747. }
  7748. // 返回最终结果
  7749. if ($finalResult) {
  7750. return $finalResult;
  7751. }
  7752. // 如果没有done类型的数据,返回最后一个chunk
  7753. return end($allChunks) ?: ['error' => '生成失败'];
  7754. }
  7755. /**
  7756. * 批量生成多个分集
  7757. *
  7758. * @param array $data 请求数据
  7759. * @return array 任务信息
  7760. */
  7761. public function batchGenerateEpisodes($data) {
  7762. $uid = Site::getUid();
  7763. $cpid = Site::getCpid();
  7764. $anime_id = getProp($data, 'anime_id');
  7765. $generate_episode_number = (int)getProp($data, 'generate_episode_number', 1);
  7766. if (!$anime_id) {
  7767. Utils::throwError('20003:anime_id参数缺失');
  7768. }
  7769. if ($generate_episode_number < 1) {
  7770. Utils::throwError('20003:生成集数必须大于0');
  7771. }
  7772. // 获取动漫信息
  7773. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  7774. if (!$anime) {
  7775. Utils::throwError('20003:该剧集不存在');
  7776. }
  7777. // 检查是否是多剧集模式
  7778. if ((int)getProp($anime, 'is_multi') !== 1) {
  7779. Utils::throwError('20003:单剧集不支持批量生成');
  7780. }
  7781. // 获取当前已生成的最大集数
  7782. $currentMaxEpisode = DB::table('mp_anime_episodes')
  7783. ->where('anime_id', $anime_id)
  7784. ->where('is_default', 1)
  7785. ->max('episode_number');
  7786. $currentMaxEpisode = $currentMaxEpisode ?: 0;
  7787. // 确定起始集数
  7788. $startEpisodeNumber = $currentMaxEpisode + 1;
  7789. // 如果用户指定了起始集数(通过episode_number参数)
  7790. if (isset($data['episode_number'])) {
  7791. $userStartEpisode = (int)getProp($data, 'episode_number');
  7792. if ($userStartEpisode > $currentMaxEpisode) {
  7793. $startEpisodeNumber = $userStartEpisode;
  7794. }
  7795. }
  7796. // 计算结束集数
  7797. $endEpisodeNumber = $startEpisodeNumber + $generate_episode_number - 1;
  7798. // 检查是否超过总集数限制
  7799. $end_episode_sequence = getProp($anime, 'end_episode_sequence');
  7800. if ($end_episode_sequence && $endEpisodeNumber > $end_episode_sequence) {
  7801. Utils::throwError("20003:总集数只有{$end_episode_sequence}集,无法生成到第{$endEpisodeNumber}集");
  7802. }
  7803. // 检查是否已有进行中的任务
  7804. $existingTask = DB::table('mp_batch_episode_generation_tasks')
  7805. ->where('anime_id', $anime_id)
  7806. ->whereIn('status', ['pending', 'processing'])
  7807. ->first();
  7808. if ($existingTask) {
  7809. Utils::throwError('20003:该剧集已有批量生成任务正在进行中,请等待完成后再试');
  7810. }
  7811. $now = date('Y-m-d H:i:s');
  7812. // 准备任务数据
  7813. $taskData = [
  7814. 'anime_id' => $anime_id,
  7815. 'uid' => $uid,
  7816. 'cpid' => $cpid,
  7817. 'start_episode' => $startEpisodeNumber,
  7818. 'end_episode' => $endEpisodeNumber,
  7819. 'total_episodes' => $generate_episode_number,
  7820. 'current_episode' => 0,
  7821. 'completed_episodes' => 0,
  7822. 'status' => 'pending',
  7823. 'request_data' => json_encode($data, JSON_UNESCAPED_UNICODE),
  7824. 'created_at' => $now,
  7825. 'updated_at' => $now
  7826. ];
  7827. // 创建批量生成任务记录
  7828. $taskId = DB::table('mp_batch_episode_generation_tasks')->insertGetId($taskData);
  7829. if (!$taskId) {
  7830. Utils::throwError('20003:创建批量生成任务失败');
  7831. }
  7832. // 更新任务状态为processing
  7833. DB::table('mp_batch_episode_generation_tasks')
  7834. ->where('id', $taskId)
  7835. ->update([
  7836. 'status' => 'processing',
  7837. 'updated_at' => $now
  7838. ]);
  7839. // 分发到队列
  7840. \App\Jobs\ProcessBatchEpisodeGenerationJob::dispatch(
  7841. $taskId,
  7842. $anime_id,
  7843. $startEpisodeNumber,
  7844. $generate_episode_number,
  7845. $data,
  7846. $uid,
  7847. $cpid
  7848. );
  7849. return [
  7850. 'task_id' => $taskId,
  7851. 'anime_id' => $anime_id,
  7852. 'start_episode' => $startEpisodeNumber,
  7853. 'end_episode' => $endEpisodeNumber,
  7854. 'total_episodes' => $generate_episode_number,
  7855. 'status' => 'processing',
  7856. 'message' => "已创建批量生成任务,将生成第{$startEpisodeNumber}集到第{$endEpisodeNumber}集,共{$generate_episode_number}集"
  7857. ];
  7858. }
  7859. /**
  7860. * 获取批量生成任务状态
  7861. *
  7862. * @param array $data 请求数据
  7863. * @return array 任务状态信息
  7864. */
  7865. public function getBatchGenerationTaskStatus($data) {
  7866. $task_id = getProp($data, 'task_id');
  7867. $anime_id = getProp($data, 'anime_id');
  7868. if (!$task_id && !$anime_id) {
  7869. Utils::throwError('20003:task_id或anime_id参数缺失');
  7870. }
  7871. $query = DB::table('mp_batch_episode_generation_tasks');
  7872. if ($task_id) {
  7873. $query->where('id', $task_id);
  7874. } else {
  7875. // 获取该anime最新的任务
  7876. $query->where('anime_id', $anime_id)
  7877. ->orderByDesc('id')
  7878. ->limit(1);
  7879. }
  7880. $task = $query->first();
  7881. if (!$task) {
  7882. Utils::throwError('20003:任务不存在');
  7883. }
  7884. // 获取任务详情
  7885. $details = DB::table('mp_batch_episode_generation_details')
  7886. ->where('task_id', $task->id)
  7887. ->orderBy('episode_number')
  7888. ->get()
  7889. ->map(function($item) {
  7890. return [
  7891. 'episode_number' => $item->episode_number,
  7892. 'status' => $item->status,
  7893. 'error_message' => $item->error_message,
  7894. 'created_at' => $item->created_at,
  7895. 'updated_at' => $item->updated_at
  7896. ];
  7897. })
  7898. ->toArray();
  7899. // 计算进度百分比
  7900. $progress = 0;
  7901. if ($task->total_episodes > 0) {
  7902. $progress = round(($task->completed_episodes / $task->total_episodes) * 100, 2);
  7903. }
  7904. return [
  7905. 'task_id' => $task->id,
  7906. 'anime_id' => $task->anime_id,
  7907. 'start_episode' => $task->start_episode,
  7908. 'end_episode' => $task->end_episode,
  7909. 'total_episodes' => $task->total_episodes,
  7910. 'current_episode' => $task->current_episode,
  7911. 'completed_episodes' => $task->completed_episodes,
  7912. 'progress' => $progress,
  7913. 'status' => $task->status,
  7914. 'error_message' => $task->error_message,
  7915. 'details' => $details,
  7916. 'created_at' => $task->created_at,
  7917. 'updated_at' => $task->updated_at,
  7918. 'completed_at' => $task->completed_at
  7919. ];
  7920. }
  7921. /**
  7922. * 智能匹配并替换主体和场景名称
  7923. * 如果生成的主体或场景名称是强制设定名称的子串,则自动替换为完整名称
  7924. *
  7925. * @param array $episode_arr 解析后的剧集数据
  7926. * @param array $extra_roles 强制主体设定(key为主体名称)
  7927. * @param array $extra_scenes 强制场景设定(key为场景名称)
  7928. * @return array 替换后的剧集数据
  7929. */
  7930. private function matchAndReplaceRolesAndScenes($episode_arr, $extra_roles, $extra_scenes) {
  7931. $replaced_count = 0;
  7932. // 1. 处理主体列表
  7933. if (!empty($episode_arr['roles'])) {
  7934. foreach ($episode_arr['roles'] as &$role) {
  7935. $generated_role_name = $role['role'] ?? '';
  7936. // 跳过旁白
  7937. if ($generated_role_name === '旁白') {
  7938. continue;
  7939. }
  7940. // 如果生成的主体名不在强制设定中,尝试模糊匹配
  7941. if (!isset($extra_roles[$generated_role_name])) {
  7942. $matched_role = $this->findMatchingName($generated_role_name, array_keys($extra_roles));
  7943. if ($matched_role) {
  7944. dLog('deepseek')->info("主体名称替换: {$generated_role_name} => {$matched_role}");
  7945. $role['role'] = $matched_role;
  7946. $replaced_count++;
  7947. }
  7948. }
  7949. }
  7950. }
  7951. // 2. 处理场景列表
  7952. if (!empty($episode_arr['scenes'])) {
  7953. foreach ($episode_arr['scenes'] as &$scene) {
  7954. $generated_scene_name = $scene['scene'] ?? '';
  7955. // 如果生成的场景名不在强制设定中,尝试模糊匹配
  7956. if (!isset($extra_scenes[$generated_scene_name])) {
  7957. $matched_scene = $this->findMatchingName($generated_scene_name, array_keys($extra_scenes));
  7958. if ($matched_scene) {
  7959. dLog('deepseek')->info("场景名称替换: {$generated_scene_name} => {$matched_scene}");
  7960. $scene['scene'] = $matched_scene;
  7961. $replaced_count++;
  7962. }
  7963. }
  7964. }
  7965. }
  7966. // 3. 处理分段剧本中的主体和场景引用(全能模式下只使用segment_content字段)
  7967. if (!empty($episode_arr['acts'])) {
  7968. foreach ($episode_arr['acts'] as &$act) {
  7969. if (!empty($act['segments'])) {
  7970. foreach ($act['segments'] as &$segment) {
  7971. if (!empty($segment['segment_content'])) {
  7972. $original_content = $segment['segment_content'];
  7973. $replaced_content = $original_content;
  7974. // 替换场景名 - 在文本中查找并替换
  7975. foreach (array_keys($extra_scenes) as $full_scene_name) {
  7976. // 尝试找到可能的短名称
  7977. $potential_short_names = [];
  7978. // 提取场景名的主要部分(冒号之前)
  7979. if (mb_strpos($full_scene_name, ':') !== false) {
  7980. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  7981. $potential_short_names[] = $short_name;
  7982. } elseif (mb_strpos($full_scene_name, ':') !== false) {
  7983. $short_name = mb_substr($full_scene_name, 0, mb_strpos($full_scene_name, ':'));
  7984. $potential_short_names[] = $short_name;
  7985. }
  7986. // 替换场景字段中的短名称
  7987. foreach ($potential_short_names as $short_name) {
  7988. if ($short_name !== $full_scene_name) {
  7989. $pattern = '/(?<=场景:|场景:|拍摄场景:|拍摄场景:|背景场景:|背景场景:|环境:|环境:)' . preg_quote($short_name, '/') . '(?=\s|$|\n)/u';
  7990. $new_content = preg_replace($pattern, $full_scene_name, $replaced_content);
  7991. if ($new_content !== $replaced_content) {
  7992. $replaced_content = $new_content;
  7993. $replaced_count++;
  7994. dLog('deepseek')->info("场景名替换: {$short_name} => {$full_scene_name}");
  7995. }
  7996. }
  7997. }
  7998. }
  7999. // 替换配音角色名(跳过旁白)
  8000. foreach (array_keys($extra_roles) as $full_role_name) {
  8001. if ($full_role_name === '旁白') {
  8002. continue;
  8003. }
  8004. // 尝试找到可能的短名称
  8005. $potential_short_names = [];
  8006. // 提取角色名的主要部分(短横线之前)
  8007. if (mb_strpos($full_role_name, '-') !== false) {
  8008. $short_name = mb_substr($full_role_name, 0, mb_strpos($full_role_name, '-'));
  8009. $potential_short_names[] = $short_name;
  8010. }
  8011. // 替换配音台词中的短名称
  8012. foreach ($potential_short_names as $short_name) {
  8013. if ($short_name !== $full_role_name) {
  8014. $pattern = '/(?<=配音台词:\[|配音台词:\[|中文配音:\[|中文配音:\[)\s*' . preg_quote($short_name, '/') . '\s*(?=\])/u';
  8015. $new_content = preg_replace($pattern, $full_role_name, $replaced_content);
  8016. if ($new_content !== $replaced_content) {
  8017. $replaced_content = $new_content;
  8018. $replaced_count++;
  8019. dLog('deepseek')->info("角色名替换: {$short_name} => {$full_role_name}");
  8020. }
  8021. }
  8022. }
  8023. }
  8024. // 如果有替换,更新segment_content
  8025. if ($replaced_content !== $original_content) {
  8026. $segment['segment_content'] = $replaced_content;
  8027. }
  8028. }
  8029. }
  8030. }
  8031. }
  8032. }
  8033. if ($replaced_count > 0) {
  8034. logDB('deepseek', 'info', '主体和场景名称智能替换', [
  8035. 'replaced_count' => $replaced_count
  8036. ]);
  8037. }
  8038. return $episode_arr;
  8039. }
  8040. /**
  8041. * 查找匹配的名称
  8042. * 规则:如果生成的名称是强制设定名称的子串(开头部分),则返回匹配的强制设定名称
  8043. *
  8044. * @param string $generated_name 生成的名称
  8045. * @param array $expected_names 预期的名称列表
  8046. * @return string|null 匹配到的名称,如果没有匹配则返回null
  8047. */
  8048. private function findMatchingName($generated_name, $expected_names) {
  8049. if (empty($generated_name)) {
  8050. return null;
  8051. }
  8052. // 尝试精确匹配
  8053. if (in_array($generated_name, $expected_names)) {
  8054. return $generated_name;
  8055. }
  8056. // 尝试模糊匹配:生成的名称是否为某个预期名称的开头部分
  8057. foreach ($expected_names as $expected_name) {
  8058. // 检查生成的名称是否是预期名称的开头(如"沈秋岚"是"沈秋岚-程家居家围裙造型"的开头)
  8059. if (mb_strpos($expected_name, $generated_name) === 0) {
  8060. return $expected_name;
  8061. }
  8062. }
  8063. // 更宽松的匹配:检查生成的名称是否包含在预期名称中的任意位置
  8064. // 这样可以处理一些变体,但优先级较低
  8065. foreach ($expected_names as $expected_name) {
  8066. if (mb_strpos($expected_name, $generated_name) !== false) {
  8067. return $expected_name;
  8068. }
  8069. }
  8070. return null;
  8071. }
  8072. /**
  8073. * 重新生成分段剧本
  8074. * @param array $data 包含以下字段:
  8075. * - prompt: string|null 用户修改要求(可选)
  8076. * - template_id: int|null 提示词模板ID(可选)
  8077. * - act_id: int|null 单个片段ID(与episode_id二选一)
  8078. * - episode_id: int|null 剧集ID,用于重新生成整个剧集的所有片段(与act_id二选一)
  8079. * @return array 返回生成结果
  8080. */
  8081. public function regenerateSegmentScript($data) {
  8082. $uid = Site::getUid();
  8083. $prompt = trim((string)getProp($data, 'prompt', ''));
  8084. $template_id = getProp($data, 'template_id', 0);
  8085. $act_id = getProp($data, 'act_id', 0);
  8086. $episode_id = getProp($data, 'episode_id', 0);
  8087. // 验证:prompt和template_id至少提供一个
  8088. if (empty($prompt) && empty($template_id)) {
  8089. Utils::throwError('20003:请提供修改要求或选择提示词模板');
  8090. }
  8091. // 验证:act_id和episode_id二选一
  8092. if (empty($act_id) && empty($episode_id)) {
  8093. Utils::throwError('20003:请提供片段ID或剧集ID');
  8094. }
  8095. if (!empty($act_id) && !empty($episode_id)) {
  8096. Utils::throwError('20003:片段ID和剧集ID只能选择一个');
  8097. }
  8098. // 如果提供了template_id,获取模板提示词
  8099. $template_prompt = '';
  8100. if ($template_id > 0) {
  8101. $template = DB::table('mp_prompt_templates')
  8102. ->where('id', $template_id)
  8103. ->where('is_deleted', 0)
  8104. ->first();
  8105. if (!$template) {
  8106. Utils::throwError('20003:提示词模板不存在或已删除');
  8107. }
  8108. $template_prompt = $template->template_prompt ?? '';
  8109. }
  8110. // 合并用户提示词和模板提示词
  8111. $final_prompt = '';
  8112. if (!empty($template_prompt)) {
  8113. $final_prompt = $template_prompt;
  8114. if (!empty($prompt)) {
  8115. $final_prompt .= "\n\n补充要求:" . $prompt;
  8116. }
  8117. } else {
  8118. $final_prompt = $prompt;
  8119. }
  8120. // 获取需要重新生成的内容参考
  8121. $reference_content = '';
  8122. $target_episode_id = 0;
  8123. $target_anime_id = 0;
  8124. $target_episode_number = 0;
  8125. if ($act_id > 0) {
  8126. // 单个片段模式:获取该片段的内容
  8127. $segment = DB::table('mp_episode_segments')
  8128. ->where('id', $act_id)
  8129. ->first();
  8130. if (!$segment) {
  8131. Utils::throwError('20003:片段不存在');
  8132. }
  8133. $target_episode_id = $segment->episode_id;
  8134. $target_anime_id = $segment->anime_id;
  8135. $target_episode_number = $segment->episode_number;
  8136. $reference_content = $segment->act_content ?? '';
  8137. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8138. } else {
  8139. // 整个剧集模式:获取所有片段的内容
  8140. $segments = DB::table('mp_episode_segments')
  8141. ->where('episode_id', $episode_id)
  8142. ->orderBy('act_number')
  8143. ->get();
  8144. if ($segments->isEmpty()) {
  8145. Utils::throwError('20003:该剧集没有片段数据');
  8146. }
  8147. $target_episode_id = $episode_id;
  8148. $target_anime_id = $segments[0]->anime_id;
  8149. $target_episode_number = $segments[0]->episode_number;
  8150. // 拼接所有片段内容,保留格式用于AI理解
  8151. $act_contents = [];
  8152. foreach ($segments as $seg) {
  8153. $act_number = $seg->act_number;
  8154. $act_content = $seg->act_content ?? '';
  8155. if (!empty($act_content)) {
  8156. $act_contents[] = "##片段{$act_number}\n" . $act_content;
  8157. }
  8158. }
  8159. $reference_content = implode("\n\n", $act_contents);
  8160. $episode_content = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('content');
  8161. if ($episode_content) {
  8162. $reference_content = "\n\n【本集原始内容】\n{$episode_content}\n\n【本集生成剧本内容】\n{$reference_content}";
  8163. }else {
  8164. $reference_content = "\n\n【原分段剧本内容】\n{$reference_content}";
  8165. }
  8166. }
  8167. if (empty($reference_content)) {
  8168. Utils::throwError('20003:没有可参考的片段内容');
  8169. }
  8170. // 获取剧集的基本信息(intro、art_style、roles、scenes)
  8171. $episode = DB::table('mp_anime_episodes')
  8172. ->where('id', $target_episode_id)
  8173. ->first();
  8174. if (!$episode) {
  8175. Utils::throwError('20003:剧集不存在');
  8176. }
  8177. $anime = DB::table('mp_animes')->where('id', $target_anime_id)->first();
  8178. $anime_script_id = getProp($anime, 'script_id');
  8179. $intro = $episode->intro ?? '';
  8180. $art_style = $episode->art_style ?? '';
  8181. $roles = json_decode($episode->roles ?? '[]', true);
  8182. $scenes = json_decode($episode->scenes ?? '[]', true);
  8183. // 构建提示词中的主体列表和场景列表参考
  8184. $roles_ref = '';
  8185. if (!empty($roles) && is_array($roles)) {
  8186. $roles_list = [];
  8187. foreach ($roles as $role) {
  8188. $role_name = getProp($role, 'role', '');
  8189. $role_desc = getProp($role, 'description', '');
  8190. $pic_prompt = getProp($role, 'pic_prompt', '');
  8191. $voice_prompt = getProp($role, 'voice_prompt', '');
  8192. if (!empty($role_name)) {
  8193. $role_line = $role_name;
  8194. if (!empty($role_desc)) $role_line .= ":" . $role_desc;
  8195. if (!empty($pic_prompt)) $role_line .= "{" . $pic_prompt . "}";
  8196. if (!empty($voice_prompt)) $role_line .= "{{" . $voice_prompt . "}}";
  8197. $roles_list[] = $role_line;
  8198. }
  8199. }
  8200. if (!empty($roles_list)) {
  8201. $roles_ref = "\n\n【主体列表参考】\n" . implode("\n", $roles_list);
  8202. }
  8203. }
  8204. $scenes_ref = '';
  8205. if (!empty($scenes) && is_array($scenes)) {
  8206. $scenes_list = [];
  8207. foreach ($scenes as $scene) {
  8208. $scene_name = getProp($scene, 'scene', '');
  8209. $scene_desc = getProp($scene, 'description', '');
  8210. $pic_prompt = getProp($scene, 'pic_prompt', '');
  8211. if (!empty($scene_name)) {
  8212. $scene_line = $scene_name;
  8213. if (!empty($scene_desc)) $scene_line .= ":" . $scene_desc;
  8214. if (!empty($pic_prompt)) $scene_line .= "{" . $pic_prompt . "}";
  8215. $scenes_list[] = $scene_line;
  8216. }
  8217. }
  8218. if (!empty($scenes_list)) {
  8219. $scenes_ref = "\n\n【场景列表参考】\n" . implode("\n", $scenes_list);
  8220. }
  8221. }
  8222. // 构建美术风格参考
  8223. $art_style_ref = '';
  8224. if (!empty($art_style)) {
  8225. $art_style_ref = "\n\n【美术风格参考】\n" . $art_style;
  8226. }
  8227. // 构建内容简介参考
  8228. $intro_ref = '';
  8229. if (!empty($intro)) {
  8230. $intro_ref = "\n\n【内容简介参考】\n" . $intro;
  8231. }
  8232. // 构建完整的AI提示词
  8233. // $system_prompt = "你是一个专业的剧本编剧和影视导演,擅长根据已有的分段剧本进行优化和调整。你需要严格按照用户的要求重新生成分段剧本内容,保持原有的格式和结构。";
  8234. $user_prompt = "请根据以下要求重新生成分段剧本:\n\n【用户要求】\n{$final_prompt}";
  8235. $user_prompt .= $intro_ref;
  8236. $user_prompt .= $art_style_ref;
  8237. $user_prompt .= $reference_content;
  8238. // $user_prompt .= $roles_ref;
  8239. // $user_prompt .= $scenes_ref;
  8240. $system_prompt = "\n\n【强制要求】\n";
  8241. $system_prompt .= "- 请仅生成<分段剧本>部分,不要生成其他任何内容:";
  8242. $system_prompt .= "- 每个分镜包含:分镜序号、场景、画面、运镜、配音台词、背景音效\n";
  8243. $system_prompt .= "- 场景必须从【场景列表参考】中选择(如果提供了场景列表),场景名必须精确匹配【场景列表参考】中的名称(如需匹配“酒店会客室-景池筹备会版”,而不是“酒店会客室”,不得缺少“-”后面“:”前面的任何内容,不能自创){$scenes_ref}\n";
  8244. $system_prompt .= "- 出场角色必须从【主体列表参考】中选择(如果提供了主体列表),角色名必须精准匹配【主体列表参考】中的名称(如需匹配“沈秋岚-程家居家围裙造型”,而不是“沈秋岚”,不得缺少“-”后面“:”前面的任何内容,不能自创){$roles_ref}\n";
  8245. $system_prompt .= "- 保持美术风格的一致性(如果提供了美术风格参考)\n";
  8246. $system_prompt .= "- 参考示例格式如下,此为第一优先规则,必须按以下格式生成内容,请忽略其他任何提示词部分关于规则的描述:
  8247. ###分段剧本
  8248. 片段数量:8
  8249. 旁白音色:成年男性(约35-50岁),音色厚重且富有磁性,带有老电影叙事般的沧桑感,语调低沉平稳,富有江湖气息。
  8250. ##片段1
  8251. 时长:12s
  8252. 分镜1
  8253. 场景:边境小镇街道
  8254. 画面:[大远景,冷色调,高对比度] 漫天黄沙在狂风中如怒龙翻滚,遮蔽了微弱的星光。悦来酒馆残破的木门在风中剧烈摇晃,铁链撞击木板发出沉重的闷响,四周建筑尽显荒凉。
  8255. 运镜:大远景固定镜头,随后风沙席卷向镜头形成遮挡转场。
  8256. 配音台词:
  8257. 背景音效:
  8258. 分镜2
  8259. 场景:悦来酒馆
  8260. 画面:[全景,暖色调阴影构图] 酒馆内部昏暗,几盏油灯在风中疯狂摇曳,投射出扭曲的长影。角落里的食客低头缩颈,双手紧紧攥着粗瓷碗,空气中漂浮着细小的尘埃。
  8261. 运镜:缓慢横移,掠过阴影中瑟缩的食客。
  8262. 配音台词:
  8263. 背景音效:
  8264. 分镜3
  8265. 场景:悦来酒馆
  8266. 画面:[中景,三分法构图] 三名大汉围坐在正中央的圆桌旁,腰间挂着的“武林盟”金色令牌在灯火下闪烁。桌上残羹冷炙横陈,一名大汉正张狂地大笑,脚踩在长凳上。
  8267. 运镜:从中景推向令牌特写。
  8268. 配音台词:
  8269. 背景音效:
  8270. 分镜4
  8271. 场景:悦来酒馆
  8272. 画面:[特写,低角度仰拍] 刀疤脸横肉颤动,嘴角挂着轻蔑的笑。他随手倾覆手中的酒碗,琥珀色的液体在空中划过弧线,重重溅在老李打着补丁的布鞋和裤脚上。
  8273. 运镜:极速推向酒水溅起的瞬间。
  8274. 配音台词:
  8275. 背景音效:
  8276. 分镜5
  8277. 镜头描述
  8278. 场景:悦来酒馆
  8279. 画面:[近景,荷兰角倾斜构图] 刀疤脸斜睨着眼,昏暗的灯光勾勒出他脸上狰狞的伤疤。他身体前倾,阴影完全笼罩了对面的老李,眼神如毒蛇般阴冷。
  8280. 运镜:固定机位,利用倾斜构图制造压迫感。
  8281. 配音台词:中文配音:[刀疤脸]老李头,这酒里掺水了吧?
  8282. 背景音效:";
  8283. // 获取模型配置
  8284. $model = getProp($data, 'model');
  8285. if (!$model) {
  8286. $model = $anime ? ($anime->model ?? 'deepseek-v4-pro') : 'deepseek-v4-pro';
  8287. }
  8288. // 验证模型是否在可用模型表中
  8289. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  8290. $model = 'deepseek-v4-pro';
  8291. }
  8292. // 模型兼容性处理
  8293. $thinkingMode = 'disabled';
  8294. $reasoningEffort = 'high';
  8295. if ($model === 'deepseek-chat') {
  8296. $model = 'deepseek-v4-flash';
  8297. $thinkingMode = 'disabled';
  8298. } elseif ($model === 'deepseek-reasoner') {
  8299. $model = 'deepseek-v4-flash';
  8300. $thinkingMode = 'enabled';
  8301. }
  8302. // 构建消息
  8303. $messages = [
  8304. [
  8305. 'role' => 'system',
  8306. 'content' => $system_prompt
  8307. ],
  8308. [
  8309. 'role' => 'user',
  8310. 'content' => $user_prompt
  8311. ]
  8312. ];
  8313. // dd($messages);
  8314. // 构建请求参数
  8315. $post_data = [
  8316. 'model' => $model,
  8317. 'messages' => $messages,
  8318. 'temperature' => 0.7,
  8319. 'frequency_penalty' => 0,
  8320. 'presence_penalty' => 0,
  8321. 'response_format' => ['type' => 'text'],
  8322. 'thinking' => ['type' => $thinkingMode],
  8323. 'stream' => false // 非流式输出
  8324. ];
  8325. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  8326. // 调用AI生成新的分段剧本
  8327. try {
  8328. $fullContent = '';
  8329. $usage = [];
  8330. // 根据模型类型选择调用方法
  8331. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  8332. // DeepSeek 官方模型使用 DeepSeek API
  8333. $chatResult = $this->chatOnly($post_data);
  8334. } else if (in_array($model, $this->gpt_text_models)) {
  8335. // GPT 模型使用 TokenRouter API
  8336. $chatResult = $this->gpt54ChatOnly($post_data);
  8337. } else {
  8338. // 其他模型使用火山引擎API
  8339. $chatResult = $this->volcEngineChatCompletion($post_data);
  8340. }
  8341. if (is_array($chatResult)) {
  8342. $fullContent = $chatResult['fullContent'] ?? '';
  8343. $usage = $chatResult['usage'] ?? [];
  8344. }
  8345. $generated_content = $fullContent;
  8346. if (empty($generated_content)) {
  8347. Utils::throwError('20003:AI生成内容为空,请重试');
  8348. }
  8349. // 解析生成的内容 - 按片段分割
  8350. $parsed_segments = [];
  8351. // 先在开头添加换行符,确保第1片段也能被正确分割
  8352. $normalizedText = "\n" . $generated_content;
  8353. $parts = preg_split('/\n\s*##/', $normalizedText);
  8354. foreach ($parts as $part) {
  8355. $part = trim($part);
  8356. if (empty($part)) continue;
  8357. // 匹配"片段X"格式
  8358. if (!preg_match('/^片段\d+/', $part)) {
  8359. continue;
  8360. }
  8361. // 分离标题和内容
  8362. $lines = explode("\n", $part, 2);
  8363. $actTitle = trim($lines[0]);
  8364. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  8365. // 解析标题,提取序号
  8366. $actNumber = 0;
  8367. if (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  8368. $actNumber = intval($segmentTitleMatch[1]);
  8369. } else {
  8370. $actNumber = count($parsed_segments) + 1;
  8371. }
  8372. // 提取时长(仅保留数字)
  8373. $actDuration = 0;
  8374. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  8375. $actDurationStr = trim($actDurationMatch[1]);
  8376. // 提取数字部分(支持整数和小数)
  8377. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  8378. $actDuration = (float)$numMatch[1];
  8379. }
  8380. }
  8381. // 清理act_content:去除时长、旁白音色等非分镜内容行
  8382. // 只保留分镜内容,并确保分镜标记使用【】格式
  8383. $cleaned_content = '';
  8384. $content_lines = explode("\n", $actContent);
  8385. $is_capturing = false; // 标记是否开始捕获分镜内容
  8386. $count = 0;
  8387. foreach ($content_lines as $line) {
  8388. $trimmed_line = trim($line);
  8389. // 跳过时长和旁白音色行
  8390. if (preg_match('/^(时长|旁白音色)[::]/u', $trimmed_line)) {
  8391. continue;
  8392. }
  8393. // 检测是否是分镜开始
  8394. // 支持格式:【分镜X】、【镜头X】、分镜X、镜头X
  8395. if (preg_match('/^(?:【)?(分镜|镜头)(\d+)(?:】)?/u', $trimmed_line, $shot_match)) {
  8396. $count++;
  8397. $is_capturing = true;
  8398. // 如果没有【】,则添加
  8399. if (!preg_match('/^【/u', $trimmed_line)) {
  8400. $trimmed_line = preg_replace('/^(分镜|镜头)(\d+)/u', '【$1$2】', $trimmed_line);
  8401. }
  8402. if ($count > 1) $trimmed_line = "\n".$trimmed_line;
  8403. }
  8404. // 如果已经开始捕获,则添加该行
  8405. if ($is_capturing && !empty($trimmed_line)) {
  8406. $cleaned_content .= $trimmed_line."\n";
  8407. }
  8408. }
  8409. $cleaned_content = str_replace(["@", "{", "}"], "", $cleaned_content);
  8410. $parsed_segments[] = [
  8411. 'act_number' => $actNumber,
  8412. 'act_title' => $actTitle,
  8413. 'act_duration' => $actDuration,
  8414. 'act_content' => $cleaned_content,
  8415. ];
  8416. }
  8417. if (empty($parsed_segments)) {
  8418. Utils::throwError('20003:无法解析生成的分段剧本,请检查格式');
  8419. }
  8420. // 获取角色和场景名称用于标记
  8421. $role_names = [];
  8422. $scene_names = [];
  8423. if (!empty($roles) && is_array($roles)) {
  8424. foreach ($roles as $role) {
  8425. $role_name = getProp($role, 'role', '');
  8426. if (!empty($role_name)) {
  8427. $role_names[] = $role_name;
  8428. }
  8429. }
  8430. }
  8431. if (!empty($scenes) && is_array($scenes)) {
  8432. foreach ($scenes as $scene) {
  8433. $scene_name = getProp($scene, 'scene', '');
  8434. if (!empty($scene_name)) {
  8435. $scene_names[] = $scene_name;
  8436. }
  8437. }
  8438. }
  8439. // 处理每个片段的 act_show_content
  8440. foreach ($parsed_segments as &$segment) {
  8441. $act_content = getProp($segment, 'act_content', '');
  8442. if (empty($act_content)) {
  8443. $segment['act_show_content'] = '';
  8444. continue;
  8445. }
  8446. $processed_content = $act_content;
  8447. // 先匹配场景(在"场景:"后面)
  8448. foreach ($scene_names as $scene_name) {
  8449. // 转义特殊字符
  8450. $escaped_scene = preg_quote($scene_name, '/');
  8451. // 匹配场景:后面的场景名称(可能换行,也可能不换行)
  8452. $pattern = '/(场景:[\s\r\n]*)(' . $escaped_scene . ')/u';
  8453. $processed_content = preg_replace_callback($pattern, function($matches) {
  8454. $prefix = $matches[1];
  8455. $scene_name = $matches[2];
  8456. // 检查是否已经被标记
  8457. if (strpos($scene_name, '{') === false && strpos($scene_name, '}') === false) {
  8458. return $prefix . '{' . $scene_name . '}';
  8459. }
  8460. return $matches[0];
  8461. }, $processed_content);
  8462. }
  8463. // 再匹配角色名称(只在"画面:"部分)
  8464. foreach ($role_names as $role_name) {
  8465. // 转义特殊字符
  8466. $escaped_role = preg_quote($role_name, '/');
  8467. // 只匹配"画面:"开始到换行之前的内容
  8468. $pattern = '/(画面:[^\n]*)/u';
  8469. $processed_content = preg_replace_callback($pattern, function($matches) use ($escaped_role) {
  8470. $line = $matches[1]; // 整行"画面:xxxxx"
  8471. // 在这一行中匹配所有角色名(避免重复标记)
  8472. $new_line = preg_replace(
  8473. '/(?<![{])(' . $escaped_role . ')(?![}])/u',
  8474. '{$1}',
  8475. $line
  8476. );
  8477. return $new_line;
  8478. }, $processed_content);
  8479. }
  8480. // 处理【镜头X】或【分镜X】重新编号为从1开始的连续整数【镜头X】
  8481. $shot_counter = 0;
  8482. $processed_content = preg_replace_callback(
  8483. '/【(?:镜头|分镜)(\d+)】/u',
  8484. function($matches) use (&$shot_counter) {
  8485. $shot_counter++;
  8486. return '【镜头' . $shot_counter . '】';
  8487. },
  8488. $processed_content
  8489. );
  8490. $segment['act_show_content'] = $processed_content;
  8491. }
  8492. unset($segment); // 解除引用
  8493. // 保存到数据库
  8494. $now = date('Y-m-d H:i:s');
  8495. $saved_acts = []; // 用于记录保存后的片段信息
  8496. if ($act_id > 0) {
  8497. // 单个片段模式:更新单条记录
  8498. if (count($parsed_segments) > 0) {
  8499. $new_segment = $parsed_segments[0];
  8500. $update_data = [
  8501. 'act_content' => getProp($new_segment, 'act_content', ''),
  8502. 'act_show_content' => getProp($new_segment, 'act_show_content', ''),
  8503. 'act_title' => getProp($new_segment, 'act_title', ''),
  8504. 'act_duration' => getProp($new_segment, 'act_duration', 0),
  8505. 'updated_at' => $now,
  8506. ];
  8507. DB::table('mp_episode_segments')
  8508. ->where('id', $act_id)
  8509. ->update($update_data);
  8510. // 获取更新后的记录
  8511. $updated_act = DB::table('mp_episode_segments')
  8512. ->where('id', $act_id)
  8513. ->first();
  8514. if ($updated_act) {
  8515. $saved_acts[] = [
  8516. 'act_id' => $updated_act->id,
  8517. 'act_number' => $updated_act->act_number,
  8518. 'act_duration' => $updated_act->video_duration ? $updated_act->video_duration : $updated_act->act_duration,
  8519. 'act_content' => $updated_act->act_content,
  8520. 'act_show_content' => $updated_act->act_show_content,
  8521. 'video_url' => $updated_act->video_url ?? '',
  8522. 'video_duration' => $updated_act->video_duration ?? 0,
  8523. 'video_time_point_start' => $updated_act->video_time_point_start ?? 0,
  8524. 'video_time_point_end' => $updated_act->video_time_point_end ?? 0,
  8525. ];
  8526. }
  8527. dLog('deepseek')->info('单个片段重新生成成功', ['act_id' => $act_id]);
  8528. }
  8529. } else {
  8530. // 整个剧集模式:删除原有记录并批量保存新记录
  8531. DB::beginTransaction();
  8532. try {
  8533. // 删除原有的所有片段记录
  8534. DB::table('mp_episode_segments')
  8535. ->where('episode_id', $target_episode_id)
  8536. ->delete();
  8537. // 批量插入新的片段记录
  8538. $segments_to_insert = [];
  8539. foreach ($parsed_segments as $index => $segment) {
  8540. $act_number = $index + 1;
  8541. $segments_to_insert[] = [
  8542. 'anime_id' => $target_anime_id,
  8543. 'episode_id' => $target_episode_id,
  8544. 'episode_number' => $target_episode_number,
  8545. 'act_number' => $act_number,
  8546. 'act_title' => getProp($segment, 'act_title', ''),
  8547. 'act_duration' => getProp($segment, 'act_duration', 0),
  8548. 'act_content' => getProp($segment, 'act_content', ''),
  8549. 'act_show_content' => getProp($segment, 'act_show_content', ''),
  8550. 'created_at' => $now,
  8551. 'updated_at' => $now,
  8552. ];
  8553. }
  8554. if (!empty($segments_to_insert)) {
  8555. DB::table('mp_episode_segments')->insert($segments_to_insert);
  8556. }
  8557. DB::commit();
  8558. // 查询保存后的所有片段记录
  8559. $saved_segments = DB::table('mp_episode_segments')
  8560. ->where('episode_id', $target_episode_id)
  8561. ->orderBy('act_number')
  8562. ->get();
  8563. foreach ($saved_segments as $saved_segment) {
  8564. $saved_acts[] = [
  8565. 'act_id' => $saved_segment->id,
  8566. 'act_number' => $saved_segment->act_number,
  8567. 'act_duration' => $saved_segment->video_duration ? $saved_segment->video_duration : $saved_segment->act_duration,
  8568. 'act_content' => $saved_segment->act_content,
  8569. 'act_show_content' => $saved_segment->act_show_content,
  8570. 'video_url' => $saved_segment->video_url ?? '',
  8571. 'video_duration' => $saved_segment->video_duration ?? 0,
  8572. 'video_time_point_start' => $saved_segment->video_time_point_start ?? 0,
  8573. 'video_time_point_end' => $saved_segment->video_time_point_end ?? 0,
  8574. ];
  8575. }
  8576. dLog('deepseek')->info('整个剧集片段重新生成成功', [
  8577. 'episode_id' => $target_episode_id,
  8578. 'segments_count' => count($segments_to_insert)
  8579. ]);
  8580. } catch (\Exception $e) {
  8581. DB::rollBack();
  8582. dLog('deepseek')->error('保存重新生成的片段失败: ' . $e->getMessage());
  8583. Utils::throwError('20003:保存失败,请重试');
  8584. }
  8585. }
  8586. // 构造返回数据结构(参考AnimeService返回格式,但不包含products)
  8587. return [
  8588. 'anime_id' => $target_anime_id,
  8589. 'episode_id' => $target_episode_id,
  8590. 'title' => getProp($episode, 'title', ''),
  8591. 'episode_number' => $target_episode_number,
  8592. 'is_generated' => getProp($episode, 'is_generated', 0),
  8593. 'acts' => $saved_acts,
  8594. ];
  8595. } catch (\Exception $e) {
  8596. dLog('deepseek')->error('重新生成分段剧本失败: ' . $e->getMessage());
  8597. throw $e;
  8598. }
  8599. }
  8600. private function buildSingleEpisodeFromScript(array $script_arr, string $fullContent, string $animeName = ''): array
  8601. {
  8602. $episode_arr = [
  8603. 'episode_title' => $animeName, // 单剧集默认使用剧本名
  8604. 'intro' => getProp($script_arr, 'intro'),
  8605. 'art_style' => getProp($script_arr, 'art_style'),
  8606. 'roles' => is_array(getProp($script_arr, 'roles')) ? getProp($script_arr, 'roles') : [],
  8607. 'scenes' => is_array(getProp($script_arr, 'scenes')) ? getProp($script_arr, 'scenes') : [],
  8608. 'acts' => is_array(getProp($script_arr, 'acts')) ? getProp($script_arr, 'acts') : [],
  8609. ];
  8610. if (empty($episode_arr['acts'])) {
  8611. $fallback_episode_arr = handleEpisodeContent($fullContent);
  8612. if (!empty($fallback_episode_arr['acts'])) {
  8613. $episode_arr = array_merge($fallback_episode_arr, [
  8614. 'intro' => getProp($fallback_episode_arr, 'intro') ?: getProp($script_arr, 'intro'),
  8615. 'art_style' => getProp($fallback_episode_arr, 'art_style') ?: getProp($script_arr, 'art_style'),
  8616. 'roles' => !empty(getProp($fallback_episode_arr, 'roles')) ? getProp($fallback_episode_arr, 'roles') : getProp($script_arr, 'roles', []),
  8617. 'scenes' => !empty(getProp($fallback_episode_arr, 'scenes')) ? getProp($fallback_episode_arr, 'scenes') : getProp($script_arr, 'scenes', []),
  8618. ]);
  8619. }
  8620. }
  8621. // if (!getProp($episode_arr, 'episode_title')) {
  8622. // $episode_title = '';
  8623. // $episodes = getProp($script_arr, 'episodes', []);
  8624. // if (is_array($episodes) && !empty($episodes[0]['title'])) {
  8625. // $episode_title = '第1集:' . $episodes[0]['title'];
  8626. // }
  8627. // if (!$episode_title) {
  8628. // $episode_title = '第1集:' . ($animeName ?: '未命名');
  8629. // }
  8630. // $episode_arr['episode_title'] = $episode_title;
  8631. // }
  8632. return $episode_arr;
  8633. }
  8634. private function saveEpisodeVersionData(
  8635. int $anime_id,
  8636. int $episode_number,
  8637. array $episode_arr,
  8638. array $existing_roles,
  8639. array $existing_scenes,
  8640. array $existing_props,
  8641. $current_episode,
  8642. $base_episode,
  8643. bool $is_regenerate_version,
  8644. string $content,
  8645. string $now,
  8646. array $ref_products = []
  8647. ): array {
  8648. $generated_roles = isset($episode_arr['roles']) && is_array($episode_arr['roles']) ? $episode_arr['roles'] : [];
  8649. $generated_scenes = isset($episode_arr['scenes']) && is_array($episode_arr['scenes']) ? $episode_arr['scenes'] : [];
  8650. $generated_props = isset($episode_arr['props']) && is_array($episode_arr['props']) ? $episode_arr['props'] : [];
  8651. $merged_roles = $generated_roles;
  8652. $merged_scenes = $generated_scenes;
  8653. $merged_props = $generated_props;
  8654. // $merged_roles = $this->mergeEpisodeResourceItems($existing_roles, $generated_roles, 'role');
  8655. // $merged_scenes = $this->mergeEpisodeResourceItems($existing_scenes, $generated_scenes, 'scene');
  8656. // 获取 mp_animes 表中的全局 roles 和 scenes 用于对比
  8657. $anime = DB::table('mp_animes')->where('id', $anime_id)->first();
  8658. $ace_mode = getProp($anime, 'ace_mode');
  8659. dLog('deepseek')->info('ace_mode', ['ace_mode' => $ace_mode]);
  8660. $global_roles = json_decode(getProp($anime, 'roles'), true);
  8661. $global_scenes = json_decode(getProp($anime, 'scenes'), true);
  8662. $global_roles = is_array($global_roles) ? $global_roles : [];
  8663. $global_scenes = is_array($global_scenes) ? $global_scenes : [];
  8664. $art_style = getProp($episode_arr, 'art_style') ?: getProp($anime, 'art_style');
  8665. $art_style_type = getProp($anime, 'art_style_type');
  8666. // 检查并创建 roles 的图片生成任务
  8667. // $merged_roles = $this->checkAndCreateImageTasks($merged_roles, $global_roles, 'role', $art_style);
  8668. // 检查并创建 scenes 的图片生成任务
  8669. // $merged_scenes = $this->checkAndCreateImageTasks($merged_scenes, $global_scenes, 'scene', $art_style);
  8670. $arr = $this->batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $merged_roles, $merged_scenes, $merged_props, $ref_products, $art_style_type);
  8671. if ($arr && is_array($arr)) {
  8672. $merged_roles = $arr['roles'];
  8673. $merged_scenes = $arr['scenes'];
  8674. $merged_props = isset($arr['props']) ? $arr['props'] : [];
  8675. }
  8676. // 确保数据是数组类型
  8677. if (!is_array($merged_roles)) {
  8678. dLog('deepseek')->error('merged_roles不是数组类型', [
  8679. 'type' => gettype($merged_roles),
  8680. 'value' => $merged_roles
  8681. ]);
  8682. $merged_roles = [];
  8683. }
  8684. if (!is_array($merged_scenes)) {
  8685. dLog('deepseek')->error('merged_scenes不是数组类型', [
  8686. 'type' => gettype($merged_scenes),
  8687. 'value' => $merged_scenes
  8688. ]);
  8689. $merged_scenes = [];
  8690. }
  8691. if (!is_array($merged_props)) {
  8692. dLog('deepseek')->error('merged_props不是数组类型', [
  8693. 'type' => gettype($merged_props),
  8694. 'value' => $merged_props
  8695. ]);
  8696. $merged_props = [];
  8697. }
  8698. // 同步新出现的主体和场景到全局
  8699. // $this->syncNewResourcesToGlobal($anime_id, $merged_roles, $merged_scenes, $global_roles, $global_scenes);
  8700. $role_arr = [];
  8701. foreach ($merged_roles as $item) {
  8702. $role_arr[$item['role']] = $item;
  8703. }
  8704. $version_count = DB::table('mp_anime_episodes')
  8705. ->where('anime_id', $anime_id)
  8706. ->where('episode_number', $episode_number)
  8707. ->count('id');
  8708. $episode = [
  8709. 'anime_id' => $anime_id,
  8710. 'episode_number' => $episode_number,
  8711. 'title' => getProp($episode_arr, 'episode_title'),
  8712. 'content' => $content,
  8713. 'intro' => getProp($episode_arr, 'intro'),
  8714. 'art_style' => getProp($episode_arr, 'art_style'),
  8715. 'roles' => json_encode($merged_roles, 256),
  8716. 'scenes' => json_encode($merged_scenes, 256),
  8717. 'props' => json_encode($merged_props, 256),
  8718. 'generate_status' => '待执行',
  8719. 'generate_at' => $now,
  8720. 'is_default' => 1,
  8721. 'updated_at' => $now,
  8722. ];
  8723. $del_flag = false;
  8724. if ($is_regenerate_version) {
  8725. DB::table('mp_anime_episodes')
  8726. ->where('anime_id', $anime_id)
  8727. ->where('episode_number', $episode_number)
  8728. ->update(['is_default' => 0, 'updated_at' => $now]);
  8729. $episode['sequence'] = $version_count + 1;
  8730. $episode['created_at'] = $now;
  8731. $episode['cpid'] = Site::getCpid();
  8732. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  8733. if (!$episode_id) {
  8734. Utils::throwError('20003:创建剧集版本失败');
  8735. }
  8736. } else {
  8737. $target_episode = $current_episode ?: $base_episode;
  8738. if ($target_episode) {
  8739. $episode_id = getProp($target_episode, 'id');
  8740. $episode['sequence'] = getProp($target_episode, 'sequence', 1);
  8741. DB::table('mp_anime_episodes')
  8742. ->where('anime_id', $anime_id)
  8743. ->where('episode_number', $episode_number)
  8744. ->where('id', '<>', $episode_id)
  8745. ->update(['is_default' => 0, 'updated_at' => $now]);
  8746. $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update($episode);
  8747. if ($boolen === false) {
  8748. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  8749. Utils::throwError('20003:分集内容保存失败');
  8750. }
  8751. $del_flag = true;
  8752. } else {
  8753. DB::table('mp_anime_episodes')
  8754. ->where('anime_id', $anime_id)
  8755. ->where('episode_number', $episode_number)
  8756. ->update(['is_default' => 0, 'updated_at' => $now]);
  8757. $episode['sequence'] = $version_count > 0 ? ($version_count + 1) : 1;
  8758. $episode['created_at'] = $now;
  8759. $episode['cpid'] = Site::getCpid();
  8760. $episode_id = DB::table('mp_anime_episodes')->insertGetId($episode);
  8761. if (!$episode_id) {
  8762. logDB('deepseek', 'error', '分集内容保存失败', ['anime_id' => $anime_id, 'episode_number' => $episode_number]);
  8763. Utils::throwError('20003:分集内容保存失败');
  8764. }
  8765. }
  8766. }
  8767. $segments = [];
  8768. $acts = isset($episode_arr['acts']) && is_array($episode_arr['acts']) ? $episode_arr['acts'] : [];
  8769. // 如果是第2集及以后,获取上一集的主体音色数据
  8770. $previous_roles_voice = [];
  8771. if ($episode_number >= 2) {
  8772. $previous_episode = DB::table('mp_anime_episodes')
  8773. ->where('anime_id', $anime_id)
  8774. ->where('episode_number', $episode_number - 1)
  8775. ->where('is_default', 1)
  8776. ->first();
  8777. if ($previous_episode) {
  8778. $previous_roles = json_decode(getProp($previous_episode, 'roles'), true);
  8779. if (is_array($previous_roles)) {
  8780. foreach ($previous_roles as $prev_role) {
  8781. $role_name = getProp($prev_role, 'role');
  8782. if ($role_name) {
  8783. $previous_roles_voice[$role_name] = [
  8784. 'voice_name' => getProp($prev_role, 'voice_name'),
  8785. 'voice_type' => getProp($prev_role, 'voice_type'),
  8786. 'voice_audio_url' => getProp($prev_role, 'voice_audio_url'),
  8787. ];
  8788. $voice_prompt = getProp($prev_role, 'voice_prompt');
  8789. if ($voice_prompt) {
  8790. $previous_roles_voice[$role_name]['voice_prompt'] = $voice_prompt;
  8791. }
  8792. }
  8793. }
  8794. }
  8795. }
  8796. }
  8797. // 将继承的音色数据同步到当前集的主体列表
  8798. if (!empty($previous_roles_voice)) {
  8799. foreach ($merged_roles as &$role) {
  8800. $role_name = getProp($role, 'role');
  8801. if ($role_name && isset($previous_roles_voice[$role_name])) {
  8802. // 强制继承上一集的音色数据
  8803. $role['voice_name'] = $previous_roles_voice[$role_name]['voice_name'];
  8804. $role['voice_type'] = $previous_roles_voice[$role_name]['voice_type'];
  8805. $role['voice_audio_url'] = $previous_roles_voice[$role_name]['voice_audio_url'];
  8806. // 如果上一集有 voice_prompt 则继承,否则跳过
  8807. if (!empty($previous_roles_voice[$role_name]['voice_prompt'])) {
  8808. $role['voice_prompt'] = $previous_roles_voice[$role_name]['voice_prompt'];
  8809. }
  8810. }
  8811. }
  8812. unset($role); // 解除引用
  8813. // 更新 role_arr 以便后续使用
  8814. $role_arr = [];
  8815. foreach ($merged_roles as $item) {
  8816. $role_arr[$item['role']] = $item;
  8817. }
  8818. }
  8819. $emotion_list = DB::table('mp_emotion_list')->where('is_enabled', 1)->pluck('emotion_name', 'emotion_code')->toArray();
  8820. $emotion_list = array_flip($emotion_list);
  8821. foreach ($acts as $act) {
  8822. $act_segments = getProp($act, 'segments', []);
  8823. if (!is_array($act_segments)) {
  8824. continue;
  8825. }
  8826. if ((int)$ace_mode === 1) {
  8827. // ace_mode=1: 按幕合并 segment_content,每幕只存一条记录
  8828. $merged_parts = [];
  8829. foreach ($act_segments as $seg) {
  8830. $seg_num = getProp($seg, 'segment_number');
  8831. $seg_content = getProp($seg, 'segment_content');
  8832. $merged_parts[] = "【分镜{$seg_num}】\n{$seg_content}\n";
  8833. }
  8834. $act_content = implode("\n", $merged_parts);
  8835. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  8836. $segments[] = [
  8837. 'anime_id' => $anime_id,
  8838. 'episode_id' => $episode_id,
  8839. 'episode_number' => $episode_number,
  8840. 'act_number' => getProp($act, 'act_number'),
  8841. 'act_title' => getProp($act, 'act_title'),
  8842. 'act_duration' => getProp($act, 'act_duration'),
  8843. 'act_content' => $act_content,
  8844. 'created_at' => $now,
  8845. 'updated_at' => $now
  8846. ];
  8847. } else {
  8848. foreach ($act_segments as $segment) {
  8849. $voice_actor = getProp($segment, 'voice_actor');
  8850. // 优先从上一集继承音色数据
  8851. $timbre_info = [];
  8852. if (isset($previous_roles_voice[$voice_actor])) {
  8853. // 从上一集继承音色数据
  8854. $timbre_info = $previous_roles_voice[$voice_actor];
  8855. } elseif (isset($role_arr[$voice_actor])) {
  8856. // 使用当前集的主体音色数据
  8857. $timbre_info = $role_arr[$voice_actor];
  8858. }
  8859. $voice_type = getProp($timbre_info, 'voice_type');
  8860. $timbre_emotion = DB::table('mp_timbres')->where('timbre_type', $voice_type)->value('emotion');
  8861. if ($timbre_emotion) {
  8862. $timbre_emotion = explode(',', $timbre_emotion);
  8863. } else {
  8864. $timbre_emotion = [];
  8865. }
  8866. $emotion = getProp($segment, 'emotion', '中性');
  8867. if (!in_array($emotion, $timbre_emotion)) {
  8868. $emotion = '中性';
  8869. }
  8870. $emotion_type = isset($emotion_list[$emotion]) ? $emotion_list[$emotion] : 'neutral';
  8871. $segments[] = [
  8872. 'anime_id' => $anime_id,
  8873. 'episode_id' => $episode_id,
  8874. 'episode_number' => $episode_number,
  8875. 'act_number' => getProp($act, 'act_number'),
  8876. 'act_title' => getProp($act, 'act_title'),
  8877. 'act_duration' => getProp($act, 'act_duration'),
  8878. 'segment_id' => getProp($segment, 'segment_id'),
  8879. 'segment_number' => getProp($segment, 'segment_number'),
  8880. 'segment_content' => getProp($segment, 'segment_content'),
  8881. 'description' => getProp($segment, 'description'),
  8882. 'composition' => getProp($segment, 'composition'),
  8883. 'camera_movement' => getProp($segment, 'camera_movement'),
  8884. 'voice_actor' => $voice_actor,
  8885. 'dialogue' => getProp($segment, 'dialogue'),
  8886. 'frame_type' => getProp($segment, 'frame_type'),
  8887. 'scene' => getProp($segment, 'scene'),
  8888. 'characters' => getProp($segment, 'characters'),
  8889. 'tail_frame' => getProp($segment, 'tail_frame'),
  8890. 'voice_name' => getProp($timbre_info, 'voice_name'),
  8891. 'voice_type' => $voice_type,
  8892. 'voice_audio_url' => getProp($timbre_info, 'voice_audio_url'),
  8893. 'emotion' => $emotion,
  8894. 'emotion_type' => $emotion_type,
  8895. 'gender' => getProp($segment, 'gender', '0'),
  8896. 'speed_ratio' => getProp($segment, 'speed_ratio', 0),
  8897. 'loudness_ratio' => getProp($segment, 'loudness_ratio', 0),
  8898. 'emotion_scale' => getProp($segment, 'emotion_scale', 4),
  8899. 'pitch' => getProp($segment, 'pitch', 0),
  8900. 'created_at' => $now,
  8901. 'updated_at' => $now
  8902. ];
  8903. }
  8904. }
  8905. }
  8906. if ($segments) {
  8907. if ($del_flag) {
  8908. DB::table('mp_episode_segments')
  8909. ->where('anime_id', $anime_id)
  8910. ->where('episode_id', $episode_id)
  8911. ->delete();
  8912. }
  8913. $boolen = DB::table('mp_episode_segments')->insert($segments);
  8914. if (!$boolen) {
  8915. logDB('deepseek', 'error', '分镜内容保存失败', ['anime_id' => $anime_id, 'episode_id' => $episode_id, 'segments_count' => count($segments)]);
  8916. Utils::throwError('20003:分镜内容保存失败');
  8917. }
  8918. }
  8919. dLog('deepseek')->info('segments', $segments);
  8920. // ace_mode=1: acts 返回值按合并格式调整
  8921. if ((int)$ace_mode === 1) {
  8922. $table_act_data = DB::table('mp_episode_segments')->where('episode_id', $episode_id)->orderBy('act_number')->select('id as act_id', 'act_number')->get();
  8923. $act_map = [];
  8924. foreach ($table_act_data as $item) {
  8925. $act_map[getProp($item, 'act_number')] = getProp($item, 'act_id');
  8926. }
  8927. $restructured_acts = [];
  8928. foreach ($acts as $act) {
  8929. $act_segments = getProp($act, 'segments', []);
  8930. if (!is_array($act_segments)) {
  8931. continue;
  8932. }
  8933. $merged_parts = [];
  8934. foreach ($act_segments as $seg) {
  8935. $seg_num = getProp($seg, 'segment_number');
  8936. $seg_content = getProp($seg, 'segment_content');
  8937. $merged_parts[] = "【分镜{$seg_num}】{$seg_content}\n";
  8938. }
  8939. $act_content = implode("\n", $merged_parts);
  8940. $act_content = str_replace(["@", "{", "}"], "", $act_content);
  8941. $restructured_acts[] = [
  8942. 'anime_id' => $anime_id,
  8943. 'episode_id' => $episode_id,
  8944. 'episode_number' => $episode_number,
  8945. 'act_id' => isset($act_map[getProp($act, 'act_number')]) ? $act_map[getProp($act, 'act_number')] : 0,
  8946. 'act_number' => getProp($act, 'act_number'),
  8947. 'act_title' => getProp($act, 'act_title'),
  8948. 'act_duration' => getProp($act, 'act_duration'),
  8949. 'act_content' => $act_content,
  8950. 'created_at' => $now,
  8951. 'updated_at' => $now,
  8952. ];
  8953. }
  8954. $acts = $restructured_acts;
  8955. }
  8956. $episode['episode_id'] = $episode_id;
  8957. $episode['roles'] = $merged_roles;
  8958. $episode['scenes'] = $merged_scenes;
  8959. $episode['props'] = $merged_props;
  8960. $episode['acts'] = $acts;
  8961. return [
  8962. 'episode' => $episode,
  8963. 'episode_id' => $episode_id,
  8964. 'merged_roles' => $merged_roles,
  8965. 'merged_scenes' => $merged_scenes,
  8966. 'merged_props' => $merged_props,
  8967. ];
  8968. }
  8969. private function buildEpisodeItemContent(array $items, string $nameKey): string
  8970. {
  8971. $content = '';
  8972. foreach ($items as $item) {
  8973. $name = trim((string)getProp($item, $nameKey));
  8974. if ($name === '' || $name === '旁白') {
  8975. continue;
  8976. }
  8977. $description = trim((string)getProp($item, 'description'));
  8978. $content .= $name . ': ' . $description;
  8979. if ($nameKey == 'role') {
  8980. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  8981. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  8982. $voice_name = trim(getProp($item, 'voice_name'));
  8983. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  8984. $voice_prompt = trim(getProp($item, 'voice_prompt'));
  8985. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  8986. }else {
  8987. $pic_prompt = trim(getProp($item, 'pic_prompt'));
  8988. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  8989. }
  8990. $content .= "\n";
  8991. }
  8992. return trim($content);
  8993. }
  8994. private function getEpisodeChatContent($animeId, $sequence, $content) {
  8995. if ((int)$sequence <= 0) {
  8996. return [];
  8997. }
  8998. $origin_content = '';
  8999. if ($content) {
  9000. $origin_content = '本集剧情内容:'.$content;
  9001. }else {
  9002. $origin_content = DB::table('mp_animes')->where('id', $animeId)->value('content');
  9003. if ($origin_content) $origin_content = '剧本全文内容:'.$origin_content;
  9004. }
  9005. $ace_mode = DB::table('mp_animes')->where('id', $animeId)->value('ace_mode');
  9006. // 获取分集信息
  9007. $episode = DB::table('mp_anime_episodes')
  9008. ->where('anime_id', $animeId)
  9009. ->where('episode_number', $sequence)
  9010. ->where('is_default', 1)
  9011. ->first();
  9012. if (!$episode) {
  9013. return [];
  9014. }
  9015. $episode_id = getProp($episode, 'id');
  9016. $episode_number = getProp($episode, 'episode_number');
  9017. $title = getProp($episode, 'title');
  9018. $intro = getProp($episode, 'intro');
  9019. $art_style = getProp($episode, 'art_style');
  9020. $roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9021. $scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9022. // 组装纯文本内容
  9023. $content = '';
  9024. // 添加分集标题和梗概
  9025. $content .= "###第{$episode_number}集:{$title}\n\n";
  9026. $content .= "###故事梗概\n";
  9027. $content .= trim($intro) . "\n\n";
  9028. // 添加美术风格
  9029. $content .= "###美术风格\n";
  9030. $content .= trim($art_style) . "\n\n";
  9031. // 添加主体列表
  9032. $content .= "###主体列表\n";
  9033. $pangbai_voice_prompt = "";
  9034. foreach ($roles as $role) {
  9035. $name = getProp($role, 'role');
  9036. $description = getProp($role, 'description');
  9037. $pic_prompt = getProp($role, 'pic_prompt');
  9038. $voice_prompt = getProp($role, 'voice_prompt');
  9039. $voice_name = getProp($role, 'voice_name');
  9040. $content .= "{$name}: {$description}";
  9041. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9042. if ($voice_prompt) $content .= '{{'.$voice_prompt.'}}';
  9043. if ($voice_name) $content .= '{{'.$voice_name.'}}';
  9044. if ($name == '旁白') $pangbai_voice_prompt = $voice_prompt;
  9045. $content .= "\n";
  9046. }
  9047. $content .= "\n";
  9048. // 添加场景列表
  9049. $content .= "###场景列表\n";
  9050. foreach ($scenes as $scene) {
  9051. $name = getProp($scene, 'scene');
  9052. $description = getProp($scene, 'description');
  9053. $pic_prompt = getProp($scene, 'pic_prompt');
  9054. $content .= "{$name}: {$description}";
  9055. if ($pic_prompt) $content .= '{'.$pic_prompt.'}';
  9056. $content .= "\n";
  9057. }
  9058. $content .= "\n";
  9059. // 获取分镜信息
  9060. $segments = DB::table('mp_episode_segments')
  9061. ->where('anime_id', $animeId)
  9062. ->where('episode_id', $episode_id)
  9063. ->orderBy('segment_number')
  9064. ->get();
  9065. if ($segments && count($segments) > 0) {
  9066. if ((int)$ace_mode === 1) {
  9067. $content .= "###分段剧本\n";
  9068. // 获取片段数量
  9069. $act_count = DB::table('mp_episode_segments')->where('anime_id', $animeId)->where('episode_id', $episode_id)->groupBy('act_number')->count('act_number');
  9070. $content .= "片段数量:{$act_count}\n";
  9071. if ($pangbai_voice_prompt) $content .= "旁白音色:{$pangbai_voice_prompt}\n";
  9072. $content .= "\n";
  9073. }else {
  9074. $content .= "###分镜剧本\n";
  9075. }
  9076. // 按幕分组
  9077. $currentAct = null;
  9078. foreach ($segments as $segment) {
  9079. $act_number = getProp($segment, 'act_number');
  9080. $act_title = getProp($segment, 'act_title');
  9081. $act_duration = getProp($segment, 'act_duration');
  9082. $segment_number = getProp($segment, 'segment_number');
  9083. $segment_content = getProp($segment, 'segment_content');
  9084. $scene_description = getProp($segment, 'scene_description');
  9085. $scene_name = getProp($segment, 'scene_name');
  9086. $composition = getProp($segment, 'composition');
  9087. $camera_movement = getProp($segment, 'camera_movement');
  9088. $voice_type = getProp($segment, 'voice_type');
  9089. $characters = getProp($segment, 'characters');
  9090. $dialogue = getProp($segment, 'dialogue');
  9091. $frame_type = getProp($segment, 'frame_type');
  9092. $tail_frame_description = getProp($segment, 'tail_frame_description');
  9093. // 判断是否是全能模式
  9094. if ((int)$ace_mode === 1) { // 全能模式
  9095. // 如果是新的分段,添加分段标题
  9096. if ($act_number !== $currentAct) {
  9097. $currentAct = $act_number;
  9098. $content .= "##{$act_title}\n";
  9099. $content .= "时长:{$act_duration}s\n";
  9100. }
  9101. }else {
  9102. // 如果是新的幕,添加幕标题
  9103. if ($act_number !== $currentAct) {
  9104. $currentAct = $act_number;
  9105. $content .= "##第{$act_number}幕:{$scene_name}\n";
  9106. }
  9107. }
  9108. // 添加分镜信息
  9109. $content .= "分镜{$segment_number}\n";
  9110. $content .= "分镜内容:\n{$segment_content}\n";
  9111. // $content .= "画面描述:{$scene_description}\n";
  9112. // $content .= "场景:{$scene_name}\n";
  9113. // $content .= "构图设计:{$composition}\n";
  9114. // $content .= "运镜调度:{$camera_movement}\n";
  9115. // if (!empty($voice_type)) {
  9116. // $content .= "配音角色:{$voice_type}\n";
  9117. // }
  9118. // if (!empty($characters)) {
  9119. // $content .= "出镜角色:{$characters}\n";
  9120. // }
  9121. // if (!empty($dialogue)) {
  9122. // $content .= "台词内容:\"{$dialogue}\"\n";
  9123. // }
  9124. // $content .= "画面类型:{$frame_type}\n";
  9125. // $content .= "尾帧描述:{$tail_frame_description}\n";
  9126. $content .= "\n";
  9127. }
  9128. }
  9129. $content = trim($content);
  9130. if($content) $content = "上集剧本内容:\n{$content}";
  9131. return [
  9132. [
  9133. 'role' => 'user',
  9134. 'content' => $origin_content
  9135. ],
  9136. [
  9137. 'role' => 'assistant',
  9138. 'content' => $content
  9139. ]
  9140. ];
  9141. }
  9142. private function getEpisodeChatMessages($animeId, $sequence): array
  9143. {
  9144. if ((int)$sequence <= 0) {
  9145. return [];
  9146. }
  9147. return DB::table('mp_anime_records')
  9148. ->where('anime_id', $animeId)
  9149. ->where('sequence', $sequence)
  9150. ->where('episode_id', '>', 0)
  9151. ->select('role', 'content')
  9152. ->orderBy('created_at')
  9153. ->orderBy('id')
  9154. ->get()
  9155. ->map(function ($value) {
  9156. return (array)$value;
  9157. })
  9158. ->toArray();
  9159. }
  9160. private function mergeEpisodeResourceItems(array $existingItems, array $generatedItems, string $nameKey): array
  9161. {
  9162. $existingMap = [];
  9163. foreach ($existingItems as $item) {
  9164. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9165. if ($itemKey === '') {
  9166. continue;
  9167. }
  9168. $existingMap[$itemKey] = $item;
  9169. }
  9170. if (!$generatedItems) {
  9171. return array_values($existingItems);
  9172. }
  9173. $merged = [];
  9174. foreach ($generatedItems as $item) {
  9175. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  9176. if ($itemKey === '') {
  9177. continue;
  9178. }
  9179. if (isset($existingMap[$itemKey])) {
  9180. if (trim((string)getProp($item, 'description')) === '') {
  9181. $merged[] = $existingMap[$itemKey];
  9182. continue;
  9183. }
  9184. // 检查内容是否发生变化
  9185. $isChanged = $this->isEpisodeResourceChanged($existingMap[$itemKey], $item, $nameKey);
  9186. if (!$isChanged) {
  9187. // nameKey 和 description 一致,继承现有项的 URL、task_id 和 task_status
  9188. $mergedItem = [
  9189. $nameKey => trim((string)getProp($item, $nameKey)),
  9190. 'description' => trim((string)getProp($item, 'description')),
  9191. ];
  9192. // 如果有 pic_prompt,添加到合并项中
  9193. $picPrompt = getProp($item, 'pic_prompt');
  9194. if (!empty($picPrompt)) {
  9195. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9196. }
  9197. // 继承现有项的 URL
  9198. $existingUrl = getProp($existingMap[$itemKey], 'url');
  9199. if (!empty($existingUrl)) {
  9200. $mergedItem['url'] = $existingUrl;
  9201. }
  9202. // 继承现有项的 task_id
  9203. $existingTaskId = getProp($existingMap[$itemKey], 'task_id');
  9204. if (!empty($existingTaskId)) {
  9205. $mergedItem['task_id'] = $existingTaskId;
  9206. }
  9207. // 继承现有项的 task_status
  9208. $existingTaskStatus = getProp($existingMap[$itemKey], 'task_status');
  9209. if (!empty($existingTaskStatus)) {
  9210. $mergedItem['task_status'] = $existingTaskStatus;
  9211. }
  9212. // 保留生成项的音色字段
  9213. $voiceName = getProp($item, 'voice_name');
  9214. if (!empty($voiceName)) {
  9215. $mergedItem['voice_name'] = $voiceName;
  9216. }
  9217. $voiceType = getProp($item, 'voice_type');
  9218. if (!empty($voiceType)) {
  9219. $mergedItem['voice_type'] = $voiceType;
  9220. }
  9221. $audioUrl = getProp($item, 'voice_audio_url');
  9222. if (!empty($audioUrl)) {
  9223. $mergedItem['voice_audio_url'] = $audioUrl;
  9224. }
  9225. $merged[] = $mergedItem;
  9226. } else {
  9227. // nameKey 或 description 不一致,重置 URL、task_id 和 task_status,但保留音色字段
  9228. $mergedItem = [
  9229. $nameKey => trim((string)getProp($item, $nameKey)),
  9230. 'description' => trim((string)getProp($item, 'description')),
  9231. ];
  9232. // 如果有 pic_prompt,添加到合并项中
  9233. $picPrompt = getProp($item, 'pic_prompt');
  9234. if (!empty($picPrompt)) {
  9235. $mergedItem['pic_prompt'] = trim((string)$picPrompt);
  9236. }
  9237. // 保留生成项的音色字段
  9238. $voiceName = getProp($item, 'voice_name');
  9239. if (!empty($voiceName)) {
  9240. $mergedItem['voice_name'] = $voiceName;
  9241. }
  9242. $voiceType = getProp($item, 'voice_type');
  9243. if (!empty($voiceType)) {
  9244. $mergedItem['voice_type'] = $voiceType;
  9245. }
  9246. $audioUrl = getProp($item, 'voice_audio_url');
  9247. if (!empty($audioUrl)) {
  9248. $mergedItem['voice_audio_url'] = $audioUrl;
  9249. }
  9250. // 不继承 URL、task_id 和 task_status(重置状态)
  9251. $merged[] = $mergedItem;
  9252. }
  9253. } else {
  9254. // 新增项,保留生成项的所有字段
  9255. $merged[] = $this->resetEpisodeResourceItem($item, $nameKey, ['url', 'task_id', 'task_status', 'voice_name', 'voice_type', 'voice_audio_url', 'pic_prompt']);
  9256. }
  9257. }
  9258. return $merged ?: array_values($existingItems);
  9259. }
  9260. private function resetEpisodeResourceItem(array $item, string $nameKey, array $preserveFields = []): array
  9261. {
  9262. $resetItem = [
  9263. $nameKey => trim((string)getProp($item, $nameKey)),
  9264. 'description' => trim((string)getProp($item, 'description')),
  9265. ];
  9266. // 保留指定的字段
  9267. foreach ($preserveFields as $field) {
  9268. $value = getProp($item, $field);
  9269. if (!empty($value)) {
  9270. $resetItem[$field] = $value;
  9271. }
  9272. }
  9273. return $resetItem;
  9274. }
  9275. private function isEpisodeResourceChanged(array $existingItem, array $generatedItem, string $nameKey): bool
  9276. {
  9277. $existingKey = $this->normalizeEpisodeResourceKey(getProp($existingItem, $nameKey));
  9278. $generatedKey = $this->normalizeEpisodeResourceKey(getProp($generatedItem, $nameKey));
  9279. if ($existingKey !== $generatedKey) {
  9280. return true;
  9281. }
  9282. // 比较 description 是否变化
  9283. if (trim((string)getProp($existingItem, 'description')) !== trim((string)getProp($generatedItem, 'description'))) {
  9284. return true;
  9285. }
  9286. // 比较 pic_prompt 是否变化
  9287. return trim((string)getProp($existingItem, 'pic_prompt')) !== trim((string)getProp($generatedItem, 'pic_prompt'));
  9288. }
  9289. private function normalizeEpisodeResourceKey($value): string
  9290. {
  9291. $value = trim((string)$value);
  9292. if ($value === '') {
  9293. return '';
  9294. }
  9295. return strtolower((string)preg_replace('/\s+/u', '', $value));
  9296. }
  9297. // 生成全局角色图片
  9298. private function batchSetGlobalRoleImg($data, $is_force=false) {
  9299. $anime_id = getProp($data, 'anime_id');
  9300. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9301. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9302. $roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9303. $art_style = getProp($anime, 'art_style');
  9304. $update_flag = false;
  9305. foreach ($roles as &$role) {
  9306. $role_name = getProp($role, 'role');
  9307. if ($role_name == '旁白') continue;
  9308. // 优先使用 pic_prompt,如果没有则使用 description
  9309. $pic_prompt = getProp($role, 'pic_prompt');
  9310. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  9311. // if ($art_style) $description = "美术风格:\n{$art_style}\n主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9312. if ($art_style) $description = "主体描述:{$description}\n图片要求:图片侧重点是人物,不要出现场景或背景,并且只能生成一个人物";
  9313. // 参考图地址
  9314. $ref_img_url = getProp($role, 'url');
  9315. if (!$is_force && $ref_img_url) continue;
  9316. $update_flag = true;
  9317. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9318. try {
  9319. $params = [
  9320. 'prompt' => $description,
  9321. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : []
  9322. 'ref_img_urls' => []
  9323. ];
  9324. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9325. $task_id = $task->id;
  9326. if (!$task_id) {
  9327. Utils::throwError("20003: 角色({$role_name})生成图片失败");
  9328. }
  9329. $role['task_id'] = $task_id;
  9330. $role['task_status'] = 'processing';
  9331. } catch (\Exception $e) {
  9332. Utils::throwError("20003:" . $e->getMessage());
  9333. }
  9334. }
  9335. if (!$update_flag) return true;
  9336. // 保存角色信息
  9337. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9338. 'roles' => json_encode($roles, 256),
  9339. 'generate_status' => '执行中',
  9340. 'generate_at' => date('Y-m-d H:i:s'),
  9341. 'updated_at' => date('Y-m-d H:i:s')
  9342. ]);
  9343. if (!$boolen) {
  9344. Utils::throwError('20003:保存角色信息失败');
  9345. }
  9346. return $boolen;
  9347. }
  9348. // 生成全局场景图片
  9349. private function batchSetGlobalSceneImg($data, $is_force=false) {
  9350. $anime_id = getProp($data, 'anime_id');
  9351. if (!$anime_id) Utils::throwError('1002:请选择对话');
  9352. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9353. $scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  9354. $art_style = getProp($anime, 'art_style');
  9355. $update_flag = false;
  9356. foreach ($scenes as &$scene) {
  9357. $scene_name = getProp($scene, 'scene');
  9358. // 优先使用 pic_prompt,如果没有则使用 description
  9359. $pic_prompt = getProp($scene, 'pic_prompt');
  9360. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  9361. if ($art_style) $description = "场景描述:{$description}\n图片要求: 图片侧重点是场景,生成的是场景环境图片,不要出现人物(此为第一优先要求)";
  9362. // 参考图地址
  9363. $ref_img_url = getProp($scene, 'url');
  9364. if (!$is_force && $ref_img_url) continue;
  9365. $update_flag = true;
  9366. // 此处调用AIImageGenerationService的生成图片任务接口: createImageGenerationTask(注意使用默认参数,prompt使用角色描述),并返回任务id
  9367. try {
  9368. $params = [
  9369. 'prompt' => $description,
  9370. // 'ref_img_urls' => !empty($ref_img_url) ? [$ref_img_url] : [],
  9371. 'ref_img_urls' => []
  9372. ];
  9373. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9374. $task_id = $task->id;
  9375. if (!$task_id) {
  9376. Utils::throwError("20003: 场景({$scene_name})生成图片失败");
  9377. }
  9378. $scene['task_id'] = $task_id;
  9379. $scene['task_status'] = 'processing';
  9380. } catch (\Exception $e) {
  9381. Utils::throwError("20003:" . $e->getMessage());
  9382. }
  9383. }
  9384. if (!$update_flag) return true;
  9385. // 保存角色信息
  9386. $boolen = DB::table('mp_animes')->where('id', $anime_id)->update([
  9387. 'scenes' => json_encode($scenes, 256),
  9388. 'generate_status' => '执行中',
  9389. 'generate_at' => date('Y-m-d H:i:s'),
  9390. 'updated_at' => date('Y-m-d H:i:s')
  9391. ]);
  9392. if (!$boolen) {
  9393. Utils::throwError('20003:保存角色信息失败');
  9394. }
  9395. return $boolen;
  9396. }
  9397. // 生成分镜主体、场景和道具图片
  9398. private function batchSetEpisodeRolesAndScenesImg($anime_id, $episode_number, $roles, $scenes, $props = [], $ref_products=[], $art_style_type='', $is_force=false) {
  9399. $character_prefix = '';
  9400. $scene_prefix = '';
  9401. $prop_prefix = '';
  9402. if ($art_style_type) {
  9403. $art_style_arr = $this->getArtStyleShortPromptByInput($art_style_type);
  9404. $character_prefix = isset($art_style_arr['character_prefix']) ? $art_style_arr['character_prefix'] : '';
  9405. $scene_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : '';
  9406. $prop_prefix = isset($art_style_arr['scene_prefix']) ? $art_style_arr['scene_prefix'] : ''; // 道具使用场景的前缀
  9407. }
  9408. $update_flag = false;
  9409. // 获取上一集的roles、scenes和props数据
  9410. $prev_roles = [];
  9411. $prev_scenes = [];
  9412. $prev_props = [];
  9413. if ($episode_number > 1) {
  9414. $prev_episode = DB::table('mp_anime_episodes')
  9415. ->where('anime_id', $anime_id)
  9416. ->where('episode_number', $episode_number - 1)
  9417. ->where('is_default', 1)
  9418. ->first();
  9419. if ($prev_episode) {
  9420. $prev_roles = json_decode(getProp($prev_episode, 'roles'), true) ?: [];
  9421. $prev_scenes = json_decode(getProp($prev_episode, 'scenes'), true) ?: [];
  9422. $prev_props = json_decode(getProp($prev_episode, 'props'), true) ?: [];
  9423. dLog('deepseek')->info("获取上一集数据成功", [
  9424. 'anime_id' => $anime_id,
  9425. 'prev_episode_number' => $episode_number - 1,
  9426. 'prev_roles_count' => count($prev_roles),
  9427. 'prev_scenes_count' => count($prev_scenes),
  9428. 'prev_props_count' => count($prev_props)
  9429. ]);
  9430. }
  9431. }
  9432. // 处理角色图片生成
  9433. foreach ($roles as &$role) {
  9434. $role_name = getProp($role, 'role');
  9435. if ($role_name == '旁白') continue;
  9436. // 如果参考资产里有该角色,则直接使用该图片,不继续生成
  9437. if (isset($ref_products[$role_name])) {
  9438. $role['url'] = isset($ref_products[$role_name]['url']) ? $ref_products[$role_name]['url'] : '';
  9439. if ($role['url']) continue;
  9440. }
  9441. $role_description = getProp($role, 'description');
  9442. $role_pic_prompt = getProp($role, 'pic_prompt');
  9443. $role_url = getProp($role, 'url');
  9444. // 检查是否可以从上一集继承
  9445. $inherited = false;
  9446. if (!$is_force && !empty($prev_roles)) {
  9447. foreach ($prev_roles as $prev_role) {
  9448. $prev_role_name = getProp($prev_role, 'role');
  9449. $prev_description = getProp($prev_role, 'description');
  9450. $prev_pic_prompt = getProp($prev_role, 'pic_prompt');
  9451. $prev_url = getProp($prev_role, 'url');
  9452. $prev_task_id = getProp($prev_role, 'task_id');
  9453. $prev_task_status = getProp($prev_role, 'task_status');
  9454. // 如果role、description、pic_prompt都一致,且上一集已有url,则继承
  9455. if ($role_name == $prev_role_name
  9456. && $role_description == $prev_description
  9457. && $role_pic_prompt == $prev_pic_prompt
  9458. && !empty($prev_url)) {
  9459. $role['task_id'] = $prev_task_id;
  9460. $role['task_status'] = $prev_task_status;
  9461. $role['url'] = $prev_url;
  9462. $inherited = true;
  9463. dLog('deepseek')->info("角色({$role_name})从上一集继承图片数据", [
  9464. 'anime_id' => $anime_id,
  9465. 'episode_number' => $episode_number,
  9466. 'task_id' => $prev_task_id,
  9467. 'url' => $prev_url
  9468. ]);
  9469. break;
  9470. }
  9471. }
  9472. }
  9473. // 如果已继承或已有url,跳过生成
  9474. if ($inherited || (!$is_force && $role_url)) {
  9475. continue;
  9476. }
  9477. // 优先使用 pic_prompt,如果没有则使用 description
  9478. $pic_prompt = getProp($role, 'pic_prompt');
  9479. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($role, 'description');
  9480. $description = "{$character_prefix}。\n主体描述:{$description}\n超高清,高细节,主体突出,构图合理,画面干净,无场景或背景,单人物,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  9481. $update_flag = true;
  9482. // 调用AIImageGenerationService的生成图片任务接口
  9483. try {
  9484. $params = [
  9485. 'prompt' => $description,
  9486. 'ref_img_urls' => []
  9487. ];
  9488. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9489. $task_id = $task->id;
  9490. if (!$task_id) {
  9491. dLog('deepseek')->error("角色({$role_name})生成图片失败");
  9492. continue; // 不中断,继续处理其他角色
  9493. }
  9494. $role['task_id'] = $task_id;
  9495. $role['task_status'] = 'processing';
  9496. dLog('deepseek')->info("角色({$role_name})创建图片生成任务成功", [
  9497. 'anime_id' => $anime_id,
  9498. 'episode_number' => $episode_number,
  9499. 'task_id' => $task_id
  9500. ]);
  9501. } catch (\Exception $e) {
  9502. dLog('deepseek')->error("角色({$role_name})创建图片生成任务失败: " . $e->getMessage());
  9503. // 不抛出异常,继续处理其他角色
  9504. }
  9505. }
  9506. // 处理场景图片生成
  9507. foreach ($scenes as &$scene) {
  9508. $scene_name = getProp($scene, 'scene');
  9509. $scene_description = getProp($scene, 'description');
  9510. $scene_pic_prompt = getProp($scene, 'pic_prompt');
  9511. $scene_url = getProp($scene, 'url');
  9512. // 如果参考资产里有该场景,则直接使用该图片,不继续生成
  9513. if (isset($ref_products[$scene_name])) {
  9514. $scene['url'] = isset($ref_products[$scene_name]['url']) ? $ref_products[$scene_name]['url'] : '';
  9515. if ($scene['url']) continue;
  9516. }
  9517. // 检查是否可以从上一集继承
  9518. $inherited = false;
  9519. if (!$is_force && !empty($prev_scenes)) {
  9520. foreach ($prev_scenes as $prev_scene) {
  9521. $prev_scene_name = getProp($prev_scene, 'scene');
  9522. $prev_description = getProp($prev_scene, 'description');
  9523. $prev_pic_prompt = getProp($prev_scene, 'pic_prompt');
  9524. $prev_url = getProp($prev_scene, 'url');
  9525. $prev_task_id = getProp($prev_scene, 'task_id');
  9526. $prev_task_status = getProp($prev_scene, 'task_status');
  9527. // 如果scene、description、pic_prompt都一致,且上一集已有url,则继承
  9528. if ($scene_name == $prev_scene_name
  9529. && $scene_description == $prev_description
  9530. && $scene_pic_prompt == $prev_pic_prompt
  9531. && !empty($prev_url)) {
  9532. $scene['task_id'] = $prev_task_id;
  9533. $scene['task_status'] = $prev_task_status;
  9534. $scene['url'] = $prev_url;
  9535. $inherited = true;
  9536. dLog('deepseek')->info("场景({$scene_name})从上一集继承图片数据", [
  9537. 'anime_id' => $anime_id,
  9538. 'episode_number' => $episode_number,
  9539. 'task_id' => $prev_task_id,
  9540. 'url' => $prev_url
  9541. ]);
  9542. break;
  9543. }
  9544. }
  9545. }
  9546. // 如果已继承或已有url,跳过生成
  9547. if ($inherited || (!$is_force && $scene_url)) {
  9548. continue;
  9549. }
  9550. // 优先使用 pic_prompt,如果没有则使用 description
  9551. $pic_prompt = getProp($scene, 'pic_prompt');
  9552. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($scene, 'description');
  9553. $description = "{$scene_prefix}。\n场景描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  9554. $update_flag = true;
  9555. // 调用AIImageGenerationService的生成图片任务接口
  9556. try {
  9557. $params = [
  9558. 'prompt' => $description,
  9559. 'ref_img_urls' => []
  9560. ];
  9561. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9562. $task_id = $task->id;
  9563. if (!$task_id) {
  9564. dLog('deepseek')->error("场景({$scene_name})生成图片失败");
  9565. continue; // 不中断,继续处理其他场景
  9566. }
  9567. $scene['task_id'] = $task_id;
  9568. $scene['task_status'] = 'processing';
  9569. dLog('deepseek')->info("场景({$scene_name})创建图片生成任务成功", [
  9570. 'anime_id' => $anime_id,
  9571. 'episode_number' => $episode_number,
  9572. 'task_id' => $task_id
  9573. ]);
  9574. } catch (\Exception $e) {
  9575. dLog('deepseek')->error("场景({$scene_name})创建图片生成任务失败: " . $e->getMessage());
  9576. // 不抛出异常,继续处理其他场景
  9577. }
  9578. }
  9579. // 处理道具图片生成(逻辑与场景一致)
  9580. foreach ($props as &$prop) {
  9581. $prop_name = getProp($prop, 'prop');
  9582. $prop_description = getProp($prop, 'description');
  9583. $prop_pic_prompt = getProp($prop, 'pic_prompt');
  9584. $prop_url = getProp($prop, 'url');
  9585. // 如果参考资产里有该道具,则直接使用该图片,不继续生成
  9586. if (isset($ref_products[$prop_name])) {
  9587. $prop['url'] = isset($ref_products[$prop_name]['url']) ? $ref_products[$prop_name]['url'] : '';
  9588. if ($prop['url']) continue;
  9589. }
  9590. // 检查是否可以从上一集继承
  9591. $inherited = false;
  9592. if (!$is_force && !empty($prev_props)) {
  9593. foreach ($prev_props as $prev_prop) {
  9594. $prev_prop_name = getProp($prev_prop, 'prop');
  9595. $prev_description = getProp($prev_prop, 'description');
  9596. $prev_pic_prompt = getProp($prev_prop, 'pic_prompt');
  9597. $prev_url = getProp($prev_prop, 'url');
  9598. $prev_task_id = getProp($prev_prop, 'task_id');
  9599. $prev_task_status = getProp($prev_prop, 'task_status');
  9600. // 如果prop、description、pic_prompt都一致,且上一集已有url,则继承
  9601. if ($prop_name == $prev_prop_name
  9602. && $prop_description == $prev_description
  9603. && $prop_pic_prompt == $prev_pic_prompt
  9604. && !empty($prev_url)) {
  9605. $prop['task_id'] = $prev_task_id;
  9606. $prop['task_status'] = $prev_task_status;
  9607. $prop['url'] = $prev_url;
  9608. $inherited = true;
  9609. dLog('deepseek')->info("道具({$prop_name})从上一集继承图片数据", [
  9610. 'anime_id' => $anime_id,
  9611. 'episode_number' => $episode_number,
  9612. 'task_id' => $prev_task_id,
  9613. 'url' => $prev_url
  9614. ]);
  9615. break;
  9616. }
  9617. }
  9618. }
  9619. // 如果已继承或已有url,跳过生成
  9620. if ($inherited || (!$is_force && $prop_url)) {
  9621. continue;
  9622. }
  9623. // 优先使用 pic_prompt,如果没有则使用 description
  9624. $pic_prompt = getProp($prop, 'pic_prompt');
  9625. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : getProp($prop, 'description');
  9626. $description = "{$prop_prefix}。\n道具描述:{$description}\n无人物,超高清,高细节,主体突出,构图合理,画面干净,无文字,无水印,无字幕,电影级光影,视觉焦点明确";
  9627. $update_flag = true;
  9628. // 调用AIImageGenerationService的生成图片任务接口
  9629. try {
  9630. $params = [
  9631. 'prompt' => $description,
  9632. 'ref_img_urls' => []
  9633. ];
  9634. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  9635. $task_id = $task->id;
  9636. if (!$task_id) {
  9637. dLog('deepseek')->error("道具({$prop_name})生成图片失败");
  9638. continue; // 不中断,继续处理其他道具
  9639. }
  9640. $prop['task_id'] = $task_id;
  9641. $prop['task_status'] = 'processing';
  9642. dLog('deepseek')->info("道具({$prop_name})创建图片生成任务成功", [
  9643. 'anime_id' => $anime_id,
  9644. 'episode_number' => $episode_number,
  9645. 'task_id' => $task_id
  9646. ]);
  9647. } catch (\Exception $e) {
  9648. dLog('deepseek')->error("道具({$prop_name})创建图片生成任务失败: " . $e->getMessage());
  9649. // 不抛出异常,继续处理其他道具
  9650. }
  9651. }
  9652. if (!$update_flag) return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  9653. // 将处理完毕的roles、scenes和props与全局(mp_animes)数据对比并合并
  9654. $this->syncRolesAndScenesToGlobal($anime_id, $roles, $scenes, $props);
  9655. // // 保存剧集的角色和场景信息
  9656. // $boolen = DB::table('mp_anime_episodes')->where('id', $episode_id)->update([
  9657. // 'roles' => json_encode($roles, 256),
  9658. // 'scenes' => json_encode($scenes, 256),
  9659. // 'generate_status' => '执行中',
  9660. // 'generate_at' => date('Y-m-d H:i:s'),
  9661. // 'updated_at' => date('Y-m-d H:i:s')
  9662. // ]);
  9663. // if (!$boolen) {
  9664. // dLog('deepseek')->error('保存剧集角色和场景信息失败', ['episode_id' => $episode_id]);
  9665. // Utils::throwError('20003:保存剧集角色和场景信息失败');
  9666. // }
  9667. dLog('deepseek')->info('剧集角色、场景和道具图片任务创建完成', [
  9668. // 'episode_id' => $episode_id,
  9669. 'roles_count' => count($roles),
  9670. 'scenes_count' => count($scenes),
  9671. 'props_count' => count($props)
  9672. ]);
  9673. return ['roles' => $roles, 'scenes' => $scenes, 'props' => $props];
  9674. }
  9675. /**
  9676. * 将剧集的roles、scenes和props同步到全局(mp_animes)
  9677. * 如果全局中不存在相同的role/scene/prop(名称、description、pic_prompt三项一致),则添加到全局
  9678. *
  9679. * @param int $anime_id 动漫对话ID
  9680. * @param array $episode_roles 剧集角色数据
  9681. * @param array $episode_scenes 剧集场景数据
  9682. * @param array $episode_props 剧集道具数据
  9683. * @return bool
  9684. */
  9685. private function syncRolesAndScenesToGlobal($anime_id, $episode_roles, $episode_scenes, $episode_props = []) {
  9686. // 获取全局数据
  9687. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9688. if (!$anime) {
  9689. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  9690. return false;
  9691. }
  9692. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9693. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  9694. $global_props = json_decode(getProp($anime, 'props'), true) ?: [];
  9695. $roles_added = false;
  9696. $roles_updated = false;
  9697. $scenes_added = false;
  9698. $props_added = false;
  9699. // 处理角色同步
  9700. foreach ($episode_roles as $episode_role) {
  9701. $episode_role_name = getProp($episode_role, 'role');
  9702. $episode_description = getProp($episode_role, 'description');
  9703. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  9704. $episode_voice_prompt = getProp($episode_role, 'voice_prompt');
  9705. // 跳过旁白
  9706. if ($episode_role_name == '旁白') {
  9707. continue;
  9708. }
  9709. // 检查全局中是否已存在相同的角色
  9710. $exists = false;
  9711. $global_role_index = -1;
  9712. foreach ($global_roles as $index => $global_role) {
  9713. $global_role_name = getProp($global_role, 'role');
  9714. $global_description = getProp($global_role, 'description');
  9715. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  9716. // 如果role、description、pic_prompt三项都一致,则认为已存在
  9717. if ($episode_role_name == $global_role_name
  9718. && $episode_description == $global_description
  9719. && $episode_pic_prompt == $global_pic_prompt) {
  9720. $exists = true;
  9721. $global_role_index = $index;
  9722. break;
  9723. }
  9724. }
  9725. // 如果不存在,则添加到全局
  9726. if (!$exists) {
  9727. $global_roles[] = $episode_role;
  9728. $roles_added = true;
  9729. dLog('deepseek')->info("角色({$episode_role_name})添加到全局", [
  9730. 'anime_id' => $anime_id,
  9731. 'role' => $episode_role_name
  9732. ]);
  9733. } else {
  9734. // 如果存在,且剧集有voice_prompt字段,将voice_prompt更新到全局
  9735. if (!empty($episode_voice_prompt)) {
  9736. $global_voice_prompt = getProp($global_roles[$global_role_index], 'voice_prompt');
  9737. // 如果全局没有voice_prompt或与剧集不一致,则更新
  9738. if ($global_voice_prompt !== $episode_voice_prompt) {
  9739. $global_roles[$global_role_index]['voice_prompt'] = $episode_voice_prompt;
  9740. $roles_updated = true;
  9741. dLog('deepseek')->info("角色({$episode_role_name})的voice_prompt更新到全局", [
  9742. 'anime_id' => $anime_id,
  9743. 'role' => $episode_role_name,
  9744. 'voice_prompt' => $episode_voice_prompt
  9745. ]);
  9746. }
  9747. }
  9748. }
  9749. }
  9750. // 处理场景同步
  9751. foreach ($episode_scenes as $episode_scene) {
  9752. $episode_scene_name = getProp($episode_scene, 'scene');
  9753. $episode_description = getProp($episode_scene, 'description');
  9754. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  9755. // 检查全局中是否已存在相同的场景
  9756. $exists = false;
  9757. foreach ($global_scenes as $global_scene) {
  9758. $global_scene_name = getProp($global_scene, 'scene');
  9759. $global_description = getProp($global_scene, 'description');
  9760. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  9761. // 如果scene、description、pic_prompt三项都一致,则认为已存在
  9762. if ($episode_scene_name == $global_scene_name
  9763. && $episode_description == $global_description
  9764. && $episode_pic_prompt == $global_pic_prompt) {
  9765. $exists = true;
  9766. break;
  9767. }
  9768. }
  9769. // 如果不存在,则添加到全局
  9770. if (!$exists) {
  9771. $global_scenes[] = $episode_scene;
  9772. $scenes_added = true;
  9773. dLog('deepseek')->info("场景({$episode_scene_name})添加到全局", [
  9774. 'anime_id' => $anime_id,
  9775. 'scene' => $episode_scene_name
  9776. ]);
  9777. }
  9778. }
  9779. // 处理道具同步(逻辑与场景一致)
  9780. foreach ($episode_props as $episode_prop) {
  9781. $episode_prop_name = getProp($episode_prop, 'prop');
  9782. $episode_description = getProp($episode_prop, 'description');
  9783. $episode_pic_prompt = getProp($episode_prop, 'pic_prompt');
  9784. // 检查全局中是否已存在相同的道具
  9785. $exists = false;
  9786. foreach ($global_props as $global_prop) {
  9787. $global_prop_name = getProp($global_prop, 'prop');
  9788. $global_description = getProp($global_prop, 'description');
  9789. $global_pic_prompt = getProp($global_prop, 'pic_prompt');
  9790. // 如果prop、description、pic_prompt三项都一致,则认为已存在
  9791. if ($episode_prop_name == $global_prop_name
  9792. && $episode_description == $global_description
  9793. && $episode_pic_prompt == $global_pic_prompt) {
  9794. $exists = true;
  9795. break;
  9796. }
  9797. }
  9798. // 如果不存在,则添加到全局
  9799. if (!$exists) {
  9800. $global_props[] = $episode_prop;
  9801. $props_added = true;
  9802. dLog('deepseek')->info("道具({$episode_prop_name})添加到全局", [
  9803. 'anime_id' => $anime_id,
  9804. 'prop' => $episode_prop_name
  9805. ]);
  9806. }
  9807. }
  9808. // 如果有新增或更新,则更新全局数据
  9809. if ($roles_added || $roles_updated || $scenes_added || $props_added) {
  9810. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  9811. if ($roles_added || $roles_updated) {
  9812. $update_data['roles'] = json_encode($global_roles, 256);
  9813. }
  9814. if ($scenes_added) {
  9815. $update_data['scenes'] = json_encode($global_scenes, 256);
  9816. }
  9817. if ($props_added) {
  9818. $update_data['props'] = json_encode($global_props, 256);
  9819. }
  9820. DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  9821. dLog('deepseek')->info('剧集数据同步到全局完成', [
  9822. 'anime_id' => $anime_id,
  9823. 'roles_added' => $roles_added,
  9824. 'roles_updated' => $roles_updated,
  9825. 'scenes_added' => $scenes_added,
  9826. 'props_added' => $props_added,
  9827. 'global_roles_count' => count($global_roles),
  9828. 'global_scenes_count' => count($global_scenes),
  9829. 'global_props_count' => count($global_props)
  9830. ]);
  9831. }
  9832. return true;
  9833. }
  9834. /**
  9835. * 将全局角色和场景的task_id、task_status和url继承给指定分集
  9836. *
  9837. * @param int $anime_id 动漫对话ID
  9838. * @param int $episode_id 分集ID
  9839. * @return bool
  9840. */
  9841. private function inheritGlobalImagesToEpisodes($anime_id, $episode_id) {
  9842. // 获取全局角色和场景数据
  9843. $anime = DB::table('mp_animes')->where('id', $anime_id)->where('is_deleted', 0)->first();
  9844. if (!$anime) {
  9845. dLog('deepseek')->warning('动漫对话不存在', ['anime_id' => $anime_id]);
  9846. return false;
  9847. }
  9848. $global_roles = json_decode(getProp($anime, 'roles'), true) ?: [];
  9849. $global_scenes = json_decode(getProp($anime, 'scenes'), true) ?: [];
  9850. // 获取指定的分集
  9851. $episode = DB::table('mp_anime_episodes')->where('id', $episode_id)->where('anime_id', $anime_id)->first();
  9852. if (!$episode) {
  9853. dLog('deepseek')->warning('分集不存在', ['anime_id' => $anime_id, 'episode_id' => $episode_id]);
  9854. return false;
  9855. }
  9856. $episode_roles = json_decode(getProp($episode, 'roles'), true) ?: [];
  9857. $episode_scenes = json_decode(getProp($episode, 'scenes'), true) ?: [];
  9858. $roles_updated = false;
  9859. $scenes_updated = false;
  9860. // 继承角色的task_id、task_status和url
  9861. foreach ($episode_roles as &$episode_role) {
  9862. $episode_role_name = getProp($episode_role, 'role');
  9863. $episode_description = getProp($episode_role, 'description');
  9864. $episode_pic_prompt = getProp($episode_role, 'pic_prompt');
  9865. $episode_url = getProp($episode_role, 'url');
  9866. // 跳过旁白角色
  9867. if ($episode_role_name == '旁白') {
  9868. continue;
  9869. }
  9870. // 如果剧集中已有URL,跳过
  9871. if (!empty($episode_url)) {
  9872. continue;
  9873. }
  9874. // 遍历全局角色数据,查找匹配的角色
  9875. foreach ($global_roles as $global_role) {
  9876. $global_role_name = getProp($global_role, 'role');
  9877. $global_description = getProp($global_role, 'description');
  9878. $global_pic_prompt = getProp($global_role, 'pic_prompt');
  9879. $global_url = getProp($global_role, 'url');
  9880. $global_task_id = getProp($global_role, 'task_id');
  9881. $global_task_status = getProp($global_role, 'task_status');
  9882. // 满足条件:1.角色名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  9883. if ($episode_role_name == $global_role_name
  9884. && $episode_description == $global_description
  9885. && $episode_pic_prompt == $global_pic_prompt) {
  9886. // 继承 task_id、task_status 和 url
  9887. if (!empty($global_task_id)) {
  9888. $episode_role['task_id'] = $global_task_id;
  9889. $episode_role['task_status'] = $global_task_status;
  9890. $roles_updated = true;
  9891. dLog('deepseek')->info('剧集角色继承全局task_id', [
  9892. 'episode_id' => $episode_id,
  9893. 'role' => $episode_role_name,
  9894. 'task_id' => $global_task_id,
  9895. 'task_status' => $global_task_status
  9896. ]);
  9897. }
  9898. if (!empty($global_url)) {
  9899. $episode_role['url'] = $global_url;
  9900. $roles_updated = true;
  9901. dLog('deepseek')->info('剧集角色继承全局url', [
  9902. 'episode_id' => $episode_id,
  9903. 'role' => $episode_role_name,
  9904. 'url' => $global_url
  9905. ]);
  9906. }
  9907. break;
  9908. }
  9909. }
  9910. }
  9911. // 继承场景的task_id、task_status和url
  9912. foreach ($episode_scenes as &$episode_scene) {
  9913. $episode_scene_name = getProp($episode_scene, 'scene');
  9914. $episode_description = getProp($episode_scene, 'description');
  9915. $episode_pic_prompt = getProp($episode_scene, 'pic_prompt');
  9916. $episode_url = getProp($episode_scene, 'url');
  9917. // 如果剧集中已有URL,跳过
  9918. if (!empty($episode_url)) {
  9919. continue;
  9920. }
  9921. // 遍历全局场景数据,查找匹配的场景
  9922. foreach ($global_scenes as $global_scene) {
  9923. $global_scene_name = getProp($global_scene, 'scene');
  9924. $global_description = getProp($global_scene, 'description');
  9925. $global_pic_prompt = getProp($global_scene, 'pic_prompt');
  9926. $global_url = getProp($global_scene, 'url');
  9927. $global_task_id = getProp($global_scene, 'task_id');
  9928. $global_task_status = getProp($global_scene, 'task_status');
  9929. // 满足条件:1.场景名相同 2.描述相同 3.pic_prompt相同 4.剧集中URL为空
  9930. if ($episode_scene_name == $global_scene_name
  9931. && $episode_description == $global_description
  9932. && $episode_pic_prompt == $global_pic_prompt) {
  9933. // 继承 task_id、task_status 和 url
  9934. if (!empty($global_task_id)) {
  9935. $episode_scene['task_id'] = $global_task_id;
  9936. $episode_scene['task_status'] = $global_task_status;
  9937. $scenes_updated = true;
  9938. dLog('deepseek')->info('剧集场景继承全局task_id', [
  9939. 'episode_id' => $episode_id,
  9940. 'scene' => $episode_scene_name,
  9941. 'task_id' => $global_task_id,
  9942. 'task_status' => $global_task_status
  9943. ]);
  9944. }
  9945. if (!empty($global_url)) {
  9946. $episode_scene['url'] = $global_url;
  9947. $scenes_updated = true;
  9948. dLog('deepseek')->info('剧集场景继承全局url', [
  9949. 'episode_id' => $episode_id,
  9950. 'scene' => $episode_scene_name,
  9951. 'url' => $global_url
  9952. ]);
  9953. }
  9954. break;
  9955. }
  9956. }
  9957. }
  9958. // 如果有更新,则保存到数据库
  9959. if ($roles_updated || $scenes_updated) {
  9960. $update_data = ['updated_at' => date('Y-m-d H:i:s')];
  9961. if ($roles_updated) {
  9962. $update_data['roles'] = json_encode($episode_roles, 256);
  9963. }
  9964. if ($scenes_updated) {
  9965. $update_data['scenes'] = json_encode($episode_scenes, 256);
  9966. }
  9967. DB::table('mp_anime_episodes')->where('id', $episode_id)->update($update_data);
  9968. dLog('deepseek')->info('剧集继承全局图片数据完成', [
  9969. 'episode_id' => $episode_id,
  9970. 'roles_updated' => $roles_updated,
  9971. 'scenes_updated' => $scenes_updated
  9972. ]);
  9973. }
  9974. return true;
  9975. }
  9976. public function chatChangeImg($data) {
  9977. $segment = getProp($data, 'segment');
  9978. $segment_content = getProp($segment, 'segment_content');
  9979. $prompt = getProp($data, 'prompt');
  9980. $ref_img = getProp($data, 'ref_img');
  9981. $question = "请修改已有的内容{$segment_content}\n修改要求如下:\n{$prompt}";
  9982. // 处理文本模型
  9983. $model = getProp($data, 'model');
  9984. if (!$model) {
  9985. // 用户没有输入,从anime表获取
  9986. $segment_id = getProp($segment, 'segment_id');
  9987. if ($segment_id) {
  9988. $episode_id = DB::table('mp_episode_segments')->where('segment_id', $segment_id)->value('episode_id');
  9989. if ($episode_id) {
  9990. $anime_id = DB::table('mp_anime_episodes')->where('id', $episode_id)->value('anime_id');
  9991. if ($anime_id) {
  9992. $model = DB::table('mp_animes')->where('id', $anime_id)->value('model');
  9993. }
  9994. }
  9995. }
  9996. if (!$model) {
  9997. // anime表也没有,使用默认值
  9998. $model = 'doubao-seed-2-0-mini-260215';
  9999. }
  10000. }
  10001. // 验证模型是否在可用模型表中
  10002. if (!DB::table('mp_text_models')->where('model', $model)->where('is_enabled', 1)->exists()) {
  10003. $model = 'doubao-seed-2-0-mini-260215';
  10004. }
  10005. $messages[] =
  10006. [
  10007. 'role' => 'user',
  10008. 'content' => $question
  10009. ];
  10010. $post_data = [
  10011. 'model' => $model,
  10012. 'messages' => $messages,
  10013. // 'max_tokens' => 8192,
  10014. 'temperature' => 0.7,
  10015. 'frequency_penalty' => 0,
  10016. 'presence_penalty' => 0,
  10017. 'response_format' => ['type' => 'text'],
  10018. 'stream' => false // 是否启用流式输出
  10019. ];
  10020. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10021. // DeepSeek 官方模型使用 DeepSeek API
  10022. $chatResult = $this->chatOnly($post_data);
  10023. } else if (in_array($model, $this->gpt_text_models)) {
  10024. // GPT-5.4 模型使用 TokenRouter API
  10025. $chatResult = $this->gpt54ChatOnly($post_data);
  10026. } else {
  10027. // 其他模型使用火山引擎API
  10028. $chatResult = $this->volcEngineChatCompletion($post_data);
  10029. }
  10030. if (is_array($chatResult)) {
  10031. extract($chatResult);
  10032. }else {
  10033. Utils::throwError('20003: 接口调用失败!');
  10034. }
  10035. return [
  10036. 'type' => 'done',
  10037. // 'episode' => $episode,
  10038. 'answer' => $fullContent,
  10039. 'reasoning' => $fullReasoningContent,
  10040. 'usage' => $usage
  10041. ];
  10042. }
  10043. // 仅调用deepseek对话接口
  10044. private function chatOnly($post_data) {
  10045. $post_data['max_tokens'] = 300000;
  10046. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10047. $result = $client->post($this->url, ['json' => $post_data, 'headers' => $this->headers]);
  10048. $response = $result->getBody()->getContents();
  10049. $response_arr = json_decode($response, true);
  10050. dLog('deepseek')->info('deepseek请求完成', ['response' => $response_arr]);
  10051. $fullContent = '';
  10052. $fullReasoningContent = [];
  10053. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10054. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10055. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10056. $fullReasoningContent = isset($response_arr['choices'][0]['message']['reasoning_content']) ? $response_arr['choices'][0]['message']['reasoning_content'] : '';
  10057. }
  10058. return [
  10059. 'fullContent' => $fullContent,
  10060. 'fullReasoningContent' => $fullReasoningContent,
  10061. 'usage' => $usage
  10062. ];
  10063. }
  10064. // 仅调用 GPT-5.4 对话接口(非流式)
  10065. private function gpt54ChatOnly($post_data) {
  10066. $apiKey = env('GPT_54_API_KEY');
  10067. if (empty($apiKey)) {
  10068. Utils::throwError('20003:GPT-5.4 API Key未配置');
  10069. }
  10070. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10071. $headers = [
  10072. 'Authorization' => 'Bearer ' . $apiKey,
  10073. 'Content-Type' => 'application/json'
  10074. ];
  10075. // 移除 thinking 参数,GPT-5.4 不支持
  10076. if (isset($post_data['thinking'])) {
  10077. unset($post_data['thinking']);
  10078. }
  10079. if (isset($post_data['reasoning_effort'])) {
  10080. unset($post_data['reasoning_effort']);
  10081. }
  10082. $post_data['max_completion_tokens'] = 100000;
  10083. // 确保 stream 为 false
  10084. $post_data['stream'] = false;
  10085. // 备用中转站地址: https://token.ithinkai.cn/v1/chat/completions
  10086. // 备用中转站地址2: https://api.nonelinear.com/v1/chat/completions
  10087. $result = $client->post('https://ai-api.kkidc.com/v1/chat/completions', [
  10088. 'json' => $post_data,
  10089. 'headers' => $headers
  10090. ]);
  10091. $response = $result->getBody()->getContents();
  10092. $response_arr = json_decode($response, true);
  10093. dLog('deepseek')->info('GPT-5.4请求完成', ['response' => $response_arr]);
  10094. $fullContent = '';
  10095. $usage = isset($response_arr['usage']) ? $response_arr['usage'] : [];
  10096. if (isset($response_arr['choices']) && count($response_arr['choices']) > 0) {
  10097. $fullContent = isset($response_arr['choices'][0]['message']['content']) ? $response_arr['choices'][0]['message']['content'] : '';
  10098. }
  10099. return [
  10100. 'fullContent' => $fullContent,
  10101. 'fullReasoningContent' => '', // GPT-5.4 不支持思考链
  10102. 'usage' => $usage
  10103. ];
  10104. }
  10105. private function splitContent($content) {
  10106. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  10107. $chapters = [];
  10108. // 匹配章节标题格式:
  10109. // 1. 标题独占一行
  10110. // 2. 格式支持:
  10111. // - **第一集**
  10112. // - 第一集:
  10113. // - ###第1章 重生
  10114. // - ##第2章 相救
  10115. // - 第三章 共处一室
  10116. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  10117. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  10118. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  10119. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  10120. $pattern = '/^[#*·\s\-_=]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场回话]).*$/mu';
  10121. // 先用正则找出所有章节标题的位置
  10122. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  10123. $titleCount = count($matches[0]);
  10124. for ($i = 0; $i < $titleCount; $i++) {
  10125. // 获取当前章节标题
  10126. $titleLine = trim($matches[0][$i][0]);
  10127. // 去除标题开头的特殊符号
  10128. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/', '', $titleLine);
  10129. // 去除标题结尾的冒号
  10130. $cleanTitle = preg_replace('/[#*·::\s]+$/', '', $cleanTitle);
  10131. $cleanTitle = trim($cleanTitle);
  10132. // 获取当前标题的结束位置
  10133. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  10134. // 获取下一个章节标题的开始位置(如果存在)
  10135. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  10136. // 提取章节内容(从标题结束到下一个标题开始)
  10137. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  10138. // 清理内容:去除前后空白和分隔线
  10139. $chapterContent = trim($chapterContent);
  10140. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  10141. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  10142. if (!empty($cleanTitle) && !empty($chapterContent)) {
  10143. $chapters[] = [
  10144. 'title' => $cleanTitle,
  10145. 'content' => $chapterContent
  10146. ];
  10147. }
  10148. }
  10149. } else {
  10150. // 如果没有匹配到章节,返回整个内容
  10151. $chapters[] = [
  10152. 'title' => '',
  10153. 'content' => $content
  10154. ];
  10155. }
  10156. return $chapters;
  10157. }
  10158. public function getContentByBid($bid) {
  10159. $chapters = DB::table('chapters as c')->select('c.id', 'c.name', 'cc.content')
  10160. ->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')
  10161. ->where('c.bid', $bid)->where('c.is_check', 1)->where('c.is_deleted', 0)->orderBy('c.sequence')->get();
  10162. $content = '';
  10163. foreach ($chapters as $chapter) {
  10164. $content .= $chapter->content . PHP_EOL . PHP_EOL;
  10165. }
  10166. return $content;
  10167. }
  10168. public function getContentByScriptId($script_id) {
  10169. $content = '';
  10170. $contents = DB::table('mp_script_episode_group')->where('script_id', $script_id)->pluck('content')->toArray();
  10171. if ($contents) {
  10172. $content = implode(PHP_EOL, $contents);
  10173. }else {
  10174. $content = DB::table('mp_scripts')->where('id', $script_id)->value('content');
  10175. }
  10176. return $content;
  10177. }
  10178. /**
  10179. * 根据文件类型提取文本内容
  10180. *
  10181. * @param mixed $file 文件对象或文件路径
  10182. * @return string
  10183. */
  10184. public function extractFileContent($file) {
  10185. // 获取文件路径和扩展名
  10186. if (is_string($file)) {
  10187. $filePath = $file;
  10188. $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  10189. } else {
  10190. // Laravel UploadedFile 对象
  10191. $filePath = $file->getRealPath();
  10192. $extension = strtolower($file->getClientOriginalExtension());
  10193. }
  10194. $content = '';
  10195. switch ($extension) {
  10196. case 'txt':
  10197. $content = $this->extractTxtContent($filePath);
  10198. break;
  10199. case 'pdf':
  10200. $content = $this->extractPdfContent($filePath);
  10201. break;
  10202. case 'doc':
  10203. case 'docx':
  10204. $content = $this->extractWordContent($filePath);
  10205. break;
  10206. // case 'jpg':
  10207. // case 'jpeg':
  10208. // case 'png':
  10209. // case 'gif':
  10210. // case 'bmp':
  10211. // case 'webp':
  10212. // $content = $this->extractImageContent($filePath);
  10213. // break;
  10214. default:
  10215. Utils::throwError('20003:不支持的文件格式,支持:txt、pdf');
  10216. }
  10217. return $content;
  10218. }
  10219. /**
  10220. * 提取 TXT 文件内容
  10221. */
  10222. private function extractTxtContent($filePath) {
  10223. if (!file_exists($filePath)) {
  10224. Utils::throwError('20003:文件不存在');
  10225. }
  10226. $content = file_get_contents($filePath);
  10227. // 尝试检测并转换编码
  10228. $encoding = mb_detect_encoding($content, ['UTF-8', 'GBK', 'GB2312', 'BIG5'], true);
  10229. if ($encoding && $encoding !== 'UTF-8') {
  10230. $content = mb_convert_encoding($content, 'UTF-8', $encoding);
  10231. }
  10232. return trim($content);
  10233. }
  10234. /**
  10235. * 提取 PDF 文件内容
  10236. */
  10237. private function extractPdfContent($filePath) {
  10238. if (!file_exists($filePath)) {
  10239. Utils::throwError('20003:文件不存在');
  10240. }
  10241. try {
  10242. $parser = new PdfParser();
  10243. $pdf = $parser->parseFile($filePath);
  10244. $content = $pdf->getText();
  10245. return trim($content);
  10246. } catch (\Exception $e) {
  10247. dLog('deepseek')->error('PDF解析失败: ' . $e->getMessage());
  10248. logDB('deepseek', 'error', 'PDF解析失败', ['error' => $e->getMessage()]);
  10249. Utils::throwError('20003:PDF解析失败,请确保文件格式正确');
  10250. }
  10251. }
  10252. /**
  10253. * 提取 Word 文件内容(支持 doc 和 docx)
  10254. */
  10255. private function extractWordContent($filePath) {
  10256. if (!file_exists($filePath)) {
  10257. Utils::throwError('20003:文件不存在');
  10258. }
  10259. try {
  10260. $phpWord = WordIOFactory::load($filePath);
  10261. $content = '';
  10262. foreach ($phpWord->getSections() as $section) {
  10263. foreach ($section->getElements() as $element) {
  10264. $content .= $this->extractWordElementText($element);
  10265. }
  10266. }
  10267. return trim($content);
  10268. } catch (\Exception $e) {
  10269. dLog('deepseek')->error('Word解析失败: ' . $e->getMessage());
  10270. logDB('deepseek', 'error', 'Word解析失败', ['error' => $e->getMessage()]);
  10271. Utils::throwError('20003:Word解析失败,请确保文件格式正确');
  10272. }
  10273. }
  10274. /**
  10275. * 递归提取 Word 元素中的文本
  10276. */
  10277. private function extractWordElementText($element) {
  10278. $text = '';
  10279. if (method_exists($element, 'getText')) {
  10280. $text .= $element->getText() . "\n";
  10281. } elseif (method_exists($element, 'getElements')) {
  10282. foreach ($element->getElements() as $childElement) {
  10283. $text .= $this->extractWordElementText($childElement);
  10284. }
  10285. }
  10286. return $text;
  10287. }
  10288. /**
  10289. * 提取图片内容(使用火山引擎 OCR)
  10290. */
  10291. private function extractImageContent($filePath) {
  10292. if (!file_exists($filePath)) {
  10293. Utils::throwError('20003:文件不存在');
  10294. }
  10295. try {
  10296. // 读取图片并转换为 base64
  10297. $imageData = file_get_contents($filePath);
  10298. $base64Image = base64_encode($imageData);
  10299. // 调用火山引擎 OCR 服务
  10300. $content = $this->callVolcEngineOCR($base64Image);
  10301. return trim($content);
  10302. } catch (\Exception $e) {
  10303. dLog('deepseek')->error('图片OCR识别失败: ' . $e->getMessage());
  10304. logDB('deepseek', 'error', '图片OCR识别失败', ['error' => $e->getMessage()]);
  10305. Utils::throwError('20003:图片识别失败');
  10306. }
  10307. }
  10308. /**
  10309. * 调用火山引擎 OCR 服务识别图片文字
  10310. *
  10311. * @param string $base64Image base64 编码的图片数据
  10312. * @return string 识别的文字内容
  10313. */
  10314. private function callVolcEngineOCR($base64Image) {
  10315. $method = 'POST';
  10316. $service = 'cv';
  10317. $host = 'visual.volcengineapi.com';
  10318. $region = env('VOLC_REGION', 'cn-north-1');
  10319. $access_key = env('VOLC_AK');
  10320. $secret_key = env('VOLC_SK');
  10321. $action = 'OCRNormal';
  10322. $version = '2020-08-26';
  10323. if (!$access_key || !$secret_key) {
  10324. Utils::throwError('20003:请配置火山引擎 AK/SK');
  10325. }
  10326. // 请求体
  10327. $body = json_encode([
  10328. 'image_base64' => $base64Image
  10329. ]);
  10330. // 生成签名
  10331. $headers = $this->getVolcEngineSignHeaders(
  10332. $method, $service, $host, $region,
  10333. "Action={$action}&Version={$version}",
  10334. $access_key, $secret_key, $body
  10335. );
  10336. $client = new Client(['timeout' => 1800, 'verify' => false]);
  10337. $response = $client->post("https://{$host}/?Action={$action}&Version={$version}", [
  10338. 'headers' => $headers,
  10339. 'body' => $body
  10340. ]);
  10341. $response_arr = json_decode($response->getBody()->getContents(), true);
  10342. // 提取识别的文字
  10343. $textLines = [];
  10344. if (isset($response_arr['data']['line_texts'])) {
  10345. $textLines = $response_arr['data']['line_texts'];
  10346. } elseif (isset($response_arr['data']['ocr_infos'])) {
  10347. foreach ($response_arr['data']['ocr_infos'] as $info) {
  10348. if (isset($info['text'])) {
  10349. $textLines[] = $info['text'];
  10350. }
  10351. }
  10352. }
  10353. if (empty($textLines)) {
  10354. dLog('deepseek')->warning('OCR识别结果为空', ['response' => $response_arr]);
  10355. return '';
  10356. }
  10357. return implode("\n", $textLines);
  10358. }
  10359. /**
  10360. * 生成火山引擎 API 签名头(用于 OCR 等 POST 请求)
  10361. */
  10362. private function getVolcEngineSignHeaders($method, $service, $host, $region, $queryString, $access_key, $secret_key, $body = '') {
  10363. $contentType = 'application/json';
  10364. $accept = 'application/json';
  10365. // 获取当前UTC时间
  10366. $t = new DateTime('now', new DateTimeZone('UTC'));
  10367. $xDate = $t->format('Ymd\THis\Z');
  10368. $dateStamp = $t->format('Ymd');
  10369. // 计算 body 的 sha256 哈希
  10370. $payloadHash = hash('sha256', $body);
  10371. // 1. 拼接规范请求串
  10372. $canonicalUri = '/';
  10373. $canonicalQueryString = $queryString;
  10374. $canonicalHeaders = "content-type:{$contentType}\nhost:{$host}\nx-content-sha256:{$payloadHash}\nx-date:{$xDate}\n";
  10375. $signedHeaders = 'content-type;host;x-content-sha256;x-date';
  10376. $canonicalRequest = implode("\n", [
  10377. $method,
  10378. $canonicalUri,
  10379. $canonicalQueryString,
  10380. $canonicalHeaders,
  10381. $signedHeaders,
  10382. $payloadHash
  10383. ]);
  10384. // 2. 拼接待签名字符串
  10385. $algorithm = 'HMAC-SHA256';
  10386. $credentialScope = implode('/', [$dateStamp, $region, $service, 'request']);
  10387. $hashedCanonicalRequest = hash('sha256', $canonicalRequest);
  10388. $stringToSign = implode("\n", [
  10389. $algorithm,
  10390. $xDate,
  10391. $credentialScope,
  10392. $hashedCanonicalRequest
  10393. ]);
  10394. // 3. 计算签名
  10395. $signingKey = $this->getSignatureKey($secret_key, $dateStamp, $region, $service);
  10396. $signature = hash_hmac('sha256', $stringToSign, $signingKey);
  10397. // 4. 添加签名到请求头
  10398. $authorizationHeader = sprintf(
  10399. '%s Credential=%s/%s, SignedHeaders=%s, Signature=%s',
  10400. $algorithm,
  10401. $access_key,
  10402. $credentialScope,
  10403. $signedHeaders,
  10404. $signature
  10405. );
  10406. return [
  10407. 'Accept' => $accept,
  10408. 'Content-Type' => $contentType,
  10409. 'Host' => $host,
  10410. 'X-Date' => $xDate,
  10411. 'X-Content-Sha256'=> $payloadHash,
  10412. 'Authorization' => $authorizationHeader
  10413. ];
  10414. }
  10415. public function generateScriptWords($cid, $model = 'r1') {
  10416. ini_set('max_execution_time', 0);
  10417. if (!$cid) Utils::throwError('20003: 请选择章节!');
  10418. $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
  10419. // 模型兼容性处理和思考模式设置
  10420. $thinkingMode = 'disabled';
  10421. $reasoningEffort = 'high';
  10422. if ($model == 'r1') {
  10423. $model = 'deepseek-v4-flash'; // r1 映射到 deepseek-v4-flash 思考模式
  10424. $thinkingMode = 'enabled';
  10425. } else {
  10426. $model = 'deepseek-v4-flash'; // 默认映射到 deepseek-v4-flash 非思考模式
  10427. $thinkingMode = 'disabled';
  10428. }
  10429. $messages = [
  10430. [
  10431. 'role' => 'system',
  10432. 'content' => '下面有一段小说文本,请帮我将文本中的每句话按从上到下的顺序拆分成角色不同的剧本文稿(不得更改上下文顺序和内容),文稿形式严格按照“角色名(男或女):台词{情感}”输出,需要注意以下几点要求:
  10433. 1.角色名后不要加入任何其他词语,只能加不包括旁白的性别,在男或女中选
  10434. 2.非对话部分请全部用旁白角色代替
  10435. 3.情感必须在【开心、悲伤、生气、惊讶、恐惧、厌恶、激动、冷漠、中性、沮丧、撒娇、害羞、安慰鼓励、咆哮、温柔、自然讲述、情感电台、磁性、广告营销、气泡音、新闻播报、娱乐八卦】中选一个,不得使用其他词语'
  10436. ],
  10437. [
  10438. 'role' => 'user',
  10439. 'content' => $content
  10440. ]
  10441. ];
  10442. $post_data = [
  10443. 'model' => $model,
  10444. 'messages' => $messages,
  10445. // 'max_tokens' => 8192,
  10446. 'temperature' => 1,
  10447. 'frequency_penalty' => 0,
  10448. 'presence_penalty' => 0,
  10449. 'thinking' => ['type' => $thinkingMode],
  10450. 'response_format' => [
  10451. 'type' => 'text'
  10452. ],
  10453. 'stream' => false
  10454. ];
  10455. if ($thinkingMode == 'enabled') $post_data['reasoning_effort'] = $reasoningEffort;
  10456. // 根据模型类型选择调用方法
  10457. $fullContent = '';
  10458. if (in_array($model, ['deepseek-reasoner', 'deepseek-chat', 'deepseek-v4-flash', 'deepseek-v4-pro'])) {
  10459. // DeepSeek 官方模型使用 DeepSeek API
  10460. $chatResult = $this->chatOnly($post_data);
  10461. } else if (in_array($model, $this->gpt_text_models)) {
  10462. // GPT-5.4 模型使用 TokenRouter API
  10463. $chatResult = $this->gpt54ChatOnly($post_data);
  10464. } else {
  10465. // 其他模型使用火山引擎API
  10466. $chatResult = $this->volcEngineChatCompletion($post_data);
  10467. }
  10468. if (is_array($chatResult)) {
  10469. $fullContent = $chatResult['fullContent'];
  10470. }
  10471. return $fullContent;
  10472. }
  10473. /**
  10474. * 智能化解析集数信息
  10475. * 支持多种表达方式,如:改成3集、调整成5集、修改为10集等
  10476. *
  10477. * @param string $prompt 用户输入的提示词
  10478. * @return int|null 解析出的集数,如果没有找到则返回null
  10479. */
  10480. private function extractEpisodeNumber($prompt)
  10481. {
  10482. if (empty($prompt)) {
  10483. return null;
  10484. }
  10485. // 定义各种可能的表达模式
  10486. $patterns = [
  10487. // 基本模式:改成N集、调整成N集、修改成N集
  10488. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为)\s*(\d+)\s*集/u',
  10489. // 扩展模式:分成N集、拆分成N集、分割成N集
  10490. '/(?:分成|拆分成|分割成|划分成|分为)\s*(\d+)\s*集/u',
  10491. // 数量模式:N集、共N集、总共N集
  10492. '/(?:共|总共|一共|总计)?\s*(\d+)\s*集/u',
  10493. // 制作模式:制作N集、生成N集、创建N集
  10494. '/(?:制作|生成|创建|产出|输出)\s*(\d+)\s*集/u',
  10495. // 计划模式:计划N集、预计N集、打算N集
  10496. '/(?:计划|预计|打算|准备|想要)\s*(\d+)\s*集/u',
  10497. // 需要模式:需要N集、要N集
  10498. '/(?:需要|要|需)\s*(\d+)\s*集/u',
  10499. // 中文数字模式:改成三集、调整成五集等
  10500. '/(?:改成|调整成|修改成|变成|设置成|设为|改为|调为|修改为|变为|分成|拆分成|分割成|划分成|分为|制作|生成|创建|产出|输出|计划|预计|打算|准备|想要|需要|要|需)\s*([一二三四五六七八九十]+)\s*集/u',
  10501. // 英文数字模式
  10502. '/(?: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',
  10503. ];
  10504. // 中文数字转阿拉伯数字的映射
  10505. $chineseNumbers = [
  10506. '一' => 1, '二' => 2, '三' => 3, '四' => 4, '五' => 5,
  10507. '六' => 6, '七' => 7, '八' => 8, '九' => 9, '十' => 10,
  10508. '十一' => 11, '十二' => 12, '十三' => 13, '十四' => 14, '十五' => 15,
  10509. '十六' => 16, '十七' => 17, '十八' => 18, '十九' => 19, '二十' => 20
  10510. ];
  10511. // 逐个尝试匹配模式
  10512. foreach ($patterns as $pattern) {
  10513. if (preg_match($pattern, $prompt, $matches)) {
  10514. $number = trim($matches[1]);
  10515. // 如果是中文数字,转换为阿拉伯数字
  10516. if (isset($chineseNumbers[$number])) {
  10517. return $chineseNumbers[$number];
  10518. }
  10519. // 如果是阿拉伯数字,直接返回
  10520. if (is_numeric($number)) {
  10521. $episodeNum = intval($number);
  10522. // 合理性检查:集数应该在1-100之间
  10523. if ($episodeNum >= 1 && $episodeNum <= 100) {
  10524. return $episodeNum;
  10525. }
  10526. }
  10527. }
  10528. }
  10529. return null;
  10530. }
  10531. /**
  10532. * 调用火山引擎对话(Chat) API
  10533. *
  10534. * @param array $params 包含以下参数:
  10535. * - model: 模型ID(必填)
  10536. * - messages: 消息列表(必填)
  10537. * - stream: 是否流式输出(可选,默认false)
  10538. * - max_tokens: 最大输出token数(可选)
  10539. * - temperature: 采样温度(可选,默认1)
  10540. * - top_p: 核采样概率(可选,默认0.7)
  10541. * - frequency_penalty: 频率惩罚系数(可选,默认0)
  10542. * - presence_penalty: 存在惩罚系数(可选,默认0)
  10543. * - stop: 停止词(可选)
  10544. * - tools: 工具列表(可选)
  10545. * @return array|Generator 非流式返回数组,流式返回生成器
  10546. */
  10547. public function volcEngineChatCompletion(array $params)
  10548. {
  10549. $apiKey = env('VOLC_AI_API_KEY');
  10550. if (empty($apiKey)) {
  10551. Utils::throwError('20003:火山引擎API Key未配置,请检查环境变量VOLC_AI_API_KEY');
  10552. }
  10553. // 构建请求参数
  10554. $originalModel = $params['model'] ?? 'deepseek-v3-2-251201';
  10555. $requestData = [
  10556. 'model' => isset(\App\Consts\BaseConst::MODELS_MAP[$originalModel]) ? \App\Consts\BaseConst::MODELS_MAP[$originalModel] : $originalModel,
  10557. 'messages' => $params['messages'] ?? [],
  10558. ];
  10559. if (!in_array($originalModel, $this->valid_text_models)) {
  10560. Utils::throwError('20003:该模型不支持!');
  10561. }
  10562. // 添加可选参数
  10563. if (isset($params['stream'])) {
  10564. $requestData['stream'] = $params['stream'];
  10565. }
  10566. if (isset($params['stream_options'])) {
  10567. $requestData['stream_options'] = $params['stream_options'];
  10568. }
  10569. if (isset($params['max_tokens'])) {
  10570. $requestData['max_tokens'] = $params['max_tokens'];
  10571. }else if (isset($params['max_completion_tokens'])) {
  10572. $requestData['max_completion_tokens'] = $params['max_completion_tokens'];
  10573. }else {
  10574. $requestData['max_completion_tokens'] = 100000;
  10575. }
  10576. if (isset($params['temperature'])) {
  10577. $requestData['temperature'] = $params['temperature'];
  10578. }
  10579. if (isset($params['top_p'])) {
  10580. $requestData['top_p'] = $params['top_p'];
  10581. }
  10582. if (isset($params['frequency_penalty'])) {
  10583. $requestData['frequency_penalty'] = $params['frequency_penalty'];
  10584. }
  10585. if (isset($params['presence_penalty'])) {
  10586. $requestData['presence_penalty'] = $params['presence_penalty'];
  10587. }
  10588. if (isset($params['stop'])) {
  10589. $requestData['stop'] = $params['stop'];
  10590. }
  10591. if (isset($params['tools'])) {
  10592. $requestData['tools'] = $params['tools'];
  10593. }
  10594. if (isset($params['tool_choice'])) {
  10595. $requestData['tool_choice'] = $params['tool_choice'];
  10596. }
  10597. if (isset($params['response_format'])) {
  10598. $requestData['response_format'] = $params['response_format'];
  10599. }
  10600. if (isset($params['thinking'])) {
  10601. // 如果 thinking 已经是数组格式,直接使用;否则转换为正确格式
  10602. if (is_array($params['thinking'])) {
  10603. $requestData['thinking'] = $params['thinking'];
  10604. if (isset($params['reasoning_effort']) && $params['thinking']['type'] == 'enabled') {
  10605. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  10606. }
  10607. } else {
  10608. $requestData['thinking'] = ['type' => $params['thinking']];
  10609. if (isset($params['reasoning_effort']) && $params['thinking'] == 'enabled') {
  10610. $requestData['reasoning_effort'] = $params['reasoning_effort'];
  10611. }
  10612. }
  10613. } else {
  10614. $requestData['thinking'] = ['type' => 'disabled'];
  10615. }
  10616. dLog('deepseek')->info('火山引擎对话API请求参数: ', $requestData);
  10617. $client = new Client(['verify' => false, 'timeout' => 1800]);
  10618. try {
  10619. // 判断是否为流式输出
  10620. $isStream = isset($params['stream']) && $params['stream'] === true;
  10621. if ($isStream) {
  10622. // 流式输出
  10623. return $this->volcEngineChatCompletionStream($client, $apiKey, $requestData);
  10624. } else {
  10625. // 非流式输出
  10626. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  10627. 'headers' => [
  10628. 'Authorization' => 'Bearer ' . $apiKey,
  10629. 'Content-Type' => 'application/json',
  10630. ],
  10631. 'json' => $requestData
  10632. ]);
  10633. $responseData = json_decode($response->getBody(), true);
  10634. dLog('deepseek')->info('火山引擎对话API响应: ', $responseData);
  10635. $usage = isset($responseData['usage']) ? $responseData['usage'] : [];
  10636. if (isset($responseData['choices']) && count($responseData['choices']) > 0) {
  10637. $fullContent = isset($responseData['choices'][0]['message']['content']) ? $responseData['choices'][0]['message']['content'] : '';
  10638. $fullReasoningContent = isset($responseData['choices'][0]['message']['reasoning_content']) ? $responseData['choices'][0]['message']['reasoning_content'] : '';
  10639. }
  10640. return [
  10641. 'fullContent' => $fullContent,
  10642. 'fullReasoningContent' => $fullReasoningContent,
  10643. 'usage' => $usage
  10644. ];
  10645. }
  10646. } catch (\Exception $e) {
  10647. dLog('deepseek')->error('火山引擎对话API请求异常: ' . $e->getMessage());
  10648. logDB('deepseek', 'error', '火山引擎对话API请求失败', ['error' => $e->getMessage(), 'model' => $requestData['model']]);
  10649. Utils::throwError('20003:火山引擎对话API请求失败: ' . $e->getMessage());
  10650. }
  10651. }
  10652. /**
  10653. * 火山引擎对话API流式输出
  10654. *
  10655. * @param Client $client HTTP客户端
  10656. * @param string $apiKey API密钥
  10657. * @param array $requestData 请求数据
  10658. * @return Generator
  10659. */
  10660. private function volcEngineChatCompletionStream($client, $apiKey, $requestData)
  10661. {
  10662. try {
  10663. $response = $client->post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', [
  10664. 'headers' => [
  10665. 'Authorization' => 'Bearer ' . $apiKey,
  10666. 'Content-Type' => 'application/json',
  10667. ],
  10668. 'json' => $requestData,
  10669. 'stream' => true
  10670. ]);
  10671. $body = $response->getBody();
  10672. $buffer = '';
  10673. $fullContent = '';
  10674. $fullReasoningContent = '';
  10675. $usage = [];
  10676. dLog('deepseek')->info('开始读取火山引擎对话API流式响应');
  10677. // 逐行读取流式响应
  10678. while (!$body->eof()) {
  10679. $chunk = $body->read(1024);
  10680. $buffer .= $chunk;
  10681. // 按行分割
  10682. $lines = explode("\n", $buffer);
  10683. $buffer = array_pop($lines);
  10684. foreach ($lines as $line) {
  10685. $line = trim($line);
  10686. if (empty($line)) {
  10687. continue;
  10688. }
  10689. // 检查是否是SSE数据行
  10690. if (strpos($line, 'data: ') !== 0) {
  10691. continue;
  10692. }
  10693. $data = substr($line, 6);
  10694. if ($data === '[DONE]') {
  10695. dLog('deepseek')->info('收到结束标记');
  10696. break 2;
  10697. }
  10698. try {
  10699. $json = json_decode($data, true);
  10700. if (json_last_error() !== JSON_ERROR_NONE) {
  10701. dLog('deepseek')->warning('JSON解析错误: ' . json_last_error_msg());
  10702. continue;
  10703. }
  10704. if (isset($json['choices'][0]['delta'])) {
  10705. $delta = $json['choices'][0]['delta'];
  10706. // 处理思维链内容
  10707. if (isset($delta['reasoning_content'])) {
  10708. $fullReasoningContent .= $delta['reasoning_content'];
  10709. yield [
  10710. 'type' => 'reasoning',
  10711. 'content' => $delta['reasoning_content'],
  10712. 'full_reasoning' => $fullReasoningContent
  10713. ];
  10714. }
  10715. // 处理回答内容
  10716. if (isset($delta['content'])) {
  10717. $fullContent .= $delta['content'];
  10718. yield [
  10719. 'type' => 'content',
  10720. 'content' => $delta['content'],
  10721. ];
  10722. }
  10723. }
  10724. // 获取使用统计信息
  10725. if (isset($json['usage'])) {
  10726. $usage = $json['usage'];
  10727. dLog('deepseek')->info('收到使用统计', ['usage' => $usage]);
  10728. }
  10729. } catch (\Exception $e) {
  10730. dLog('deepseek')->error('解析流式响应失败: ' . $e->getMessage());
  10731. continue;
  10732. }
  10733. }
  10734. }
  10735. dLog('deepseek')->info('流式读取完成', [
  10736. 'content_length' => strlen($fullContent),
  10737. 'reasoning_length' => strlen($fullReasoningContent)
  10738. ]);
  10739. yield [
  10740. 'type' => 'done',
  10741. 'full_content' => $fullContent,
  10742. 'full_reasoning' => $fullReasoningContent,
  10743. 'usage' => $usage
  10744. ];
  10745. } catch (\Exception $e) {
  10746. dLog('deepseek')->error('火山引擎对话API流式请求异常: ' . $e->getMessage());
  10747. logDB('deepseek', 'error', '火山引擎对话API流式请求失败', ['error' => $e->getMessage()]);
  10748. throw $e;
  10749. }
  10750. }
  10751. /**
  10752. * 检查并创建图片生成任务
  10753. *
  10754. * @param array $merged_items 合并后的资源列表(roles 或 scenes)
  10755. * @param array $global_items 全局资源列表(来自 mp_animes 表)
  10756. * @param string $nameKey 资源名称字段('role' 或 'scene')
  10757. * @param string $art_style 美术风格
  10758. * @return array 更新后的资源列表
  10759. */
  10760. private function checkAndCreateImageTasks(array $merged_items, array $global_items, string $nameKey, string $art_style = ''): array
  10761. {
  10762. // 确保参数为数组
  10763. $merged_items = is_array($merged_items) ? $merged_items : [];
  10764. $global_items = is_array($global_items) ? $global_items : [];
  10765. // 构建全局资源映射表,用于快速查找
  10766. $global_map = [];
  10767. foreach ($global_items as $item) {
  10768. $itemKey = $this->normalizeEpisodeResourceKey(getProp($item, $nameKey));
  10769. if ($itemKey === '') {
  10770. continue;
  10771. }
  10772. $global_map[$itemKey] = $item;
  10773. }
  10774. // 遍历合并后的资源列表,检查是否需要创建图片生成任务
  10775. foreach ($merged_items as &$item) {
  10776. $item_name = getProp($item, $nameKey);
  10777. $item_description = getProp($item, 'description');
  10778. // $item_url = getProp($item, 'url');
  10779. // // 如果已有图片URL,跳过
  10780. // if (!empty($item_url)) {
  10781. // continue;
  10782. // }
  10783. // 如果是旁白角色,跳过
  10784. if ($nameKey === 'role' && $item_name === '旁白') {
  10785. continue;
  10786. }
  10787. $itemKey = $this->normalizeEpisodeResourceKey($item_name);
  10788. if ($itemKey === '') {
  10789. continue;
  10790. }
  10791. $need_create_task = false;
  10792. // 条件1:在全局资源中找不到匹配的名称
  10793. if (!isset($global_map[$itemKey])) {
  10794. $need_create_task = true;
  10795. } else {
  10796. // 条件2:名称匹配但描述或 pic_prompt 不一致
  10797. $global_description = trim((string)getProp($global_map[$itemKey], 'description'));
  10798. $current_description = trim((string)$item_description);
  10799. $global_pic_prompt = trim((string)getProp($global_map[$itemKey], 'pic_prompt'));
  10800. $current_pic_prompt = trim((string)getProp($item, 'pic_prompt'));
  10801. // 如果 description 或 pic_prompt 有变化,需要重新生成
  10802. if ($global_description !== $current_description || $global_pic_prompt !== $current_pic_prompt) {
  10803. $need_create_task = true;
  10804. }
  10805. }
  10806. // 如果需要创建任务,调用图片生成服务
  10807. if ($need_create_task) {
  10808. try {
  10809. // 优先使用 pic_prompt,如果没有则使用 description
  10810. $pic_prompt = getProp($item, 'pic_prompt');
  10811. $description = !empty($pic_prompt) ? trim((string)$pic_prompt) : $item_description;
  10812. // 添加美术风格前缀
  10813. if ($art_style) {
  10814. $prefix = $nameKey === 'role' ? '主体描述' : '场景描述';
  10815. // $description = "美术风格:\n{$art_style}\n\n{$prefix}:{$description}";
  10816. $description = "{$prefix}:{$description}";
  10817. }
  10818. $params = [
  10819. 'prompt' => $description,
  10820. 'ref_img_urls' => []
  10821. ];
  10822. $task = $this->aiImageGenerationService->createImageGenerationTask($params);
  10823. $task_id = $task->id;
  10824. if ($task_id) {
  10825. $item['task_id'] = $task_id;
  10826. $item['task_status'] = 'processing';
  10827. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  10828. dLog('deepseek')->info("{$resource_type}({$item_name})创建图片生成任务成功", ['task_id' => $task_id]);
  10829. }
  10830. } catch (\Exception $e) {
  10831. $resource_type = $nameKey === 'role' ? '角色' : '场景';
  10832. dLog('deepseek')->error("{$resource_type}({$item_name})创建图片生成任务失败: " . $e->getMessage());
  10833. logDB('deepseek', 'error', "{$resource_type}创建图片生成任务失败", ['name' => $item_name, 'error' => $e->getMessage()]);
  10834. // 不抛出异常,继续处理其他资源
  10835. }
  10836. }
  10837. }
  10838. return $merged_items;
  10839. }
  10840. /**
  10841. * 同步新出现的主体和场景到全局
  10842. *
  10843. * @param int $anime_id 动漫ID
  10844. * @param array $merged_roles 合并后的角色列表
  10845. * @param array $merged_scenes 合并后的场景列表
  10846. * @param array $global_roles 全局角色列表
  10847. * @param array $global_scenes 全局场景列表
  10848. * @return void
  10849. */
  10850. private function syncNewResourcesToGlobal(
  10851. int $anime_id,
  10852. array $merged_roles,
  10853. array $merged_scenes,
  10854. array $global_roles,
  10855. array $global_scenes
  10856. ): void {
  10857. // 构建全局角色映射表
  10858. $global_role_map = [];
  10859. foreach ($global_roles as $role) {
  10860. $roleKey = $this->normalizeEpisodeResourceKey(getProp($role, 'role'));
  10861. if ($roleKey !== '') {
  10862. $global_role_map[$roleKey] = $role;
  10863. }
  10864. }
  10865. // 构建全局场景映射表
  10866. $global_scene_map = [];
  10867. foreach ($global_scenes as $scene) {
  10868. $sceneKey = $this->normalizeEpisodeResourceKey(getProp($scene, 'scene'));
  10869. if ($sceneKey !== '') {
  10870. $global_scene_map[$sceneKey] = $scene;
  10871. }
  10872. }
  10873. $need_update = false;
  10874. $new_global_roles = $global_roles;
  10875. $new_global_scenes = $global_scenes;
  10876. // 检查并添加新角色到全局
  10877. foreach ($merged_roles as $role) {
  10878. $role_name = getProp($role, 'role');
  10879. // 跳过旁白
  10880. if ($role_name === '旁白') {
  10881. continue;
  10882. }
  10883. $roleKey = $this->normalizeEpisodeResourceKey($role_name);
  10884. if ($roleKey === '') {
  10885. continue;
  10886. }
  10887. // 如果全局中不存在该角色,添加到全局
  10888. if (!isset($global_role_map[$roleKey])) {
  10889. $new_global_roles[] = [
  10890. 'role' => $role_name,
  10891. 'description' => getProp($role, 'description', ''),
  10892. 'pic_prompt' => getProp($role, 'pic_prompt', ''),
  10893. 'voice_name' => getProp($role, 'voice_name', ''),
  10894. 'voice_type' => getProp($role, 'voice_type', ''),
  10895. 'voice_audio_url' => getProp($role, 'voice_audio_url', ''),
  10896. 'url' => getProp($role, 'url', ''),
  10897. 'task_id' => getProp($role, 'task_id', ''),
  10898. 'task_status' => getProp($role, 'task_status', ''),
  10899. ];
  10900. $global_role_map[$roleKey] = true; // 标记已添加
  10901. $need_update = true;
  10902. dLog('deepseek')->info("新角色同步到全局", [
  10903. 'anime_id' => $anime_id,
  10904. 'role' => $role_name,
  10905. 'task_id' => getProp($role, 'task_id', ''),
  10906. ]);
  10907. }
  10908. // else {
  10909. // // 如果角色已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  10910. // $global_role = $global_role_map[$roleKey];
  10911. // if (is_array($global_role)) {
  10912. // $updated = false;
  10913. // $update_fields = [];
  10914. // // 检查描述是否更新
  10915. // $current_description = trim((string)getProp($role, 'description'));
  10916. // $global_description = trim((string)getProp($global_role, 'description'));
  10917. // if ($current_description !== '' && $current_description !== $global_description) {
  10918. // $updated = true;
  10919. // $update_fields[] = 'description';
  10920. // }
  10921. // // 检查pic_prompt是否更新
  10922. // $current_pic_prompt = trim((string)getProp($role, 'pic_prompt'));
  10923. // $global_pic_prompt = trim((string)getProp($global_role, 'pic_prompt'));
  10924. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  10925. // $updated = true;
  10926. // $update_fields[] = 'pic_prompt';
  10927. // }
  10928. // // 检查图片任务信息是否更新
  10929. // $current_task_id = getProp($role, 'task_id');
  10930. // $global_task_id = getProp($global_role, 'task_id');
  10931. // if ($current_task_id && $current_task_id !== $global_task_id) {
  10932. // $updated = true;
  10933. // $update_fields[] = 'task_id';
  10934. // }
  10935. // // 如果有更新,同步到全局
  10936. // if ($updated) {
  10937. // foreach ($new_global_roles as &$global_role_item) {
  10938. // $global_role_key = $this->normalizeEpisodeResourceKey(getProp($global_role_item, 'role'));
  10939. // if ($global_role_key === $roleKey) {
  10940. // if (in_array('description', $update_fields)) {
  10941. // $global_role_item['description'] = $current_description;
  10942. // }
  10943. // if (in_array('pic_prompt', $update_fields)) {
  10944. // $global_role_item['pic_prompt'] = $current_pic_prompt;
  10945. // }
  10946. // if (in_array('task_id', $update_fields)) {
  10947. // $global_role_item['task_id'] = $current_task_id;
  10948. // $global_role_item['task_status'] = getProp($role, 'task_status', '');
  10949. // $global_role_item['url'] = getProp($role, 'url', '');
  10950. // }
  10951. // break;
  10952. // }
  10953. // }
  10954. // $need_update = true;
  10955. // dLog('deepseek')->info("角色信息更新到全局", [
  10956. // 'anime_id' => $anime_id,
  10957. // 'role' => $role_name,
  10958. // 'update_fields' => implode(',', $update_fields),
  10959. // ]);
  10960. // }
  10961. // }
  10962. // }
  10963. }
  10964. // 检查并添加新场景到全局
  10965. foreach ($merged_scenes as $scene) {
  10966. $scene_name = getProp($scene, 'scene');
  10967. $sceneKey = $this->normalizeEpisodeResourceKey($scene_name);
  10968. if ($sceneKey === '') {
  10969. continue;
  10970. }
  10971. // 如果全局中不存在该场景,添加到全局
  10972. if (!isset($global_scene_map[$sceneKey])) {
  10973. $new_global_scenes[] = [
  10974. 'scene' => $scene_name,
  10975. 'description' => getProp($scene, 'description', ''),
  10976. 'pic_prompt' => getProp($scene, 'pic_prompt', ''),
  10977. 'url' => getProp($scene, 'url', ''),
  10978. 'task_id' => getProp($scene, 'task_id', ''),
  10979. 'task_status' => getProp($scene, 'task_status', ''),
  10980. ];
  10981. $global_scene_map[$sceneKey] = true; // 标记已添加
  10982. $need_update = true;
  10983. dLog('deepseek')->info("新场景同步到全局", [
  10984. 'anime_id' => $anime_id,
  10985. 'scene' => $scene_name,
  10986. 'task_id' => getProp($scene, 'task_id', ''),
  10987. ]);
  10988. }
  10989. // else {
  10990. // // 如果场景已存在,但描述、pic_prompt或图片信息有更新,则更新全局数据
  10991. // $global_scene = $global_scene_map[$sceneKey];
  10992. // if (is_array($global_scene)) {
  10993. // $updated = false;
  10994. // $update_fields = [];
  10995. // // 检查描述是否更新
  10996. // $current_description = trim((string)getProp($scene, 'description'));
  10997. // $global_description = trim((string)getProp($global_scene, 'description'));
  10998. // if ($current_description !== '' && $current_description !== $global_description) {
  10999. // $updated = true;
  11000. // $update_fields[] = 'description';
  11001. // }
  11002. // // 检查pic_prompt是否更新
  11003. // $current_pic_prompt = trim((string)getProp($scene, 'pic_prompt'));
  11004. // $global_pic_prompt = trim((string)getProp($global_scene, 'pic_prompt'));
  11005. // if ($current_pic_prompt !== '' && $current_pic_prompt !== $global_pic_prompt) {
  11006. // $updated = true;
  11007. // $update_fields[] = 'pic_prompt';
  11008. // }
  11009. // // 检查图片任务信息是否更新
  11010. // $current_task_id = getProp($scene, 'task_id');
  11011. // $global_task_id = getProp($global_scene, 'task_id');
  11012. // if ($current_task_id && $current_task_id !== $global_task_id) {
  11013. // $updated = true;
  11014. // $update_fields[] = 'task_id';
  11015. // }
  11016. // // 如果有更新,同步到全局
  11017. // if ($updated) {
  11018. // foreach ($new_global_scenes as &$global_scene_item) {
  11019. // $global_scene_key = $this->normalizeEpisodeResourceKey(getProp($global_scene_item, 'scene'));
  11020. // if ($global_scene_key === $sceneKey) {
  11021. // if (in_array('description', $update_fields)) {
  11022. // $global_scene_item['description'] = $current_description;
  11023. // }
  11024. // if (in_array('pic_prompt', $update_fields)) {
  11025. // $global_scene_item['pic_prompt'] = $current_pic_prompt;
  11026. // }
  11027. // if (in_array('task_id', $update_fields)) {
  11028. // $global_scene_item['task_id'] = $current_task_id;
  11029. // $global_scene_item['task_status'] = getProp($scene, 'task_status', '');
  11030. // $global_scene_item['url'] = getProp($scene, 'url', '');
  11031. // }
  11032. // break;
  11033. // }
  11034. // }
  11035. // $need_update = true;
  11036. // dLog('deepseek')->info("场景信息更新到全局", [
  11037. // 'anime_id' => $anime_id,
  11038. // 'scene' => $scene_name,
  11039. // 'update_fields' => implode(',', $update_fields),
  11040. // ]);
  11041. // }
  11042. // }
  11043. // }
  11044. }
  11045. // 如果有新增或更新,更新数据库
  11046. if ($need_update) {
  11047. $update_data = [
  11048. 'roles' => json_encode($new_global_roles, 256),
  11049. 'scenes' => json_encode($new_global_scenes, 256),
  11050. 'updated_at' => date('Y-m-d H:i:s'),
  11051. ];
  11052. $result = DB::table('mp_animes')->where('id', $anime_id)->update($update_data);
  11053. if ($result !== false) {
  11054. dLog('deepseek')->info("全局角色和场景更新成功", [
  11055. 'anime_id' => $anime_id,
  11056. 'roles_count' => count($new_global_roles),
  11057. 'scenes_count' => count($new_global_scenes),
  11058. ]);
  11059. } else {
  11060. dLog('deepseek')->error("全局角色和场景更新失败", ['anime_id' => $anime_id]);
  11061. logDB('deepseek', 'error', '全局角色和场景更新失败', ['anime_id' => $anime_id]);
  11062. }
  11063. }
  11064. }
  11065. }