<commit_before>"""A Script that tags you movie files.

Run the script in a folder containing the mp4/mkv movie files with their
filename as the movie's title.

This script might seem a little messy and ugly and I know maybe there is
better and effecient way to do some of the tasks.
but I am unaware of them at the moment and am a begginer in Python and
this is my first, or maybe second python script.

TO-DO
1. Add a way to notify when the script is done running
2. Seems a little too much for now but I could change/add stream specific
metadata according to the file
For example depending upon what kind of audio the mkv file has (like AAC 5.1,
DTS 5.1), the script can also change the title/handler of the audio stream
right now it just blanks it out.
The same can be done for subtitles depending upon language. This can also be
implemented to discard dvd subtitles that are sometimes found
in MKVs but are not supported by MP4
3. Add proper error handleling for ffmpeg
"""
import os
import subprocess
import urllib
import shlex
import linecache
import sys
import tmdbsimple as tmdb
from imdbpie import Imdb
from mutagen.mp4 import MP4, MP4Cover


def PrintException():
    exc_type, exc_obj, tb = sys.exc_info()
    f = tb.tb_frame
    lineno = tb.tb_lineno
    fname = f.f_code.co_filename
    linecache.checkcache(fname)
    line = linecache.getline(fname, lineno, f.f_globals)
    print ('\nEXCEPTION IN ({}, LINE {} "{}"): {}'.format(fname, lineno, line.strip(), exc_obj))


#  Setting the API key for usage of TMDB API
tmdb.API_KEY = 'b888b64c9155c26ade5659ea4dd60e64'


def collect_files(file_type):
    """
    returns a list of files in the current directory that are of
    the extension passed as string\n
    eg: collect_files('txt') would return a list of all txt files
    """
    filenames = []
    for filename in os.listdir(os.getcwd()):
        if filename.endswith(file_type):
            filenames.append(filename)
    return filenames


def get_common_files(mediafile_list, srtfile_list):
    """
    returns a list of filenames that are common in mediafile_list and
    strfile_list. \n
    While getting common filenames it ignores the extension.\n
    Also the returned list will have the same file extension the mediafile_list
    files have
    """

    media_filenames = [i[:-4] for i in mediafile_list]
    subtitle_filenames = [i[:-4] for i in srtfile_list]
    media_type = mediafile_list[0][-4:]
    media_set = set(media_filenames)
    srt_set = set(subtitle_filenames)
    common_files = list(media_set & srt_set)
    common_files = [i + media_type for i in common_files]
    common_files.sort()
    return common_files


def remove_common_files(list1, list2):
    """
    returns a subset of list1 that has common elements removed that were found
    in both lists
    or in other words - returns a subset of list1 that has elements unique to
    only list1
    """

    # results in a list of values that are unique to list1
    new_list1 = list(set(list1) - set(list2))
    new_list1.sort()
    return new_list1


def start_process(filenames, mode):
    """
    This is the main funtion of the script
    where it does its main processing.\n
    filenames is the list of files to be processed\n
    mode = 1,2,3 or 4\n
    1 means mp4 to tagged mp4\n
    2 means mp4 with sub to subbed and tagged mp4\n
    3 means mkv to tagged mp4\n
    4 means mkv with sub to subbed and tagged mp4
    """

    searchindex = 0
    for filename in filenames:
        try:
            title = filename[:-4]

            print('\nFetching movie data for "' + title + '"')
            search = tmdb.Search()
            srch_response = search.movie(query=title)
            # getting a Movies object from the id that we got from the search
            # results
            try:    # sometimes blank search results are returned
                tmdb_movie = tmdb.Movies(srch_response['results'][searchindex]['id'])
            except IndexError:
                while len(srch_response['results']) == 0:
                    title = input("\nCould not find the movie, Enter"
                                  " alternate movie title >> ")

                    searchindex = int(input('Search result index >> '))
                    srch_response = search.movie(query=title)
                    try:
                        tmdb_movie = (tmdb.Movies(srch_response['results']
                                      [searchindex]['id']))
                    except IndexError:<commit_msg>Tweaked the verbosity of the script a little<commit_after>"""A Script that tags you movie files.

Run the script in a folder containing the mp4/mkv movie files with their
filename as the movie's title.

This script might seem a little messy and ugly and I know maybe there is
better and effecient way to do some of the tasks.
but I am unaware of them at the moment and am a begginer in Python and
this is my first, or maybe second python script.

TO-DO
1. Add a way to notify when the script is done running
2. Seems a little too much for now but I could change/add stream specific
metadata according to the file
For example depending upon what kind of audio the mkv file has (like AAC 5.1,
DTS 5.1), the script can also change the title/handler of the audio stream
right now it just blanks it out.
The same can be done for subtitles depending upon language. This can also be
implemented to discard dvd subtitles that are sometimes found
in MKVs but are not supported by MP4
3. Add proper error handleling for ffmpeg
"""
import os
import subprocess
import urllib
import shlex
import linecache
import sys
import tmdbsimple as tmdb
from imdbpie import Imdb
from mutagen.mp4 import MP4, MP4Cover


