Created
December 7, 2022 22:35
-
-
Save sonofsparda757/ffccfe8c74a24c004e4817f7e00c4937 to your computer and use it in GitHub Desktop.
get sizes of all torrents in a given directory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import sys | |
import bencodepy | |
import humanize | |
import argparse | |
def total_size_files_torrent(file_name): | |
try: | |
parsed = bencodepy.decode_from_file(file_name) | |
except bencodepy.exceptions.DecodingError as e: | |
print("Error parsing {}: {}".format(file_name, e)) | |
return 0 | |
else: | |
try: | |
file_list = parsed.get(b'info').get(b'files') | |
if file_list == None: | |
return parsed.get(b'info').get(b'length') | |
return sum(item[b'length'] for item in file_list) | |
except: | |
print("error on:", file_name) | |
return 0 | |
def total_size_torrents_in_directory(directory, verbose=False): | |
directory_file_total = 0 | |
t2size = {} | |
for filename in os.listdir(directory): | |
if filename.endswith(".torrent"): | |
file_path = os.path.join(directory, filename) | |
torrent_file_size = total_size_files_torrent(file_path) | |
if verbose: | |
print("{}: {}".format(file_path, humanize.naturalsize( | |
torrent_file_size))) | |
directory_file_total += torrent_file_size | |
t2size[filename] = torrent_file_size | |
return directory_file_total, t2size | |
def main(): | |
parser = argparse.ArgumentParser( | |
description="%s displays file sizes of a set of torrent files." % | |
sys.argv[0]) | |
parser.add_argument("location", type=str, | |
help="Torrent file or directory of torrent files") | |
parser.add_argument("-v", action="store_true", | |
help="Display verbose output", ) | |
args = parser.parse_args() | |
if os.path.isfile(args.location): | |
combined_file_size = total_size_files_torrent(args.location) | |
print("{}: {}".format(args.location, humanize.naturalsize( | |
combined_file_size))) | |
elif os.path.isdir(args.location): | |
directory_size, t2size = total_size_torrents_in_directory(args.location, | |
verbose=None) | |
print("individual sizes:") | |
t2size_sorted = dict(sorted(t2size.items(), key=lambda item: item[1])) | |
for k in t2size_sorted.keys(): | |
print("{size:.2f} GiB".format(size=t2size_sorted[k]* 9.31e-10), k) | |
print() | |
print("============================================================================") | |
print() | |
print("Combined File Size for all torrents in directory " | |
"'{}': {:.2f} TiB".format(args.location, directory_size*9.09e-13)) | |
else: | |
print("Error: Could not find file or directory '{}'".format( | |
args.location)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage:
python torrent-file-size.py path/to/torrents/folder