# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/labelbox/2_LabelboxUtils.ipynb (unless otherwise specified).

__all__ = ['root_dir', 'load_key', 'py_client', 'get_project', 'get_project_labels', 'get_project_coco_annotations',
           'polygons_to_label', 'poly2pts', 'xyformat_lbl2pts', 'xyformat_points2label', 'img_from_url', 'bbox2sz',
           'get_default_frontend', 'clone_ontology', 'clone_project']

# Cell
from pathlib import Path
from .coco_exporter import *
from .imports import *

root_dir = Path('../').absolute()

# Cell
import os

def load_key():
    try:
        with open(root_dir/'API_KEY.txt', 'r') as f: os.environ['LABELBOX_API_KEY'] = f.read()
        key = os.environ['LABELBOX_API_KEY']
        print(f'Successfully loaded API key: {key[:10]}...')
    except Exception as e:
        print(f'Failed to load labelbox API key. \n{e}')

load_key()

# Cell
py_client = Client()

# Cell
def get_project(name):
    ps = list(py_client.get_projects(where=Project.name == name))
    if len(ps): return ps[0]
    return None

# Cell
def get_project_labels(project, out_dir='../../data/meta', overwrite=True):
    exp_url = project.export_labels()
    exp_pth = Path(out_dir)/f'{project.name}_lbls.json'
    exp_pth.parent.mkdir(parents=True, exist_ok=True)
    download_url(exp_url, exp_pth, overwrite=overwrite)
    with open(exp_pth, 'r') as f:
        lbl_json = json.load(f)
    return lbl_json, exp_pth

# Cell
def get_project_coco_annotations(project, out_dir='../../data/meta'):
    _, exp_pth = get_project_labels(project, out_dir=out_dir)
    coco_pth = Path(out_dir)/f'{project.name}_coco.json'
    coco_pth.parent.mkdir(parents=True, exist_ok=True)
    coco_from_json(exp_pth, coco_pth)
    return get_annotations(coco_pth), coco_pth

# Cell
def polygons_to_label(points):
    ps = [{ 'x': int(p[0]), 'y': int(p[1]) } for p in points]
    return { 'geometry': ps }

# Cell
def poly2pts(poly, closed=False):
    pts = list(poly.exterior.coords)
    return pts if closed else pts[:-1]

# Cell
def xyformat_lbl2pts(lbl2pts):
    lbl_list = defaultdict(list)
    for ps,label in lbl2pts:
        lbl_list[label].append(polygons_to_label(ps))
    return lbl_list

# Cell
def xyformat_points2label(points,labels):
    return xyformat_lbl2pts(zip(points,labels))

# Cell
def img_from_url(url):
    response = requests.get(url)
    return PILImage.create(BytesIO(response.content))

# Cell
def bbox2sz(b):
    "Converts Coco l,t,r,b to x,y,w,h"
    lx,ly,w,h = b
    w,h = w-lx,h-ly
    return lx,ly,w,h

# Cell
def get_default_frontend(iframe="https://image-segmentation-v4.labelbox.com"):
    return list(py_client.get_labeling_frontends(where=LabelingFrontend.iframe_url_path == iframe))[0]

def clone_ontology(project, default_tool='polygon'):
    lf = list(project.labeling_frontend_options())[0]
    ontology = json.loads(lf.customization_options)
    for x in ontology['tools']: x['tool'] = default_tool
    return ontology

def clone_project(name, from_project, default_tool='polygon'):
    project = py_client.create_project(name=name)
    for ds in from_project.datasets():
        project.datasets.connect(ds)

    ontology = clone_ontology(from_project, default_tool=default_tool)
    lf = get_default_frontend()

    project.setup(lf, ontology)
    return project
