Advertisement
Mirx

Sonarr_Example_invoke_external_application.py

May 3rd, 2018
798
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.60 KB | None | 0 0
  1. #!/usr/bin/env python
  2. #
  3.  
  4. ###################################################################################################
  5. ### SONARR POST-PROCESSING SCRIPT                                                               ###
  6. #                                                                                               ###
  7. # Script to rip srt subtitles out of .mkv files                                                 ###
  8. #                                                                                               ###
  9. # Used to extract subtitles from .mkv files.                                                    ###
  10. # Example usecases are:                                                                         ###
  11. #                                                                                               ###
  12. # 1) Handling of embedded and external subtitles can differ in functionality                    ###
  13. # 2) Prevent unneeded subtitle searches by 3rth party tools                                     ###
  14. #                                                                                               ###
  15. # To specify the languages extracted, you need to alter the values for                          ###
  16. # Lang_X_StreamIds, Lang_X_Ext(.2chr_language_tag.srt), Lang_X_chr3Ext (.3chr_language_tag.srt) ###
  17. #                                                                                               ###
  18. # Processing files which contain multiple subtitle streams for the same language will only      ###
  19. # result in the first and the last stream being extracted.                                      ###
  20. # This is often the case with WEB-DL.                                                           ###
  21. # ISO_639-1 codes are recommended, 2 character for the 1st language, 3 character for the 2nd.   ###
  22. #                                                                                               ###
  23. #                       !!! Make sure to alter your log file location !!!                       ###
  24. #                           !!! Make sure to alter your ffmpeg path !!!                         ###
  25. #                                                                                               ###
  26. # Credits to BenV for the basecode                                                              ###
  27. #                                                                                               ###
  28. # Changed in v2:                                                                                ###
  29. # - Decided not to make the overwrite a variable due to potential script stalls                 ###
  30. # - Simplify troubleshooting so no script alterations are needed                                ###
  31. # - Made script suitable for 2 subtitle streams of the same language                            ###
  32. # - Make language tag / Ext input a variable .nl.srt                                            ###
  33. #                                                                                               ###
  34. ###################################################################################################
  35.  
  36.  
  37. from re import findall
  38. from subprocess import Popen, PIPE
  39. from datetime import datetime
  40. from os import environ, path
  41. from sys import argv
  42.  
  43.                         ### Variables ###
  44.    
  45.     # Get the video file name from the environment variables or argv
  46.     # Manual troubleshoot mode example command: python scriptname.py /volume1/Sonarr/Series/SeriesE01.mkv
  47. if len(argv) >= 2:
  48.     filePath = argv[1]
  49. else:
  50.     filePath = environ.get('sonarr_episodefile_path')
  51.    
  52.     #Extracting the filename and extension for logfile usage
  53. fileName = filePath.split('/')[-1]
  54.  
  55.     #Logfile location and open it unbuffered so you can read it during execution.
  56. fp = open('/volume1/Sonarr/postprocess.log', 'a',0)
  57.  
  58.     # If the ffmpeg excutable is in the path use this
  59. #ffmpeg = 'D:\\aaa\\ffmpeg.exe'
  60.     # if you want to use an ffmpeg version from the SynoCommunity use this:
  61. ffmpeg = '/volume1/@appstore/ffmpeg/bin/ffmpeg'
  62.  
  63.     # This list contains possible subtitle stream identifiers for the first preferred language
  64. Lang1StreamIds = ['nl','nld','dut','dutch','qoq','qoq-team']
  65.  
  66.     # This will determine the 2 character language tag used for the first preffered language
  67. Lang1Ext = '.nl.srt'
  68.  
  69.     # This will determine the 3 character language tag used for the first preffered language
  70. Lang1chr3Ext = '.nld.srt'
  71.    
  72.     # This counter is used for counting the matches for the first preffered language
  73. Lang1ExtCount = 0
  74.  
  75.     # This list contains possible subtitle stream identifiers for the second preferred language
  76. Lang2StreamIds = ['en','eng','english']
  77.  
  78.     # This will determine the language tag used for the first preffered language
  79. Lang2Ext = '.en.srt'
  80.  
  81.     # This will determine the 3 character language tag used for the first preffered language
  82. Lang2chr3Ext = '.eng.srt'
  83.    
  84.     # This counter is used for counting the matches for the first preffered language
  85. Lang2ExtCount = 0
  86.  
  87.                         ### Processing script ###
  88.  
  89.     #Timestamp variable for logfile
  90. sttime = datetime.now().strftime('%Y%m%d %H:%M:%S - ')
  91. if not filePath.lower().endswith('.mkv'):
  92.     fp.write(sttime + fileName + ' is not an .mkv file, processing stopped.\n\n')
  93.     fp.close()
  94.     raise SystemExit
  95. else:
  96.     fp.write(sttime + fileName + ' is an .mkv file, processing started.\n')
  97.  
  98.     # First read the information from the video with ffmpeg.
  99.     # ffmpeg writes this info to the stderr and not to stdout.
  100. Cmd = [ffmpeg,'-i', filePath]
  101. Merge = Popen(Cmd, stdout=PIPE, stderr=PIPE)
  102.     # After the command is prepared we execute it and wait for it to finish with the communicate command
  103. output,err = Merge.communicate()
  104.  
  105.     # ffmpeg writes to stderr
  106.     # make lines insted of one large buffer
  107. err= err.splitlines()
  108.  
  109.     # loop through the information lines, find the stream identifiers and count them
  110. NonSubStreamCount = 0
  111. for Line in err:
  112.     if 'Stream #' in Line:
  113.         NonSubStreamCount += 1
  114.             # if it is a subtitle stream, get the stream info
  115.         if 'Subtitle: subrip' in Line:
  116.             NonSubStreamCount -= 1
  117.                 # use some regexes to find the stream info
  118.             StreamNum = int(findall(r'\d+\.{0,1}\d*', Line)[1]) - NonSubStreamCount
  119.             StreamLang = findall(r'\((.*?)\)', Line)[0]
  120.                 # compose the map identifiers for the ffmpeg command.
  121.             Streamspec = '0:s:' + str(StreamNum)
  122.                 # try to identify the language and create the correct file extension belonging to that language.
  123.             Ext = ''
  124.                 # First we look to see if it is a sub matching preferred language 1
  125.             for Id in Lang1StreamIds:
  126.                 if Id == StreamLang.lower():
  127.                     Ext = Lang1Ext
  128.                     Lang1ExtCount += 1
  129.                     break
  130.                 # If not, we look to see if it is a sub matching preferred language 2
  131.             if not Ext:
  132.                 for Id in Lang2StreamIds:
  133.                     if Id == StreamLang.lower():
  134.                         Ext = Lang2Ext
  135.                         Lang2ExtCount += 1
  136.                         break
  137.                 # We only process the files is their is a preferred language match
  138.             if Ext:
  139.                 OutputFile = filePath[:-4] + Ext
  140.                 if Ext == Lang1Ext:
  141.                     if Lang1ExtCount >= 2:
  142.                         OutputFile = filePath[:-4] + Lang1chr3Ext
  143.                 if Ext == Lang2Ext:
  144.                     if Lang2ExtCount >= 2:
  145.                         OutputFile = filePath[:-4] + Lang2chr3Ext  
  146.                 Cmd =[ffmpeg, '-y', '-loglevel','-32','-i', filePath,'-map',Streamspec,OutputFile]
  147.                 Merge = Popen(Cmd, stdout=PIPE, stderr=PIPE)
  148.                 sttime = datetime.now().strftime('%Y%m%d_%H:%M:%S - ')
  149.                 fp.write(sttime + 'Extracting stream ' + Streamspec + ' language = ' + StreamLang + '\n')
  150.                 output,err = Merge.communicate()
  151.                 if err:
  152.                     fp.write('Problem extracting subtitle.\n')
  153.                     fp.write(err + '\n')
  154.  
  155. sttime = datetime.now().strftime('%Y%m%d_%H:%M:%S - ')
  156. fp.write(sttime + 'Processing finished.\n\n')
  157.                    
  158.     # close the logfile and exit back to Sonarr
  159. fp.close()
  160. raise SystemExit
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement