#AUTOGENERATED! DO NOT EDIT! File to edit: dev/00_utils.ipynb (unless otherwise specified).

__all__ = ['IMG_EXT', 'cd_root', 'extension_counts', 'stop_instance']

#Cell
import boto3
from collections import Counter
import mimetypes
import os
import requests

#Cell
IMG_EXT = {k[1:] for k, v in mimetypes.types_map.items() if 'image' in v}

#Cell
def cd_root(root_subdir='pylib'):
    """Run at start of Jupyter notebook to enter project root.

    Parameters
    ----------
    root_subdir: str
        Name of a subdirectory contained in the project root directory.
        If not found in the current working directory, this will move
        to the parent directory.

    Examples
    --------
    Sample file structure (abbreviated):

    delphi/
        pylib/
            setup.py
            delphi/
                __init__.py
                utils.py
        py/
            fetch_raw_data.py
        notebooks/
            nb01_eda.ipynb

    Running cd_root() from nb01_eda.ipynb will change the working
    directory from notebooks/ to delphi, which is typically the
    same directory we'd run scripts in py/ from. This makes converting
    from notebooks to scripts easier.
    """
    if root_subdir not in next(os.walk('.'))[1]:
        os.chdir('..')
    print('Current directory:', os.getcwd())

#Cell
def extension_counts(paths, common_only=True, exts=None):
    """Given a sequence of paths, find the number of times each extension
    occurs.

    Parameters
    ----------
    paths: list[str]
        Sequence of paths that can be iterated over.
    common_only: bool
        Specifies whether to limit counts to include only certain extensions,
        either passed in by the user or pulled from the mimetypes library.
    exts: set[str]
        Set of file extensions to include (format should not start with '.').
        If common_only is True and exts is None, a set of common file
        extensions are pulled from the mimetypes library.

    Returns
    -------
    dict[str, int]: dict-like object mapping file extension to
        the number of times it appears in `paths`. Files with no extension
        are represented by ''.
    """
    exts = exts or set(ext.lstrip('.') for ext in mimetypes.types_map.keys())
    counts = Counter(os.path.splitext(path)[-1].lstrip('.') for path in paths)
    if common_only:
        counts = {k: v for k, v in counts.items() if k in exts}
    return dict(counts)

#Cell
def stop_instance(debug=False, timeout=5):
    """Stop an active ec2 instance.

    Parameters
    ----------
    debug: bool
        If True, run the stop command in dry run mode. This checks if the
        user has required permissions to execute the command.
    timeout: int
        Max amount of time for request to get ec2 information. If we
        are not on an EC2, this would hang indefinitely otherwise.

    Returns
    -------
    None
    """
    url = 'http://169.254.169.254/latest/dynamic/instance-identity/document'
    try:
        r = requests.get(url, timeout=timeout).json()
    except requests.ReadTimeout as e:
        print('Request timed out. Failed to shutdown instance.')
        return
    id_, region = r['instanceId'], r['region']
    ec2 = boto3.client('ec2', region_name=region)
    ec2.stop_instances(InstanceIds=[id_], DryRun=debug)