-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
231 lines (195 loc) · 7.78 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
const ffmpeg = require('fluent-ffmpeg');
const ffmpegPath = require('ffmpeg-static');
const axios = require('axios');
const FormData = require('form-data');
const yaml = require('js-yaml');
const { ArgumentParser } = require('argparse');
const GhostAdminAPI = require('@tryghost/admin-api');
const showdown = require('showdown');
const sharp = require('sharp');
ffmpeg.setFfmpegPath(ffmpegPath);
const downloadYouTubeAudio = async (url, outputPath) => {
if (fs.existsSync(outputPath)) {
console.log('Audio file already exists, skipping download.');
return;
}
return new Promise((resolve, reject) => {
exec(`yt-dlp -x --audio-format wav -o "${outputPath}" "${url}"`, (error, stdout, stderr) => {
if (error) {
reject(`Error during audio download: ${error.message}`);
} else {
console.log('Audio download completed');
resolve();
}
});
});
};
const transcribeAudio = async (audioFile, outputFile) => {
if (fs.existsSync(audioFile.replace('.wav', '.txt'))) {
console.log('Transcript file already exists, skipping transcription.');
return;
}
return new Promise((resolve, reject) => {
exec(`whisper ${audioFile} -o ${outputFile}`, (error, stdout, stderr) => {
if (error) {
reject(`Error: ${error.message}`);
} else {
resolve();
}
});
});
};
const generateSummary = async (transcript, prompt, model = 'llama3') => {
const question = prompt.replace('{transcript}', transcript.replace(/[^A-Za-z\s]/g, '').replace(/\n/g, ''));
const promptData = {
model: model,
stream: false,
prompt: question,
};
try {
const response = await axios.post('http://localhost:11434/api/generate', promptData);
return response.data.response || 'Failed to generate summary';
} catch (error) {
return 'Failed to generate summary';
}
};
const extractYouTubeId = (url) => {
const urlObj = new URL(url);
return urlObj.searchParams.get('v');
};
const readImageFile = async (imagePath) => {
try {
const imageBuffer = await fs.promises.readFile(imagePath);
return imageBuffer;
} catch (error) {
console.error('Failed to read image file:', error.message);
throw error;
}
};
const playButtonSVG = Buffer.from(`
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 150 100">
<rect x="0" y="0" width="150" height="100" rx="25" ry="25" fill="rgba(255,0,0,0.8)" />
<polygon points="55,25 95,50 55,75" fill="white"/>
</svg>
`);
const addPlayButtonOverlay = async (thumbnailPath, outputPath) => {
try {
await sharp(`${thumbnailPath}.jpg`)
.composite([{ input: playButtonSVG, gravity: 'center' }])
.toFile(outputPath);
console.log('Play button overlay added successfully');
} catch (error) {
console.error('Failed to add play button overlay:', error.message);
throw error;
}
};
const uploadGhostImage = async (ghostApi, imagePath) => {
try {
const imageBuffer = await readImageFile(imagePath);
const formData = new FormData();
formData.append('file', imageBuffer, {
filename: path.basename(imagePath),
contentType: 'image/jpeg'
});
const uploadedImage = await ghostApi.images.upload(formData);
console.log('Image uploaded successfully:', uploadedImage.url);
return uploadedImage.url;
} catch (error) {
console.error('Failed to upload image:', error.message);
throw new Error('Failed to upload image');
}
};
const createGhostPost = async (apiUrl, adminApiKey, title, body, featureImage, codeInjectionHead) => {
var converter = new showdown.Converter();
const ghost = new GhostAdminAPI({
url: apiUrl,
key: adminApiKey,
version: 'v5.0'
});
try {
await ghost.posts.add({
title: title,
html: converter.makeHtml(body),
status: 'draft',
feature_image: `${featureImage}.jpg`,
codeinjection_head: codeInjectionHead
},
{ source: 'html' }
);
console.log('Draft post created successfully');
} catch (error) {
console.error(`Failed to create draft post: ${error}`);
}
};
const downloadThumbnail = async (url, outputPath) => {
return new Promise((resolve, reject) => {
exec(`yt-dlp --write-thumbnail --skip-download --convert-thumbnails jpg -o "${outputPath}" "${url}"`, (error, stdout, stderr) => {
if (error) {
reject(`Error downloading thumbnail: ${error.message}`);
} else {
console.log('Thumbnail download completed');
resolve();
}
});
});
};
const main = async () => {
const parser = new ArgumentParser({ description: 'Process YouTube video URL and configuration file.' });
parser.add_argument('url', { type: 'str', help: 'YouTube video URL' });
parser.add_argument('config', { type: 'str', help: 'Configuration file with prompts and paths' });
const args = parser.parse_args();
const { url, config } = args;
try {
const configFile = fs.readFileSync(config, 'utf8');
const configData = yaml.load(configFile);
const prompts = configData.prompts || {};
const { summary: summaryPrompt, title: titlePrompt, teaser: teaserPrompt, cta: ctaPrompt } = prompts;
const directory = configData.directory;
const ghostUrl = configData.ghost.url;
const ghostKey = configData.ghost.key;
if (!directory || !ghostUrl || !ghostKey) {
console.log('Missing directory path or Ghost credentials in the configuration file.');
return;
}
const youtubeId = extractYouTubeId(url);
if (!youtubeId) {
console.log('Invalid YouTube URL. Exiting the process.');
return;
}
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory, { recursive: true });
}
const audioFilePath = path.join(directory, `${youtubeId}.wav`);
const transcriptFilePath = path.join(directory, `${youtubeId}.txt`);
const thumbnailPath = path.join(directory, `${youtubeId}`);
const outputPath = path.join(directory, `${youtubeId}_with_button.jpg`);
await downloadYouTubeAudio(url, audioFilePath);
await transcribeAudio(audioFilePath, directory);
await downloadThumbnail(url, thumbnailPath);
if (fs.existsSync(transcriptFilePath)) {
const transcript = fs.readFileSync(transcriptFilePath, 'utf8');
const content = await generateSummary(transcript, summaryPrompt);
const title = await generateSummary(content, titlePrompt);
const teaser = await generateSummary(content, teaserPrompt);
const cta = await generateSummary(content, ctaPrompt);
const body = `${title}\n\n${url}\n\n${teaser}\n\n${content}\n\n${cta}`;
const codeInjectionHead = '<style>figure.gh-article-image {display:none;}</style>';
await addPlayButtonOverlay(thumbnailPath, outputPath);
const ghostApi = new GhostAdminAPI({
url: ghostUrl,
key: ghostKey,
version: 'v5.0'
});
const featureImage = await uploadGhostImage(ghostApi, outputPath);
await createGhostPost(ghostUrl, ghostKey, youtubeId, body, featureImage, codeInjectionHead);
} else {
console.log('Transcription failed. Exiting the process.');
}
} catch (error) {
console.error(`Error: ${error.message}`);
}
};
main();