Helpers.php 212 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688
  1. <?php
  2. use App\Consts\BaseConst;
  3. use GuzzleHttp\Client;
  4. use Illuminate\Support\Facades\DB;
  5. use Illuminate\Support\Facades\Cache;
  6. use Illuminate\Support\Facades\Log;
  7. use Monolog\Handler\StreamHandler;
  8. use Monolog\Logger;
  9. use OSS\OssClient;
  10. use OSS\Core\OssException;
  11. use Tos\TosClient;
  12. use Tos\Exception\TosClientException;
  13. use Tos\Exception\TosServerException;
  14. use Tos\Model\PutObjectInput;
  15. // use Imagick;
  16. /**
  17. * 截取字符串
  18. *
  19. * @param $string
  20. * @param $length
  21. * @param bool $append
  22. * @return array|string
  23. */
  24. function sysSubStr($string, $length, $append = false)
  25. {
  26. if (strlen($string) <= $length) {
  27. return $string;
  28. }
  29. $i = 0;
  30. $stringLast = [];
  31. while ($i < $length) {
  32. $stringTMP = mb_substr($string, $i, 1);
  33. if (ord($stringTMP) >= 224) {
  34. $stringTMP = mb_substr($string, $i, 3);
  35. $i += 3;
  36. } elseif (ord($stringTMP) >= 192) {
  37. $stringTMP = mb_substr($string, $i, 2);
  38. $i += 2;
  39. } else {
  40. ++$i;
  41. }
  42. $stringLast[] = $stringTMP;
  43. }
  44. $stringLast = implode('', $stringLast);
  45. if ($append) {
  46. $stringLast .= '...';
  47. }
  48. return $stringLast;
  49. }
  50. /**
  51. * 自定义日志
  52. *
  53. * @param $name
  54. * @param string $filename
  55. * @return \Illuminate\Log\Writer
  56. */
  57. function myLog($name, $filename = '')
  58. {
  59. if (!$filename) {
  60. $filename = $name;
  61. }
  62. $filename = $filename . '.log';
  63. $logger = new Logger($name);
  64. $writer = new \Illuminate\Log\Writer($logger);
  65. $writer->useDailyFiles(storage_path('logs/' . $filename));
  66. return $writer;
  67. }
  68. /**
  69. * 业务调试日志
  70. *
  71. * @return Logger
  72. */
  73. function commonLog()
  74. {
  75. $name = 'common';
  76. $filename = $name . '.log';
  77. $logger = new Logger($name);
  78. $logger->pushHandler(new StreamHandler(storage_path('logs/' . $filename), 'debug'));
  79. return $logger;
  80. }
  81. /**
  82. * @param $name
  83. * @return Logger
  84. */
  85. function dLog($name)
  86. {
  87. $filename = $name . '-' . date('Y-m-d') . '.log';
  88. $logger = new Logger($name);
  89. $logger->pushHandler(new StreamHandler(storage_path('logs/' . $filename), 'debug'));
  90. return $logger;
  91. }
  92. /**
  93. * 获取对象或数组的属性值
  94. *
  95. * @param $param
  96. * @param $key
  97. * @param string $default
  98. * @return mixed|string
  99. */
  100. function getProp($param, $key, $default = '')
  101. {
  102. $result = $default;
  103. if (is_object($param) && isset($param->$key)) {
  104. $result = $param->$key;
  105. }
  106. if (is_array($param) && isset($param[$key])) {
  107. $result = $param[$key];
  108. }
  109. return $result;
  110. }
  111. /**
  112. * @param $data
  113. * @param array $trans
  114. * @return array
  115. */
  116. function assetData($data, $trans = []): array
  117. {
  118. $result = [];
  119. if (empty($data)) {
  120. return $result;
  121. }
  122. if (empty($trans)) {
  123. return $data;
  124. }
  125. foreach ($trans as $tran) {
  126. [$originKey, $newKey, $conv, $default] = [$tran['o'], $tran['n'], $tran['conv'], $tran['default']];
  127. if (isset($data[$originKey])) {
  128. $result[$newKey] = $conv(getProp($data, $originKey, $default));
  129. }
  130. }
  131. return $result;
  132. }
  133. /**
  134. * 随机数
  135. *
  136. * @param int $num
  137. * @return string
  138. * @throws Exception
  139. */
  140. function random($num = 16)
  141. {
  142. $bytes = random_bytes($num);
  143. return bin2hex($bytes);
  144. }
  145. /**
  146. * 生成订单
  147. *
  148. * @param string $prefix 订单前缀
  149. * @return string
  150. */
  151. function generateOrderSn($prefix = '')
  152. {
  153. return $prefix . date('YmdHis') . getMillisecond() . rand(1000, 9999);
  154. }
  155. /**
  156. * 分页数据
  157. *
  158. * @param $data
  159. * @return array
  160. */
  161. function getMeta($data)
  162. {
  163. $currentPage = (int)$data->currentPage();
  164. $lastPage = (int)$data->lastPage();
  165. return [
  166. 'current_page' => $currentPage,
  167. 'next_page' => $currentPage >= $lastPage ? $lastPage : ++$currentPage,
  168. 'last_page' => $lastPage,
  169. 'per_page' => (int)$data->perPage(),
  170. 'total' => (int)$data->total(),
  171. 'is_end' => !$data->hasMorePages(),
  172. 'next_page_url' => (string)$data->nextPageUrl(),
  173. 'prev_page_url' => (string)$data->previousPageUrl()
  174. ];
  175. }
  176. /**
  177. * 钉钉通知异常
  178. *
  179. * @param $message
  180. */
  181. function sendNotice($message)
  182. {
  183. $webHook = env('DD_WEB_HOOK');
  184. $data = [
  185. 'msgtype' => 'text',
  186. 'text' => [
  187. 'content' => $message
  188. ],
  189. 'at' => [
  190. 'isAll' => true
  191. ]
  192. ];
  193. // 异步发送
  194. $client = new GuzzleHttp\Client();
  195. $client->post($webHook, ['json' => $data]);
  196. }
  197. /**
  198. * 判断数据是合法的json数据
  199. *
  200. * @param $string
  201. * @return bool
  202. */
  203. function is_json($string)
  204. {
  205. json_decode($string);
  206. return (json_last_error() == JSON_ERROR_NONE);
  207. }
  208. /**
  209. * 获取ip地址
  210. *
  211. * @return mixed|string
  212. */
  213. function getIpAddr()
  214. {
  215. $ipaddress = '';
  216. if (isset($_SERVER['HTTP_CLIENT_IP']))
  217. $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
  218. else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
  219. $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
  220. else if (isset($_SERVER['HTTP_X_FORWARDED']))
  221. $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
  222. else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
  223. $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
  224. else if (isset($_SERVER['HTTP_FORWARDED']))
  225. $ipaddress = $_SERVER['HTTP_FORWARDED'];
  226. else if (isset($_SERVER['REMOTE_ADDR']))
  227. $ipaddress = $_SERVER['REMOTE_ADDR'];
  228. else
  229. $ipaddress = 'UNKNOWN';
  230. return $ipaddress;
  231. }
  232. /**
  233. * @param int $num
  234. * @return bool|string
  235. * @throws Exception
  236. */
  237. function randStr($num = 5)
  238. {
  239. $str = 'QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm';
  240. return substr(str_shuffle($str), random_int(0, strlen($str) - 11), $num);
  241. }
  242. /**
  243. * 上传文件(火山云tos)
  244. *
  245. * @param $prefix 文件夹前缀
  246. * @param $file 文件二进制
  247. * @param $filename 文件名(不带后缀)
  248. * @return mixed
  249. */
  250. function uploadFileByTos($prefix, $file, $filename='')
  251. {
  252. if (!$filename) $filename = randStr(10) . '.' . $file->getClientOriginalExtension();
  253. else $filename = $filename . '.' . $file->getClientOriginalExtension();
  254. try {
  255. $client = new TosClient([
  256. 'region' => env('VOLC_REGION'),
  257. 'endpoint' => env('VOLC_END_POINT'),
  258. 'ak' => env('VOLC_AK'),
  259. 'sk' => env('VOLC_SK'),
  260. ]);
  261. $stream = fopen($file->getRealPath(), 'r');
  262. $input = new PutObjectInput(env('VOLC_BUCKET'), "$prefix/$filename", $stream);
  263. $output = $client->putObject($input);
  264. if ($output->getRequestId()) {
  265. return "https://".env('VOLC_BUCKET').'.'.env('VOLC_END_POINT')."/$prefix/$filename";
  266. }
  267. } catch (TosClientException $ex) {
  268. dLog('exception')->info('saveToTos', [$ex->getMessage()]);
  269. } catch (TosServerException $ex) {
  270. dLog('exception')->info('saveToTos', [$ex->getRequestId(), $ex->getStatusCode(), $ex->getErrorCode()]);
  271. }
  272. return '';
  273. }
  274. /**
  275. * 上传文件流(火山云tos)
  276. *
  277. * @param $prefix 文件夹前缀
  278. * @param $file 文件二进制
  279. * @param $filename 文件名(带后缀)
  280. * @return mixed
  281. */
  282. function uploadStreamByTos($prefix, $stream, $filename)
  283. {
  284. try {
  285. $client = new TosClient([
  286. 'region' => env('VOLC_REGION'),
  287. 'endpoint' => env('VOLC_END_POINT'),
  288. 'ak' => env('VOLC_AK'),
  289. 'sk' => env('VOLC_SK'),
  290. ]);
  291. $input = new PutObjectInput(env('VOLC_BUCKET'), "$prefix/$filename", $stream);
  292. $output = $client->putObject($input);
  293. if ($output->getRequestId()) {
  294. return "https://".env('VOLC_BUCKET').'.'.env('VOLC_END_POINT')."/$prefix/$filename";
  295. }
  296. } catch (TosClientException $ex) {
  297. dLog('exception')->info('saveToTos', [$ex->getMessage()]);
  298. } catch (TosServerException $ex) {
  299. dLog('exception')->info('saveToTos', [$ex->getRequestId(), $ex->getStatusCode(), $ex->getErrorCode()]);
  300. }
  301. return '';
  302. }
  303. // 从图片URL获取图片扩展名
  304. function getImgExtFromUrl(string $url): ?string {
  305. $imageInfo = @getimagesize($url);
  306. if ($imageInfo !== false) {
  307. // 返回MIME类型
  308. return mimeToExt($imageInfo['mime']);
  309. // 或者返回文件扩展名
  310. // return image_type_to_extension($imageInfo[2], false);
  311. }
  312. return null;
  313. }
  314. /**
  315. * 从视频URL获取视频扩展名
  316. * 通过下载文件头部字节来识别真实的视频格式
  317. *
  318. * @param string $url 视频URL
  319. * @return string 返回扩展名(如 .mp4),默认 .mp4
  320. */
  321. function getVideoExtFromUrl(string $url): string {
  322. try {
  323. // 方法1:从URL路径中提取扩展名
  324. $parsedUrl = parse_url($url);
  325. $path = $parsedUrl['path'] ?? '';
  326. $pathInfo = pathinfo($path);
  327. $extension = $pathInfo['extension'] ?? '';
  328. if ($extension) {
  329. // 验证是否为常见视频格式
  330. $validVideoExts = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v', 'mpeg', 'mpg'];
  331. if (in_array(strtolower($extension), $validVideoExts)) {
  332. return '.' . strtolower($extension);
  333. }
  334. }
  335. // 方法2:下载文件头部字节来识别格式
  336. $client = new \GuzzleHttp\Client(['timeout' => 30]);
  337. // 先尝试HEAD请求获取Content-Type
  338. try {
  339. $response = $client->head($url);
  340. $contentType = $response->getHeader('Content-Type')[0] ?? '';
  341. // 根据Content-Type映射扩展名
  342. $mimeMap = [
  343. 'video/mp4' => '.mp4',
  344. 'video/x-msvideo' => '.avi',
  345. 'video/quicktime' => '.mov',
  346. 'video/x-ms-wmv' => '.wmv',
  347. 'video/x-flv' => '.flv',
  348. 'video/x-matroska' => '.mkv',
  349. 'video/webm' => '.webm',
  350. 'video/mpeg' => '.mpeg',
  351. ];
  352. if (isset($mimeMap[$contentType])) {
  353. return $mimeMap[$contentType];
  354. }
  355. } catch (\Exception $e) {
  356. // HEAD请求失败,继续尝试其他方法
  357. }
  358. // 方法3:下载前几个字节分析文件魔数(Magic Number)
  359. $response = $client->get($url, [
  360. 'stream' => true,
  361. 'headers' => [
  362. 'Range' => 'bytes=0-31' // 只下载前32字节
  363. ]
  364. ]);
  365. $header = $response->getBody()->read(32);
  366. // 根据文件魔数判断格式
  367. // MP4/M4V: 以 ftyp 开头(偏移4-8字节)
  368. if (strpos($header, 'ftyp') !== false) {
  369. // 进一步判断是否为 M4V
  370. if (strpos($header, 'M4V') !== false || strpos($header, 'm4v') !== false) {
  371. return '.m4v';
  372. }
  373. return '.mp4';
  374. }
  375. // AVI: 以 RIFF 开头,包含 AVI
  376. if (substr($header, 0, 4) === 'RIFF' && strpos($header, 'AVI') !== false) {
  377. return '.avi';
  378. }
  379. // MOV: 包含 moov 或 mdat
  380. if (strpos($header, 'moov') !== false || strpos($header, 'mdat') !== false) {
  381. return '.mov';
  382. }
  383. // FLV: 以 FLV 开头
  384. if (substr($header, 0, 3) === 'FLV') {
  385. return '.flv';
  386. }
  387. // WebM: 以 0x1A 0x45 0xDF 0xA3 开头
  388. if (ord($header[0]) === 0x1A && ord($header[1]) === 0x45 &&
  389. ord($header[2]) === 0xDF && ord($header[3]) === 0xA3) {
  390. return '.webm';
  391. }
  392. // MKV: 与WebM类似,但包含 matroska
  393. if (strpos($header, 'matroska') !== false) {
  394. return '.mkv';
  395. }
  396. // MPEG: 以 0x00 0x00 0x01 开头
  397. if (ord($header[0]) === 0x00 && ord($header[1]) === 0x00 && ord($header[2]) === 0x01) {
  398. return '.mpeg';
  399. }
  400. // 默认返回 .mp4(最常见的格式)
  401. return '.mp4';
  402. } catch (\Exception $e) {
  403. // 出错时返回默认格式
  404. return '.mp4';
  405. }
  406. }
  407. // 辅助 MIME 映射函数
  408. function mimeToExt(string $mime): ?string {
  409. $map = [
  410. 'audio/wav' => '.wav',
  411. 'audio/x-ms-wma' => '.wma',
  412. 'video/x-ms-wmv' => '.wmv',
  413. 'video/mp4' => '.mp4',
  414. 'audio/mpeg' => '.mp3',
  415. 'audio/amr' => '.amr',
  416. 'application/vnd.rn-realmedia' => '.rm',
  417. 'audio/mid' => '.mid',
  418. 'image/bmp' => '.bmp',
  419. 'image/gif' => '.gif',
  420. 'image/png' => '.png',
  421. 'image/tiff' => '.tiff',
  422. 'image/jpeg' => '.jpg',
  423. 'application/pdf' => '.pdf',
  424. ];
  425. return $map[$mime] ?? null;
  426. }
  427. /**
  428. * 上传文件(阿里云oss)
  429. *
  430. * @param $prefix 文件夹前缀
  431. * @param $file 文件二进制
  432. * @param $filename 文件名(不带后缀)
  433. * @return mixed
  434. */
  435. function uploadFile($prefix, $file, $filename='')
  436. {
  437. // 阿里云主账号
  438. $accessKeyId = env('OSS_ACCESS_ID');
  439. $accessKeySecret = env('OSS_ACCESS_KEY');
  440. $endpoint = env('OSS_END_POINT');
  441. $bucket = env('OSS_BUCKET');
  442. if (!$filename) $filename = randStr(10) . '.' . $file->getClientOriginalExtension();
  443. else $filename = $filename . '.' . $file->getClientOriginalExtension();
  444. // 设置文件名称。
  445. $object = env('OSS_DIRECTORY') . '/' . $prefix . '/' . $filename;
  446. $provider = new \OSS\Credentials\StaticCredentialsProvider($accessKeyId, $accessKeySecret);
  447. try {
  448. $configs = [
  449. "provider" => $provider,
  450. "endpoint" => $endpoint,
  451. "signatureVersion" => 'v4',
  452. "region" => "cn-hangzhou"
  453. ];
  454. $ossClient = new OssClient($configs);
  455. $uploadRes = $ossClient->uploadFile($bucket, $object, $file->path());
  456. } catch (OssException $e) {
  457. dLog('exception')->info('saveImageToOss', [$e->getMessage()]);
  458. return '';
  459. }
  460. // 替换域名
  461. if (!isset($uploadRes['oss-request-url'])) return '';
  462. $url = str_ireplace('zw-ai.oss-cn-hangzhou.aliyuncs.com', 'cdn-zwai.ycsd.cn', $uploadRes['oss-request-url']);
  463. $url = urldecode($url);
  464. return str_ireplace('http://', 'https://', $url);
  465. }
  466. /**
  467. * 上传文件流(阿里云oss)
  468. *
  469. * @param $prefix 文件夹前缀
  470. * @param $file 文件二进制
  471. * @param $filename 文件名(带后缀)
  472. * @return mixed
  473. */
  474. function uploadStreamToOss($prefix, $stream, $filename) {
  475. $accessKeyId = env('OSS_ACCESS_ID');
  476. $accessKeySecret = env('OSS_ACCESS_KEY');
  477. $endpoint = env('OSS_END_POINT');
  478. $bucket = env('OSS_BUCKET');
  479. // if (!$filename) $filename = randStr(10) . '.' . $file->getClientOriginalExtension();
  480. // 设置文件名称。
  481. $object = env('OSS_DIRECTORY') . '/' . $prefix . '/' . $filename;
  482. $provider = new \OSS\Credentials\StaticCredentialsProvider($accessKeyId, $accessKeySecret);
  483. try{
  484. $configs = [
  485. "provider" => $provider,
  486. "endpoint" => $endpoint,
  487. "signatureVersion" => 'v4',
  488. "region"=> "cn-hangzhou"
  489. ];
  490. $ossClient = new OssClient($configs);
  491. $uploadRes = $ossClient->putObject($bucket, $object, $stream);
  492. } catch (OssException $e) {
  493. dLog('exception')->info('saveImageToOss', [$e->getMessage()]);
  494. return '';
  495. }
  496. // 替换域名
  497. if (!isset($uploadRes['oss-request-url'])) return '';
  498. $url = str_ireplace('zw-ai.oss-cn-hangzhou.aliyuncs.com', 'cdn-zwai.ycsd.cn', $uploadRes['oss-request-url']);
  499. $url = urldecode($url);
  500. return str_ireplace('http://', 'https://', $url);
  501. }
  502. /**
  503. * 下载文件到本地
  504. *
  505. * @param $object
  506. * @param $localFile
  507. * @return string
  508. */
  509. function downloadFile($object, $localFile)
  510. {
  511. // 阿里云主账号
  512. $accessKeyId = env('OSS_ACCESS_ID');
  513. $accessKeySecret = env('OSS_ACCESS_KEY');
  514. $endpoint = env('OSS_END_POINT');
  515. $bucket = env('OSS_BUCKET');
  516. try {
  517. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  518. $ossClient->getObject($bucket, $object, [
  519. OssClient::OSS_FILE_DOWNLOAD => $localFile
  520. ]);
  521. } catch (OssException $e) {
  522. printf($e->getMessage());
  523. return '';
  524. }
  525. }
  526. /**
  527. * 上传封面
  528. *
  529. * @param $file
  530. * @return string
  531. * @throws Exception
  532. */
  533. function uploadCoverFile($file)
  534. {
  535. // 阿里云主账号
  536. $accessKeyId = env('OSS_ACCESS_ID');
  537. $accessKeySecret = env('OSS_ACCESS_KEY');
  538. $endpoint = env('OSS_END_POINT');
  539. $bucket = env('OSS_BUCKET');
  540. // 设置文件名称。
  541. $object = 'books/cover/' . randStr(10) . '.' . $file->getClientOriginalExtension();
  542. try {
  543. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  544. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path());
  545. } catch (OssException $e) {
  546. printf($e->getMessage());
  547. return '';
  548. }
  549. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  550. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  551. }
  552. function uploadAgreementFile($file)
  553. {
  554. // 阿里云主账号
  555. $accessKeyId = env('OSS_ACCESS_ID');
  556. $accessKeySecret = env('OSS_ACCESS_KEY');
  557. $endpoint = env('OSS_END_POINT');
  558. $bucket = env('OSS_BUCKET');
  559. $file_name = $file->getClientOriginalName();
  560. $file_name = str_replace('.' . $file->getClientOriginalExtension(), '', $file_name);
  561. // 设置文件名称。
  562. $object = 'books/contract/' . $file_name . '-' . date('YmdHi') . '.' . $file->getClientOriginalExtension();
  563. try {
  564. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  565. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file);
  566. } catch (OssException $e) {
  567. printf($e->getMessage());
  568. return '';
  569. }
  570. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  571. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . urldecode(getProp($urlArr, 'path')) : '';
  572. }
  573. /**
  574. * 上传wap推荐图片
  575. *
  576. * @param $file
  577. * @param $filename
  578. * @return string
  579. * @throws Exception
  580. */
  581. function uploadWapRecommendPic($file, $filename)
  582. {
  583. // 阿里云主账号
  584. $accessKeyId = env('OSS_ACCESS_ID');
  585. $accessKeySecret = env('OSS_ACCESS_KEY');
  586. $endpoint = env('OSS_END_POINT');
  587. $bucket = env('OSS_BUCKET_YCSD');
  588. // 设置文件名称。
  589. $object = 'ycsd_web_3nd/images/homebanners/' . $filename . '.' . $file->getClientOriginalExtension();
  590. try {
  591. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  592. $options = array(
  593. OssClient::OSS_HEADERS => array(
  594. 'Content-Type' => 'image/jpeg',
  595. 'Content-Disposition' => 'inline'
  596. ),
  597. );
  598. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path(), $options);
  599. } catch (OssException $e) {
  600. printf($e->getMessage());
  601. return '';
  602. }
  603. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  604. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  605. }
  606. /**
  607. * @param $path
  608. * @return Generator
  609. */
  610. function readFileContent($path)
  611. {
  612. if ($handle = fopen($path, 'r')) {
  613. while (!feof($handle)) {
  614. yield trim(fgets($handle));
  615. }
  616. fclose($handle);
  617. }
  618. }
  619. function exportFileCsv(array $headers, array $data, string $filename)
  620. {
  621. header("Content-type:application/vnd.ms-excel");
  622. header("Content-Disposition:attachment;filename=" . $filename . ".csv");
  623. $headers = collect($headers)->map(function ($item) {
  624. return "\"" . mb_convert_encoding($item, "GBK", "UTF-8") . "\"";
  625. })->all();
  626. echo implode(",", $headers);
  627. echo "\r\n";
  628. foreach ($data as $item) {
  629. $rows = collect($item)->map(function ($row) {
  630. return "\"" . mb_convert_encoding(is_numeric($row) && strlen($row) > 12 ? "'" . $row : $row, "GBK", "UTF-8") . "\"";
  631. })->all();
  632. echo implode(",", $rows);
  633. echo "\r\n";
  634. }
  635. exit();
  636. }
  637. //function exportFileCsv(array $header, array $data, string $filename) {
  638. // header('Content-Encoding: UTF-8');
  639. // header("Content-type:application/vnd.ms-excel;charset=UTF-8");
  640. // header('Content-Disposition: attachment;filename="' . $filename . '.csv"');
  641. //
  642. // //打开php标准输出流
  643. // $fp = fopen('php://output', 'a');
  644. //
  645. // //添加BOM头,以UTF8编码导出CSV文件,如果文件头未添加BOM头,打开会出现乱码。
  646. // fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
  647. // //添加导出标题
  648. // fputcsv($fp, $header);
  649. //
  650. // foreach ($data as $k => $item) {
  651. // fputcsv($fp, $item);
  652. // if ($k % 5000 == 0) {
  653. // //每1万条数据就刷新缓冲区
  654. // ob_flush();
  655. // flush();
  656. // }
  657. // }
  658. // exit();
  659. //}
  660. //function exportFileCsv(array $header, array $data, string $filename) {
  661. //
  662. // header('Content-Type: application/vnd.ms-excel');
  663. // header('Content-Disposition: attachment;filename="'.$filename.'.csv"');
  664. // header('Cache-Control: max-age=0');
  665. //
  666. // //打开PHP文件句柄,php://output 表示直接输出到浏览器
  667. // $fp = fopen('php://output', 'a');
  668. //
  669. // //输出Excel列名信息
  670. // foreach ($header as $key => $value) {
  671. // //CSV的Excel支持GBK编码,一定要转换,否则乱码
  672. // $header[$key] = iconv('utf-8', 'gbk', $value);
  673. // }
  674. //
  675. // //将数据通过fputcsv写到文件句柄
  676. // fputcsv($fp, $header);
  677. //
  678. // //计数器
  679. // $num = 0;
  680. //
  681. // //每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
  682. // $limit = 10000;
  683. //
  684. // //逐行取出数据,不浪费内存
  685. // $count = count($data);
  686. // for ($i = 0; $i < $count; $i++) {
  687. //
  688. // $num++;
  689. //
  690. // //刷新一下输出buffer,防止由于数据过多造成问题
  691. // if ($limit == $num) {
  692. // ob_flush();
  693. // flush();
  694. // $num = 0;
  695. // }
  696. //
  697. // $row = $data[$i];
  698. // foreach ($row as $key => $value) {
  699. // $row[$key] = iconv('utf-8', 'gbk', $value);
  700. // }
  701. //
  702. // fputcsv($fp, $row);
  703. // }
  704. // exit();
  705. //}
  706. // 获取除空格外的字数
  707. function getSize(string $content)
  708. {
  709. $content = preg_replace('/\s+/', '', $content);
  710. return mb_strlen($content, 'utf-8');
  711. }
  712. // 获取word字符数(不计空格)
  713. function getChargeSize(string $content)
  714. {
  715. //判断是否存在替换字符
  716. $is_replace_count = substr_count($content, "龘");
  717. try {
  718. //先将回车换行符做特殊处理
  719. $str = preg_replace('/(\r\n+|\s+| +)/', "龘", $content);
  720. //处理英文字符数字,连续字母、数字、英文符号视为一个单词
  721. $str = preg_replace('/[a-z_A-Z0-9-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",\'<>~`\?:;|]/', "m", $str);
  722. //合并字符m,连续字母、数字、英文符号视为一个单词
  723. $str = preg_replace('/m+/', "*", $str);
  724. //去掉回车换行符
  725. $str = preg_replace('/龘+/', "", $str);
  726. //返回字数
  727. return mb_strlen($str) + $is_replace_count;
  728. } catch (\Exception $e) {
  729. return 0;
  730. }
  731. }
  732. // 将阿拉伯数字转换成中文
  733. function chineseNum($figure, $capital = false, $mode = true)
  734. {
  735. if ($figure == '0') return '零';
  736. $numberChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
  737. $unitChar = ['', '十', '百', '千', '', '万', '亿', '兆', '京', '垓', '秭', '穣', '沟', '涧', '正', '载', '极', '恒河沙', '阿僧祇', '那由他', '不可思议', '无量大数'];
  738. if ($capital !== false) {
  739. $numberChar = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  740. $unitChar = ['', '拾', '佰', '仟', '', '万', '亿', '兆', '京', '垓', '秭', '穣', '沟', '涧', '正', '载', '极', '恒河沙', '阿僧祇', '那由他', '不可思议', '无量大数'];
  741. }
  742. $dec = "点";
  743. $target = '';
  744. $matches = [];
  745. if ($mode) {
  746. preg_match("/^0*(\d*)\.?(\d*)/", $figure, $matches);
  747. } else {
  748. preg_match("/(\d*)\.?(\d*)/", $figure, $matches);
  749. }
  750. list(, $number, $point) = $matches;
  751. if ($point) {
  752. $target = $dec . chineseNum($point, $capital, false);
  753. }
  754. if (!$number) {
  755. return $target;
  756. }
  757. $str = strrev($number);
  758. for ($i = 0; $i < strlen($str); $i++) {
  759. $out[$i] = $numberChar[$str[$i]];
  760. if ($mode === false) {
  761. continue;
  762. }
  763. $out[$i] .= $str[$i] != '0' ? $unitChar[$i % 4] : '';
  764. if ($i > 0 && $str[$i] + $str[$i - 1] == 0) {
  765. $out[$i] = '';
  766. }
  767. if ($i % 4 == 0) {
  768. $temp = substr($str, $i, 4);
  769. $out[$i] = str_replace($numberChar[0], '', $out[$i]);
  770. if (strrev($temp) > 0) {
  771. $out[$i] .= $unitChar[4 + floor($i / 4)];
  772. } else {
  773. $out[$i] .= $numberChar[0];
  774. }
  775. }
  776. }
  777. $result = join('', array_reverse($out)) . $target;
  778. return mb_substr($result, 0, 2) == '一十' ? mb_substr($result, 1) : $result;
  779. }
  780. function addPrefix($str)
  781. {
  782. if (!$str) return '';
  783. if (mb_substr($str, 0, 4) == 'http') return $str;
  784. if (mb_substr($str, 0, 5) == 'https') return $str;
  785. if (mb_substr($str, 0, 7) == '/books/') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com' . $str;
  786. if (mb_substr($str, 0, 6) == '/card/') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com' . $str;
  787. if (mb_substr($str, 0, 15) == 'uploader/idcard') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com/' . $str;
  788. if (mb_substr($str, 0, 6) == '/cover') return 'https://cdn-newyc.ycsd.cn/ycsd_cover/covermiddle' . mb_substr($str, 6);
  789. if (mb_substr($str, 0, 8) == '/images/') return 'https://cdn-newyc.ycsd.cn/ycsd_cover' . $str;
  790. }
  791. /**
  792. * 章节内容排版
  793. *
  794. * @param $content
  795. * @return string
  796. */
  797. function filterContent($content)
  798. {
  799. if (!$content) return '';
  800. $content = str_replace(
  801. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  802. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...', '‘', '’', '-'],
  803. $content);
  804. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  805. // 段落首字母前加两个中文空格
  806. $string = explode(PHP_EOL, $content);
  807. foreach ($string as $line => $text) {
  808. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' '], '', $string[$line]);
  809. if (!$string[$line]) {
  810. unset($string[$line]);
  811. } else {
  812. $string[$line] = $string[$line] . PHP_EOL;
  813. // if (mb_substr($string[$line], 0, 1) == ' ') {
  814. // $string[$line] = str_replace(' ', '', $string[$line]); // 去除多个空格
  815. // $string[$line] = '  ' . $string[$line].PHP_EOL;
  816. // }
  817. // if (mb_substr($string[$line], 0, 2) != '  ') {
  818. // $string[$line] = '  ' . $string[$line].PHP_EOL;
  819. // }
  820. // if (mb_substr($string[$line], 0, 2) == '  ' && str_replace(' ', '', $string[$line])) {
  821. // $string[$line] .= PHP_EOL;
  822. // }
  823. }
  824. }
  825. $content = implode(PHP_EOL, $string);
  826. return $content;
  827. }
  828. /**
  829. * 书籍简介排版
  830. *
  831. * @param $content
  832. * @return string
  833. */
  834. function filterContent2($content)
  835. {
  836. if (!$content) return '';
  837. $content = str_replace(
  838. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  839. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...', '‘', '’', '-'],
  840. $content);
  841. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  842. // 段落首字母前加两个中文空格
  843. $string = explode(PHP_EOL, $content);
  844. $content = '';
  845. foreach ($string as $line => $text) {
  846. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' ', '<br />'], '', $string[$line]);
  847. if (!$string[$line]) {
  848. unset($string[$line]);
  849. } else {
  850. $string[$line] = '  ' . $string[$line] . '<br />';
  851. $content .= $string[$line];
  852. }
  853. }
  854. $content = trim($content, '<br />');
  855. return $content;
  856. }
  857. /**
  858. * 书籍简介排版-抖音版
  859. *
  860. * @param $content
  861. * @return string
  862. */
  863. function filterIntro($content)
  864. {
  865. if (!$content) return '';
  866. $content = str_replace(
  867. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p>', '&ldquo;', '&rdquo;', '&hellip;', '&lsquo;', '&rsquo;', '&mdash;'],
  868. [' ', ' ', ' ', ' ', ' ', '', ' ', '“', '”', '...', '‘', '’', '-'],
  869. $content);
  870. $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
  871. // 段落首字母前加两个中文空格
  872. $string = explode(PHP_EOL, $content);
  873. $content = '';
  874. foreach ($string as $line => $text) {
  875. $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' ', '<br />'], '', $string[$line]);
  876. if (!$string[$line]) {
  877. unset($string[$line]);
  878. } else {
  879. $content .= $string[$line];
  880. }
  881. }
  882. $content = trim($content, '<br />');
  883. return $content;
  884. }
  885. /**
  886. * 压缩视频文件
  887. * 压缩策略:3秒视频约1M~1.5M
  888. *
  889. * @param string $videoUrl 视频URL地址
  890. * @param string $prefix 上传文件夹前缀(如:'videos')
  891. * @return string 返回压缩后的视频URL,失败返回空字符串
  892. */
  893. function compressVideo($videoUrl, $prefix = 'videos')
  894. {
  895. if (env('APP_ENV') == 'local') return $videoUrl;
  896. try {
  897. // 创建临时目录
  898. $tempDir = storage_path('app/temp/videos');
  899. if (!is_dir($tempDir)) {
  900. mkdir($tempDir, 0775, true);
  901. // 确保目录权限正确
  902. chmod($tempDir, 0775);
  903. }
  904. // 生成唯一文件名(不包含点号)
  905. $uniqueId = uniqid('video_') . bin2hex(random_bytes(4));
  906. $videoExt = getVideoExtFromUrl($videoUrl);
  907. $inputFile = $tempDir . '/' . $uniqueId . '_input' . $videoExt;
  908. $outputFile = $tempDir . '/' . $uniqueId . '_output.mp4';
  909. // 下载视频到本地
  910. dLog('video_compress')->info('开始下载视频', ['url' => $videoUrl]);
  911. $client = new \GuzzleHttp\Client(['timeout' => 300]);
  912. $response = $client->get($videoUrl);
  913. // 使用更安全的方式写入文件
  914. $fileContent = $response->getBody()->getContents();
  915. if (file_put_contents($inputFile, $fileContent) === false) {
  916. dLog('video_compress')->error('视频文件写入失败', [
  917. 'url' => $videoUrl,
  918. 'file' => $inputFile,
  919. 'dir_writable' => is_writable($tempDir)
  920. ]);
  921. return '';
  922. }
  923. // 设置文件权限
  924. chmod($inputFile, 0664);
  925. if (!file_exists($inputFile)) {
  926. dLog('video_compress')->error('视频下载失败', ['url' => $videoUrl]);
  927. return '';
  928. }
  929. $inputFileSize = filesize($inputFile);
  930. dLog('video_compress')->info('视频下载成功', [
  931. 'url' => $videoUrl,
  932. 'size' => $inputFileSize,
  933. 'size_mb' => round($inputFileSize / 1024 / 1024, 2) . 'MB'
  934. ]);
  935. // 获取视频时长(秒)
  936. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  937. $durationCmd = "$ffprobePath -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 \"$inputFile\"";
  938. $duration = (float)trim(shell_exec($durationCmd));
  939. if ($duration <= 0) {
  940. dLog('video_compress')->error('无法获取视频时长', ['file' => $inputFile]);
  941. @unlink($inputFile);
  942. return '';
  943. }
  944. // 计算目标码率
  945. // 目标:3秒视频 = 1~1.5MB,即每秒约 0.33~0.5MB = 2730~4096 kbps
  946. // 使用中间值:3500 kbps
  947. $targetBitrate = 3500; // kbps
  948. // 根据视频时长动态调整码率,确保文件大小合理
  949. // 目标文件大小 = duration * 0.4MB/s = duration * 400KB/s
  950. $targetFileSizeKB = $duration * 400; // KB
  951. $targetBitrateCalculated = (int)(($targetFileSizeKB * 8) / $duration); // kbps
  952. // 使用计算出的码率,但不低于1500kbps,不高于5000kbps
  953. $targetBitrate = max(1500, min(5000, $targetBitrateCalculated));
  954. dLog('video_compress')->info('视频信息', [
  955. 'duration' => $duration . 's',
  956. 'target_bitrate' => $targetBitrate . 'kbps',
  957. 'estimated_size' => round($targetFileSizeKB / 1024, 2) . 'MB'
  958. ]);
  959. // 使用FFmpeg压缩视频
  960. // -c:v libx264: 使用H.264编码器
  961. // -b:v: 视频码率
  962. // -c:a aac: 音频编码器
  963. // -b:a 128k: 音频码率
  964. // -movflags +faststart: 优化网络播放
  965. // -preset medium: 编码速度与质量平衡
  966. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  967. $ffmpegCmd = "$ffmpegPath -i \"$inputFile\" -c:v libx264 -b:v {$targetBitrate}k -c:a aac -b:a 128k -movflags +faststart -preset medium -y \"$outputFile\" 2>&1";
  968. dLog('video_compress')->info('开始压缩视频', ['command' => $ffmpegCmd]);
  969. $output = shell_exec($ffmpegCmd);
  970. if (!file_exists($outputFile)) {
  971. dLog('video_compress')->error('视频压缩失败', [
  972. 'input' => $inputFile,
  973. 'output' => $output
  974. ]);
  975. @unlink($inputFile);
  976. return '';
  977. }
  978. // 设置输出文件权限
  979. chmod($outputFile, 0664);
  980. $outputFileSize = filesize($outputFile);
  981. $compressionRatio = round((1 - $outputFileSize / $inputFileSize) * 100, 2);
  982. dLog('video_compress')->info('视频压缩成功', [
  983. 'input_size' => round($inputFileSize / 1024 / 1024, 2) . 'MB',
  984. 'output_size' => round($outputFileSize / 1024 / 1024, 2) . 'MB',
  985. 'compression_ratio' => $compressionRatio . '%',
  986. 'duration' => $duration . 's',
  987. 'size_per_second' => round($outputFileSize / $duration / 1024 / 1024, 2) . 'MB/s'
  988. ]);
  989. // 上传压缩后的视频到云存储
  990. $stream = fopen($outputFile, 'r');
  991. if (!$stream) {
  992. dLog('video_compress')->error('无法打开压缩后的视频文件', ['file' => $outputFile]);
  993. @unlink($inputFile);
  994. @unlink($outputFile);
  995. return '';
  996. }
  997. $filename = $uniqueId . '.mp4';
  998. // 根据环境变量选择上传方式
  999. $uploadMethod = env('VIDEO_UPLOAD_METHOD', 'tos'); // 默认使用火山云
  1000. if ($uploadMethod === 'oss') {
  1001. $compressedUrl = uploadStreamToOss($prefix, $stream, $filename);
  1002. } else {
  1003. $compressedUrl = uploadStreamByTos($prefix, $stream, $filename);
  1004. }
  1005. // 安全关闭文件流
  1006. if (is_resource($stream)) {
  1007. fclose($stream);
  1008. }
  1009. // 清理临时文件
  1010. @unlink($inputFile);
  1011. @unlink($outputFile);
  1012. if (!$compressedUrl) {
  1013. dLog('video_compress')->error('压缩视频上传失败');
  1014. return '';
  1015. }
  1016. dLog('video_compress')->info('压缩视频上传成功', [
  1017. 'original_url' => $videoUrl,
  1018. 'compressed_url' => $compressedUrl
  1019. ]);
  1020. return $compressedUrl;
  1021. } catch (\Exception $e) {
  1022. dLog('video_compress')->error('视频压缩异常', [
  1023. 'url' => $videoUrl,
  1024. 'error' => $e->getMessage(),
  1025. 'trace' => $e->getTraceAsString()
  1026. ]);
  1027. // 安全关闭文件流(如果存在)
  1028. if (isset($stream) && is_resource($stream)) {
  1029. @fclose($stream);
  1030. }
  1031. // 清理可能存在的临时文件
  1032. if (isset($inputFile) && file_exists($inputFile)) {
  1033. @unlink($inputFile);
  1034. }
  1035. if (isset($outputFile) && file_exists($outputFile)) {
  1036. @unlink($outputFile);
  1037. }
  1038. return ''; // 出错时返回空字符串
  1039. }
  1040. }
  1041. /**
  1042. * 获取视频第一帧并上传
  1043. * 根据远程视频URL获取第一帧图片并保存到TOS或OSS(默认TOS)
  1044. *
  1045. * @param string $videoUrl 视频URL地址
  1046. * @param string $prefix 上传文件夹前缀(如:'videos')
  1047. * @param string $uploadMethod 上传方式:'tos'(默认) 或 'oss'
  1048. * @return string 返回图片URL地址,失败返回空字符串
  1049. */
  1050. /**
  1051. * 视频生成提示词追加内容约束:避免生成字幕 / 水印 / Logo
  1052. *
  1053. * 三项约束**独立判断、独立追加**(不做整体判断):
  1054. * - 缺少“字幕” → 追加「避免生成任何字幕」;
  1055. * - 缺少“水印” → 追加「不要生成水印」;
  1056. * - 缺少“logo/Logo” → 追加「不要生成Logo」。
  1057. * 因此“有字幕、没有水印和 logo”时只会补后两条;函数幂等(追加的内容本身含上述关键词,
  1058. * 再次调用不会重复追加)。
  1059. *
  1060. * @param string $prompt
  1061. * @return string
  1062. */
  1063. function appendVideoNoCaptionPrompt($prompt)
  1064. {
  1065. $prompt = (string)$prompt;
  1066. if (trim($prompt) === '') {
  1067. return $prompt;
  1068. }
  1069. $missing = [];
  1070. if (!preg_match('/字幕/u', $prompt)) {
  1071. $missing[] = '避免生成任何字幕';
  1072. }
  1073. if (!preg_match('/水印/u', $prompt)) {
  1074. $missing[] = '不要生成水印';
  1075. }
  1076. if (!preg_match('/logo/iu', $prompt)) {
  1077. $missing[] = '不要生成Logo';
  1078. }
  1079. if (empty($missing)) {
  1080. return $prompt;
  1081. }
  1082. return rtrim($prompt) . "\n" . implode('、', $missing);
  1083. }
  1084. function getVideoFirstFrame($videoUrl, $prefix = 'videos', $uploadMethod = 'tos', $filename = '')
  1085. {
  1086. if (env('APP_ENV') == 'local') return '';
  1087. try {
  1088. // 创建临时目录
  1089. $tempDir = storage_path('app/temp/video_frames');
  1090. if (!is_dir($tempDir)) {
  1091. mkdir($tempDir, 0775, true);
  1092. chmod($tempDir, 0775);
  1093. }
  1094. // 生成唯一文件名
  1095. $uniqueId = uniqid('frame_') . bin2hex(random_bytes(4));
  1096. $videoExt = getVideoExtFromUrl($videoUrl);
  1097. $inputFile = $tempDir . '/' . $uniqueId . '_video' . $videoExt;
  1098. $outputFile = $tempDir . '/' . $uniqueId . '_frame.jpg';
  1099. // 下载视频到本地
  1100. dLog('video_frame')->info('开始下载视频', ['url' => $videoUrl]);
  1101. $client = new \GuzzleHttp\Client(['timeout' => 300]);
  1102. $response = $client->get($videoUrl);
  1103. $fileContent = $response->getBody()->getContents();
  1104. if (file_put_contents($inputFile, $fileContent) === false) {
  1105. dLog('video_frame')->error('视频文件写入失败', [
  1106. 'url' => $videoUrl,
  1107. 'file' => $inputFile
  1108. ]);
  1109. return '';
  1110. }
  1111. chmod($inputFile, 0664);
  1112. if (!file_exists($inputFile)) {
  1113. dLog('video_frame')->error('视频下载失败', ['url' => $videoUrl]);
  1114. return '';
  1115. }
  1116. dLog('video_frame')->info('视频下载成功', [
  1117. 'url' => $videoUrl,
  1118. 'size_mb' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB'
  1119. ]);
  1120. // 使用FFmpeg提取第一帧
  1121. // -i: 输入文件
  1122. // -ss 00:00:00: 从视频开始位置(第0秒)
  1123. // -vframes 1: 只提取1帧
  1124. // -q:v 2: 图片质量(1-31,数字越小质量越高)
  1125. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  1126. $ffmpegCmd = "$ffmpegPath -i \"$inputFile\" -ss 00:00:00 -vframes 1 -q:v 2 -y \"$outputFile\" 2>&1";
  1127. dLog('video_frame')->info('开始提取第一帧', ['command' => $ffmpegCmd]);
  1128. $output = shell_exec($ffmpegCmd);
  1129. if (!file_exists($outputFile)) {
  1130. dLog('video_frame')->error('提取第一帧失败', [
  1131. 'input' => $inputFile,
  1132. 'output' => $output
  1133. ]);
  1134. @unlink($inputFile);
  1135. return '';
  1136. }
  1137. chmod($outputFile, 0664);
  1138. dLog('video_frame')->info('第一帧提取成功', [
  1139. 'size' => round(filesize($outputFile) / 1024, 2) . 'KB'
  1140. ]);
  1141. // 上传图片到云存储
  1142. $stream = fopen($outputFile, 'r');
  1143. if (!$stream) {
  1144. dLog('video_frame')->error('无法打开图片文件', ['file' => $outputFile]);
  1145. @unlink($inputFile);
  1146. @unlink($outputFile);
  1147. return '';
  1148. }
  1149. // 支持指定固定文件名(例如 act_{actId}.jpg):同名覆盖上传,避免每次切换都新增 OSS 文件
  1150. $filename = $filename !== '' ? $filename : ($uniqueId . '.jpg');
  1151. // 根据参数选择上传方式,默认使用TOS
  1152. if ($uploadMethod === 'oss') {
  1153. $frameUrl = uploadStreamToOss($prefix, $stream, $filename);
  1154. } else {
  1155. $frameUrl = uploadStreamByTos($prefix, $stream, $filename);
  1156. }
  1157. // 安全关闭文件流
  1158. if (is_resource($stream)) {
  1159. fclose($stream);
  1160. }
  1161. // 清理临时文件
  1162. @unlink($inputFile);
  1163. @unlink($outputFile);
  1164. if (!$frameUrl) {
  1165. dLog('video_frame')->error('图片上传失败');
  1166. return '';
  1167. }
  1168. dLog('video_frame')->info('图片上传成功', [
  1169. 'video_url' => $videoUrl,
  1170. 'frame_url' => $frameUrl
  1171. ]);
  1172. return $frameUrl;
  1173. } catch (\Exception $e) {
  1174. dLog('video_frame')->error('提取视频第一帧异常', [
  1175. 'url' => $videoUrl,
  1176. 'error' => $e->getMessage(),
  1177. 'trace' => $e->getTraceAsString()
  1178. ]);
  1179. // 安全关闭文件流(如果存在)
  1180. if (isset($stream) && is_resource($stream)) {
  1181. @fclose($stream);
  1182. }
  1183. // 清理可能存在的临时文件
  1184. if (isset($inputFile) && file_exists($inputFile)) {
  1185. @unlink($inputFile);
  1186. }
  1187. if (isset($outputFile) && file_exists($outputFile)) {
  1188. @unlink($outputFile);
  1189. }
  1190. return '';
  1191. }
  1192. }
  1193. function sensitiveStr($list, $string)
  1194. {
  1195. $count = 0; //违规词的个数
  1196. $sensitiveWord = ''; //违规词
  1197. $stringAfter = $string; //替换后的内容
  1198. $total = count($list);
  1199. $size = 500;
  1200. $last = ceil($total / $size);
  1201. $patternList = [];
  1202. for ($page = 1; $page <= $last; $page++) {
  1203. $arr = array_slice($list, $size * ($page - 1), $size);
  1204. $filter = [];
  1205. foreach ($arr as $v) {
  1206. if (preg_match('/[^a-zA-Z0-9\|\p{Han}\·]/u', $v)) continue;
  1207. $filter[] = $v;
  1208. // $a = preg_replace('/[^a-zA-Z0-9\|\p{Han}]/u', '', $v);
  1209. // if ($a) $filter[] = $a;
  1210. }
  1211. $pattern = "/" . implode("|", $filter) . "/i"; //定义正则表达式
  1212. if (preg_match_all($pattern, $string, $matches)) { //匹配到了结果
  1213. $patternList = array_merge($patternList, $matches[0]); //匹配到的数组
  1214. }
  1215. }
  1216. $sensitiveWord = '';
  1217. if ($patternList) {
  1218. $count = count($patternList);
  1219. // $sensitiveWord = implode(',', $patternList); //敏感词数组转字符串
  1220. $replaceArray = array_combine($patternList, array_fill(0, count($patternList), '*')); //把匹配到的数组进行合并,替换使用
  1221. $stringAfter = strtr($string, $replaceArray); //结果替换
  1222. // 将敏感词合并
  1223. $return_pattern = [];
  1224. foreach ($patternList as $v) {
  1225. if (!isset($return_pattern[$v])) {
  1226. $return_pattern[$v] = [
  1227. 'word' => $v,
  1228. 'count' => 1,
  1229. ];
  1230. } else {
  1231. $return_pattern[$v]['count'] += 1;
  1232. }
  1233. }
  1234. foreach ($return_pattern as $v) {
  1235. $sensitiveWord .= $v['word'] . ',';
  1236. }
  1237. }
  1238. return [
  1239. 'count' => $count,
  1240. 'sensitive_words' => trim($sensitiveWord, ','),
  1241. 'content' => $stringAfter
  1242. ];
  1243. }
  1244. /**
  1245. * 转换时间格式
  1246. *
  1247. * @param $date
  1248. * @param string $format
  1249. * @return false|string
  1250. */
  1251. function transDate($date, $format = 'Y-m-d H:i:s')
  1252. {
  1253. return strtotime($date) > 0 ? date($format, strtotime($date)) : '';
  1254. }
  1255. /**
  1256. * 根据网段获取计算所有IP
  1257. *
  1258. * @param string $segment 网段 '139.217.0.1/24'
  1259. * @return array [网络地址:139.217.0.1 广播地址:139.217.0.255 IP列表: ['139.217.0.2','139.217.0.3'……'139.217.0.254']]
  1260. */
  1261. function getIpBySegment($segment)
  1262. {
  1263. $segmentInfo = explode("/", $segment);
  1264. $beginIpArray = explode(".", $segmentInfo[0]);
  1265. $mask = intval($segmentInfo['1']);
  1266. $endIp = array();
  1267. foreach ($beginIpArray as $ipKey => $item) {
  1268. $beginFlag = 8 * ($ipKey); //0 8 16 24
  1269. $endFlag = 8 * ($ipKey + 1);//8 16 24 32
  1270. $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
  1271. $endIp[] = $mask >= $endFlag ? $item : ($mask > $beginFlag ? bindec(str_pad(substr($decbinItem, 0, $mask - $beginFlag), 8, "1", STR_PAD_RIGHT)) : ($ipKey <= 2 ? pow(2, 8) - 1 : pow(2, 8) - 1));
  1272. }
  1273. $ipArray = array();
  1274. for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0]++) {
  1275. for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1]++) {
  1276. for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2]++) {
  1277. for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3]++) {
  1278. $ipArray[] = implode(".", $beginIp);
  1279. }
  1280. }
  1281. }
  1282. }
  1283. $network_ip_addr = $beginIpArray[0] . '.' . $beginIpArray[1] . '.' . $beginIpArray[2] . '.' . '0'; // 网络地址
  1284. $broadcast_ip_addr = end($ipArray); // 广播地址
  1285. if ($ipArray[0] == $network_ip_addr) { // 如果是网络地址则删掉
  1286. unset($ipArray[0]);
  1287. }
  1288. $last = count($ipArray);
  1289. unset($ipArray[$last]);
  1290. return [$network_ip_addr, $broadcast_ip_addr, $ipArray];
  1291. }
  1292. /**
  1293. * 在指定网段中分配子网段
  1294. *
  1295. * @param string $segment 指定网段
  1296. * @param int $ipNum 需要的IP数
  1297. * @param array $usedIpArray 不可用(已经使用)的IP,默认为空数组
  1298. * @return bool|string 成功则返回分配的网段
  1299. */
  1300. function allocateSegment($segment, $ipNum, $usedIpArray = [])
  1301. {
  1302. $usedIpArray = empty($usedIpArray) ? [] : array_flip($usedIpArray);
  1303. //计算需要多少个IP
  1304. $i = 0;
  1305. $ipCount = pow(2, $i);
  1306. while ($ipCount < $ipNum) {
  1307. $i++;
  1308. $ipCount = pow(2, $i);
  1309. }
  1310. $newMask = 32 - $i;
  1311. //大网段的开始和结束IP
  1312. $segmentInfo = explode("/", $segment); //['139.217.0.1',24]
  1313. $beginIpArray = explode(".", $segmentInfo[0]);//[139,217,0,1]
  1314. $mask = intval($segmentInfo['1']); //24
  1315. if ($newMask < $mask) {
  1316. return false;
  1317. }
  1318. $endIp = array();
  1319. $step = [];
  1320. foreach ($beginIpArray as $ipKey => $item) {
  1321. $beginFlag = 8 * ($ipKey); //0 8 16 24
  1322. $endFlag = 8 * ($ipKey + 1);//8 16 24 32
  1323. $step[$ipKey] = $newMask > $endFlag ? 1 : ($endFlag - $newMask < 8 ? pow(2, $endFlag - $newMask) : pow(2, 8));
  1324. $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
  1325. $endIp[] = $mask >= $endFlag ? $item : ($mask > $beginFlag ? bindec(str_pad(substr($decbinItem, 0, $mask - $beginFlag), 8, "1", STR_PAD_RIGHT)) : ($ipKey <= 2 ? pow(2, 8) - 1 : pow(2, 8) - 1));
  1326. }
  1327. //遍历生成网段
  1328. for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0] += $step[0]) {
  1329. for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1] += $step[1]) {
  1330. for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2] += $step[2]) {
  1331. for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3] += $step[3]) {
  1332. $newSegment = implode('.', $beginIp) . '/' . $newMask;
  1333. //获取该网段所有的IP
  1334. $ipArray = getIpBySegment($newSegment);
  1335. $canUse = true;
  1336. //判断该网段是否可用
  1337. if (!empty($usedIpArray)) {
  1338. foreach ($ipArray as $ip) {
  1339. if (isset($usedIpArray[$ip])) {
  1340. $canUse = false;
  1341. break;
  1342. }
  1343. }
  1344. }
  1345. if ($canUse) {
  1346. return $newSegment;
  1347. }
  1348. }
  1349. }
  1350. }
  1351. }
  1352. return false;
  1353. }
  1354. function remove_xss($val)
  1355. {
  1356. // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
  1357. // this prevents some character re-spacing such as <java\0script>
  1358. // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
  1359. $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
  1360. // straight replacements, the user should never need these since they're normal characters
  1361. // this prevents like <IMG SRC=@avascript:alert('XSS')>
  1362. $search = 'abcdefghijklmnopqrstuvwxyz';
  1363. $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  1364. $search .= '1234567890!@#$%^&*()';
  1365. $search .= '~`";:?+/={}[]-_|\'\\';
  1366. for ($i = 0; $i < strlen($search); $i++) {
  1367. // ;? matches the ;, which is optional
  1368. // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
  1369. // @ @ search for the hex values
  1370. $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
  1371. // @ @ 0{0,7} matches '0' zero to seven times
  1372. $val = preg_replace('/(�{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
  1373. }
  1374. // now the only remaining whitespace attacks are \t, \n, and \r
  1375. $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
  1376. $ra2 = array(
  1377. 'onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'
  1378. );
  1379. $ra = array_merge($ra1, $ra2);
  1380. $found = true; // keep replacing as long as the previous round replaced something
  1381. while ($found == true) {
  1382. $val_before = $val;
  1383. for ($i = 0; $i < sizeof($ra); $i++) {
  1384. $pattern = '/';
  1385. for ($j = 0; $j < strlen($ra[$i]); $j++) {
  1386. if ($j > 0) {
  1387. $pattern .= '(';
  1388. $pattern .= '(&#[xX]0{0,8}([9ab]);)';
  1389. $pattern .= '|';
  1390. $pattern .= '|(�{0,8}([9|10|13]);)';
  1391. $pattern .= ')*';
  1392. }
  1393. $pattern .= $ra[$i][$j];
  1394. }
  1395. $pattern .= '/i';
  1396. $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
  1397. $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
  1398. if ($val_before == $val) {
  1399. // no replacements were made, so exit the loop
  1400. $found = false;
  1401. }
  1402. }
  1403. }
  1404. return $val;
  1405. }
  1406. /**
  1407. * 计算作者积分等级
  1408. *
  1409. * @param $score
  1410. */
  1411. function calcAuthorLevel($score): int
  1412. {
  1413. switch (true) {
  1414. case $score <= 0:
  1415. $level = 0;
  1416. break;
  1417. case $score <= 5000:
  1418. $level = 1;
  1419. break;
  1420. case $score <= 50000:
  1421. $level = 2;
  1422. break;
  1423. case $score <= 100000:
  1424. $level = 3;
  1425. break;
  1426. case $score <= 300000:
  1427. $level = 4;
  1428. break;
  1429. case $score <= 800000:
  1430. $level = 5;
  1431. break;
  1432. case $score <= 1500000:
  1433. $level = 6;
  1434. break;
  1435. case $score <= 2500000:
  1436. $level = 7;
  1437. break;
  1438. case $score <= 5000000:
  1439. $level = 8;
  1440. break;
  1441. case $score <= 10000000:
  1442. $level = 9;
  1443. break;
  1444. default:
  1445. $level = 10;
  1446. break;
  1447. }
  1448. return $level;
  1449. }
  1450. /**
  1451. * 运营数据(上传附件)
  1452. *
  1453. * @param $file
  1454. * @return string
  1455. * @throws Exception
  1456. */
  1457. function uploadEnclosureFile($file)
  1458. {
  1459. // 阿里云主账号
  1460. $accessKeyId = env('OSS_ACCESS_ID');
  1461. $accessKeySecret = env('OSS_ACCESS_KEY');
  1462. $endpoint = env('OSS_END_POINT');
  1463. $bucket = env('OSS_BUCKET');
  1464. // 设置文件名称。
  1465. $object = 'books/enclosure/' . randStr(10) . '--' . $file->getClientOriginalName();
  1466. try {
  1467. $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
  1468. $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path());
  1469. } catch (OssException $e) {
  1470. printf($e->getMessage());
  1471. return '';
  1472. }
  1473. $urlArr = parse_url($ossImgBackData['oss-request-url']);
  1474. return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
  1475. }
  1476. // 获取当前域名是http还是https
  1477. function getHttpType()
  1478. {
  1479. return ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
  1480. }
  1481. // 根据id生成唯一邀请码
  1482. function enCodeId($user_id)
  1483. {
  1484. $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
  1485. $num = strlen($key);
  1486. $code = ''; // 邀请码
  1487. while ($user_id > 0) { // 转进制
  1488. $mod = $user_id % $num; // 求模
  1489. $user_id = ($user_id - $mod) / $num;
  1490. $code = $key[$mod] . $code;
  1491. }
  1492. $code = str_pad($code, 6, 'A', STR_PAD_LEFT); // 不足用0补充
  1493. return $code;
  1494. }
  1495. // 根据邀请码解密为id
  1496. function deCodeId($code)
  1497. {
  1498. $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
  1499. $num = strlen($key);
  1500. if (strrpos($code, '0') !== false) $code = substr($code, strrpos($code, '0') + 1);
  1501. $len = strlen($code);
  1502. $code = strrev($code);
  1503. $user_id = 0;
  1504. for ($i = 0; $i < $len; $i++) {
  1505. $user_id += strpos($key, $code[$i]) * pow($num, $i);
  1506. }
  1507. return $user_id;
  1508. }
  1509. /**
  1510. * 将二维数组按其中的某个数组排序(此方法适用于将数据库数据按数组取出后自动按ID排序的情况 ps:即未按该数组排序)
  1511. *
  1512. * @param array $array 二维数组
  1513. * @param array $sort 排序数组
  1514. * @param string $field 排序字段(二维数组和排序数组相同的字段)
  1515. * @return array
  1516. */
  1517. function sortByArray(array $array, array $sort, string $field): array
  1518. {
  1519. $data = [];
  1520. if (is_array($array) && is_array($sort)) {
  1521. foreach ($sort as $v) {
  1522. foreach ($array as $key => $val) {
  1523. if ($v == $val[$field]) {
  1524. array_push($data, $array[$key]);
  1525. }
  1526. }
  1527. }
  1528. }
  1529. return $data;
  1530. }
  1531. /**
  1532. * 将二维数组按其中的字段排序(正序或倒序)
  1533. *
  1534. * @param array $array 二维数组
  1535. * @param string $field 排序字段
  1536. * @param mixed $type 排序方式(3倒序,4正序)
  1537. * @return array|mixed
  1538. */
  1539. function sortByField(array $array, string $field, $type): array
  1540. {
  1541. if (is_array($array)) {
  1542. array_multisort(array_column($array, $field), $type, $array);
  1543. }
  1544. return $array;
  1545. }
  1546. // 生成用户邀请码
  1547. function setUserInviteCode($id)
  1548. {
  1549. return \Vinkla\Hashids\Facades\Hashids::connection('invite')->encode($id);
  1550. }
  1551. // 解密用户邀请码
  1552. function decodeUserInviteCode($code)
  1553. {
  1554. return \Vinkla\Hashids\Facades\Hashids::connection('invite')->decode($code);
  1555. }
  1556. function getMillisecond()
  1557. {
  1558. list($microsecond, $time) = explode(' ', microtime());
  1559. return (float)sprintf('%.0f', (floatval($microsecond) + floatval($time)) * 1000);
  1560. }
  1561. function get_client_ip($type = 0, $adv = false)
  1562. {
  1563. $type = $type ? 1 : 0;
  1564. static $ip = null;
  1565. if (null !== $ip) {
  1566. return $ip[$type];
  1567. }
  1568. if ($adv) {
  1569. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  1570. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  1571. $pos = array_search('unknown', $arr);
  1572. if (false !== $pos) {
  1573. unset($arr[$pos]);
  1574. }
  1575. $ip = trim($arr[0]);
  1576. } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  1577. $ip = $_SERVER['HTTP_CLIENT_IP'];
  1578. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1579. $ip = $_SERVER['REMOTE_ADDR'];
  1580. }
  1581. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  1582. $ip = $_SERVER['REMOTE_ADDR'];
  1583. }
  1584. // IP地址合法验证
  1585. $long = sprintf("%u", ip2long($ip));
  1586. $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
  1587. return $ip[$type];
  1588. }
  1589. /**
  1590. * 获取真实IP
  1591. */
  1592. function _getIp()
  1593. {
  1594. if (getenv('HTTP_X_FORWARDED_FOR')) {
  1595. $ip = getenv('HTTP_X_FORWARDED_FOR');
  1596. } else if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
  1597. $ip = getenv("HTTP_CLIENT_IP");
  1598. else if (getenv("HTTP_X_FORWARD_FOR") && strcasecmp(getenv("HTTP_X_FORWARD_FOR"), "unknown"))
  1599. $ip = getenv("HTTP_X_FORWARD_FOR");
  1600. else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
  1601. $ip = getenv("REMOTE_ADDR");
  1602. else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
  1603. $ip = $_SERVER['REMOTE_ADDR'];
  1604. else
  1605. $ip = "unknown";
  1606. return ($ip);
  1607. }
  1608. /**
  1609. * 数组 转 对象
  1610. *
  1611. * @param array $arr 数组
  1612. * @return object
  1613. */
  1614. function array_to_object($arr)
  1615. {
  1616. if (gettype($arr) != 'array') {
  1617. return;
  1618. }
  1619. foreach ($arr as $k => $v) {
  1620. if (gettype($v) == 'array' || getType($v) == 'object') {
  1621. $arr[$k] = (object)array_to_object($v);
  1622. }
  1623. }
  1624. return (object)$arr;
  1625. }
  1626. /**
  1627. * 对象 转 数组
  1628. *
  1629. * @param object $obj 对象
  1630. * @return array
  1631. */
  1632. function object_to_array($obj)
  1633. {
  1634. $obj = (array)$obj;
  1635. foreach ($obj as $k => $v) {
  1636. if (gettype($v) == 'resource') {
  1637. return;
  1638. }
  1639. if (gettype($v) == 'object' || gettype($v) == 'array') {
  1640. $obj[$k] = (array)object_to_array($v);
  1641. }
  1642. }
  1643. return $obj;
  1644. }
  1645. /**
  1646. * 检查是否为手机号码
  1647. */
  1648. function _isPhone($number)
  1649. {
  1650. return preg_match("/^1[34578][0-9]{9}$/", $number);
  1651. }
  1652. /**
  1653. * 判断所传的参数是否缺少,如果缺少返回渠道的字段,正确返回0
  1654. *
  1655. * @param array $param
  1656. * @param array $must
  1657. * @return int|mixed
  1658. */
  1659. function checkParam(array $param, array $must)
  1660. {
  1661. foreach ($must as $item) {
  1662. if (array_key_exists($item, $param) && $param[$item] != '') {
  1663. } else {
  1664. return $item;
  1665. }
  1666. }
  1667. return 0;
  1668. }
  1669. /**
  1670. * 对象 转 数组
  1671. *
  1672. * @param object $obj 对象
  1673. * @return array
  1674. */
  1675. function ignoreKeyInArray($targetArray, $delete_keys = [], $changes = [])
  1676. {
  1677. $change_keys = array_keys($changes);
  1678. foreach ($targetArray as $key => $value) {
  1679. if (in_array($key, $delete_keys) && isset($targetArray[$key])) unset($targetArray[$key]);
  1680. if (in_array($key, $change_keys) && isset($targetArray[$key])) $targetArray[$key] = $changes[$key];
  1681. if (is_array($value)) ignoreKeyInArray($value, $delete_keys, $change_keys);
  1682. }
  1683. return $targetArray;
  1684. }
  1685. function itemTransform($trans, $data)
  1686. {
  1687. if ($data) {
  1688. return $trans->transform($data);
  1689. } else {
  1690. return [];
  1691. }
  1692. }
  1693. function collectionTransform($trans, $data)
  1694. {
  1695. $ret_data = [];
  1696. if ($data) {
  1697. foreach ($data as $item) {
  1698. $ret_data[] = $trans->transform($item);
  1699. }
  1700. }
  1701. return $ret_data;
  1702. }
  1703. function paginationTransform($trans, $paginator)
  1704. {
  1705. $ret = [];
  1706. $ret['list'] = [];
  1707. if ($paginator) {
  1708. foreach ($paginator as $item) {
  1709. $ret['list'][] = $trans->transform($item);
  1710. }
  1711. $ret['meta'] = [
  1712. 'total' => (int)$paginator->total(),
  1713. 'per_page' => (int)$paginator->perPage(),
  1714. 'current_page' => (int)$paginator->currentPage(),
  1715. 'last_page' => (int)$paginator->lastPage(),
  1716. 'next_page_url' => (string)$paginator->nextPageUrl(),
  1717. 'prev_page_url' => (string)$paginator->previousPageUrl()
  1718. ];
  1719. }
  1720. return $ret;
  1721. }
  1722. /**
  1723. * 加密site id
  1724. */
  1725. function encodeDistributionChannelId($id)
  1726. {
  1727. $encrypt_pool = [
  1728. ];
  1729. if (isset($encrypt_pool[$id])) {
  1730. return $encrypt_pool[$id];
  1731. }
  1732. $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
  1733. return $hashids->encode($id);
  1734. }
  1735. /**
  1736. * 解密密site id
  1737. */
  1738. function decodeDistributionChannelId($code)
  1739. {
  1740. $encrypt_pool = [
  1741. ];
  1742. if (isset($encrypt_pool[$code])) {
  1743. return $encrypt_pool[$code];
  1744. }
  1745. $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
  1746. $res = $hashids->decode($code);
  1747. if ($res && isset($res[0])) {
  1748. return $res[0];
  1749. }
  1750. return null;
  1751. }
  1752. //bid加密
  1753. function book_hash_encode($bid)
  1754. {
  1755. return Vinkla\Hashids\Facades\Hashids::encode($bid);
  1756. }
  1757. function decodeBid($encode_bid)
  1758. {
  1759. $bid = 0;
  1760. try {
  1761. $bid_arr = \Hashids::decode($encode_bid);
  1762. if (isset($bid_arr[0])) {
  1763. $bid = $bid_arr[0];
  1764. }
  1765. } catch (\Exception $e) {
  1766. return null;
  1767. }
  1768. return $bid;
  1769. }
  1770. /**
  1771. * 获取当前域名
  1772. */
  1773. function _domain()
  1774. {
  1775. return str_replace('https://', '', str_replace('http://', '', url('/')));
  1776. }
  1777. /**
  1778. * 字符串转*
  1779. *
  1780. * @param $str // 待转的字符串
  1781. * @param $start // 转*起始位置
  1782. * @param int $end // 转*结束位置
  1783. * @param string $dot // 转换的字符(必须是单字符,默认是*)
  1784. * @param string $charset // 编码方式
  1785. * @param string $end_char // 特殊字符(碰到此字符则确定end位置)
  1786. * @return string
  1787. */
  1788. function trans_pass($str, $start, $end = 0, $dot = "*", $charset = "UTF-8", $end_char = '@'): string
  1789. {
  1790. $len = mb_strlen($str, $charset);
  1791. if ($start == 0 || $start > $len) {
  1792. $start = 1;
  1793. }
  1794. if ($end != 0 && $end > $len) {
  1795. $end = $len - 2;
  1796. }
  1797. if (strstr($str, $end_char)) {
  1798. $end = $len - strrpos($str, $end_char);
  1799. }
  1800. $endStart = $len - $end;
  1801. $top = mb_substr($str, 0, $start, $charset);
  1802. $bottom = "";
  1803. if ($endStart > 0) {
  1804. $bottom = mb_substr($str, $endStart, $end, $charset);
  1805. }
  1806. $len -= mb_strlen($top, $charset);
  1807. $len -= mb_strlen($bottom, $charset);
  1808. $newStr = $top;
  1809. for ($i = 0; $i < $len; $i++) {
  1810. $newStr .= $dot;
  1811. }
  1812. $newStr .= $bottom;
  1813. return $newStr;
  1814. }
  1815. /**
  1816. * 格式化章节内容
  1817. *
  1818. * @param $content
  1819. * @return false|string
  1820. */
  1821. function formatContent($content)
  1822. {
  1823. if (!$content) return '';
  1824. $content = str_replace(
  1825. ['&nbsp;&nbsp;', '<br /><br />', '<br>', '<br />', '&nbsp;', '<p>', '</p >', '&ldquo;', '&rdquo;', '&hellip;'],
  1826. [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...'],
  1827. $content);
  1828. $content = str_replace(["&nbsp;", '&ldquo;', '&hellip;', '&rdquo;', '<p>'], '', $content);
  1829. // 段落首字母前加两个中文空格
  1830. $string = explode(PHP_EOL, $content);
  1831. foreach ($string as $line => $text) {
  1832. if (mb_substr($text, 0, 2) != '  ') $string[$line] = '  ' . $text;
  1833. }
  1834. $content = implode(PHP_EOL, $string);
  1835. $content = mb_convert_encoding($content, 'UTF-8', 'UTF-8,GBK,GB2312');
  1836. $content = iconv('UTF-8', 'UTF-8//IGNORE', $content);
  1837. return $content;
  1838. }
  1839. /**
  1840. * 筛选出有效的id集合
  1841. *
  1842. * @param array $ids
  1843. * @return array
  1844. */
  1845. function filterValidIds(array $ids): array
  1846. {
  1847. // 传参
  1848. if (empty($ids)) {
  1849. return [];
  1850. }
  1851. $result = [];
  1852. foreach ($ids as $id) {
  1853. if (in_array($id, $result) || !is_numeric($id) || (int)$id < 1) {
  1854. continue;
  1855. }
  1856. $result[] = (int)$id;
  1857. }
  1858. return $result;
  1859. }
  1860. function arrayToStr($map)
  1861. {
  1862. $isMap = isArrMap($map);
  1863. $result = "";
  1864. if ($isMap) {
  1865. $result = "map[";
  1866. }
  1867. $keyArr = array_keys($map);
  1868. if ($isMap) {
  1869. sort($keyArr);
  1870. }
  1871. $paramsArr = array();
  1872. foreach ($keyArr as $k) {
  1873. $v = $map[$k];
  1874. if ($isMap) {
  1875. if (is_array($v)) {
  1876. $paramsArr[] = sprintf("%s:%s", $k, arrayToStr($v));
  1877. } else {
  1878. $paramsArr[] = sprintf("%s:%s", $k, trim(strval($v)));
  1879. }
  1880. } else {
  1881. if (is_array($v)) {
  1882. $paramsArr[] = arrayToStr($v);
  1883. } else {
  1884. $paramsArr[] = trim(strval($v));
  1885. }
  1886. }
  1887. }
  1888. $result = sprintf("%s%s", $result, join(" ", $paramsArr));
  1889. if (!$isMap) {
  1890. $result = sprintf("[%s]", $result);
  1891. } else {
  1892. $result = sprintf("%s]", $result);
  1893. }
  1894. return $result;
  1895. }
  1896. function isArrMap($map)
  1897. {
  1898. foreach ($map as $k => $v) {
  1899. if (is_string($k)) {
  1900. return true;
  1901. }
  1902. }
  1903. return false;
  1904. }
  1905. /**
  1906. * 随机字符串
  1907. *
  1908. * @param $length
  1909. * @return string
  1910. */
  1911. function makeRandStr($length): string
  1912. {
  1913. // 密码字符集,可任意添加你需要的字符
  1914. $str = [
  1915. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
  1916. 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
  1917. 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
  1918. 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
  1919. 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
  1920. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
  1921. ];
  1922. // 在 $str 中随机取 $length 个数组元素键名
  1923. $keys = array_rand($str, $length);
  1924. $password = '';
  1925. for ($i = 0; $i < $length; $i++) {
  1926. // 将 $length 个数组元素连接成字符串
  1927. $password .= $str[$keys[$i]];
  1928. }
  1929. return $password;
  1930. }
  1931. /**
  1932. * 导出数据为excel表格
  1933. *
  1934. * @param $data 一个二维数组,结构如同从数据库查出来的数组
  1935. * @param $title excel的第一行标题,一个数组,如果为空则没有标题
  1936. * @param $filename 下载的文件名
  1937. * @examlpe10
  1938. */
  1939. function exportExcel($data = [], $title = [], $filename = 'report')
  1940. {
  1941. ob_end_clean();
  1942. ob_start();
  1943. header("Content-type:application/octet-stream");
  1944. header("Accept-Ranges:bytes");
  1945. header("Content-type:application/vnd.ms-excel");
  1946. header("Content-Disposition:attachment;filename=" . $filename . ".xls");
  1947. header("Pragma: no-cache");
  1948. header("Expires: 0");
  1949. //导出xls 开始
  1950. if (!empty($title)) {
  1951. foreach ($title as $k => $v) {
  1952. $title[$k] = iconv("UTF-8", "GB2312", $v);
  1953. }
  1954. $title = implode("\t", $title);
  1955. echo "$title\n";
  1956. }
  1957. if (!empty($data)) {
  1958. foreach ($data as $key => $val) {
  1959. foreach ($val as $ck => $cv) {
  1960. $data[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
  1961. }
  1962. $data[$key] = implode("\t", $data[$key]);
  1963. }
  1964. echo implode("\n", $data);
  1965. }
  1966. }
  1967. /**
  1968. * 导出csv文件
  1969. * @param string $name
  1970. * @param array $headers
  1971. * @param array $data
  1972. * @return void
  1973. */
  1974. function exportCsv(string $name, array $headers, array $data = [])
  1975. {
  1976. header('Content-Description: File Transfer');
  1977. header('Content-Type: application/csv');
  1978. header("Content-Disposition: attachment; filename=".$name.".csv");
  1979. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  1980. $handle = fopen('php://output', 'w');
  1981. ob_clean();
  1982. // UTF-8 BOM,避免 Excel 打开 CSV 中文乱码
  1983. fwrite($handle, "\xEF\xBB\xBF");
  1984. fputcsv($handle, $headers);
  1985. if ($data) {
  1986. foreach ($data as $row) {
  1987. fputcsv($handle, $row);
  1988. }
  1989. }
  1990. ob_flush();
  1991. fclose($handle);
  1992. die();
  1993. }
  1994. // 树状分类
  1995. function buildCategoryTree($categories, $pid = 0) {
  1996. $tree = [];
  1997. foreach ($categories as $category) {
  1998. if ($category['pid'] == $pid) {
  1999. $children = buildCategoryTree($categories, $category['category_id']);
  2000. if ($children) {
  2001. $category['children'] = $children;
  2002. }
  2003. $tree[] = $category;
  2004. }
  2005. }
  2006. return $tree;
  2007. }
  2008. // 获取文件的md5值
  2009. function getFileContentMD5($filePath){
  2010. //获取文件MD5的128位二进制数组
  2011. $md5Bytes = md5_file($filePath,true);
  2012. //计算文件的Content-MD5
  2013. $contentMD5 = base64_encode($md5Bytes);
  2014. return $contentMD5;
  2015. }
  2016. function getTextTokens($text) {
  2017. // 方法1:按空格分词(西文较准)
  2018. $words = preg_split('/\s+/', $text);
  2019. $wordCount = count($words);
  2020. // 方法2:按字符数估算(中文较准:1个汉字 ≈ 1.5-2 tokens)
  2021. $charCount = mb_strlen($text);
  2022. // 综合估算(根据语言调整权重)
  2023. $tokenCount = $wordCount + $charCount * 0.5; // 示例公式
  2024. // 更简单:直接按字符数 * 系数(中文推荐)
  2025. // $tokenCount = $charCount * 1.8; // 经验系数
  2026. return (int)ceil($tokenCount);
  2027. }
  2028. // 处理小说剧本文本
  2029. function handleScriptWords($text, $enable_emotion=1) {
  2030. $text = preg_replace('/[\r\n]+/', PHP_EOL, $text);
  2031. $text_arr = explode(PHP_EOL, $text);
  2032. $roles = [];
  2033. $words = [];
  2034. $role_gender = [];
  2035. // $sequence = 0;
  2036. foreach ($text_arr as $line) {
  2037. $line = trim($line);
  2038. if ($enable_emotion) {
  2039. $match_rule = '/^(.*?)\:(.*?)\{(.*?)\}$/';
  2040. $count = 4;
  2041. } else {
  2042. $match_rule = '/^(.*?)\:(.*?)$/';
  2043. $count = 3;
  2044. }
  2045. preg_match($match_rule, $line, $matches);
  2046. if (count($matches) == $count) {
  2047. $gender = '0';
  2048. // 角色部分拆分
  2049. preg_match('/^(.*?)\((.*?)\)$/', $matches[1], $matches2);
  2050. if (count($matches2) == 3) {
  2051. $role = $matches2[1];
  2052. $gender_arr = ['男'=>'1', '女'=>'2'];
  2053. $gender = isset($gender_arr[$matches2[2]]) ? $gender_arr[$matches2[2]] : '0';
  2054. }else {
  2055. $role = $matches[1];
  2056. }
  2057. if (!in_array($role, $roles)) {
  2058. $roles[] = $role; // 记录角色
  2059. $role_gender[$role] = $gender;
  2060. }
  2061. $words[] = [
  2062. 'role' => $role,
  2063. 'gender' => $gender,
  2064. 'text' => $matches[2],
  2065. 'emotion' => $enable_emotion ? $matches[3] : '中性',
  2066. ];
  2067. }
  2068. }
  2069. $new_words = [];
  2070. $tmp = '';
  2071. $tmp_arr = [];
  2072. $tmp_text = '';
  2073. // 将words数组按照role和emotion合并相邻的text内容,不相邻则跳过合并
  2074. foreach ($words as $word) {
  2075. if(!$tmp) $tmp = $word['role'].'-'.$word['emotion'];
  2076. if($tmp == $word['role'].'-'.$word['emotion']) {
  2077. $tmp_text .= PHP_EOL.$word['text'];
  2078. $tmp_arr = [
  2079. 'role' => $word['role'],
  2080. 'gender' => $word['gender'],
  2081. 'text' => trim($tmp_text, PHP_EOL),
  2082. 'emotion' => $word['emotion'],
  2083. ];
  2084. }else {
  2085. // $sequence++;
  2086. // $tmp_arr['sequence'] = $sequence;
  2087. $new_words[] = $tmp_arr;
  2088. $tmp = $word['role'].'-'.$word['emotion'];
  2089. $tmp_text = $word['text'];
  2090. $tmp_arr = [
  2091. 'role' => $word['role'],
  2092. 'gender' => $word['gender'],
  2093. 'text' => trim($tmp_text, PHP_EOL),
  2094. 'emotion' => $word['emotion'],
  2095. ];
  2096. }
  2097. }
  2098. if ($tmp_arr) {
  2099. // $sequence++;
  2100. // $tmp_arr['sequence'] = $sequence;
  2101. $new_words[] = $tmp_arr;
  2102. }
  2103. return [
  2104. 'roles' => $roles,
  2105. 'role_gender' => $role_gender,
  2106. 'words' => $new_words,
  2107. ];
  2108. }
  2109. function extractScriptContent($originalContent) {
  2110. if (!$originalContent) return [];
  2111. // 使用更精确的正则表达式分割内容
  2112. $parts = [];
  2113. // 提取剧本名(###剧本名:后面的内容,支持多个空格)
  2114. preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
  2115. $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
  2116. // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
  2117. preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
  2118. $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
  2119. // 提取剧本亮点(支持多个空格)
  2120. preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
  2121. $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
  2122. // 提取人物关系(支持多个空格)
  2123. preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
  2124. $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
  2125. // 提取核心矛盾(支持多个空格)
  2126. preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
  2127. $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
  2128. // 提取主体列表(支持多个空格)
  2129. preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
  2130. $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
  2131. $parts['roles'] = parseRolesFromText($rolesText);
  2132. // 提取美术风格(支持多个空格)
  2133. preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
  2134. $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
  2135. // 提取场景列表(支持多个空格)
  2136. preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
  2137. $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
  2138. $parts['scenes'] = parseScenesFromText($scenesText);
  2139. // 提取分集详细内容(多剧集模式,支持多个空格)
  2140. preg_match('/###\s*分集剧本\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
  2141. $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
  2142. // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
  2143. preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
  2144. $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
  2145. // 优先使用原文内容,其次使用分集详细内容
  2146. // $parts['content'] = $generatedContent ?: $detailedContent;
  2147. // 解析分集剧本内容
  2148. $episodes = [];
  2149. if ($detailedContent) {
  2150. // 按 ##分集 分割
  2151. preg_match_all('/##\s*分集(\d+)\s*\n(.*?)(?=\n\s*##分集|\z)/s', $detailedContent, $episodeMatches, PREG_SET_ORDER);
  2152. foreach ($episodeMatches as $episodeMatch) {
  2153. $episodeNum = $episodeMatch[1];
  2154. $episodeContent = trim($episodeMatch[2]);
  2155. $episode = [
  2156. 'episode_number' => $episodeNum,
  2157. 'episode_content' => $episodeContent,
  2158. 'episode_name' => '',
  2159. 'scene_description' => '',
  2160. 'camera_movement' => '',
  2161. 'characters' => '',
  2162. 'dialogues' => []
  2163. ];
  2164. // 提取分集名(格式:##分集01第一集: 第一集的标题)
  2165. if (preg_match('/^第.*?集\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $nameMatch)) {
  2166. $episode['episode_name'] = trim($nameMatch[1]);
  2167. }
  2168. // 提取场景描述
  2169. if (preg_match('/场景描述\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $sceneMatch)) {
  2170. $episode['scene_description'] = trim($sceneMatch[1]);
  2171. }
  2172. // 提取运镜
  2173. if (preg_match('/运镜\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $cameraMatch)) {
  2174. $episode['camera_movement'] = trim($cameraMatch[1]);
  2175. }
  2176. // 提取出场角色
  2177. if (preg_match('/出场角色\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $charactersMatch)) {
  2178. $episode['characters'] = trim($charactersMatch[1]);
  2179. }
  2180. // 提取台词内容
  2181. if (preg_match('/台词内容\s*[::]\s*\n(.*?)$/su', $episodeContent, $dialoguesMatch)) {
  2182. $dialoguesText = trim($dialoguesMatch[1]);
  2183. $dialogueLines = explode("\n", $dialoguesText);
  2184. foreach ($dialogueLines as $line) {
  2185. $line = trim($line);
  2186. if (empty($line)) {
  2187. continue;
  2188. }
  2189. // 匹配格式:角色名: 对话内容 或 角色名:对话内容
  2190. if (preg_match('/^(.+?)\s*[::]\s*(.+)$/u', $line, $dialogueMatch)) {
  2191. $episode['dialogues'][] = [
  2192. 'character' => trim($dialogueMatch[1]),
  2193. 'text' => trim($dialogueMatch[2])
  2194. ];
  2195. }
  2196. }
  2197. }
  2198. $episodes[] = $episode;
  2199. }
  2200. }
  2201. $parts['episodes'] = $episodes;
  2202. return $parts;
  2203. }
  2204. /**
  2205. * 处理剧本内容
  2206. */
  2207. function handleScriptContent($originalContent) {
  2208. if (!$originalContent) return [];
  2209. // 使用更精确的正则表达式分割内容
  2210. $parts = [];
  2211. // // 确保内容使用UTF-8编码
  2212. // if (!mb_check_encoding($originalContent, 'UTF-8')) {
  2213. // $originalContent = mb_convert_encoding($originalContent, 'UTF-8', 'auto');
  2214. // }
  2215. // 提取剧本名(###剧本名:后面的内容,支持多个空格)
  2216. preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
  2217. $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
  2218. // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
  2219. preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
  2220. $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
  2221. // 提取剧本亮点(支持多个空格)
  2222. preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
  2223. $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
  2224. // 提取人物关系(支持多个空格)
  2225. preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
  2226. $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
  2227. // 提取核心矛盾(支持多个空格)
  2228. preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
  2229. $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
  2230. // 提取主体列表(支持多个空格)
  2231. preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
  2232. $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
  2233. $parts['roles'] = parseRolesFromText($rolesText);
  2234. // 提取美术风格(支持多个空格)
  2235. preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
  2236. $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
  2237. // 提取场景列表(支持多个空格)
  2238. preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
  2239. $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
  2240. $parts['scenes'] = parseScenesFromText($scenesText);
  2241. // 提取分集详细内容(多剧集模式,支持多个空格)
  2242. preg_match('/###\s*分集详细内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
  2243. $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
  2244. // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
  2245. preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
  2246. $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
  2247. // 优先使用原文内容,其次使用分集详细内容
  2248. $parts['content'] = $generatedContent ?: $detailedContent;
  2249. $parts['episode_title'] = '';
  2250. $parts['acts'] = [];
  2251. // 单剧集格式:顶层是大纲信息,分镜部分采用 handleEpisodeContent 的结构标准
  2252. $singleStoryboard = '';
  2253. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
  2254. $singleStoryboard = trim($singleStoryboardMatch[1]);
  2255. }
  2256. if ($singleStoryboard !== '') {
  2257. $episodeContent = $singleStoryboard;
  2258. if (!preg_match('/第\d+集[::\s]+/u', $episodeContent)) {
  2259. $defaultEpisodeTitle = '第1集:' . ($parts['script_name'] ?? '未命名');
  2260. $episodeContent = $defaultEpisodeTitle . "\n\n" . $episodeContent;
  2261. }
  2262. $episodeSections = [];
  2263. $episodeSections[] = $episodeContent;
  2264. if ($parts['intro'] !== '') {
  2265. $episodeSections[] = "###故事梗概\n" . $parts['intro'];
  2266. }
  2267. if ($parts['art_style'] !== '') {
  2268. $episodeSections[] = "###美术风格\n" . $parts['art_style'];
  2269. }
  2270. if ($rolesText !== '') {
  2271. $episodeSections[] = "###主体列表\n" . $rolesText;
  2272. }
  2273. if ($scenesText !== '') {
  2274. $episodeSections[] = "###场景列表\n" . $scenesText;
  2275. }
  2276. if (strpos($episodeContent, '###分镜剧本') === false) {
  2277. $episodeSections[] = "###分镜剧本\n" . $singleStoryboard;
  2278. }
  2279. $episode_arr = handleEpisodeContent(implode("\n\n", $episodeSections));
  2280. if (!empty($episode_arr['acts'])) {
  2281. $parts['episode_title'] = getProp($episode_arr, 'episode_title');
  2282. $parts['acts'] = getProp($episode_arr, 'acts', []);
  2283. if (empty($parts['roles'])) {
  2284. $parts['roles'] = getProp($episode_arr, 'roles', []);
  2285. }
  2286. if (empty($parts['scenes'])) {
  2287. $parts['scenes'] = getProp($episode_arr, 'scenes', []);
  2288. }
  2289. }
  2290. }
  2291. if (empty($parts['acts'])) {
  2292. $fallbackEpisodeArr = handleEpisodeContent($originalContent);
  2293. if (!empty($fallbackEpisodeArr['acts'])) {
  2294. $parts['episode_title'] = getProp($fallbackEpisodeArr, 'episode_title');
  2295. $parts['acts'] = getProp($fallbackEpisodeArr, 'acts', []);
  2296. if (empty($parts['intro'])) {
  2297. $parts['intro'] = getProp($fallbackEpisodeArr, 'intro');
  2298. }
  2299. if (empty($parts['art_style'])) {
  2300. $parts['art_style'] = getProp($fallbackEpisodeArr, 'art_style');
  2301. }
  2302. if (empty($parts['roles'])) {
  2303. $parts['roles'] = getProp($fallbackEpisodeArr, 'roles', []);
  2304. }
  2305. if (empty($parts['scenes'])) {
  2306. $parts['scenes'] = getProp($fallbackEpisodeArr, 'scenes', []);
  2307. }
  2308. }
  2309. }
  2310. // 多剧集格式:继续兼容旧的分集剧本结构
  2311. $fullScript = '';
  2312. if (preg_match('/###分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2313. $fullScript = trim($storyboardMatch[1]);
  2314. } elseif (preg_match('/##分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2315. $fullScript = trim($storyboardMatch[1]);
  2316. } elseif (preg_match('/分集剧本[::]\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2317. $fullScript = trim($storyboardMatch[1]);
  2318. }
  2319. if (empty($fullScript) && preg_match('/(##分集.*)/su', $originalContent, $fallbackMatch)) {
  2320. $fullScript = trim($fallbackMatch[1]);
  2321. }
  2322. $episodes = [];
  2323. preg_match_all('/##分集(\d+)\s*\n分集名[::]\s*(.*?)\s*\n(?:场景描述[::].*?\n出场角色[::].*?\n台词内容[::]\s*\n)?(.*?)(?=\n##分集|$)/su', $fullScript, $matches, PREG_SET_ORDER);
  2324. foreach ($matches as $match) {
  2325. $episodeNumber = (int)trim($match[1]);
  2326. $episodeName = trim($match[2]);
  2327. $episodeContent = trim($match[3]);
  2328. $segments = [];
  2329. preg_match_all('/分镜(\d+)\s*\n(.*?)(?=\n分镜\d+|\z)/s', $episodeContent, $segmentMatches, PREG_SET_ORDER);
  2330. foreach ($segmentMatches as $segMatch) {
  2331. $segmentNumber = (int)trim($segMatch[1]);
  2332. $segmentContent = trim($segMatch[2]);
  2333. $segments[] = [
  2334. 'segment_number' => $segmentNumber,
  2335. 'segment_content' => $segmentContent,
  2336. ];
  2337. }
  2338. $episodes[] = [
  2339. 'episode_number' => $episodeNumber,
  2340. 'title' => $episodeName,
  2341. 'content' => $episodeContent,
  2342. 'segments' => $segments,
  2343. ];
  2344. }
  2345. if (empty($episodes) && !empty($parts['acts'])) {
  2346. $singleSegments = [];
  2347. foreach ($parts['acts'] as $act) {
  2348. $actSegments = getProp($act, 'segments', []);
  2349. if (!is_array($actSegments)) {
  2350. continue;
  2351. }
  2352. foreach ($actSegments as $segment) {
  2353. $singleSegments[] = [
  2354. 'segment_number' => getProp($segment, 'segment_number'),
  2355. 'segment_content' => getProp($segment, 'segment_content'),
  2356. ];
  2357. }
  2358. }
  2359. $episodeTitle = $parts['episode_title'] ?: ('第1集:' . ($parts['script_name'] ?? '未命名'));
  2360. $episodeName = preg_replace('/^第\d+集[::]\s*/u', '', $episodeTitle);
  2361. $episodes[] = [
  2362. 'episode_number' => 1,
  2363. 'title' => $episodeName,
  2364. 'content' => $singleStoryboard,
  2365. 'segments' => $singleSegments,
  2366. ];
  2367. }
  2368. $parts['episodes'] = $episodes;
  2369. return $parts;
  2370. }
  2371. function handleEpisodeContent($originalContent) {
  2372. if (!$originalContent) return [];
  2373. // 解析剧集内容
  2374. $result = [
  2375. 'episode_title' => '',
  2376. 'intro' => '',
  2377. 'art_style' => '',
  2378. 'roles' => [],
  2379. 'scenes' => [],
  2380. 'acts' => []
  2381. ];
  2382. // 提取剧集标题 - 匹配"第xx集:标题"或"第xx集 标题"格式,排除###标记
  2383. if (preg_match('/第(\d+)集[::\s]+([^#\n]+?)(?=\s*###|\s*$|\n)/u', $originalContent, $titleMatch)) {
  2384. $result['episode_title'] = '第' . $titleMatch[1] . '集:' . trim($titleMatch[2]);
  2385. }
  2386. // 提取故事梗概 - 兼容多种格式:###故事梗概、### 故事梗概、### 故事梗概
  2387. if (preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $summaryMatch)) {
  2388. $result['intro'] = trim($summaryMatch[1]);
  2389. }
  2390. // 提取美术风格 - 兼容多种格式
  2391. if (preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $styleMatch)) {
  2392. $result['art_style'] = trim($styleMatch[1]);
  2393. }
  2394. // 提取主体列表 - 兼容多种格式
  2395. if (preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $charactersMatch)) {
  2396. $charactersText = trim($charactersMatch[1]);
  2397. $characterLines = explode("\n", $charactersText);
  2398. foreach ($characterLines as $line) {
  2399. $line = trim($line);
  2400. if (empty($line)) continue;
  2401. // 兼容中文冒号:和英文冒号:,同时提取音色信息
  2402. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  2403. $role = trim($charMatch[1]);
  2404. $description = trim($charMatch[2]);
  2405. $timbreName = null;
  2406. // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
  2407. $picPrompt = null;
  2408. if (preg_match('/^(.*?)\{([^}]+)\}\{\{([^}]+)\}\}\s*$/u', $description, $fullMatch)) {
  2409. // 匹配格式:主体描述{主体图片提示词}{{音色名}}
  2410. $description = trim($fullMatch[1]);
  2411. $picPrompt = trim($fullMatch[2]);
  2412. $timbreName = trim($fullMatch[3]);
  2413. } elseif (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  2414. // 兼容旧格式:主体描述{{音色名}}
  2415. $description = trim($timbreMatch[1]);
  2416. $timbreName = trim($timbreMatch[2]);
  2417. }
  2418. $roleData = [
  2419. 'role' => $role,
  2420. 'description' => $description
  2421. ];
  2422. // 如果有主体图片提示词,添加到数组中
  2423. if ($picPrompt) {
  2424. // 检查开头是否有"全景,正面拍摄。"
  2425. $prefix = '全景,正面拍摄。';
  2426. $prefixParts = ['全景', '正面拍摄'];
  2427. // 检查是否包含完整前缀
  2428. if (strpos($picPrompt, $prefix) !== 0) {
  2429. // 检查是否包含部分前缀词汇(不论位置)
  2430. $hasAnyPrefix = false;
  2431. foreach ($prefixParts as $part) {
  2432. if (mb_strpos($picPrompt, $part) !== false) {
  2433. $hasAnyPrefix = true;
  2434. break;
  2435. }
  2436. }
  2437. if ($hasAnyPrefix) {
  2438. // 移除所有"全景"和"正面拍摄"词汇(包括它们后面的标点)
  2439. $picPrompt = preg_replace('/全景[,,、。. ]*/u', '', $picPrompt);
  2440. $picPrompt = preg_replace('/正面拍摄[,,、。. ]*/u', '', $picPrompt);
  2441. // 清理开头和结尾的标点符号和空格
  2442. $picPrompt = preg_replace('/^[。,,、 ]+|[。,,、 ]+$/u', '', $picPrompt);
  2443. }
  2444. // 在开头添加完整前缀
  2445. $picPrompt = $prefix . $picPrompt;
  2446. }
  2447. // 检查是否包含"姿态:"或"姿态:"
  2448. if (preg_match('/姿态[::]/u', $picPrompt)) {
  2449. // 如果有姿态描述,统一替换为"姿态:站立"
  2450. $picPrompt = preg_replace('/姿态[::][^.。\n]+/u', '姿态:站立', $picPrompt);
  2451. } else {
  2452. // 如果没有姿态描述,在末尾添加"姿态:站立"
  2453. $picPrompt = preg_replace('/[。,, ]+$/u', '', $picPrompt) . '。姿态:站立。';
  2454. }
  2455. $roleData['pic_prompt'] = $picPrompt;
  2456. }
  2457. // 如果有音色信息,添加到数组中
  2458. if ($timbreName) {
  2459. $timbre = DB::table('mp_timbres')->where('is_enabled', 1)->where('timbre_name', 'like', "%{$timbreName}%")->orderBy('id')->select('timbre_type', 'audio_url')->first();
  2460. if ($timbre) {
  2461. $roleData['voice_name'] = $timbreName;
  2462. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2463. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');;
  2464. }
  2465. }else {
  2466. // 从描述或人物提示词中获取"男"或"女",赋予默认音色,获取不到则使用旁白音色
  2467. if ($picPrompt) {
  2468. if (strstr($picPrompt, '男')) {
  2469. $roleData['voice_name'] = '阳光青年';
  2470. }elseif (strstr($picPrompt, '女')) {
  2471. $roleData['voice_name'] = '爽快思思';
  2472. }else {
  2473. if ($description) {
  2474. if (strstr($description, '男')) {
  2475. $roleData['voice_name'] = '阳光青年';
  2476. }elseif (strstr($description, '女')) {
  2477. $roleData['voice_name'] = '爽快思思';
  2478. }else {
  2479. $roleData['voice_name'] = '旁白';
  2480. }
  2481. }
  2482. }
  2483. }
  2484. if (!empty($roleData['voice_name'])) {
  2485. if ($roleData['voice_name'] == '旁白') {
  2486. $roleData['voice_type'] = 'zh_male_linjiananhai_moon_bigtts';
  2487. $roleData['voice_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav';
  2488. }else {
  2489. $timbre = DB::table('mp_timbres')
  2490. ->where('is_enabled', 1)
  2491. ->where('timbre_name', 'like', "%".$roleData['voice_name']."%")
  2492. ->orderBy('id')
  2493. ->select('timbre_type', 'audio_url')
  2494. ->first();
  2495. if ($timbre) {
  2496. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2497. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  2498. }
  2499. }
  2500. }
  2501. }
  2502. $result['roles'][] = $roleData;
  2503. }
  2504. }
  2505. // 加入旁白角色(如果不存在)
  2506. $hasNarrator = false;
  2507. foreach ($result['roles'] as $role) {
  2508. if (isset($role['role']) && $role['role'] === '旁白') {
  2509. $hasNarrator = true;
  2510. break;
  2511. }
  2512. }
  2513. if (!$hasNarrator) {
  2514. $result['roles'][] = [
  2515. 'role' => '旁白',
  2516. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  2517. 'pic_prompt' => '',
  2518. 'voice_name' => '旁白',
  2519. 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  2520. 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  2521. ];
  2522. }
  2523. }
  2524. // 提取场景列表 - 兼容多种格式
  2525. if (preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $scenesMatch)) {
  2526. $scenesText = trim($scenesMatch[1]);
  2527. $sceneLines = explode("\n", $scenesText);
  2528. foreach ($sceneLines as $line) {
  2529. $line = trim($line);
  2530. if (empty($line)) continue;
  2531. // 兼容中文冒号:和英文冒号:
  2532. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $sceneMatch)) {
  2533. $scene = trim($sceneMatch[1]);
  2534. $description = trim($sceneMatch[2]);
  2535. $picPrompt = null;
  2536. // 检查描述末尾是否有{场景图片提示词}格式
  2537. if (preg_match('/^(.*?)\{([^}]+)\}\s*$/u', $description, $promptMatch)) {
  2538. // 匹配格式:场景描述{场景图片提示词}
  2539. $description = trim($promptMatch[1]);
  2540. $picPrompt = trim($promptMatch[2]);
  2541. }
  2542. $sceneData = [
  2543. 'scene' => $scene,
  2544. 'description' => $description
  2545. ];
  2546. // 如果有场景图片提示词,添加到数组中
  2547. if ($picPrompt) {
  2548. $sceneData['pic_prompt'] = $picPrompt;
  2549. }
  2550. $result['scenes'][] = $sceneData;
  2551. }
  2552. }
  2553. }
  2554. // 提取分镜剧本 - 兼容多种格式
  2555. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $storyboardMatch)) {
  2556. $storyboardText = trim($storyboardMatch[1]);
  2557. // 按幕分割 - 修复第1幕识别和乱码问题
  2558. $acts = [];
  2559. // 先在开头添加换行符,确保第1幕也能被正确分割
  2560. $normalizedText = "\n" . $storyboardText;
  2561. $parts = preg_split('/\n\s*##/', $normalizedText);
  2562. foreach ($parts as $part) {
  2563. $part = trim($part);
  2564. if (empty($part)) continue;
  2565. // 如果不是以"第"开头,跳过
  2566. if (!preg_match('/^第\d+幕/', $part)) {
  2567. continue;
  2568. }
  2569. // 分离标题和内容
  2570. $lines = explode("\n", $part, 2);
  2571. $actTitle = trim($lines[0]);
  2572. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  2573. // 解析幕标题,提取序号和详细信息 - 修复乱码问题
  2574. if (preg_match('/^第(\d+)幕[::]?\s*(.*)$/u', $actTitle, $actTitleMatch)) {
  2575. $actNumber = intval($actTitleMatch[1]);
  2576. $actDetails = trim($actTitleMatch[2]);
  2577. // 如果详细信息为空或者就是冒号,使用完整标题
  2578. if (empty($actDetails) || $actDetails === ':' || $actDetails === ':') {
  2579. $actDetails = $actTitle;
  2580. }
  2581. } else {
  2582. $actNumber = count($acts) + 1;
  2583. $actDetails = $actTitle;
  2584. }
  2585. // 解析该幕下的分镜
  2586. $segments = [];
  2587. $segmentPattern = '/分镜(\d+)\s*\n(.*?)(?=\n+\s*分镜\d+|\z)/s';
  2588. preg_match_all($segmentPattern, $actContent, $segmentMatches, PREG_SET_ORDER);
  2589. foreach ($segmentMatches as $segmentMatch) {
  2590. $segmentNumber = intval($segmentMatch[1]);
  2591. $segmentContent = trim($segmentMatch[2]);
  2592. // 解析分镜详细信息
  2593. $segmentData = [
  2594. 'segment_id' => date('YmdHis') . mt_rand(1000, 9999) . str_pad($segmentNumber, 3, "0", STR_PAD_LEFT), // 生成唯一ID(后续可在生成任务里查看历史版本)
  2595. 'segment_number' => $segmentNumber,
  2596. 'segment_content' => $segmentContent,
  2597. 'description' => '',
  2598. 'composition' => '',
  2599. 'camera_movement' => '',
  2600. 'voice_actor' => '',
  2601. 'dialogue' => '',
  2602. 'frame_type' => '',
  2603. 'scene' => '', // 新增:场景
  2604. 'characters' => '', // 新增:出镜角色
  2605. 'tail_frame' => '', // 新增:尾帧描述
  2606. // 新增字段
  2607. 'emotion' => '中性', // 新增: 情感
  2608. 'gender' => '0', // 新增: 性别(0未知,1男,2女)
  2609. 'speed_ratio' => 0, // 新增: 语速
  2610. 'loudness_ratio' => 0, // 新增: 音量
  2611. 'emotion_scale' => 4, // 新增: 语调
  2612. 'pitch' => 0, // 新增: 音调
  2613. ];
  2614. // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
  2615. if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  2616. $segmentData['description'] = trim($descMatch[1]);
  2617. }
  2618. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  2619. $segmentData['composition'] = trim($compMatch[1]);
  2620. }
  2621. if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  2622. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  2623. }
  2624. if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  2625. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  2626. }
  2627. if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
  2628. $dialogue = trim($dialogueMatch[1]) == '无' ? '' : trim($dialogueMatch[1]);
  2629. // 确保台词使用中文左右双引号
  2630. if (!empty($dialogue)) {
  2631. $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
  2632. $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
  2633. // 句首或句尾没有中文双引号,则分别添加中文左右双引号
  2634. if (!preg_match('/^[“]/', $dialogue)) {
  2635. $dialogue = '“' . $dialogue;
  2636. }
  2637. if (!preg_match('/[”]$/', $dialogue)) {
  2638. $dialogue .= '”';
  2639. }
  2640. // 将修改后的台词替换回 $segmentContent
  2641. $originalDialogue = $dialogueMatch[1];
  2642. $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
  2643. }
  2644. $segmentData['dialogue'] = $dialogue;
  2645. }
  2646. if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  2647. $segmentData['frame_type'] = trim($frameMatch[1]);
  2648. }
  2649. // 新增:场景字段
  2650. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  2651. $segmentData['scene'] = trim($sceneMatch[1]);
  2652. }
  2653. // 新增:出镜角色字段
  2654. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  2655. $segmentData['characters'] = trim($charactersMatch[1]);
  2656. }
  2657. // 新增:尾帧描述字段
  2658. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  2659. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  2660. }
  2661. $replaceEmptyArr = [];
  2662. // 新增:情感字段
  2663. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  2664. $replaceEmptyArr[] = trim($emotionMatch[0]);
  2665. $segmentData['emotion'] = trim($emotionMatch[1]);
  2666. }
  2667. // 新增:性别字段
  2668. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  2669. $replaceEmptyArr[] = trim($genderMatch[0]);
  2670. $genderStr = trim($genderMatch[1]);
  2671. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  2672. $segmentData['gender'] = '1';
  2673. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  2674. $segmentData['gender'] = '2';
  2675. } else {
  2676. $segmentData['gender'] = '0';
  2677. }
  2678. }
  2679. // 新增:语速字段
  2680. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  2681. $replaceEmptyArr[] = trim($speedMatch[0]);
  2682. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  2683. }
  2684. // 新增:音量字段
  2685. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  2686. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  2687. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  2688. }
  2689. // 新增:情感强度字段
  2690. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  2691. $replaceEmptyArr[] = trim($scaleMatch[0]);
  2692. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  2693. }
  2694. // 新增:音调字段
  2695. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  2696. $replaceEmptyArr[] = trim($pitchMatch[0]);
  2697. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  2698. }
  2699. $segmentData['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  2700. // 去除多余的换行符(将连续多个换行符替换为单个换行符)
  2701. $segmentData['segment_content'] = preg_replace('/\n{2,}/', "\n", $segmentData['segment_content']);
  2702. $segmentData['segment_content'] = trim($segmentData['segment_content']);
  2703. $segments[] = $segmentData;
  2704. }
  2705. $acts[] = [
  2706. 'act_number' => $actNumber,
  2707. 'act_title' => $actTitle,
  2708. 'act_details' => $actDetails,
  2709. 'segments' => $segments
  2710. ];
  2711. }
  2712. $result['acts'] = $acts;
  2713. }
  2714. return $result;
  2715. }
  2716. /**
  2717. * 处理剧本内容(全能模式)
  2718. */
  2719. function handleScriptContentForAce($originalContent) {
  2720. if (!$originalContent) return [];
  2721. // 使用更精确的正则表达式分割内容
  2722. $parts = [];
  2723. // // 确保内容使用UTF-8编码
  2724. // if (!mb_check_encoding($originalContent, 'UTF-8')) {
  2725. // $originalContent = mb_convert_encoding($originalContent, 'UTF-8', 'auto');
  2726. // }
  2727. // 提取剧本名(###剧本名:后面的内容,支持多个空格)
  2728. preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
  2729. $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
  2730. // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
  2731. preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
  2732. $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
  2733. // 提取剧本亮点(支持多个空格)
  2734. preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
  2735. $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
  2736. // 提取人物关系(支持多个空格)
  2737. preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
  2738. $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
  2739. // 提取核心矛盾(支持多个空格)
  2740. preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
  2741. $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
  2742. // 提取主体列表(支持多个空格)
  2743. preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
  2744. $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
  2745. $parts['roles'] = parseRolesFromTextForAce($rolesText);
  2746. // 提取美术风格(支持多个空格)
  2747. preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
  2748. $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
  2749. // 提取场景列表(支持多个空格)
  2750. preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
  2751. $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
  2752. $parts['scenes'] = parseScenesFromText($scenesText);
  2753. // 提取道具列表(支持多个空格)
  2754. preg_match('/###\s*道具列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $propsMatch);
  2755. $propsText = isset($propsMatch[1]) ? trim($propsMatch[1]) : '';
  2756. $parts['props'] = parsePropsFromText($propsText);
  2757. // 提取分集详细内容(多剧集模式,支持多个空格)
  2758. preg_match('/###\s*分集详细内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
  2759. $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
  2760. // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
  2761. preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
  2762. $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
  2763. // 优先使用原文内容,其次使用分集详细内容
  2764. $parts['content'] = $generatedContent ?: $detailedContent;
  2765. $parts['episode_title'] = '';
  2766. $parts['acts'] = [];
  2767. // 单剧集格式:顶层是大纲信息,分段部分采用 handleEpisodeContentForAce 的结构标准
  2768. $singleStoryboard = '';
  2769. if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
  2770. $singleStoryboard = trim($singleStoryboardMatch[1]);
  2771. } elseif (preg_match('/###\s*分段剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
  2772. $singleStoryboard = trim($singleStoryboardMatch[1]);
  2773. }
  2774. if ($singleStoryboard !== '') {
  2775. // 构造符合 handleEpisodeContentForAce 期望的输入格式
  2776. $episodeContent = '';
  2777. // 如果分镜剧本内容不包含剧集标题,添加默认标题
  2778. if (!preg_match('/第\d+集[::\s]+/u', $singleStoryboard)) {
  2779. $defaultEpisodeTitle = '第1集:' . ($parts['script_name'] ?? '未命名');
  2780. $episodeContent = $defaultEpisodeTitle . "\n\n";
  2781. }
  2782. // 组装完整的剧集内容,按 handleEpisodeContentForAce 期望的结构
  2783. $episodeSections = [];
  2784. // 添加故事梗概(如果有)
  2785. if (!empty($parts['intro'])) {
  2786. $episodeSections[] = "###故事梗概\n" . $parts['intro'];
  2787. }
  2788. // 添加美术风格(如果有)
  2789. if (!empty($parts['art_style'])) {
  2790. $episodeSections[] = "###美术风格\n" . $parts['art_style'];
  2791. }
  2792. // 添加主体列表(如果有)
  2793. if (!empty($rolesText)) {
  2794. $episodeSections[] = "###主体列表\n" . $rolesText;
  2795. }
  2796. // 添加场景列表(如果有)
  2797. if (!empty($scenesText)) {
  2798. $episodeSections[] = "###场景列表\n" . $scenesText;
  2799. }
  2800. // 添加道具列表(如果有)
  2801. if (!empty($propsText)) {
  2802. $episodeSections[] = "###道具列表\n" . $propsText;
  2803. }
  2804. // 添加分镜剧本内容(兼容"分镜剧本"和"分段剧本")
  2805. if (strpos($singleStoryboard, '###分镜剧本') === false && strpos($singleStoryboard, '###分段剧本') === false) {
  2806. $episodeSections[] = "###分镜剧本\n" . $singleStoryboard;
  2807. } else {
  2808. $episodeSections[] = $singleStoryboard;
  2809. }
  2810. // 拼接完整内容
  2811. $episodeContent .= implode("\n\n", $episodeSections);
  2812. // 调用 handleEpisodeContentForAce 方法解析
  2813. $episode_arr = handleEpisodeContentForAce($episodeContent);
  2814. if (!empty($episode_arr['acts'])) {
  2815. $parts['episode_title'] = getProp($episode_arr, 'episode_title', '');
  2816. $parts['acts'] = getProp($episode_arr, 'acts', []);
  2817. }
  2818. // 更新roles、scenes和props
  2819. $episode_roles = getProp($episode_arr, 'roles');
  2820. $episode_scenes = getProp($episode_arr, 'scenes');
  2821. $episode_props = getProp($episode_arr, 'props');
  2822. if ($episode_roles) $parts['roles'] = $episode_roles;
  2823. if ($episode_scenes) $parts['scenes'] = $episode_scenes;
  2824. if ($episode_props) $parts['props'] = $episode_props;
  2825. }
  2826. // 如果上面的处理没有得到 acts,尝试直接用原始内容调用 handleEpisodeContentForAce
  2827. if (empty($parts['acts'])) {
  2828. $fallbackEpisodeArr = handleEpisodeContentForAce($originalContent);
  2829. if (!empty($fallbackEpisodeArr['acts'])) {
  2830. $parts['episode_title'] = getProp($fallbackEpisodeArr, 'episode_title', '');
  2831. $parts['acts'] = getProp($fallbackEpisodeArr, 'acts', []);
  2832. if (empty($parts['intro'])) {
  2833. $parts['intro'] = getProp($fallbackEpisodeArr, 'intro', '');
  2834. }
  2835. if (empty($parts['art_style'])) {
  2836. $parts['art_style'] = getProp($fallbackEpisodeArr, 'art_style', '');
  2837. }
  2838. }
  2839. // 更新roles、scenes和props
  2840. $episode_roles = getProp($fallbackEpisodeArr, 'roles');
  2841. $episode_scenes = getProp($fallbackEpisodeArr, 'scenes');
  2842. $episode_props = getProp($fallbackEpisodeArr, 'props');
  2843. if ($episode_roles) $parts['roles'] = $episode_roles;
  2844. if ($episode_scenes) $parts['scenes'] = $episode_scenes;
  2845. if ($episode_props) $parts['props'] = $episode_props;
  2846. }
  2847. // 多剧集格式:继续兼容旧的分集剧本结构
  2848. $fullScript = '';
  2849. if (preg_match('/###分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2850. $fullScript = trim($storyboardMatch[1]);
  2851. } elseif (preg_match('/##分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2852. $fullScript = trim($storyboardMatch[1]);
  2853. } elseif (preg_match('/分集剧本[::]\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
  2854. $fullScript = trim($storyboardMatch[1]);
  2855. }
  2856. if (empty($fullScript) && preg_match('/(##分集.*)/su', $originalContent, $fallbackMatch)) {
  2857. $fullScript = trim($fallbackMatch[1]);
  2858. }
  2859. $episodes = [];
  2860. preg_match_all('/##分集(\d+)\s*\n分集名[::]\s*(.*?)\s*\n(?:场景描述[::].*?\n出场角色[::].*?\n台词内容[::]\s*\n)?(.*?)(?=\n##分集|$)/su', $fullScript, $matches, PREG_SET_ORDER);
  2861. foreach ($matches as $match) {
  2862. $episodeNumber = (int)trim($match[1]);
  2863. $episodeName = trim($match[2]);
  2864. $episodeContent = trim($match[3]);
  2865. $segments = [];
  2866. preg_match_all('/分镜(\d+)\s*\n(.*?)(?=\n分镜\d+|\z)/s', $episodeContent, $segmentMatches, PREG_SET_ORDER);
  2867. foreach ($segmentMatches as $segMatch) {
  2868. $segmentNumber = (int)trim($segMatch[1]);
  2869. $segmentContent = trim($segMatch[2]);
  2870. $segments[] = [
  2871. 'segment_number' => $segmentNumber,
  2872. 'segment_content' => $segmentContent,
  2873. ];
  2874. }
  2875. $episodes[] = [
  2876. 'episode_number' => $episodeNumber,
  2877. 'title' => $episodeName,
  2878. 'content' => $episodeContent,
  2879. 'segments' => $segments,
  2880. ];
  2881. }
  2882. if (empty($episodes) && !empty($parts['acts'])) {
  2883. $singleSegments = [];
  2884. foreach ($parts['acts'] as $act) {
  2885. $actSegments = getProp($act, 'segments', []);
  2886. if (!is_array($actSegments)) {
  2887. continue;
  2888. }
  2889. foreach ($actSegments as $segment) {
  2890. $singleSegments[] = [
  2891. 'segment_number' => getProp($segment, 'segment_number'),
  2892. 'segment_content' => getProp($segment, 'segment_content'),
  2893. ];
  2894. }
  2895. }
  2896. $episodeTitle = $parts['episode_title'] ?: ('第1集:' . ($parts['script_name'] ?? '未命名'));
  2897. $episodeName = preg_replace('/^第\d+集[::]\s*/u', '', $episodeTitle);
  2898. $episodes[] = [
  2899. 'episode_number' => 1,
  2900. 'title' => $episodeName,
  2901. 'content' => $singleStoryboard,
  2902. 'segments' => $singleSegments,
  2903. ];
  2904. }
  2905. $parts['episodes'] = $episodes;
  2906. return $parts;
  2907. }
  2908. /**
  2909. * 将主体列表文本拆分为主体数组
  2910. *
  2911. * @param string $rolesText 主体列表文本内容
  2912. * @return array 主体名称数组
  2913. */
  2914. function parseRolesFromTextForAce(string $rolesText): array
  2915. {
  2916. if (empty($rolesText)) {
  2917. return [];
  2918. }
  2919. $roles = [];
  2920. // 按行分割文本
  2921. $lines = explode("\n", $rolesText);
  2922. foreach ($lines as $line) {
  2923. $line = trim($line);
  2924. if (empty($line)) {
  2925. continue;
  2926. }
  2927. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  2928. $role = trim($charMatch[1]);
  2929. $description = trim($charMatch[2]);
  2930. $timbreName = null;
  2931. // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
  2932. $picPrompt = null;
  2933. $timbrePrompt = null;
  2934. if (preg_match('/^(.*?)\{([^}]+)\}\{\{([^}]+)\}\}\s*$/u', $description, $fullMatch)) {
  2935. // 匹配格式:主体描述{主体图片提示词}{{音色名}}
  2936. $description = trim($fullMatch[1]);
  2937. $picPrompt = trim($fullMatch[2]);
  2938. $timbrePrompt = trim($fullMatch[3]);
  2939. } elseif (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  2940. // 兼容旧格式:主体描述{{音色名}}
  2941. $description = trim($timbreMatch[1]);
  2942. $timbrePrompt = trim($timbreMatch[2]);
  2943. }
  2944. $roleData = [
  2945. 'role' => $role,
  2946. 'description' => $description,
  2947. ];
  2948. // 如果有主体图片提示词,添加到数组中
  2949. if ($picPrompt) $roleData['pic_prompt'] = $picPrompt;
  2950. // 如果有音色提示词,添加到数组中
  2951. if ($timbrePrompt) $roleData['voice_prompt'] = $timbrePrompt;
  2952. if ($timbreName) {
  2953. $timbre = DB::table('mp_timbres')
  2954. ->where('is_enabled', 1)
  2955. ->where('timbre_name', 'like', "%{$timbreName}%")
  2956. ->orderBy('id')
  2957. ->select('timbre_type', 'audio_url')
  2958. ->first();
  2959. if ($timbre) {
  2960. $roleData['voice_name'] = $timbreName;
  2961. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2962. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  2963. }
  2964. }
  2965. // else {
  2966. // // 从描述或人物提示词中获取"男"或"女",赋予默认音色,获取不到则使用旁白音色
  2967. // if ($picPrompt) {
  2968. // if (strstr($picPrompt, '男')) {
  2969. // $roleData['voice_name'] = '阳光青年';
  2970. // }elseif (strstr($picPrompt, '女')) {
  2971. // $roleData['voice_name'] = '爽快思思';
  2972. // }else {
  2973. // if ($description) {
  2974. // if (strstr($description, '男')) {
  2975. // $roleData['voice_name'] = '阳光青年';
  2976. // }elseif (strstr($description, '女')) {
  2977. // $roleData['voice_name'] = '爽快思思';
  2978. // }else {
  2979. // $roleData['voice_name'] = '旁白';
  2980. // }
  2981. // }
  2982. // }
  2983. // }
  2984. // if (!empty($roleData['voice_name'])) {
  2985. // if ($roleData['voice_name'] == '旁白') {
  2986. // $roleData['voice_type'] = 'zh_male_linjiananhai_moon_bigtts';
  2987. // $roleData['voice_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav';
  2988. // }else {
  2989. // $timbre = DB::table('mp_timbres')
  2990. // ->where('is_enabled', 1)
  2991. // ->where('timbre_name', 'like', "%".$roleData['voice_name']."%")
  2992. // ->orderBy('id')
  2993. // ->select('timbre_type', 'audio_url')
  2994. // ->first();
  2995. // if ($timbre) {
  2996. // $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  2997. // $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  2998. // }
  2999. // }
  3000. // }
  3001. // }
  3002. $roles[] = $roleData;
  3003. }
  3004. }
  3005. $hasNarrator = false;
  3006. foreach ($roles as $role) {
  3007. if (getProp($role, 'role') === '旁白') {
  3008. $hasNarrator = true;
  3009. break;
  3010. }
  3011. }
  3012. if (!$hasNarrator) {
  3013. $roles[] = [
  3014. 'role' => '旁白',
  3015. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  3016. 'pic_prompt' => '',
  3017. 'voice_prompt' => '',
  3018. // 'voice_name' => '旁白',
  3019. // 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  3020. // 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  3021. ];
  3022. }
  3023. return $roles;
  3024. }
  3025. function handleEpisodeContentForAce($originalContent) {
  3026. if (!$originalContent) return [];
  3027. // 解析剧集内容
  3028. $result = [
  3029. 'episode_title' => '',
  3030. 'intro' => '',
  3031. 'art_style' => '',
  3032. 'roles' => [],
  3033. 'scenes' => [],
  3034. 'props' => [],
  3035. 'acts' => []
  3036. ];
  3037. // 提取剧集标题 - 匹配"第xx集:标题"或"第xx集 标题"格式,排除###标记
  3038. if (preg_match('/第(\d+)集[::\s]+([^#\n]+?)(?=\s*###|\s*$|\n)/u', $originalContent, $titleMatch)) {
  3039. $result['episode_title'] = '第' . $titleMatch[1] . '集:' . trim($titleMatch[2]);
  3040. }
  3041. // 提取故事梗概 - 兼容多种格式:###故事梗概、### 故事梗概、### 故事梗概
  3042. if (preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $summaryMatch)) {
  3043. $result['intro'] = trim($summaryMatch[1]);
  3044. }
  3045. // 提取美术风格 - 兼容多种格式
  3046. if (preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $styleMatch)) {
  3047. $result['art_style'] = trim($styleMatch[1]);
  3048. }
  3049. // 提取主体列表 - 兼容多种格式
  3050. // 旧正则(2026-08-14 前):只允许 ### 与标题同行,初衷是防止板块为空时把后续"###分段剧本"当板块内容;
  3051. // 但不兼容模型偶发的"###\n主体列表"换行标题格式(如 mp_anime_records id=31915),导致 roles/scenes/props 解析为空。
  3052. // if (preg_match('/###[ \t]*主体列表[ \t]*\r?\n(.*?)(?=###[^#\n]|\z)/s', $originalContent, $charactersMatch)) {
  3053. // 新正则:开头 \s*? 非贪婪,兼容 ###主体列表、### 主体列表、###\n主体列表、###\n\n主体列表;
  3054. // 结束边界 (?=\n?\s*###[^#]|\z) 保证空板块(### 后直接跟下一章节)与换行标题格式都不会吞入后续内容。
  3055. if (preg_match('/###\s*?主体列表\s*?\r?\n(.*?)(?=\n?\s*###[^#]|\z)/s', $originalContent, $charactersMatch)) {
  3056. $charactersText = trim($charactersMatch[1]);
  3057. $characterLines = explode("\n", $charactersText);
  3058. foreach ($characterLines as $line) {
  3059. $line = trim($line);
  3060. if (empty($line)) continue;
  3061. // 兼容中文冒号:和英文冒号:,同时提取音色信息
  3062. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  3063. $role = trim($charMatch[1]);
  3064. $description = trim($charMatch[2]);
  3065. $timbreName = null;
  3066. // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
  3067. $picPrompt = null;
  3068. $timbrePrompt = null;
  3069. // 修复正则:使用更精确的匹配,支持花括号嵌套
  3070. // 格式1: 描述{pic_prompt} {{voice_prompt}}
  3071. if (preg_match('/^(.*?)\{(.+?)\}\s*\{\{(.+?)\}\}\s*$/u', $description, $fullMatch)) {
  3072. // 匹配格式:主体描述{主体图片提示词}{{音色名}}
  3073. $description = trim($fullMatch[1]);
  3074. $picPrompt = trim($fullMatch[2]);
  3075. $timbrePrompt = trim($fullMatch[3]);
  3076. }
  3077. // 格式2: 描述{{voice_prompt}}(兼容旧格式,只有音色)
  3078. elseif (preg_match('/^(.*?)\{\{(.+?)\}\}\s*$/u', $description, $timbreMatch)) {
  3079. // 兼容旧格式:主体描述{{音色名}}
  3080. $description = trim($timbreMatch[1]);
  3081. $timbrePrompt = trim($timbreMatch[2]);
  3082. }
  3083. // 格式3: 描述{pic_prompt}(只有图片提示词)
  3084. elseif (preg_match('/^(.*?)\{(.+?)\}\s*$/u', $description, $picMatch)) {
  3085. $description = trim($picMatch[1]);
  3086. $picPrompt = trim($picMatch[2]);
  3087. }
  3088. $roleData = [
  3089. 'role' => $role,
  3090. 'description' => $description
  3091. ];
  3092. // 如果有主体图片提示词,添加到数组中
  3093. if ($picPrompt) {
  3094. // 检查开头是否有"全景,正面拍摄。"
  3095. $prefix = '全景,正面拍摄。';
  3096. $prefixParts = ['全景', '正面拍摄'];
  3097. // 检查是否包含完整前缀
  3098. if (strpos($picPrompt, $prefix) !== 0) {
  3099. // 检查是否包含部分前缀词汇(不论位置)
  3100. $hasAnyPrefix = false;
  3101. foreach ($prefixParts as $part) {
  3102. if (mb_strpos($picPrompt, $part) !== false) {
  3103. $hasAnyPrefix = true;
  3104. break;
  3105. }
  3106. }
  3107. if ($hasAnyPrefix) {
  3108. // 移除所有"全景"和"正面拍摄"词汇(包括它们后面的标点)
  3109. $picPrompt = preg_replace('/全景[,,、。. ]*/u', '', $picPrompt);
  3110. $picPrompt = preg_replace('/正面拍摄[,,、。. ]*/u', '', $picPrompt);
  3111. // 清理开头和结尾的标点符号和空格
  3112. $picPrompt = preg_replace('/^[。,,、 ]+|[。,,、 ]+$/u', '', $picPrompt);
  3113. }
  3114. // 在开头添加完整前缀
  3115. $picPrompt = $prefix . $picPrompt;
  3116. }
  3117. // 检查是否包含"姿态:"或"姿态:"
  3118. if (preg_match('/姿态[::]/u', $picPrompt)) {
  3119. // 如果有姿态描述,统一替换为"姿态:站立"
  3120. $picPrompt = preg_replace('/姿态[::][^.。\n]+/u', '姿态:站立', $picPrompt);
  3121. } else {
  3122. // 如果没有姿态描述,在末尾添加"姿态:站立"
  3123. $picPrompt = preg_replace('/[。,, ]+$/u', '', $picPrompt) . '。姿态:站立。';
  3124. }
  3125. $roleData['pic_prompt'] = $picPrompt;
  3126. }
  3127. if ($timbrePrompt) $roleData['voice_prompt'] = $timbrePrompt;
  3128. $result['roles'][] = $roleData;
  3129. }
  3130. }
  3131. // // 加入旁白角色(如果不存在)
  3132. // $hasNarrator = false;
  3133. // foreach ($result['roles'] as $role) {
  3134. // if (isset($role['role']) && $role['role'] === '旁白') {
  3135. // $hasNarrator = true;
  3136. // break;
  3137. // }
  3138. // }
  3139. // if (!$hasNarrator) {
  3140. // $result['roles'][] = [
  3141. // 'role' => '旁白',
  3142. // 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  3143. // 'pic_prompt' => '',
  3144. // 'voice_name' => '旁白',
  3145. // 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  3146. // 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  3147. // ];
  3148. // }
  3149. }
  3150. // 提取场景列表 - 兼容多种格式
  3151. // 旧正则(2026-08-14 前):只允许 ### 与标题同行,原因同上方主体列表,不兼容"###\n场景列表"换行标题格式。
  3152. // if (preg_match('/###[ \t]*场景列表[ \t]*\r?\n(.*?)(?=###[^#\n]|\z)/s', $originalContent, $scenesMatch)) {
  3153. if (preg_match('/###\s*?场景列表\s*?\r?\n(.*?)(?=\n?\s*###[^#]|\z)/s', $originalContent, $scenesMatch)) {
  3154. $scenesText = trim($scenesMatch[1]);
  3155. $sceneLines = explode("\n", $scenesText);
  3156. foreach ($sceneLines as $line) {
  3157. $line = trim($line);
  3158. if (empty($line)) continue;
  3159. // 兼容中文冒号:和英文冒号:
  3160. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $sceneMatch)) {
  3161. $scene = trim($sceneMatch[1]);
  3162. $description = trim($sceneMatch[2]);
  3163. $picPrompt = null;
  3164. // 检查描述末尾是否有{场景图片提示词}或{场景图片提示词}{{补充说明}}格式
  3165. // 格式1: 描述{pic_prompt}{{补充说明}}(如"{...}{{无人物}}")
  3166. if (preg_match('/^(.*?)\{(.+?)\}\s*\{\{(.+?)\}\}\s*$/u', $description, $fullMatch)) {
  3167. $description = trim($fullMatch[1]);
  3168. $picPrompt = trim($fullMatch[2]);
  3169. }
  3170. // 格式2: 描述{{补充说明}}(只有补充说明,无图片提示词)
  3171. elseif (preg_match('/^(.*?)\{\{(.+?)\}\}\s*$/u', $description, $voiceMatch)) {
  3172. $description = trim($voiceMatch[1]);
  3173. }
  3174. // 格式3: 描述{pic_prompt}(只有图片提示词)
  3175. elseif (preg_match('/^(.*?)\{(.+?)\}\s*$/u', $description, $picMatch)) {
  3176. $description = trim($picMatch[1]);
  3177. $picPrompt = trim($picMatch[2]);
  3178. }
  3179. $sceneData = [
  3180. 'scene' => $scene,
  3181. 'description' => $description
  3182. ];
  3183. // 如果有场景图片提示词,添加到数组中
  3184. if ($picPrompt) {
  3185. $sceneData['pic_prompt'] = $picPrompt;
  3186. }
  3187. $result['scenes'][] = $sceneData;
  3188. }
  3189. }
  3190. }
  3191. // 提取道具列表 - 兼容多种格式
  3192. // 旧正则(2026-08-14 前):只允许 ### 与标题同行,原因同上方主体列表,不兼容"###\n道具列表"换行标题格式;
  3193. // 同时旧代码仅在提取到 pic_prompt 时才保存道具,用于兜底防止把分段剧本误当道具,代价是纯描述道具被丢弃。
  3194. // if (preg_match('/###[ \t]*道具列表[ \t]*\r?\n(.*?)(?=###[^#\n]|\z)/s', $originalContent, $propsMatch)) {
  3195. if (preg_match('/###\s*?道具列表\s*?\r?\n(.*?)(?=\n?\s*###[^#]|\z)/s', $originalContent, $propsMatch)) {
  3196. $propsText = trim($propsMatch[1]);
  3197. $propLines = explode("\n", $propsText);
  3198. foreach ($propLines as $line) {
  3199. $line = trim($line);
  3200. if (empty($line)) continue;
  3201. // 兼容中文冒号:和英文冒号:
  3202. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $propMatch)) {
  3203. $prop = trim($propMatch[1]);
  3204. $description = trim($propMatch[2]);
  3205. $picPrompt = null;
  3206. // 检查描述末尾是否有{道具图片提示词}或{道具图片提示词}{{音效提示词}}格式(与主体列表保持一致)
  3207. // 格式1: 描述{pic_prompt}{{voice_prompt}}(图片提示词+音效提示词)
  3208. if (preg_match('/^(.*?)\{(.+?)\}\s*\{\{(.+?)\}\}\s*$/u', $description, $fullMatch)) {
  3209. $description = trim($fullMatch[1]);
  3210. $picPrompt = trim($fullMatch[2]);
  3211. }
  3212. // 格式2: 描述{{voice_prompt}}(只有音效提示词)
  3213. elseif (preg_match('/^(.*?)\{\{(.+?)\}\}\s*$/u', $description, $voiceMatch)) {
  3214. $description = trim($voiceMatch[1]);
  3215. }
  3216. // 格式3: 描述{pic_prompt}(只有图片提示词)
  3217. elseif (preg_match('/^(.*?)\{(.+?)\}\s*$/u', $description, $picMatch)) {
  3218. $description = trim($picMatch[1]);
  3219. $picPrompt = trim($picMatch[2]);
  3220. }
  3221. $propData = [
  3222. 'prop' => $prop,
  3223. 'description' => $description
  3224. ];
  3225. // 新正则已精确切分道具板块,不再依赖"必须有提示词"兜底,纯描述道具也保留
  3226. if ($picPrompt) {
  3227. $propData['pic_prompt'] = $picPrompt;
  3228. }
  3229. $result['props'][] = $propData;
  3230. }
  3231. }
  3232. }
  3233. // 提取分镜剧本 - 兼容多种格式(旧格式:###分镜剧本,新格式:###分段剧本)
  3234. $storyboardPattern = '/###\s*(?:分镜剧本|分段剧本)\s*\n(.*?)(?=\n\s*###[^#]|\z)/s';
  3235. if (preg_match($storyboardPattern, $originalContent, $storyboardMatch)) {
  3236. $storyboardText = trim($storyboardMatch[1]);
  3237. // 提取旁白音色(新格式独有)
  3238. $narratorVoice = '';
  3239. if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $storyboardText, $narratorMatch)) {
  3240. $narratorVoice = trim($narratorMatch[1]);
  3241. // 将旁白加入到roles数组
  3242. $hasNarrator = false;
  3243. foreach ($result['roles'] as $role) {
  3244. if (isset($role['role']) && $role['role'] === '旁白') {
  3245. $hasNarrator = true;
  3246. break;
  3247. }
  3248. }
  3249. if (!$hasNarrator) {
  3250. $result['roles'][] = [
  3251. 'role' => '旁白',
  3252. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  3253. 'pic_prompt' => '',
  3254. 'voice_prompt' => $narratorVoice
  3255. ];
  3256. }
  3257. }
  3258. // 按幕/片段分割 - 兼容"第X幕"和"片段X"两种格式
  3259. $acts = [];
  3260. // 先在开头添加换行符,确保第1幕/片段1也能被正确分割
  3261. $normalizedText = "\n" . $storyboardText;
  3262. $parts = preg_split('/\n\s*##/', $normalizedText);
  3263. foreach ($parts as $part) {
  3264. $part = trim($part);
  3265. if (empty($part)) continue;
  3266. // 兼容"第X幕"和"片段X"两种格式
  3267. if (!preg_match('/^(?:第\d+幕|片段\d+)/', $part)) {
  3268. continue;
  3269. }
  3270. // 分离标题和内容
  3271. $lines = explode("\n", $part, 2);
  3272. $actTitle = trim($lines[0]);
  3273. $actContent = isset($lines[1]) ? trim($lines[1]) : '';
  3274. // 解析标题,提取序号和详细信息
  3275. if (preg_match('/^第(\d+)幕[::]?\s*(.*)$/u', $actTitle, $actTitleMatch)) {
  3276. // 旧格式:第X幕
  3277. $actNumber = intval($actTitleMatch[1]);
  3278. $actDetails = trim($actTitleMatch[2]);
  3279. if (empty($actDetails) || $actDetails === ':' || $actDetails === ':') {
  3280. $actDetails = $actTitle;
  3281. }
  3282. } elseif (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
  3283. // 新格式:片段X
  3284. $actNumber = intval($segmentTitleMatch[1]);
  3285. $actDetails = $actTitle;
  3286. } else {
  3287. $actNumber = count($acts) + 1;
  3288. $actDetails = $actTitle;
  3289. }
  3290. // 提取时长(新格式独有,仅保留数字)
  3291. $actDuration = '';
  3292. if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
  3293. $actDurationStr = trim($actDurationMatch[1]);
  3294. // 提取数字部分(支持整数和小数)
  3295. if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
  3296. $actDuration = $numMatch[1];
  3297. }
  3298. }
  3299. // 解析该幕/片段下的分镜
  3300. $segments = [];
  3301. $segmentPattern = '/分镜(\d+)\s*\n(.*?)(?=\n+\s*分镜\d+|\z)/s';
  3302. preg_match_all($segmentPattern, $actContent, $segmentMatches, PREG_SET_ORDER);
  3303. foreach ($segmentMatches as $segmentMatch) {
  3304. $segmentNumber = intval($segmentMatch[1]);
  3305. $segmentContent = trim($segmentMatch[2]);
  3306. // 解析分镜详细信息
  3307. $segmentData = [
  3308. 'segment_id' => date('YmdHis') . mt_rand(1000, 9999) . str_pad($segmentNumber, 3, "0", STR_PAD_LEFT),
  3309. 'segment_number' => $segmentNumber,
  3310. 'segment_content' => $segmentContent,
  3311. 'description' => '',
  3312. 'composition' => '',
  3313. 'camera_movement' => '',
  3314. 'voice_actor' => '',
  3315. 'dialogue' => '',
  3316. 'frame_type' => '',
  3317. 'scene' => '',
  3318. 'characters' => '',
  3319. 'tail_frame' => '',
  3320. 'emotion' => '中性',
  3321. 'gender' => '0',
  3322. 'speed_ratio' => 0,
  3323. 'loudness_ratio' => 0,
  3324. 'emotion_scale' => 4,
  3325. 'pitch' => 0,
  3326. ];
  3327. // 提取场景
  3328. if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
  3329. $segmentData['scene'] = trim($sceneMatch[1]);
  3330. }
  3331. // 提取画面描述 - 兼容新格式的方括号标注
  3332. if (preg_match('/(?:画面|画面描述|镜头描述|场景描述)[::]\s*(\[.*?\])?\s*([^\n]+)/u', $segmentContent, $descMatch)) {
  3333. $frameTypeInDesc = isset($descMatch[1]) ? trim($descMatch[1], '[]') : '';
  3334. $description = trim($descMatch[2]);
  3335. if (!empty($frameTypeInDesc)) {
  3336. $segmentData['frame_type'] = $frameTypeInDesc;
  3337. }
  3338. $segmentData['description'] = $description;
  3339. }
  3340. // 提取运镜
  3341. if (preg_match('/(?:运镜|运镜调度|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
  3342. $segmentData['camera_movement'] = trim($cameraMatch[1]);
  3343. }
  3344. // 提取配音台词 - 兼容新格式"中文配音:[角色] 台词"
  3345. // 修复:排除背景音效等非台词内容
  3346. if (preg_match('/配音台词[::]\s*(?:中文配音[::]?)?\s*(?:\[([^\]]+)\])?\s*([^\n]*?)(?=\n|$)/u', $segmentContent, $dialogueMatch)) {
  3347. $voiceActor = isset($dialogueMatch[1]) ? trim($dialogueMatch[1]) : '';
  3348. $dialogue = isset($dialogueMatch[2]) ? trim($dialogueMatch[2]) : '';
  3349. // 排除非台词内容(如果匹配到的是空或者是其他字段标记)
  3350. if (!empty($dialogue) && preg_match('/^(?:背景音效|音效|场景|画面|运镜|构图)[::]/u', $dialogue)) {
  3351. $dialogue = ''; // 如果匹配到的是其他字段,清空
  3352. }
  3353. if (!empty($voiceActor)) {
  3354. $segmentData['voice_actor'] = $voiceActor;
  3355. }
  3356. if ($dialogue && $dialogue !== '无') {
  3357. // 确保台词使用中文左右双引号
  3358. $dialogue = preg_replace('/^[""]/u', '"', $dialogue);
  3359. $dialogue = preg_replace('/[""]$/u', '"', $dialogue);
  3360. if (!preg_match('/^["]/', $dialogue)) {
  3361. $dialogue = '"' . $dialogue;
  3362. }
  3363. if (!preg_match('/["]$/', $dialogue)) {
  3364. $dialogue .= '"';
  3365. }
  3366. $segmentData['dialogue'] = $dialogue;
  3367. }
  3368. }
  3369. // 兼容旧格式的台词字段
  3370. // 修复:排除背景音效等非台词内容
  3371. if (empty($segmentData['dialogue']) && preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]*?)(?=\n|$)/u', $segmentContent, $oldDialogueMatch)) {
  3372. $dialogue = trim($oldDialogueMatch[1]);
  3373. // 排除非台词内容
  3374. if (!empty($dialogue) && preg_match('/^(?:背景音效|音效|场景|画面|运镜|构图)[::]/u', $dialogue)) {
  3375. $dialogue = ''; // 如果匹配到的是其他字段,清空
  3376. }
  3377. if ($dialogue && $dialogue !== '无') {
  3378. $dialogue = preg_replace('/^[""]/u', '"', $dialogue);
  3379. $dialogue = preg_replace('/[""]$/u', '"', $dialogue);
  3380. if (!preg_match('/^["]/', $dialogue)) {
  3381. $dialogue = '"' . $dialogue;
  3382. }
  3383. if (!preg_match('/["]$/', $dialogue)) {
  3384. $dialogue .= '"';
  3385. }
  3386. $segmentData['dialogue'] = $dialogue;
  3387. }
  3388. }
  3389. // 兼容旧格式的配音角色字段
  3390. if (empty($segmentData['voice_actor']) && preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
  3391. $segmentData['voice_actor'] = trim($voiceMatch[1]);
  3392. }
  3393. // 提取构图
  3394. if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
  3395. $segmentData['composition'] = trim($compMatch[1]);
  3396. }
  3397. // 提取画面类型
  3398. if (empty($segmentData['frame_type']) && preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
  3399. $segmentData['frame_type'] = trim($frameMatch[1]);
  3400. }
  3401. // 提取出镜角色
  3402. if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
  3403. $segmentData['characters'] = trim($charactersMatch[1]);
  3404. }
  3405. // 提取尾帧描述
  3406. if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
  3407. $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
  3408. }
  3409. $replaceEmptyArr = [];
  3410. // 提取情感
  3411. if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
  3412. $replaceEmptyArr[] = trim($emotionMatch[0]);
  3413. $segmentData['emotion'] = trim($emotionMatch[1]);
  3414. }
  3415. // 提取性别
  3416. if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
  3417. $replaceEmptyArr[] = trim($genderMatch[0]);
  3418. $genderStr = trim($genderMatch[1]);
  3419. if (strpos($genderStr, '男') !== false || $genderStr === '1') {
  3420. $segmentData['gender'] = '1';
  3421. } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
  3422. $segmentData['gender'] = '2';
  3423. } else {
  3424. $segmentData['gender'] = '0';
  3425. }
  3426. }
  3427. // 提取语速
  3428. if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
  3429. $replaceEmptyArr[] = trim($speedMatch[0]);
  3430. $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
  3431. }
  3432. // 提取音量
  3433. if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
  3434. $replaceEmptyArr[] = trim($loudnessMatch[0]);
  3435. $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
  3436. }
  3437. // 提取情感强度
  3438. if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
  3439. $replaceEmptyArr[] = trim($scaleMatch[0]);
  3440. $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
  3441. }
  3442. // 提取音调
  3443. if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
  3444. $replaceEmptyArr[] = trim($pitchMatch[0]);
  3445. $segmentData['pitch'] = (int)trim($pitchMatch[1]);
  3446. }
  3447. $segmentData['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
  3448. $segmentData['segment_content'] = preg_replace('/\n{2,}/', "\n", $segmentData['segment_content']);
  3449. $segmentData['segment_content'] = trim($segmentData['segment_content']);
  3450. $segments[] = $segmentData;
  3451. }
  3452. $acts[] = [
  3453. 'act_number' => $actNumber,
  3454. 'act_title' => $actTitle,
  3455. 'act_details' => $actDetails,
  3456. 'act_duration' => $actDuration,
  3457. 'segments' => $segments
  3458. ];
  3459. }
  3460. $result['acts'] = $acts;
  3461. }
  3462. return $result;
  3463. }
  3464. /**
  3465. * 远程图片压缩(尽可能保持原图 fidelity,压缩到不超过 maxBytes 字节)
  3466. * 采用有损/无损组合策略:保留原始格式尽量不失真,若需要则通过尺寸缩放和质量调节来降低体积。
  3467. *
  3468. * @param string $url 远程图片 URL
  3469. * @param int $maxBytes 最大字节数,默认 3MB
  3470. * @param string|null $aspectRatio 目标长宽比,如 "16:9"、"4:3"、"1:1" 等,null 则保持原图比例
  3471. * @return string|null 返回压缩后的图片二进制数据,失败时返回 null
  3472. */
  3473. function compressRemoteImageUrlToSize(string $url, int $maxBytes = 3 * 1024 * 1024, ?string $aspectRatio = null): ?string
  3474. {
  3475. // 1) 下载图片数据(使用 Guzzle 以避免 allow_url_fopen 依赖)
  3476. try {
  3477. $client = new Client(['timeout' => 30]);
  3478. $response = $client->get($url, ['stream' => true]);
  3479. if ($response->getStatusCode() !== 200) {
  3480. return null;
  3481. }
  3482. $data = $response->getBody()->getContents();
  3483. } catch (\Exception $e) {
  3484. return null;
  3485. }
  3486. if (!$data) return null;
  3487. // 2) 识别图片类型
  3488. $imgInfo = @getimagesizefromstring($data);
  3489. $mime = $imgInfo['mime'] ?? '';
  3490. if ($mime == 'image/jpeg') return null; // JPEG 不做有损压缩
  3491. // 3) 载入图像对象
  3492. $srcImg = @imagecreatefromstring($data);
  3493. if (!$srcImg) {
  3494. return null;
  3495. }
  3496. $origW = imagesx($srcImg);
  3497. $origH = imagesy($srcImg);
  3498. // 3.2) 计算目标尺寸(根据长宽比调整)
  3499. $targetW = $origW;
  3500. $targetH = $origH;
  3501. if ($aspectRatio !== null) {
  3502. // 解析长宽比,如 "16:9" -> [16, 9]
  3503. $validRatios = array_keys(BaseConst::IMAGE_RATIOS);
  3504. if (in_array($aspectRatio, $validRatios)) {
  3505. list($ratioW, $ratioH) = explode(':', $aspectRatio);
  3506. $ratioW = (float)$ratioW;
  3507. $ratioH = (float)$ratioH;
  3508. $targetRatio = $ratioW / $ratioH;
  3509. $currentRatio = $origW / $origH;
  3510. // 根据目标比例裁剪图片
  3511. if ($currentRatio > $targetRatio) {
  3512. // 原图更宽,需要裁剪宽度
  3513. $targetW = (int)round($origH * $targetRatio);
  3514. $targetH = $origH;
  3515. } else {
  3516. // 原图更高,需要裁剪高度
  3517. $targetW = $origW;
  3518. $targetH = (int)round($origW / $targetRatio);
  3519. }
  3520. }
  3521. }
  3522. // 如果需要裁剪,创建裁剪后的图像
  3523. if ($targetW !== $origW || $targetH !== $origH) {
  3524. $croppedImg = imagecreatetruecolor($targetW, $targetH);
  3525. imagealphablending($croppedImg, false);
  3526. imagesavealpha($croppedImg, true);
  3527. // 处理透明背景
  3528. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  3529. $transparent = imagecolorallocatealpha($croppedImg, 0, 0, 0, 127);
  3530. imagefill($croppedImg, 0, 0, $transparent);
  3531. }
  3532. // 居中裁剪
  3533. $srcX = (int)(($origW - $targetW) / 2);
  3534. $srcY = (int)(($origH - $targetH) / 2);
  3535. imagecopy($croppedImg, $srcImg, 0, 0, $srcX, $srcY, $targetW, $targetH);
  3536. // 替换原图
  3537. safeDestroyImage($srcImg);
  3538. $srcImg = $croppedImg;
  3539. $origW = $targetW;
  3540. $origH = $targetH;
  3541. }
  3542. // 3.1) 内部渲染成不同格式的字符串
  3543. $render = function($srcRes, string $mimeType, int $quality) {
  3544. ob_start();
  3545. switch (strtolower($mimeType)) {
  3546. case 'image/jpeg':
  3547. case 'image/jpg':
  3548. case 'image/pjpeg':
  3549. // 输出 JPEG
  3550. imagejpeg($srcRes, null, $quality);
  3551. break;
  3552. case 'image/png':
  3553. // 将 quality 映射到 PNG 的 compression level (0-9)
  3554. $level = (int)round((100 - $quality) / 11.11);
  3555. if ($level < 0) $level = 0;
  3556. if ($level > 9) $level = 9;
  3557. imagepng($srcRes, null, $level);
  3558. break;
  3559. case 'image/webp':
  3560. if (function_exists('imagewebp')) {
  3561. imagewebp($srcRes, null, $quality);
  3562. } else {
  3563. imagejpeg($srcRes, null, $quality);
  3564. }
  3565. break;
  3566. default:
  3567. imagejpeg($srcRes, null, $quality);
  3568. break;
  3569. }
  3570. $out = ob_get_contents();
  3571. ob_end_clean();
  3572. return $out;
  3573. };
  3574. // 4) 尝试策略:尽量保留原图尺寸,逐步降维/降质量,直到 <= maxBytes
  3575. $tryList = [];
  3576. // 原始尺寸,尽量保留
  3577. $tryList[] = ['scale'=>1.0, 'mime'=>$mime, 'quality'=>100];
  3578. // 逐步缩小尺寸
  3579. for ($s = 0.9; $s >= 0.2; $s -= 0.1) {
  3580. $tryList[] = ['scale'=>$s, 'mime'=>$mime, 'quality'=>90];
  3581. }
  3582. // 一系列质量等级(用于 JPEG/WebP)
  3583. $qualityLevels = [95, 90, 85, 75, 60, 50, 40, 30];
  3584. foreach ($qualityLevels as $q) {
  3585. $tryList[] = ['scale'=>1.0, 'mime'=>$mime, 'quality'=>$q];
  3586. }
  3587. $bestData = null;
  3588. foreach ($tryList as $cand) {
  3589. $scale = isset($cand['scale']) ? (float)$cand['scale'] : 1.0;
  3590. $mimeT = $cand['mime'] ?? $mime;
  3591. $quality = isset($cand['quality']) ? (int)$cand['quality'] : 90;
  3592. $w = (int)round($origW * $scale);
  3593. $h = (int)round($origH * $scale);
  3594. $src = $srcImg;
  3595. $tempImg = null;
  3596. if ($scale < 1.0) {
  3597. $tempImg = imagecreatetruecolor($w, $h);
  3598. // 处理透明通道
  3599. imagealphablending($tempImg, false);
  3600. imagesavealpha($tempImg, true);
  3601. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  3602. $transparent = imagecolorallocatealpha($tempImg, 0, 0, 0, 127);
  3603. imagefill($tempImg, 0, 0, $transparent);
  3604. }
  3605. // 确保 $srcImg 有效
  3606. if (!$srcImg || (!is_resource($srcImg) && !($srcImg instanceof \GdImage))) {
  3607. safeDestroyImage($tempImg);
  3608. continue;
  3609. }
  3610. imagecopyresampled($tempImg, $srcImg, 0, 0, 0, 0, $w, $h, $origW, $origH);
  3611. $src = $tempImg;
  3612. }
  3613. $imageBytes = $render($src, $mimeT, $quality);
  3614. if ($tempImg !== null) {
  3615. safeDestroyImage($tempImg);
  3616. }
  3617. if ($imageBytes !== false && strlen($imageBytes) <= $maxBytes) {
  3618. $bestData = $imageBytes;
  3619. break;
  3620. }
  3621. }
  3622. // 5) 回退策略:若仍未达到要求,尝试更大幅度降解到一个合理的小尺寸 JPEG
  3623. if ($bestData === null) {
  3624. $tmpW = max(1, (int)round($origW * 0.5));
  3625. $tmpH = max(1, (int)round($origH * 0.5));
  3626. $tmpImg = imagecreatetruecolor($tmpW, $tmpH);
  3627. imagealphablending($tmpImg, false);
  3628. imagesavealpha($tmpImg, true);
  3629. if (in_array(strtolower($mime), ['image/png','image/webp'])) {
  3630. $transparent = imagecolorallocatealpha($tmpImg, 0, 0, 0, 127);
  3631. imagefill($tmpImg, 0, 0, $transparent);
  3632. }
  3633. imagecopyresampled($tmpImg, $srcImg, 0, 0, 0, 0, $tmpW, $tmpH, $origW, $origH);
  3634. ob_start();
  3635. if (in_array(strtolower($mime), ['image/jpeg','image/jpg','image/pjpeg'])) {
  3636. imagejpeg($tmpImg, null, 75);
  3637. } elseif (strtolower($mime) === 'image/png') {
  3638. imagepng($tmpImg, null, 6);
  3639. } elseif (function_exists('imagewebp')) {
  3640. imagewebp($tmpImg, null, 75);
  3641. } else {
  3642. imagejpeg($tmpImg, null, 75);
  3643. }
  3644. $tmpBytes = ob_get_contents();
  3645. ob_end_clean();
  3646. safeDestroyImage($tmpImg);
  3647. if ($tmpBytes !== '' && strlen($tmpBytes) <= $maxBytes) {
  3648. $bestData = $tmpBytes;
  3649. }
  3650. }
  3651. // 6) 清理
  3652. safeDestroyImage($srcImg);
  3653. return $bestData;
  3654. }
  3655. /**
  3656. * 安全销毁 GD 图像资源(兼容 PHP7.4+ 的资源管理)
  3657. * 通过引用传递并在销毁后置空变量,避免未定义变量的问题
  3658. *
  3659. * @param resource|\GdImage|null &$img GD 图像资源或对象(PHP7.4 为 resource,PHP8.0+ 为 GdImage)
  3660. */
  3661. function safeDestroyImage(&$img)
  3662. {
  3663. if (is_resource($img) || (is_object($img) && $img instanceof \GdImage)) {
  3664. @imagedestroy($img);
  3665. }
  3666. $img = null;
  3667. }
  3668. /**
  3669. * 图片超清(超分辨率)放大
  3670. *
  3671. * 默认使用 FFmpeg(Lanczos + unsharp)进行放大,画质优于 GD;
  3672. * 本地环境(APP_ENV=local)或服务器未安装 FFmpeg 时自动回退到 GD 插值放大,
  3673. * 使用 GD 前会先检查 GD 扩展是否可用,避免报错。
  3674. * 说明:插值放大不会像 AI 超分那样生成全新细节,但零外部 API、可实时完成。
  3675. *
  3676. * 参数:
  3677. * - image_url string 必填 原图 URL(https)或服务器本地绝对路径
  3678. * - target string 可选 目标档位:1080p / 2k / 4k,默认 4k(按长边放大)
  3679. * - width int 可选 指定目标宽度(与 height 同时传时优先于 target)
  3680. * - height int 可选 指定目标高度
  3681. * - format string 可选 输出格式:jpg / png / webp,默认保持原图格式
  3682. * (gif 转 png;webp 带透明转 png、无透明转 jpg)
  3683. * - quality int 可选 输出质量 1-100,默认 95(jpg/webp 生效)
  3684. * - sharpen bool 可选 是否锐化,默认 true
  3685. * - sharpen_amount float 可选 锐化强度 0-2,默认 0.35
  3686. * - upload bool 可选 是否上传 TOS 返回 URL,默认 true;false 时返回 base64
  3687. * - driver string 可选 处理驱动:ffmpeg(默认)/ gd;本地环境强制跳过 ffmpeg
  3688. *
  3689. * @param array $params
  3690. * @return array
  3691. * @throws \InvalidArgumentException|\RuntimeException
  3692. */
  3693. function upscaleImage(array $params): array
  3694. {
  3695. $imageUrl = trim((string)($params['image_url'] ?? ''));
  3696. if ($imageUrl === '') {
  3697. throw new \InvalidArgumentException('image_url不能为空');
  3698. }
  3699. // 读取图片二进制(支持远程URL和本地路径)
  3700. $binary = @file_get_contents($imageUrl);
  3701. if ($binary === false || strlen($binary) === 0) {
  3702. throw new \RuntimeException('图片读取失败: ' . $imageUrl);
  3703. }
  3704. $info = @getimagesizefromstring($binary);
  3705. if ($info === false) {
  3706. throw new \RuntimeException('无法识别的图片格式: ' . $imageUrl);
  3707. }
  3708. $srcWidth = max(1, (int)$info[0]);
  3709. $srcHeight = max(1, (int)$info[1]);
  3710. $srcType = (int)($info[2] ?? IMAGETYPE_PNG);
  3711. // WebP 默认输出格式取决于是否带透明通道(有透明转PNG保留透明,无透明转JPG控制体积)
  3712. $srcHasAlpha = $srcType === IMAGETYPE_WEBP && upscaleImageHasAlpha($binary);
  3713. // 计算目标尺寸
  3714. [$dstWidth, $dstHeight] = upscaleImageResolveTargetDimensions($srcWidth, $srcHeight, $params);
  3715. // 目标尺寸不比原图大时不降采样,直接返回原图
  3716. if ($dstWidth <= $srcWidth && $dstHeight <= $srcHeight) {
  3717. return [
  3718. 'url' => $imageUrl,
  3719. 'base64' => null,
  3720. 'width' => $srcWidth,
  3721. 'height' => $srcHeight,
  3722. 'src_width' => $srcWidth,
  3723. 'src_height' => $srcHeight,
  3724. 'upscaled' => false,
  3725. 'driver' => 'original',
  3726. ];
  3727. }
  3728. // 驱动选择:默认 ffmpeg;本地环境跳过 ffmpeg;ffmpeg 不可用时回退 gd;
  3729. // 使用 gd 前先检查 GD 扩展是否可用,防止报错
  3730. $driver = strtolower((string)($params['driver'] ?? 'ffmpeg'));
  3731. if (!in_array($driver, ['ffmpeg', 'gd'], true)) {
  3732. throw new \InvalidArgumentException('不支持的driver: ' . $driver . '(可选: gd / ffmpeg)');
  3733. }
  3734. $isLocal = env('APP_ENV') === 'local';
  3735. $useFfmpeg = false;
  3736. $useGd = false;
  3737. if ($driver === 'ffmpeg') {
  3738. if ($isLocal) {
  3739. // 本地环境跳过 ffmpeg,使用 GD 超分
  3740. $useGd = true;
  3741. } elseif (upscaleImageIsFfmpegAvailable((string)env('FFMPEG_PATH', 'ffmpeg'))) {
  3742. $useFfmpeg = true;
  3743. } else {
  3744. // 线上未安装 ffmpeg,回退 GD 超分
  3745. $useGd = true;
  3746. }
  3747. } else {
  3748. $useGd = true;
  3749. }
  3750. if ($useGd && !upscaleImageGdAvailable()) {
  3751. $reason = $isLocal ? '本地环境已跳过FFmpeg' : 'FFmpeg不可用';
  3752. throw new \RuntimeException($reason . ',且当前PHP环境缺少GD扩展,无法进行图片超分');
  3753. }
  3754. if ($useFfmpeg) {
  3755. return upscaleImageWithFfmpeg(
  3756. $params,
  3757. $binary,
  3758. $srcType,
  3759. $srcHasAlpha,
  3760. $srcWidth,
  3761. $srcHeight,
  3762. $dstWidth,
  3763. $dstHeight
  3764. );
  3765. }
  3766. return upscaleImageWithGd(
  3767. $params,
  3768. $binary,
  3769. $srcType,
  3770. $srcHasAlpha,
  3771. $srcWidth,
  3772. $srcHeight,
  3773. $dstWidth,
  3774. $dstHeight
  3775. );
  3776. }
  3777. /**
  3778. * 使用 GD 进行图片超分放大(Blackman/Bicubic 插值 + 卷积锐化)
  3779. *
  3780. * @param array $params
  3781. * @param string $binary 图片二进制内容
  3782. * @param int $srcType 原图类型(IMAGETYPE_*)
  3783. * @param bool $srcHasAlpha 原图是否带透明通道(WebP 默认格式判断用)
  3784. * @param int $srcWidth
  3785. * @param int $srcHeight
  3786. * @param int $dstWidth
  3787. * @param int $dstHeight
  3788. * @return array
  3789. * @throws \RuntimeException
  3790. */
  3791. function upscaleImageWithGd(
  3792. array $params,
  3793. string $binary,
  3794. int $srcType,
  3795. bool $srcHasAlpha,
  3796. int $srcWidth,
  3797. int $srcHeight,
  3798. int $dstWidth,
  3799. int $dstHeight
  3800. ): array {
  3801. // 4K 放大峰值内存较高:目标图(4B/像素) + 锐化卷积临时缓冲(4B/像素) + 源图 + 编码缓冲,
  3802. // 按需临时提升内存限制,避免超过默认 128M 报 FatalError
  3803. upscaleImageEnsureMemory(
  3804. $dstWidth * $dstHeight * 8 + $srcWidth * $srcHeight * 4 + 96 * 1024 * 1024
  3805. );
  3806. $srcImg = @imagecreatefromstring($binary);
  3807. if (!$srcImg) {
  3808. throw new \RuntimeException('图片解码失败');
  3809. }
  3810. $dstImg = null;
  3811. try {
  3812. // 高质量插值放大(Blackman 优于 Bicubic,PHP7.4 低版本需回退)
  3813. $filter = defined('IMG_BLACKMAN') ? IMG_BLACKMAN : IMG_BICUBIC;
  3814. $dstImg = imagescale($srcImg, $dstWidth, $dstHeight, $filter);
  3815. if (!$dstImg) {
  3816. throw new \RuntimeException('图片放大失败');
  3817. }
  3818. // 缩放完成后原图不再需要,提前释放以降低内存峰值
  3819. safeDestroyImage($srcImg);
  3820. // 可选锐化,弥补插值放大后的发虚感
  3821. $sharpen = (bool)($params['sharpen'] ?? true);
  3822. $sharpenAmount = (float)($params['sharpen_amount'] ?? 0.35);
  3823. if ($sharpen && $sharpenAmount > 0.01 && function_exists('imageconvolution')) {
  3824. upscaleImageSharpen($dstImg, min(2.0, max(0.01, $sharpenAmount)));
  3825. }
  3826. // 确定输出格式并编码
  3827. $format = upscaleImageResolveOutputFormat($params, $srcType, $srcHasAlpha);
  3828. $quality = max(1, min(100, (int)($params['quality'] ?? 95)));
  3829. $encoded = upscaleImageEncode($dstImg, $format, $quality);
  3830. if ($encoded === null) {
  3831. throw new \RuntimeException('图片编码失败,不支持的输出格式: ' . $format);
  3832. }
  3833. return upscaleImageBuildResult(
  3834. $params,
  3835. $encoded,
  3836. $format,
  3837. $dstWidth,
  3838. $dstHeight,
  3839. $srcWidth,
  3840. $srcHeight,
  3841. 'gd'
  3842. );
  3843. } finally {
  3844. safeDestroyImage($srcImg);
  3845. safeDestroyImage($dstImg);
  3846. }
  3847. }
  3848. /**
  3849. * 使用 FFmpeg 进行图片超分放大(Lanczos 插值 + unsharp 锐化)
  3850. *
  3851. * 与视频超分保持一致的 ffmpeg 用法,仅当 ffmpeg 可用时进入。
  3852. *
  3853. * @param array $params
  3854. * @param string $binary 图片二进制内容
  3855. * @param int $srcType 原图类型(IMAGETYPE_*)
  3856. * @param bool $srcHasAlpha 原图是否带透明通道(WebP 默认格式判断用)
  3857. * @param int $srcWidth
  3858. * @param int $srcHeight
  3859. * @param int $dstWidth
  3860. * @param int $dstHeight
  3861. * @return array
  3862. * @throws \RuntimeException
  3863. */
  3864. function upscaleImageWithFfmpeg(
  3865. array $params,
  3866. string $binary,
  3867. int $srcType,
  3868. bool $srcHasAlpha,
  3869. int $srcWidth,
  3870. int $srcHeight,
  3871. int $dstWidth,
  3872. int $dstHeight
  3873. ): array {
  3874. $ffmpegPath = (string)env('FFMPEG_PATH', 'ffmpeg');
  3875. // 创建临时目录
  3876. $tempDir = storage_path('app/temp/images');
  3877. if (!is_dir($tempDir)) {
  3878. @mkdir($tempDir, 0775, true);
  3879. }
  3880. $format = upscaleImageResolveOutputFormat($params, $srcType, $srcHasAlpha);
  3881. $ext = $format === 'jpeg' ? 'jpg' : $format;
  3882. $quality = max(1, min(100, (int)($params['quality'] ?? 95)));
  3883. $uniqueId = 'img_upscale_' . date('YmdHis') . '_' . uniqid() . '_' . bin2hex(random_bytes(4));
  3884. $inputFile = $tempDir . '/' . $uniqueId . '_input';
  3885. $outputFile = $tempDir . '/' . $uniqueId . '_output.' . $ext;
  3886. try {
  3887. if (file_put_contents($inputFile, $binary) === false) {
  3888. throw new \RuntimeException('图片写入临时文件失败');
  3889. }
  3890. // 构建滤镜链:Lanczos 缩放 + unsharp 锐化(亮度通道)
  3891. $filters = ['scale=' . $dstWidth . ':' . $dstHeight . ':flags=lanczos'];
  3892. $sharpen = (bool)($params['sharpen'] ?? true);
  3893. if ($sharpen) {
  3894. $sharpenAmount = (float)($params['sharpen_amount'] ?? 0.35);
  3895. $luma = number_format(min(2.0, max(0.1, $sharpenAmount * 2)), 2, '.', '');
  3896. $filters[] = 'unsharp=5:5:' . $luma . ':5:5:0.0';
  3897. }
  3898. $encodeArgs = upscaleImageBuildFfmpegEncodeArgs($format, $quality);
  3899. $ffmpegCmd = escapeshellarg($ffmpegPath)
  3900. . ' -y -i ' . escapeshellarg($inputFile)
  3901. . ' -vf ' . escapeshellarg(implode(',', $filters))
  3902. . ' ' . $encodeArgs
  3903. . ' ' . escapeshellarg($outputFile)
  3904. . ' 2>&1';
  3905. dLog('generate')->info('FFmpeg图片放大命令', ['command' => $ffmpegCmd]);
  3906. $output = shell_exec($ffmpegCmd);
  3907. if (!file_exists($outputFile) || filesize($outputFile) === 0) {
  3908. throw new \RuntimeException('FFmpeg图片放大失败: ' . trim((string)$output));
  3909. }
  3910. $encoded = file_get_contents($outputFile);
  3911. if ($encoded === false || strlen($encoded) === 0) {
  3912. throw new \RuntimeException('FFmpeg放大结果读取失败');
  3913. }
  3914. return upscaleImageBuildResult(
  3915. $params,
  3916. $encoded,
  3917. $format,
  3918. $dstWidth,
  3919. $dstHeight,
  3920. $srcWidth,
  3921. $srcHeight,
  3922. 'ffmpeg'
  3923. );
  3924. } finally {
  3925. @unlink($inputFile);
  3926. @unlink($outputFile);
  3927. }
  3928. }
  3929. /**
  3930. * 检查 GD 扩展是否可用于图片超分
  3931. *
  3932. * @return bool
  3933. */
  3934. function upscaleImageGdAvailable(): bool
  3935. {
  3936. return extension_loaded('gd')
  3937. && function_exists('imagecreatefromstring')
  3938. && function_exists('imagescale');
  3939. }
  3940. /**
  3941. * 获取当前 PHP 内存限制(字节),-1 表示无限制
  3942. *
  3943. * @return int
  3944. */
  3945. function upscaleImageMemoryLimitBytes(): int
  3946. {
  3947. $val = trim((string)ini_get('memory_limit'));
  3948. if ($val === '' || $val === '-1') {
  3949. return -1;
  3950. }
  3951. $unit = strtoupper(substr($val, -1));
  3952. $num = (float)$val;
  3953. switch ($unit) {
  3954. case 'G':
  3955. return (int)($num * 1024 * 1024 * 1024);
  3956. case 'M':
  3957. return (int)($num * 1024 * 1024);
  3958. case 'K':
  3959. return (int)($num * 1024);
  3960. default:
  3961. return (int)$num;
  3962. }
  3963. }
  3964. /**
  3965. * 确保 PHP 内存限制满足图片超分需要(只升不降;已是无限制时不做处理)
  3966. *
  3967. * 4K 放大时源图解码、目标图、锐化卷积缓冲同时存在,峰值内存较大,
  3968. * 按目标尺寸估算并临时调高 memory_limit,避免 FatalError OOM。
  3969. *
  3970. * @param int $neededBytes 预估需要的内存字节数
  3971. * @return void
  3972. */
  3973. function upscaleImageEnsureMemory(int $neededBytes): void
  3974. {
  3975. $current = upscaleImageMemoryLimitBytes();
  3976. if ($current > 0 && $neededBytes > $current) {
  3977. @ini_set('memory_limit', (string)(int)ceil($neededBytes / (1024 * 1024)) . 'M');
  3978. }
  3979. }
  3980. /**
  3981. * 检查 ffmpeg 是否可用
  3982. *
  3983. * @param string $ffmpegPath
  3984. * @return bool
  3985. */
  3986. function upscaleImageIsFfmpegAvailable(string $ffmpegPath): bool
  3987. {
  3988. // 配置了绝对路径时直接检查文件
  3989. if (strpos($ffmpegPath, '/') !== false || strpos($ffmpegPath, '\\') !== false) {
  3990. return file_exists($ffmpegPath);
  3991. }
  3992. $cmd = (PHP_OS_FAMILY === 'Windows')
  3993. ? 'where ' . escapeshellarg($ffmpegPath) . ' 2>NUL'
  3994. : 'command -v ' . escapeshellarg($ffmpegPath) . ' 2>/dev/null';
  3995. $output = @shell_exec($cmd);
  3996. return !empty(trim((string)$output));
  3997. }
  3998. /**
  3999. * 构建 ffmpeg 图片输出编码参数
  4000. *
  4001. * @param string $format
  4002. * @param int $quality
  4003. * @return string
  4004. */
  4005. function upscaleImageBuildFfmpegEncodeArgs(string $format, int $quality): string
  4006. {
  4007. switch ($format) {
  4008. case 'jpg':
  4009. case 'jpeg':
  4010. // mjpeg 质量范围 2-31,2 最佳
  4011. return '-frames:v 1 -q:v ' . (2 + (int)round((100 - $quality) / 100 * 29));
  4012. case 'png':
  4013. return '-frames:v 1 -compression_level ' . max(0, min(9, (int)round((100 - $quality) / 10)));
  4014. case 'webp':
  4015. return '-frames:v 1 -q:v ' . (2 + (int)round((100 - $quality) / 100 * 29));
  4016. }
  4017. return '-frames:v 1';
  4018. }
  4019. /**
  4020. * 确定放大后的输出格式
  4021. *
  4022. * @param array $params
  4023. * @param int $srcType
  4024. * @param bool $srcHasAlpha 原图是否带透明通道
  4025. * @return string
  4026. */
  4027. function upscaleImageResolveOutputFormat(array $params, int $srcType, bool $srcHasAlpha = false): string
  4028. {
  4029. $format = strtolower((string)($params['format'] ?? ''));
  4030. if (in_array($format, ['jpg', 'jpeg', 'png', 'webp'], true)) {
  4031. return $format;
  4032. }
  4033. return upscaleImageGuessFormatByType($srcType, $srcHasAlpha);
  4034. }
  4035. /**
  4036. * 根据图片类型推断默认输出格式
  4037. *
  4038. * @param int $srcType
  4039. * @param bool $srcHasAlpha 原图是否带透明通道
  4040. * @return string
  4041. */
  4042. function upscaleImageGuessFormatByType(int $srcType, bool $srcHasAlpha = false): string
  4043. {
  4044. switch ($srcType) {
  4045. case IMAGETYPE_PNG:
  4046. return 'png';
  4047. case IMAGETYPE_WEBP:
  4048. // 带透明通道的 WebP 转 PNG 保留透明,否则转 JPG 控制体积
  4049. return $srcHasAlpha ? 'png' : 'jpg';
  4050. case IMAGETYPE_GIF:
  4051. return 'png'; // GIF 转 PNG,保留透明通道
  4052. case IMAGETYPE_JPEG:
  4053. default:
  4054. return 'jpg';
  4055. }
  4056. }
  4057. /**
  4058. * 检测图片二进制是否带透明通道(目前用于 WebP 默认输出格式判断)
  4059. *
  4060. * 通过解析容器头判断,不整图解码,速度快:
  4061. * - WebP: ALPH 块存在、VP8X 扩展头的 ALPHA 标志位、VP8L 无损格式的 alpha 标志
  4062. *
  4063. * @param string $binary
  4064. * @return bool
  4065. */
  4066. function upscaleImageHasAlpha(string $binary): bool
  4067. {
  4068. if (strlen($binary) < 16 || substr($binary, 0, 4) !== 'RIFF' || substr($binary, 8, 4) !== 'WEBP') {
  4069. return false;
  4070. }
  4071. $offset = 12;
  4072. $len = strlen($binary);
  4073. while ($offset + 8 <= $len) {
  4074. $fourcc = substr($binary, $offset, 4);
  4075. $chunkSize = (int)unpack('V', substr($binary, $offset + 4, 4))[1];
  4076. if ($fourcc === 'ALPH') {
  4077. return true;
  4078. }
  4079. if ($fourcc === 'VP8X' && $chunkSize >= 1) {
  4080. // VP8X 扩展头标志字节:bit4(0x10)=ALPHA
  4081. return (ord($binary[$offset + 8]) & 0x10) !== 0;
  4082. }
  4083. if ($fourcc === 'VP8L' && $chunkSize >= 1) {
  4084. // VP8L 无损格式:首字节 bit2=alpha_is_used
  4085. return ((ord($binary[$offset + 8]) >> 2) & 1) !== 0;
  4086. }
  4087. if ($chunkSize <= 0) {
  4088. break;
  4089. }
  4090. // RIFF 块数据为奇数长度时补 1 字节对齐
  4091. $offset += 8 + $chunkSize + ($chunkSize % 2);
  4092. }
  4093. return false;
  4094. }
  4095. /**
  4096. * 使用卷积矩阵对图片进行锐化(C级实现,速度快)
  4097. *
  4098. * @param resource|\GdImage $img
  4099. * @param float $amount 锐化强度 0-2
  4100. * @return void
  4101. */
  4102. function upscaleImageSharpen($img, float $amount): void
  4103. {
  4104. $neighbor = -$amount;
  4105. $center = 1 + 4 * $amount;
  4106. imageconvolution($img, [
  4107. [0, $neighbor, 0],
  4108. [$neighbor, $center, $neighbor],
  4109. [0, $neighbor, 0],
  4110. ], 1, 0);
  4111. }
  4112. /**
  4113. * 将 GD 图像编码为指定格式的二进制
  4114. *
  4115. * @param resource|\GdImage $img
  4116. * @param string $format
  4117. * @param int $quality
  4118. * @return string|null 失败返回 null
  4119. */
  4120. function upscaleImageEncode($img, string $format, int $quality): ?string
  4121. {
  4122. $encoded = null;
  4123. ob_start();
  4124. try {
  4125. switch ($format) {
  4126. case 'jpg':
  4127. case 'jpeg':
  4128. imagejpeg($img, null, $quality);
  4129. break;
  4130. case 'png':
  4131. // 显式开启 alpha 通道保存,否则透明区域会丢失
  4132. imagesavealpha($img, true);
  4133. // quality 100-1 映射到 PNG 压缩级别 0-9
  4134. imagepng($img, null, (int)round((100 - $quality) / 10));
  4135. break;
  4136. case 'webp':
  4137. if (!function_exists('imagewebp')) {
  4138. throw new \RuntimeException('GD扩展不支持WebP输出');
  4139. }
  4140. imagesavealpha($img, true);
  4141. imagewebp($img, null, $quality);
  4142. break;
  4143. default:
  4144. throw new \RuntimeException('不支持的输出格式: ' . $format);
  4145. }
  4146. $encoded = ob_get_clean();
  4147. } catch (\Throwable $e) {
  4148. ob_end_clean();
  4149. $encoded = null;
  4150. }
  4151. return $encoded;
  4152. }
  4153. /**
  4154. * 组装放大结果:上传 TOS 返回 URL,或返回 base64
  4155. *
  4156. * @param array $params
  4157. * @param string $encoded
  4158. * @param string $format
  4159. * @param int $dstWidth
  4160. * @param int $dstHeight
  4161. * @param int $srcWidth
  4162. * @param int $srcHeight
  4163. * @param string $driver
  4164. * @return array
  4165. * @throws \RuntimeException
  4166. */
  4167. function upscaleImageBuildResult(
  4168. array $params,
  4169. string $encoded,
  4170. string $format,
  4171. int $dstWidth,
  4172. int $dstHeight,
  4173. int $srcWidth,
  4174. int $srcHeight,
  4175. string $driver
  4176. ): array {
  4177. $upload = (bool)($params['upload'] ?? true);
  4178. if ($upload) {
  4179. $ext = $format === 'jpeg' ? 'jpg' : $format;
  4180. $filename = 'upscale_' . date('YmdHis') . '_' . uniqid() . '.' . $ext;
  4181. $url = uploadStreamByTos('image', $encoded, $filename);
  4182. if (!$url) {
  4183. throw new \RuntimeException('放大图片上传TOS失败');
  4184. }
  4185. return [
  4186. 'url' => $url,
  4187. 'base64' => null,
  4188. 'width' => $dstWidth,
  4189. 'height' => $dstHeight,
  4190. 'src_width' => $srcWidth,
  4191. 'src_height' => $srcHeight,
  4192. 'upscaled' => true,
  4193. 'driver' => $driver,
  4194. ];
  4195. }
  4196. $mime = $format === 'jpg' || $format === 'jpeg' ? 'image/jpeg' : 'image/' . $format;
  4197. return [
  4198. 'url' => null,
  4199. 'base64' => 'data:' . $mime . ';base64,' . base64_encode($encoded),
  4200. 'width' => $dstWidth,
  4201. 'height' => $dstHeight,
  4202. 'src_width' => $srcWidth,
  4203. 'src_height' => $srcHeight,
  4204. 'upscaled' => true,
  4205. 'driver' => $driver,
  4206. ];
  4207. }
  4208. /**
  4209. * 计算放大后的目标尺寸
  4210. *
  4211. * @param int $srcWidth
  4212. * @param int $srcHeight
  4213. * @param array $params
  4214. * @return array [width, height]
  4215. */
  4216. function upscaleImageResolveTargetDimensions(int $srcWidth, int $srcHeight, array $params): array
  4217. {
  4218. $width = (int)($params['width'] ?? 0);
  4219. $height = (int)($params['height'] ?? 0);
  4220. // 显式指定宽高时,按指定尺寸处理(支持只传其中一个,另一个按比例计算)
  4221. if ($width > 0 || $height > 0) {
  4222. $ratio = $srcWidth / $srcHeight;
  4223. if ($width > 0 && $height > 0) {
  4224. return [$width, $height];
  4225. }
  4226. return $width > 0
  4227. ? [$width, max(1, (int)round($width / $ratio))]
  4228. : [max(1, (int)round($height * $ratio)), $height];
  4229. }
  4230. // 预设档位:按长边放大(1080p=1920,2K=2560,4K=3840)
  4231. $presets = [
  4232. '1080p' => 1920,
  4233. '2k' => 2560,
  4234. '4k' => 3840,
  4235. ];
  4236. $target = strtolower((string)($params['target'] ?? '4k'));
  4237. $maxEdge = $presets[$target] ?? $presets['4k'];
  4238. $ratio = $srcWidth / $srcHeight;
  4239. if ($srcWidth >= $srcHeight) {
  4240. $dstWidth = $maxEdge;
  4241. $dstHeight = max(1, (int)round($maxEdge / $ratio));
  4242. } else {
  4243. $dstHeight = $maxEdge;
  4244. $dstWidth = max(1, (int)round($maxEdge * $ratio));
  4245. }
  4246. return [$dstWidth, $dstHeight];
  4247. }
  4248. // /**
  4249. // * 使用 Imagick 将远程图片压缩至不超过 maxBytes(默认3MB)内
  4250. // * 目标:在尽量保留原始格式和质量的前提下进行压缩,避免内存暴涨
  4251. // * 依赖:Imagick 扩展与 ImageMagick 库,下载使用 Guzzle 获取图片 blob
  4252. // *
  4253. // * @param string $url
  4254. // * @param int $maxBytes 最大字节数,默认 3*1024*1024
  4255. // * @return string|null 经过压缩后的图片 blob,失败返回 null
  4256. // */
  4257. // function compressRemoteImageUrlToSizeImagick(string $url, int $maxBytes = 3 * 1024 * 1024): ?string
  4258. // {
  4259. // // 兼容性检查
  4260. // if (!extension_loaded('imagick') || !class_exists('Imagick')) {
  4261. // return null;
  4262. // }
  4263. // try {
  4264. // $client = new Client(['timeout' => 30]);
  4265. // // 使用流式下载,将数据写入临时文件,避免一次性加载到内存
  4266. // $response = $client->get($url, ['stream' => true]);
  4267. // if ($response->getStatusCode() !== 200) {
  4268. // return null;
  4269. // }
  4270. // $body = $response->getBody();
  4271. // $tmp = tmpfile();
  4272. // if ($tmp === false) {
  4273. // return null;
  4274. // }
  4275. // stream_copy_to_stream($body, $tmp);
  4276. // rewind($tmp);
  4277. // $imagick = new Imagick();
  4278. // $imagick->readImageFile($tmp);
  4279. // $origW = $imagick->getImageWidth();
  4280. // $origH = $imagick->getImageHeight();
  4281. // $format = strtolower($imagick->getImageFormat());
  4282. // // 尝试序列:尺寸缩放 + 质量调节
  4283. // $scales = [1.0, 0.9, 0.8, 0.6, 0.4, 0.25];
  4284. // $qualities = [95, 90, 85, 75, 60, 40, 30, 20];
  4285. // $bestBlob = null;
  4286. // foreach ($scales as $scale) {
  4287. // foreach ($qualities as $q) {
  4288. // $clone = clone $imagick;
  4289. // if ($scale < 1.0) {
  4290. // $w = (int)round($origW * $scale);
  4291. // $h = (int)round($origH * $scale);
  4292. // if ($w < 1 || $h < 1) {
  4293. // $clone->destroy();
  4294. // continue;
  4295. // }
  4296. // $clone->resizeImage($w, $h, Imagick::FILTER_LANCZOS, 1);
  4297. // }
  4298. // $clone->setImageFormat($format);
  4299. // $clone->setImageCompressionQuality($q);
  4300. // $blob = $clone->getImageBlob();
  4301. // $clone->destroy();
  4302. // if ($blob !== false && strlen($blob) <= $maxBytes) {
  4303. // $bestBlob = $blob;
  4304. // break 2;
  4305. // }
  4306. // }
  4307. // }
  4308. // if ($bestBlob !== null) {
  4309. // $imagick->destroy();
  4310. // fclose($tmp);
  4311. // return $bestBlob;
  4312. // }
  4313. // // 回退:尝试强制输出为当前格式的一个中等质量版本
  4314. // $fallback = clone $imagick;
  4315. // $fallback->setImageFormat($format);
  4316. // $fallback->setImageCompressionQuality(75);
  4317. // $blob = $fallback->getImageBlob();
  4318. // $fallback->destroy();
  4319. // $imagick->destroy();
  4320. // fclose($tmp);
  4321. // if ($blob !== false && strlen($blob) <= $maxBytes) {
  4322. // return $blob;
  4323. // }
  4324. // } catch (\Exception $e) {
  4325. // return null;
  4326. // }
  4327. // return null;
  4328. // }
  4329. /**
  4330. * 将主体列表文本拆分为主体数组
  4331. *
  4332. * @param string $rolesText 主体列表文本内容
  4333. * @return array 主体名称数组
  4334. */
  4335. function parseRolesFromText(string $rolesText): array
  4336. {
  4337. if (empty($rolesText)) {
  4338. return [];
  4339. }
  4340. $roles = [];
  4341. // 按行分割文本
  4342. $lines = explode("\n", $rolesText);
  4343. foreach ($lines as $line) {
  4344. $line = trim($line);
  4345. if (empty($line)) {
  4346. continue;
  4347. }
  4348. if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
  4349. $role = trim($charMatch[1]);
  4350. $description = trim($charMatch[2]);
  4351. $timbreName = null;
  4352. // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
  4353. $picPrompt = null;
  4354. if (preg_match('/^(.*?)\{([^}]+)\}\{\{([^}]+)\}\}\s*$/u', $description, $fullMatch)) {
  4355. // 匹配格式:主体描述{主体图片提示词}{{音色名}}
  4356. $description = trim($fullMatch[1]);
  4357. $picPrompt = trim($fullMatch[2]);
  4358. $timbreName = trim($fullMatch[3]);
  4359. } elseif (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
  4360. // 兼容旧格式:主体描述{{音色名}}
  4361. $description = trim($timbreMatch[1]);
  4362. $timbreName = trim($timbreMatch[2]);
  4363. }
  4364. $roleData = [
  4365. 'role' => $role,
  4366. 'description' => $description,
  4367. ];
  4368. // 如果有主体图片提示词,添加到数组中
  4369. if ($picPrompt) {
  4370. $roleData['pic_prompt'] = $picPrompt;
  4371. }
  4372. if ($timbreName) {
  4373. $timbre = DB::table('mp_timbres')
  4374. ->where('is_enabled', 1)
  4375. ->where('timbre_name', 'like', "%{$timbreName}%")
  4376. ->orderBy('id')
  4377. ->select('timbre_type', 'audio_url')
  4378. ->first();
  4379. if ($timbre) {
  4380. $roleData['voice_name'] = $timbreName;
  4381. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  4382. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  4383. }
  4384. }else {
  4385. // 从描述或人物提示词中获取"男"或"女",赋予默认音色,获取不到则使用旁白音色
  4386. if ($picPrompt) {
  4387. if (strstr($picPrompt, '男')) {
  4388. $roleData['voice_name'] = '阳光青年';
  4389. }elseif (strstr($picPrompt, '女')) {
  4390. $roleData['voice_name'] = '爽快思思';
  4391. }else {
  4392. if ($description) {
  4393. if (strstr($description, '男')) {
  4394. $roleData['voice_name'] = '阳光青年';
  4395. }elseif (strstr($description, '女')) {
  4396. $roleData['voice_name'] = '爽快思思';
  4397. }else {
  4398. $roleData['voice_name'] = '旁白';
  4399. }
  4400. }
  4401. }
  4402. }
  4403. if (!empty($roleData['voice_name'])) {
  4404. if ($roleData['voice_name'] == '旁白') {
  4405. $roleData['voice_type'] = 'zh_male_linjiananhai_moon_bigtts';
  4406. $roleData['voice_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav';
  4407. }else {
  4408. $timbre = DB::table('mp_timbres')
  4409. ->where('is_enabled', 1)
  4410. ->where('timbre_name', 'like', "%".$roleData['voice_name']."%")
  4411. ->orderBy('id')
  4412. ->select('timbre_type', 'audio_url')
  4413. ->first();
  4414. if ($timbre) {
  4415. $roleData['voice_type'] = getProp($timbre, 'timbre_type');
  4416. $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
  4417. }
  4418. }
  4419. }
  4420. }
  4421. $roles[] = $roleData;
  4422. }
  4423. }
  4424. $hasNarrator = false;
  4425. foreach ($roles as $role) {
  4426. if (getProp($role, 'role') === '旁白') {
  4427. $hasNarrator = true;
  4428. break;
  4429. }
  4430. }
  4431. if (!$hasNarrator) {
  4432. $roles[] = [
  4433. 'role' => '旁白',
  4434. 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
  4435. 'pic_prompt' => '',
  4436. 'voice_name' => '旁白',
  4437. 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
  4438. 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
  4439. ];
  4440. }
  4441. return $roles;
  4442. }
  4443. /**
  4444. * 将场景列表文本拆分为场景数组
  4445. *
  4446. * @param string $rolesText 场景列表列表文本内容
  4447. * @return array 场景名称数组
  4448. */
  4449. function parseScenesFromText(string $scenesText): array
  4450. {
  4451. if (empty($scenesText)) {
  4452. return [];
  4453. }
  4454. $scenes = [];
  4455. // 按行分割文本
  4456. $lines = explode("\n", $scenesText);
  4457. foreach ($lines as $line) {
  4458. $line = trim($line);
  4459. if (empty($line)) {
  4460. continue;
  4461. }
  4462. $line = str_replace(':', ':', $line);
  4463. if (strstr($line, ':')) {
  4464. $line_arr = explode(':', $line, 2);
  4465. if (count($line_arr) == 2) {
  4466. $scene = trim($line_arr[0]);
  4467. $description = trim($line_arr[1]);
  4468. $picPrompt = null;
  4469. // 检查描述末尾是否有{场景图片提示词}格式
  4470. if (preg_match('/^(.*?)\{([^}]+)\}\s*$/u', $description, $promptMatch)) {
  4471. // 匹配格式:场景描述{场景图片提示词}
  4472. $description = trim($promptMatch[1]);
  4473. $picPrompt = trim($promptMatch[2]);
  4474. }
  4475. $sceneData = [
  4476. 'scene' => $scene,
  4477. 'description' => $description,
  4478. ];
  4479. // 如果有场景图片提示词,添加到数组中
  4480. if ($picPrompt) {
  4481. $sceneData['pic_prompt'] = $picPrompt;
  4482. }
  4483. $scenes[] = $sceneData;
  4484. }
  4485. }
  4486. }
  4487. return $scenes;
  4488. }
  4489. /**
  4490. * 将道具列表文本拆分为道具数组
  4491. *
  4492. * @param string $propsText 道具列表文本内容
  4493. * @return array 道具数组
  4494. */
  4495. function parsePropsFromText(string $propsText): array
  4496. {
  4497. if (empty($propsText)) {
  4498. return [];
  4499. }
  4500. $props = [];
  4501. // 按行分割文本
  4502. $lines = explode("\n", $propsText);
  4503. foreach ($lines as $line) {
  4504. $line = trim($line);
  4505. if (empty($line)) {
  4506. continue;
  4507. }
  4508. $line = str_replace(':', ':', $line);
  4509. if (strstr($line, ':')) {
  4510. $line_arr = explode(':', $line, 2);
  4511. if (count($line_arr) == 2) {
  4512. $prop = trim($line_arr[0]);
  4513. $description = trim($line_arr[1]);
  4514. $picPrompt = null;
  4515. // 检查描述末尾是否有{道具图片提示词}格式
  4516. if (preg_match('/^(.*?)\{([^}]+)\}\s*$/u', $description, $promptMatch)) {
  4517. // 匹配格式:道具描述{道具图片提示词}
  4518. $description = trim($promptMatch[1]);
  4519. $picPrompt = trim($promptMatch[2]);
  4520. }
  4521. $propData = [
  4522. 'prop' => $prop,
  4523. 'description' => $description,
  4524. ];
  4525. // 如果有道具图片提示词,添加到数组中
  4526. if ($picPrompt) {
  4527. $propData['pic_prompt'] = $picPrompt;
  4528. }
  4529. $props[] = $propData;
  4530. }
  4531. }
  4532. }
  4533. return $props;
  4534. }
  4535. // 拆分章节内容
  4536. function splitContent($content) {
  4537. // 根据章节标题来拆分章节内容,返回包含标题和内容的二维数组
  4538. $chapters = [];
  4539. // 匹配章节标题格式:
  4540. // 1. 标题可能独占一行,也可能在正文末尾或中间
  4541. // 2. 格式支持:
  4542. // - **第一集**
  4543. // - 第一集:
  4544. // - ###第1章 重生
  4545. // - ##第2章 相救
  4546. // - 第三章 共处一室
  4547. // 3. 支持阿拉伯数字(0-9)和中文数字(一二两三四五六七八九十百千万)
  4548. // 4. 支持章节关键字:章、节、集、幕、场、回、话
  4549. // 5. "第"字与数字、数字与章节关键字之间可能有空格
  4550. // 6. 前后可能有#、*、·等修饰符号,后面可能有冒号、空格、标题文字等
  4551. // 先预处理:仅在"第X集/章"位于某段正文末尾(可能因未换行粘连)时补换行使其独立成行;
  4552. // 支持正文末尾直接跟"第X集"或"第X集:标题"的粘连格式;
  4553. // 正文中间出现的"第X集"字样(如"真假千金文里第一集就被赶出厂")保持不动,避免误判为章节标题
  4554. $content = preg_replace('/([^ \t\r\f\v\n#*·\-_=])(第\s*[一二两三四五六七八九十百千万0-9]+\s*[章节集幕场话])((?:[::][^\n]*|[ \t\r\f\v]*))$/mu', "$1\n\n$2$3", $content);
  4555. // 匹配章节标题:标题必须位于行首(前面仅允许空格/Tab 或 #*·-_= 等修饰符),避免跨行误匹配
  4556. $pattern = '/^[#*·\-_= \t]*第\s*([一二两三四五六七八九十百千万0-9]+)\s*([章节集幕场话]).*$/mu';
  4557. // 用正则找出所有章节标题的位置
  4558. if (preg_match_all($pattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
  4559. $titleCount = count($matches[0]);
  4560. // 先导集/先导片等“先导”段落:位于第一个章节标题之前时,作为第一集的内容并入第一个分组
  4561. $prologue = '';
  4562. $prologueAttached = false;
  4563. $firstTitlePos = $matches[0][0][1];
  4564. if ($firstTitlePos > 0) {
  4565. $leadingText = substr($content, 0, $firstTitlePos);
  4566. // 只截取“先导”标题及其之后的内容(标题之前的书名等信息仍按原逻辑忽略)
  4567. if (preg_match('/^[#*·\-_= \t]*先[ \t]*导[^\n]*$/mu', $leadingText, $prologueMatch, PREG_OFFSET_CAPTURE)) {
  4568. $prologue = trim(substr($leadingText, $prologueMatch[0][1]));
  4569. }
  4570. }
  4571. for ($i = 0; $i < $titleCount; $i++) {
  4572. // 获取当前章节标题
  4573. $titleLine = trim($matches[0][$i][0]);
  4574. // 去除标题开头的特殊符号
  4575. $cleanTitle = preg_replace('/^[#*·\-_=\s]+/u', '', $titleLine);
  4576. // 去除标题结尾的冒号和特殊符号
  4577. $cleanTitle = preg_replace('/[#*·::\s]+$/u', '', $cleanTitle);
  4578. $cleanTitle = trim($cleanTitle);
  4579. // 获取当前标题的结束位置
  4580. $titleEndPos = $matches[0][$i][1] + strlen($matches[0][$i][0]);
  4581. // 获取下一个章节标题的开始位置(如果存在)
  4582. $nextTitlePos = ($i < $titleCount - 1) ? $matches[0][$i + 1][1] : strlen($content);
  4583. // 提取章节内容(从标题结束到下一个标题开始)
  4584. $chapterContent = substr($content, $titleEndPos, $nextTitlePos - $titleEndPos);
  4585. // 清理内容:去除前后空白和分隔线
  4586. $chapterContent = trim($chapterContent);
  4587. $chapterContent = preg_replace('/^[\-\s]+/u', '', $chapterContent);
  4588. $chapterContent = preg_replace('/[\-\s]+$/u', '', $chapterContent);
  4589. if (!empty($cleanTitle) && !empty($chapterContent)) {
  4590. // 第一个分组(第一集)融合先导集/先导片等内容
  4591. if (!$prologueAttached && $prologue !== '') {
  4592. $chapterContent = $prologue . "\n\n" . $chapterContent;
  4593. $prologueAttached = true;
  4594. }
  4595. $chapters[] = [
  4596. 'title' => $cleanTitle,
  4597. 'content' => $chapterContent
  4598. ];
  4599. }
  4600. }
  4601. } else {
  4602. // 如果没有匹配到章节,返回整个内容
  4603. $chapters[] = [
  4604. 'title' => '',
  4605. 'content' => $content
  4606. ];
  4607. }
  4608. return $chapters;
  4609. }
  4610. /**
  4611. * 记录日志到数据库
  4612. *
  4613. * @param string $channel 日志频道/目录名
  4614. * @param string $level 日志级别 (info, error, warning, debug)
  4615. * @param string $message 日志信息
  4616. * @param array $context 日志详细数据
  4617. * @return void
  4618. */
  4619. function logDB($channel, $level, $message, $context = []) {
  4620. try {
  4621. // 获取调用堆栈信息
  4622. $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
  4623. $caller = $trace[1] ?? $trace[0];
  4624. // 在 create 之前添加:
  4625. $jsonEncoded = json_encode($context, JSON_INVALID_UTF8_SUBSTITUTE);
  4626. $cleanContext = json_decode($jsonEncoded, true);
  4627. \App\Models\SystemLog::create([
  4628. 'channel' => $channel,
  4629. 'level' => $level,
  4630. 'message' => $message,
  4631. 'context' => $cleanContext,
  4632. 'file' => $caller['file'] ?? '',
  4633. 'line' => $caller['line'] ?? 0,
  4634. 'log_time' => date('Y-m-d H:i:s'),
  4635. ]);
  4636. } catch (\Exception $e) {
  4637. // 记录日志失败时不影响主流程
  4638. \Log::error('记录日志到数据库失败: ' . $e->getMessage());
  4639. }
  4640. }
  4641. function filterScriptContent($content) {
  4642. if (!$content) return '';
  4643. if (mb_substr($content, 0, 6) == '确认分镜大纲') return '确认分镜大纲';
  4644. if (mb_strlen($content) > 500) return '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。';
  4645. return $content;
  4646. }
  4647. /**
  4648. * 根据错误信息返回映射错误说明
  4649. *
  4650. * @param string $errorMessage 错误信息
  4651. * @return string 映射后的错误说明
  4652. */
  4653. function mapErrorMessage($errorMessage)
  4654. {
  4655. if (empty($errorMessage)) {
  4656. return '未知异常,请重试';
  4657. }
  4658. // 配置类错误:原文返回,避免走模型翻译后语义走样
  4659. if (stripos($errorMessage, 'NB_SEEDANCE_API_KEY') !== false
  4660. || stripos($errorMessage, 'NB_SEEDANCE_ASSET_AK') !== false) {
  4661. return $errorMessage;
  4662. }
  4663. // 按优先级匹配错误信息
  4664. if (stripos($errorMessage, 'OutputImageSensitiveContentDetected') !== false) {
  4665. return '输出结果含有敏感词,请重试';
  4666. }
  4667. // GPT/Azure 内容审核拦截(prompt 触发 content management policy)
  4668. if (stripos($errorMessage, 'content_filter') !== false
  4669. || stripos($errorMessage, 'content management policy') !== false
  4670. || stripos($errorMessage, 'was filtered due to the prompt') !== false) {
  4671. return '输入内容触发模型安全审核,请调整过于血腥、暴力等描述后重试';
  4672. }
  4673. if (stripos($errorMessage, '系统繁忙,请稍后再试') !== false) {
  4674. return '系统繁忙,请稍后再试';
  4675. }
  4676. if (stripos($errorMessage, 'InternalServiceError') !== false) {
  4677. return '外部服务器网络错误,请稍后重试';
  4678. }
  4679. if (stripos($errorMessage, 'InputTextSensitiveContentDetected') !== false) {
  4680. return '输入文字含有敏感词,请调整后重试';
  4681. }
  4682. if (stripos($errorMessage, 'ServerOverloaded') !== false) {
  4683. return '当前系统过载,请稍后重试';
  4684. }
  4685. if (stripos($errorMessage, 'The request failed because the output video may be related to copyright restrictions') !== false) {
  4686. return '输出视频可能涉及版权限制,请更换内容或降低相似度后重试。';
  4687. }
  4688. // 未命中预设错误:调用模型生成友好翻译并缓存,避免轮询场景重复消耗
  4689. try {
  4690. $cacheKey = 'unknown_error_translate_' . md5((string)$errorMessage);
  4691. return Cache::remember($cacheKey, 600, function () use ($errorMessage) {
  4692. $friendlyError = app(\App\Services\DeepSeek\DeepSeekService::class)->analyzeErrorMessage($errorMessage);
  4693. return $friendlyError ?: '未知异常,请重试';
  4694. });
  4695. } catch (\Throwable $e) {
  4696. return '未知异常,请重试';
  4697. }
  4698. }
  4699. /**
  4700. * 视频超分:480p档升级到720p,720p档升级到1080p(使用FFmpeg本地超分)
  4701. * 目标分辨率按源视频方向强制为标准档位(横屏 16:9 / 竖屏 9:16)
  4702. * 可通过 $targetResolution 显式指定目标档位(720p/1080p),显式指定优先;未指定时按源档位自动识别
  4703. *
  4704. * @param string|resource $videoSource 视频URL地址或视频内容(字符串)
  4705. * @param string $prefix 上传文件夹前缀(如:'video')
  4706. * @param bool $isContent 是否为视频内容而非URL(默认false)
  4707. * @param string $targetResolution 显式目标档位:'720p' 或 '1080p',空字符串表示自动识别
  4708. * @return string 返回超分后的视频URL,失败返回原视频URL或空字符串
  4709. */
  4710. function upgrade480pTo720p($videoSource, $prefix = 'video', $isContent = false, $targetResolution = '')
  4711. {
  4712. if (env('APP_ENV') == 'local') {
  4713. return $isContent ? '' : $videoSource;
  4714. }
  4715. try {
  4716. // 创建临时目录
  4717. $tempDir = storage_path('app/temp/videos');
  4718. if (!is_dir($tempDir)) {
  4719. mkdir($tempDir, 0775, true);
  4720. chmod($tempDir, 0775);
  4721. }
  4722. // 生成唯一文件名
  4723. $uniqueId = uniqid('video_upgrade_') . bin2hex(random_bytes(4));
  4724. // 处理输入源
  4725. if ($isContent) {
  4726. // 如果是视频内容,直接写入临时文件
  4727. dLog('video_upgrade')->info('检测到视频内容,写入临时文件');
  4728. $inputFile = $tempDir . '/' . $uniqueId . '_input.mp4';
  4729. if (file_put_contents($inputFile, $videoSource) === false) {
  4730. dLog('video_upgrade')->error('视频内容写入临时文件失败');
  4731. return '';
  4732. }
  4733. $videoUrl = '视频内容';
  4734. } else {
  4735. // 如果是URL,下载视频
  4736. $videoUrl = $videoSource;
  4737. $videoExt = getVideoExtFromUrl($videoUrl);
  4738. $inputFile = $tempDir . '/' . $uniqueId . '_input' . $videoExt;
  4739. // 下载视频到本地
  4740. dLog('video_upgrade')->info('开始下载视频进行升级', ['url' => $videoUrl]);
  4741. $client = new \GuzzleHttp\Client(['timeout' => 300]);
  4742. $response = $client->get($videoUrl);
  4743. $fileContent = $response->getBody()->getContents();
  4744. if (file_put_contents($inputFile, $fileContent) === false) {
  4745. dLog('video_upgrade')->error('视频文件写入失败', [
  4746. 'url' => $videoUrl,
  4747. 'file' => $inputFile
  4748. ]);
  4749. return $videoUrl;
  4750. }
  4751. }
  4752. chmod($inputFile, 0664);
  4753. if (!file_exists($inputFile)) {
  4754. dLog('video_upgrade')->error('视频文件不存在', ['file' => $inputFile]);
  4755. return $isContent ? '' : $videoSource;
  4756. }
  4757. $inputFileSize = filesize($inputFile);
  4758. dLog('video_upgrade')->info('视频准备完成,开始超分', [
  4759. 'source' => $videoUrl,
  4760. 'size' => $inputFileSize,
  4761. 'size_mb' => round($inputFileSize / 1024 / 1024, 2) . 'MB'
  4762. ]);
  4763. // 获取视频分辨率,根据源档位选择目标档位
  4764. // 使用 ffprobe 的 JSON 输出,这是最可靠的方式
  4765. $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
  4766. $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
  4767. // 获取视频流信息,使用JSON格式输出
  4768. $probeCmd = "$ffprobePath -v quiet -print_format json -show_streams \"$inputFile\"";
  4769. $probeOutput = shell_exec($probeCmd);
  4770. $videoInfo = json_decode($probeOutput, true);
  4771. $width = 0;
  4772. $height = 0;
  4773. // 从JSON中提取视频流的宽高
  4774. if (isset($videoInfo['streams']) && is_array($videoInfo['streams'])) {
  4775. foreach ($videoInfo['streams'] as $stream) {
  4776. if (isset($stream['codec_type']) && $stream['codec_type'] === 'video') {
  4777. $width = isset($stream['width']) ? (int)$stream['width'] : 0;
  4778. $height = isset($stream['height']) ? (int)$stream['height'] : 0;
  4779. break;
  4780. }
  4781. }
  4782. }
  4783. dLog('video_upgrade')->info('ffprobe获取视频分辨率', [
  4784. 'width' => $width,
  4785. 'height' => $height,
  4786. 'json_parsed' => !empty($videoInfo)
  4787. ]);
  4788. // 根据视频方向决定目标标准分辨率
  4789. // 480p档 -> 720p(720*1280 竖屏 / 1280*720 横屏)
  4790. // 720p档 -> 1080p(1080*1920 竖屏 / 1920*1080 横屏)
  4791. $shortSide = min($width, $height);
  4792. $targetShortSide = 0;
  4793. $targetResolution = strtolower(trim($targetResolution));
  4794. if (in_array($targetResolution, ['720p', '1080p'], true)) {
  4795. // 显式指定档位优先(不允许降级:源短边超过目标档位则跳过)
  4796. $targetShortSide = $targetResolution === '720p' ? 720 : 1080;
  4797. if ($shortSide > $targetShortSide + 40) {
  4798. dLog('video_upgrade')->info('视频分辨率高于目标档位,跳过超分', [
  4799. 'width' => $width,
  4800. 'height' => $height,
  4801. 'target' => $targetResolution
  4802. ]);
  4803. @unlink($inputFile);
  4804. return $isContent ? '' : $videoSource;
  4805. }
  4806. } elseif ($shortSide > 0 && abs($shortSide - 480) <= 40) {
  4807. $targetShortSide = 720;
  4808. } elseif ($shortSide > 0 && abs($shortSide - 720) <= 40) {
  4809. $targetShortSide = 1080;
  4810. } else {
  4811. // 自动识别且非480p/720p档,无需超分,直接返回原视频
  4812. dLog('video_upgrade')->info('视频不属于480p/720p档位,跳过超分', [
  4813. 'width' => $width,
  4814. 'height' => $height,
  4815. 'short_side' => $shortSide
  4816. ]);
  4817. @unlink($inputFile);
  4818. return $isContent ? '' : $videoSource;
  4819. }
  4820. $isPortrait = $width > 0 && $height > 0 && $width < $height;
  4821. $targetWidth = $isPortrait ? $targetShortSide : (int)round($targetShortSide * 16 / 9);
  4822. $targetHeight = $isPortrait ? (int)round($targetShortSide * 16 / 9) : $targetShortSide;
  4823. $scaleFilter = "scale={$targetWidth}:{$targetHeight}:flags=lanczos:force_original_aspect_ratio=decrease,pad={$targetWidth}:{$targetHeight}:(ow-iw)/2:(oh-ih)/2";
  4824. if ($width > 0 && $height > 0) {
  4825. dLog('video_upgrade')->info('缩放计算详情', [
  4826. 'original' => "{$width}x{$height}",
  4827. 'target' => "{$targetWidth}x{$targetHeight}",
  4828. 'is_portrait' => $width < $height ? 'yes' : 'no'
  4829. ]);
  4830. dLog('video_upgrade')->info(($isPortrait ? '竖屏' : '横屏') . '视频超分', [
  4831. 'original_size' => "{$width}x{$height}",
  4832. 'target_size' => "{$targetWidth}x{$targetHeight}",
  4833. 'scale_filter' => $scaleFilter
  4834. ]);
  4835. } else {
  4836. // 无法获取分辨率,默认按横屏处理
  4837. $targetWidth = (int)round($targetShortSide * 16 / 9);
  4838. $targetHeight = $targetShortSide;
  4839. $scaleFilter = "scale={$targetWidth}:{$targetHeight}:flags=lanczos:force_original_aspect_ratio=decrease,pad={$targetWidth}:{$targetHeight}:(ow-iw)/2:(oh-ih)/2";
  4840. dLog('video_upgrade')->warning('无法获取视频分辨率,默认按横屏处理');
  4841. }
  4842. // 输出文件路径
  4843. $outputFile = $tempDir . '/' . $uniqueId . '_output.mp4';
  4844. // 使用FFmpeg超分视频,使用高质量的Lanczos算法和锐化滤镜
  4845. // 滤镜说明:
  4846. // 1. scale: 使用Lanczos算法缩放并保持宽高比,pad补边到标准分辨率(720p或1080p档)
  4847. // 2. unsharp=5:5:1.0:5:5:0.5: 锐化滤镜,增强细节
  4848. // - 5:5:1.0 表示亮度锐化(luma_msize_x:luma_msize_y:luma_amount)
  4849. // - 5:5:0.5 表示色度锐化(chroma_msize_x:chroma_msize_y:chroma_amount)
  4850. // 3. hqdn3d=1.5:1.5:6:6: 降噪滤镜,轻微降噪以改善画质
  4851. // - 参数分别为亮度空间/时间和色度空间/时间
  4852. // 编码参数:
  4853. // -c:v libx264: 使用H.264编码器
  4854. // -preset slow: 编码速度预设(ultrafast到veryslow,越慢压缩率越高)
  4855. // 可选值: ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow
  4856. // 推荐: slow(平衡速度和压缩率)或 slower(更好压缩)
  4857. // -crf 23: 恒定质量模式(0-51,数值越小画质越好,文件越大)
  4858. // 推荐值: 18(高质量,大文件) 23(默认,平衡) 28(中等质量,小文件)
  4859. // 当前设置可在.env中配置 VIDEO_UPGRADE_CRF,默认23
  4860. // -tune film: 针对电影内容优化(适合AI生成的动画视频)
  4861. // -profile:v high: 使用H.264 High Profile,支持更高级的压缩特性
  4862. // -level 4.1: H.264 level 4.1,支持更高的码率和分辨率
  4863. // -pix_fmt yuv420p: 像素格式,确保兼容性
  4864. // -c:a aac -b:a 128k: 音频使用AAC编码,128kbps(比直接copy更小)
  4865. // -movflags +faststart: 优化网络播放
  4866. // 从环境变量读取编码参数,允许灵活配置
  4867. $crf = env('VIDEO_UPGRADE_CRF', 23); // CRF值: 18(高质量) 23(默认) 28(小文件)
  4868. $preset = env('VIDEO_UPGRADE_PRESET', 'slow'); // 编码速度: slow, slower, veryslow
  4869. $audioBitrate = env('VIDEO_UPGRADE_AUDIO_BITRATE', '128k'); // 音频码率
  4870. $unsharp = env('VIDEO_UPGRADE_UNSHARP', '5:5:0.5:5:5:0.2');
  4871. dLog('video_upgrade')->info('使用编码参数', [
  4872. 'crf' => $crf,
  4873. 'preset' => $preset,
  4874. 'audio_bitrate' => $audioBitrate
  4875. ]);
  4876. $ffmpegCmd = "$ffmpegPath -i \"$inputFile\" -vf \"$scaleFilter,unsharp=$unsharp,hqdn3d=1.5:1.5:6:6\" -c:v libx264 -preset $preset -crf $crf -tune film -profile:v high -level 4.1 -pix_fmt yuv420p -c:a aac -b:a $audioBitrate -movflags +faststart -y \"$outputFile\" 2>&1";
  4877. dLog('video_upgrade')->info('开始FFmpeg超分视频', ['command' => $ffmpegCmd]);
  4878. $output = shell_exec($ffmpegCmd);
  4879. if (!file_exists($outputFile)) {
  4880. dLog('video_upgrade')->error('视频升级失败', [
  4881. 'input' => $inputFile,
  4882. 'output' => $output
  4883. ]);
  4884. @unlink($inputFile);
  4885. return $isContent ? '' : $videoSource;
  4886. }
  4887. chmod($outputFile, 0664);
  4888. // 验证输出视频的分辨率(使用JSON格式,最可靠)
  4889. $verifyCmd = "$ffprobePath -v quiet -print_format json -show_streams \"$outputFile\"";
  4890. $verifyOutput = shell_exec($verifyCmd);
  4891. $outputVideoInfo = json_decode($verifyOutput, true);
  4892. $outputWidth = 0;
  4893. $outputHeight = 0;
  4894. if (isset($outputVideoInfo['streams']) && is_array($outputVideoInfo['streams'])) {
  4895. foreach ($outputVideoInfo['streams'] as $stream) {
  4896. if (isset($stream['codec_type']) && $stream['codec_type'] === 'video') {
  4897. $outputWidth = isset($stream['width']) ? (int)$stream['width'] : 0;
  4898. $outputHeight = isset($stream['height']) ? (int)$stream['height'] : 0;
  4899. break;
  4900. }
  4901. }
  4902. }
  4903. dLog('video_upgrade')->info('输出视频分辨率验证', [
  4904. 'input_original' => "{$width}x{$height}",
  4905. 'expected' => ($width > 0 && $height > 0) ? ($width < $height ? '720x1280' : '1280x720') : '1280x720',
  4906. 'actual_output' => "{$outputWidth}x{$outputHeight}",
  4907. 'success' => ($outputWidth > 0 && $outputHeight > 0)
  4908. ]);
  4909. $outputFileSize = filesize($outputFile);
  4910. $sizeRatio = round($outputFileSize / $inputFileSize, 2);
  4911. dLog('video_upgrade')->info('视频升级成功', [
  4912. 'input_size' => round($inputFileSize / 1024 / 1024, 2) . 'MB',
  4913. 'output_size' => round($outputFileSize / 1024 / 1024, 2) . 'MB',
  4914. 'size_ratio' => $sizeRatio
  4915. ]);
  4916. // 上传到TOS - 使用普通的文件名,不暴露是升级后的视频
  4917. $video_name = 'ai_generation_' . time() . '_' . uniqid() . '.mp4';
  4918. $uploadedUrl = uploadStreamByTos($prefix, file_get_contents($outputFile), $video_name);
  4919. // 清理临时文件
  4920. @unlink($inputFile);
  4921. @unlink($outputFile);
  4922. if (!$uploadedUrl) {
  4923. dLog('video_upgrade')->error('升级后的视频上传失败');
  4924. return $isContent ? '' : $videoSource;
  4925. }
  4926. dLog('video_upgrade')->info('升级后的视频上传成功', ['url' => $uploadedUrl]);
  4927. return $uploadedUrl;
  4928. } catch (\Exception $e) {
  4929. dLog('video_upgrade')->error('视频升级过程出错', [
  4930. 'source' => $isContent ? '视频内容' : $videoSource,
  4931. 'error' => $e->getMessage()
  4932. ]);
  4933. // 清理可能存在的临时文件
  4934. if (isset($inputFile) && file_exists($inputFile)) {
  4935. @unlink($inputFile);
  4936. }
  4937. if (isset($outputFile) && file_exists($outputFile)) {
  4938. @unlink($outputFile);
  4939. }
  4940. // 出错时返回原视频URL或空字符串
  4941. return $isContent ? '' : $videoSource;
  4942. }
  4943. }
  4944. /**
  4945. * 拼接画风前缀;前缀为空时返回空字符串,避免提示词以句号开头
  4946. *
  4947. * @param mixed $prefix
  4948. * @return string
  4949. */
  4950. function buildStylePromptPrefix($prefix): string
  4951. {
  4952. $prefix = trim((string)$prefix);
  4953. return $prefix === '' ? '' : $prefix . "。\n";
  4954. }
  4955. /**
  4956. * 取模型配置表中"可用且排序最高"的模型名(mp_text_models / mp_image_models / mp_video_models)
  4957. *
  4958. * 口径:is_enabled=1,按 order 倒序、id 倒序取第一个;无可用模型时直接报错。
  4959. *
  4960. * @param string $table 配置表名
  4961. * @param bool $aceModeOnly 仅取 ace_mode=1(仅视频表使用)
  4962. * @return string
  4963. */
  4964. function defaultModelByTable(string $table, bool $aceModeOnly = false): string
  4965. {
  4966. $query = DB::table($table)->where('is_enabled', 1);
  4967. if ($aceModeOnly) {
  4968. $query->where('ace_mode', 1);
  4969. }
  4970. $model = $query->orderBy('order', 'desc')->orderBy('id', 'desc')->value('model');
  4971. if (empty($model)) {
  4972. \App\Libs\Utils::throwError('20003:暂无可用模型,请先在后台配置并启用');
  4973. }
  4974. return (string)$model;
  4975. }
  4976. /** 默认文字模型(mp_text_models) */
  4977. function defaultTextModel(): string
  4978. {
  4979. return defaultModelByTable('mp_text_models');
  4980. }
  4981. /** 默认图片模型(mp_image_models) */
  4982. function defaultImageModel(): string
  4983. {
  4984. return defaultModelByTable('mp_image_models');
  4985. }
  4986. /** 默认视频模型(mp_video_models);$aceModeOnly=true 时仅取 ace_mode=1 的模型 */
  4987. function defaultVideoModel(bool $aceModeOnly = false): string
  4988. {
  4989. return defaultModelByTable('mp_video_models', $aceModeOnly);
  4990. }