import copy
import json
import argparse
import numpy
import glob
import os
from tqdm import tqdm

def Label_Studio2Labelme(label_Studio_json_dirs, labelme_json_dir):
    labelme_json = {}
    shape_dic = {}
    jsons_path = []

    for labelme_dir in label_Studio_json_dirs:
        list_path = glob.glob(labelme_dir + "/*.json")
        jsons_path.extend(list_path)

    for Label_Studio_json in jsons_path:
        with open(Label_Studio_json, 'r', encoding='utf-8') as f:
            info = json.load(f)
            for json_dic in info:
                if not json_dic['annotations'][0]['result']:
                    continue
                shapes_list = []
                labelme_json['version'] = '5.0.1'
                labelme_json['flags'] = {}
                for result_dic in tqdm(json_dic['annotations'][0]['result']):
                    # print(len(result_dic))
                    points_list = []
                    # 进行标签改动
                    if result_dic['value']['rectanglelabels'][0] == 'Pseudocode':
                        shape_dic['label'] = 'Code'
                    else:
                        shape_dic['label'] = copy.deepcopy(result_dic['value']['rectanglelabels'][0])
                    x1, y1 = result_dic['value']['x'] * result_dic['original_width'] / 100, \
                             result_dic['value']['y'] * result_dic['original_height'] / 100
                    points_list.append([x1, y1])
                    x2, y2 = x1 + result_dic['value']['width'] * result_dic['original_width'] / 100, \
                             y1 + result_dic['value']['height'] * result_dic['original_height'] / 100
                    points_list.append([x2, y2])
                    shape_dic['points'] = points_list
                    shape_dic['group_id'] = None
                    shape_dic['shape_type'] = result_dic['type'][:9]
                    shape_dic['flags'] = {}
                    shapes_list.append(copy.deepcopy(shape_dic))
                labelme_json['shapes'] = shapes_list
                labelme_json['imagePath'] = os.path.basename(json_dic['data']['image'])
                labelme_json['imageData'] = None
                labelme_json['imageHeight'] = json_dic['annotations'][0]['result'][0]['original_height']
                labelme_json['imageWidth'] = json_dic['annotations'][0]['result'][0]['original_width']
                labelme_json['updated_by'] = json_dic['updated_by']
                json.dump(labelme_json,
                          open(labelme_json_dir + '/' +
                               str(os.path.splitext(os.path.basename(json_dic['data']['image']))[0]) + '.json',
                               'w', encoding='utf-8'),
                          ensure_ascii=False, indent=2)
        f.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--Label_Studio_json_dirs', type=str,
                        nargs="+", default=[])
    parser.add_argument('--Labelme_json_dir', type=str, default='')
    args = parser.parse_args()

    Label_Studio2Labelme(args.Label_Studio_json_dirs, args.Labelme_json_dir)


