reformat code

This commit is contained in:
Ville Rantanen
2021-12-07 21:00:31 +02:00
parent a7710d7df9
commit 361db95e5a
3 changed files with 56 additions and 35 deletions

View File

@@ -8,7 +8,8 @@ import parse
from ansi import cursor from ansi import cursor
from datetime import datetime from datetime import datetime
__version__=1.0 __version__ = 1.0
class Chopper: class Chopper:
def __init__(self, buf): def __init__(self, buf):

View File

@@ -13,8 +13,12 @@ from datetime import datetime
class Probe: class Probe:
def __init__(self): def __init__(self):
parser = argparse.ArgumentParser(description="Readable version of ffprobe. Give filename as argument.") parser = argparse.ArgumentParser(
parser.add_argument("-c", dest="colorize", action="store_true", default=False, help="Colorize") description="Readable version of ffprobe. Give filename as argument."
)
parser.add_argument(
"-c", dest="colorize", action="store_true", default=False, help="Colorize"
)
parser.add_argument("filename", help="File to probe") parser.add_argument("filename", help="File to probe")
parsed = parser.parse_args() parsed = parser.parse_args()
@@ -32,7 +36,8 @@ class Probe:
"-hide_banner", "-hide_banner",
"-of", "-of",
"default=noprint_wrappers=0", "default=noprint_wrappers=0",
"-print_format", "json", "-print_format",
"json",
"-show_format", "-show_format",
"-show_streams", "-show_streams",
self.filename, self.filename,
@@ -46,13 +51,18 @@ class Probe:
print(errors) print(errors)
self.json_data = json.loads(self.raw_data) self.json_data = json.loads(self.raw_data)
def print(self): def print(self):
# ~ print(self.json_data['format']) # ~ print(self.json_data['format'])
self.json_data['format']['time'] = self._timestr(self.json_data['format'].get('duration',"0")) self.json_data["format"]["time"] = self._timestr(
self.json_data['format']['hrate'] = self._speedfmt(self.json_data['format'].get('bit_rate',"0")) self.json_data["format"].get("duration", "0")
self.json_data['format']['hsize'] = self._sizefmt(float(self.json_data['format'].get('size',0))) )
self.json_data['format'].update(self._get_colors()) self.json_data["format"]["hrate"] = self._speedfmt(
self.json_data["format"].get("bit_rate", "0")
)
self.json_data["format"]["hsize"] = self._sizefmt(
float(self.json_data["format"].get("size", 0))
)
self.json_data["format"].update(self._get_colors())
msg = """{Y}==== Format ===={z} msg = """{Y}==== Format ===={z}
File: {filename} File: {filename}
@@ -60,37 +70,42 @@ class Probe:
Length: {time} Length: {time}
Size: {hsize} Size: {hsize}
Bitrate: {hrate} Bitrate: {hrate}
Streams: {nb_streams}""".format(**self.json_data['format'] Streams: {nb_streams}""".format(
**self.json_data["format"]
) )
print(msg) print(msg)
for stream in self.json_data['streams']: for stream in self.json_data["streams"]:
original = stream.copy() original = stream.copy()
stream.update(self._get_colors()) stream.update(self._get_colors())
if stream['codec_type'] == "video": if stream["codec_type"] == "video":
msg = self.format_video(stream) msg = self.format_video(stream)
elif stream['codec_type'] == "audio": elif stream["codec_type"] == "audio":
msg = self.format_audio(stream) msg = self.format_audio(stream)
elif stream['codec_type'] == "subtitle": elif stream["codec_type"] == "subtitle":
msg = self.format_subtitle(stream) msg = self.format_subtitle(stream)
else: else:
msg = "Unrecognized stream\n{}".format(json.dumps(original, indent=2)) msg = "Unrecognized stream\n{}".format(json.dumps(original, indent=2))
print(msg) print(msg)
def format_subtitle(self, stream): def format_subtitle(self, stream):
stream['tags-lang'] = stream.get('tags',{}).get('language',"NA") stream["tags-lang"] = stream.get("tags", {}).get("language", "NA")
msg = """{Y}==== Stream:{index} ===={z} msg = """{Y}==== Stream:{index} ===={z}
Type: {G}{codec_type}{z} Type: {G}{codec_type}{z}
Codec: {codec_long_name} ({codec_name}) Codec: {codec_long_name} ({codec_name})
Language: {tags-lang}""".format(**stream) Language: {tags-lang}""".format(
**stream
)
return msg return msg
def format_video(self, stream): def format_video(self, stream):
stream['hrate'] = self._speedfmt(stream.get("bit_rate",0)) stream["hrate"] = self._speedfmt(stream.get("bit_rate", 0))
stream['fps'] = "{:.2f}".format(float(stream['r_frame_rate'].split('/')[0]) / float(stream['r_frame_rate'].split('/')[1])) stream["fps"] = "{:.2f}".format(
float(stream["r_frame_rate"].split("/")[0])
/ float(stream["r_frame_rate"].split("/")[1])
)
msg = """{Y}==== Stream:{index} ===={z} msg = """{Y}==== Stream:{index} ===={z}
Type: {G}{codec_type}{z} Type: {G}{codec_type}{z}
Codec: {codec_long_name} ({codec_name}) Codec: {codec_long_name} ({codec_name})
@@ -98,24 +113,27 @@ Language: {tags-lang}""".format(**stream)
Resolution: {width}x{height} Resolution: {width}x{height}
Aspect: {display_aspect_ratio} Aspect: {display_aspect_ratio}
Profile: {profile} Profile: {profile}
FPS: {r_frame_rate} ({fps})""".format(**stream) FPS: {r_frame_rate} ({fps})""".format(
**stream
)
return msg return msg
def format_audio(self, stream): def format_audio(self, stream):
stream['hrate'] = self._speedfmt(stream.get("bit_rate",0)) stream["hrate"] = self._speedfmt(stream.get("bit_rate", 0))
msg = """{Y}==== Stream:{index} ===={z} msg = """{Y}==== Stream:{index} ===={z}
Type: {G}{codec_type}{z} Type: {G}{codec_type}{z}
Codec: {codec_long_name} ({codec_name}) Codec: {codec_long_name} ({codec_name})
Bitrate: {hrate} Bitrate: {hrate}
Sample Rate: {sample_rate} Hz Sample Rate: {sample_rate} Hz
Channels: {channels} ({channel_layout})""".format(**stream) Channels: {channels} ({channel_layout})""".format(
**stream
)
return msg return msg
def _timestr(self, sec): def _timestr(self, sec):
msec = int((float(sec) - int(float(sec)))*1000) msec = int((float(sec) - int(float(sec))) * 1000)
sec = int(float(sec)) sec = int(float(sec))
try: try:
hours = int(sec) // 3600 % 24 hours = int(sec) // 3600 % 24
@@ -141,32 +159,34 @@ Sample Rate: {sample_rate} Hz
except Exception: except Exception:
return b return b
def _sizefmt(self, num, suffix='B'): def _sizefmt(self, num, suffix="B"):
num = float(num) num = float(num)
for unit in ['','K','M','G','T','P','E','Z']: for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
if abs(num) < 1024.0: if abs(num) < 1024.0:
return "%3.1f %s%s" % (num, unit, suffix) return "%3.1f %s%s" % (num, unit, suffix)
num /= 1024.0 num /= 1024.0
return "%.1f %s%s" % (num, 'Y', suffix) return "%.1f %s%s" % (num, "Y", suffix)
def _get_colors(self): def _get_colors(self):
if self.colorize: if self.colorize:
return { return {
'Y': fg.boldyellow, "Y": fg.boldyellow,
'G': fg.boldgreen, "G": fg.boldgreen,
'z': fx.reset, "z": fx.reset,
} }
else: else:
return { return {
'Y': "", "Y": "",
'G': "", "G": "",
'z': "", "z": "",
} }
def main(): def main():
Probe() Probe()
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@@ -18,8 +18,8 @@ setup(
keywords=["ffmpeg"], keywords=["ffmpeg"],
entry_points={ entry_points={
"console_scripts": [ "console_scripts": [
"ffmpeg-parser = ffmpegparser.ffmpegparser:main", "ffmpeg-parser = ffmpegparser.ffmpegparser:main",
"ffprobe-parser = ffmpegparser.ffprobeparser:main" "ffprobe-parser = ffmpegparser.ffprobeparser:main",
] ]
}, },
install_requires=["parse", "ansi"], install_requires=["parse", "ansi"],