summaryrefslogtreecommitdiffhomepage
path: root/libs/guessit/__main__.py
blob: 36d55f1964246adf5475288fad54e3733175f2ca (plain)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Entry point module
"""
# pragma: no cover
import json
import logging
import sys

from collections import OrderedDict

from rebulk.__version__ import __version__ as __rebulk_version__

from guessit import api
from guessit.__version__ import __version__
from guessit.jsonutils import GuessitEncoder
from guessit.options import argument_parser, parse_options, load_config, merge_options


def guess_filename(filename, options):
    """
    Guess a single filename using given options
    :param filename: filename to parse
    :type filename: str
    :param options:
    :type options: dict
    :return:
    :rtype:
    """
    if not options.get('yaml') and not options.get('json') and not options.get('show_property'):
        print('For:', filename)

    guess = api.guessit(filename, options)

    if options.get('show_property'):
        print(guess.get(options.get('show_property'), ''))
        return

    if options.get('json'):
        print(json.dumps(guess, cls=GuessitEncoder, ensure_ascii=False))
    elif options.get('yaml'):
        # pylint:disable=import-outside-toplevel
        import yaml
        from guessit import yamlutils

        ystr = yaml.dump({filename: OrderedDict(guess)}, Dumper=yamlutils.CustomDumper, default_flow_style=False,
                         allow_unicode=True)
        i = 0
        for yline in ystr.splitlines():
            if i == 0:
                print("? " + yline[:-1])
            elif i == 1:
                print(":" + yline[1:])
            else:
                print(yline)
            i += 1
    else:
        print('GuessIt found:', json.dumps(guess, cls=GuessitEncoder, indent=4, ensure_ascii=False))


def display_properties(options):
    """
    Display properties
    """
    properties = api.properties(options)

    if options.get('json'):
        if options.get('values'):
            print(json.dumps(properties, cls=GuessitEncoder, ensure_ascii=False))
        else:
            print(json.dumps(list(properties.keys()), cls=GuessitEncoder, ensure_ascii=False))
    elif options.get('yaml'):
        # pylint:disable=import-outside-toplevel
        import yaml
        from guessit import yamlutils
        if options.get('values'):
            print(yaml.dump(properties, Dumper=yamlutils.CustomDumper, default_flow_style=False, allow_unicode=True))
        else:
            print(yaml.dump(list(properties.keys()), Dumper=yamlutils.CustomDumper, default_flow_style=False,
                            allow_unicode=True))
    else:
        print('GuessIt properties:')

        properties_list = list(sorted(properties.keys()))
        for property_name in properties_list:
            property_values = properties.get(property_name)
            print(2 * ' ' + f'[+] {property_name}')
            if property_values and options.get('values'):
                for property_value in property_values:
                    print(4 * ' ' + f'[!] {property_value}')


def main(args=None):  # pylint:disable=too-many-branches
    """
    Main function for entry point
    """
    if args is None:  # pragma: no cover
        options = parse_options()
    else:
        options = parse_options(args)

    config = load_config(options)
    options = merge_options(config, options)

    if options.get('verbose'):
        logging.basicConfig(stream=sys.stdout, format='%(message)s')
        logging.getLogger().setLevel(logging.DEBUG)

    help_required = True

    if options.get('version'):
        print('+-------------------------------------------------------+')
        print('+                   GuessIt ' + __version__ + (28 - len(__version__)) * ' ' + '+')
        print('+-------------------------------------------------------+')
        print('+                   Rebulk ' + __rebulk_version__ + (29 - len(__rebulk_version__)) * ' ' + '+')
        print('+-------------------------------------------------------+')
        print('|      Please report any bug or feature request at      |')
        print('|     https://github.com/guessit-io/guessit/issues.     |')
        print('+-------------------------------------------------------+')
        help_required = False

    if options.get('yaml'):
        try:
            import yaml  # pylint:disable=unused-variable,unused-import,import-outside-toplevel
        except ImportError:  # pragma: no cover
            del options['yaml']
            print('PyYAML is not installed. \'--yaml\' option will be ignored ...', file=sys.stderr)

    if options.get('properties') or options.get('values'):
        display_properties(options)
        help_required = False

    filenames = []
    if options.get('filename'):
        for filename in options.get('filename'):
            filenames.append(filename)
    if options.get('input_file'):
        with open(options.get('input_file'), 'r', encoding='utf-8') as input_file:
            filenames.extend([line.strip() for line in input_file.readlines()])

    filenames = list(filter(lambda f: f, filenames))

    if filenames:
        for filename in filenames:
            help_required = False
            guess_filename(filename, options)

    if help_required:  # pragma: no cover
        argument_parser.print_help()


if __name__ == '__main__':  # pragma: no cover
    main()