This repository has no description
3.6 kB
101 lines
1{ self, ... }:
2{
3 perSystem =
4 { pkgs, ... }:
5 {
6 packages.mpv =
7 let
8 # Lazy-loaded autosub script
9 autosub = pkgs.writeText "autosub.lua" ''
10 utils = require 'mp.utils'
11
12 -- Log function: log to both terminal and mpv OSD (On-Screen Display)
13 function log(string, secs)
14 secs = secs or 2 -- secs defaults to 2 when the secs parameter is absent
15 mp.msg.warn(string) -- This logs to the terminal
16 mp.osd_message(string, secs) -- This logs to mpv screen
17 end
18
19 function download()
20 log('Searching subtitles ...', 10)
21 path = mp.get_property('path')
22
23 -- Build dl_subs lazily when needed
24 log('Building subtitle downloader...', 5)
25 result = utils.subprocess({ args = {"nix", "build", "--no-link", "--print-out-paths", "${self}#mpv-dl-subs"} })
26 if result.error ~= nil then
27 log('Failed to build subtitle downloader')
28 return
29 end
30
31 dl_subs_path = string.gsub(result.stdout, "\n", "") .. "/bin/dl_subs"
32
33 -- Download subtitles
34 result = utils.subprocess({ args = {dl_subs_path, path} })
35 if result.error == nil then
36 filename = string.gsub(result.stdout, "\n", "")
37 log(filename)
38 mp.commandv('sub_add', filename)
39 log('Subtitles ready!')
40 else
41 log('Subtitles failed downloading')
42 end
43 end
44
45 mp.add_key_binding('S', "download_subs", download)
46 '';
47
48 in
49 self.wrapperModules.mpv.apply {
50 pkgs = pkgs;
51 scripts = with pkgs.mpvScripts; [
52 sponsorblock
53 quality-menu
54 vr-reversal
55 visualizer
56 ];
57 extraFlags = {
58 "--ytdl-format" = "best[height<1081]";
59 "--script-opts" = "ytdl_hook-ytdl_path=${pkgs.yt-dlp}/bin/yt-dlp";
60 "--script-opts-append" = "sponsorblock-local_database=no";
61 "--audio-channels" = "2";
62 "--script" = autosub;
63 };
64 "mpv.input".content = ''
65 : script-binding console/enable
66 x add audio-delay -0.050
67 X add audio-delay 0.050
68 F script-binding quality_menu/video_formats_toggle
69 Alt+f script-binding quality_menu/audio_formats_toggle
70 '';
71 "mpv.conf".content = ''
72 osd-font-size=20
73 '';
74 };
75
76 # Separate package for subtitle downloader
77 packages.mpv-dl-subs =
78 pkgs.writers.writePython3Bin "dl_subs"
79 {
80 libraries = [ pkgs.python3Packages.subliminal ];
81 flakeIgnore = [ "E501" ];
82 }
83 ''
84 import babelfish
85 import subliminal
86 from pathlib import Path
87 import sys
88 import os
89
90 video_path = Path(sys.argv[1])
91 video = subliminal.scan_video(video_path)
92 cache_path = Path(os.path.expanduser("~/.cache/subliminal")) / f"{video.title}.srt"
93 if not cache_path.exists():
94 cache_path.parent.mkdir(parents=True, exist_ok=True)
95 language = babelfish.Language("eng")
96 sub = subliminal.download_best_subtitles([video], {language})[video][0]
97 cache_path.write_bytes(sub.content)
98 print(cache_path)
99 '';
100 };
101}