Advertisement
Guest User

Untitled

a guest
Oct 9th, 2020
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.34 KB | None | 0 0
  1. -- -- Open clipboard inserter
  2. -- -- Wait for unknown word and add it to anki through yomichan
  3. -- -- Select all the subtitle lines to add to the card.
  4. -- -- Ctrl + c
  5. -- -- Tab back to MPV and Ctrl + v
  6. -- -- Done. The lines, their respective Audio and the current paused image
  7. -- -- will be added to the back of the card.
  8. -- -- Ctrl + t will toggle clipboard inserter on and off.
  9.  
  10. local utils = require 'mp.utils'
  11. local msg = require 'mp.msg'
  12. local subs = {}
  13. local enable_subs_to_clip = true
  14. local use_powershell_clipboard = nil
  15.  
  16. ------------- User Config -------------
  17. -- Set these to match your field names in Anki
  18. local FRONT_FIELD = "Front"
  19. local SENTENCE_AUDIO_FIELD = "Sentence-Audio"
  20. local SENTENCE_FIELD = "Sentence"
  21. local IMAGE_FIELD = "Image"
  22. -- Anki collection media path. Ensure Anki username is correct.
  23. local prefix = utils.join_path(os.getenv('APPDATA'), [[Anki2\User 1\collection.media]])
  24. -- Optional padding and fade settings in seconds
  25. local AUDIO_CLIP_FADE = 0.2
  26. local AUDIO_CLIP_PADDING = 0.75
  27. ---------------------------------------
  28.  
  29. local function clean(s)
  30. local newtext = string.gsub(s, "\n", "")
  31. newtext = string.gsub(newtext, "\r", "")
  32. return string.gsub(newtext, "^%s*(.-)%s*$", "%1")
  33. end
  34.  
  35. local function get_name(s, e)
  36. return mp.get_property("filename"):gsub('%W','').. tostring(s) .. tostring(e)
  37. end
  38.  
  39. local function get_clipboard()
  40. local res = utils.subprocess({ args = {
  41. 'powershell', '-NoProfile', '-Command', [[& {
  42. Trap {
  43. Write-Error -ErrorRecord $_
  44. Exit 1
  45. }
  46. $clip = ""
  47. if (Get-Command "Get-Clipboard" -errorAction SilentlyContinue) {
  48. $clip = Get-Clipboard -Raw -Format Text -TextFormatType UnicodeText
  49. } else {
  50. Add-Type -AssemblyName PresentationCore
  51. $clip = [Windows.Clipboard]::GetText()
  52. }
  53. $clip = $clip -Replace "`r",""
  54. $u8clip = [System.Text.Encoding]::UTF8.GetBytes($clip)
  55. [Console]::OpenStandardOutput().Write($u8clip, 0, $u8clip.Length)
  56. }]]
  57. } })
  58. if not res.error then
  59. return res.stdout
  60. end
  61. end
  62.  
  63. local function powershell_set_clipboard(text)
  64. utils.subprocess({ args = {
  65. 'powershell', '-NoProfile', '-Command', [[Set-Clipboard -Value @"]] .. "\n" .. text .. "\n" .. [["@]]
  66. }})
  67. end
  68.  
  69. local function cmd_set_clipboard(text)
  70. local cmd = 'echo ' .. text .. ' | clip';
  71. mp.command("run cmd /D /C " .. cmd);
  72. end
  73.  
  74. local function determine_clip_type()
  75. powershell_set_clipboard([[Anacreon様]])
  76. use_powershell_clipboard = get_clipboard() == [[Anacreon様]]
  77. end
  78.  
  79. local function record_sub(name, text)
  80. if text and mp.get_property_number('sub-start') and mp.get_property_number('sub-end') then
  81. local sub_delay = mp.get_property_native("sub-delay")
  82. local newtext = clean(text)
  83. if newtext == '' then
  84. return
  85. end
  86.  
  87. subs[newtext] = { mp.get_property_number('sub-start') + sub_delay, mp.get_property_number('sub-end') + sub_delay }
  88. if enable_subs_to_clip then
  89. if use_powershell_clipboard == nil then
  90. determine_clip_type()
  91. end
  92. if use_powershell_clipboard then
  93. powershell_set_clipboard(newtext)
  94. else
  95. cmd_set_clipboard(newtext)
  96. end
  97. end
  98. end
  99. end
  100.  
  101. local function create_audio(s, e)
  102.  
  103. if s == nil or e == nil then
  104. return
  105. end
  106.  
  107. local name = get_name(s, e)
  108. s = s - AUDIO_CLIP_PADDING
  109. local t = e - s + AUDIO_CLIP_PADDING
  110. local source = mp.get_property("path")
  111. local destination = utils.join_path(prefix, name .. '.mp3')
  112. mp.commandv(
  113. 'run',
  114. 'mpv',
  115. source,
  116. '--loop-file=no',
  117. '--video=no',
  118. '--no-ocopy-metadata',
  119. '--no-sub',
  120. '--audio-channels=1',
  121. string.format('--start=%.3f', s),
  122. string.format('--length=%.3f', t),
  123. string.format('--aid=%s', mp.get_property("aid")),
  124. string.format("--af-append=afade=t=in:curve=ipar:st=%.3f:d=%.3f", s, AUDIO_CLIP_FADE),
  125. string.format("--af-append=afade=t=out:curve=ipar:st=%.3f:d=%.3f", s + t - AUDIO_CLIP_FADE, AUDIO_CLIP_FADE),
  126. string.format('-o=%s', destination)
  127. )
  128. end
  129.  
  130. local function create_screenshot(s, e)
  131. local source = mp.get_property("path")
  132. local img = utils.join_path(prefix, get_name(s,e) .. '.webp')
  133. mp.commandv(
  134. 'run',
  135. 'mpv',
  136. source,
  137. '--loop-file=no',
  138. '--audio=no',
  139. '--no-ocopy-metadata',
  140. '--no-sub',
  141. '--frames=1',
  142. '--ovc=libwebp',
  143. '--ovcopts-add=lossless=0',
  144. '--ovcopts-add=compression_level=6',
  145. '--ovcopts-add=preset=drawing',
  146. '--vf-add=scale=-2:480',
  147. string.format('--start=%.3f', mp.get_property_number("time-pos")),
  148. string.format('-o=%s', img)
  149. )
  150. end
  151.  
  152. local function get(request)
  153. local args = {
  154. 'powershell', '-NoProfile', '-Command', [[& {
  155. $data = Invoke-RestMethod -Uri http://127.0.0.1:8765 -Method Post -ContentType 'application/json; charset=UTF-8' -Body @"]] .. "\n" .. request .. "\n" .. [["@ | ConvertTo-Json -Depth 10
  156. $u8data = [System.Text.Encoding]::UTF8.GetBytes($data)
  157. [Console]::OpenStandardOutput().Write($u8data, 0, $u8data.Length)
  158. }]]
  159. }
  160.  
  161. local result = utils.subprocess({ args = args, cancellable = true, capture_stderr = true })
  162. print(result.stdout)
  163. print(result.stderr)
  164. return utils.parse_json(result.stdout)
  165. end
  166.  
  167. local function add_to_last_added(ifield, afield, tfield)
  168. local noteid = math.max(unpack(get('{"action": "findNotes", "params": {"query": "added:1"}, "version": 6}')["result"]))
  169. local note = get('{"action": "notesInfo", "params": {"notes": ['.. noteid.. ']}, "version": 6}')
  170.  
  171. ifield = string.gsub(ifield, "\"", "\\\"")
  172. afield = string.gsub(afield, "\"", "\\\"")
  173. tfield = string.gsub(tfield, "\"", "\\\"")
  174.  
  175. if note ~= nil then
  176. get('{"action": "updateNoteFields", "version": 6, "params": {"note": {"id": ' .. noteid.. ', "fields": {"' .. SENTENCE_AUDIO_FIELD .. '": "' .. afield .. '","' .. SENTENCE_FIELD .. '": "' .. tfield .. '","' .. IMAGE_FIELD .. '": "' .. ifield .. '"} } } }')
  177.  
  178. mp.osd_message("Updated note: " .. note["result"][1]["fields"][FRONT_FIELD]["value"], 3)
  179. msg.info("Updated note: " .. note["result"][1]["fields"][FRONT_FIELD]["value"])
  180. end
  181. end
  182.  
  183. local function get_extract()
  184. local lines = get_clipboard()
  185. local e = 0
  186. local s = 0
  187. for line in lines:gmatch("[^\r\n]+") do
  188. line = clean(line)
  189. if subs[line]~= nil then
  190. msg.info(lines)
  191. if subs[line][1] ~= nil and subs[line][2] ~= nil then
  192. if s == 0 then
  193. s = subs[line][1]
  194. else
  195. s = math.min(s, subs[line][1])
  196. end
  197. e = math.max(e, subs[line][2])
  198. end
  199. end
  200. end
  201. if e ~= 0 then
  202. create_screenshot(s, e)
  203. create_audio(s, e)
  204. local ifield = '<img src='.. get_name(s,e) ..'.webp>'
  205. local afield = "[sound:".. get_name(s,e) .. ".mp3]"
  206. local tfield = string.gsub(string.gsub(lines,"\n+", "<br />"), "\r", "")
  207. add_to_last_added(ifield, afield, tfield)
  208. end
  209. end
  210.  
  211. local function ex()
  212. pcall(get_extract)
  213. end
  214.  
  215. local function rec(...)
  216. --pcall(record_sub, ...)
  217. record_sub(...)
  218. end
  219.  
  220. local function toggle_sub_to_clipboard()
  221. enable_subs_to_clip = not enable_subs_to_clip
  222. mp.osd_message("Clipboard inserter " .. (enable_subs_to_clip and "activated" or "deactived"), 3)
  223. end
  224.  
  225. mp.observe_property("sub-text", 'string', rec)
  226. mp.add_key_binding("ctrl+v", ex)
  227. mp.add_key_binding("ctrl+t", toggle_sub_to_clipboard)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement