const express = require('express');
const { chromium } = require('playwright');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
const html = `
YouTube Transcript Generator (Playwright)
YouTube Transcript Generator (Playwright)
`;
app.get('/', (req, res) => {
res.send(html);
});
app.post('/extract-transcript', async (req, res) => {
const { videoUrl, videoTitle } = req.body;
if (!videoUrl || !videoTitle) {
return res.status(400).send('videoUrl and videoTitle are required');
}
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
try {
await page.goto(videoUrl, { waitUntil: 'networkidle' });
// Set viewport size
await page.setViewportSize({ width: 1920, height: 1080 });
// Click the "Expand" button to expand the video description
await page.click('tp-yt-paper-button#expand');
// Wait for the "Show transcript" button and click it
await page.click('button[aria-label="Show transcript"]');
// Wait for the transcript container to appear
await page.waitForSelector('ytd-transcript-segment-list-renderer');
// Extract the transcript text
const transcript = await page.evaluate(() => {
const elements = Array.from(document.querySelectorAll('ytd-transcript-segment-renderer .segment-text'));
return elements.map(element => element.innerText).join('\n');
});
res.json({ transcript });
} catch (error) {
console.error('Error extracting transcript:', error);
res.status(500).send('Error extracting transcript');
} finally {
await browser.close();
}
});
const PORT = 7860;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});