DeepSeekService.php 303 KB

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