A clean and minimal youtube frontend, without all the ads and whistles
JavaScript
feat: claude models support
Seyar Chapukhde1218faf12f
diff --git a/README.md b/README.mdindex 6b15cdc..9669e37 100644--- a/README.md+++ b/README.md@@ -31,7 +31,7 @@ A clean and minimal youtube frontend supported by yt-dlp, and optionally your lo[Check out the todo list](https://github.com/christian-fei/my-yt/issues/5)-> Application runs on http://localhost:3000+> Application runs on http://localhost:3000@@ -74,13 +74,16 @@ docker run -d -p 3000:3000 -v $HOME/my-yt-data:/app/data christianfei/my-yt:late## Environment variables for LLM integration-The default values are-```-AI_MODEL meta-llama-3.1-8b-instruct-AI_HOST http://127.0.0.1:1234-AI_ENDPOINT /v1/chat/completions-AI_APIKEY-```+| Variable | Type | Default |+|---|---|---|+| SKIP_TRANSCODING | boolean | false | |+| AI_APIKEY | string | |+| AI_MODEL | string | meta-llama-3.1-8b-instruct |+| AI_HOST | string | http://127.0.0.1:1234 |+| AI_ENDPOINT | string | /v1/chat/completions |+| AI_TEMPERATURE | string | 0 |+| AI_LANGUAGE | string | english | | |+Simply set the env variables to your needs, by following the format above (e.g. url starting with "http", no ending slash, AI_ENDPOINT with leading slash and path)diff --git a/lib/drivers/anthropic.js b/lib/drivers/anthropic.jsnew file mode 100644index 0000000..d787fb0--- /dev/null+++ b/lib/drivers/anthropic.js@@ -0,0 +1,63 @@+const ANTHROPIC_VERSION = '2023-06-01'+const MAX_PROMPT_LEN = 10000+const MAX_TOKENS = 1024++export class Anthropic {+ constructor(system, {+ model,+ host,+ apiKey,+ max_tokens = MAX_TOKENS,+ }) {++ this.system = system+ const auth = apiKey ? { 'x-api-key': apiKey } : {}+ this.headers = Object.assign({+ 'Content-Type': 'application/json',+ 'anthropic-version': ANTHROPIC_VERSION,+ }, auth)++ this.settings = {+ model,+ host,+ apiKey,+ max_tokens+ }+ }++ async summarize(prompt, { endpoint }) {+ if (prompt.length > MAX_PROMPT_LEN) prompt = prompt.substring(0, MAX_PROMPT_LEN)++ const body = JSON.stringify({+ model: this.settings.model,+ system: this.system,+ max_tokens: this.settings.max_tokens,+ messages: [+ { role: "user", content: prompt }+ ]+ })++ try {+ const response = await fetch(this.settings.host + endpoint, {+ method: 'POST',+ headers: this.headers,+ body+ })++ const data = await response.json()+ if (!response.ok) {+ console.error(data)+ throw new Error(`HTTP error! Status: ${response.status}`)+ }++ const messages = data?.content || []+ let message = messages[messages.length - 1].text || ''++ message = message.replace('<|eot_id|>', '')+ return message+ } catch (error) {+ console.error('Error summarizing text:', error)+ throw error+ }+ }+}diff --git a/lib/drivers/openai.js b/lib/drivers/openai.jsnew file mode 100644index 0000000..2b45eef--- /dev/null+++ b/lib/drivers/openai.js@@ -0,0 +1,56 @@+const MAX_PROMPT_LEN = 10000++export class Openai {+ constructor(system, {+ model,+ host,+ apiKey,+ max_tokens,+ }) {++ this.system = system+ this.headers = Object.assign({+ 'Content-Type': 'application/json',+ }, apiKey ? { 'Authorization': `Bearer ${apiKey}` } : {})++ this.settings = {+ model,+ host,+ apiKey,+ max_tokens+ }+ }++ async summarize(prompt, { endpoint }) {+ if (prompt.length > MAX_PROMPT_LEN) prompt = prompt.substring(0, MAX_PROMPT_LEN)++ const body = JSON.stringify({+ model: this.settings.model,+ messages: [+ { role: "system", content: this.system },+ { role: "user", content: prompt }+ ]+ })++ try {+ const response = await fetch(this.settings.host + endpoint, {+ method: 'POST',+ headers: this.headers,+ body+ })++ const data = await response.json()+ if (!response.ok) {+ console.error(data)+ throw new Error(`HTTP error! Status: ${response.status}`)+ }++ let message = data.choices[data.choices.length - 1]?.message?.content || ''+ message = message.replace('<|eot_id|>', '')+ return message+ } catch (error) {+ console.error('Error summarizing text:', error)+ throw error+ }+ }+}diff --git a/lib/llm.js b/lib/llm.jsindex 538d3ec..688a6c9 100644--- a/lib/llm.js+++ b/lib/llm.js@@ -1,48 +1,21 @@-export async function fetchCompletionLMSTUDIO (- system,+import { Anthropic } from "./drivers/anthropic.js"+import { Openai } from "./drivers/openai.js"++export async function fetchCompletionLMSTUDIO(+ system,prompt,- {- model,- host,- endpoint,- apiKey- } = {- model: 'meta-llama-3.1-8b-instruct',- host: 'http://127.0.0.1:1234',- endpoint: '/v1/chat/completions',- apiKey: ''- }+ llmSettings,) {- if (prompt.length > 10000) prompt = prompt.substring(0, 10000)- const headers = Object.assign({- 'Content-Type': 'application/json'- }, apiKey ? {'Authorization': `Bearer ${apiKey}`} : {})- const body = JSON.stringify({- model,- messages: [- {role: "system", content: system},- {role: "user", content: prompt}- ]- })-try {- const response = await fetch(host + endpoint, {- method: 'POST',- headers,- body- })-- const data = await response.json()- if (!response.ok) {- console.error(data)- throw new Error(`HTTP error! Status: ${response.status}`)+ let llm+ if (llmSettings.model.includes('claude')) {+ llm = new Anthropic(system, llmSettings)+ } else {+ llm = new Openai(system, llmSettings)}-- let message = data.choices[data.choices.length - 1]?.message?.content || ''- message = message.replace('<|eot_id|>', '')- return message- } catch (error) {- console.error('Error summarizing text:', error)- throw error++ return await llm.summarize(prompt, llmSettings)+ } catch (e) {+ console.error('Error summarizing video', e.message)}-}\ No newline at end of file+}diff --git a/lib/router/api.js b/lib/router/api.jsindex d216889..0e13d40 100644--- a/lib/router/api.js+++ b/lib/router/api.js@@ -6,43 +6,57 @@ import { broadcastSSE } from '../sse.js'import { downloadVideo, extractIdFromUrl, isUnsupportedUrl, isYouTubeUrl } from '../youtube.js'import { updateAndPersistVideosForChannel } from '../update-videos.js'+const llmDefaults = {+ model:'meta-llama-3.1-8b-instruct',+ host: 'http://127.0.0.1:1234',+ endpoint: '/v1/chat/completions',+ apiKey: '',+ apiHeader: '',+ temperature: 0,+ language: 'english'+}+const llmSettings = {- model: process.env.AI_MODEL || 'meta-llama-3.1-8b-instruct',- host: process.env.AI_HOST ||'http://127.0.0.1:1234',- endpoint: process.env.AI_ENDPOINT ||'/v1/chat/completions',- apiKey: process.env.AI_APIKEY || ''+ ...llmDefaults,+ model: process.env.AI_MODEL,+ host: process.env.AI_HOST,+ endpoint: process.env.AI_ENDPOINT,+ apiKey: process.env.AI_APIKEY,+ apiHeader: process.env.AI_AUTH_HEADER,+ temperature: process.env.AI_TEMPERATURE,+ language: process.env.AI_LANGUAGE}export default function apiHandler(req, res, repo, connections = [], state = {}) {const url = new URL(req.url, `http://${req.headers.host}`)-- if (url.pathname === '/api/channels' && req.method === 'GET')++ if (url.pathname === '/api/channels' && req.method === 'GET')return getChannelHandler(req, res, repo, connections)- if (url.pathname === '/api/channels' && req.method === 'POST')+ if (url.pathname === '/api/channels' && req.method === 'POST')return addChannelHandler(req, res, repo, connections)- if (url.pathname === '/api/channels' && req.method === 'DELETE')+ if (url.pathname === '/api/channels' && req.method === 'DELETE')return deleteChannelHandler(req, res, repo, connections)- if (url.pathname === '/api/download-video' && req.method === 'POST')+ if (url.pathname === '/api/download-video' && req.method === 'POST')return downloadVideoHandler(req, res, repo, connections, state)- if (url.pathname === '/api/summarize-video' && req.method === 'POST')+ if (url.pathname === '/api/summarize-video' && req.method === 'POST')return summarizeVideoHandler(req, res, repo, connections, state, llmSettings)- if (url.pathname === '/api/ignore-video' && req.method === 'POST')+ if (url.pathname === '/api/ignore-video' && req.method === 'POST')return ignoreVideoHandler(req, res, repo, connections)- if (url.pathname === '/api/delete-video' && req.method === 'POST')+ if (url.pathname === '/api/delete-video' && req.method === 'POST')return deleteVideoHandler(req, res, repo, connections)- if (url.pathname === '/api/videos' && req.method === 'GET')+ if (url.pathname === '/api/videos' && req.method === 'GET')return searchVideosHandler(req, res, repo, connections)- if (url.pathname === '/api/video-quality' && req.method === 'GET')+ if (url.pathname === '/api/video-quality' && req.method === 'GET')return getVideoQualityHandler(req, res, repo, connections)- if (url.pathname === '/api/video-quality' && req.method === 'POST')+ if (url.pathname === '/api/video-quality' && req.method === 'POST')return setVideoQualityHandler(req, res, repo, connections)- if (url.pathname === '/api/disk-usage' && req.method === 'GET')+ if (url.pathname === '/api/disk-usage' && req.method === 'GET')return diskUsageHandler(req, res, repo, connections)- if (url.pathname === '/api/reclaim-disk-space' && req.method === 'POST')+ if (url.pathname === '/api/reclaim-disk-space' && req.method === 'POST')return reclaimDiskSpaceHandler(req, res, repo, connections)- if (url.pathname.match(/\/api\/videos\/.*/) && req.method === 'GET')+ if (url.pathname.match(/\/api\/videos\/.*/) && req.method === 'GET')return watchVideoHandler(req, res, repo)- if (url.pathname.match(/\/api\/captions\/.*/) && req.method === 'GET')+ if (url.pathname.match(/\/api\/captions\/.*/) && req.method === 'GET')return captionsHandler(req, res, repo)res.writeHead(404)@@ -60,7 +74,7 @@ async function addChannelHandler(req, res, repo, connections = []) {let { name } = JSON.parse(body)name = name.trim()name = name.startsWith('@') ? name.substring(1) : name-+if (repo.channelExists(name)) {res.writeHead(409)return res.end('Channel already added')@@ -82,7 +96,7 @@ async function deleteChannelHandler(req, res, repo, connections = []) {const body = await getBody(req)let { name } = JSON.parse(body)name = name.trim()-+if (!repo.channelExists(name)) {res.writeHead(409, { 'Content-Type': 'text/plain' })return res.end('Channel does not exist')@@ -96,14 +110,14 @@ async function deleteChannelHandler(req, res, repo, connections = []) {async function downloadVideoHandler(req, res, repo, connections = [], state = {}) {const body = await getBody(req)let { id, external } = JSON.parse(body)-+if (isUnsupportedUrl(id)) {console.log('unsupported url', id)res.writeHead(400)return res.end()}if (isYouTubeUrl(id)) { id = extractIdFromUrl(id) }-+state.downloading = state.downloading || {}state.downloading[id] = {lines: []}@@ -139,7 +153,7 @@ async function summarizeVideoHandler(req, res, repo, connections = [], state = {broadcastSSE(JSON.stringify({type: 'download-log-line', line}), connections)state.changed = true})- .then(({summary, transcript}) =>+ .then(({summary, transcript}) =>broadcastSSE(JSON.stringify({type: 'summary', summary, transcript, videoId: id}), connections)).catch((error) => {broadcastSSE(JSON.stringify({type: 'download-log-line', line: error.message}), connections)@@ -204,7 +218,7 @@ function diskUsageHandler(req, res, repo) {const videos = repo.getAllVideos()const filterFn = onlyIgnored ? video => video.downloaded && video.ignored : video => video.downloaded-+const diskSpaceUsed = videos.filter(filterFn).reduce((total, video) => {try {@@ -303,8 +317,8 @@ function watchVideoHandler(req, res, repo) {res.statusCode = (start !== undefined || end !== undefined) ? 206 : 200res.setHeader("content-length", retrievedLength)-- if (range !== undefined) {++ if (range !== undefined) {res.setHeader("accept-ranges", "bytes")res.setHeader("content-range", `bytes ${start || 0}-${end || (contentLength-1)}/${contentLength}`)}@@ -315,7 +329,7 @@ function watchVideoHandler(req, res, repo) {res.writeHead(500)res.end()})-+fileStream.pipe(res)}@@ -348,6 +362,6 @@ async function getBody (req) {function getQuery (req) {return (req.url && req.url.indexOf('?') >= 0)- ? querystring.parse(req.url.substring(req.url.indexOf('?') + 1))+ ? querystring.parse(req.url.substring(req.url.indexOf('?') + 1)): {}-}\ No newline at end of file+}