| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431 |
- <?php
- use App\Consts\BaseConst;
- use GuzzleHttp\Client;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Log;
- use Monolog\Handler\StreamHandler;
- use Monolog\Logger;
- use OSS\OssClient;
- use OSS\Core\OssException;
- use Tos\TosClient;
- use Tos\Exception\TosClientException;
- use Tos\Exception\TosServerException;
- use Tos\Model\PutObjectInput;
- // use Imagick;
- /**
- * 截取字符串
- *
- * @param $string
- * @param $length
- * @param bool $append
- * @return array|string
- */
- function sysSubStr($string, $length, $append = false)
- {
- if (strlen($string) <= $length) {
- return $string;
- }
- $i = 0;
- $stringLast = [];
- while ($i < $length) {
- $stringTMP = mb_substr($string, $i, 1);
- if (ord($stringTMP) >= 224) {
- $stringTMP = mb_substr($string, $i, 3);
- $i += 3;
- } elseif (ord($stringTMP) >= 192) {
- $stringTMP = mb_substr($string, $i, 2);
- $i += 2;
- } else {
- ++$i;
- }
- $stringLast[] = $stringTMP;
- }
- $stringLast = implode('', $stringLast);
- if ($append) {
- $stringLast .= '...';
- }
- return $stringLast;
- }
- /**
- * 自定义日志
- *
- * @param $name
- * @param string $filename
- * @return \Illuminate\Log\Writer
- */
- function myLog($name, $filename = '')
- {
- if (!$filename) {
- $filename = $name;
- }
- $filename = $filename . '.log';
- $logger = new Logger($name);
- $writer = new \Illuminate\Log\Writer($logger);
- $writer->useDailyFiles(storage_path('logs/' . $filename));
- return $writer;
- }
- /**
- * 业务调试日志
- *
- * @return Logger
- */
- function commonLog()
- {
- $name = 'common';
- $filename = $name . '.log';
- $logger = new Logger($name);
- $logger->pushHandler(new StreamHandler(storage_path('logs/' . $filename), 'debug'));
- return $logger;
- }
- /**
- * @param $name
- * @return Logger
- */
- function dLog($name)
- {
- $filename = $name . '-' . date('Y-m-d') . '.log';
- $logger = new Logger($name);
- $logger->pushHandler(new StreamHandler(storage_path('logs/' . $filename), 'debug'));
- return $logger;
- }
- /**
- * 获取对象或数组的属性值
- *
- * @param $param
- * @param $key
- * @param string $default
- * @return mixed|string
- */
- function getProp($param, $key, $default = '')
- {
- $result = $default;
- if (is_object($param) && isset($param->$key)) {
- $result = $param->$key;
- }
- if (is_array($param) && isset($param[$key])) {
- $result = $param[$key];
- }
- return $result;
- }
- /**
- * @param $data
- * @param array $trans
- * @return array
- */
- function assetData($data, $trans = []): array
- {
- $result = [];
- if (empty($data)) {
- return $result;
- }
- if (empty($trans)) {
- return $data;
- }
- foreach ($trans as $tran) {
- [$originKey, $newKey, $conv, $default] = [$tran['o'], $tran['n'], $tran['conv'], $tran['default']];
- if (isset($data[$originKey])) {
- $result[$newKey] = $conv(getProp($data, $originKey, $default));
- }
- }
- return $result;
- }
- /**
- * 随机数
- *
- * @param int $num
- * @return string
- * @throws Exception
- */
- function random($num = 16)
- {
- $bytes = random_bytes($num);
- return bin2hex($bytes);
- }
- /**
- * 生成订单
- *
- * @param string $prefix 订单前缀
- * @return string
- */
- function generateOrderSn($prefix = '')
- {
- return $prefix . date('YmdHis') . getMillisecond() . rand(1000, 9999);
- }
- /**
- * 分页数据
- *
- * @param $data
- * @return array
- */
- function getMeta($data)
- {
- $currentPage = (int)$data->currentPage();
- $lastPage = (int)$data->lastPage();
- return [
- 'current_page' => $currentPage,
- 'next_page' => $currentPage >= $lastPage ? $lastPage : ++$currentPage,
- 'last_page' => $lastPage,
- 'per_page' => (int)$data->perPage(),
- 'total' => (int)$data->total(),
- 'is_end' => !$data->hasMorePages(),
- 'next_page_url' => (string)$data->nextPageUrl(),
- 'prev_page_url' => (string)$data->previousPageUrl()
- ];
- }
- /**
- * 钉钉通知异常
- *
- * @param $message
- */
- function sendNotice($message)
- {
- $webHook = env('DD_WEB_HOOK');
- $data = [
- 'msgtype' => 'text',
- 'text' => [
- 'content' => $message
- ],
- 'at' => [
- 'isAll' => true
- ]
- ];
- // 异步发送
- $client = new GuzzleHttp\Client();
- $client->post($webHook, ['json' => $data]);
- }
- /**
- * 判断数据是合法的json数据
- *
- * @param $string
- * @return bool
- */
- function is_json($string)
- {
- json_decode($string);
- return (json_last_error() == JSON_ERROR_NONE);
- }
- /**
- * 获取ip地址
- *
- * @return mixed|string
- */
- function getIpAddr()
- {
- $ipaddress = '';
- if (isset($_SERVER['HTTP_CLIENT_IP']))
- $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
- else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
- $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
- else if (isset($_SERVER['HTTP_X_FORWARDED']))
- $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
- else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
- $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
- else if (isset($_SERVER['HTTP_FORWARDED']))
- $ipaddress = $_SERVER['HTTP_FORWARDED'];
- else if (isset($_SERVER['REMOTE_ADDR']))
- $ipaddress = $_SERVER['REMOTE_ADDR'];
- else
- $ipaddress = 'UNKNOWN';
- return $ipaddress;
- }
- /**
- * @param int $num
- * @return bool|string
- * @throws Exception
- */
- function randStr($num = 5)
- {
- $str = 'QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm';
- return substr(str_shuffle($str), random_int(0, strlen($str) - 11), $num);
- }
- /**
- * 上传文件(火山云tos)
- *
- * @param $prefix 文件夹前缀
- * @param $file 文件二进制
- * @param $filename 文件名(不带后缀)
- * @return mixed
- */
- function uploadFileByTos($prefix, $file, $filename='')
- {
- if (!$filename) $filename = randStr(10) . '.' . $file->getClientOriginalExtension();
- else $filename = $filename . '.' . $file->getClientOriginalExtension();
- try {
- $client = new TosClient([
- 'region' => env('VOLC_REGION'),
- 'endpoint' => env('VOLC_END_POINT'),
- 'ak' => env('VOLC_AK'),
- 'sk' => env('VOLC_SK'),
- ]);
-
- $stream = fopen($file->getRealPath(), 'r');
- $input = new PutObjectInput(env('VOLC_BUCKET'), "$prefix/$filename", $stream);
- $output = $client->putObject($input);
- if ($output->getRequestId()) {
- return "https://".env('VOLC_BUCKET').'.'.env('VOLC_END_POINT')."/$prefix/$filename";
- }
- } catch (TosClientException $ex) {
- dLog('exception')->info('saveToTos', [$ex->getMessage()]);
- } catch (TosServerException $ex) {
- dLog('exception')->info('saveToTos', [$ex->getRequestId(), $ex->getStatusCode(), $ex->getErrorCode()]);
- }
- return '';
- }
- /**
- * 上传文件流(火山云tos)
- *
- * @param $prefix 文件夹前缀
- * @param $file 文件二进制
- * @param $filename 文件名(带后缀)
- * @return mixed
- */
- function uploadStreamByTos($prefix, $stream, $filename)
- {
- try {
- $client = new TosClient([
- 'region' => env('VOLC_REGION'),
- 'endpoint' => env('VOLC_END_POINT'),
- 'ak' => env('VOLC_AK'),
- 'sk' => env('VOLC_SK'),
- ]);
- $input = new PutObjectInput(env('VOLC_BUCKET'), "$prefix/$filename", $stream);
- $output = $client->putObject($input);
- if ($output->getRequestId()) {
- return "https://".env('VOLC_BUCKET').'.'.env('VOLC_END_POINT')."/$prefix/$filename";
- }
- } catch (TosClientException $ex) {
- dLog('exception')->info('saveToTos', [$ex->getMessage()]);
- } catch (TosServerException $ex) {
- dLog('exception')->info('saveToTos', [$ex->getRequestId(), $ex->getStatusCode(), $ex->getErrorCode()]);
- }
- return '';
- }
- // 从图片URL获取图片扩展名
- function getImgExtFromUrl(string $url): ?string {
- $imageInfo = @getimagesize($url);
- if ($imageInfo !== false) {
- // 返回MIME类型
- return mimeToExt($imageInfo['mime']);
- // 或者返回文件扩展名
- // return image_type_to_extension($imageInfo[2], false);
- }
- return null;
- }
- /**
- * 从视频URL获取视频扩展名
- * 通过下载文件头部字节来识别真实的视频格式
- *
- * @param string $url 视频URL
- * @return string 返回扩展名(如 .mp4),默认 .mp4
- */
- function getVideoExtFromUrl(string $url): string {
- try {
- // 方法1:从URL路径中提取扩展名
- $parsedUrl = parse_url($url);
- $path = $parsedUrl['path'] ?? '';
- $pathInfo = pathinfo($path);
- $extension = $pathInfo['extension'] ?? '';
-
- if ($extension) {
- // 验证是否为常见视频格式
- $validVideoExts = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v', 'mpeg', 'mpg'];
- if (in_array(strtolower($extension), $validVideoExts)) {
- return '.' . strtolower($extension);
- }
- }
-
- // 方法2:下载文件头部字节来识别格式
- $client = new \GuzzleHttp\Client(['timeout' => 30]);
-
- // 先尝试HEAD请求获取Content-Type
- try {
- $response = $client->head($url);
- $contentType = $response->getHeader('Content-Type')[0] ?? '';
-
- // 根据Content-Type映射扩展名
- $mimeMap = [
- 'video/mp4' => '.mp4',
- 'video/x-msvideo' => '.avi',
- 'video/quicktime' => '.mov',
- 'video/x-ms-wmv' => '.wmv',
- 'video/x-flv' => '.flv',
- 'video/x-matroska' => '.mkv',
- 'video/webm' => '.webm',
- 'video/mpeg' => '.mpeg',
- ];
-
- if (isset($mimeMap[$contentType])) {
- return $mimeMap[$contentType];
- }
- } catch (\Exception $e) {
- // HEAD请求失败,继续尝试其他方法
- }
-
- // 方法3:下载前几个字节分析文件魔数(Magic Number)
- $response = $client->get($url, [
- 'stream' => true,
- 'headers' => [
- 'Range' => 'bytes=0-31' // 只下载前32字节
- ]
- ]);
-
- $header = $response->getBody()->read(32);
-
- // 根据文件魔数判断格式
- // MP4/M4V: 以 ftyp 开头(偏移4-8字节)
- if (strpos($header, 'ftyp') !== false) {
- // 进一步判断是否为 M4V
- if (strpos($header, 'M4V') !== false || strpos($header, 'm4v') !== false) {
- return '.m4v';
- }
- return '.mp4';
- }
-
- // AVI: 以 RIFF 开头,包含 AVI
- if (substr($header, 0, 4) === 'RIFF' && strpos($header, 'AVI') !== false) {
- return '.avi';
- }
-
- // MOV: 包含 moov 或 mdat
- if (strpos($header, 'moov') !== false || strpos($header, 'mdat') !== false) {
- return '.mov';
- }
-
- // FLV: 以 FLV 开头
- if (substr($header, 0, 3) === 'FLV') {
- return '.flv';
- }
-
- // WebM: 以 0x1A 0x45 0xDF 0xA3 开头
- if (ord($header[0]) === 0x1A && ord($header[1]) === 0x45 &&
- ord($header[2]) === 0xDF && ord($header[3]) === 0xA3) {
- return '.webm';
- }
-
- // MKV: 与WebM类似,但包含 matroska
- if (strpos($header, 'matroska') !== false) {
- return '.mkv';
- }
-
- // MPEG: 以 0x00 0x00 0x01 开头
- if (ord($header[0]) === 0x00 && ord($header[1]) === 0x00 && ord($header[2]) === 0x01) {
- return '.mpeg';
- }
-
- // 默认返回 .mp4(最常见的格式)
- return '.mp4';
-
- } catch (\Exception $e) {
- // 出错时返回默认格式
- return '.mp4';
- }
- }
- // 辅助 MIME 映射函数
- function mimeToExt(string $mime): ?string {
- $map = [
- 'audio/wav' => '.wav',
- 'audio/x-ms-wma' => '.wma',
- 'video/x-ms-wmv' => '.wmv',
- 'video/mp4' => '.mp4',
- 'audio/mpeg' => '.mp3',
- 'audio/amr' => '.amr',
- 'application/vnd.rn-realmedia' => '.rm',
- 'audio/mid' => '.mid',
- 'image/bmp' => '.bmp',
- 'image/gif' => '.gif',
- 'image/png' => '.png',
- 'image/tiff' => '.tiff',
- 'image/jpeg' => '.jpg',
- 'application/pdf' => '.pdf',
- ];
- return $map[$mime] ?? null;
- }
- /**
- * 上传文件(阿里云oss)
- *
- * @param $prefix 文件夹前缀
- * @param $file 文件二进制
- * @param $filename 文件名(不带后缀)
- * @return mixed
- */
- function uploadFile($prefix, $file, $filename='')
- {
- // 阿里云主账号
- $accessKeyId = env('OSS_ACCESS_ID');
- $accessKeySecret = env('OSS_ACCESS_KEY');
- $endpoint = env('OSS_END_POINT');
- $bucket = env('OSS_BUCKET');
- if (!$filename) $filename = randStr(10) . '.' . $file->getClientOriginalExtension();
- else $filename = $filename . '.' . $file->getClientOriginalExtension();
- // 设置文件名称。
- $object = env('OSS_DIRECTORY') . '/' . $prefix . '/' . $filename;
- $provider = new \OSS\Credentials\StaticCredentialsProvider($accessKeyId, $accessKeySecret);
- try {
- $configs = [
- "provider" => $provider,
- "endpoint" => $endpoint,
- "signatureVersion" => 'v4',
- "region" => "cn-hangzhou"
- ];
- $ossClient = new OssClient($configs);
- $uploadRes = $ossClient->uploadFile($bucket, $object, $file->path());
- } catch (OssException $e) {
- dLog('exception')->info('saveImageToOss', [$e->getMessage()]);
- return '';
- }
- // 替换域名
- if (!isset($uploadRes['oss-request-url'])) return '';
- $url = str_ireplace('zw-ai.oss-cn-hangzhou.aliyuncs.com', 'cdn-zwai.ycsd.cn', $uploadRes['oss-request-url']);
- $url = urldecode($url);
- return str_ireplace('http://', 'https://', $url);
- }
- /**
- * 上传文件流(阿里云oss)
- *
- * @param $prefix 文件夹前缀
- * @param $file 文件二进制
- * @param $filename 文件名(带后缀)
- * @return mixed
- */
- function uploadStreamToOss($prefix, $stream, $filename) {
- $accessKeyId = env('OSS_ACCESS_ID');
- $accessKeySecret = env('OSS_ACCESS_KEY');
- $endpoint = env('OSS_END_POINT');
- $bucket = env('OSS_BUCKET');
- // if (!$filename) $filename = randStr(10) . '.' . $file->getClientOriginalExtension();
- // 设置文件名称。
- $object = env('OSS_DIRECTORY') . '/' . $prefix . '/' . $filename;
- $provider = new \OSS\Credentials\StaticCredentialsProvider($accessKeyId, $accessKeySecret);
- try{
- $configs = [
- "provider" => $provider,
- "endpoint" => $endpoint,
- "signatureVersion" => 'v4',
- "region"=> "cn-hangzhou"
- ];
- $ossClient = new OssClient($configs);
- $uploadRes = $ossClient->putObject($bucket, $object, $stream);
- } catch (OssException $e) {
- dLog('exception')->info('saveImageToOss', [$e->getMessage()]);
- return '';
- }
- // 替换域名
- if (!isset($uploadRes['oss-request-url'])) return '';
- $url = str_ireplace('zw-ai.oss-cn-hangzhou.aliyuncs.com', 'cdn-zwai.ycsd.cn', $uploadRes['oss-request-url']);
- $url = urldecode($url);
- return str_ireplace('http://', 'https://', $url);
- }
- /**
- * 下载文件到本地
- *
- * @param $object
- * @param $localFile
- * @return string
- */
- function downloadFile($object, $localFile)
- {
- // 阿里云主账号
- $accessKeyId = env('OSS_ACCESS_ID');
- $accessKeySecret = env('OSS_ACCESS_KEY');
- $endpoint = env('OSS_END_POINT');
- $bucket = env('OSS_BUCKET');
- try {
- $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
- $ossClient->getObject($bucket, $object, [
- OssClient::OSS_FILE_DOWNLOAD => $localFile
- ]);
- } catch (OssException $e) {
- printf($e->getMessage());
- return '';
- }
- }
- /**
- * 上传封面
- *
- * @param $file
- * @return string
- * @throws Exception
- */
- function uploadCoverFile($file)
- {
- // 阿里云主账号
- $accessKeyId = env('OSS_ACCESS_ID');
- $accessKeySecret = env('OSS_ACCESS_KEY');
- $endpoint = env('OSS_END_POINT');
- $bucket = env('OSS_BUCKET');
- // 设置文件名称。
- $object = 'books/cover/' . randStr(10) . '.' . $file->getClientOriginalExtension();
- try {
- $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
- $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path());
- } catch (OssException $e) {
- printf($e->getMessage());
- return '';
- }
- $urlArr = parse_url($ossImgBackData['oss-request-url']);
- return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
- }
- function uploadAgreementFile($file)
- {
- // 阿里云主账号
- $accessKeyId = env('OSS_ACCESS_ID');
- $accessKeySecret = env('OSS_ACCESS_KEY');
- $endpoint = env('OSS_END_POINT');
- $bucket = env('OSS_BUCKET');
- $file_name = $file->getClientOriginalName();
- $file_name = str_replace('.' . $file->getClientOriginalExtension(), '', $file_name);
- // 设置文件名称。
- $object = 'books/contract/' . $file_name . '-' . date('YmdHi') . '.' . $file->getClientOriginalExtension();
- try {
- $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
- $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file);
- } catch (OssException $e) {
- printf($e->getMessage());
- return '';
- }
- $urlArr = parse_url($ossImgBackData['oss-request-url']);
- return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . urldecode(getProp($urlArr, 'path')) : '';
- }
- /**
- * 上传wap推荐图片
- *
- * @param $file
- * @param $filename
- * @return string
- * @throws Exception
- */
- function uploadWapRecommendPic($file, $filename)
- {
- // 阿里云主账号
- $accessKeyId = env('OSS_ACCESS_ID');
- $accessKeySecret = env('OSS_ACCESS_KEY');
- $endpoint = env('OSS_END_POINT');
- $bucket = env('OSS_BUCKET_YCSD');
- // 设置文件名称。
- $object = 'ycsd_web_3nd/images/homebanners/' . $filename . '.' . $file->getClientOriginalExtension();
- try {
- $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
- $options = array(
- OssClient::OSS_HEADERS => array(
- 'Content-Type' => 'image/jpeg',
- 'Content-Disposition' => 'inline'
- ),
- );
- $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path(), $options);
- } catch (OssException $e) {
- printf($e->getMessage());
- return '';
- }
- $urlArr = parse_url($ossImgBackData['oss-request-url']);
- return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
- }
- /**
- * @param $path
- * @return Generator
- */
- function readFileContent($path)
- {
- if ($handle = fopen($path, 'r')) {
- while (!feof($handle)) {
- yield trim(fgets($handle));
- }
- fclose($handle);
- }
- }
- function exportFileCsv(array $headers, array $data, string $filename)
- {
- header("Content-type:application/vnd.ms-excel");
- header("Content-Disposition:attachment;filename=" . $filename . ".csv");
- $headers = collect($headers)->map(function ($item) {
- return "\"" . mb_convert_encoding($item, "GBK", "UTF-8") . "\"";
- })->all();
- echo implode(",", $headers);
- echo "\r\n";
- foreach ($data as $item) {
- $rows = collect($item)->map(function ($row) {
- return "\"" . mb_convert_encoding(is_numeric($row) && strlen($row) > 12 ? "'" . $row : $row, "GBK", "UTF-8") . "\"";
- })->all();
- echo implode(",", $rows);
- echo "\r\n";
- }
- exit();
- }
- //function exportFileCsv(array $header, array $data, string $filename) {
- // header('Content-Encoding: UTF-8');
- // header("Content-type:application/vnd.ms-excel;charset=UTF-8");
- // header('Content-Disposition: attachment;filename="' . $filename . '.csv"');
- //
- // //打开php标准输出流
- // $fp = fopen('php://output', 'a');
- //
- // //添加BOM头,以UTF8编码导出CSV文件,如果文件头未添加BOM头,打开会出现乱码。
- // fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
- // //添加导出标题
- // fputcsv($fp, $header);
- //
- // foreach ($data as $k => $item) {
- // fputcsv($fp, $item);
- // if ($k % 5000 == 0) {
- // //每1万条数据就刷新缓冲区
- // ob_flush();
- // flush();
- // }
- // }
- // exit();
- //}
- //function exportFileCsv(array $header, array $data, string $filename) {
- //
- // header('Content-Type: application/vnd.ms-excel');
- // header('Content-Disposition: attachment;filename="'.$filename.'.csv"');
- // header('Cache-Control: max-age=0');
- //
- // //打开PHP文件句柄,php://output 表示直接输出到浏览器
- // $fp = fopen('php://output', 'a');
- //
- // //输出Excel列名信息
- // foreach ($header as $key => $value) {
- // //CSV的Excel支持GBK编码,一定要转换,否则乱码
- // $header[$key] = iconv('utf-8', 'gbk', $value);
- // }
- //
- // //将数据通过fputcsv写到文件句柄
- // fputcsv($fp, $header);
- //
- // //计数器
- // $num = 0;
- //
- // //每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
- // $limit = 10000;
- //
- // //逐行取出数据,不浪费内存
- // $count = count($data);
- // for ($i = 0; $i < $count; $i++) {
- //
- // $num++;
- //
- // //刷新一下输出buffer,防止由于数据过多造成问题
- // if ($limit == $num) {
- // ob_flush();
- // flush();
- // $num = 0;
- // }
- //
- // $row = $data[$i];
- // foreach ($row as $key => $value) {
- // $row[$key] = iconv('utf-8', 'gbk', $value);
- // }
- //
- // fputcsv($fp, $row);
- // }
- // exit();
- //}
- // 获取除空格外的字数
- function getSize(string $content)
- {
- $content = preg_replace('/\s+/', '', $content);
- return mb_strlen($content, 'utf-8');
- }
- // 获取word字符数(不计空格)
- function getChargeSize(string $content)
- {
- //判断是否存在替换字符
- $is_replace_count = substr_count($content, "龘");
- try {
- //先将回车换行符做特殊处理
- $str = preg_replace('/(\r\n+|\s+| +)/', "龘", $content);
- //处理英文字符数字,连续字母、数字、英文符号视为一个单词
- $str = preg_replace('/[a-z_A-Z0-9-\.!@#\$%\\\^&\*\)\(\+=\{\}\[\]\/",\'<>~`\?:;|]/', "m", $str);
- //合并字符m,连续字母、数字、英文符号视为一个单词
- $str = preg_replace('/m+/', "*", $str);
- //去掉回车换行符
- $str = preg_replace('/龘+/', "", $str);
- //返回字数
- return mb_strlen($str) + $is_replace_count;
- } catch (\Exception $e) {
- return 0;
- }
- }
- // 将阿拉伯数字转换成中文
- function chineseNum($figure, $capital = false, $mode = true)
- {
- if ($figure == '0') return '零';
- $numberChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
- $unitChar = ['', '十', '百', '千', '', '万', '亿', '兆', '京', '垓', '秭', '穣', '沟', '涧', '正', '载', '极', '恒河沙', '阿僧祇', '那由他', '不可思议', '无量大数'];
- if ($capital !== false) {
- $numberChar = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
- $unitChar = ['', '拾', '佰', '仟', '', '万', '亿', '兆', '京', '垓', '秭', '穣', '沟', '涧', '正', '载', '极', '恒河沙', '阿僧祇', '那由他', '不可思议', '无量大数'];
- }
- $dec = "点";
- $target = '';
- $matches = [];
- if ($mode) {
- preg_match("/^0*(\d*)\.?(\d*)/", $figure, $matches);
- } else {
- preg_match("/(\d*)\.?(\d*)/", $figure, $matches);
- }
- list(, $number, $point) = $matches;
- if ($point) {
- $target = $dec . chineseNum($point, $capital, false);
- }
- if (!$number) {
- return $target;
- }
- $str = strrev($number);
- for ($i = 0; $i < strlen($str); $i++) {
- $out[$i] = $numberChar[$str[$i]];
- if ($mode === false) {
- continue;
- }
- $out[$i] .= $str[$i] != '0' ? $unitChar[$i % 4] : '';
- if ($i > 0 && $str[$i] + $str[$i - 1] == 0) {
- $out[$i] = '';
- }
- if ($i % 4 == 0) {
- $temp = substr($str, $i, 4);
- $out[$i] = str_replace($numberChar[0], '', $out[$i]);
- if (strrev($temp) > 0) {
- $out[$i] .= $unitChar[4 + floor($i / 4)];
- } else {
- $out[$i] .= $numberChar[0];
- }
- }
- }
- $result = join('', array_reverse($out)) . $target;
- return mb_substr($result, 0, 2) == '一十' ? mb_substr($result, 1) : $result;
- }
- function addPrefix($str)
- {
- if (!$str) return '';
- if (mb_substr($str, 0, 4) == 'http') return $str;
- if (mb_substr($str, 0, 5) == 'https') return $str;
- if (mb_substr($str, 0, 7) == '/books/') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com' . $str;
- if (mb_substr($str, 0, 6) == '/card/') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com' . $str;
- if (mb_substr($str, 0, 15) == 'uploader/idcard') return 'http://zwcontent.oss-cn-hangzhou.aliyuncs.com/' . $str;
- if (mb_substr($str, 0, 6) == '/cover') return 'https://cdn-newyc.ycsd.cn/ycsd_cover/covermiddle' . mb_substr($str, 6);
- if (mb_substr($str, 0, 8) == '/images/') return 'https://cdn-newyc.ycsd.cn/ycsd_cover' . $str;
- }
- /**
- * 章节内容排版
- *
- * @param $content
- * @return string
- */
- function filterContent($content)
- {
- if (!$content) return '';
- $content = str_replace(
- [' ', '<br /><br />', '<br>', '<br />', ' ', '<p>', '</p>', '“', '”', '…', '‘', '’', '—'],
- [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...', '‘', '’', '-'],
- $content);
- $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
- // 段落首字母前加两个中文空格
- $string = explode(PHP_EOL, $content);
- foreach ($string as $line => $text) {
- $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' '], '', $string[$line]);
- if (!$string[$line]) {
- unset($string[$line]);
- } else {
- $string[$line] = $string[$line] . PHP_EOL;
- // if (mb_substr($string[$line], 0, 1) == ' ') {
- // $string[$line] = str_replace(' ', '', $string[$line]); // 去除多个空格
- // $string[$line] = ' ' . $string[$line].PHP_EOL;
- // }
- // if (mb_substr($string[$line], 0, 2) != ' ') {
- // $string[$line] = ' ' . $string[$line].PHP_EOL;
- // }
- // if (mb_substr($string[$line], 0, 2) == ' ' && str_replace(' ', '', $string[$line])) {
- // $string[$line] .= PHP_EOL;
- // }
- }
- }
- $content = implode(PHP_EOL, $string);
- return $content;
- }
- /**
- * 书籍简介排版
- *
- * @param $content
- * @return string
- */
- function filterContent2($content)
- {
- if (!$content) return '';
- $content = str_replace(
- [' ', '<br /><br />', '<br>', '<br />', ' ', '<p>', '</p>', '“', '”', '…', '‘', '’', '—'],
- [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...', '‘', '’', '-'],
- $content);
- $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
- // 段落首字母前加两个中文空格
- $string = explode(PHP_EOL, $content);
- $content = '';
- foreach ($string as $line => $text) {
- $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' ', '<br />'], '', $string[$line]);
- if (!$string[$line]) {
- unset($string[$line]);
- } else {
- $string[$line] = ' ' . $string[$line] . '<br />';
- $content .= $string[$line];
- }
- }
- $content = trim($content, '<br />');
- return $content;
- }
- /**
- * 书籍简介排版-抖音版
- *
- * @param $content
- * @return string
- */
- function filterIntro($content)
- {
- if (!$content) return '';
- $content = str_replace(
- [' ', '<br /><br />', '<br>', '<br />', ' ', '<p>', '</p>', '“', '”', '…', '‘', '’', '—'],
- [' ', ' ', ' ', ' ', ' ', '', ' ', '“', '”', '...', '‘', '’', '-'],
- $content);
- $content = preg_replace('/(\r\n)+/', PHP_EOL, $content);
- // 段落首字母前加两个中文空格
- $string = explode(PHP_EOL, $content);
- $content = '';
- foreach ($string as $line => $text) {
- $string[$line] = str_replace([' ', "\r\n", "\r", "\n", ' ', '<br />'], '', $string[$line]);
- if (!$string[$line]) {
- unset($string[$line]);
- } else {
- $content .= $string[$line];
- }
- }
- $content = trim($content, '<br />');
- return $content;
- }
- /**
- * 压缩视频文件
- * 压缩策略:3秒视频约1M~1.5M
- *
- * @param string $videoUrl 视频URL地址
- * @param string $prefix 上传文件夹前缀(如:'videos')
- * @return string 返回压缩后的视频URL,失败返回空字符串
- */
- function compressVideo($videoUrl, $prefix = 'videos')
- {
- if (env('APP_ENV') == 'local') return $videoUrl;
- try {
- // 创建临时目录
- $tempDir = storage_path('app/temp/videos');
- if (!is_dir($tempDir)) {
- mkdir($tempDir, 0775, true);
- // 确保目录权限正确
- chmod($tempDir, 0775);
- }
- // 生成唯一文件名(不包含点号)
- $uniqueId = uniqid('video_') . bin2hex(random_bytes(4));
- $videoExt = getVideoExtFromUrl($videoUrl);
- $inputFile = $tempDir . '/' . $uniqueId . '_input' . $videoExt;
- $outputFile = $tempDir . '/' . $uniqueId . '_output.mp4';
- // 下载视频到本地
- dLog('video_compress')->info('开始下载视频', ['url' => $videoUrl]);
- $client = new \GuzzleHttp\Client(['timeout' => 300]);
- $response = $client->get($videoUrl);
-
- // 使用更安全的方式写入文件
- $fileContent = $response->getBody()->getContents();
- if (file_put_contents($inputFile, $fileContent) === false) {
- dLog('video_compress')->error('视频文件写入失败', [
- 'url' => $videoUrl,
- 'file' => $inputFile,
- 'dir_writable' => is_writable($tempDir)
- ]);
- return '';
- }
-
- // 设置文件权限
- chmod($inputFile, 0664);
- if (!file_exists($inputFile)) {
- dLog('video_compress')->error('视频下载失败', ['url' => $videoUrl]);
- return '';
- }
- $inputFileSize = filesize($inputFile);
- dLog('video_compress')->info('视频下载成功', [
- 'url' => $videoUrl,
- 'size' => $inputFileSize,
- 'size_mb' => round($inputFileSize / 1024 / 1024, 2) . 'MB'
- ]);
- // 获取视频时长(秒)
- $ffprobePath = env('FFPROBE_PATH', 'ffprobe');
- $durationCmd = "$ffprobePath -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 \"$inputFile\"";
- $duration = (float)trim(shell_exec($durationCmd));
- if ($duration <= 0) {
- dLog('video_compress')->error('无法获取视频时长', ['file' => $inputFile]);
- @unlink($inputFile);
- return '';
- }
- // 计算目标码率
- // 目标:3秒视频 = 1~1.5MB,即每秒约 0.33~0.5MB = 2730~4096 kbps
- // 使用中间值:3500 kbps
- $targetBitrate = 3500; // kbps
-
- // 根据视频时长动态调整码率,确保文件大小合理
- // 目标文件大小 = duration * 0.4MB/s = duration * 400KB/s
- $targetFileSizeKB = $duration * 400; // KB
- $targetBitrateCalculated = (int)(($targetFileSizeKB * 8) / $duration); // kbps
-
- // 使用计算出的码率,但不低于1500kbps,不高于5000kbps
- $targetBitrate = max(1500, min(5000, $targetBitrateCalculated));
- dLog('video_compress')->info('视频信息', [
- 'duration' => $duration . 's',
- 'target_bitrate' => $targetBitrate . 'kbps',
- 'estimated_size' => round($targetFileSizeKB / 1024, 2) . 'MB'
- ]);
- // 使用FFmpeg压缩视频
- // -c:v libx264: 使用H.264编码器
- // -b:v: 视频码率
- // -c:a aac: 音频编码器
- // -b:a 128k: 音频码率
- // -movflags +faststart: 优化网络播放
- // -preset medium: 编码速度与质量平衡
- $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
- $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";
-
- dLog('video_compress')->info('开始压缩视频', ['command' => $ffmpegCmd]);
- $output = shell_exec($ffmpegCmd);
- if (!file_exists($outputFile)) {
- dLog('video_compress')->error('视频压缩失败', [
- 'input' => $inputFile,
- 'output' => $output
- ]);
- @unlink($inputFile);
- return '';
- }
-
- // 设置输出文件权限
- chmod($outputFile, 0664);
- $outputFileSize = filesize($outputFile);
- $compressionRatio = round((1 - $outputFileSize / $inputFileSize) * 100, 2);
- dLog('video_compress')->info('视频压缩成功', [
- 'input_size' => round($inputFileSize / 1024 / 1024, 2) . 'MB',
- 'output_size' => round($outputFileSize / 1024 / 1024, 2) . 'MB',
- 'compression_ratio' => $compressionRatio . '%',
- 'duration' => $duration . 's',
- 'size_per_second' => round($outputFileSize / $duration / 1024 / 1024, 2) . 'MB/s'
- ]);
- // 上传压缩后的视频到云存储
- $stream = fopen($outputFile, 'r');
- if (!$stream) {
- dLog('video_compress')->error('无法打开压缩后的视频文件', ['file' => $outputFile]);
- @unlink($inputFile);
- @unlink($outputFile);
- return '';
- }
-
- $filename = $uniqueId . '.mp4';
-
- // 根据环境变量选择上传方式
- $uploadMethod = env('VIDEO_UPLOAD_METHOD', 'tos'); // 默认使用火山云
-
- if ($uploadMethod === 'oss') {
- $compressedUrl = uploadStreamToOss($prefix, $stream, $filename);
- } else {
- $compressedUrl = uploadStreamByTos($prefix, $stream, $filename);
- }
-
- // 安全关闭文件流
- if (is_resource($stream)) {
- fclose($stream);
- }
- // 清理临时文件
- @unlink($inputFile);
- @unlink($outputFile);
- if (!$compressedUrl) {
- dLog('video_compress')->error('压缩视频上传失败');
- return '';
- }
- dLog('video_compress')->info('压缩视频上传成功', [
- 'original_url' => $videoUrl,
- 'compressed_url' => $compressedUrl
- ]);
- return $compressedUrl;
- } catch (\Exception $e) {
- dLog('video_compress')->error('视频压缩异常', [
- 'url' => $videoUrl,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
-
- // 安全关闭文件流(如果存在)
- if (isset($stream) && is_resource($stream)) {
- @fclose($stream);
- }
-
- // 清理可能存在的临时文件
- if (isset($inputFile) && file_exists($inputFile)) {
- @unlink($inputFile);
- }
- if (isset($outputFile) && file_exists($outputFile)) {
- @unlink($outputFile);
- }
-
- return ''; // 出错时返回空字符串
- }
- }
- /**
- * 获取视频第一帧并上传
- * 根据远程视频URL获取第一帧图片并保存到TOS或OSS(默认TOS)
- *
- * @param string $videoUrl 视频URL地址
- * @param string $prefix 上传文件夹前缀(如:'videos')
- * @param string $uploadMethod 上传方式:'tos'(默认) 或 'oss'
- * @return string 返回图片URL地址,失败返回空字符串
- */
- function getVideoFirstFrame($videoUrl, $prefix = 'videos', $uploadMethod = 'tos')
- {
- if (env('APP_ENV') == 'local') return '';
- try {
- // 创建临时目录
- $tempDir = storage_path('app/temp/video_frames');
- if (!is_dir($tempDir)) {
- mkdir($tempDir, 0775, true);
- chmod($tempDir, 0775);
- }
- // 生成唯一文件名
- $uniqueId = uniqid('frame_') . bin2hex(random_bytes(4));
- $videoExt = getVideoExtFromUrl($videoUrl);
- $inputFile = $tempDir . '/' . $uniqueId . '_video' . $videoExt;
- $outputFile = $tempDir . '/' . $uniqueId . '_frame.jpg';
- // 下载视频到本地
- dLog('video_frame')->info('开始下载视频', ['url' => $videoUrl]);
- $client = new \GuzzleHttp\Client(['timeout' => 300]);
- $response = $client->get($videoUrl);
-
- $fileContent = $response->getBody()->getContents();
- if (file_put_contents($inputFile, $fileContent) === false) {
- dLog('video_frame')->error('视频文件写入失败', [
- 'url' => $videoUrl,
- 'file' => $inputFile
- ]);
- return '';
- }
-
- chmod($inputFile, 0664);
- if (!file_exists($inputFile)) {
- dLog('video_frame')->error('视频下载失败', ['url' => $videoUrl]);
- return '';
- }
- dLog('video_frame')->info('视频下载成功', [
- 'url' => $videoUrl,
- 'size_mb' => round(filesize($inputFile) / 1024 / 1024, 2) . 'MB'
- ]);
- // 使用FFmpeg提取第一帧
- // -i: 输入文件
- // -ss 00:00:00: 从视频开始位置(第0秒)
- // -vframes 1: 只提取1帧
- // -q:v 2: 图片质量(1-31,数字越小质量越高)
- $ffmpegPath = env('FFMPEG_PATH', 'ffmpeg');
- $ffmpegCmd = "$ffmpegPath -i \"$inputFile\" -ss 00:00:00 -vframes 1 -q:v 2 -y \"$outputFile\" 2>&1";
-
- dLog('video_frame')->info('开始提取第一帧', ['command' => $ffmpegCmd]);
- $output = shell_exec($ffmpegCmd);
- if (!file_exists($outputFile)) {
- dLog('video_frame')->error('提取第一帧失败', [
- 'input' => $inputFile,
- 'output' => $output
- ]);
- @unlink($inputFile);
- return '';
- }
-
- chmod($outputFile, 0664);
- dLog('video_frame')->info('第一帧提取成功', [
- 'size' => round(filesize($outputFile) / 1024, 2) . 'KB'
- ]);
- // 上传图片到云存储
- $stream = fopen($outputFile, 'r');
- if (!$stream) {
- dLog('video_frame')->error('无法打开图片文件', ['file' => $outputFile]);
- @unlink($inputFile);
- @unlink($outputFile);
- return '';
- }
-
- $filename = $uniqueId . '.jpg';
-
- // 根据参数选择上传方式,默认使用TOS
- if ($uploadMethod === 'oss') {
- $frameUrl = uploadStreamToOss($prefix, $stream, $filename);
- } else {
- $frameUrl = uploadStreamByTos($prefix, $stream, $filename);
- }
-
- // 安全关闭文件流
- if (is_resource($stream)) {
- fclose($stream);
- }
- // 清理临时文件
- @unlink($inputFile);
- @unlink($outputFile);
- if (!$frameUrl) {
- dLog('video_frame')->error('图片上传失败');
- return '';
- }
- dLog('video_frame')->info('图片上传成功', [
- 'video_url' => $videoUrl,
- 'frame_url' => $frameUrl
- ]);
- return $frameUrl;
- } catch (\Exception $e) {
- dLog('video_frame')->error('提取视频第一帧异常', [
- 'url' => $videoUrl,
- 'error' => $e->getMessage(),
- 'trace' => $e->getTraceAsString()
- ]);
-
- // 安全关闭文件流(如果存在)
- if (isset($stream) && is_resource($stream)) {
- @fclose($stream);
- }
-
- // 清理可能存在的临时文件
- if (isset($inputFile) && file_exists($inputFile)) {
- @unlink($inputFile);
- }
- if (isset($outputFile) && file_exists($outputFile)) {
- @unlink($outputFile);
- }
-
- return '';
- }
- }
- function sensitiveStr($list, $string)
- {
- $count = 0; //违规词的个数
- $sensitiveWord = ''; //违规词
- $stringAfter = $string; //替换后的内容
- $total = count($list);
- $size = 500;
- $last = ceil($total / $size);
- $patternList = [];
- for ($page = 1; $page <= $last; $page++) {
- $arr = array_slice($list, $size * ($page - 1), $size);
- $filter = [];
- foreach ($arr as $v) {
- if (preg_match('/[^a-zA-Z0-9\|\p{Han}\·]/u', $v)) continue;
- $filter[] = $v;
- // $a = preg_replace('/[^a-zA-Z0-9\|\p{Han}]/u', '', $v);
- // if ($a) $filter[] = $a;
- }
- $pattern = "/" . implode("|", $filter) . "/i"; //定义正则表达式
- if (preg_match_all($pattern, $string, $matches)) { //匹配到了结果
- $patternList = array_merge($patternList, $matches[0]); //匹配到的数组
- }
- }
- $sensitiveWord = '';
- if ($patternList) {
- $count = count($patternList);
- // $sensitiveWord = implode(',', $patternList); //敏感词数组转字符串
- $replaceArray = array_combine($patternList, array_fill(0, count($patternList), '*')); //把匹配到的数组进行合并,替换使用
- $stringAfter = strtr($string, $replaceArray); //结果替换
- // 将敏感词合并
- $return_pattern = [];
- foreach ($patternList as $v) {
- if (!isset($return_pattern[$v])) {
- $return_pattern[$v] = [
- 'word' => $v,
- 'count' => 1,
- ];
- } else {
- $return_pattern[$v]['count'] += 1;
- }
- }
- foreach ($return_pattern as $v) {
- $sensitiveWord .= $v['word'] . ',';
- }
- }
- return [
- 'count' => $count,
- 'sensitive_words' => trim($sensitiveWord, ','),
- 'content' => $stringAfter
- ];
- }
- /**
- * 转换时间格式
- *
- * @param $date
- * @param string $format
- * @return false|string
- */
- function transDate($date, $format = 'Y-m-d H:i:s')
- {
- return strtotime($date) > 0 ? date($format, strtotime($date)) : '';
- }
- /**
- * 根据网段获取计算所有IP
- *
- * @param string $segment 网段 '139.217.0.1/24'
- * @return array [网络地址:139.217.0.1 广播地址:139.217.0.255 IP列表: ['139.217.0.2','139.217.0.3'……'139.217.0.254']]
- */
- function getIpBySegment($segment)
- {
- $segmentInfo = explode("/", $segment);
- $beginIpArray = explode(".", $segmentInfo[0]);
- $mask = intval($segmentInfo['1']);
- $endIp = array();
- foreach ($beginIpArray as $ipKey => $item) {
- $beginFlag = 8 * ($ipKey); //0 8 16 24
- $endFlag = 8 * ($ipKey + 1);//8 16 24 32
- $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
- $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));
- }
- $ipArray = array();
- for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0]++) {
- for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1]++) {
- for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2]++) {
- for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3]++) {
- $ipArray[] = implode(".", $beginIp);
- }
- }
- }
- }
- $network_ip_addr = $beginIpArray[0] . '.' . $beginIpArray[1] . '.' . $beginIpArray[2] . '.' . '0'; // 网络地址
- $broadcast_ip_addr = end($ipArray); // 广播地址
- if ($ipArray[0] == $network_ip_addr) { // 如果是网络地址则删掉
- unset($ipArray[0]);
- }
- $last = count($ipArray);
- unset($ipArray[$last]);
- return [$network_ip_addr, $broadcast_ip_addr, $ipArray];
- }
- /**
- * 在指定网段中分配子网段
- *
- * @param string $segment 指定网段
- * @param int $ipNum 需要的IP数
- * @param array $usedIpArray 不可用(已经使用)的IP,默认为空数组
- * @return bool|string 成功则返回分配的网段
- */
- function allocateSegment($segment, $ipNum, $usedIpArray = [])
- {
- $usedIpArray = empty($usedIpArray) ? [] : array_flip($usedIpArray);
- //计算需要多少个IP
- $i = 0;
- $ipCount = pow(2, $i);
- while ($ipCount < $ipNum) {
- $i++;
- $ipCount = pow(2, $i);
- }
- $newMask = 32 - $i;
- //大网段的开始和结束IP
- $segmentInfo = explode("/", $segment); //['139.217.0.1',24]
- $beginIpArray = explode(".", $segmentInfo[0]);//[139,217,0,1]
- $mask = intval($segmentInfo['1']); //24
- if ($newMask < $mask) {
- return false;
- }
- $endIp = array();
- $step = [];
- foreach ($beginIpArray as $ipKey => $item) {
- $beginFlag = 8 * ($ipKey); //0 8 16 24
- $endFlag = 8 * ($ipKey + 1);//8 16 24 32
- $step[$ipKey] = $newMask > $endFlag ? 1 : ($endFlag - $newMask < 8 ? pow(2, $endFlag - $newMask) : pow(2, 8));
- $decbinItem = str_pad(decbin($item), 8, "0", STR_PAD_LEFT);
- $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));
- }
- //遍历生成网段
- for ($beginIp[0] = $beginIpArray[0]; $beginIp[0] <= $endIp[0]; $beginIp[0] += $step[0]) {
- for ($beginIp[1] = $beginIpArray[1]; $beginIp[1] <= $endIp[1]; $beginIp[1] += $step[1]) {
- for ($beginIp[2] = $beginIpArray[2]; $beginIp[2] <= $endIp[2]; $beginIp[2] += $step[2]) {
- for ($beginIp[3] = $beginIpArray[3]; $beginIp[3] <= $endIp[3]; $beginIp[3] += $step[3]) {
- $newSegment = implode('.', $beginIp) . '/' . $newMask;
- //获取该网段所有的IP
- $ipArray = getIpBySegment($newSegment);
- $canUse = true;
- //判断该网段是否可用
- if (!empty($usedIpArray)) {
- foreach ($ipArray as $ip) {
- if (isset($usedIpArray[$ip])) {
- $canUse = false;
- break;
- }
- }
- }
- if ($canUse) {
- return $newSegment;
- }
- }
- }
- }
- }
- return false;
- }
- function remove_xss($val)
- {
- // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
- // this prevents some character re-spacing such as <java\0script>
- // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
- $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
- // straight replacements, the user should never need these since they're normal characters
- // this prevents like <IMG SRC=@avascript:alert('XSS')>
- $search = 'abcdefghijklmnopqrstuvwxyz';
- $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
- $search .= '1234567890!@#$%^&*()';
- $search .= '~`";:?+/={}[]-_|\'\\';
- for ($i = 0; $i < strlen($search); $i++) {
- // ;? matches the ;, which is optional
- // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
- // @ @ search for the hex values
- $val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
- // @ @ 0{0,7} matches '0' zero to seven times
- $val = preg_replace('/(�{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
- }
- // now the only remaining whitespace attacks are \t, \n, and \r
- $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
- $ra2 = array(
- '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'
- );
- $ra = array_merge($ra1, $ra2);
- $found = true; // keep replacing as long as the previous round replaced something
- while ($found == true) {
- $val_before = $val;
- for ($i = 0; $i < sizeof($ra); $i++) {
- $pattern = '/';
- for ($j = 0; $j < strlen($ra[$i]); $j++) {
- if ($j > 0) {
- $pattern .= '(';
- $pattern .= '(&#[xX]0{0,8}([9ab]);)';
- $pattern .= '|';
- $pattern .= '|(�{0,8}([9|10|13]);)';
- $pattern .= ')*';
- }
- $pattern .= $ra[$i][$j];
- }
- $pattern .= '/i';
- $replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
- $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
- if ($val_before == $val) {
- // no replacements were made, so exit the loop
- $found = false;
- }
- }
- }
- return $val;
- }
- /**
- * 计算作者积分等级
- *
- * @param $score
- */
- function calcAuthorLevel($score): int
- {
- switch (true) {
- case $score <= 0:
- $level = 0;
- break;
- case $score <= 5000:
- $level = 1;
- break;
- case $score <= 50000:
- $level = 2;
- break;
- case $score <= 100000:
- $level = 3;
- break;
- case $score <= 300000:
- $level = 4;
- break;
- case $score <= 800000:
- $level = 5;
- break;
- case $score <= 1500000:
- $level = 6;
- break;
- case $score <= 2500000:
- $level = 7;
- break;
- case $score <= 5000000:
- $level = 8;
- break;
- case $score <= 10000000:
- $level = 9;
- break;
- default:
- $level = 10;
- break;
- }
- return $level;
- }
- /**
- * 运营数据(上传附件)
- *
- * @param $file
- * @return string
- * @throws Exception
- */
- function uploadEnclosureFile($file)
- {
- // 阿里云主账号
- $accessKeyId = env('OSS_ACCESS_ID');
- $accessKeySecret = env('OSS_ACCESS_KEY');
- $endpoint = env('OSS_END_POINT');
- $bucket = env('OSS_BUCKET');
- // 设置文件名称。
- $object = 'books/enclosure/' . randStr(10) . '--' . $file->getClientOriginalName();
- try {
- $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
- $ossImgBackData = $ossClient->uploadFile($bucket, $object, $file->path());
- } catch (OssException $e) {
- printf($e->getMessage());
- return '';
- }
- $urlArr = parse_url($ossImgBackData['oss-request-url']);
- return getProp($urlArr, 'path') ? 'http://' . $bucket . '.' . $endpoint . getProp($urlArr, 'path') : '';
- }
- // 获取当前域名是http还是https
- function getHttpType()
- {
- return ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
- }
- // 根据id生成唯一邀请码
- function enCodeId($user_id)
- {
- $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
- $num = strlen($key);
- $code = ''; // 邀请码
- while ($user_id > 0) { // 转进制
- $mod = $user_id % $num; // 求模
- $user_id = ($user_id - $mod) / $num;
- $code = $key[$mod] . $code;
- }
- $code = str_pad($code, 6, 'A', STR_PAD_LEFT); // 不足用0补充
- return $code;
- }
- // 根据邀请码解密为id
- function deCodeId($code)
- {
- $key = 'XzeTdSPQc1uYHRBVWmUE6x94q25g3krfCGhb8FjtDZvMNKJpnayw7s';
- $num = strlen($key);
- if (strrpos($code, '0') !== false) $code = substr($code, strrpos($code, '0') + 1);
- $len = strlen($code);
- $code = strrev($code);
- $user_id = 0;
- for ($i = 0; $i < $len; $i++) {
- $user_id += strpos($key, $code[$i]) * pow($num, $i);
- }
- return $user_id;
- }
- /**
- * 将二维数组按其中的某个数组排序(此方法适用于将数据库数据按数组取出后自动按ID排序的情况 ps:即未按该数组排序)
- *
- * @param array $array 二维数组
- * @param array $sort 排序数组
- * @param string $field 排序字段(二维数组和排序数组相同的字段)
- * @return array
- */
- function sortByArray(array $array, array $sort, string $field): array
- {
- $data = [];
- if (is_array($array) && is_array($sort)) {
- foreach ($sort as $v) {
- foreach ($array as $key => $val) {
- if ($v == $val[$field]) {
- array_push($data, $array[$key]);
- }
- }
- }
- }
- return $data;
- }
- /**
- * 将二维数组按其中的字段排序(正序或倒序)
- *
- * @param array $array 二维数组
- * @param string $field 排序字段
- * @param mixed $type 排序方式(3倒序,4正序)
- * @return array|mixed
- */
- function sortByField(array $array, string $field, $type): array
- {
- if (is_array($array)) {
- array_multisort(array_column($array, $field), $type, $array);
- }
- return $array;
- }
- // 生成用户邀请码
- function setUserInviteCode($id)
- {
- return \Vinkla\Hashids\Facades\Hashids::connection('invite')->encode($id);
- }
- // 解密用户邀请码
- function decodeUserInviteCode($code)
- {
- return \Vinkla\Hashids\Facades\Hashids::connection('invite')->decode($code);
- }
- function getMillisecond()
- {
- list($microsecond, $time) = explode(' ', microtime());
- return (float)sprintf('%.0f', (floatval($microsecond) + floatval($time)) * 1000);
- }
- function get_client_ip($type = 0, $adv = false)
- {
- $type = $type ? 1 : 0;
- static $ip = null;
- if (null !== $ip) {
- return $ip[$type];
- }
- if ($adv) {
- if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
- $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
- $pos = array_search('unknown', $arr);
- if (false !== $pos) {
- unset($arr[$pos]);
- }
- $ip = trim($arr[0]);
- } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
- $ip = $_SERVER['HTTP_CLIENT_IP'];
- } elseif (isset($_SERVER['REMOTE_ADDR'])) {
- $ip = $_SERVER['REMOTE_ADDR'];
- }
- } elseif (isset($_SERVER['REMOTE_ADDR'])) {
- $ip = $_SERVER['REMOTE_ADDR'];
- }
- // IP地址合法验证
- $long = sprintf("%u", ip2long($ip));
- $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
- return $ip[$type];
- }
- /**
- * 获取真实IP
- */
- function _getIp()
- {
- if (getenv('HTTP_X_FORWARDED_FOR')) {
- $ip = getenv('HTTP_X_FORWARDED_FOR');
- } else if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
- $ip = getenv("HTTP_CLIENT_IP");
- else if (getenv("HTTP_X_FORWARD_FOR") && strcasecmp(getenv("HTTP_X_FORWARD_FOR"), "unknown"))
- $ip = getenv("HTTP_X_FORWARD_FOR");
- else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
- $ip = getenv("REMOTE_ADDR");
- else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
- $ip = $_SERVER['REMOTE_ADDR'];
- else
- $ip = "unknown";
- return ($ip);
- }
- /**
- * 数组 转 对象
- *
- * @param array $arr 数组
- * @return object
- */
- function array_to_object($arr)
- {
- if (gettype($arr) != 'array') {
- return;
- }
- foreach ($arr as $k => $v) {
- if (gettype($v) == 'array' || getType($v) == 'object') {
- $arr[$k] = (object)array_to_object($v);
- }
- }
- return (object)$arr;
- }
- /**
- * 对象 转 数组
- *
- * @param object $obj 对象
- * @return array
- */
- function object_to_array($obj)
- {
- $obj = (array)$obj;
- foreach ($obj as $k => $v) {
- if (gettype($v) == 'resource') {
- return;
- }
- if (gettype($v) == 'object' || gettype($v) == 'array') {
- $obj[$k] = (array)object_to_array($v);
- }
- }
- return $obj;
- }
- /**
- * 检查是否为手机号码
- */
- function _isPhone($number)
- {
- return preg_match("/^1[34578][0-9]{9}$/", $number);
- }
- /**
- * 判断所传的参数是否缺少,如果缺少返回渠道的字段,正确返回0
- *
- * @param array $param
- * @param array $must
- * @return int|mixed
- */
- function checkParam(array $param, array $must)
- {
- foreach ($must as $item) {
- if (array_key_exists($item, $param) && $param[$item] != '') {
- } else {
- return $item;
- }
- }
- return 0;
- }
- /**
- * 对象 转 数组
- *
- * @param object $obj 对象
- * @return array
- */
- function ignoreKeyInArray($targetArray, $delete_keys = [], $changes = [])
- {
- $change_keys = array_keys($changes);
- foreach ($targetArray as $key => $value) {
- if (in_array($key, $delete_keys) && isset($targetArray[$key])) unset($targetArray[$key]);
- if (in_array($key, $change_keys) && isset($targetArray[$key])) $targetArray[$key] = $changes[$key];
- if (is_array($value)) ignoreKeyInArray($value, $delete_keys, $change_keys);
- }
- return $targetArray;
- }
- function itemTransform($trans, $data)
- {
- if ($data) {
- return $trans->transform($data);
- } else {
- return [];
- }
- }
- function collectionTransform($trans, $data)
- {
- $ret_data = [];
- if ($data) {
- foreach ($data as $item) {
- $ret_data[] = $trans->transform($item);
- }
- }
- return $ret_data;
- }
- function paginationTransform($trans, $paginator)
- {
- $ret = [];
- $ret['list'] = [];
- if ($paginator) {
- foreach ($paginator as $item) {
- $ret['list'][] = $trans->transform($item);
- }
- $ret['meta'] = [
- 'total' => (int)$paginator->total(),
- 'per_page' => (int)$paginator->perPage(),
- 'current_page' => (int)$paginator->currentPage(),
- 'last_page' => (int)$paginator->lastPage(),
- 'next_page_url' => (string)$paginator->nextPageUrl(),
- 'prev_page_url' => (string)$paginator->previousPageUrl()
- ];
- }
- return $ret;
- }
- /**
- * 加密site id
- */
- function encodeDistributionChannelId($id)
- {
- $encrypt_pool = [
- ];
- if (isset($encrypt_pool[$id])) {
- return $encrypt_pool[$id];
- }
- $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
- return $hashids->encode($id);
- }
- /**
- * 解密密site id
- */
- function decodeDistributionChannelId($code)
- {
- $encrypt_pool = [
- ];
- if (isset($encrypt_pool[$code])) {
- return $encrypt_pool[$code];
- }
- $hashids = new \Hashids\Hashids('', 16, 'abcdefghjklmnopqrstuvwxyz1234567890');
- $res = $hashids->decode($code);
- if ($res && isset($res[0])) {
- return $res[0];
- }
- return null;
- }
- //bid加密
- function book_hash_encode($bid)
- {
- return Vinkla\Hashids\Facades\Hashids::encode($bid);
- }
- function decodeBid($encode_bid)
- {
- $bid = 0;
- try {
- $bid_arr = \Hashids::decode($encode_bid);
- if (isset($bid_arr[0])) {
- $bid = $bid_arr[0];
- }
- } catch (\Exception $e) {
- return null;
- }
- return $bid;
- }
- /**
- * 获取当前域名
- */
- function _domain()
- {
- return str_replace('https://', '', str_replace('http://', '', url('/')));
- }
- /**
- * 字符串转*
- *
- * @param $str // 待转的字符串
- * @param $start // 转*起始位置
- * @param int $end // 转*结束位置
- * @param string $dot // 转换的字符(必须是单字符,默认是*)
- * @param string $charset // 编码方式
- * @param string $end_char // 特殊字符(碰到此字符则确定end位置)
- * @return string
- */
- function trans_pass($str, $start, $end = 0, $dot = "*", $charset = "UTF-8", $end_char = '@'): string
- {
- $len = mb_strlen($str, $charset);
- if ($start == 0 || $start > $len) {
- $start = 1;
- }
- if ($end != 0 && $end > $len) {
- $end = $len - 2;
- }
- if (strstr($str, $end_char)) {
- $end = $len - strrpos($str, $end_char);
- }
- $endStart = $len - $end;
- $top = mb_substr($str, 0, $start, $charset);
- $bottom = "";
- if ($endStart > 0) {
- $bottom = mb_substr($str, $endStart, $end, $charset);
- }
- $len -= mb_strlen($top, $charset);
- $len -= mb_strlen($bottom, $charset);
- $newStr = $top;
- for ($i = 0; $i < $len; $i++) {
- $newStr .= $dot;
- }
- $newStr .= $bottom;
- return $newStr;
- }
- /**
- * 格式化章节内容
- *
- * @param $content
- * @return false|string
- */
- function formatContent($content)
- {
- if (!$content) return '';
- $content = str_replace(
- [' ', '<br /><br />', '<br>', '<br />', ' ', '<p>', '</p >', '“', '”', '…'],
- [' ', PHP_EOL, PHP_EOL, PHP_EOL, ' ', '', PHP_EOL, '“', '”', '...'],
- $content);
- $content = str_replace([" ", '“', '…', '”', '<p>'], '', $content);
- // 段落首字母前加两个中文空格
- $string = explode(PHP_EOL, $content);
- foreach ($string as $line => $text) {
- if (mb_substr($text, 0, 2) != ' ') $string[$line] = ' ' . $text;
- }
- $content = implode(PHP_EOL, $string);
- $content = mb_convert_encoding($content, 'UTF-8', 'UTF-8,GBK,GB2312');
- $content = iconv('UTF-8', 'UTF-8//IGNORE', $content);
- return $content;
- }
- /**
- * 筛选出有效的id集合
- *
- * @param array $ids
- * @return array
- */
- function filterValidIds(array $ids): array
- {
- // 传参
- if (empty($ids)) {
- return [];
- }
- $result = [];
- foreach ($ids as $id) {
- if (in_array($id, $result) || !is_numeric($id) || (int)$id < 1) {
- continue;
- }
- $result[] = (int)$id;
- }
- return $result;
- }
- function arrayToStr($map)
- {
- $isMap = isArrMap($map);
- $result = "";
- if ($isMap) {
- $result = "map[";
- }
- $keyArr = array_keys($map);
- if ($isMap) {
- sort($keyArr);
- }
- $paramsArr = array();
- foreach ($keyArr as $k) {
- $v = $map[$k];
- if ($isMap) {
- if (is_array($v)) {
- $paramsArr[] = sprintf("%s:%s", $k, arrayToStr($v));
- } else {
- $paramsArr[] = sprintf("%s:%s", $k, trim(strval($v)));
- }
- } else {
- if (is_array($v)) {
- $paramsArr[] = arrayToStr($v);
- } else {
- $paramsArr[] = trim(strval($v));
- }
- }
- }
- $result = sprintf("%s%s", $result, join(" ", $paramsArr));
- if (!$isMap) {
- $result = sprintf("[%s]", $result);
- } else {
- $result = sprintf("%s]", $result);
- }
- return $result;
- }
- function isArrMap($map)
- {
- foreach ($map as $k => $v) {
- if (is_string($k)) {
- return true;
- }
- }
- return false;
- }
- /**
- * 随机字符串
- *
- * @param $length
- * @return string
- */
- function makeRandStr($length): string
- {
- // 密码字符集,可任意添加你需要的字符
- $str = [
- 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
- 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
- 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
- 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
- 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
- ];
- // 在 $str 中随机取 $length 个数组元素键名
- $keys = array_rand($str, $length);
- $password = '';
- for ($i = 0; $i < $length; $i++) {
- // 将 $length 个数组元素连接成字符串
- $password .= $str[$keys[$i]];
- }
- return $password;
- }
- /**
- * 导出数据为excel表格
- *
- * @param $data 一个二维数组,结构如同从数据库查出来的数组
- * @param $title excel的第一行标题,一个数组,如果为空则没有标题
- * @param $filename 下载的文件名
- * @examlpe10
- */
- function exportExcel($data = [], $title = [], $filename = 'report')
- {
- ob_end_clean();
- ob_start();
- header("Content-type:application/octet-stream");
- header("Accept-Ranges:bytes");
- header("Content-type:application/vnd.ms-excel");
- header("Content-Disposition:attachment;filename=" . $filename . ".xls");
- header("Pragma: no-cache");
- header("Expires: 0");
- //导出xls 开始
- if (!empty($title)) {
- foreach ($title as $k => $v) {
- $title[$k] = iconv("UTF-8", "GB2312", $v);
- }
- $title = implode("\t", $title);
- echo "$title\n";
- }
- if (!empty($data)) {
- foreach ($data as $key => $val) {
- foreach ($val as $ck => $cv) {
- $data[$key][$ck] = iconv("UTF-8", "GB2312", $cv);
- }
- $data[$key] = implode("\t", $data[$key]);
- }
- echo implode("\n", $data);
- }
- }
- /**
- * 导出csv文件
- * @param string $name
- * @param array $headers
- * @param array $data
- * @return void
- */
- function exportCsv(string $name, array $headers, array $data = [])
- {
- header('Content-Description: File Transfer');
- header('Content-Type: application/csv');
- header("Content-Disposition: attachment; filename=".$name.".csv");
- header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
- $handle = fopen('php://output', 'w');
- ob_clean();
- fputcsv($handle, $headers);
- if ($data) {
- foreach ($data as $row) {
- fputcsv($handle, $row);
- }
- }
- ob_flush();
- fclose($handle);
- die();
- }
- // 树状分类
- function buildCategoryTree($categories, $pid = 0) {
- $tree = [];
- foreach ($categories as $category) {
- if ($category['pid'] == $pid) {
- $children = buildCategoryTree($categories, $category['category_id']);
- if ($children) {
- $category['children'] = $children;
- }
- $tree[] = $category;
- }
- }
- return $tree;
- }
- // 获取文件的md5值
- function getFileContentMD5($filePath){
- //获取文件MD5的128位二进制数组
- $md5Bytes = md5_file($filePath,true);
- //计算文件的Content-MD5
- $contentMD5 = base64_encode($md5Bytes);
- return $contentMD5;
- }
- function getTextTokens($text) {
- // 方法1:按空格分词(西文较准)
- $words = preg_split('/\s+/', $text);
- $wordCount = count($words);
-
- // 方法2:按字符数估算(中文较准:1个汉字 ≈ 1.5-2 tokens)
- $charCount = mb_strlen($text);
-
- // 综合估算(根据语言调整权重)
- $tokenCount = $wordCount + $charCount * 0.5; // 示例公式
-
- // 更简单:直接按字符数 * 系数(中文推荐)
- // $tokenCount = $charCount * 1.8; // 经验系数
-
- return (int)ceil($tokenCount);
- }
- // 处理小说剧本文本
- function handleScriptWords($text, $enable_emotion=1) {
- $text = preg_replace('/[\r\n]+/', PHP_EOL, $text);
- $text_arr = explode(PHP_EOL, $text);
- $roles = [];
- $words = [];
- $role_gender = [];
- // $sequence = 0;
- foreach ($text_arr as $line) {
- $line = trim($line);
- if ($enable_emotion) {
- $match_rule = '/^(.*?)\:(.*?)\{(.*?)\}$/';
- $count = 4;
- } else {
- $match_rule = '/^(.*?)\:(.*?)$/';
- $count = 3;
- }
- preg_match($match_rule, $line, $matches);
-
- if (count($matches) == $count) {
- $gender = '0';
- // 角色部分拆分
- preg_match('/^(.*?)\((.*?)\)$/', $matches[1], $matches2);
- if (count($matches2) == 3) {
- $role = $matches2[1];
- $gender_arr = ['男'=>'1', '女'=>'2'];
- $gender = isset($gender_arr[$matches2[2]]) ? $gender_arr[$matches2[2]] : '0';
- }else {
- $role = $matches[1];
- }
- if (!in_array($role, $roles)) {
- $roles[] = $role; // 记录角色
- $role_gender[$role] = $gender;
- }
- $words[] = [
- 'role' => $role,
- 'gender' => $gender,
- 'text' => $matches[2],
- 'emotion' => $enable_emotion ? $matches[3] : '中性',
- ];
- }
- }
- $new_words = [];
- $tmp = '';
- $tmp_arr = [];
- $tmp_text = '';
- // 将words数组按照role和emotion合并相邻的text内容,不相邻则跳过合并
- foreach ($words as $word) {
- if(!$tmp) $tmp = $word['role'].'-'.$word['emotion'];
- if($tmp == $word['role'].'-'.$word['emotion']) {
- $tmp_text .= PHP_EOL.$word['text'];
- $tmp_arr = [
- 'role' => $word['role'],
- 'gender' => $word['gender'],
- 'text' => trim($tmp_text, PHP_EOL),
- 'emotion' => $word['emotion'],
- ];
- }else {
- // $sequence++;
- // $tmp_arr['sequence'] = $sequence;
- $new_words[] = $tmp_arr;
- $tmp = $word['role'].'-'.$word['emotion'];
- $tmp_text = $word['text'];
- $tmp_arr = [
- 'role' => $word['role'],
- 'gender' => $word['gender'],
- 'text' => trim($tmp_text, PHP_EOL),
- 'emotion' => $word['emotion'],
- ];
- }
- }
- if ($tmp_arr) {
- // $sequence++;
- // $tmp_arr['sequence'] = $sequence;
- $new_words[] = $tmp_arr;
- }
- return [
- 'roles' => $roles,
- 'role_gender' => $role_gender,
- 'words' => $new_words,
- ];
- }
- function extractScriptContent($originalContent) {
- if (!$originalContent) return [];
-
- // 使用更精确的正则表达式分割内容
- $parts = [];
-
- // 提取剧本名(###剧本名:后面的内容,支持多个空格)
- preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
- $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
- // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
- preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
- $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
-
- // 提取剧本亮点(支持多个空格)
- preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
- $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
-
- // 提取人物关系(支持多个空格)
- preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
- $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
-
- // 提取核心矛盾(支持多个空格)
- preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
- $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
-
- // 提取主体列表(支持多个空格)
- preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
- $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
- $parts['roles'] = parseRolesFromText($rolesText);
-
- // 提取美术风格(支持多个空格)
- preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
- $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
-
- // 提取场景列表(支持多个空格)
- preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
- $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
- $parts['scenes'] = parseScenesFromText($scenesText);
- // 提取分集详细内容(多剧集模式,支持多个空格)
- preg_match('/###\s*分集剧本\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
- $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
-
- // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
- preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
- $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
-
- // 优先使用原文内容,其次使用分集详细内容
- // $parts['content'] = $generatedContent ?: $detailedContent;
- // 解析分集剧本内容
- $episodes = [];
- if ($detailedContent) {
- // 按 ##分集 分割
- preg_match_all('/##\s*分集(\d+)\s*\n(.*?)(?=\n\s*##分集|\z)/s', $detailedContent, $episodeMatches, PREG_SET_ORDER);
-
- foreach ($episodeMatches as $episodeMatch) {
- $episodeNum = $episodeMatch[1];
- $episodeContent = trim($episodeMatch[2]);
-
- $episode = [
- 'episode_number' => $episodeNum,
- 'episode_content' => $episodeContent,
- 'episode_name' => '',
- 'scene_description' => '',
- 'camera_movement' => '',
- 'characters' => '',
- 'dialogues' => []
- ];
-
- // 提取分集名(格式:##分集01第一集: 第一集的标题)
- if (preg_match('/^第.*?集\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $nameMatch)) {
- $episode['episode_name'] = trim($nameMatch[1]);
- }
-
- // 提取场景描述
- if (preg_match('/场景描述\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $sceneMatch)) {
- $episode['scene_description'] = trim($sceneMatch[1]);
- }
-
- // 提取运镜
- if (preg_match('/运镜\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $cameraMatch)) {
- $episode['camera_movement'] = trim($cameraMatch[1]);
- }
-
- // 提取出场角色
- if (preg_match('/出场角色\s*[::]\s*(.+?)(?=\n|$)/u', $episodeContent, $charactersMatch)) {
- $episode['characters'] = trim($charactersMatch[1]);
- }
-
- // 提取台词内容
- if (preg_match('/台词内容\s*[::]\s*\n(.*?)$/su', $episodeContent, $dialoguesMatch)) {
- $dialoguesText = trim($dialoguesMatch[1]);
- $dialogueLines = explode("\n", $dialoguesText);
-
- foreach ($dialogueLines as $line) {
- $line = trim($line);
- if (empty($line)) {
- continue;
- }
-
- // 匹配格式:角色名: 对话内容 或 角色名:对话内容
- if (preg_match('/^(.+?)\s*[::]\s*(.+)$/u', $line, $dialogueMatch)) {
- $episode['dialogues'][] = [
- 'character' => trim($dialogueMatch[1]),
- 'text' => trim($dialogueMatch[2])
- ];
- }
- }
- }
-
- $episodes[] = $episode;
- }
- }
- $parts['episodes'] = $episodes;
- return $parts;
- }
- /**
- * 处理剧本内容
- */
- function handleScriptContent($originalContent) {
- if (!$originalContent) return [];
-
- // 使用更精确的正则表达式分割内容
- $parts = [];
-
- // // 确保内容使用UTF-8编码
- // if (!mb_check_encoding($originalContent, 'UTF-8')) {
- // $originalContent = mb_convert_encoding($originalContent, 'UTF-8', 'auto');
- // }
-
- // 提取剧本名(###剧本名:后面的内容,支持多个空格)
- preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
- $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
- // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
- preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
- $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
-
- // 提取剧本亮点(支持多个空格)
- preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
- $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
-
- // 提取人物关系(支持多个空格)
- preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
- $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
-
- // 提取核心矛盾(支持多个空格)
- preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
- $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
-
- // 提取主体列表(支持多个空格)
- preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
- $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
- $parts['roles'] = parseRolesFromText($rolesText);
-
- // 提取美术风格(支持多个空格)
- preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
- $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
-
- // 提取场景列表(支持多个空格)
- preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
- $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
- $parts['scenes'] = parseScenesFromText($scenesText);
- // 提取分集详细内容(多剧集模式,支持多个空格)
- preg_match('/###\s*分集详细内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
- $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
-
- // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
- preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
- $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
-
- // 优先使用原文内容,其次使用分集详细内容
- $parts['content'] = $generatedContent ?: $detailedContent;
- $parts['episode_title'] = '';
- $parts['acts'] = [];
- // 单剧集格式:顶层是大纲信息,分镜部分采用 handleEpisodeContent 的结构标准
- $singleStoryboard = '';
- if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
- $singleStoryboard = trim($singleStoryboardMatch[1]);
- }
- if ($singleStoryboard !== '') {
- $episodeContent = $singleStoryboard;
- if (!preg_match('/第\d+集[::\s]+/u', $episodeContent)) {
- $defaultEpisodeTitle = '第1集:' . ($parts['script_name'] ?? '未命名');
- $episodeContent = $defaultEpisodeTitle . "\n\n" . $episodeContent;
- }
- $episodeSections = [];
- $episodeSections[] = $episodeContent;
- if ($parts['intro'] !== '') {
- $episodeSections[] = "###故事梗概\n" . $parts['intro'];
- }
- if ($parts['art_style'] !== '') {
- $episodeSections[] = "###美术风格\n" . $parts['art_style'];
- }
- if ($rolesText !== '') {
- $episodeSections[] = "###主体列表\n" . $rolesText;
- }
- if ($scenesText !== '') {
- $episodeSections[] = "###场景列表\n" . $scenesText;
- }
- if (strpos($episodeContent, '###分镜剧本') === false) {
- $episodeSections[] = "###分镜剧本\n" . $singleStoryboard;
- }
- $episode_arr = handleEpisodeContent(implode("\n\n", $episodeSections));
- if (!empty($episode_arr['acts'])) {
- $parts['episode_title'] = getProp($episode_arr, 'episode_title');
- $parts['acts'] = getProp($episode_arr, 'acts', []);
- if (empty($parts['roles'])) {
- $parts['roles'] = getProp($episode_arr, 'roles', []);
- }
- if (empty($parts['scenes'])) {
- $parts['scenes'] = getProp($episode_arr, 'scenes', []);
- }
- }
- }
- if (empty($parts['acts'])) {
- $fallbackEpisodeArr = handleEpisodeContent($originalContent);
- if (!empty($fallbackEpisodeArr['acts'])) {
- $parts['episode_title'] = getProp($fallbackEpisodeArr, 'episode_title');
- $parts['acts'] = getProp($fallbackEpisodeArr, 'acts', []);
- if (empty($parts['intro'])) {
- $parts['intro'] = getProp($fallbackEpisodeArr, 'intro');
- }
- if (empty($parts['art_style'])) {
- $parts['art_style'] = getProp($fallbackEpisodeArr, 'art_style');
- }
- if (empty($parts['roles'])) {
- $parts['roles'] = getProp($fallbackEpisodeArr, 'roles', []);
- }
- if (empty($parts['scenes'])) {
- $parts['scenes'] = getProp($fallbackEpisodeArr, 'scenes', []);
- }
- }
- }
- // 多剧集格式:继续兼容旧的分集剧本结构
- $fullScript = '';
- if (preg_match('/###分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
- $fullScript = trim($storyboardMatch[1]);
- } elseif (preg_match('/##分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
- $fullScript = trim($storyboardMatch[1]);
- } elseif (preg_match('/分集剧本[::]\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
- $fullScript = trim($storyboardMatch[1]);
- }
- if (empty($fullScript) && preg_match('/(##分集.*)/su', $originalContent, $fallbackMatch)) {
- $fullScript = trim($fallbackMatch[1]);
- }
- $episodes = [];
- preg_match_all('/##分集(\d+)\s*\n分集名[::]\s*(.*?)\s*\n(?:场景描述[::].*?\n出场角色[::].*?\n台词内容[::]\s*\n)?(.*?)(?=\n##分集|$)/su', $fullScript, $matches, PREG_SET_ORDER);
- foreach ($matches as $match) {
- $episodeNumber = (int)trim($match[1]);
- $episodeName = trim($match[2]);
- $episodeContent = trim($match[3]);
- $segments = [];
- preg_match_all('/分镜(\d+)\s*\n(.*?)(?=\n分镜\d+|\z)/s', $episodeContent, $segmentMatches, PREG_SET_ORDER);
- foreach ($segmentMatches as $segMatch) {
- $segmentNumber = (int)trim($segMatch[1]);
- $segmentContent = trim($segMatch[2]);
- $segments[] = [
- 'segment_number' => $segmentNumber,
- 'segment_content' => $segmentContent,
- ];
- }
- $episodes[] = [
- 'episode_number' => $episodeNumber,
- 'title' => $episodeName,
- 'content' => $episodeContent,
- 'segments' => $segments,
- ];
- }
- if (empty($episodes) && !empty($parts['acts'])) {
- $singleSegments = [];
- foreach ($parts['acts'] as $act) {
- $actSegments = getProp($act, 'segments', []);
- if (!is_array($actSegments)) {
- continue;
- }
- foreach ($actSegments as $segment) {
- $singleSegments[] = [
- 'segment_number' => getProp($segment, 'segment_number'),
- 'segment_content' => getProp($segment, 'segment_content'),
- ];
- }
- }
- $episodeTitle = $parts['episode_title'] ?: ('第1集:' . ($parts['script_name'] ?? '未命名'));
- $episodeName = preg_replace('/^第\d+集[::]\s*/u', '', $episodeTitle);
- $episodes[] = [
- 'episode_number' => 1,
- 'title' => $episodeName,
- 'content' => $singleStoryboard,
- 'segments' => $singleSegments,
- ];
- }
- $parts['episodes'] = $episodes;
-
- return $parts;
- }
- function handleEpisodeContent($originalContent) {
- if (!$originalContent) return [];
-
- // 解析剧集内容
- $result = [
- 'episode_title' => '',
- 'intro' => '',
- 'art_style' => '',
- 'roles' => [],
- 'scenes' => [],
- 'acts' => []
- ];
-
- // 提取剧集标题 - 匹配"第xx集:标题"或"第xx集 标题"格式,排除###标记
- if (preg_match('/第(\d+)集[::\s]+([^#\n]+?)(?=\s*###|\s*$|\n)/u', $originalContent, $titleMatch)) {
- $result['episode_title'] = '第' . $titleMatch[1] . '集:' . trim($titleMatch[2]);
- }
-
- // 提取故事梗概 - 兼容多种格式:###故事梗概、### 故事梗概、### 故事梗概
- if (preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $summaryMatch)) {
- $result['intro'] = trim($summaryMatch[1]);
- }
-
- // 提取美术风格 - 兼容多种格式
- if (preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $styleMatch)) {
- $result['art_style'] = trim($styleMatch[1]);
- }
-
- // 提取主体列表 - 兼容多种格式
- if (preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $charactersMatch)) {
- $charactersText = trim($charactersMatch[1]);
- $characterLines = explode("\n", $charactersText);
-
- foreach ($characterLines as $line) {
- $line = trim($line);
- if (empty($line)) continue;
-
- // 兼容中文冒号:和英文冒号:,同时提取音色信息
- if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
- $role = trim($charMatch[1]);
- $description = trim($charMatch[2]);
- $timbreName = null;
-
- // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
- $picPrompt = null;
- if (preg_match('/^(.*?)\{([^}]+)\}\{\{([^}]+)\}\}\s*$/u', $description, $fullMatch)) {
- // 匹配格式:主体描述{主体图片提示词}{{音色名}}
- $description = trim($fullMatch[1]);
- $picPrompt = trim($fullMatch[2]);
- $timbreName = trim($fullMatch[3]);
- } elseif (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
- // 兼容旧格式:主体描述{{音色名}}
- $description = trim($timbreMatch[1]);
- $timbreName = trim($timbreMatch[2]);
- }
-
- $roleData = [
- 'role' => $role,
- 'description' => $description
- ];
-
- // 如果有主体图片提示词,添加到数组中
- if ($picPrompt) {
- // 检查开头是否有"全景,正面拍摄。"
- $prefix = '全景,正面拍摄。';
- $prefixParts = ['全景', '正面拍摄'];
-
- // 检查是否包含完整前缀
- if (strpos($picPrompt, $prefix) !== 0) {
- // 检查是否包含部分前缀词汇(不论位置)
- $hasAnyPrefix = false;
- foreach ($prefixParts as $part) {
- if (mb_strpos($picPrompt, $part) !== false) {
- $hasAnyPrefix = true;
- break;
- }
- }
-
- if ($hasAnyPrefix) {
- // 移除所有"全景"和"正面拍摄"词汇(包括它们后面的标点)
- $picPrompt = preg_replace('/全景[,,、。. ]*/u', '', $picPrompt);
- $picPrompt = preg_replace('/正面拍摄[,,、。. ]*/u', '', $picPrompt);
- // 清理开头和结尾的标点符号和空格
- $picPrompt = preg_replace('/^[。,,、 ]+|[。,,、 ]+$/u', '', $picPrompt);
- }
- // 在开头添加完整前缀
- $picPrompt = $prefix . $picPrompt;
- }
-
- // 检查是否包含"姿态:"或"姿态:"
- if (preg_match('/姿态[::]/u', $picPrompt)) {
- // 如果有姿态描述,统一替换为"姿态:站立"
- $picPrompt = preg_replace('/姿态[::][^.。\n]+/u', '姿态:站立', $picPrompt);
- } else {
- // 如果没有姿态描述,在末尾添加"姿态:站立"
- $picPrompt = preg_replace('/[。,, ]+$/u', '', $picPrompt) . '。姿态:站立。';
- }
-
- $roleData['pic_prompt'] = $picPrompt;
- }
-
- // 如果有音色信息,添加到数组中
- if ($timbreName) {
- $timbre = DB::table('mp_timbres')->where('is_enabled', 1)->where('timbre_name', 'like', "%{$timbreName}%")->orderBy('id')->select('timbre_type', 'audio_url')->first();
- if ($timbre) {
- $roleData['voice_name'] = $timbreName;
- $roleData['voice_type'] = getProp($timbre, 'timbre_type');
- $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');;
- }
- }else {
- // 从描述或人物提示词中获取"男"或"女",赋予默认音色,获取不到则使用旁白音色
- if ($picPrompt) {
- if (strstr($picPrompt, '男')) {
- $roleData['voice_name'] = '阳光青年';
- }elseif (strstr($picPrompt, '女')) {
- $roleData['voice_name'] = '爽快思思';
- }else {
- if ($description) {
- if (strstr($description, '男')) {
- $roleData['voice_name'] = '阳光青年';
- }elseif (strstr($description, '女')) {
- $roleData['voice_name'] = '爽快思思';
- }else {
- $roleData['voice_name'] = '旁白';
- }
- }
- }
- }
- if (!empty($roleData['voice_name'])) {
- if ($roleData['voice_name'] == '旁白') {
- $roleData['voice_type'] = 'zh_male_linjiananhai_moon_bigtts';
- $roleData['voice_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav';
- }else {
- $timbre = DB::table('mp_timbres')
- ->where('is_enabled', 1)
- ->where('timbre_name', 'like', "%".$roleData['voice_name']."%")
- ->orderBy('id')
- ->select('timbre_type', 'audio_url')
- ->first();
- if ($timbre) {
- $roleData['voice_type'] = getProp($timbre, 'timbre_type');
- $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
- }
- }
- }
- }
-
- $result['roles'][] = $roleData;
- }
- }
- // 加入旁白角色(如果不存在)
- $hasNarrator = false;
- foreach ($result['roles'] as $role) {
- if (isset($role['role']) && $role['role'] === '旁白') {
- $hasNarrator = true;
- break;
- }
- }
-
- if (!$hasNarrator) {
- $result['roles'][] = [
- 'role' => '旁白',
- 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
- 'pic_prompt' => '',
- 'voice_name' => '旁白',
- 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
- 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
- ];
- }
- }
-
- // 提取场景列表 - 兼容多种格式
- if (preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $scenesMatch)) {
- $scenesText = trim($scenesMatch[1]);
- $sceneLines = explode("\n", $scenesText);
-
- foreach ($sceneLines as $line) {
- $line = trim($line);
- if (empty($line)) continue;
-
- // 兼容中文冒号:和英文冒号:
- if (preg_match('/^([^::]+)[::](.+)$/u', $line, $sceneMatch)) {
- $scene = trim($sceneMatch[1]);
- $description = trim($sceneMatch[2]);
- $picPrompt = null;
-
- // 检查描述末尾是否有{场景图片提示词}格式
- if (preg_match('/^(.*?)\{([^}]+)\}\s*$/u', $description, $promptMatch)) {
- // 匹配格式:场景描述{场景图片提示词}
- $description = trim($promptMatch[1]);
- $picPrompt = trim($promptMatch[2]);
- }
-
- $sceneData = [
- 'scene' => $scene,
- 'description' => $description
- ];
-
- // 如果有场景图片提示词,添加到数组中
- if ($picPrompt) {
- $sceneData['pic_prompt'] = $picPrompt;
- }
-
- $result['scenes'][] = $sceneData;
- }
- }
- }
-
- // 提取分镜剧本 - 兼容多种格式
- if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $storyboardMatch)) {
- $storyboardText = trim($storyboardMatch[1]);
-
- // 按幕分割 - 修复第1幕识别和乱码问题
- $acts = [];
-
- // 先在开头添加换行符,确保第1幕也能被正确分割
- $normalizedText = "\n" . $storyboardText;
- $parts = preg_split('/\n\s*##/', $normalizedText);
-
- foreach ($parts as $part) {
- $part = trim($part);
- if (empty($part)) continue;
-
- // 如果不是以"第"开头,跳过
- if (!preg_match('/^第\d+幕/', $part)) {
- continue;
- }
-
- // 分离标题和内容
- $lines = explode("\n", $part, 2);
- $actTitle = trim($lines[0]);
- $actContent = isset($lines[1]) ? trim($lines[1]) : '';
-
- // 解析幕标题,提取序号和详细信息 - 修复乱码问题
- if (preg_match('/^第(\d+)幕[::]?\s*(.*)$/u', $actTitle, $actTitleMatch)) {
- $actNumber = intval($actTitleMatch[1]);
- $actDetails = trim($actTitleMatch[2]);
- // 如果详细信息为空或者就是冒号,使用完整标题
- if (empty($actDetails) || $actDetails === ':' || $actDetails === ':') {
- $actDetails = $actTitle;
- }
- } else {
- $actNumber = count($acts) + 1;
- $actDetails = $actTitle;
- }
-
- // 解析该幕下的分镜
- $segments = [];
- $segmentPattern = '/分镜(\d+)\s*\n(.*?)(?=\n+\s*分镜\d+|\z)/s';
- preg_match_all($segmentPattern, $actContent, $segmentMatches, PREG_SET_ORDER);
-
- foreach ($segmentMatches as $segmentMatch) {
- $segmentNumber = intval($segmentMatch[1]);
- $segmentContent = trim($segmentMatch[2]);
-
- // 解析分镜详细信息
- $segmentData = [
- 'segment_id' => date('YmdHis') . mt_rand(1000, 9999) . str_pad($segmentNumber, 3, "0", STR_PAD_LEFT), // 生成唯一ID(后续可在生成任务里查看历史版本)
- 'segment_number' => $segmentNumber,
- 'segment_content' => $segmentContent,
- 'description' => '',
- 'composition' => '',
- 'camera_movement' => '',
- 'voice_actor' => '',
- 'dialogue' => '',
- 'frame_type' => '',
- 'scene' => '', // 新增:场景
- 'characters' => '', // 新增:出镜角色
- 'tail_frame' => '', // 新增:尾帧描述
- // 新增字段
- 'emotion' => '中性', // 新增: 情感
- 'gender' => '0', // 新增: 性别(0未知,1男,2女)
- 'speed_ratio' => 0, // 新增: 语速
- 'loudness_ratio' => 0, // 新增: 音量
- 'emotion_scale' => 4, // 新增: 语调
- 'pitch' => 0, // 新增: 音调
- ];
-
- // 提取各个字段 - 兼容中文冒号和英文冒号,支持多种表达方式
- if (preg_match('/(?:画面描述|镜头描述|场景描述)[::]\s*([^\n]+)/u', $segmentContent, $descMatch)) {
- $segmentData['description'] = trim($descMatch[1]);
- }
- if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
- $segmentData['composition'] = trim($compMatch[1]);
- }
- if (preg_match('/(?:运镜调度|运镜|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
- $segmentData['camera_movement'] = trim($cameraMatch[1]);
- }
- if (preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
- $segmentData['voice_actor'] = trim($voiceMatch[1]);
- }
- if (preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]+)/u', $segmentContent, $dialogueMatch)) {
- $dialogue = trim($dialogueMatch[1]) == '无' ? '' : trim($dialogueMatch[1]);
-
- // 确保台词使用中文左右双引号
- if (!empty($dialogue)) {
- $dialogue = preg_replace('/^["”]/u', '“', $dialogue); // 替换句首英文双引号或中文右双引号
- $dialogue = preg_replace('/["“]$/u', '”', $dialogue); // 替换句尾英文双引号或中文左双引号
- // 句首或句尾没有中文双引号,则分别添加中文左右双引号
- if (!preg_match('/^[“]/', $dialogue)) {
- $dialogue = '“' . $dialogue;
- }
- if (!preg_match('/[”]$/', $dialogue)) {
- $dialogue .= '”';
- }
-
- // 将修改后的台词替换回 $segmentContent
- $originalDialogue = $dialogueMatch[1];
- $segmentContent = str_replace($originalDialogue, $dialogue, $segmentContent);
- }
-
- $segmentData['dialogue'] = $dialogue;
- }
- if (preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
- $segmentData['frame_type'] = trim($frameMatch[1]);
- }
- // 新增:场景字段
- if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
- $segmentData['scene'] = trim($sceneMatch[1]);
- }
- // 新增:出镜角色字段
- if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
- $segmentData['characters'] = trim($charactersMatch[1]);
- }
- // 新增:尾帧描述字段
- if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
- $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
- }
- $replaceEmptyArr = [];
- // 新增:情感字段
- if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
- $replaceEmptyArr[] = trim($emotionMatch[0]);
- $segmentData['emotion'] = trim($emotionMatch[1]);
- }
- // 新增:性别字段
- if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
- $replaceEmptyArr[] = trim($genderMatch[0]);
- $genderStr = trim($genderMatch[1]);
- if (strpos($genderStr, '男') !== false || $genderStr === '1') {
- $segmentData['gender'] = '1';
- } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
- $segmentData['gender'] = '2';
- } else {
- $segmentData['gender'] = '0';
- }
- }
- // 新增:语速字段
- if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
- $replaceEmptyArr[] = trim($speedMatch[0]);
- $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
- }
- // 新增:音量字段
- if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
- $replaceEmptyArr[] = trim($loudnessMatch[0]);
- $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
- }
- // 新增:情感强度字段
- if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
- $replaceEmptyArr[] = trim($scaleMatch[0]);
- $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
- }
- // 新增:音调字段
- if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
- $replaceEmptyArr[] = trim($pitchMatch[0]);
- $segmentData['pitch'] = (int)trim($pitchMatch[1]);
- }
- $segmentData['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
- // 去除多余的换行符(将连续多个换行符替换为单个换行符)
- $segmentData['segment_content'] = preg_replace('/\n{2,}/', "\n", $segmentData['segment_content']);
- $segmentData['segment_content'] = trim($segmentData['segment_content']);
-
- $segments[] = $segmentData;
- }
-
- $acts[] = [
- 'act_number' => $actNumber,
- 'act_title' => $actTitle,
- 'act_details' => $actDetails,
- 'segments' => $segments
- ];
- }
-
- $result['acts'] = $acts;
- }
-
- return $result;
- }
- /**
- * 处理剧本内容(全能模式)
- */
- function handleScriptContentForAce($originalContent) {
- if (!$originalContent) return [];
-
- // 使用更精确的正则表达式分割内容
- $parts = [];
-
- // // 确保内容使用UTF-8编码
- // if (!mb_check_encoding($originalContent, 'UTF-8')) {
- // $originalContent = mb_convert_encoding($originalContent, 'UTF-8', 'auto');
- // }
-
- // 提取剧本名(###剧本名:后面的内容,支持多个空格)
- preg_match('/###\s*剧本名\s*[::]\s*(.*?)(?=\n|$)/u', $originalContent, $scriptNameMatch);
- $parts['script_name'] = isset($scriptNameMatch[1]) ? trim($scriptNameMatch[1]) : '';
- // 提取故事梗概(直到遇到下一个###标记,支持多个空格)
- preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $summaryMatch);
- $parts['intro'] = isset($summaryMatch[1]) ? trim($summaryMatch[1]) : '';
-
- // 提取剧本亮点(支持多个空格)
- preg_match('/###\s*剧本亮点\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $highlightsMatch);
- $parts['highlights'] = isset($highlightsMatch[1]) ? trim($highlightsMatch[1]) : '';
-
- // 提取人物关系(支持多个空格)
- preg_match('/###\s*人物关系\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $relationsMatch);
- $parts['role_relationship'] = isset($relationsMatch[1]) ? trim($relationsMatch[1]) : '';
-
- // 提取核心矛盾(支持多个空格)
- preg_match('/###\s*核心矛盾\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contradictionsMatch);
- $parts['core_contradiction'] = isset($contradictionsMatch[1]) ? trim($contradictionsMatch[1]) : '';
-
- // 提取主体列表(支持多个空格)
- preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $subjectsMatch);
- $rolesText = isset($subjectsMatch[1]) ? trim($subjectsMatch[1]) : '';
- $parts['roles'] = parseRolesFromTextForAce($rolesText);
-
- // 提取美术风格(支持多个空格)
- preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $artStyleMatch);
- $parts['art_style'] = isset($artStyleMatch[1]) ? trim($artStyleMatch[1]) : '';
-
- // 提取场景列表(支持多个空格)
- preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $scenesMatch);
- $scenesText = isset($scenesMatch[1]) ? trim($scenesMatch[1]) : '';
- $parts['scenes'] = parseScenesFromText($scenesText);
- // 提取分集详细内容(多剧集模式,支持多个空格)
- preg_match('/###\s*分集详细内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $contentMatch);
- $detailedContent = isset($contentMatch[1]) ? trim($contentMatch[1]) : '';
-
- // 提取原文内容(单剧集模式,AI生成的原文,支持多个空格)
- preg_match('/###\s*原文内容\s*\n(.*?)(?=\n\s*###|$)/s', $originalContent, $originalContentMatch);
- $generatedContent = isset($originalContentMatch[1]) ? trim($originalContentMatch[1]) : '';
-
- // 优先使用原文内容,其次使用分集详细内容
- $parts['content'] = $generatedContent ?: $detailedContent;
- $parts['episode_title'] = '';
- $parts['acts'] = [];
- // 单剧集格式:顶层是大纲信息,分段部分采用 handleEpisodeContentForAce 的结构标准
- $singleStoryboard = '';
- if (preg_match('/###\s*分镜剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
- $singleStoryboard = trim($singleStoryboardMatch[1]);
- } elseif (preg_match('/###\s*分段剧本\s*\n(.*?)(?=\n\s*###[^#]|\z)/su', $originalContent, $singleStoryboardMatch)) {
- $singleStoryboard = trim($singleStoryboardMatch[1]);
- }
- if ($singleStoryboard !== '') {
- // 构造符合 handleEpisodeContentForAce 期望的输入格式
- $episodeContent = '';
-
- // 如果分镜剧本内容不包含剧集标题,添加默认标题
- if (!preg_match('/第\d+集[::\s]+/u', $singleStoryboard)) {
- $defaultEpisodeTitle = '第1集:' . ($parts['script_name'] ?? '未命名');
- $episodeContent = $defaultEpisodeTitle . "\n\n";
- }
-
- // 组装完整的剧集内容,按 handleEpisodeContentForAce 期望的结构
- $episodeSections = [];
-
- // 添加故事梗概(如果有)
- if (!empty($parts['intro'])) {
- $episodeSections[] = "###故事梗概\n" . $parts['intro'];
- }
-
- // 添加美术风格(如果有)
- if (!empty($parts['art_style'])) {
- $episodeSections[] = "###美术风格\n" . $parts['art_style'];
- }
-
- // 添加主体列表(如果有)
- if (!empty($rolesText)) {
- $episodeSections[] = "###主体列表\n" . $rolesText;
- }
-
- // 添加场景列表(如果有)
- if (!empty($scenesText)) {
- $episodeSections[] = "###场景列表\n" . $scenesText;
- }
-
- // 添加分镜剧本内容(兼容"分镜剧本"和"分段剧本")
- if (strpos($singleStoryboard, '###分镜剧本') === false && strpos($singleStoryboard, '###分段剧本') === false) {
- $episodeSections[] = "###分镜剧本\n" . $singleStoryboard;
- } else {
- $episodeSections[] = $singleStoryboard;
- }
-
- // 拼接完整内容
- $episodeContent .= implode("\n\n", $episodeSections);
-
- // 调用 handleEpisodeContentForAce 方法解析
- $episode_arr = handleEpisodeContentForAce($episodeContent);
-
- if (!empty($episode_arr['acts'])) {
- $parts['episode_title'] = getProp($episode_arr, 'episode_title', '');
- $parts['acts'] = getProp($episode_arr, 'acts', []);
- }
- // 更新roles和scenes
- $episode_roles = getProp($episode_arr, 'roles');
- $episode_scenes = getProp($episode_arr, 'scenes');
- if ($episode_roles) $parts['roles'] = $episode_roles;
- if ($episode_scenes) $parts['scenes'] = $episode_scenes;
- }
- // 如果上面的处理没有得到 acts,尝试直接用原始内容调用 handleEpisodeContentForAce
- if (empty($parts['acts'])) {
- $fallbackEpisodeArr = handleEpisodeContentForAce($originalContent);
- if (!empty($fallbackEpisodeArr['acts'])) {
- $parts['episode_title'] = getProp($fallbackEpisodeArr, 'episode_title', '');
- $parts['acts'] = getProp($fallbackEpisodeArr, 'acts', []);
- if (empty($parts['intro'])) {
- $parts['intro'] = getProp($fallbackEpisodeArr, 'intro', '');
- }
- if (empty($parts['art_style'])) {
- $parts['art_style'] = getProp($fallbackEpisodeArr, 'art_style', '');
- }
- }
- // 更新roles和scenes
- $episode_roles = getProp($fallbackEpisodeArr, 'roles');
- $episode_scenes = getProp($fallbackEpisodeArr, 'scenes');
- if ($episode_roles) $parts['roles'] = $episode_roles;
- if ($episode_scenes) $parts['scenes'] = $episode_scenes;
- }
- // 多剧集格式:继续兼容旧的分集剧本结构
- $fullScript = '';
- if (preg_match('/###分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
- $fullScript = trim($storyboardMatch[1]);
- } elseif (preg_match('/##分集剧本\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
- $fullScript = trim($storyboardMatch[1]);
- } elseif (preg_match('/分集剧本[::]\s*\n(.*)/su', $originalContent, $storyboardMatch)) {
- $fullScript = trim($storyboardMatch[1]);
- }
- if (empty($fullScript) && preg_match('/(##分集.*)/su', $originalContent, $fallbackMatch)) {
- $fullScript = trim($fallbackMatch[1]);
- }
- $episodes = [];
- preg_match_all('/##分集(\d+)\s*\n分集名[::]\s*(.*?)\s*\n(?:场景描述[::].*?\n出场角色[::].*?\n台词内容[::]\s*\n)?(.*?)(?=\n##分集|$)/su', $fullScript, $matches, PREG_SET_ORDER);
- foreach ($matches as $match) {
- $episodeNumber = (int)trim($match[1]);
- $episodeName = trim($match[2]);
- $episodeContent = trim($match[3]);
- $segments = [];
- preg_match_all('/分镜(\d+)\s*\n(.*?)(?=\n分镜\d+|\z)/s', $episodeContent, $segmentMatches, PREG_SET_ORDER);
- foreach ($segmentMatches as $segMatch) {
- $segmentNumber = (int)trim($segMatch[1]);
- $segmentContent = trim($segMatch[2]);
- $segments[] = [
- 'segment_number' => $segmentNumber,
- 'segment_content' => $segmentContent,
- ];
- }
- $episodes[] = [
- 'episode_number' => $episodeNumber,
- 'title' => $episodeName,
- 'content' => $episodeContent,
- 'segments' => $segments,
- ];
- }
- if (empty($episodes) && !empty($parts['acts'])) {
- $singleSegments = [];
- foreach ($parts['acts'] as $act) {
- $actSegments = getProp($act, 'segments', []);
- if (!is_array($actSegments)) {
- continue;
- }
- foreach ($actSegments as $segment) {
- $singleSegments[] = [
- 'segment_number' => getProp($segment, 'segment_number'),
- 'segment_content' => getProp($segment, 'segment_content'),
- ];
- }
- }
- $episodeTitle = $parts['episode_title'] ?: ('第1集:' . ($parts['script_name'] ?? '未命名'));
- $episodeName = preg_replace('/^第\d+集[::]\s*/u', '', $episodeTitle);
- $episodes[] = [
- 'episode_number' => 1,
- 'title' => $episodeName,
- 'content' => $singleStoryboard,
- 'segments' => $singleSegments,
- ];
- }
- $parts['episodes'] = $episodes;
-
- return $parts;
- }
- /**
- * 将主体列表文本拆分为主体数组
- *
- * @param string $rolesText 主体列表文本内容
- * @return array 主体名称数组
- */
- function parseRolesFromTextForAce(string $rolesText): array
- {
- if (empty($rolesText)) {
- return [];
- }
-
- $roles = [];
-
- // 按行分割文本
- $lines = explode("\n", $rolesText);
-
- foreach ($lines as $line) {
- $line = trim($line);
- if (empty($line)) {
- continue;
- }
- if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
- $role = trim($charMatch[1]);
- $description = trim($charMatch[2]);
- $timbreName = null;
- // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
- $picPrompt = null;
- $timbrePrompt = null;
- if (preg_match('/^(.*?)\{([^}]+)\}\{\{([^}]+)\}\}\s*$/u', $description, $fullMatch)) {
- // 匹配格式:主体描述{主体图片提示词}{{音色名}}
- $description = trim($fullMatch[1]);
- $picPrompt = trim($fullMatch[2]);
- $timbrePrompt = trim($fullMatch[3]);
- } elseif (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
- // 兼容旧格式:主体描述{{音色名}}
- $description = trim($timbreMatch[1]);
- $timbrePrompt = trim($timbreMatch[2]);
- }
- $roleData = [
- 'role' => $role,
- 'description' => $description,
- ];
- // 如果有主体图片提示词,添加到数组中
- if ($picPrompt) $roleData['pic_prompt'] = $picPrompt;
- // 如果有音色提示词,添加到数组中
- if ($timbrePrompt) $roleData['voice_prompt'] = $timbrePrompt;
- if ($timbreName) {
- $timbre = DB::table('mp_timbres')
- ->where('is_enabled', 1)
- ->where('timbre_name', 'like', "%{$timbreName}%")
- ->orderBy('id')
- ->select('timbre_type', 'audio_url')
- ->first();
- if ($timbre) {
- $roleData['voice_name'] = $timbreName;
- $roleData['voice_type'] = getProp($timbre, 'timbre_type');
- $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
- }
- }
- // else {
- // // 从描述或人物提示词中获取"男"或"女",赋予默认音色,获取不到则使用旁白音色
- // if ($picPrompt) {
- // if (strstr($picPrompt, '男')) {
- // $roleData['voice_name'] = '阳光青年';
- // }elseif (strstr($picPrompt, '女')) {
- // $roleData['voice_name'] = '爽快思思';
- // }else {
- // if ($description) {
- // if (strstr($description, '男')) {
- // $roleData['voice_name'] = '阳光青年';
- // }elseif (strstr($description, '女')) {
- // $roleData['voice_name'] = '爽快思思';
- // }else {
- // $roleData['voice_name'] = '旁白';
- // }
- // }
- // }
- // }
- // if (!empty($roleData['voice_name'])) {
- // if ($roleData['voice_name'] == '旁白') {
- // $roleData['voice_type'] = 'zh_male_linjiananhai_moon_bigtts';
- // $roleData['voice_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav';
- // }else {
- // $timbre = DB::table('mp_timbres')
- // ->where('is_enabled', 1)
- // ->where('timbre_name', 'like', "%".$roleData['voice_name']."%")
- // ->orderBy('id')
- // ->select('timbre_type', 'audio_url')
- // ->first();
- // if ($timbre) {
- // $roleData['voice_type'] = getProp($timbre, 'timbre_type');
- // $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
- // }
- // }
- // }
- // }
- $roles[] = $roleData;
- }
- }
- $hasNarrator = false;
- foreach ($roles as $role) {
- if (getProp($role, 'role') === '旁白') {
- $hasNarrator = true;
- break;
- }
- }
- if (!$hasNarrator) {
- $roles[] = [
- 'role' => '旁白',
- 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
- 'pic_prompt' => '',
- 'voice_prompt' => '',
- // 'voice_name' => '旁白',
- // 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
- // 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
- ];
- }
-
- return $roles;
- }
- function handleEpisodeContentForAce($originalContent) {
- if (!$originalContent) return [];
-
- // 解析剧集内容
- $result = [
- 'episode_title' => '',
- 'intro' => '',
- 'art_style' => '',
- 'roles' => [],
- 'scenes' => [],
- 'acts' => []
- ];
-
- // 提取剧集标题 - 匹配"第xx集:标题"或"第xx集 标题"格式,排除###标记
- if (preg_match('/第(\d+)集[::\s]+([^#\n]+?)(?=\s*###|\s*$|\n)/u', $originalContent, $titleMatch)) {
- $result['episode_title'] = '第' . $titleMatch[1] . '集:' . trim($titleMatch[2]);
- }
-
- // 提取故事梗概 - 兼容多种格式:###故事梗概、### 故事梗概、### 故事梗概
- if (preg_match('/###\s*故事梗概\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $summaryMatch)) {
- $result['intro'] = trim($summaryMatch[1]);
- }
-
- // 提取美术风格 - 兼容多种格式
- if (preg_match('/###\s*美术风格\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $styleMatch)) {
- $result['art_style'] = trim($styleMatch[1]);
- }
-
- // 提取主体列表 - 兼容多种格式
- if (preg_match('/###\s*主体列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $charactersMatch)) {
- $charactersText = trim($charactersMatch[1]);
- $characterLines = explode("\n", $charactersText);
-
- foreach ($characterLines as $line) {
- $line = trim($line);
- if (empty($line)) continue;
-
- // 兼容中文冒号:和英文冒号:,同时提取音色信息
- if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
- $role = trim($charMatch[1]);
- $description = trim($charMatch[2]);
- $timbreName = null;
-
- // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
- $picPrompt = null;
- $timbrePrompt = null;
-
- // 修复正则:使用更精确的匹配,支持花括号嵌套
- // 格式1: 描述{pic_prompt} {{voice_prompt}}
- if (preg_match('/^(.*?)\{(.+?)\}\s*\{\{(.+?)\}\}\s*$/u', $description, $fullMatch)) {
- // 匹配格式:主体描述{主体图片提示词}{{音色名}}
- $description = trim($fullMatch[1]);
- $picPrompt = trim($fullMatch[2]);
- $timbrePrompt = trim($fullMatch[3]);
- }
- // 格式2: 描述{{voice_prompt}}(兼容旧格式,只有音色)
- elseif (preg_match('/^(.*?)\{\{(.+?)\}\}\s*$/u', $description, $timbreMatch)) {
- // 兼容旧格式:主体描述{{音色名}}
- $description = trim($timbreMatch[1]);
- $timbrePrompt = trim($timbreMatch[2]);
- }
- // 格式3: 描述{pic_prompt}(只有图片提示词)
- elseif (preg_match('/^(.*?)\{(.+?)\}\s*$/u', $description, $picMatch)) {
- $description = trim($picMatch[1]);
- $picPrompt = trim($picMatch[2]);
- }
-
- $roleData = [
- 'role' => $role,
- 'description' => $description
- ];
-
- // 如果有主体图片提示词,添加到数组中
- if ($picPrompt) {
- // 检查开头是否有"全景,正面拍摄。"
- $prefix = '全景,正面拍摄。';
- $prefixParts = ['全景', '正面拍摄'];
-
- // 检查是否包含完整前缀
- if (strpos($picPrompt, $prefix) !== 0) {
- // 检查是否包含部分前缀词汇(不论位置)
- $hasAnyPrefix = false;
- foreach ($prefixParts as $part) {
- if (mb_strpos($picPrompt, $part) !== false) {
- $hasAnyPrefix = true;
- break;
- }
- }
-
- if ($hasAnyPrefix) {
- // 移除所有"全景"和"正面拍摄"词汇(包括它们后面的标点)
- $picPrompt = preg_replace('/全景[,,、。. ]*/u', '', $picPrompt);
- $picPrompt = preg_replace('/正面拍摄[,,、。. ]*/u', '', $picPrompt);
- // 清理开头和结尾的标点符号和空格
- $picPrompt = preg_replace('/^[。,,、 ]+|[。,,、 ]+$/u', '', $picPrompt);
- }
- // 在开头添加完整前缀
- $picPrompt = $prefix . $picPrompt;
- }
- // 检查是否包含"姿态:"或"姿态:"
- if (preg_match('/姿态[::]/u', $picPrompt)) {
- // 如果有姿态描述,统一替换为"姿态:站立"
- $picPrompt = preg_replace('/姿态[::][^.。\n]+/u', '姿态:站立', $picPrompt);
- } else {
- // 如果没有姿态描述,在末尾添加"姿态:站立"
- $picPrompt = preg_replace('/[。,, ]+$/u', '', $picPrompt) . '。姿态:站立。';
- }
-
- $roleData['pic_prompt'] = $picPrompt;
- }
-
- if ($timbrePrompt) $roleData['voice_prompt'] = $timbrePrompt;
-
- $result['roles'][] = $roleData;
- }
- }
- // // 加入旁白角色(如果不存在)
- // $hasNarrator = false;
- // foreach ($result['roles'] as $role) {
- // if (isset($role['role']) && $role['role'] === '旁白') {
- // $hasNarrator = true;
- // break;
- // }
- // }
-
- // if (!$hasNarrator) {
- // $result['roles'][] = [
- // 'role' => '旁白',
- // 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
- // 'pic_prompt' => '',
- // 'voice_name' => '旁白',
- // 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
- // 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
- // ];
- // }
- }
-
- // 提取场景列表 - 兼容多种格式
- if (preg_match('/###\s*场景列表\s*\n(.*?)(?=\n\s*###[^#]|\z)/s', $originalContent, $scenesMatch)) {
- $scenesText = trim($scenesMatch[1]);
- $sceneLines = explode("\n", $scenesText);
-
- foreach ($sceneLines as $line) {
- $line = trim($line);
- if (empty($line)) continue;
-
- // 兼容中文冒号:和英文冒号:
- if (preg_match('/^([^::]+)[::](.+)$/u', $line, $sceneMatch)) {
- $scene = trim($sceneMatch[1]);
- $description = trim($sceneMatch[2]);
- $picPrompt = null;
-
- // 检查描述末尾是否有{场景图片提示词}格式
- if (preg_match('/^(.*?)\{([^}]+)\}\s*$/u', $description, $promptMatch)) {
- // 匹配格式:场景描述{场景图片提示词}
- $description = trim($promptMatch[1]);
- $picPrompt = trim($promptMatch[2]);
- }
-
- $sceneData = [
- 'scene' => $scene,
- 'description' => $description
- ];
-
- // 如果有场景图片提示词,添加到数组中
- if ($picPrompt) {
- $sceneData['pic_prompt'] = $picPrompt;
- }
-
- $result['scenes'][] = $sceneData;
- }
- }
- }
-
- // 提取分镜剧本 - 兼容多种格式(旧格式:###分镜剧本,新格式:###分段剧本)
- $storyboardPattern = '/###\s*(?:分镜剧本|分段剧本)\s*\n(.*?)(?=\n\s*###[^#]|\z)/s';
- if (preg_match($storyboardPattern, $originalContent, $storyboardMatch)) {
- $storyboardText = trim($storyboardMatch[1]);
-
- // 提取旁白音色(新格式独有)
- $narratorVoice = '';
- if (preg_match('/旁白音色[::]\s*([^\n]+)/u', $storyboardText, $narratorMatch)) {
- $narratorVoice = trim($narratorMatch[1]);
-
- // 将旁白加入到roles数组
- $hasNarrator = false;
- foreach ($result['roles'] as $role) {
- if (isset($role['role']) && $role['role'] === '旁白') {
- $hasNarrator = true;
- break;
- }
- }
-
- if (!$hasNarrator) {
- $result['roles'][] = [
- 'role' => '旁白',
- 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
- 'pic_prompt' => '',
- 'voice_prompt' => $narratorVoice
- ];
- }
- }
-
- // 按幕/片段分割 - 兼容"第X幕"和"片段X"两种格式
- $acts = [];
-
- // 先在开头添加换行符,确保第1幕/片段1也能被正确分割
- $normalizedText = "\n" . $storyboardText;
- $parts = preg_split('/\n\s*##/', $normalizedText);
-
- foreach ($parts as $part) {
- $part = trim($part);
- if (empty($part)) continue;
-
- // 兼容"第X幕"和"片段X"两种格式
- if (!preg_match('/^(?:第\d+幕|片段\d+)/', $part)) {
- continue;
- }
-
- // 分离标题和内容
- $lines = explode("\n", $part, 2);
- $actTitle = trim($lines[0]);
- $actContent = isset($lines[1]) ? trim($lines[1]) : '';
-
- // 解析标题,提取序号和详细信息
- if (preg_match('/^第(\d+)幕[::]?\s*(.*)$/u', $actTitle, $actTitleMatch)) {
- // 旧格式:第X幕
- $actNumber = intval($actTitleMatch[1]);
- $actDetails = trim($actTitleMatch[2]);
- if (empty($actDetails) || $actDetails === ':' || $actDetails === ':') {
- $actDetails = $actTitle;
- }
- } elseif (preg_match('/^片段(\d+)\s*$/u', $actTitle, $segmentTitleMatch)) {
- // 新格式:片段X
- $actNumber = intval($segmentTitleMatch[1]);
- $actDetails = $actTitle;
- } else {
- $actNumber = count($acts) + 1;
- $actDetails = $actTitle;
- }
-
- // 提取时长(新格式独有,仅保留数字)
- $actDuration = '';
- if (preg_match('/时长[::]\s*([^\n]+)/u', $actContent, $actDurationMatch)) {
- $actDurationStr = trim($actDurationMatch[1]);
- // 提取数字部分(支持整数和小数)
- if (preg_match('/([-+]?[0-9]*\.?[0-9]+)/', $actDurationStr, $numMatch)) {
- $actDuration = $numMatch[1];
- }
- }
-
- // 解析该幕/片段下的分镜
- $segments = [];
- $segmentPattern = '/分镜(\d+)\s*\n(.*?)(?=\n+\s*分镜\d+|\z)/s';
- preg_match_all($segmentPattern, $actContent, $segmentMatches, PREG_SET_ORDER);
-
- foreach ($segmentMatches as $segmentMatch) {
- $segmentNumber = intval($segmentMatch[1]);
- $segmentContent = trim($segmentMatch[2]);
-
- // 解析分镜详细信息
- $segmentData = [
- 'segment_id' => date('YmdHis') . mt_rand(1000, 9999) . str_pad($segmentNumber, 3, "0", STR_PAD_LEFT),
- 'segment_number' => $segmentNumber,
- 'segment_content' => $segmentContent,
- 'description' => '',
- 'composition' => '',
- 'camera_movement' => '',
- 'voice_actor' => '',
- 'dialogue' => '',
- 'frame_type' => '',
- 'scene' => '',
- 'characters' => '',
- 'tail_frame' => '',
- 'emotion' => '中性',
- 'gender' => '0',
- 'speed_ratio' => 0,
- 'loudness_ratio' => 0,
- 'emotion_scale' => 4,
- 'pitch' => 0,
- ];
-
- // 提取场景
- if (preg_match('/(?:场景|拍摄场景|背景场景|环境)[::]\s*([^\n]+)/u', $segmentContent, $sceneMatch)) {
- $segmentData['scene'] = trim($sceneMatch[1]);
- }
-
- // 提取画面描述 - 兼容新格式的方括号标注
- if (preg_match('/(?:画面|画面描述|镜头描述|场景描述)[::]\s*(\[.*?\])?\s*([^\n]+)/u', $segmentContent, $descMatch)) {
- $frameTypeInDesc = isset($descMatch[1]) ? trim($descMatch[1], '[]') : '';
- $description = trim($descMatch[2]);
-
- if (!empty($frameTypeInDesc)) {
- $segmentData['frame_type'] = $frameTypeInDesc;
- }
- $segmentData['description'] = $description;
- }
-
- // 提取运镜
- if (preg_match('/(?:运镜|运镜调度|镜头运动|摄影机运动)[::]\s*([^\n]+)/u', $segmentContent, $cameraMatch)) {
- $segmentData['camera_movement'] = trim($cameraMatch[1]);
- }
-
- // 提取配音台词 - 兼容新格式"中文配音:[角色] 台词"
- // 修复:排除背景音效等非台词内容
- if (preg_match('/配音台词[::]\s*(?:中文配音[::]?)?\s*(?:\[([^\]]+)\])?\s*([^\n]*?)(?=\n|$)/u', $segmentContent, $dialogueMatch)) {
- $voiceActor = isset($dialogueMatch[1]) ? trim($dialogueMatch[1]) : '';
- $dialogue = isset($dialogueMatch[2]) ? trim($dialogueMatch[2]) : '';
-
- // 排除非台词内容(如果匹配到的是空或者是其他字段标记)
- if (!empty($dialogue) && preg_match('/^(?:背景音效|音效|场景|画面|运镜|构图)[::]/u', $dialogue)) {
- $dialogue = ''; // 如果匹配到的是其他字段,清空
- }
-
- if (!empty($voiceActor)) {
- $segmentData['voice_actor'] = $voiceActor;
- }
-
- if ($dialogue && $dialogue !== '无') {
- // 确保台词使用中文左右双引号
- $dialogue = preg_replace('/^[""]/u', '"', $dialogue);
- $dialogue = preg_replace('/[""]$/u', '"', $dialogue);
- if (!preg_match('/^["]/', $dialogue)) {
- $dialogue = '"' . $dialogue;
- }
- if (!preg_match('/["]$/', $dialogue)) {
- $dialogue .= '"';
- }
- $segmentData['dialogue'] = $dialogue;
- }
- }
-
- // 兼容旧格式的台词字段
- // 修复:排除背景音效等非台词内容
- if (empty($segmentData['dialogue']) && preg_match('/(?:台词内容|台词|对白|对话)[::]\s*([^\n]*?)(?=\n|$)/u', $segmentContent, $oldDialogueMatch)) {
- $dialogue = trim($oldDialogueMatch[1]);
-
- // 排除非台词内容
- if (!empty($dialogue) && preg_match('/^(?:背景音效|音效|场景|画面|运镜|构图)[::]/u', $dialogue)) {
- $dialogue = ''; // 如果匹配到的是其他字段,清空
- }
-
- if ($dialogue && $dialogue !== '无') {
- $dialogue = preg_replace('/^[""]/u', '"', $dialogue);
- $dialogue = preg_replace('/[""]$/u', '"', $dialogue);
- if (!preg_match('/^["]/', $dialogue)) {
- $dialogue = '"' . $dialogue;
- }
- if (!preg_match('/["]$/', $dialogue)) {
- $dialogue .= '"';
- }
- $segmentData['dialogue'] = $dialogue;
- }
- }
-
- // 兼容旧格式的配音角色字段
- if (empty($segmentData['voice_actor']) && preg_match('/(?:配音角色|配音|角色|声优)[::]\s*([^\n]+)/u', $segmentContent, $voiceMatch)) {
- $segmentData['voice_actor'] = trim($voiceMatch[1]);
- }
-
- // 提取构图
- if (preg_match('/(?:构图设计|构图|镜头构图)[::]\s*([^\n]+)/u', $segmentContent, $compMatch)) {
- $segmentData['composition'] = trim($compMatch[1]);
- }
-
- // 提取画面类型
- if (empty($segmentData['frame_type']) && preg_match('/(?:画面类型|镜头类型|类型)[::]\s*([^\n]+)/u', $segmentContent, $frameMatch)) {
- $segmentData['frame_type'] = trim($frameMatch[1]);
- }
-
- // 提取出镜角色
- if (preg_match('/(?:出镜角色|角色出镜|登场角色|人物)[::]\s*([^\n]+)/u', $segmentContent, $charactersMatch)) {
- $segmentData['characters'] = trim($charactersMatch[1]);
- }
-
- // 提取尾帧描述
- if (preg_match('/(?:尾帧描述|尾帧|结束帧|最后一帧|结尾画面|结束画面)[::]\s*([^\n]+)/u', $segmentContent, $tailFrameMatch)) {
- $segmentData['tail_frame'] = trim($tailFrameMatch[1]);
- }
-
- $replaceEmptyArr = [];
-
- // 提取情感
- if (preg_match('/(?:情感|情绪|感情)[::]\s*([^\n]+)/u', $segmentContent, $emotionMatch)) {
- $replaceEmptyArr[] = trim($emotionMatch[0]);
- $segmentData['emotion'] = trim($emotionMatch[1]);
- }
-
- // 提取性别
- if (preg_match('/(?:性别)[::]\s*([^\n]+)/u', $segmentContent, $genderMatch)) {
- $replaceEmptyArr[] = trim($genderMatch[0]);
- $genderStr = trim($genderMatch[1]);
- if (strpos($genderStr, '男') !== false || $genderStr === '1') {
- $segmentData['gender'] = '1';
- } elseif (strpos($genderStr, '女') !== false || $genderStr === '2') {
- $segmentData['gender'] = '2';
- } else {
- $segmentData['gender'] = '0';
- }
- }
-
- // 提取语速
- if (preg_match('/(?:语速|说话速度)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $speedMatch)) {
- $replaceEmptyArr[] = trim($speedMatch[0]);
- $segmentData['speed_ratio'] = (float)trim($speedMatch[1]);
- }
-
- // 提取音量
- if (preg_match('/(?:音量|声音大小)[::]\s*([-+]?[0-9]*\.?[0-9]+)/u', $segmentContent, $loudnessMatch)) {
- $replaceEmptyArr[] = trim($loudnessMatch[0]);
- $segmentData['loudness_ratio'] = (float)trim($loudnessMatch[1]);
- }
-
- // 提取情感强度
- if (preg_match('/(?:情感强度|情绪强度)[::]\s*([0-9]+)/u', $segmentContent, $scaleMatch)) {
- $replaceEmptyArr[] = trim($scaleMatch[0]);
- $segmentData['emotion_scale'] = (int)trim($scaleMatch[1]);
- }
-
- // 提取音调
- if (preg_match('/(?:音调|音高)[::]\s*([-+]?[0-9]+)/u', $segmentContent, $pitchMatch)) {
- $replaceEmptyArr[] = trim($pitchMatch[0]);
- $segmentData['pitch'] = (int)trim($pitchMatch[1]);
- }
- $segmentData['segment_content'] = str_replace($replaceEmptyArr, '', $segmentContent);
- $segmentData['segment_content'] = preg_replace('/\n{2,}/', "\n", $segmentData['segment_content']);
- $segmentData['segment_content'] = trim($segmentData['segment_content']);
-
- $segments[] = $segmentData;
- }
-
- $acts[] = [
- 'act_number' => $actNumber,
- 'act_title' => $actTitle,
- 'act_details' => $actDetails,
- 'act_duration' => $actDuration,
- 'segments' => $segments
- ];
- }
-
- $result['acts'] = $acts;
- }
-
- return $result;
- }
- /**
- * 远程图片压缩(尽可能保持原图 fidelity,压缩到不超过 maxBytes 字节)
- * 采用有损/无损组合策略:保留原始格式尽量不失真,若需要则通过尺寸缩放和质量调节来降低体积。
- *
- * @param string $url 远程图片 URL
- * @param int $maxBytes 最大字节数,默认 3MB
- * @param string|null $aspectRatio 目标长宽比,如 "16:9"、"4:3"、"1:1" 等,null 则保持原图比例
- * @return string|null 返回压缩后的图片二进制数据,失败时返回 null
- */
- function compressRemoteImageUrlToSize(string $url, int $maxBytes = 3 * 1024 * 1024, ?string $aspectRatio = null): ?string
- {
- // 1) 下载图片数据(使用 Guzzle 以避免 allow_url_fopen 依赖)
- try {
- $client = new Client(['timeout' => 30]);
- $response = $client->get($url, ['stream' => true]);
- if ($response->getStatusCode() !== 200) {
- return null;
- }
- $data = $response->getBody()->getContents();
- } catch (\Exception $e) {
- return null;
- }
- if (!$data) return null;
- // 2) 识别图片类型
- $imgInfo = @getimagesizefromstring($data);
- $mime = $imgInfo['mime'] ?? '';
- if ($mime == 'image/jpeg') return null; // JPEG 不做有损压缩
- // 3) 载入图像对象
- $srcImg = @imagecreatefromstring($data);
- if (!$srcImg) {
- return null;
- }
- $origW = imagesx($srcImg);
- $origH = imagesy($srcImg);
- // 3.2) 计算目标尺寸(根据长宽比调整)
- $targetW = $origW;
- $targetH = $origH;
-
- if ($aspectRatio !== null) {
- // 解析长宽比,如 "16:9" -> [16, 9]
- $validRatios = array_keys(BaseConst::IMAGE_RATIOS);
- if (in_array($aspectRatio, $validRatios)) {
- list($ratioW, $ratioH) = explode(':', $aspectRatio);
- $ratioW = (float)$ratioW;
- $ratioH = (float)$ratioH;
- $targetRatio = $ratioW / $ratioH;
- $currentRatio = $origW / $origH;
-
- // 根据目标比例裁剪图片
- if ($currentRatio > $targetRatio) {
- // 原图更宽,需要裁剪宽度
- $targetW = (int)round($origH * $targetRatio);
- $targetH = $origH;
- } else {
- // 原图更高,需要裁剪高度
- $targetW = $origW;
- $targetH = (int)round($origW / $targetRatio);
- }
- }
- }
-
- // 如果需要裁剪,创建裁剪后的图像
- if ($targetW !== $origW || $targetH !== $origH) {
- $croppedImg = imagecreatetruecolor($targetW, $targetH);
- imagealphablending($croppedImg, false);
- imagesavealpha($croppedImg, true);
-
- // 处理透明背景
- if (in_array(strtolower($mime), ['image/png','image/webp'])) {
- $transparent = imagecolorallocatealpha($croppedImg, 0, 0, 0, 127);
- imagefill($croppedImg, 0, 0, $transparent);
- }
-
- // 居中裁剪
- $srcX = (int)(($origW - $targetW) / 2);
- $srcY = (int)(($origH - $targetH) / 2);
- imagecopy($croppedImg, $srcImg, 0, 0, $srcX, $srcY, $targetW, $targetH);
-
- // 替换原图
- safeDestroyImage($srcImg);
- $srcImg = $croppedImg;
- $origW = $targetW;
- $origH = $targetH;
- }
- // 3.1) 内部渲染成不同格式的字符串
- $render = function($srcRes, string $mimeType, int $quality) {
- ob_start();
- switch (strtolower($mimeType)) {
- case 'image/jpeg':
- case 'image/jpg':
- case 'image/pjpeg':
- // 输出 JPEG
- imagejpeg($srcRes, null, $quality);
- break;
- case 'image/png':
- // 将 quality 映射到 PNG 的 compression level (0-9)
- $level = (int)round((100 - $quality) / 11.11);
- if ($level < 0) $level = 0;
- if ($level > 9) $level = 9;
- imagepng($srcRes, null, $level);
- break;
- case 'image/webp':
- if (function_exists('imagewebp')) {
- imagewebp($srcRes, null, $quality);
- } else {
- imagejpeg($srcRes, null, $quality);
- }
- break;
- default:
- imagejpeg($srcRes, null, $quality);
- break;
- }
- $out = ob_get_contents();
- ob_end_clean();
- return $out;
- };
- // 4) 尝试策略:尽量保留原图尺寸,逐步降维/降质量,直到 <= maxBytes
- $tryList = [];
- // 原始尺寸,尽量保留
- $tryList[] = ['scale'=>1.0, 'mime'=>$mime, 'quality'=>100];
- // 逐步缩小尺寸
- for ($s = 0.9; $s >= 0.2; $s -= 0.1) {
- $tryList[] = ['scale'=>$s, 'mime'=>$mime, 'quality'=>90];
- }
- // 一系列质量等级(用于 JPEG/WebP)
- $qualityLevels = [95, 90, 85, 75, 60, 50, 40, 30];
- foreach ($qualityLevels as $q) {
- $tryList[] = ['scale'=>1.0, 'mime'=>$mime, 'quality'=>$q];
- }
- $bestData = null;
- foreach ($tryList as $cand) {
- $scale = isset($cand['scale']) ? (float)$cand['scale'] : 1.0;
- $mimeT = $cand['mime'] ?? $mime;
- $quality = isset($cand['quality']) ? (int)$cand['quality'] : 90;
- $w = (int)round($origW * $scale);
- $h = (int)round($origH * $scale);
- $src = $srcImg;
- $tempImg = null;
- if ($scale < 1.0) {
- $tempImg = imagecreatetruecolor($w, $h);
- // 处理透明通道
- imagealphablending($tempImg, false);
- imagesavealpha($tempImg, true);
- if (in_array(strtolower($mime), ['image/png','image/webp'])) {
- $transparent = imagecolorallocatealpha($tempImg, 0, 0, 0, 127);
- imagefill($tempImg, 0, 0, $transparent);
- }
- // 确保 $srcImg 有效
- if (!$srcImg || (!is_resource($srcImg) && !($srcImg instanceof \GdImage))) {
- safeDestroyImage($tempImg);
- continue;
- }
- imagecopyresampled($tempImg, $srcImg, 0, 0, 0, 0, $w, $h, $origW, $origH);
- $src = $tempImg;
- }
- $imageBytes = $render($src, $mimeT, $quality);
- if ($tempImg !== null) {
- safeDestroyImage($tempImg);
- }
- if ($imageBytes !== false && strlen($imageBytes) <= $maxBytes) {
- $bestData = $imageBytes;
- break;
- }
- }
- // 5) 回退策略:若仍未达到要求,尝试更大幅度降解到一个合理的小尺寸 JPEG
- if ($bestData === null) {
- $tmpW = max(1, (int)round($origW * 0.5));
- $tmpH = max(1, (int)round($origH * 0.5));
- $tmpImg = imagecreatetruecolor($tmpW, $tmpH);
- imagealphablending($tmpImg, false);
- imagesavealpha($tmpImg, true);
- if (in_array(strtolower($mime), ['image/png','image/webp'])) {
- $transparent = imagecolorallocatealpha($tmpImg, 0, 0, 0, 127);
- imagefill($tmpImg, 0, 0, $transparent);
- }
- imagecopyresampled($tmpImg, $srcImg, 0, 0, 0, 0, $tmpW, $tmpH, $origW, $origH);
- ob_start();
- if (in_array(strtolower($mime), ['image/jpeg','image/jpg','image/pjpeg'])) {
- imagejpeg($tmpImg, null, 75);
- } elseif (strtolower($mime) === 'image/png') {
- imagepng($tmpImg, null, 6);
- } elseif (function_exists('imagewebp')) {
- imagewebp($tmpImg, null, 75);
- } else {
- imagejpeg($tmpImg, null, 75);
- }
- $tmpBytes = ob_get_contents();
- ob_end_clean();
- safeDestroyImage($tmpImg);
- if ($tmpBytes !== '' && strlen($tmpBytes) <= $maxBytes) {
- $bestData = $tmpBytes;
- }
- }
- // 6) 清理
- safeDestroyImage($srcImg);
- return $bestData;
- }
- /**
- * 安全销毁 GD 图像资源(兼容 PHP7.4+ 的资源管理)
- * 通过引用传递并在销毁后置空变量,避免未定义变量的问题
- *
- * @param resource|\GdImage|null &$img GD 图像资源或对象(PHP7.4 为 resource,PHP8.0+ 为 GdImage)
- */
- function safeDestroyImage(&$img)
- {
- if (is_resource($img) || (is_object($img) && $img instanceof \GdImage)) {
- @imagedestroy($img);
- }
- $img = null;
- }
- // /**
- // * 使用 Imagick 将远程图片压缩至不超过 maxBytes(默认3MB)内
- // * 目标:在尽量保留原始格式和质量的前提下进行压缩,避免内存暴涨
- // * 依赖:Imagick 扩展与 ImageMagick 库,下载使用 Guzzle 获取图片 blob
- // *
- // * @param string $url
- // * @param int $maxBytes 最大字节数,默认 3*1024*1024
- // * @return string|null 经过压缩后的图片 blob,失败返回 null
- // */
- // function compressRemoteImageUrlToSizeImagick(string $url, int $maxBytes = 3 * 1024 * 1024): ?string
- // {
- // // 兼容性检查
- // if (!extension_loaded('imagick') || !class_exists('Imagick')) {
- // return null;
- // }
- // try {
- // $client = new Client(['timeout' => 30]);
- // // 使用流式下载,将数据写入临时文件,避免一次性加载到内存
- // $response = $client->get($url, ['stream' => true]);
- // if ($response->getStatusCode() !== 200) {
- // return null;
- // }
- // $body = $response->getBody();
- // $tmp = tmpfile();
- // if ($tmp === false) {
- // return null;
- // }
- // stream_copy_to_stream($body, $tmp);
- // rewind($tmp);
- // $imagick = new Imagick();
- // $imagick->readImageFile($tmp);
- // $origW = $imagick->getImageWidth();
- // $origH = $imagick->getImageHeight();
- // $format = strtolower($imagick->getImageFormat());
- // // 尝试序列:尺寸缩放 + 质量调节
- // $scales = [1.0, 0.9, 0.8, 0.6, 0.4, 0.25];
- // $qualities = [95, 90, 85, 75, 60, 40, 30, 20];
- // $bestBlob = null;
- // foreach ($scales as $scale) {
- // foreach ($qualities as $q) {
- // $clone = clone $imagick;
- // if ($scale < 1.0) {
- // $w = (int)round($origW * $scale);
- // $h = (int)round($origH * $scale);
- // if ($w < 1 || $h < 1) {
- // $clone->destroy();
- // continue;
- // }
- // $clone->resizeImage($w, $h, Imagick::FILTER_LANCZOS, 1);
- // }
- // $clone->setImageFormat($format);
- // $clone->setImageCompressionQuality($q);
- // $blob = $clone->getImageBlob();
- // $clone->destroy();
- // if ($blob !== false && strlen($blob) <= $maxBytes) {
- // $bestBlob = $blob;
- // break 2;
- // }
- // }
- // }
- // if ($bestBlob !== null) {
- // $imagick->destroy();
- // fclose($tmp);
- // return $bestBlob;
- // }
- // // 回退:尝试强制输出为当前格式的一个中等质量版本
- // $fallback = clone $imagick;
- // $fallback->setImageFormat($format);
- // $fallback->setImageCompressionQuality(75);
- // $blob = $fallback->getImageBlob();
- // $fallback->destroy();
- // $imagick->destroy();
- // fclose($tmp);
- // if ($blob !== false && strlen($blob) <= $maxBytes) {
- // return $blob;
- // }
- // } catch (\Exception $e) {
- // return null;
- // }
- // return null;
- // }
- /**
- * 将主体列表文本拆分为主体数组
- *
- * @param string $rolesText 主体列表文本内容
- * @return array 主体名称数组
- */
- function parseRolesFromText(string $rolesText): array
- {
- if (empty($rolesText)) {
- return [];
- }
-
- $roles = [];
-
- // 按行分割文本
- $lines = explode("\n", $rolesText);
-
- foreach ($lines as $line) {
- $line = trim($line);
- if (empty($line)) {
- continue;
- }
- if (preg_match('/^([^::]+)[::](.+)$/u', $line, $charMatch)) {
- $role = trim($charMatch[1]);
- $description = trim($charMatch[2]);
- $timbreName = null;
- // 检查描述末尾是否有{主体图片提示词}{{音色名}}格式
- $picPrompt = null;
- if (preg_match('/^(.*?)\{([^}]+)\}\{\{([^}]+)\}\}\s*$/u', $description, $fullMatch)) {
- // 匹配格式:主体描述{主体图片提示词}{{音色名}}
- $description = trim($fullMatch[1]);
- $picPrompt = trim($fullMatch[2]);
- $timbreName = trim($fullMatch[3]);
- } elseif (preg_match('/^(.*?)\{\{([^}]+)\}\}\s*$/u', $description, $timbreMatch)) {
- // 兼容旧格式:主体描述{{音色名}}
- $description = trim($timbreMatch[1]);
- $timbreName = trim($timbreMatch[2]);
- }
- $roleData = [
- 'role' => $role,
- 'description' => $description,
- ];
- // 如果有主体图片提示词,添加到数组中
- if ($picPrompt) {
- $roleData['pic_prompt'] = $picPrompt;
- }
- if ($timbreName) {
- $timbre = DB::table('mp_timbres')
- ->where('is_enabled', 1)
- ->where('timbre_name', 'like', "%{$timbreName}%")
- ->orderBy('id')
- ->select('timbre_type', 'audio_url')
- ->first();
- if ($timbre) {
- $roleData['voice_name'] = $timbreName;
- $roleData['voice_type'] = getProp($timbre, 'timbre_type');
- $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
- }
- }else {
- // 从描述或人物提示词中获取"男"或"女",赋予默认音色,获取不到则使用旁白音色
- if ($picPrompt) {
- if (strstr($picPrompt, '男')) {
- $roleData['voice_name'] = '阳光青年';
- }elseif (strstr($picPrompt, '女')) {
- $roleData['voice_name'] = '爽快思思';
- }else {
- if ($description) {
- if (strstr($description, '男')) {
- $roleData['voice_name'] = '阳光青年';
- }elseif (strstr($description, '女')) {
- $roleData['voice_name'] = '爽快思思';
- }else {
- $roleData['voice_name'] = '旁白';
- }
- }
- }
- }
- if (!empty($roleData['voice_name'])) {
- if ($roleData['voice_name'] == '旁白') {
- $roleData['voice_type'] = 'zh_male_linjiananhai_moon_bigtts';
- $roleData['voice_audio_url'] = 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav';
- }else {
- $timbre = DB::table('mp_timbres')
- ->where('is_enabled', 1)
- ->where('timbre_name', 'like', "%".$roleData['voice_name']."%")
- ->orderBy('id')
- ->select('timbre_type', 'audio_url')
- ->first();
- if ($timbre) {
- $roleData['voice_type'] = getProp($timbre, 'timbre_type');
- $roleData['voice_audio_url'] = getProp($timbre, 'audio_url');
- }
- }
- }
- }
- $roles[] = $roleData;
- }
- }
- $hasNarrator = false;
- foreach ($roles as $role) {
- if (getProp($role, 'role') === '旁白') {
- $hasNarrator = true;
- break;
- }
- }
- if (!$hasNarrator) {
- $roles[] = [
- 'role' => '旁白',
- 'description' => '负责叙述剧情、补充说明和情感渲染的非视觉角色。',
- 'pic_prompt' => '',
- 'voice_name' => '旁白',
- 'voice_type' => 'zh_male_linjiananhai_moon_bigtts',
- 'voice_audio_url' => 'https://zw-audiobook.tos-cn-beijing.volces.com/demonstrate/zh_male_linjiananhai_moon_bigtts.wav'
- ];
- }
-
- return $roles;
- }
- /**
- * 将场景列表文本拆分为主体数组
- *
- * @param string $rolesText 场景列表列表文本内容
- * @return array 场景名称数组
- */
- function parseScenesFromText(string $scenesText): array
- {
- if (empty($scenesText)) {
- return [];
- }
-
- $scenes = [];
-
- // 按行分割文本
- $lines = explode("\n", $scenesText);
-
- foreach ($lines as $line) {
- $line = trim($line);
- if (empty($line)) {
- continue;
- }
-
- $line = str_replace(':', ':', $line);
- if (strstr($line, ':')) {
- $line_arr = explode(':', $line, 2);
- if (count($line_arr) == 2) {
- $scene = trim($line_arr[0]);
- $description = trim($line_arr[1]);
- $picPrompt = null;
-
- // 检查描述末尾是否有{场景图片提示词}格式
- if (preg_match('/^(.*?)\{([^}]+)\}\s*$/u', $description, $promptMatch)) {
- // 匹配格式:场景描述{场景图片提示词}
- $description = trim($promptMatch[1]);
- $picPrompt = trim($promptMatch[2]);
- }
-
- $sceneData = [
- 'scene' => $scene,
- 'description' => $description,
- ];
-
- // 如果有场景图片提示词,添加到数组中
- if ($picPrompt) {
- $sceneData['pic_prompt'] = $picPrompt;
- }
-
- $scenes[] = $sceneData;
- }
- }
- }
-
- return $scenes;
- }
- /**
- * 记录日志到数据库
- *
- * @param string $channel 日志频道/目录名
- * @param string $level 日志级别 (info, error, warning, debug)
- * @param string $message 日志信息
- * @param array $context 日志详细数据
- * @return void
- */
- function logDB($channel, $level, $message, $context = []) {
- try {
- // 获取调用堆栈信息
- $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
- $caller = $trace[1] ?? $trace[0];
- // 在 create 之前添加:
- $jsonEncoded = json_encode($context, JSON_INVALID_UTF8_SUBSTITUTE);
- $cleanContext = json_decode($jsonEncoded, true);
-
- \App\Models\SystemLog::create([
- 'channel' => $channel,
- 'level' => $level,
- 'message' => $message,
- 'context' => $cleanContext,
- 'file' => $caller['file'] ?? '',
- 'line' => $caller['line'] ?? 0,
- 'log_time' => date('Y-m-d H:i:s'),
- ]);
- } catch (\Exception $e) {
- // 记录日志失败时不影响主流程
- \Log::error('记录日志到数据库失败: ' . $e->getMessage());
- }
- }
- function filterScriptContent($content) {
- if (!$content) return '';
- if (mb_substr($content, 0, 6) == '确认分镜大纲') return '确认分镜大纲';
- if (mb_strlen($content) > 500) return '我已按照您的要求完成策划并将内容更新到您右侧的策划文档。';
- return $content;
- }
- /**
- * 根据错误信息返回映射错误说明
- *
- * @param string $errorMessage 错误信息
- * @return string 映射后的错误说明
- */
- function mapErrorMessage($errorMessage)
- {
- if (empty($errorMessage)) {
- return '未知异常,请重试';
- }
- // 按优先级匹配错误信息
- if (stripos($errorMessage, 'OutputImageSensitiveContentDetected') !== false) {
- return '输出结果含有敏感词,请重试';
- }
- if (stripos($errorMessage, '系统繁忙,请稍后再试') !== false) {
- return '系统繁忙,请稍后再试';
- }
- if (stripos($errorMessage, 'InternalServiceError') !== false) {
- return '外部服务器网络错误,请稍后重试';
- }
- if (stripos($errorMessage, 'InputTextSensitiveContentDetected') !== false) {
- return '输入文字含有敏感词,请调整后重试';
- }
- if (stripos($errorMessage, 'ServerOverloaded') !== false) {
- return '当前系统过载,请稍后重试';
- }
- if (stripos($errorMessage, 'The request failed because the output video may be related to copyright restrictions') !== false) {
- return '涉及到版权问题无法生成,请调整后重试';
- }
- if (stripos($errorMessage, 'sensitive') !== false) {
- return '含有敏感词,请调整后重试';
- }
- // 默认返回
- return '未知异常,请重试';
- }
|