diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..c176ec8 --- /dev/null +++ b/.env.example @@ -0,0 +1,35 @@ +HOST=0.0.0.0 +PORT=7000 +BASE_URL=http://127.0.0.1:7000 +CACHE_DIR=.cache +CACHE_TTL_SECONDS=86400 +MAX_RESULTS=8 +MIN_CONFIDENCE=0.55 + +# Required for OpenSubtitles search/download. +OPENSUBTITLES_API_KEY= +OPENSUBTITLES_TOKEN= +OPENSUBTITLES_USER_AGENT=StremioSubEngine v0.1.0 + +# none | libretranslate | ollama +TRANSLATOR=none +LIBRETRANSLATE_URL=http://127.0.0.1:5000 +LIBRETRANSLATE_API_KEY= +OLLAMA_URL=http://127.0.0.1:11434 +OLLAMA_MODEL=qwen3:4b +TRANSLATION_CONCURRENCY=4 + +# Full media-aware synchronization/ASR. Keep disabled on public Internet hosts unless you understand the SSRF implications. +ENABLE_MEDIA_ACCESS=false +ALLOW_PRIVATE_STREAMS=true +SYNC_ENGINE=ffsubsync +FFSUBSYNC_COMMAND=ffsubsync +ALASS_COMMAND=alass-cli +SYNC_TIMEOUT_MS=180000 + +ENABLE_ASR=false +PYTHON_COMMAND=python3 +ASR_MODEL=small +ASR_DEVICE=auto +ASR_COMPUTE_TYPE=auto +ASR_TIMEOUT_MS=900000 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..34811e8 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,16 @@ +name: CI +on: + push: + branches: [main] + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - run: npm test + - run: npm run check diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1ba0222 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.cache/ +.env +node_modules/ +.DS_Store +__pycache__/ +*.pyc diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..4e68278 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,12 @@ +FROM node:22-bookworm-slim + +RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg python3 python3-pip ca-certificates \ + && pip3 install --break-system-packages 'ffsubsync==0.5.1' 'faster-whisper>=1.1,<2' \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app +COPY . . +RUN mkdir -p /data/cache +ENV CACHE_DIR=/data/cache HOST=0.0.0.0 PORT=7000 +EXPOSE 7000 +CMD ["node", "src/index.mjs"] diff --git a/Dockerfile.lite b/Dockerfile.lite new file mode 100644 index 0000000..4b3d48a --- /dev/null +++ b/Dockerfile.lite @@ -0,0 +1,7 @@ +FROM node:22-bookworm-slim +WORKDIR /app +COPY . . +RUN mkdir -p /data/cache +ENV CACHE_DIR=/data/cache HOST=0.0.0.0 PORT=7000 ENABLE_MEDIA_ACCESS=false ENABLE_ASR=false +EXPOSE 7000 +CMD ["node", "src/index.mjs"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3681911 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 SaymonMaster14 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 996380a..95a8eee 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,172 @@ # Stremio Sub Engine -Bootstrap commit. The implementation is developed through pull requests. +A self-hosted Stremio subtitle add-on that treats subtitles as a resolution problem rather than a single-provider lookup: + +1. identify the exact video release from `videoHash`, `videoSize`, filename and IMDb/episode identity; +2. rank subtitle candidates by confidence; +3. prefer a correctly timed subtitle in the target language; +4. otherwise use a synchronized subtitle in another language and translate only its text, preserving timestamps; +5. when the Stremio request exposes an accessible `streamUrl`, optionally align against the actual audio with `ffsubsync`/ALASS; +6. if no subtitle exists at all, optionally fall back to `faster-whisper` ASR. + +The project intentionally separates **resolution**, **alignment**, and **transformation**. ASR is the last fallback, not the default path. + +## What works with Stremio today + +Current subtitle requests can include `videoHash`, `videoSize` and `filename`. That is enough for exact OpenSubtitles hash matching and strong release-name matching. Translation works server-side while preserving the matched subtitle's timestamps. + +Current Stremio clients do **not universally pass the selected stream URL to subtitle add-ons**. Therefore audio-aware synchronization and ASR cannot be guaranteed by a normal remote add-on today. This repository already implements those code paths and consumes an optional `streamUrl` extra when available. + +Full media-aware mode is most useful when this add-on is self-hosted on the same machine/network namespace as a Stremio streaming server, or when the selected stream URL is otherwise reachable from the add-on host. + +## Quick start + +Requirements for the normal mode: + +- Node.js 22+ +- an OpenSubtitles REST API key + +```bash +cp .env.example .env +# set OPENSUBTITLES_API_KEY in .env +node src/index.mjs +``` + +Open `http://127.0.0.1:7000/configure`, choose preferences, and press **Install in Stremio**. + +No npm dependencies are required at runtime. + +## Docker + +The default Docker image includes FFmpeg, ffsubsync 0.5.1 and faster-whisper so full media-aware mode can be enabled without changing images: + +```bash +cp .env.example .env +docker compose up -d addon +``` + +For lookup/translation-only deployments, `Dockerfile.lite` omits Python/FFmpeg tooling. + +### Free/open-source translation + +Two local/self-hostable translation backends are implemented: + +- `TRANSLATOR=libretranslate` — LibreTranslate HTTP API. +- `TRANSLATOR=ollama` — an Ollama model using structured JSON batches. + +To run LibreTranslate alongside the add-on: + +```bash +docker compose --profile translate up -d +``` + +Set `TRANSLATOR=libretranslate` and, from inside Compose, `LIBRETRANSLATE_URL=http://libretranslate:5000`. + +## OpenSubtitles + +Configure: + +```env +OPENSUBTITLES_API_KEY=... +OPENSUBTITLES_TOKEN=... # optional; useful for authenticated quota +``` + +The resolver performs bounded searches using exact file hash first, then IMDb/season/episode identity. Results are deduplicated and ranked using: + +- OpenSubtitles movie-hash match; +- IMDb identity match; +- release/filename token similarity; +- target-language match; +- trusted-uploader and accessibility metadata. + +Only candidates above the configured confidence threshold are returned to Stremio. This avoids auto-selecting a random same-title subtitle just because one exists. + +## Translation pipeline + +A foreign-language subtitle is only translated when its timing confidence is high enough. The parser converts SRT/WebVTT into cue objects, translates cue text, and renders fresh SRT while leaving cue start/end timestamps unchanged. + +Ollama batches cues and requires an equal-length JSON response. LibreTranslate uses bounded concurrency per cue. Generated subtitles are cached on disk. + +## Full synchronization + +Enable explicit media access: + +```env +ENABLE_MEDIA_ACCESS=true +SYNC_ENGINE=ffsubsync +``` + +When a subtitle request contains `streamUrl`, the materialization pipeline can run: + +```text +ffsubsync -i input.srt -o output.srt \ + --multi-segment-sync --segment-count 6 \ + --skip-intro-outro --parallel-workers 4 \ + --skip-sync-on-low-quality +``` + +This uses sparse samples across the reference rather than blindly processing the entire movie. `SYNC_ENGINE=alass` is also supported when `alass-cli` is installed. + +### Security + +Media access is **off by default** because a server that accepts arbitrary stream URLs can become an SSRF primitive. Keep it disabled on public hosts unless stream URL input is trusted and network access is isolated. `ALLOW_PRIVATE_STREAMS=false` rejects obvious loopback/private literal IPs. + +## ASR fallback + +Enable: + +```env +ENABLE_MEDIA_ACCESS=true +ENABLE_ASR=true +ASR_MODEL=small +ASR_DEVICE=auto +ASR_COMPUTE_TYPE=auto +``` + +If there are no accepted subtitle candidates and an accessible `streamUrl` exists, Stremio receives an ASR fallback subtitle URL. On first fetch, `tools/asr_faster_whisper.py` transcribes the stream and emits SRT. The result is cached. + +ASR is deliberately last because it is much more expensive than reusing an existing correctly timed subtitle. + +## Stremio endpoints + +- `/manifest.json` — unconfigured manifest; +- `/configure` — custom configuration page; +- `//manifest.json` — configured add-on manifest; +- `//subtitles/{type}/{id}/{extra}.json` — subtitle resolution; +- `/subtitle/{opaque-job-id}.srt` — lazy download/sync/translate/ASR materialization; +- `/health` — enabled provider/capability status without exposing secrets. + +The opaque job URL is intentional: selected stream URLs and provider credentials are not embedded in the subtitle URL returned to the player. + +## Development + +```bash +npm test +npm run check +``` + +The codebase has zero Node runtime dependencies and uses the built-in Node test runner. + +## Architecture + +```text +Stremio subtitle request + | + v +release identity (IMDb + hash + filename) + | + v +provider searches -> dedupe -> confidence ranking + | + +-- target language, good timing -------------------+ + | | + +-- foreign language, good timing -> translation ---+--> cached SRT + | | + +-- streamUrl available -> audio alignment ---------+ + | | + +-- no subtitle -> faster-whisper ASR --------------+ +``` + +## License + +MIT. diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..3884882 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,21 @@ +services: + addon: + build: . + ports: + - "7000:7000" + env_file: .env + volumes: + - subtitle-cache:/data/cache + restart: unless-stopped + + libretranslate: + image: libretranslate/libretranslate:latest + profiles: ["translate"] + environment: + LT_LOAD_ONLY: en,pt,es,fr,de,it + ports: + - "5000:5000" + restart: unless-stopped + +volumes: + subtitle-cache: diff --git a/package.json b/package.json new file mode 100644 index 0000000..1b446b6 --- /dev/null +++ b/package.json @@ -0,0 +1,16 @@ +{ + "name": "stremio-sub-engine", + "version": "0.1.0", + "private": false, + "description": "Self-hosted Stremio subtitle resolution, translation, synchronization and ASR fallback engine.", + "type": "module", + "engines": { "node": ">=22" }, + "scripts": { + "start": "node src/index.mjs", + "dev": "node --watch src/index.mjs", + "test": "node --test", + "check": "node tools/check.mjs" + }, + "keywords": ["stremio", "subtitles", "opensubtitles", "translation", "ffsubsync", "whisper"], + "license": "MIT" +} diff --git a/src/app.mjs b/src/app.mjs new file mode 100644 index 0000000..ff87a76 --- /dev/null +++ b/src/app.mjs @@ -0,0 +1,97 @@ +import { buildManifest } from './manifest.mjs'; +import { configurePage } from './configure-page.mjs'; +import { decodePrefs } from './prefs.mjs'; +import { parseExtraSegment, parseVideoId } from './media.mjs'; +import { resolveCandidates } from './providers/index.mjs'; + +function json(res, status, body, headers = {}) { + const payload = JSON.stringify(body); + res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Access-Control-Allow-Origin': '*', ...headers }); + res.end(payload); +} + +function text(res, status, body, contentType = 'text/plain; charset=utf-8') { + res.writeHead(status, { 'Content-Type': contentType, 'Access-Control-Allow-Origin': '*' }); + res.end(body); +} + +function parseSubtitlePath(pathname) { + const parts = pathname.split('/').filter(Boolean); + let configToken = null; + let offset = 0; + if (parts[0] !== 'subtitles') { configToken = parts[0]; offset = 1; } + if (parts[offset] !== 'subtitles' || parts.length < offset + 3) return null; + const type = parts[offset + 1]; + const idPart = parts[offset + 2]; + const id = idPart.replace(/\.json$/i, ''); + const extra = parts[offset + 3] ? parseExtraSegment(parts[offset + 3]) : {}; + return { configToken, type, id, extra }; +} + +export function createApp({ config, providers, translator, pipeline }) { + return async function app(req, res) { + try { + const url = new URL(req.url, config.baseUrl); + if (req.method === 'OPTIONS') return text(res, 204, ''); + if (url.pathname === '/' || url.pathname === '/configure') return text(res, 200, configurePage(config.baseUrl), 'text/html; charset=utf-8'); + if (url.pathname === '/health') { + return json(res, 200, { + ok: true, + providers: Object.fromEntries(providers.map((p) => [p.name, p.enabled])), + translator: translator?.name || null, + mediaAccess: config.media.enabled, + syncEngine: config.media.enabled ? config.media.syncEngine : null, + asr: config.media.enabled && config.media.asrEnabled + }); + } + if (url.pathname === '/manifest.json') return json(res, 200, buildManifest(false), { 'Cache-Control': 'public, max-age=300' }); + const manifestMatch = url.pathname.match(/^\/([^/]+)\/manifest\.json$/); + if (manifestMatch) return json(res, 200, buildManifest(true), { 'Cache-Control': 'public, max-age=300' }); + + const renderMatch = url.pathname.match(/^\/subtitle\/([0-9a-f-]{36})\.srt$/i); + if (renderMatch) { + const subtitle = await pipeline.materialize(renderMatch[1]); + return text(res, 200, subtitle, 'application/x-subrip; charset=utf-8'); + } + + const route = parseSubtitlePath(url.pathname); + if (route && ['movie', 'series'].includes(route.type)) { + const prefs = decodePrefs(route.configToken); + const identity = parseVideoId(route.id); + const media = { ...route.extra, identity }; + const translatorAvailable = Boolean(translator); + const candidates = await resolveCandidates({ + providers, + media, + prefs, + filename: route.extra.filename, + translatorAvailable, + maxResults: config.maxResults + }); + const threshold = Math.max(config.minConfidence, prefs.minConfidence); + const accepted = candidates.filter((candidate) => candidate.confidence >= threshold); + const subtitles = []; + for (const candidate of accepted) { + const id = await pipeline.registerCandidate(candidate, prefs, route.extra.streamUrl); + const outputLang = prefs.translate && candidate.language !== prefs.targetLang ? prefs.targetLang : candidate.language; + const markers = [Math.round(candidate.confidence * 100) + '%', ...(candidate.reasons || []).slice(0, 2)]; + subtitles.push({ + id: `sse-${candidate.providerId}-${markers.join('-')}`, + lang: outputLang, + url: `${config.baseUrl}/subtitle/${id}.srt` + }); + } + if (!subtitles.length && prefs.asr && config.media.enabled && config.media.asrEnabled && route.extra.streamUrl) { + const id = await pipeline.registerAsr(prefs, route.extra.streamUrl); + subtitles.push({ id: 'sse-asr-fallback', lang: prefs.targetLang, url: `${config.baseUrl}/subtitle/${id}.srt` }); + } + return json(res, 200, { subtitles }, { 'Cache-Control': 'public, max-age=300, stale-while-revalidate=300' }); + } + + return json(res, 404, { error: 'not_found' }); + } catch (error) { + console.error('[stremio-sub-engine]', error?.message || error); + return json(res, error?.statusCode || 500, { error: 'subtitle_engine_error', message: error?.message || 'Unknown error' }); + } + }; +} diff --git a/src/asr.mjs b/src/asr.mjs new file mode 100644 index 0000000..ba1a37c --- /dev/null +++ b/src/asr.mjs @@ -0,0 +1,28 @@ +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; + +const execFileAsync = promisify(execFile); + +export async function transcribeStream(mediaConfig, streamUrl) { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'stremio-sub-asr-')); + const output = path.join(dir, 'output.srt'); + try { + await execFileAsync(mediaConfig.pythonCommand, [ + mediaConfig.asrScript, + '--input', streamUrl, + '--output', output, + '--model', mediaConfig.asrModel, + '--device', mediaConfig.asrDevice, + '--compute-type', mediaConfig.asrComputeType + ], { + timeout: mediaConfig.asrTimeoutMs, + maxBuffer: 8 * 1024 * 1024 + }); + return await fs.readFile(output, 'utf8'); + } finally { + await fs.rm(dir, { recursive: true, force: true }).catch(() => {}); + } +} diff --git a/src/cache.mjs b/src/cache.mjs new file mode 100644 index 0000000..5e24489 --- /dev/null +++ b/src/cache.mjs @@ -0,0 +1,66 @@ +import { createHash, randomUUID } from 'node:crypto'; +import fs from 'node:fs/promises'; +import path from 'node:path'; + +async function atomicWrite(file, data) { + await fs.mkdir(path.dirname(file), { recursive: true }); + const temp = `${file}.${process.pid}.${randomUUID()}.tmp`; + await fs.writeFile(temp, data); + await fs.rename(temp, file); +} + +export class DiskCache { + constructor(root, ttlSeconds = 86400) { + this.root = root; + this.ttlMs = ttlSeconds * 1000; + } + key(value) { + return createHash('sha256').update(typeof value === 'string' ? value : JSON.stringify(value)).digest('hex'); + } + file(namespace, key, ext = 'json') { + return path.join(this.root, namespace, `${key}.${ext}`); + } + async getJson(namespace, key) { + try { + const file = this.file(namespace, key); + const stat = await fs.stat(file); + if (Date.now() - stat.mtimeMs > this.ttlMs) return null; + return JSON.parse(await fs.readFile(file, 'utf8')); + } catch { return null; } + } + async setJson(namespace, key, value) { + await atomicWrite(this.file(namespace, key), JSON.stringify(value)); + } + async getText(namespace, key, ext = 'srt') { + try { + const file = this.file(namespace, key, ext); + const stat = await fs.stat(file); + if (Date.now() - stat.mtimeMs > this.ttlMs) return null; + return await fs.readFile(file, 'utf8'); + } catch { return null; } + } + async setText(namespace, key, value, ext = 'srt') { + await atomicWrite(this.file(namespace, key, ext), value); + } +} + +export class JobStore { + constructor(root, ttlSeconds = 21600) { + this.root = path.join(root, 'jobs'); + this.ttlMs = ttlSeconds * 1000; + } + async create(job) { + const id = randomUUID(); + await atomicWrite(path.join(this.root, `${id}.json`), JSON.stringify({ ...job, createdAt: Date.now() })); + return id; + } + async get(id) { + if (!/^[0-9a-f-]{36}$/i.test(id)) return null; + try { + const file = path.join(this.root, `${id}.json`); + const raw = JSON.parse(await fs.readFile(file, 'utf8')); + if (Date.now() - raw.createdAt > this.ttlMs) return null; + return raw; + } catch { return null; } + } +} diff --git a/src/config.mjs b/src/config.mjs new file mode 100644 index 0000000..c6021db --- /dev/null +++ b/src/config.mjs @@ -0,0 +1,55 @@ +import path from 'node:path'; + +function bool(name, fallback = false) { + const value = process.env[name]; + if (value == null) return fallback; + return ['1', 'true', 'yes', 'on'].includes(value.toLowerCase()); +} + +function num(name, fallback) { + const value = Number(process.env[name]); + return Number.isFinite(value) ? value : fallback; +} + +export function loadConfig() { + const port = num('PORT', 7000); + const host = process.env.HOST || '0.0.0.0'; + return { + host, + port, + baseUrl: (process.env.BASE_URL || `http://127.0.0.1:${port}`).replace(/\/$/, ''), + cacheDir: path.resolve(process.env.CACHE_DIR || '.cache'), + cacheTtlSeconds: num('CACHE_TTL_SECONDS', 86400), + maxResults: Math.max(1, Math.min(20, num('MAX_RESULTS', 8))), + minConfidence: Math.max(0, Math.min(1, num('MIN_CONFIDENCE', 0.55))), + opensubtitles: { + apiKey: process.env.OPENSUBTITLES_API_KEY || '', + token: process.env.OPENSUBTITLES_TOKEN || '', + userAgent: process.env.OPENSUBTITLES_USER_AGENT || 'StremioSubEngine v0.1.0', + apiBase: (process.env.OPENSUBTITLES_API_BASE || 'https://api.opensubtitles.com/api/v1').replace(/\/$/, '') + }, + translator: { + provider: (process.env.TRANSLATOR || 'none').toLowerCase(), + libreTranslateUrl: (process.env.LIBRETRANSLATE_URL || 'http://127.0.0.1:5000').replace(/\/$/, ''), + libreTranslateApiKey: process.env.LIBRETRANSLATE_API_KEY || '', + ollamaUrl: (process.env.OLLAMA_URL || 'http://127.0.0.1:11434').replace(/\/$/, ''), + ollamaModel: process.env.OLLAMA_MODEL || 'qwen3:4b', + concurrency: Math.max(1, Math.min(16, num('TRANSLATION_CONCURRENCY', 4))) + }, + media: { + enabled: bool('ENABLE_MEDIA_ACCESS', false), + allowPrivateStreams: bool('ALLOW_PRIVATE_STREAMS', true), + syncEngine: (process.env.SYNC_ENGINE || 'ffsubsync').toLowerCase(), + ffsubsyncCommand: process.env.FFSUBSYNC_COMMAND || 'ffsubsync', + alassCommand: process.env.ALASS_COMMAND || 'alass-cli', + syncTimeoutMs: num('SYNC_TIMEOUT_MS', 180000), + asrEnabled: bool('ENABLE_ASR', false), + pythonCommand: process.env.PYTHON_COMMAND || 'python3', + asrScript: path.resolve(process.env.ASR_SCRIPT || 'tools/asr_faster_whisper.py'), + asrModel: process.env.ASR_MODEL || 'small', + asrDevice: process.env.ASR_DEVICE || 'auto', + asrComputeType: process.env.ASR_COMPUTE_TYPE || 'auto', + asrTimeoutMs: num('ASR_TIMEOUT_MS', 900000) + } + }; +} diff --git a/src/configure-page.mjs b/src/configure-page.mjs new file mode 100644 index 0000000..52830f1 --- /dev/null +++ b/src/configure-page.mjs @@ -0,0 +1,19 @@ +export function configurePage(origin) { + const parsedOrigin = new URL(origin); + const safeOrigin = origin.replace(/ +Stremio Sub Engine + +

Stremio Sub Engine

Configure subtitle resolution. Translation and full media sync still depend on the server capabilities shown at ${safeOrigin}/health.

+ + + + + +

No provider secrets are stored in this URL. API keys and model backends live on the self-hosted server.

+`; +} diff --git a/src/index.mjs b/src/index.mjs new file mode 100644 index 0000000..326ceb3 --- /dev/null +++ b/src/index.mjs @@ -0,0 +1,20 @@ +import http from 'node:http'; +import { loadConfig } from './config.mjs'; +import { DiskCache, JobStore } from './cache.mjs'; +import { createProviders } from './providers/index.mjs'; +import { createTranslator } from './translators/index.mjs'; +import { SubtitlePipeline } from './pipeline.mjs'; +import { createApp } from './app.mjs'; + +const config = loadConfig(); +const cache = new DiskCache(config.cacheDir, config.cacheTtlSeconds); +const jobs = new JobStore(config.cacheDir); +const providers = createProviders(config, cache); +const translator = createTranslator(config.translator); +const pipeline = new SubtitlePipeline({ config, cache, jobs, providers, translator }); +const server = http.createServer(createApp({ config, providers, translator, pipeline })); + +server.listen(config.port, config.host, () => { + console.log(`Stremio Sub Engine listening on ${config.host}:${config.port}`); + console.log(`Manifest: ${config.baseUrl}/manifest.json`); +}); diff --git a/src/languages.mjs b/src/languages.mjs new file mode 100644 index 0000000..c0cb89f --- /dev/null +++ b/src/languages.mjs @@ -0,0 +1,28 @@ +const ISO3_TO_TRANSLATOR = { + por: 'pt', pob: 'pt', eng: 'en', spa: 'es', fra: 'fr', fre: 'fr', deu: 'de', ger: 'de', + ita: 'it', nld: 'nl', dut: 'nl', pol: 'pl', rus: 'ru', ukr: 'uk', jpn: 'ja', kor: 'ko', + zho: 'zh', chi: 'zh', ara: 'ar', hin: 'hi', tur: 'tr' +}; + +const OPENSUBTITLES_TO_ISO3 = { + en: 'eng', es: 'spa', pt: 'por', 'pt-br': 'por', pb: 'por', fr: 'fra', de: 'deu', it: 'ita', + nl: 'nld', pl: 'pol', ru: 'rus', uk: 'ukr', ja: 'jpn', ko: 'kor', zh: 'zho', ar: 'ara', hi: 'hin', tr: 'tur' +}; + +const ISO3_TO_OPENSUBTITLES = { + eng: 'en', spa: 'es', por: 'pt', pob: 'pt-br', fra: 'fr', deu: 'de', ita: 'it', nld: 'nl', + pol: 'pl', rus: 'ru', ukr: 'uk', jpn: 'ja', kor: 'ko', zho: 'zh', ara: 'ar', hin: 'hi', tur: 'tr' +}; + +export function toTranslatorLanguage(code) { + return ISO3_TO_TRANSLATOR[code?.toLowerCase()] || code?.slice(0, 2).toLowerCase() || 'auto'; +} + +export function toOpenSubtitlesLanguage(code) { + return ISO3_TO_OPENSUBTITLES[code?.toLowerCase()] || code?.toLowerCase() || 'en'; +} + +export function fromOpenSubtitlesLanguage(code) { + const normalized = code?.toLowerCase(); + return OPENSUBTITLES_TO_ISO3[normalized] || (normalized?.length === 3 ? normalized : 'und'); +} diff --git a/src/manifest.mjs b/src/manifest.mjs new file mode 100644 index 0000000..4e0098e --- /dev/null +++ b/src/manifest.mjs @@ -0,0 +1,15 @@ +export function buildManifest(configured = false) { + return { + id: 'community.stremio-sub-engine', + version: '0.1.0', + name: configured ? 'Stremio Sub Engine' : 'Stremio Sub Engine (configure)', + description: 'Resolve the correct subtitle for the selected release, translate it, and optionally synchronize/transcribe against the actual stream.', + resources: ['subtitles'], + types: ['movie', 'series'], + idPrefixes: ['tt'], + behaviorHints: { + configurable: true, + configurationRequired: !configured + } + }; +} diff --git a/src/media.mjs b/src/media.mjs new file mode 100644 index 0000000..772429f --- /dev/null +++ b/src/media.mjs @@ -0,0 +1,39 @@ +export function parseVideoId(id) { + const parts = String(id || '').split(':'); + const imdb = /^tt\d+$/.test(parts[0]) ? parts[0] : null; + const season = parts[1] && /^\d+$/.test(parts[1]) ? Number(parts[1]) : null; + const episode = parts[2] && /^\d+$/.test(parts[2]) ? Number(parts[2]) : null; + return { imdb, imdbNumeric: imdb ? Number(imdb.slice(2)) : null, season, episode }; +} + +export function parseExtraSegment(segment = '') { + const cleaned = segment.replace(/\.json$/i, ''); + const params = new URLSearchParams(cleaned); + const videoSize = Number(params.get('videoSize')); + return { + videoHash: params.get('videoHash') || undefined, + videoSize: Number.isFinite(videoSize) && videoSize > 0 ? videoSize : undefined, + filename: params.get('filename') || undefined, + streamUrl: params.get('streamUrl') || undefined + }; +} + +export function releaseTokens(filename = '') { + return new Set(String(filename) + .toLowerCase() + .replace(/\.[a-z0-9]{2,5}$/i, '') + .replace(/[^a-z0-9]+/g, ' ') + .trim() + .split(/\s+/) + .filter((x) => x.length > 1)); +} + +export function releaseSimilarity(a, b) { + const aa = releaseTokens(a); + const bb = releaseTokens(b); + if (!aa.size || !bb.size) return 0; + let intersection = 0; + for (const token of aa) if (bb.has(token)) intersection += 1; + const union = new Set([...aa, ...bb]).size; + return union ? intersection / union : 0; +} diff --git a/src/pipeline.mjs b/src/pipeline.mjs new file mode 100644 index 0000000..e7114f4 --- /dev/null +++ b/src/pipeline.mjs @@ -0,0 +1,70 @@ +import { normalizeToSrt } from './subtitle/format.mjs'; +import { translateSubtitle } from './translators/index.mjs'; +import { downloadCandidate } from './providers/index.mjs'; +import { syncSubtitle } from './sync.mjs'; +import { transcribeStream } from './asr.mjs'; +import { validateStreamUrl } from './security.mjs'; + +export class SubtitlePipeline { + constructor({ config, cache, jobs, providers, translator }) { + this.config = config; + this.cache = cache; + this.jobs = jobs; + this.providers = providers; + this.translator = translator; + this.inflight = new Map(); + } + + async registerCandidate(candidate, prefs, streamUrl) { + return this.jobs.create({ + kind: 'candidate', candidate, prefs, + streamUrl: streamUrl || null, + sync: Boolean(prefs.sync && streamUrl && this.config.media.enabled), + translate: Boolean(prefs.translate && candidate.language !== prefs.targetLang) + }); + } + + async registerAsr(prefs, streamUrl) { + return this.jobs.create({ + kind: 'asr', prefs, streamUrl, + translate: false, + sync: false + }); + } + + async materialize(id) { + const job = await this.jobs.get(id); + if (!job) throw Object.assign(new Error('Subtitle job not found or expired'), { statusCode: 404 }); + const key = this.cache.key(job); + const cached = await this.cache.getText('rendered', key); + if (cached) return cached; + if (this.inflight.has(key)) return this.inflight.get(key); + const promise = this.#materialize(job).then(async (result) => { + await this.cache.setText('rendered', key, result); + return result; + }).finally(() => this.inflight.delete(key)); + this.inflight.set(key, promise); + return promise; + } + + async #materialize(job) { + let subtitle; + if (job.kind === 'asr') { + if (!this.config.media.enabled || !this.config.media.asrEnabled) throw new Error('ASR is disabled on this server'); + const streamUrl = validateStreamUrl(job.streamUrl, this.config.media.allowPrivateStreams); + subtitle = await transcribeStream(this.config.media, streamUrl); + } else { + subtitle = await downloadCandidate(this.providers, job.candidate); + subtitle = normalizeToSrt(subtitle); + if (job.sync) { + const streamUrl = validateStreamUrl(job.streamUrl, this.config.media.allowPrivateStreams); + subtitle = await syncSubtitle(this.config.media, streamUrl, subtitle); + subtitle = normalizeToSrt(subtitle); + } + if (job.translate) { + subtitle = await translateSubtitle(this.translator, subtitle, job.candidate.language, job.prefs.targetLang); + } + } + return normalizeToSrt(subtitle); + } +} diff --git a/src/prefs.mjs b/src/prefs.mjs new file mode 100644 index 0000000..6f7452b --- /dev/null +++ b/src/prefs.mjs @@ -0,0 +1,40 @@ +const DEFAULT_PREFS = Object.freeze({ + targetLang: 'por', + fallbackLangs: ['eng', 'spa'], + translate: true, + sync: true, + asr: true, + minConfidence: 0.55 +}); + +export function normalizePrefs(input = {}) { + const targetLang = /^[a-z]{3}$/i.test(input.targetLang || '') ? input.targetLang.toLowerCase() : DEFAULT_PREFS.targetLang; + const fallbackLangs = Array.isArray(input.fallbackLangs) + ? input.fallbackLangs.filter((x) => /^[a-z]{3}$/i.test(x)).map((x) => x.toLowerCase()).slice(0, 8) + : DEFAULT_PREFS.fallbackLangs; + const minConfidence = Number(input.minConfidence); + return { + targetLang, + fallbackLangs: [...new Set(fallbackLangs.filter((x) => x !== targetLang))], + translate: input.translate !== false, + sync: input.sync !== false, + asr: input.asr !== false, + minConfidence: Number.isFinite(minConfidence) ? Math.max(0, Math.min(1, minConfidence)) : DEFAULT_PREFS.minConfidence + }; +} + +export function encodePrefs(prefs) { + return Buffer.from(JSON.stringify(normalizePrefs(prefs))).toString('base64url'); +} + +export function decodePrefs(token) { + if (!token) return normalizePrefs(); + try { + const parsed = JSON.parse(Buffer.from(token, 'base64url').toString('utf8')); + return normalizePrefs(parsed); + } catch { + return normalizePrefs(); + } +} + +export { DEFAULT_PREFS }; diff --git a/src/providers/index.mjs b/src/providers/index.mjs new file mode 100644 index 0000000..63bdf88 --- /dev/null +++ b/src/providers/index.mjs @@ -0,0 +1,55 @@ +import { OpenSubtitlesProvider } from './opensubtitles.mjs'; +import { rankCandidates } from '../ranking.mjs'; + +function dedupe(candidates) { + const map = new Map(); + for (const candidate of candidates) { + const key = `${candidate.provider}:${candidate.providerId}`; + if (!map.has(key)) map.set(key, candidate); + } + return [...map.values()]; +} + +export function createProviders(config, cache) { + return [new OpenSubtitlesProvider(config.opensubtitles, cache)]; +} + +export async function resolveCandidates({ providers, media, prefs, filename, translatorAvailable, maxResults }) { + const target = [prefs.targetLang]; + const fallback = prefs.translate && translatorAvailable ? prefs.fallbackLangs : []; + const searches = []; + + for (const provider of providers.filter((p) => p.enabled)) { + if (media.videoHash) { + searches.push(provider.search({ languages: target, videoHash: media.videoHash, videoSize: media.videoSize })); + if (fallback.length) searches.push(provider.search({ languages: fallback, videoHash: media.videoHash, videoSize: media.videoSize })); + } + if (media.identity.imdbNumeric) { + searches.push(provider.search({ + languages: target, + imdbNumeric: media.identity.imdbNumeric, + season: media.identity.season, + episode: media.identity.episode + })); + if (fallback.length) searches.push(provider.search({ + languages: fallback, + imdbNumeric: media.identity.imdbNumeric, + season: media.identity.season, + episode: media.identity.episode + })); + } else if (filename) { + searches.push(provider.search({ languages: target, text: filename })); + if (fallback.length) searches.push(provider.search({ languages: fallback, text: filename })); + } + } + + const settled = await Promise.allSettled(searches); + const candidates = dedupe(settled.flatMap((item) => item.status === 'fulfilled' ? item.value : [])); + return rankCandidates(candidates, { filename, targetLang: prefs.targetLang }).slice(0, maxResults); +} + +export async function downloadCandidate(providers, candidate) { + const provider = providers.find((p) => p.name === candidate.provider); + if (!provider) throw new Error(`Provider not available: ${candidate.provider}`); + return provider.download(candidate); +} diff --git a/src/providers/opensubtitles.mjs b/src/providers/opensubtitles.mjs new file mode 100644 index 0000000..97ec4a5 --- /dev/null +++ b/src/providers/opensubtitles.mjs @@ -0,0 +1,83 @@ +import { fromOpenSubtitlesLanguage, toOpenSubtitlesLanguage } from '../languages.mjs'; + +function buildHeaders(config) { + const headers = { + 'Api-Key': config.apiKey, + 'User-Agent': config.userAgent, + 'Content-Type': 'application/json' + }; + if (config.token) headers.Authorization = `Bearer ${config.token}`; + return headers; +} + +export class OpenSubtitlesProvider { + constructor(config, cache) { + this.config = config; + this.cache = cache; + this.name = 'opensubtitles'; + } + get enabled() { return Boolean(this.config.apiKey); } + + async request(pathname, options = {}) { + if (!this.enabled) throw new Error('OpenSubtitles provider is disabled: OPENSUBTITLES_API_KEY is missing'); + const url = `${this.config.apiBase}${pathname}`; + const response = await fetch(url, { ...options, headers: { ...buildHeaders(this.config), ...(options.headers || {}) } }); + if (!response.ok) { + const body = await response.text().catch(() => ''); + throw new Error(`OpenSubtitles ${response.status}: ${body.slice(0, 300)}`); + } + return response.json(); + } + + async search(query) { + if (!this.enabled) return []; + const params = new URLSearchParams(); + if (query.languages?.length) params.set('languages', query.languages.map(toOpenSubtitlesLanguage).join(',')); + if (query.imdbNumeric) params.set('imdb_id', String(query.imdbNumeric)); + if (query.videoHash) params.set('moviehash', query.videoHash); + if (query.videoSize) params.set('moviebytesize', String(query.videoSize)); + if (query.season != null) params.set('season_number', String(query.season)); + if (query.episode != null) params.set('episode_number', String(query.episode)); + if (query.text) params.set('query', query.text); + params.set('order_by', 'download_count'); + params.set('order_direction', 'desc'); + + const cacheKey = this.cache.key(params.toString()); + let body = await this.cache.getJson('search-opensubtitles', cacheKey); + if (!body) { + body = await this.request(`/subtitles?${params.toString()}`); + await this.cache.setJson('search-opensubtitles', cacheKey, body); + } + + return (body.data || []).flatMap((entry) => { + const a = entry.attributes || {}; + const files = Array.isArray(a.files) ? a.files : []; + return files.map((file) => ({ + provider: this.name, + providerId: String(file.file_id), + fileId: file.file_id, + fileName: file.file_name || '', + release: a.release || '', + language: fromOpenSubtitlesLanguage(a.language), + movieHashMatch: Boolean(a.moviehash_match), + imdbMatch: query.imdbNumeric ? Number(a.feature_details?.imdb_id) === Number(query.imdbNumeric) : false, + trusted: Boolean(a.from_trusted), + hearingImpaired: a.hearing_impaired === true, + downloadCount: Number(a.download_count || 0), + fps: a.fps || null, + subtitleId: a.subtitle_id || entry.id + })); + }); + } + + async download(candidate) { + const body = await this.request('/download', { + method: 'POST', + body: JSON.stringify({ file_id: Number(candidate.fileId), sub_format: 'srt' }) + }); + if (!body.link) throw new Error('OpenSubtitles download response did not include a link'); + const response = await fetch(body.link, { redirect: 'follow' }); + if (!response.ok) throw new Error(`Subtitle download failed with HTTP ${response.status}`); + return await response.text(); + } +} diff --git a/src/ranking.mjs b/src/ranking.mjs new file mode 100644 index 0000000..4068ae5 --- /dev/null +++ b/src/ranking.mjs @@ -0,0 +1,33 @@ +import { releaseSimilarity } from './media.mjs'; + +export function scoreCandidate(candidate, context) { + let confidence = 0.18; + const reasons = []; + if (candidate.movieHashMatch) { + confidence += 0.57; + reasons.push('hash'); + } + if (candidate.imdbMatch) { + confidence += 0.12; + reasons.push('id'); + } + const similarity = releaseSimilarity(context.filename, candidate.fileName || candidate.release); + if (similarity > 0) { + confidence += Math.min(0.23, similarity * 0.23); + if (similarity >= 0.5) reasons.push('release'); + } + if (candidate.language === context.targetLang) { + confidence += 0.08; + reasons.push('target-language'); + } + if (candidate.trusted) confidence += 0.04; + if (candidate.hearingImpaired === false) confidence += 0.01; + confidence = Math.max(0, Math.min(1, confidence)); + return { ...candidate, confidence, reasons, similarity }; +} + +export function rankCandidates(candidates, context) { + return candidates + .map((candidate) => scoreCandidate(candidate, context)) + .sort((a, b) => b.confidence - a.confidence || (b.downloadCount || 0) - (a.downloadCount || 0)); +} diff --git a/src/security.mjs b/src/security.mjs new file mode 100644 index 0000000..8978205 --- /dev/null +++ b/src/security.mjs @@ -0,0 +1,23 @@ +import net from 'node:net'; + +function isPrivateIpv4(ip) { + const octets = ip.split('.').map(Number); + if (octets.length !== 4) return false; + return octets[0] === 10 || octets[0] === 127 || + (octets[0] === 192 && octets[1] === 168) || + (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) || + (octets[0] === 169 && octets[1] === 254) || octets[0] === 0; +} + +export function validateStreamUrl(raw, allowPrivate = true) { + const url = new URL(raw); + if (!['http:', 'https:'].includes(url.protocol)) throw new Error('Only http(s) stream URLs are allowed'); + if (url.username || url.password) throw new Error('Credentials in stream URLs are not allowed'); + if (!allowPrivate) { + const host = url.hostname.replace(/^\[|\]$/g, ''); + if (host === 'localhost' || (net.isIP(host) === 4 && isPrivateIpv4(host)) || (net.isIP(host) === 6 && (host === '::1' || host.startsWith('fc') || host.startsWith('fd')))) { + throw new Error('Private/loopback stream URLs are disabled'); + } + } + return url.toString(); +} diff --git a/src/subtitle/format.mjs b/src/subtitle/format.mjs new file mode 100644 index 0000000..98b0c36 --- /dev/null +++ b/src/subtitle/format.mjs @@ -0,0 +1,47 @@ +function normalizeNewlines(text) { + return String(text).replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n'); +} + +function parseTimecode(value) { + const m = value.trim().match(/(?:(\d{1,2}):)?(\d{2}):(\d{2})[,.](\d{3})/); + if (!m) return null; + return (((Number(m[1] || 0) * 60 + Number(m[2])) * 60 + Number(m[3])) * 1000) + Number(m[4]); +} + +function formatTimecode(ms) { + const clamped = Math.max(0, Math.round(ms)); + const h = Math.floor(clamped / 3600000); + const m = Math.floor((clamped % 3600000) / 60000); + const s = Math.floor((clamped % 60000) / 1000); + const milli = clamped % 1000; + return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')},${String(milli).padStart(3, '0')}`; +} + +export function parseSubtitle(text) { + const normalized = normalizeNewlines(text).replace(/^WEBVTT[^\n]*\n+/, ''); + const blocks = normalized.split(/\n{2,}/).map((x) => x.trim()).filter(Boolean); + const cues = []; + for (const block of blocks) { + const lines = block.split('\n'); + const timelineIndex = lines.findIndex((line) => line.includes('-->')); + if (timelineIndex < 0) continue; + const [rawStart, rawEnd] = lines[timelineIndex].split('-->').map((x) => x.trim()); + const start = parseTimecode(rawStart); + const end = parseTimecode(rawEnd.split(/\s+/)[0]); + if (start == null || end == null) continue; + const body = lines.slice(timelineIndex + 1).join('\n').trim(); + if (!body) continue; + cues.push({ start, end, text: body }); + } + return cues; +} + +export function renderSrt(cues) { + return cues.map((cue, index) => `${index + 1}\n${formatTimecode(cue.start)} --> ${formatTimecode(cue.end)}\n${cue.text.trim()}\n`).join('\n'); +} + +export function normalizeToSrt(text) { + const cues = parseSubtitle(text); + if (!cues.length) throw new Error('No subtitle cues could be parsed'); + return renderSrt(cues); +} diff --git a/src/sync.mjs b/src/sync.mjs new file mode 100644 index 0000000..806d3e7 --- /dev/null +++ b/src/sync.mjs @@ -0,0 +1,34 @@ +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import fs from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; + +const execFileAsync = promisify(execFile); + +export async function syncSubtitle(mediaConfig, streamUrl, subtitle) { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'stremio-sub-sync-')); + const input = path.join(dir, 'input.srt'); + const output = path.join(dir, 'output.srt'); + try { + await fs.writeFile(input, subtitle, 'utf8'); + if (mediaConfig.syncEngine === 'alass') { + await execFileAsync(mediaConfig.alassCommand, [streamUrl, input, output], { + timeout: mediaConfig.syncTimeoutMs, + maxBuffer: 4 * 1024 * 1024 + }); + } else { + await execFileAsync(mediaConfig.ffsubsyncCommand, [ + streamUrl, '-i', input, '-o', output, + '--multi-segment-sync', '--segment-count', '6', '--skip-intro-outro', '--parallel-workers', '4', + '--skip-sync-on-low-quality' + ], { + timeout: mediaConfig.syncTimeoutMs, + maxBuffer: 4 * 1024 * 1024 + }); + } + return await fs.readFile(output, 'utf8'); + } finally { + await fs.rm(dir, { recursive: true, force: true }).catch(() => {}); + } +} diff --git a/src/translators/index.mjs b/src/translators/index.mjs new file mode 100644 index 0000000..7fb7455 --- /dev/null +++ b/src/translators/index.mjs @@ -0,0 +1,17 @@ +import { parseSubtitle, renderSrt } from '../subtitle/format.mjs'; +import { LibreTranslateTranslator } from './libretranslate.mjs'; +import { OllamaTranslator } from './ollama.mjs'; + +export function createTranslator(config) { + if (config.provider === 'libretranslate') return new LibreTranslateTranslator(config); + if (config.provider === 'ollama') return new OllamaTranslator(config); + return null; +} + +export async function translateSubtitle(translator, subtitle, source, target) { + if (!translator) throw new Error('Translation requested but no translator is configured'); + const cues = parseSubtitle(subtitle); + if (!cues.length) throw new Error('Subtitle has no parseable cues'); + const translated = await translator.translateTexts(cues.map((cue) => cue.text), source, target); + return renderSrt(cues.map((cue, index) => ({ ...cue, text: translated[index] }))); +} diff --git a/src/translators/libretranslate.mjs b/src/translators/libretranslate.mjs new file mode 100644 index 0000000..a09fd46 --- /dev/null +++ b/src/translators/libretranslate.mjs @@ -0,0 +1,40 @@ +import { toTranslatorLanguage } from '../languages.mjs'; + +async function mapLimit(items, limit, worker) { + const results = new Array(items.length); + let index = 0; + const runners = Array.from({ length: Math.min(limit, items.length) }, async () => { + while (true) { + const current = index++; + if (current >= items.length) break; + results[current] = await worker(items[current], current); + } + }); + await Promise.all(runners); + return results; +} + +export class LibreTranslateTranslator { + constructor(config) { this.config = config; this.name = 'libretranslate'; } + get enabled() { return true; } + async translateTexts(texts, source, target) { + const targetCode = toTranslatorLanguage(target); + const sourceCode = source && source !== 'und' ? toTranslatorLanguage(source) : 'auto'; + return mapLimit(texts, this.config.concurrency, async (text) => { + const response = await fetch(`${this.config.libreTranslateUrl}/translate`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + q: text, + source: sourceCode, + target: targetCode, + format: 'text', + ...(this.config.libreTranslateApiKey ? { api_key: this.config.libreTranslateApiKey } : {}) + }) + }); + if (!response.ok) throw new Error(`LibreTranslate ${response.status}: ${(await response.text()).slice(0, 200)}`); + const body = await response.json(); + return body.translatedText; + }); + } +} diff --git a/src/translators/ollama.mjs b/src/translators/ollama.mjs new file mode 100644 index 0000000..baafb83 --- /dev/null +++ b/src/translators/ollama.mjs @@ -0,0 +1,39 @@ +import { toTranslatorLanguage } from '../languages.mjs'; + +export class OllamaTranslator { + constructor(config) { this.config = config; this.name = 'ollama'; } + get enabled() { return Boolean(this.config.ollamaModel); } + + async translateTexts(texts, source, target) { + const out = []; + const batchSize = 36; + for (let i = 0; i < texts.length; i += batchSize) { + const batch = texts.slice(i, i + batchSize); + const response = await fetch(`${this.config.ollamaUrl}/api/chat`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + model: this.config.ollamaModel, + stream: false, + format: 'json', + options: { temperature: 0 }, + messages: [ + { + role: 'system', + content: `Translate subtitle cue text from ${toTranslatorLanguage(source)} to ${toTranslatorLanguage(target)}. Preserve HTML/ASS tags, line breaks, punctuation and speaker markers. Never merge, split, reorder, censor, summarize or explain cues. Return exactly JSON: {"translations":[...]} with the same number of strings as the input.` + }, + { role: 'user', content: JSON.stringify({ cues: batch }) } + ] + }) + }); + if (!response.ok) throw new Error(`Ollama ${response.status}: ${(await response.text()).slice(0, 200)}`); + const body = await response.json(); + const parsed = JSON.parse(body.message?.content || '{}'); + if (!Array.isArray(parsed.translations) || parsed.translations.length !== batch.length) { + throw new Error('Ollama returned an invalid translation batch'); + } + out.push(...parsed.translations.map(String)); + } + return out; + } +} diff --git a/test/app.test.mjs b/test/app.test.mjs new file mode 100644 index 0000000..cb09c5f --- /dev/null +++ b/test/app.test.mjs @@ -0,0 +1,64 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import { createApp } from '../src/app.mjs'; + +async function withServer(handler, fn) { + const server = http.createServer(handler); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + try { return await fn(`http://127.0.0.1:${server.address().port}`); } + finally { await new Promise((resolve) => server.close(resolve)); } +} + +test('serves manifest and health', async () => { + const config = { + baseUrl: 'http://127.0.0.1:7000', maxResults: 8, minConfidence: 0.55, + media: { enabled: false, asrEnabled: false, syncEngine: 'ffsubsync' } + }; + const handler = createApp({ config, providers: [{ name: 'mock', enabled: true }], translator: null, pipeline: {} }); + await withServer(handler, async (base) => { + const manifest = await (await fetch(`${base}/manifest.json`)).json(); + assert.equal(manifest.resources[0], 'subtitles'); + const health = await (await fetch(`${base}/health`)).json(); + assert.equal(health.providers.mock, true); + }); +}); + +test('serves configure page with an install link script', async () => { + const config = { + baseUrl: 'http://127.0.0.1:7000', maxResults: 8, minConfidence: 0.55, + media: { enabled: false, asrEnabled: false, syncEngine: 'ffsubsync' } + }; + const handler = createApp({ config, providers: [], translator: null, pipeline: {} }); + await withServer(handler, async (base) => { + const response = await fetch(`${base}/configure`); + const html = await response.text(); + assert.equal(response.status, 200); + assert.match(html, /stremio:\/\//); + assert.match(html, /Install in Stremio/); + }); +}); + +test('resolves a Stremio subtitle request and returns opaque subtitle URL', async () => { + const config = { + baseUrl: 'http://127.0.0.1:7000', maxResults: 8, minConfidence: 0.55, + media: { enabled: false, asrEnabled: false, syncEngine: 'ffsubsync' } + }; + const provider = { + name: 'mock', enabled: true, + async search(query) { + return [{ provider: 'mock', providerId: '42', fileId: 42, fileName: 'Movie.2026.1080p.WEB-DL.srt', release: 'Movie.2026.1080p.WEB-DL', language: 'por', movieHashMatch: Boolean(query.videoHash), imdbMatch: Boolean(query.imdbNumeric), trusted: true, hearingImpaired: false, downloadCount: 100 }]; + } + }; + const pipeline = { async registerCandidate() { return '123e4567-e89b-12d3-a456-426614174000'; } }; + const handler = createApp({ config, providers: [provider], translator: null, pipeline }); + await withServer(handler, async (base) => { + const response = await fetch(`${base}/subtitles/movie/tt1234567/videoHash=abc&videoSize=123&filename=Movie.2026.1080p.WEB-DL.mkv.json`); + const body = await response.json(); + assert.equal(response.status, 200); + assert.equal(body.subtitles.length, 1); + assert.equal(body.subtitles[0].lang, 'por'); + assert.equal(body.subtitles[0].url, 'http://127.0.0.1:7000/subtitle/123e4567-e89b-12d3-a456-426614174000.srt'); + assert.ok(!body.subtitles[0].url.includes('videoHash')); + }); +}); diff --git a/test/format.test.mjs b/test/format.test.mjs new file mode 100644 index 0000000..1b7a3e4 --- /dev/null +++ b/test/format.test.mjs @@ -0,0 +1,15 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { parseSubtitle, renderSrt, normalizeToSrt } from '../src/subtitle/format.mjs'; + +test('parses SRT and preserves multiline text', () => { + const cues = parseSubtitle('1\n00:00:01,000 --> 00:00:02,500\nHello\nworld\n\n2\n00:00:03.000 --> 00:00:04.000\nBye'); + assert.equal(cues.length, 2); + assert.equal(cues[0].text, 'Hello\nworld'); + assert.match(renderSrt(cues), /00:00:01,000 --> 00:00:02,500/); +}); + +test('normalizes WebVTT to SRT', () => { + const out = normalizeToSrt('WEBVTT\n\n00:01.000 --> 00:02.000\nOi'); + assert.match(out, /^1\n00:00:01,000 --> 00:00:02,000/m); +}); diff --git a/test/media.test.mjs b/test/media.test.mjs new file mode 100644 index 0000000..fa1f704 --- /dev/null +++ b/test/media.test.mjs @@ -0,0 +1,18 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { parseVideoId, parseExtraSegment, releaseSimilarity } from '../src/media.mjs'; + +test('parses series video ids', () => { + assert.deepEqual(parseVideoId('tt1234567:2:8'), { imdb: 'tt1234567', imdbNumeric: 1234567, season: 2, episode: 8 }); +}); + +test('parses Stremio subtitle extras', () => { + const extra = parseExtraSegment('videoHash=abc&videoSize=123&filename=Movie.mkv.json'); + assert.equal(extra.videoHash, 'abc'); + assert.equal(extra.videoSize, 123); + assert.equal(extra.filename, 'Movie.mkv'); +}); + +test('release similarity identifies same release', () => { + assert.ok(releaseSimilarity('Movie.2026.1080p.WEB-DL-GROUP.mkv', 'Movie.2026.1080p.WEB-DL-GROUP.srt') > 0.7); +}); diff --git a/test/prefs.test.mjs b/test/prefs.test.mjs new file mode 100644 index 0000000..5a02e96 --- /dev/null +++ b/test/prefs.test.mjs @@ -0,0 +1,11 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { encodePrefs, decodePrefs } from '../src/prefs.mjs'; + +test('prefs round-trip', () => { + const token = encodePrefs({ targetLang: 'eng', translate: false, sync: false, asr: false, minConfidence: 0.8 }); + const prefs = decodePrefs(token); + assert.equal(prefs.targetLang, 'eng'); + assert.equal(prefs.translate, false); + assert.equal(prefs.minConfidence, 0.8); +}); diff --git a/test/ranking.test.mjs b/test/ranking.test.mjs new file mode 100644 index 0000000..f4bc551 --- /dev/null +++ b/test/ranking.test.mjs @@ -0,0 +1,12 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { rankCandidates } from '../src/ranking.mjs'; + +test('exact hash beats filename-only candidate', () => { + const ranked = rankCandidates([ + { provider: 'x', providerId: '1', language: 'por', fileName: 'Movie.2026.WEB-DL.srt', movieHashMatch: false, imdbMatch: true }, + { provider: 'x', providerId: '2', language: 'eng', fileName: 'Other.srt', movieHashMatch: true, imdbMatch: true } + ], { filename: 'Movie.2026.WEB-DL.mkv', targetLang: 'por' }); + assert.equal(ranked[0].providerId, '2'); + assert.ok(ranked[0].confidence > 0.8); +}); diff --git a/tools/asr_faster_whisper.py b/tools/asr_faster_whisper.py new file mode 100644 index 0000000..70e1b0d --- /dev/null +++ b/tools/asr_faster_whisper.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python3 +import argparse +from faster_whisper import WhisperModel + + +def ts(seconds: float) -> str: + total = max(0, int(round(seconds * 1000))) + h, rem = divmod(total, 3600000) + m, rem = divmod(rem, 60000) + s, ms = divmod(rem, 1000) + return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}" + + +def main(): + p = argparse.ArgumentParser() + p.add_argument('--input', required=True) + p.add_argument('--output', required=True) + p.add_argument('--model', default='small') + p.add_argument('--device', default='auto') + p.add_argument('--compute-type', default='auto') + p.add_argument('--language', default=None) + args = p.parse_args() + + model = WhisperModel(args.model, device=args.device, compute_type=args.compute_type) + segments, _ = model.transcribe(args.input, language=args.language, vad_filter=True, beam_size=5) + with open(args.output, 'w', encoding='utf-8') as f: + for i, segment in enumerate(segments, 1): + text = segment.text.strip() + if not text: + continue + f.write(f"{i}\n{ts(segment.start)} --> {ts(segment.end)}\n{text}\n\n") + + +if __name__ == '__main__': + main() diff --git a/tools/check.mjs b/tools/check.mjs new file mode 100644 index 0000000..9594e84 --- /dev/null +++ b/tools/check.mjs @@ -0,0 +1,15 @@ +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; + +async function walk(dir) { + const out = []; + for (const entry of await fs.readdir(dir, { withFileTypes: true })) { + const p = path.join(dir, entry.name); + if (entry.isDirectory()) out.push(...await walk(p)); + else if (entry.name.endsWith('.mjs') && entry.name !== 'index.mjs') out.push(p); + } + return out; +} +for (const file of await walk(path.resolve('src'))) await import(pathToFileURL(file)); +console.log('Imported all source modules successfully.');