60 lines
1.7 KiB
Python
60 lines
1.7 KiB
Python
from math import log2, log10
|
|
from typing import Union
|
|
|
|
from hurry.filesize import size
|
|
|
|
|
|
def filesize(bytes: int, spaces: bool = True, formatter: bool = True):
|
|
if formatter:
|
|
system = [
|
|
(1024 ** 5, ' PB'),
|
|
(1024 ** 4, ' TB'),
|
|
(1024 ** 3, ' GB'),
|
|
(1024 ** 2, ' MB'),
|
|
(1024 ** 1, ' KB'),
|
|
(1024 ** 0, ' B'),
|
|
]
|
|
x = size(bytes, system=system)
|
|
else:
|
|
x = size(bytes)
|
|
if spaces:
|
|
return x
|
|
else:
|
|
return x.replace(' ', '')
|
|
|
|
|
|
def human_readable_size(size: Union[int, float], bits=False, decimal_places: int = 2, base: int = 10):
|
|
# Define the units
|
|
units = {False: {2: ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'],
|
|
10: ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']},
|
|
True: {2: ['bits', 'Kib', 'Mib', 'Gib', 'Tib', 'Pib', 'Eib', 'Zib', 'Yib'],
|
|
10: ['bits', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb', 'Yb']}}
|
|
|
|
# Convert bytes to bits if needed
|
|
if bits:
|
|
size *= 8
|
|
|
|
# Determine the unit
|
|
if size == 0:
|
|
return '0 ' + units[bits][base][0]
|
|
else:
|
|
if base == 2:
|
|
log = int(log2(size))
|
|
exp = log // 10
|
|
elif base == 10:
|
|
log = int(log10(size))
|
|
exp = log // 3
|
|
else:
|
|
raise ValueError("Invalid base. Use either 2 or 10.")
|
|
|
|
if exp >= len(units[bits][base]):
|
|
exp = len(units[bits][base]) - 1
|
|
size /= base ** (exp * (10 if base == 2 else 3))
|
|
|
|
if decimal_places == 0:
|
|
size = int(size)
|
|
else:
|
|
size = round(size, decimal_places)
|
|
|
|
return f'{size} {units[bits][base][exp]}'
|