about summary refs log tree commit diff
path: root/users/Profpatsch/lyric/lyric-mpv-script.lua
blob: ba05c7c449f648d14b38d78ae98dff46d74ea7b5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
-- get_lrc_subtitles.lua

-- Function to remove Unicode symbol characters
function remove_symbols(str)
    -- This pattern matches anything that is not a letter, digit, or whitespace
    return str:gsub("[%p%c%z]", "") -- remove punctuation, control, and zero-width characters
end

-- Asynchronous callback function to handle the result of the 'get_subtitles' command
function handle_subtitle_result(success, result)
    if not success or result.status ~= 0 then
        mp.msg.error("Failed to get subtitles")
        mp.msg.error("Exit code: " .. tostring(result.exit_code))
        if result.stderr then
            mp.msg.error("Error: " .. result.stderr)
        end
        return
    end

    -- Extract the output from the external command
    local subtitle_file = result.stdout:match("^%s*(.-)%s*$")  -- trim any extra whitespace

    -- If no subtitle file was returned, stop
    if not subtitle_file or subtitle_file == "" then
        mp.msg.warn("No subtitle file found")
        return
    end

    -- Load the subtitle file in MPV
    mp.commandv("sub-add", subtitle_file)
    mp.msg.info("Loaded subtitle file: " .. subtitle_file)
end

-- Function to load the LRC subtitle file
function load_lrc_subtitles()
    -- Retrieve metadata for the currently playing file
    local artist = mp.get_property("metadata/by-key/artist")
    local album = mp.get_property("metadata/by-key/album")
    local title = mp.get_property("metadata/by-key/title")

    -- If any metadata is missing, print a warning and stop
    if not artist or not album or not title then
        mp.msg.warn("Artist, album, or title metadata is missing")
        return
    end

    -- Concatenate the metadata
    local query = string.format("%s %s %s", artist, album, title)

    -- Remove Unicode symbols from the query string
    query = remove_symbols(query)

    -- Create the command array
    local cmd = {"@get_subtitles_command@", query}

    -- Run the external command asynchronously to get the subtitle file
    mp.command_native_async({
        name = "subprocess",
        args = cmd,
        capture_stdout = true,
        capture_stderr = true
    }, handle_subtitle_result)
end

-- Register the event that triggers when a file is loaded
mp.register_event("file-loaded", load_lrc_subtitles)