feat: output top 10 segment candidates with timestamps and duration

This commit is contained in:
Kilo Code Cloud
2026-01-14 20:05:28 +00:00
parent 3c263a78c6
commit 9ea4d4ab33
3 changed files with 50 additions and 34 deletions

View File

@@ -2,12 +2,14 @@ export interface CliArgs {
url?: string; url?: string;
output: string; output: string;
format: string; format: string;
topN: number;
} }
export function parseArgs(): CliArgs { export function parseArgs(): CliArgs {
const args: CliArgs = { const args: CliArgs = {
output: "./downloads", output: "./downloads",
format: "best", format: "best",
topN: 10,
}; };
const rawArgs = Bun.argv; const rawArgs = Bun.argv;
@@ -22,8 +24,11 @@ export function parseArgs(): CliArgs {
} else if (arg === "-f" || arg === "--format") { } else if (arg === "-f" || arg === "--format") {
args.format = nextArg || "best"; args.format = nextArg || "best";
i++; i++;
} else if (arg === "-n" || arg === "--top") {
args.topN = parseInt(nextArg || "10", 10);
i++;
} else if (arg === "-h" || arg === "--help") { } else if (arg === "-h" || arg === "--help") {
console.log(`YouTube Most Watched Segment Downloader console.log(`YouTube Most Watched Segments Downloader
Usage: yt-segments <url> [options] Usage: yt-segments <url> [options]
@@ -33,11 +38,12 @@ Arguments:
Options: Options:
-o, --output <dir> Output directory (default: ./downloads) -o, --output <dir> Output directory (default: ./downloads)
-f, --format <fmt> Video format (default: best) -f, --format <fmt> Video format (default: best)
-n, --top <num> Number of top segments to show (default: 10)
-h, --help Show this help message -h, --help Show this help message
Examples: Examples:
yt-segments "https://www.youtube.com/watch?v=abc123" yt-segments "https://www.youtube.com/watch?v=abc123"
yt-segments "https://youtu.be/abc123" -o ./videos -f mp4 yt-segments "https://youtu.be/abc123" -o ./videos -n 5
`); `);
process.exit(0); process.exit(0);
} else if (!arg.startsWith("-") && !arg.includes("bun")) { } else if (!arg.startsWith("-") && !arg.includes("bun")) {

View File

@@ -6,6 +6,7 @@ export interface DownloadOptions {
url: string; url: string;
outputDir: string; outputDir: string;
format: string; format: string;
topN: number;
} }
interface RawHeatmapSegment { interface RawHeatmapSegment {
@@ -142,9 +143,10 @@ function getIntensity(segment: RawHeatmapSegment): number {
return segment.intensity ?? segment.heat ?? segment.value ?? 0; return segment.intensity ?? segment.heat ?? segment.value ?? 0;
} }
function findHighestIntegralJump( function getTopSegmentsByIntegral(
segments: RawHeatmapSegment[] segments: RawHeatmapSegment[],
): ProcessedSegment | null { topN: number
): ProcessedSegment[] {
// Convert to processed format and filter valid segments // Convert to processed format and filter valid segments
const validSegments = segments const validSegments = segments
.map(seg => ({ .map(seg => ({
@@ -161,10 +163,10 @@ function findHighestIntegralJump(
); );
if (validSegments.length === 0) { if (validSegments.length === 0) {
return null; return [];
} }
// Calculate integral jump for each segment (intensity × duration) // Calculate integral for each segment and sort by highest
const withIntegral = validSegments.map(seg => { const withIntegral = validSegments.map(seg => {
const segmentDuration = seg.end - seg.start; const segmentDuration = seg.end - seg.start;
const integralJump = seg.intensity * segmentDuration; const integralJump = seg.intensity * segmentDuration;
@@ -174,15 +176,13 @@ function findHighestIntegralJump(
}; };
}); });
// Find the segment with the highest integral jump (biggest bump in the integral) // Sort by integral jump (highest first) and return top N
// This is the segment that contributed most to the total integral withIntegral.sort((a, b) => b.integralJump - a.integralJump);
return withIntegral.reduce((max, current) => { return withIntegral.slice(0, topN);
return current.integralJump > max.integralJump ? current : max;
});
} }
export async function downloadMostWatchedSegment(options: DownloadOptions): Promise<void> { export async function downloadMostWatchedSegment(options: DownloadOptions): Promise<void> {
const { url, outputDir, format } = options; const { url, outputDir, format, topN } = options;
// Create output directory if it doesn't exist // Create output directory if it doesn't exist
if (!existsSync(outputDir)) { if (!existsSync(outputDir)) {
@@ -208,38 +208,47 @@ export async function downloadMostWatchedSegment(options: DownloadOptions): Prom
} }
console.log(`\nHeatmap data found: ${info.heatmap.length} segments`); console.log(`\nHeatmap data found: ${info.heatmap.length} segments`);
console.log(`\nTop ${topN} segments by integral jump:\n`);
// Find segment with highest integral jump (biggest bump) // Get top segments
const topSegment = findHighestIntegralJump(info.heatmap); const topSegments = getTopSegmentsByIntegral(info.heatmap, topN);
if (!topSegment) { if (topSegments.length === 0) {
console.log("No valid segments found. Downloading full video..."); console.log("No valid segments found. Downloading full video...");
const outputPath = join(outputDir, `${safeTitle}.%(ext)s`); const outputPath = join(outputDir, `${safeTitle}.%(ext)s`);
await downloadSegment(url, outputPath, 0, info.duration, format); await downloadSegment(url, outputPath, 0, info.duration, format);
return; return;
} }
console.log(`\nSegment with highest integral jump:`); // Output the top segments
console.log(` Time: ${formatTime(topSegment.start)} - ${formatTime(topSegment.end)}`); for (let i = 0; i < topSegments.length; i++) {
console.log(` Duration: ${formatTime(topSegment.end - topSegment.start)}`); const seg = topSegments[i];
console.log(` Intensity: ${(topSegment.intensity * 100).toFixed(1)}%`); const duration = seg.end - seg.start;
console.log(` Integral Jump: ${topSegment.integralJump.toFixed(4)}`); console.log(`${i + 1}. ${formatTime(seg.start)} - ${formatTime(seg.end)} | Duration: ${formatTime(duration)} | Integral: ${seg.integralJump.toFixed(4)}`);
}
// Download the segment console.log("");
// Download the top segment
const topSegment = topSegments[0];
const outputPath = join(outputDir, `${safeTitle}_most_watched.%(ext)s`); const outputPath = join(outputDir, `${safeTitle}_most_watched.%(ext)s`);
console.log(`\nDownloading segment...`); console.log(`Downloading segment: ${formatTime(topSegment.start)} - ${formatTime(topSegment.end)}`);
await downloadSegment(url, outputPath, topSegment.start, topSegment.end, format); await downloadSegment(url, outputPath, topSegment.start, topSegment.end, format);
// Save segment info // Save segment info
const segmentInfoPath = join(outputDir, `${safeTitle}_segment_info.txt`); const segmentInfoPath = join(outputDir, `${safeTitle}_top_segments.txt`);
const segmentInfo = `# ${info.title}\n\n` + let segmentInfo = `# ${info.title}\n\n`;
`Segment with highest integral jump (biggest bump in heatmap):\n` + segmentInfo += `Top ${topN} segments by integral jump:\n\n`;
` Start: ${formatTime(topSegment.start)} (${topSegment.start.toFixed(1)}s)\n` +
` End: ${formatTime(topSegment.end)} (${topSegment.end.toFixed(1)}s)\n` + for (let i = 0; i < topSegments.length; i++) {
` Duration: ${formatTime(topSegment.end - topSegment.start)}\n` + const seg = topSegments[i];
` Intensity: ${(topSegment.intensity * 100).toFixed(1)}%\n` + const duration = seg.end - seg.start;
` Integral Jump: ${topSegment.integralJump.toFixed(4)}\n`; segmentInfo += `${i + 1}. ${formatTime(seg.start)} - ${formatTime(seg.end)}\n`;
segmentInfo += ` Duration: ${formatTime(duration)}\n`;
segmentInfo += ` Integral: ${seg.integralJump.toFixed(4)}\n`;
segmentInfo += ` Intensity: ${(seg.intensity * 100).toFixed(1)}%\n\n`;
}
writeFileSync(segmentInfoPath, segmentInfo); writeFileSync(segmentInfoPath, segmentInfo);
console.log(`\nSegment info saved to: ${segmentInfoPath}`); console.log(`\nSegment info saved to: ${segmentInfoPath}`);

View File

@@ -12,20 +12,21 @@ async function main() {
console.log("Options:"); console.log("Options:");
console.log(" -o, --output <dir> Output directory (default: ./downloads)"); console.log(" -o, --output <dir> Output directory (default: ./downloads)");
console.log(" -f, --format <fmt> Video format (default: best)"); console.log(" -f, --format <fmt> Video format (default: best)");
console.log(" -n, --top <num> Number of top segments (default: 10)");
console.log(" -h, --help Show help"); console.log(" -h, --help Show help");
process.exit(1); process.exit(1);
} }
console.log(`Downloading most watched segment from: ${args.url}`); console.log(`Analyzing video: ${args.url}`);
console.log(`Output directory: ${args.output}`); console.log(`Output directory: ${args.output}`);
console.log(`Format: ${args.format}`); console.log(`Top ${args.topN} segments by integral jump\n`);
console.log("");
try { try {
await downloadMostWatchedSegment({ await downloadMostWatchedSegment({
url: args.url, url: args.url,
outputDir: args.output, outputDir: args.output,
format: args.format, format: args.format,
topN: args.topN,
}); });
} catch (error) { } catch (error) {
console.error("Error:", error instanceof Error ? error.message : error); console.error("Error:", error instanceof Error ? error.message : error);