@barbapapazes/video-toolkit 0.8.1 → 0.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +1 -1
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{basename as e,extname as t,isAbsolute as n,join as r,resolve as i}from"node:path";import a from"node:process";import{intro as o,isCancel as s,log as c,outro as l,select as u,spinner as d,text as f}from"@clack/prompts";import{cac as ee}from"cac";import{homedir as p}from"node:os";import{loadConfig as m}from"c12";import{copyFileSync as h,createReadStream as g,existsSync as _,mkdirSync as v,readFileSync as y,readdirSync as b,statSync as x,unlinkSync as S,writeFileSync as C}from"node:fs";import{format as w,parse as T}from"date-fns";import{Buffer as E}from"node:buffer";import D from"sharp";import{execSync as O}from"node:child_process";import k from"openai";var A=`0.8.
|
|
2
|
+
import{basename as e,extname as t,isAbsolute as n,join as r,resolve as i}from"node:path";import a from"node:process";import{intro as o,isCancel as s,log as c,outro as l,select as u,spinner as d,text as f}from"@clack/prompts";import{cac as ee}from"cac";import{homedir as p}from"node:os";import{loadConfig as m}from"c12";import{copyFileSync as h,createReadStream as g,existsSync as _,mkdirSync as v,readFileSync as y,readdirSync as b,statSync as x,unlinkSync as S,writeFileSync as C}from"node:fs";import{format as w,parse as T}from"date-fns";import{Buffer as E}from"node:buffer";import D from"sharp";import{execSync as O}from"node:child_process";import k from"openai";var A=`0.8.2`;const j={openaiApiKey:``,language:`fr`,model:`whisper-1`,templatesDir:r(p(),`.config`,`video-toolkit`,`templates`)};async function M(){let{config:e}=await m({name:`video-toolkit`,defaults:j,globalRc:!0});return{openaiApiKey:e.openaiApiKey||``,language:e.language||`fr`,model:e.model||`whisper-1`,templatesDir:e.templatesDir}}function N(n){let a=i(n),o=e(a,t(a)),s=i(a,`..`),c=r(s,`${o}_audio.mp3`),l=r(s,`${o}.srt`),u=r(s,`thumbnails`);_(u)||v(u,{recursive:!0});let d=[`first`,`25`,`50`,`75`,`last`];return{videoPath:a,audioPath:c,srtPath:l,thumbnailTempPaths:d.map(e=>r(u,`${o}_thumbnail_${e}_temp.png`)),thumbnailPaths:d.map(e=>r(u,`${o}_thumbnail_${e}.png`))}}function P(e){return n(e)?e:i(a.cwd(),e)}function F(e){let n=P(e);if(!_(n))return[];try{return b(n,{withFileTypes:!0}).filter(e=>e.isFile()&&t(e.name).toLowerCase()===`.svg`).map(e=>e.name.replace(/\.svg$/i,``))}catch{return[]}}function I(e,t){return r(P(t),`${e}.svg`)}function L(e,t,r){let i=n(e)?e:I(e,r);if(!_(i))throw Error(`SVG template not found at ${i}. Please ensure the template exists in ${P(r)}.`);let a;try{a=y(i,`utf-8`)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to load SVG template from ${i}: ${t}`)}let o=t.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`);return a.replace(/\{\{text\}\}/g,o)}async function R(e,t,n,r,i){try{let a=L(r,n,i),o=await D(e).metadata();if(!o.width||!o.height)throw Error(`Could not determine image dimensions`);let s=await D(E.from(a)).resize(o.width,o.height,{fit:`fill`}).png().toBuffer();await D(e).composite([{input:s,blend:`over`}]).toFile(t)}catch(e){throw console.error(`Error adding text to image:`,e),e}}function z(e=a.cwd()){let n=[];try{let i=b(e).filter(t=>x(r(e,t)).isDirectory()&&/^\d{4}$/.test(t));for(let a of i){let i=r(e,a),o=b(i).filter(e=>x(r(i,e)).isDirectory()&&/^\d{2}$/.test(e));for(let e of o){let o=r(i,e),s=b(o).filter(e=>x(r(o,e)).isDirectory()&&/^\d{2}$/.test(e));for(let i of s){let s=r(o,i),c=b(s,{withFileTypes:!0}).filter(e=>e.isFile()&&t(e.name).toLowerCase()===`.mp4`).map(e=>e.name);if(c.length>0){let t=`${a}-${e}-${i}`;n.push({path:s,date:new Date(t),displayPath:`${a}/${e}/${i}`,videoFile:c[0]})}}}}}catch(e){return c.error(`Error reading directories: ${e}`),[]}return n.sort((e,t)=>t.date.getTime()-e.date.getTime()).slice(0,8)}async function B(e=a.cwd()){let n=z(e);n.length===0&&(c.error(`No dated folders with video files found.`),c.info(`Expected structure: YYYY/MM/DD/*.mp4`),a.exit(1));let i=n.map(e=>({label:`${e.displayPath} (${e.videoFile})`,value:e.path,hint:`Process video from ${e.displayPath}`}));i.push({label:`Custom date`,value:`custom`,hint:`Enter a specific date`});let o=await u({message:`Select a content folder with video:`,options:i});if(s(o)&&(c.error(`Operation cancelled.`),a.exit(0)),o===`custom`){let n=await f({message:`Enter date (YYYY-MM-DD):`,placeholder:w(new Date,`yyyy-MM-dd`),validate:e=>{if(!e)return`Date is required`;if(!/^\d{4}-\d{2}-\d{2}$/.test(e))return`Invalid date format. Please use YYYY-MM-DD`;try{let t=T(e,`yyyy-MM-dd`,new Date);if(Number.isNaN(t.getTime()))return`Invalid date`}catch{return`Invalid date`}}});s(n)&&(c.error(`Operation cancelled.`),a.exit(0));let i=T(n,`yyyy-MM-dd`,new Date),o=r(e,w(i,`yyyy`),w(i,`MM`),w(i,`dd`));_(o)||(c.error(`Folder does not exist: ${o}`),a.exit(1));let l=b(o,{withFileTypes:!0}).filter(e=>e.isFile()&&t(e.name).toLowerCase()===`.mp4`).map(e=>e.name);return l.length===0&&(c.error(`No .mp4 files found in: ${o}`),a.exit(1)),{folderPath:o,videoPath:r(o,l[0])}}let l=n.find(e=>e.path===o);l||(c.error(`Selected folder not found.`),a.exit(1));let d=r(l.path,l.videoFile);return{folderPath:l.path,videoPath:d}}async function V(){let e=await f({message:`Enter text for the thumbnail (or press Enter to skip):`,placeholder:`Optional thumbnail text`});if(typeof e!=`symbol`)return e.trim()||void 0}async function H(e){let t=F(e);if(t.length===0){c.error(`No templates found in ${e}`),c.info(`Please add SVG templates to ${e} before proceeding.`);return}let n=await u({message:`Choose a template:`,options:t.map(e=>({label:e,value:e}))});if(typeof n!=`symbol`)return n}function U(e,t){let n=`ffmpeg -i ${e} -q:a 0 -map a ${t}`;try{O(n,{stdio:`inherit`})}catch(e){console.error(`Error extracting audio:`,e)}}function W(e){try{let t=O(`ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "${e}"`,{encoding:`utf-8`});return Number.parseFloat(t.trim())}catch(e){throw console.error(`Error getting video duration:`,e),e}}function G(e,t,n=`first`){let r=``;r=n===`first`?`ffmpeg -i "${e}" -vf "select=eq(n\\,0)" -vframes 1 "${t}" -y`:n===`last`?`ffmpeg -sseof -0.1 -i "${e}" -vframes 1 "${t}" -y`:`ffmpeg -ss ${W(e)*(Number.parseInt(n)/100)} -i "${e}" -vframes 1 "${t}" -y`;try{O(r,{stdio:`inherit`})}catch(e){throw console.error(`Error extracting thumbnail:`,e),e}}async function K(e,t){return await new k({apiKey:t.openaiApiKey}).audio.transcriptions.create({file:g(e),model:t.model,language:t.language,response_format:`srt`})}async function q(e,t){let n=d();n.start(`Extracting audio...`);try{U(e,t),n.stop(`Audio extracted successfully`)}catch(e){n.stop(`Audio extraction failed`),c.error(`Error during audio extraction: ${e}`),a.exit(1)}}async function J(e,t,n){let r=d();r.start(`Generating transcription with OpenAI...`);try{C(t,await K(e,n)),r.stop(`Transcription generated successfully`)}catch(t){r.stop(`Transcription generation failed`),c.error(`Error during transcription generation: ${t}`);try{S(e)}catch{}a.exit(1)}}async function Y(e,t,n){let r=d(),i=n===`first`?`start`:n===`last`?`end`:`${n}%`;r.start(`Extracting thumbnail at ${i}...`);try{G(e,t,n),r.stop(`Thumbnail extracted successfully`)}catch(e){r.stop(`Thumbnail extraction failed`),c.error(`Error during thumbnail extraction: ${e}`),a.exit(1)}}async function X(e,t,n,r,i){let o=d();o.start(`Adding text to thumbnail...`);try{await R(e,t,n,r,i),o.stop(`Text added to thumbnail successfully`)}catch(e){o.stop(`Failed to add text to thumbnail`),c.error(`Error adding text to thumbnail: ${e}`),a.exit(1)}}function Z(e,t=`temporary file`){try{S(e)}catch{c.warn(`Could not delete ${t}: ${e}`)}}async function Q(e){o(`Video Toolkit - Add Template`);let t=await M(),n=i(e);_(n)||(c.error(`Source file not found: ${n}`),a.exit(1)),n.toLowerCase().endsWith(`.svg`)||(c.error(`Source file must be an SVG file`),a.exit(1));let r=await f({message:`Enter a name for this template:`,placeholder:`e.g., series-x, youtube-intro`,validate:e=>{if(!e||e.trim()===``)return`Template name is required`;if(!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(e))return`Template name should start and end with lowercase letters or numbers, and can contain hyphens in between`}});typeof r==`symbol`&&(c.error(`Template name is required. Exiting.`),a.exit(1));let s=P(t.templatesDir);_(s)||(v(s,{recursive:!0}),c.success(`Created templates directory: ${s}`));let u=i(s,`${r}.svg`);_(u)&&c.warn(`Template '${r}' already exists. Overwriting...`);try{h(n,u),l(`✓ Template '${r}' added successfully at ${u}`)}catch(e){let t=e instanceof Error?e.message:String(e);c.error(`Failed to copy template: ${t}`),a.exit(1)}}const $=ee(`video-toolkit`);async function te(t){let n=await M();n.openaiApiKey||(c.error(`OpenAI API key is required. Please set it in:`),c.error(` - Config file: ~/.video-toolkitrc`),a.exit(1));let{videoPath:r,audioPath:i,srtPath:s,thumbnailTempPaths:u,thumbnailPaths:d}=N(t);o(`Video Toolkit - Processing: ${e(r)}`),await q(r,i),await J(i,s,n),Z(i,`audio file`);let f=await V();if(f){let e=await H(n.templatesDir);if(!e){c.warn(`No template selected. Skipping thumbnail generation.`),l(`✓ Transcription saved to: ${s}`);return}let t=[`first`,`25`,`50`,`75`,`last`];for(let i=0;i<t.length;i++)await Y(r,u[i],t[i]),await X(u[i],d[i],f,e,n.templatesDir),Z(u[i],`temporary thumbnail`);l(`✓ Transcription saved to: ${s}\n✓ Thumbnails saved:\n - ${d.join(`
|
|
3
3
|
- `)}`)}else l(`✓ Transcription saved to: ${s}`)}$.command(`[path]`,`Process a video from dated content folders`).option(`--path <path>`,`Base path for content directory (defaults to current directory)`).action(async(e,t)=>{let n=e||t?.path||a.cwd();o(`Video Toolkit - Process video from content folder`);let{videoPath:r}=await B(n);await te(r)}),$.command(`add-template <file>`,`Add an SVG template to the templates directory`).action(async e=>{await Q(e)}),$.help(),$.version(A),$.parse();export{};
|
package/package.json
CHANGED