DeepSeekService.php 285 KB

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