def print_metadata(input, show_popup=False, interlace='none'):
    extractor = create_metadata_extractor()
    meta = extractor.extract(input, interlace != 'none')
    o = []

    o.append(os.path.basename(input))
    o.append(output('Directory: {}', os.path.dirname(input)))
    size = os.path.getsize(input)
    if meta.title:
        o.append(output('Title: {}', meta.title))
    o.append(output('Size: {}', sizeof_fmt(size)))
    o.append(output('Format: {}', meta.format))

    durations = [float(s.duration) for s in meta.streams if s.duration]
    if len(durations) > 0:
        o.append(output('Duration: {}', duration_to_str(max(durations))))

    o.append(output('Bitrate: {}', bitrate_to_str(meta.bit_rate)))
    for video in meta.video_streams:
        if video.bit_depth:
            o.append(output('Video: {} {} bit ({}x{})', video.codec,video.bit_depth, video.width, video.height))
        else:
            o.append(output('Video: {} ({}x{})', video.codec, video.width, video.height))

    audio_streams = []
    for audio in meta.audio_streams:
        audio_streams.append((audio.codec, audio.language, audio.channel_layout))
    audio_streams.sort()
    o.append(output('Audio:'))
    for a in audio_streams:
        o.append(output('  {} ({}, {})', *a))

    subtitles = [s.language for s in meta.subtitle_streams]
    if len(subtitles) == 0:
        subtitles = ['None']
    o.append(output('Subtitles: {}', ', '.join(subtitles)))
    o.append(output('Ripped: {}', meta.ripped))

    if meta.interlace_report:
        if interlace == 'summary':
            o.append(output('Interlaced: {}', meta.interlace_report.is_interlaced()))
        elif interlace == 'report':
            o.append(output('Interlaced:'))
            single = meta.interlace_report.single
            o.append(output('  Single: TFF={}, BFF={}, Progressive={}, Undetermined={} ({:.2f}%)', single.tff, single.bff,
                            single.progressive, single.undetermined, single.ratio * 100))
            multi = meta.interlace_report.multi
            o.append(output('  Multi: TFF={}, BFF={}, Progressive={}, Undetermined={} ({:.2f}%)', multi.tff, multi.bff,
                            multi.progressive, multi.undetermined, multi.ratio * 100))

    final = '\n'.join(o)
    if show_popup:
        popup(final)
    else:
        print(final)
def create_table_object(input_to_cmd, interlace='none'):
    from media_management_scripts.utils import create_metadata_extractor
    from media_management_scripts.support.formatting import sizeof_fmt, duration_to_str
    extractor = create_metadata_extractor()
    metadatas = [
        extractor.extract(i, interlace != 'none') for i in input_to_cmd
    ]
    header = [''] + [os.path.basename(f.file) for f in metadatas]
    num_audio = max([len(m.audio_streams) for m in metadatas])
    rows = [
        'Size', 'Duration', 'Bitrate (kb/s)', 'Video Codec', 'Resolution',
        'Audio'
    ]
    for i in range(1, num_audio):
        rows.append('')
    rows.append('Subtitles')
    file_columns = [rows]
    first_size = os.path.getsize(metadatas[0].file)
    for m in metadatas:
        data = []
        size = os.path.getsize(m.file)
        size_ratio = '{:.1f}%'.format(size / first_size * 100)
        data.append('{} ({})'.format(sizeof_fmt(size), size_ratio))
        data.append(
            duration_to_str(m.estimated_duration) if m.
            estimated_duration else '')
        data.append('{:.2f}'.format(m.bit_rate / 1024.0))
        video = m.video_streams[0]
        data.append(video.codec)
        data.append('{}x{}'.format(video.width, video.height))
        for a in m.audio_streams:
            data.append('{} ({}, {})'.format(a.codec, a.language,
                                             a.channel_layout))
        for i in range(len(m.audio_streams), num_audio):
            data.append('')
        data.append(','.join([s.language for s in m.subtitle_streams]))
        file_columns.append(data)
    table = list(map(list, zip(*file_columns)))
    return header, table
 def to_dict(self):
     return {
         'file': self.file,
         'title': self.title,
         'duration': self.estimated_duration,
         'duration_str': duration_to_str(self.estimated_duration) if self.estimated_duration else None,
         'size': self.size,
         'size_str': sizeof_fmt(self.size),
         'resolution': self.resolution._name_ if self.resolution else None,
         'bit_rate': self.bit_rate,
         'bit_rate_str': bitrate_to_str(self.bit_rate),
         'ripped': self.ripped,
         'format': self.format,
         'format_long_name': self.format_long_name,
         'mime_type': self.mime_type,
         'tags': self.tags,
         # 'streams': [s.to_dict() for s in self.streams],
         'video_streams': [s.to_dict() for s in self.video_streams],
         'audio_streams': [s.to_dict() for s in self.audio_streams],
         'subtitle_streams': [s.to_dict() for s in self.subtitle_streams],
         'other_streams': [s.to_dict() for s in self.other_streams],
         'chapters': [c.to_dict() for c in self.chapters] if self.chapters else [],
         'interlace': self.interlace_report.to_dict() if self.interlace_report else None
     }
 def callback(file, m, curr):
     current = sizeof_fmt(curr)
     max = sizeof_fmt(m)
     text = 'Transferring...\n{}\n{} of {}'.format(filename, current, max)
     d.gauge_update(percent=int(curr / m * 100), text=text, update_text=True)
def do_compare(input, output):
    count = 0
    sum_percent = 0
    bigger = []
    not_converted = []
    table = [['File', 'Original', 'Transcoded', 'Percent']]
    total_i = 0
    total_o = 0
    for i, o in get_input_output(input, output):
        name = os.path.basename(i)
        if os.path.exists(o):
            i_size = os.path.getsize(i)
            o_size = os.path.getsize(o)
            percent = o_size / float(i_size) * 100
            if percent < 15:
                not_converted.append('{} (Too small, {:2f}%)'.format(
                    name, percent))
            elif o_size > i_size:
                bigger.append((name, o, i_size, o_size, percent))
            else:
                count += 1
                total_i += i_size
                total_o += o_size
                sum_percent += percent
                table.append([
                    name,
                    sizeof_fmt(i_size),
                    sizeof_fmt(o_size),
                    _f_percent(percent)
                ])
        else:
            not_converted.append(name)

    if count > 0:
        table.append(['', '', '', ''])
        per = total_o / float(total_i) * 100
        table.append([
            'Total',
            sizeof_fmt(total_i),
            sizeof_fmt(total_o),
            _f_percent(per)
        ])

        avg = sum_percent / count
        table.append(['Average', '', '', _f_percent(avg)])

    t = Texttable(max_width=0)
    t.set_deco(Texttable.VLINES | Texttable.HEADER)
    t.set_cols_align(['l', 'r', 'r', 'r'])
    t.add_rows(table)

    print(t.draw())

    print('{} Larger than original'.format(len(bigger)))
    for i, o, i_size, o_size, percent in bigger:
        print('{}: {} -> {} ({:.2f}%)'.format(i, sizeof_fmt(i_size),
                                              sizeof_fmt(o_size), percent))
    if len(not_converted) > 0:
        print('Not Converted:')
        for i in not_converted:
            print('  {}'.format(i))