from dateutil.relativedelta import relativedelta
from datetime import datetime

def human_format(num):
    if num == 0:
        return "0"
    magnitude = 0
    while abs(num) >= 1000:
        magnitude += 1
        num /= 1000.0
    if magnitude == 0:
        if isinstance(num, int):
            return str(num)
        elif float(round(num)) == num:
            return str(int(num))
        else:
            return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])
    else:
        return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitude])

attrs = ['years', 'months', 'days', 'hours', 'minutes', 'seconds']
human_readable = lambda delta: ['%d %s' % (getattr(delta, attr), attr if getattr(delta, attr) > 1 else attr[:-1]) for attr in attrs if getattr(delta, attr)]
replacements = {'years': 'y', 'year': 'y', 'months': 'm', 'month': 'm', 'days': 'd', 'day': 'd', 'hours': 'h', 'hour': 'h', 'minutes': 'min', 'minute': 'min', 'seconds': 's', 'second': 's'}

def formatted_human_readable(seconds):
    if seconds == 0:
        return '0'
    if seconds < 1:
        milliseconds = int(seconds * 1000)
        if milliseconds > 0:
            return f'{milliseconds}ms'
        else:
            return '0'
    result = ''.join(human_readable(relativedelta(seconds=seconds))[:2])
    for replacement in replacements:
        result = result.replace(replacement, replacements[replacement])
    return result.replace(' ', '')


def start_week(date):
    week = int(date.strftime("%V"))
    year = date.year
    month = date.month
    if int(week) > 50 and month == 1:
        year -= 1
    return datetime.strptime(str(year) + '-' + str(week) + '-1', "%Y-%W-%w")
