File size: 5,377 Bytes
07444d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
from asyncio import constants
import os
import json
import numpy as np
from pathlib import Path
from EnumCategory import EnumCategory
from EnumParkingStatus import EnumParkingStatus
from StatusInferEngine import StatusInferEngine
from Constants import Constants
from datetime import datetime
from JSonEditor import JSonEditor

class AbstractFinalFileGenerator:
    def __init__(self, pathRootDataset, loadOriginalSpaces = True):
        self.originalFileReader = self._buildOriginalFileReader()
        self.pathRootDataset = pathRootDataset
        self.dictNewAnnots = {}
        self.orderedDictKeys = []
        self._loadJsonsNewAnnotations()
        self.loadOriginalSpaces = loadOriginalSpaces
        self.get_basename = True

    def _buildOriginalFileReader(self):
        raise NotImplementedError("Abstract Class")

    def generateNewVersionJson(self, pathOldFormatJson, pathNewJson, images_start_id = 0, annotations_start_id = 0, infer_unknown = True):
        editor = JSonEditor(pathOldFormatJson)
        editor.generate_final_json()
        annot_curr_id, map = self._adjust_ids(editor.json, "images", images_start_id)
        self._remapImagesIds(editor.json, Constants.JSON_ANNOTATIONS_KEY, map)

        annot_curr_id, map = self._adjust_ids(editor.json, "annotations", annotations_start_id)

        self._loadSpaces(editor.json, annot_curr_id)
        if infer_unknown:
            statusEngine = StatusInferEngine(editor)
            statusEngine.inferUnknownStatus()

        editor.save_json(pathNewJson)

    def _loadJsonsNewAnnotations(self):
        pathJsons = Path(self.pathRootDataset).rglob('*.json')
        for path in pathJsons:
            with open(path, 'r') as file:
                json_dict = json.load(file)
                name = os.path.basename(path)
                key = self._getDateFromFileName(name)
                self.dictNewAnnots[key] = json_dict
                self.orderedDictKeys.append(key)
        self.orderedDictKeys.sort()

    def _getDateFromFileName(self, fileName):
        raise NotImplementedError("Abstract Class")

    def _loadSpaces(self, json, annotations_start_id):
        # Loading parking images and spaces from the current JSON
        images = json["images"]
        numAnnotatiosLoaded = 0

        annot = json["annotations"]

        for imgData in images:
            # print(imgData)
            id = imgData["id"]

            if self.loadOriginalSpaces == True:
                # Loading original parking spaces
                listDicts = self._loadOriginalParkingSpacesAnnotations(imgData["file_name"], id, annotations_start_id)
                annotations_start_id += len(listDicts) + 1
                numAnnotatiosLoaded += len(listDicts)
                annot.extend(listDicts)

            if len(self.dictNewAnnots) > 0:
                # Loading new parking spaces from root directory
                img_filename = os.path.basename(imgData["file_name"]) if self.get_basename else imgData["file_name"]
                listDicts = self._loadNewParkingSpaces(img_filename, id, annotations_start_id)
                annotations_start_id += len(listDicts) + 1
                numAnnotatiosLoaded += len(listDicts)
                annot.extend(listDicts)

        return numAnnotatiosLoaded

    def _loadNewParkingSpaces(self, imgFileName, imgId, annotations_start_id):
        fileDate = self._getDateFromFileName(imgFileName)
        listDicts = []


        if fileDate not in self.dictNewAnnots:

            dict_keys = sorted(list(self.dictNewAnnots.keys()))
            new_file_date = dict_keys[0]
            key_date = dict_keys[0].split('-')

            datetime_key = datetime(int(key_date[0]),int(key_date[1]),int(key_date[2]))

            while dict_keys and fileDate > datetime_key:
                new_file_date = dict_keys.pop(0)

            print('prior', fileDate, new_file_date)
            fileDate = new_file_date

        if fileDate in self.dictNewAnnots:
            spaces = self.dictNewAnnots[fileDate]
            for space in spaces:
                resh = np.reshape(space, -1).tolist()
                dict = self._createDefaultDictParkingSpace(imgId, annotations_start_id)
                dict["segmentation"] = resh
                dict["parking_status_id"] = EnumParkingStatus.UNKNOWN.value

                annotations_start_id += 1
                listDicts.append(dict)

        return listDicts

    def _loadOriginalParkingSpacesAnnotations(self, imgFileName, imgId, annotations_start_id):
        raise NotImplementedError("Abstract Class")

    def _createDefaultDictParkingSpace(self, imgId, annotationId):
        dict = {}
        dict["id"] = annotationId
        dict["image_id"] = imgId
        dict["category_id"] = EnumCategory.PARKING_SPACE.value
        return dict

    def _adjust_ids(self, json, tag_name, images_start_id = 0):
        curr_id = images_start_id
        items = json[tag_name]
        newMapping = {}
        for it in items:
            newMapping[int(it["id"])] = curr_id
            it["id"] = curr_id
            curr_id = curr_id + 1
        return curr_id, newMapping

    def _remapImagesIds(self, json, tag_name, newMapping):
        items = json[tag_name]
        for it in items:
            it[Constants.JSON_LINK_IMAGE_ID_KEY] = newMapping[int(it[Constants.JSON_LINK_IMAGE_ID_KEY])]
        return