Zappy - Year end project 2
This is a project that Epitech asked us to create in order to allow us to reveiw the notions of the current year.
Loading...
Searching...
No Matches
convert_data.py
Go to the documentation of this file.
7
8"""! _summary_
9 @brief Note to self: Rewrite more than half of that class
10"""
11
12from global_variables import Commands, Items, TranslationReference
13
14
16 """_summary_
17 Class in charge of converting and translating the data received from the outside into commands understood by the internal program
18 """
19
20 def __init__(self, data, error: int = 84, success: int = 0) -> None:
21 self.error = error
22 self.success = success
23 self.data = ""
24 self.update_raw_data(data)
25 # print(f"data = '{self.data}'")
27 self.enum_equivalence = self.tr.enum_equivalence
28 self.text_equivalence = self.tr.text_equivalence
29 self.item_string_to_class = self.tr.item_string_to_class
30 self.item_class_to_string = self.tr.item_class_to_string
31
34 Commands.BROADCAST_TEXT: self._input_parse_inventory
35 }
36
38 Commands.BROADCAST_TEXT: self._output_parse_inventory
39 }
40
41 def update_raw_data(self, data: any) -> int:
42 """_summary_
43
44 Args:
45 data (any): _description_: The type of data is meant to be of type dict or string or a set of byte string.
46 Other formats will return an error.
47 If the content is empty, an error is returned.
48
49 Returns:
50 int: _description_: success if it succeeded to update the raw data, error if it failed to update the raw data.
51 """
52 if isinstance(data, (str, dict, bytes)) is True:
53 if isinstance(data, bytes):
54 data = data.decode()
55 if data in ("", {}):
56 return self.error
57 self.data = data
58 return self.success
59 return self.error
60
61 def set_raw_data(self, data: any) -> int:
62 """_summary_
63
64 Args:
65 data (any): _description_: The type of data is meant to be of type dict or string or a set of byte string.
66 Other formats will return an error.
67 If the content is empty, an error is returned.
68
69 Returns:
70 int: _description_: success if it succeeded to update the raw data, error if it failed to update the raw data.
71 """
72 return self.update_raw_data(data)
73
74 def _process_inventory(self, data_list: list[str]) -> dict[Commands, list[list[str, int]]]:
75 """_summary_
76 This function is to be used to process the inventory list.
77 Args:
78 data_list (list[str]): _description_: The raw list
79
80 Returns:
81 dict[Commands, list[str]]: _description_: The converted version
82 """
83 processed_result = []
84
85 for i in data_list:
86 name, quantity = i.split(" ")
87 if quantity.isnumeric() is False:
88 return {Commands.UNKNOWN: ""}
89 processed_result.append([name.strip(), int(quantity)])
90 return {Commands.INVENTORY: processed_result}
91
92 def _process_look(self, data: list[str]) -> dict[Commands, list[Items]]:
93 """_summary_
94 This function is in charge of converting the input to a list of items.
95
96 Args:
97 data (list[str]): _description_: The semi processed list based of the input
98
99 Returns:
100 dict[Commands, list[Items or str]]: _description_: The final converted version of the input
101 """
102
103 processed_result = []
104 temporary_result = []
105 for i in data:
106 if " " in i:
107 for j in i.split(" "):
108 temporary_result.append(j)
109 else:
110 temporary_result.append(i)
111
112 for i in temporary_result:
113 tmp = i.strip()
114 if tmp in self.item_string_to_class:
115 processed_result.append(self.item_string_to_class[tmp])
116 else:
117 processed_result.append(Items.UNKNOWN)
118 return {Commands.LOOK: processed_result}
119
120 def _special_list_treatment(self, previous_command: Commands) -> dict[Commands, any]:
121 """_summary_
122 Function in charge of the converting a list input to the correct response command.
123
124 Returns:
125 dict[Commands, any]: _description_: The converted list
126 """
127 key = ","
128 if "[" == self.data[0]:
129 self.data = self.data[1:]
130 if "]" == self.data[-1]:
131 self.data = self.data[:-1]
132 if key not in self.data:
133 processed_list = {previous_command: [self.data]}
134 return processed_list
135 data_list = self.data.split(key)
136 if data_list[-1] == "":
137 data_list.pop(-1)
138 if len(data_list) == 0:
139 processed_response = {previous_command: []}
140 return processed_response
141 if " " in data_list[0] and data_list[0][-1].isnumeric():
142 processed_inventory = self._process_inventory(data_list)
143 return processed_inventory
144 processed_look = self._process_look(self.data)
145 return processed_look
146
147 def _get_launch_command(self, triger_command: str) -> Commands:
148 """_summary_
149 This is a function that will extract the command that was used to get the response.
150 Args:
151 triger_command (str): _description_: The command
152
153 Returns:
154 Commands: _description_: The corresponding command but using the internal command tracking.
155 """
156 if isinstance(triger_command, (str, dict)) is not True:
157 return Commands.UNKNOWN
158 if isinstance(triger_command, dict):
159 return list(triger_command.keys())[0]
160 if triger_command == "":
161 return Commands.UNKNOWN
162 if "\n" == triger_command[-1]:
163 triger_command = triger_command[:-1]
164 if " " in triger_command:
165 triger_command = triger_command.split()[0]
166 if triger_command in self.enum_equivalence:
167 return self.enum_equivalence[triger_command]
168 return Commands.UNKNOWN
169
170 def to_internal(self, triger_command: str = "") -> dict[Commands, any]:
171 """_summary_
172 Convert the raw data to the internal language used by the ai
173
174 Returns:
175 dict[Commands, any]: _description_: the format of a node of data comming back
176 """
177 command = self._get_launch_command(triger_command)
178 arguments = ""
179
180 if isinstance(self.data, str) is False:
181 return {command: arguments}
182 if "\n" == self.data[-1]:
183 self.data = self.data[:-1]
184 if "[" in self.data:
185 processed_data = self._special_list_treatment(command)
186 return processed_data
187 if len(self.data) == 0:
188 return {command: arguments}
189 arguments = self.data
190 return {command: arguments}
191
192 def _input_parse_look(self, data: str) -> list[list[str]]:
193 """_summary_
194
195 Input data:
196 "[tile1, tile2, ...]"
197 ex: "[player remedy, ...]"
198 Look, command format (output):
199 {Command.look:[["player", "food", "Linemate", "deraumere", "sibur", "mendiane", "phiras", "thystame"], ... ]}
200 tile 1 tile n
201 Args:
202 data (str): _description_: The arguments provided alongside the command
203
204 Returns:
205 list[list[str]]: _description_: The Internal process data
206 """
207 result = []
208 data = data.split(', ')
209 if "[" in data[0]:
210 data[0] = data[0][1:]
211 if "]" in data[-1]:
212 data[-1] = data[-1][:-1]
213 for i in data:
214 print(f"i = {i}")
215 term = i.lower()
216 if term in self.item_string_to_class:
217 term = self.item_string_to_class[term]
218 else:
219 continue
220 result.append(term)
221
222 return result
223
224 def _input_parse_inventory(self, data: str) -> list[dict[Items, int]]:
225 """_summary_
226
227 Input data:
228 "[linemate n, sibur n, ...]"
229 ex: "[linemate 20 sibur 10, ...]"
230 Look, command format (output):
231 {Command.INVENTORY:[{Items.LINEMATE: 20}, {Items.SIBUR, 10}, ...]}
232
233 Args:
234 data (str): _description_: The arguments provided alongside the command
235
236 Returns:
237 list[dict[Items, int | str]]: _description_: The Internal process data
238 """
239 result = []
240 data = data.split(', ')
241
242 if "[" in data[0]:
243 data[0] = data[0][1:]
244 if "]" in data[-1]:
245 data[-1] = data[-1][:-1]
246 for i in data:
247 if " " in i:
248 term, definition = i.split(" ", 1)
249 term = term.lower()
250 if definition.isnumeric():
251 definition = int(definition)
252 else:
253 continue
254 if term in self.item_string_to_class:
255 term = self.item_string_to_class[term]
256 else:
257 continue
258 result.append({term: definition})
259 else:
260 term = i.lower()
261 if term in self.item_string_to_class:
262 term = self.item_string_to_class[term]
263 else:
264 continue
265 result.append({term: definition})
266
267 return result
268
269 def _output_parse_inventory(self, data: list[dict[Items, int]]) -> str:
270 """_summary_
271
272 Input data:
273 {Command.INVENTORY:[{Items.LINEMATE: 20}, {Items.SIBUR, 10}, ...]}
274 Look, command format (output):
275 "[linemate n, sibur n, ...]"
276 ex: "[linemate 20 sibur 10, ...]"
277
278 Args:
279 data (str): _description_: The arguments provided alongside the command
280
281 Returns:
282 list[dict[Items, int]]: _description_: The Internal process data
283 """
284 result = "["
285 nodes = []
286 for i in data:
287 term = list(i)[0]
288 definition = i[term]
289 tmp = term + " " + definition
290 nodes.append(tmp)
291 result += ", ".join(nodes) + "]" + "\n"
292 return result
293
294 def to_external(self) -> str:
295 """_summary_
296 Convert the internal data to the external language used by the over programs
297
298 Returns:
299 str: _description_: a string containing the command for the other programs
300 """
301 result_order = ""
302 if isinstance(self.data, dict) is False:
303 if isinstance(self.data, str):
304 if self.data == "":
305 self.data += "\n"
306 if self.data[-1] != '\n':
307 self.data += '\n'
308 return self.data
309 return (self.text_equivalence[Commands.UNKNOWN] + '\n')
310 if len(self.data) == 0:
311 return (self.text_equivalence[Commands.UNKNOWN] + '\n')
312 command = list(self.data)[0]
313 arguments = self.data[command]
314 if command == Commands.UNKNOWN:
315 return (self.text_equivalence[Commands.UNKNOWN] + '\n')
316 if command in self.text_equivalence:
317 result_order = self.text_equivalence[command]
318 if arguments == "":
319 result_order += '\n'
320 return result_order
321 if command in self.item_equivalence_output:
322 arguments = self.item_equivalence_output[command](arguments)
323 else:
324 if isinstance(arguments, list) is True:
325 result_order += " ".join(arguments)
326 else:
327 result_order += " " + str(arguments)
328 result_order += '\n'
329 self.data = None
330 return result_order
int update_raw_data(self, any data)
Commands _get_launch_command(self, str triger_command)
None __init__(self, data, int error=84, int success=0)
int set_raw_data(self, any data)
dict[Commands, any] to_internal(self, str triger_command="")
dict[Commands, any] _special_list_treatment(self, Commands previous_command)
list[dict[Items, int]] _input_parse_inventory(self, str data)
dict[Commands, list[Items]] _process_look(self, list[str] data)
list[list[str]] _input_parse_look(self, str data)
str _output_parse_inventory(self, list[dict[Items, int]] data)
dict[Commands, list[list[str, int]]] _process_inventory(self, list[str] data_list)