def PrintException():
    exc_type, exc_obj, tb = sys.exc_info()
    f = tb.tb_frame
    lineno = tb.tb_lineno
    fname = f.f_code.co_filename
    linecache.checkcache(fname)
    line = linecache.getline(fname, lineno, f.f_globals)
    print ('\nEXCEPTION IN ({}, LINE {} "{}"): {}'.format(fname, lineno, line.strip(), exc_obj))


#  Setting the API key for usage of TMDB API
tmdb.API_KEY = 'b888b64c9155c26ade5659ea4dd60e64'


def collect_files(file_type):
    """
    returns a list of files in the current directory that are of
    the extension passed as string\n
    eg: collect_files('txt') would return a list of all txt files
    """
    filenames = []
    for filename in os.listdir(os.getcwd()):
        if filename.endswith(file_type):
            filenames.append(filename)
    return filenames


def get_common_files(mediafile_list, srtfile_list):
    """
    returns a list of filenames that are common in mediafile_list and
    strfile_list. \n
    While getting common filenames it ignores the extension.\n
    Also the returned list will have the same file extension the mediafile_list
    files have
    """

    media_filenames = [i[:-4] for i in mediafile_list]
    subtitle_filenames = [i[:-4] for i in srtfile_list]
    media_type = mediafile_list[0][-4:]
    media_set = set(media_filenames)
    srt_set = set(subtitle_filenames)
    common_files = list(media_set & srt_set)
    common_files = [i + media_type for i in common_files]
    common_files.sort()
    return common_files


def remove_common_files(list1, list2):
    """
    returns a subset of list1 that has common elements removed that were found
    in both lists
    or in other words - returns a subset of list1 that has elements unique to
    only list1
    """

    # results in a list of values that are unique to list1
    new_list1 = list(set(list1) - set(list2))
    new_list1.sort()
    return new_list1


def start_process(filenames, mode):
    """
    This is the main funtion of the script
    where it does its main processing.\n
    filenames is the list of files to be processed\n
    mode = 1,2,3 or 4\n
    1 means mp4 to tagged mp4\n
    2 means mp4 with sub to subbed and tagged mp4\n
    3 means mkv to tagged mp4\n
    4 means mkv with sub to subbed and tagged mp4
    """

    searchindex = 0
    for filename in filenames:
        try:
            title = filename[:-4]

            print('\nFetching movie data for "' + title + '"')
            search = tmdb.Search()
            srch_response = search.movie(query=title)
            # getting a Movies object from the id that we got from the search
            # results
            try:    # sometimes blank search results are returned
                tmdb_movie = tmdb.Movies(srch_response['results'][searchindex]['id'])
            except IndexError:
                while len(srch_response['results']) == 0:
                    title = input("\nCould not find the movie, Enter"
                                  " alternate movie title >> ")

                    searchindex = int(input("Search result index (enter 0 if "
                                            "you don't know what this is) >> "))
                    print('\nFetching movie data for "' + title + '"')
                    srch_response = search.movie(query=title)
                    try:
                        tmdb_movie = (tmdb.Movies(srch_response['results']
                                      [searchindex]['id']))
                    except IndexError:
{'fraction_non_alphanumeric': 0.07065217391304347, 'fraction_numerical': 0.014021739130434783, 'mean_word_length': 2.594140625, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4160845', 'n_tokens_mistral': 2799, 'n_tokens_neox': 2655, 'n_words': 1082}