Parse a human-readable size string to bytes. Args: size_str: Size string like "100GB", "50MB", "1TB". Returns: Size in bytes.
(size_str: str)
| 16 | |
| 17 | |
| 18 | def parse_size(size_str: str) -> int: |
| 19 | """ |
| 20 | Parse a human-readable size string to bytes. |
| 21 | |
| 22 | Args: |
| 23 | size_str: Size string like "100GB", "50MB", "1TB". |
| 24 | |
| 25 | Returns: |
| 26 | Size in bytes. |
| 27 | """ |
| 28 | size_str = size_str.strip().upper() |
| 29 | |
| 30 | units = { |
| 31 | "B": 1, |
| 32 | "KB": 1024, |
| 33 | "MB": 1024**2, |
| 34 | "GB": 1024**3, |
| 35 | "TB": 1024**4, |
| 36 | } |
| 37 | |
| 38 | for unit, multiplier in units.items(): |
| 39 | if size_str.endswith(unit): |
| 40 | try: |
| 41 | value = float(size_str[: -len(unit)]) |
| 42 | return int(value * multiplier) |
| 43 | except ValueError: |
| 44 | pass |
| 45 | |
| 46 | # Try parsing as plain number (bytes) |
| 47 | try: |
| 48 | return int(size_str) |
| 49 | except ValueError: |
| 50 | raise ValueError(f"Invalid size string: {size_str}") |
| 51 | |
| 52 | |
| 53 | @dataclass |