Advertisement
Abu3safeer

Untitled

Apr 29th, 2024
603
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.27 KB | None | 0 0
  1. import argparse
  2. from pathlib import Path
  3. import subprocess
  4. import json
  5. from argparse import ArgumentParser
  6. from datetime import datetime
  7.  
  8. def get_ext_by_codec(codec_name):
  9.     if codec_name in ['SubStationAlpha', 'S_TEXT/ASS', 'S_TEXT/SSA']:
  10.         ext = 'ass'
  11.     elif codec_name in ['SubRip/SRT', 'S_TEXT/UTF8', 'S_ARIBSUB']:
  12.         ext = 'srt'
  13.     elif codec_name in ['S_TEXT/WEBVTT', 'D_WEBVTT/SUBTITLES']:
  14.         ext = 'vtt'
  15.     elif codec_name in ['S_HDMV/PGS', 'S_HDMV/TEXTST', 'S_DVBSUB']:
  16.         ext = 'sup'
  17.     else:
  18.         ext = 'ass'
  19.     return ext
  20.  
  21.  
  22. def extract_all_subtitles(file: Path):
  23.     print(f'file {file.name}')
  24.     command = ["mkvmerge", "-J", file]
  25.     result = subprocess.run(command, capture_output=True, text=True)
  26.  
  27.     # Check if the command was successful
  28.     if result.returncode == 0:
  29.         # Parse the JSON response
  30.         mkv_info = json.loads(result.stdout)
  31.  
  32.         # Now 'mkv_info' is a Python dictionary containing information about the MKV file
  33.         # You can access specific fields like mkv_info['tracks'], etc.
  34.         for track in mkv_info['tracks']:
  35.             track_codec = track['codec']
  36.             track_id = track['id']
  37.             track_type = track['type']
  38.             track_language = track['properties']['language']
  39.             if track_type == 'subtitles':
  40.                 extension = get_ext_by_codec(track_codec)
  41.                 subprocess.run(['mkvextract', 'tracks', file, f'{track_id}:subs/{file.name[:-4]}.{track_id}.{track_language}.{extension}'])
  42.                 print(f'Track {track_id} codec: {track_codec} language: {track_language} type: {track_type}')
  43.     else:
  44.         time_now = datetime.now().strftime("%Y-%m-%d %H:%M")
  45.         # Print an error message if the command failed
  46.         with open('error.txt', 'a') as f:
  47.             f.write(result.stderr)
  48.             f.write(f'[{time_now}] Error: cannot process file {file} {result.stderr}\n')
  49.             f.close()
  50.  
  51.         print(f"[{time_now}] Error: cannot process file {file} {result.stderr}")
  52.  
  53.  
  54. if __name__ == '__main__':
  55.     parser = ArgumentParser()
  56.     parser.add_argument('filename', metavar='filename', type=str)
  57.     args = parser.parse_args()
  58.     print(args.filename)
  59.     file = Path(args.filename)
  60.     extract_all_subtitles(file)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement