import os, subprocess, shutil, json, re, orjson, requests from pathlib import Path from faster_whisper import WhisperModel MEILI_URL = os.getenv("MEILI_URL", "http://meili:7700") MEILI_KEY = os.getenv("MEILI_KEY", "") LIB = Path(os.getenv("LIBRARY_ROOT", "/library")) TRN = Path(os.getenv("TRANSCRIPT_ROOT", "/transcripts")) TMP = Path(os.getenv("TMP_ROOT", "/tmpdl")) MODEL_NAME = os.getenv("WHISPER_MODEL","large-v3") COMPUTE = os.getenv("WHISPER_PRECISION","int8") OWUI_URL = os.getenv("OPENWEBUI_URL", "").rstrip("/") OWUI_KEY = os.getenv("OPENWEBUI_API_KEY", "") OWUI_KB = os.getenv("OPENWEBUI_KB_NAME", "Homelab Library") TRN.mkdir(parents=True, exist_ok=True) LIB.mkdir(parents=True, exist_ok=True) TMP.mkdir(parents=True, exist_ok=True) # Lazy Whisper model loader so the worker can start even if model download/setup is slow _model = None def get_model(): global _model if _model is None: _model = WhisperModel(MODEL_NAME, compute_type=COMPUTE) return _model def log(feed): try: with open(TRN / "_feed.log", "a", encoding="utf-8") as f: f.write(orjson.dumps(feed).decode()+"\n") except Exception: pass def sanitize(name): return re.sub(r'[\\/:"*?<>|]+', ' ', name).strip() def yt_dlp(url, outdir): # 1) Normalize YouTube Music URLs to standard YouTube yurl = url if 'music.youtube.com' in yurl: yurl = yurl.replace('music.youtube.com', 'www.youtube.com') outtmpl = str(outdir / "%(uploader)s/%(upload_date)s - %(title)s.%(ext)s") base_cmd = [ "yt-dlp", "-o", outtmpl, "-f", "bv*+ba/best", "-x", "--audio-format", "m4a", "--write-thumbnail", "--no-playlist", "--no-warnings", "--restrict-filenames", ] # 3) Optional cookies (set YTDLP_COOKIES=/path/to/cookies.txt in .env and mount it) cookies_path = os.getenv("YTDLP_COOKIES", "").strip() if cookies_path: base_cmd += ["--cookies", cookies_path] # Primary attempt try: subprocess.check_call(base_cmd + [yurl]) except subprocess.CalledProcessError: # 2) Retry with Android client + mobile UA retry_cmd = base_cmd + [ "--extractor-args", "youtube:player_client=android", "--user-agent", "Mozilla/5.0 (Linux; Android 10; SM-G973F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0 Mobile Safari/537.36", yurl, ] subprocess.check_call(retry_cmd) media = (list(outdir.rglob("*.[mM][pP]4")) + list(outdir.rglob("*.mkv")) + list(outdir.rglob("*.m4a")) + list(outdir.rglob("*.mp3"))) return sorted(media, key=lambda p: p.stat().st_mtime)[-1:] def transcribe(media_path: Path): model = get_model() segments, info = model.transcribe(str(media_path), vad_filter=True, language="auto") title = media_path.stem base = TRN / title segs, text_parts = [], [] for s in segments: segs.append({"start": s.start, "end": s.end, "text": s.text}) text_parts.append(s.text) txt = " ".join(text_parts).strip() open(base.with_suffix(".json"), "wb").write(orjson.dumps({"file": str(media_path), "language": info.language, "segments": segs})) open(base.with_suffix(".txt"), "w", encoding="utf-8").write(txt) def fmt_ts(t): h=int(t//3600); m=int((t%3600)//60); s=t-(h*3600+m*60) return f"{h:02}:{m:02}:{s:06.3f}".replace('.',',') with open(base.with_suffix(".srt"), "w", encoding="utf-8") as srt: for i,s in enumerate(segs,1): srt.write(f"{i}\n{fmt_ts(s['start'])} --> {fmt_ts(s['end'])}\n{s['text'].strip()}\n\n") with open(base.with_suffix(".vtt"), "w", encoding="utf-8") as vtt: vtt.write("WEBVTT\n\n") for s in segs: vtt.write(f"{fmt_ts(s['start']).replace(',', '.')} --> {fmt_ts(s['end']).replace(',', '.')} \n{s['text'].strip()}\n\n") return base def index_meili(json_path: Path): doc = json.loads(open(json_path, "r", encoding="utf-8").read()) title = Path(doc["file"]).stem date = re.findall(r"\b(\d{8})\b", title) payload = { "id": title, "type": "podcast", "title": title, "date": date[0] if date else "", "source": str(Path(LIB, Path(doc["file"]).name)), "text": " ".join(s["text"] for s in doc.get("segments", [])), "segments": doc.get("segments", []), "meta": {"language": doc.get("language", "")} } import time for attempt in range(5): try: r = requests.post( f"{MEILI_URL}/indexes/library/documents", headers={"Authorization": f"Bearer {MEILI_KEY}", "Content-Type":"application/json"}, data=orjson.dumps(payload), timeout=15, ) r.raise_for_status() break except Exception: if attempt == 4: raise time.sleep(2 * (attempt + 1)) import tldextract, trafilatura, requests as _requests def slugify(text): text = re.sub(r'[^A-Za-z0-9\-._ ]+', '', text).strip().replace(' ', '_') return text[:120] or 'page' def save_web_snapshot(url: str): r = _requests.get(url, timeout=30, headers={"User-Agent":"Mozilla/5.0"}) r.raise_for_status() html = r.text downloaded = trafilatura.load_html(html, url=url) text = trafilatura.extract(downloaded, include_comments=False, include_images=False, with_metadata=True) or "" meta = trafilatura.metadata.extract_metadata(downloaded) or None title = (meta.title if meta and getattr(meta, 'title', None) else None) or (re.search(r'