Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
FROM node:20-slim

RUN apt-get update && apt-get install -y --no-install-recommends \
python3 ffmpeg curl \
&& curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -o /usr/local/bin/yt-dlp \
&& chmod a+rx /usr/local/bin/yt-dlp \
&& apt-get clean && rm -rf /var/lib/apt/lists/*

WORKDIR /app

COPY package.json package-lock.json* ./
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ LLM_API_KEY=...
LLM_MODEL=MiniMaxAI/MiniMax-M2.5
TG_BOT_TOKEN=...
TG_CHANNEL_ID=-100...

# 影片轉錄(選填,啟用後自動轉錄影片貼文)
TRANSCRIBER=groq
GROQ_API_KEY=gsk_...
```

## CLI 工具模式
Expand Down Expand Up @@ -123,6 +127,7 @@ npx @cablate/banini-tracker push -m "分析結果..."
|------|---------|------|--------|
| Facebook 抓取(Apify) | ~$0.02 | 盤中 ~198 次 + 盤後 30 次 | ~$4.56 |
| LLM 分析(常駐模式) | 依模型而定 | 同上 | 依模型定價 |
| 影片轉錄(Groq Whisper) | ~$0.006/分鐘 | 視影片數量 | 極低 |
| Telegram 推送 | 免費 | — | $0 |

> 盤中:週一~五 09:00-13:30 每 30 分鐘(~9 次/日 × 22 工作日)
Expand Down
10 changes: 10 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"dependencies": {
"commander": "^13.0.0",
"dotenv": "^16.4.0",
"groq-sdk": "^1.1.2",
"node-cron": "^4.2.1",
"openai": "^4.0.0"
},
Expand Down
4 changes: 3 additions & 1 deletion src/facebook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ export async function fetchFacebookPosts(
shareCount: item.shares ?? 0,
url: item.url ?? '',
mediaType: media?.__typename?.toLowerCase() ?? 'text',
mediaUrl: media?.thumbnail ?? media?.photo_image?.uri ?? '',
mediaUrl: media?.video_url ?? media?.playable_url
?? (media?.__typename?.toLowerCase() === 'video' ? media?.url : null)
?? media?.thumbnail ?? media?.photo_image?.uri ?? '',
};
});
}
18 changes: 17 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { analyzePosts } from './analyze.js';
import { sendTelegramMessageWithConfig, formatReport, formatFallbackReport } from './telegram.js';
import { filterNewPosts as filterNew, markPostsSeen } from './seen.js';
import { withRetry } from './retry.js';
import { createTranscriber, transcribeVideoPosts, type TranscriberType } from './transcribe.js';

// ── Config ──────────────────────────────────────────────────
const FB_PAGE_URL = 'https://www.facebook.com/DieWithoutBang/';
Expand All @@ -41,6 +42,7 @@ interface UnifiedPost {
mediaType: string;
mediaUrl: string;
ocrText: string;
transcriptText: string;
}

function fromFacebook(p: FacebookPost): UnifiedPost {
Expand All @@ -49,6 +51,7 @@ function fromFacebook(p: FacebookPost): UnifiedPost {
source: 'facebook',
text: p.text,
ocrText: p.ocrText,
transcriptText: '',
timestamp: p.timestamp,
likeCount: p.likeCount,
replyCount: p.commentCount,
Expand Down Expand Up @@ -112,6 +115,17 @@ async function runInner(opts: RunOptions) {
return;
}

// 2.5. 影片轉錄
const transcriberType = (process.env.TRANSCRIBER ?? 'noop') as TranscriberType;
const transcriber = createTranscriber(transcriberType);
if (transcriber.name !== 'noop') {
const transcripts = await transcribeVideoPosts(newPosts, transcriber);
for (const p of newPosts) {
const result = transcripts.get(p.id);
if (result) p.transcriptText = result.text;
}
}

// 按時間從新到舊排序
newPosts.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());

Expand All @@ -135,6 +149,7 @@ async function runInner(opts: RunOptions) {
const localTime = new Date(p.timestamp).toLocaleString('zh-TW', { timeZone: 'Asia/Taipei' });
console.log(`--- [${tag}]${todayTag} ${localTime} [${p.mediaType}] ---`);
console.log(p.text || '(無文字,可能是純圖片)');
if (p.transcriptText) console.log(`[影片轉錄] ${p.transcriptText}`);
if (p.mediaUrl) console.log(`媒體: ${p.mediaUrl}`);
console.log(`讚: ${p.likeCount} | 回覆: ${p.replyCount} | ${p.url}\n`);
}
Expand All @@ -146,12 +161,13 @@ async function runInner(opts: RunOptions) {

// 5. AI 分析
const textsForAnalysis = newPosts
.filter((p) => p.text.trim().length > 0 || p.ocrText.trim().length > 0)
.filter((p) => p.text.trim().length > 0 || p.ocrText.trim().length > 0 || p.transcriptText.trim().length > 0)
.map((p) => {
const tag = 'Facebook';
const localTime = new Date(p.timestamp).toLocaleString('zh-TW', { timeZone: 'Asia/Taipei' });
let content = `[${tag}] ${p.text}`;
if (p.ocrText) content += `\n[圖片 OCR] ${p.ocrText}`;
if (p.transcriptText) content += `\n[影片轉錄] ${p.transcriptText}`;
return { text: content, timestamp: localTime, isToday: isToday(p.timestamp) };
});

Expand Down
171 changes: 171 additions & 0 deletions src/transcribe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
// ── 影片轉錄抽象層 ──────────────────────────────────────────
// 策略模式:定義轉錄介面,具體實作由外部決定。
// 新增轉錄服務時只需實作 Transcriber 介面並在 createTranscriber() 加入。

import { execFile } from 'child_process';
import { createReadStream, unlinkSync, mkdirSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { promisify } from 'util';
import Groq from 'groq-sdk';

const execFileAsync = promisify(execFile);

export interface TranscribeResult {
text: string;
durationSec?: number;
}

export interface Transcriber {
readonly name: string;
transcribe(videoUrl: string): Promise<TranscribeResult>;
}

// ── Noop(預設:不轉錄)────────────────────────────────────

export class NoopTranscriber implements Transcriber {
readonly name = 'noop';
async transcribe(_videoUrl: string): Promise<TranscribeResult> {
return { text: '' };
}
}

// ── Groq Whisper ────────────────────────────────────────────
// Facebook 影片 URL 通常是頁面連結(reel/watch),Groq 無法直接存取。
// 流程:yt-dlp 下載音訊 → 傳檔案給 Groq Whisper → 清理暫存檔。

function needsDownload(url: string): boolean {
return /facebook\.com\/(reel|watch|video)/i.test(url);
}

async function downloadAudio(videoUrl: string): Promise<string> {
const tmpDir = join(tmpdir(), 'banini-tracker');
mkdirSync(tmpDir, { recursive: true });
const outTemplate = join(tmpDir, `audio-${Date.now}.%(ext)s`);
const outFile = join(tmpDir, `audio-${Date.now()}.m4a`);

await execFileAsync('yt-dlp', [
'-f', 'ba',
'--extract-audio',
'--audio-format', 'm4a',
'-o', outFile.replace('.m4a', '.%(ext)s'),
'--no-playlist',
'--quiet',
videoUrl,
], { timeout: 60_000 });

return outFile;
}

export class GroqTranscriber implements Transcriber {
readonly name = 'groq';
private client: Groq;
private model: string;

constructor(apiKey: string, model = 'whisper-large-v3') {
this.client = new Groq({ apiKey });
this.model = model;
}

async transcribe(videoUrl: string): Promise<TranscribeResult> {
if (needsDownload(videoUrl)) {
return this.transcribeViaDownload(videoUrl);
}
return this.transcribeViaUrl(videoUrl);
}

private async transcribeViaUrl(url: string): Promise<TranscribeResult> {
const result = await this.client.audio.transcriptions.create({
url,
model: this.model,
language: 'zh',
temperature: 0,
response_format: 'verbose_json',
});
const raw = result as any;
return {
text: result.text ?? '',
durationSec: raw.duration ? Math.round(raw.duration) : undefined,
};
}

private async transcribeViaDownload(videoUrl: string): Promise<TranscribeResult> {
console.log(`[轉錄] 下載音訊: ${videoUrl.slice(0, 60)}...`);
const audioFile = await downloadAudio(videoUrl);
try {
const result = await this.client.audio.transcriptions.create({
file: createReadStream(audioFile),
model: this.model,
language: 'zh',
temperature: 0,
response_format: 'verbose_json',
});
const raw = result as any;
return {
text: result.text ?? '',
durationSec: raw.duration ? Math.round(raw.duration) : undefined,
};
} finally {
try { unlinkSync(audioFile); } catch {}
}
}
}

// ── 工廠 ──────────────────────────────────────────────────

export type TranscriberType = 'noop' | 'groq';

export function createTranscriber(type: TranscriberType = 'noop'): Transcriber {
switch (type) {
case 'noop':
return new NoopTranscriber();
case 'groq': {
const apiKey = process.env.GROQ_API_KEY;
if (!apiKey) throw new Error('GROQ_API_KEY 環境變數未設定');
return new GroqTranscriber(apiKey, process.env.GROQ_WHISPER_MODEL ?? 'whisper-large-v3');
}
default:
throw new Error(`不支援的轉錄器類型: ${type}`);
}
}

// ── 輔助:判斷貼文是否為影片 ────────────────────────────────

export function isVideoPost(mediaType: string): boolean {
const videoTypes = ['video', 'native_video', 'live_video', 'reel'];
return videoTypes.includes(mediaType.toLowerCase());
}

// ── 批次轉錄 ────────────────────────────────────────────────

export interface TranscribablePost {
id: string;
mediaType: string;
mediaUrl: string;
}

export async function transcribeVideoPosts<T extends TranscribablePost>(
posts: T[],
transcriber: Transcriber,
): Promise<Map<string, TranscribeResult>> {
const results = new Map<string, TranscribeResult>();

for (const post of posts) {
if (!isVideoPost(post.mediaType) || !post.mediaUrl) continue;

try {
console.log(`[轉錄][${transcriber.name}] 處理影片: ${post.id}`);
const result = await transcriber.transcribe(post.mediaUrl);
if (result.text.trim().length > 0) {
results.set(post.id, result);
console.log(`[轉錄] ${post.id}: ${result.text.slice(0, 50)}...(${result.durationSec ?? '?'}s)`);
} else {
console.log(`[轉錄] ${post.id}: 無可辨識內容`);
}
} catch (err) {
console.error(`[轉錄] ${post.id} 失敗: ${err instanceof Error ? err.message : err}`);
}
}

return results;
}
Loading