Skip to content

armgit / my-yt

Public Imported from GitHub
0

A clean and minimal youtube frontend, without all the ads and whistles

JavaScript

video summary, downloaded videos section

Christian Fei43453e80f75a
diff --git a/index.html b/index.html
index fdce51c..7e6393a 100644
--- a/index.html
+++ b/index.html
@@ -193,6 +193,10 @@
</dialog>
<main>
+ <details class="downloaded-videos-container">
+ <summary>Downloaded videos</summary>
+ <div class="videos-container"></div>
+ </details>
<div class="channels-container"></div>
<details class="download-log">
<summary>Download Log</summary>
@@ -210,7 +214,7 @@
if (!message || !message.data) return console.error('skipping empty message')
try {
const data = JSON.parse(message.data, {})
- console.log('sse message', data)
+ console.log('[sse] message', data)
if (data.type === 'download-log-line' && data.line) {
const $downloadLog = document.querySelector('.download-log');
@@ -228,6 +232,7 @@
for (const [name, videos] of Object.entries(data.videos)) {
appendChannelSectionTo(name, videos, $channelsContainer)
+ updateDownloadedVideos(videos)
}
handleNewVideos(data.videos)
window.videos = data.videos
@@ -237,11 +242,11 @@
if (data.type === 'channel' && data.name && Array.isArray(data.videos)) {
const $existingChannelSection = document.querySelector(`details[data-channel="${data.name}"]`)
if ($existingChannelSection) {
- console.log('replacing old channel section', data.name)
$existingChannelSection.querySelector(`.videos-container`).replaceWith(channelVideosContents(data.videos))
} else {
appendChannelSectionTo(data.name, data.videos, $channelsContainer)
}
+ updateDownloadedVideos(data.videos)
window.videos[data.name] = data.videos
handleNewVideos(data.videos)
}
@@ -261,6 +266,21 @@
$channelsContainer.appendChild($channelSection)
}
+ function updateDownloadedVideos (videos) {
+ const $downloadedVideosContainer = document.querySelector('details.downloaded-videos-container')
+ const $videosContainer = $downloadedVideosContainer.querySelector('.videos-container')
+ videos.filter(v => v.downloaded).forEach(v => {
+ const $existing = $downloadedVideosContainer.querySelector(`[data-video-id="${v.id}"]`)
+ if ($existing) {
+ const $video = createVideoElement(v)
+ $existing.replaceWith($video)
+ return
+ }
+ const $video = createVideoElement(v)
+ $videosContainer.appendChild($video)
+ })
+ }
+
// store
class Store {
showThumbnailsKey = 'showThumbnails'
@@ -404,25 +424,32 @@
console.log('ignoring video', video.id)
continue
}
- const $video = document.createElement('div')
- $video.classList.add('video')
- $video.dataset['videoId'] = video.id
- $video.innerHTML = `
- <img src="${video.thumbnail}"/>
- <span>${video.publishedTime}</span> | <span>${video.viewCount}</span> | <span>${video.duration || 'N/A'}</span><br/>
- ${video.title}
- <div class="actions">
- ${!video.downloaded ? `<span tabindex="0" class="action download" data-video-id="${video.id}">⬇️ Download</span>` : ''}
- ${video.downloaded ? `<a tabindex="0" href="/videos/${video.id}" target="_blank" class="action watch" data-video-id="${video.id}">👀 watch</a>`: ``}
- ${!video.summary ? `<span tabindex="0" class="action summarize" data-video-id="${video.id}">📖 Summarize</span>` : `<span tabindex="0" class="action show-summary" data-video-id="${video.id}" data-summary="${video.summary}">📖 Show summary</span>`}
- <span tabindex="0" class="action ignore" data-video-id="${video.id}">🙈 Ignore</span>
- </div>
- `
- $videosContainer.appendChild($video)
+ $videosContainer.appendChild(createVideoElement(video))
}
return $videosContainer
}
+ function createVideoElement (video) {
+ const $video = document.createElement('div')
+ $video.classList.add('video')
+ $video.dataset['videoId'] = video.id
+ $video.innerHTML = `
+ <img src="${video.thumbnail}"/>
+ <span>${video.publishedTime}</span> | <span>${video.viewCount}</span> | <span>${video.duration || 'N/A'}</span><br/>
+ ${video.title}
+ <div class="actions">
+ ${video.downloaded
+ ? `<a tabindex="0" href="/videos/${video.id}" target="_blank" class="action watch" data-video-id="${video.id}">👀 watch</a>`
+ : `<span tabindex="0" class="action download" data-video-id="${video.id}">⬇️ Download</span>`}
+ ${!video.summary
+ ? `<span tabindex="0" class="action summarize" data-video-id="${video.id}">📖 Summarize</span>`
+ : `<span tabindex="0" class="action show-summary" data-video-id="${video.id}" data-summary="${video.summary}">📖 Summary</span>`}
+ <span tabindex="0" class="action ignore" data-video-id="${video.id}">🙈 Ignore</span>
+ </div>
+ `
+ return $video
+ }
+
function handleNewVideos (videos) {
document.querySelectorAll('.video .actions .action.watch')
.forEach($watchAction => {
@@ -514,6 +541,7 @@
console.error('Error starting download:', error)
})
}
+
function summarizeVideoHandler (event) {
event.preventDefault()
const summaryStartedText = '⚡️ summary started'
@@ -531,6 +559,7 @@
console.error('Error starting summary:', error)
})
}
+
function showSummaryHandler (event) {
event.preventDefault()
const videoId = event.target.dataset.videoId
diff --git a/server.js b/server.js
index 219e481..964ec90 100644
--- a/server.js
+++ b/server.js
@@ -172,45 +172,144 @@ async function summarizeVideo(id, repo) {
*/
const transcriptPath = `./data/videos/${id}-sub.en.srt`
const transcriptContent = fs.readFileSync(transcriptPath, 'utf-8')
- const cleanedTranscript = transcriptContent.replace(/\d+\n\d{2}:\d{2}:\d{2},\d{3} --> \d{2}:\d{2}:\d{2},\d{3}\n<font color="white" size=".72c">(.*?)<\/font>/g, '$1\n').replace(/\n+/g, '\n')
+ let cleanedTranscript = transcriptContent.replace(/\d+\n\d{2}:\d{2}:\d{2},\d{3} --> \d{2}:\d{2}:\d{2},\d{3}\n<font color="white" size=".72c">(.*?)<\/font>/g, '$1\n').replace(/\n+/g, '\n')
repo.setVideoTranscript(id, cleanedTranscript)
fs.writeFileSync(`./data/videos/${id}-sub.en.txt`, cleanedTranscript)
+ const shortenedText = await shortenTextLMSTUDIO(cleanedTranscript)
- const {response} = await fetchAIResponse(`Summarize the following transcript of a YouTube video, avoid talking about the host and avoid describing the context, keep it short, to the point, and fit it in max 10 paragraphs: \n ${cleanedTranscript}`)
- console.log(response)
- repo.setVideoSummary(id, response)
-
+ const prompt = `Summarize the following transcript, in max 10 paragraphs, your output should just contain the summary, keep it short, succint, to the point: \n\n ${cleanedTranscript}`
+ console.log('prompt', prompt)
+ const summary = await fetchAIResponseLMSTUDIO(prompt)
+ console.log(summary)
+ repo.setVideoSummary(id, summary)
+
console.log('Download completed')
} catch (error) {
console.error('Error downloading video:', error)
}
}
-async function fetchAIResponse (prompt) {
- const url = 'http://localhost:11434/api/generate';
- const options = {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- body: JSON.stringify({
- "model": "llama3.2",
- "prompt": prompt,
- "stream": false
- })
- };
+async function fetchAIResponseOLLAMA (prompt) {
try {
- const response = await fetch(url, options);
+ const response = await fetch('http://localhost:11434/api/generate', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ "model": "llama3.2",
+ "prompt": prompt,
+ "stream": false
+ })
+ })
if (!response.ok) {
- throw new Error(`HTTP error! Status: ${response.status}`);
+ throw new Error(`HTTP error! Status: ${response.status}`)
}
- const data = await response.json();
- // console.log(data);
+ const data = await response.json()
+ // console.log(data)
return data
} catch (error) {
- console.error('Error summarizing text:', error);
+ console.error('Error summarizing text:', error)
+ }
+}
+async function fetchAIResponseLMSTUDIO (prompt) {
+ if (prompt.length > 2500) prompt = prompt.substring(0, 2500)
+ try {
+ const response = await fetch('http://localhost:1234/v1/completions', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ "model": "mlx-community/Llama-3.2-3B-Instruct-4bit",
+ "prompt": prompt,
+ "temperature": 0.7,
+ // "max_tokens": 10,
+ "stream": false,
+ // "stop": "\n"
+ })
+ })
+ if (!response.ok) {
+ throw new Error(`HTTP error! Status: ${response.status}`)
+ }
+ const data = await response.json()
+ console.log(data)
+ return data.choices[data.choices.length - 1]?.text
+ } catch (error) {
+ console.error('Error summarizing text:', error)
+ }
+}
+
+
+async function shortenTextOLLAMA(text) {
+ // split the text into 1600 character blocks
+ const chunks = []
+ for (let i = 0; i < text.length; i += 5000) {
+ chunks.push(text.substring(i, i + 5000))
+ }
+ const responses = []
+ try {
+ for (const chunk of chunks) {
+ console.log('shortening chunk', chunk.substring(0, 20))
+ const prompt = `shorten the following text: \n ${chunk}`
+ const response = await fetch('http://localhost:11434/api/generate', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ "model": "gemma2",
+ "prompt": prompt,
+ "stream": false
+ })
+ })
+ if (!response.ok) {
+ throw new Error(`HTTP error! Status: ${response.status}`)
+ }
+ const data = await response.json()
+ responses.push(data.response)
+ }
+ } catch (error) {
+ console.error('Error summarizing text:', error)
}
+ return responses.join(' \n')
+}
+async function shortenTextLMSTUDIO(text) {
+ // split the text into 1600 character blocks
+ const chunks = []
+ for (let i = 0; i < text.length; i += 1800) {
+ chunks.push(text.substring(i, i + 1800))
+ }
+ const responses = []
+ try {
+ for (const chunk of chunks) {
+ console.log('shortening chunk', chunk.substring(0, 20))
+ const prompt = `shorten the following text: \n ${chunk}`
+ const response = await fetch('http://localhost:1234/v1/completions', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ "model": "mlx-community/Llama-3.2-3B-Instruct-4bit",
+ "prompt": prompt,
+ "temperature": 0.7,
+ // "max_tokens": 10,
+ "stream": false,
+ // "stop": "\n"
+ })
+ })
+ if (!response.ok) {
+ throw new Error(`HTTP error! Status: ${response.status}`)
+ }
+ const data = await response.json()
+ responses.push(data.response)
+ }
+ } catch (error) {
+ console.error('Error summarizing text:', error)
+ }
+ return responses.join(' \n')
}
@@ -398,4 +497,5 @@ function createServer ({repo, port = 3000}) {
res.writeHead(200, { 'Content-Type': 'text/html' })
res.end(indexHtml)
})
+
}