rpa-suite 1.5.3__py3-none-any.whl → 1.5.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,25 +7,24 @@ import time
7
7
  import traceback
8
8
 
9
9
  # Define a generic type for the function return
10
- T = TypeVar('T')
10
+ T = TypeVar("T")
11
11
 
12
12
 
13
13
  class ParallelRunner(Generic[T]):
14
-
15
14
  """
16
15
  Class to execute functions in parallel while maintaining the main application flow.
17
-
16
+
18
17
  Allows starting a function in a separate process and retrieving its result later.
19
-
18
+
20
19
  pt-br
21
20
  ------
22
21
  Classe para executar funções em paralelo mantendo o fluxo principal da aplicação.
23
-
22
+
24
23
  Permite iniciar uma função em um processo separado e obter seu resultado posteriormente.
25
24
  """
26
-
25
+
27
26
  display_message = None
28
-
27
+
29
28
  def __init__(self, display_message: bool = False):
30
29
  """
31
30
  Initializes the ParallelRunner.
@@ -40,13 +39,13 @@ class ParallelRunner(Generic[T]):
40
39
  Args:
41
40
  display_message (bool): Se True, exibe mensagens de debug durante a execução.
42
41
  """
43
-
42
+
44
43
  self._manager = Manager()
45
44
  self._result_dict = self._manager.dict()
46
45
  self._process = None
47
46
  self._start_time = None
48
47
  self.display_message = display_message
49
-
48
+
50
49
  @staticmethod
51
50
  def _execute_function(function, args, kwargs, result_dict):
52
51
  """
@@ -61,24 +60,24 @@ class ParallelRunner(Generic[T]):
61
60
  try:
62
61
  # Executa a função do usuário com os argumentos fornecidos
63
62
  result = function(*args, **kwargs)
64
-
63
+
65
64
  # Armazena o resultado no dicionário compartilhado
66
- result_dict['status'] = 'success'
67
- result_dict['result'] = result
68
-
65
+ result_dict["status"] = "success"
66
+ result_dict["result"] = result
67
+
69
68
  # Para debug
70
- #print(f"[Processo Filho] Resultado calculado: {result}")
71
- #print(f"[Processo Filho] Dicionário de resultados: {dict(result_dict)}")
72
-
69
+ # print(f"[Processo Filho] Resultado calculado: {result}")
70
+ # print(f"[Processo Filho] Dicionário de resultados: {dict(result_dict)}")
71
+
73
72
  except Exception as e:
74
73
  # Em caso de erro, armazena informações sobre o erro
75
- result_dict['status'] = 'error'
76
- result_dict['error'] = str(e)
77
- result_dict['traceback'] = traceback.format_exc()
78
-
74
+ result_dict["status"] = "error"
75
+ result_dict["error"] = str(e)
76
+ result_dict["traceback"] = traceback.format_exc()
77
+
79
78
  # Para debug
80
79
  print(f"[Processo Filho] Erro ocorrido: {str(e)}")
81
-
80
+
82
81
  @staticmethod
83
82
  def _execute_function_w_disp_msg(function, args, kwargs, result_dict):
84
83
  """
@@ -93,101 +92,102 @@ class ParallelRunner(Generic[T]):
93
92
  try:
94
93
  # Executa a função do usuário com os argumentos fornecidos
95
94
  result = function(*args, **kwargs)
96
-
95
+
97
96
  # Armazena o resultado no dicionário compartilhado
98
- result_dict['status'] = 'success'
99
- result_dict['result'] = result
100
-
97
+ result_dict["status"] = "success"
98
+ result_dict["result"] = result
99
+
101
100
  # Para debug
102
101
  print(f"[Processo Filho] Resultado calculado: {result}")
103
102
  print(f"[Processo Filho] Dicionário de resultados: {dict(result_dict)}")
104
-
103
+
105
104
  except Exception as e:
106
105
  # Em caso de erro, armazena informações sobre o erro
107
- result_dict['status'] = 'error'
108
- result_dict['error'] = str(e)
109
- result_dict['traceback'] = traceback.format_exc()
110
-
106
+ result_dict["status"] = "error"
107
+ result_dict["error"] = str(e)
108
+ result_dict["traceback"] = traceback.format_exc()
109
+
111
110
  # Para debug
112
- print(f"[Processo Filho] Erro ocorrido: {str(e)}")
113
-
114
-
115
- def run(self, function: Callable[..., T], *args, **kwargs) -> 'ParallelRunner[T]':
111
+ print(f"[Processo Filho] Erro ocorrido: {str(e)}")
112
+
113
+ def run(self, function: Callable[..., T], *args, **kwargs) -> "ParallelRunner[T]":
116
114
  """
117
115
  Starts the execution of the function in a parallel process.
118
-
116
+
119
117
  Args:
120
118
  function: Function to be executed in parallel
121
119
  *args: Positional arguments for the function
122
120
  **kwargs: Keyword arguments for the function
123
-
121
+
124
122
  Returns:
125
123
  self: Returns the instance itself to allow chained calls
126
124
 
127
125
  pt-br
128
126
  ------
129
127
  Inicia a execução da função em um processo paralelo.
130
-
128
+
131
129
  Args:
132
130
  function: Função a ser executada em paralelo
133
131
  *args: Argumentos posicionais para a função
134
132
  **kwargs: Argumentos nomeados para a função
135
-
133
+
136
134
  Returns:
137
135
  self: Retorna a própria instância para permitir chamadas encadeadas
138
136
  """
139
137
  # Limpar resultado anterior, se houver
140
138
  if self._result_dict:
141
139
  self._result_dict.clear()
142
-
140
+
143
141
  # Configura valores iniciais no dicionário compartilhado
144
- self._result_dict['status'] = 'running'
145
-
142
+ self._result_dict["status"] = "running"
143
+
146
144
  # Inicia o processo com a função auxiliar estática
147
145
  if self.display_message:
148
146
  self._process = Process(
149
- target=ParallelRunner._execute_function_w_disp_msg,
150
- args=(function, args, kwargs, self._result_dict)
147
+ target=ParallelRunner._execute_function_w_disp_msg,
148
+ args=(function, args, kwargs, self._result_dict),
151
149
  )
152
150
  else:
153
151
  self._process = Process(
154
- target=ParallelRunner._execute_function,
155
- args=(function, args, kwargs, self._result_dict)
152
+ target=ParallelRunner._execute_function,
153
+ args=(function, args, kwargs, self._result_dict),
156
154
  )
157
-
155
+
158
156
  self._process.daemon = True # Processo filho termina quando o principal termina
159
157
  self._process.start()
160
158
  self._start_time = time.time()
161
-
159
+
162
160
  return self
163
161
 
164
162
  def is_running(self) -> bool:
165
163
  """
166
164
  Checks if the process is still running.
167
-
165
+
168
166
  Returns:
169
167
  bool: True if the process is still running, False otherwise
170
-
168
+
171
169
  pt-br
172
170
  ------
173
171
  Verifica se o processo ainda está em execução.
174
-
172
+
175
173
  Retorna:
176
174
  bool: True se o processo ainda estiver em execução, False caso contrário
177
175
  """
178
176
  if self._process is None:
179
177
  return False
180
178
  return self._process.is_alive()
181
-
182
- def get_result(self, timeout: Optional[float] = 60, terminate_on_timeout: bool = True) -> Dict[str, Any]:
179
+
180
+ def get_result(
181
+ self, timeout: Optional[float] = 60, terminate_on_timeout: bool = True
182
+ ) -> Dict[str, Any]:
183
183
  """
184
184
  Retrieves the result of the parallel execution.
185
-
185
+
186
186
  Args:
187
187
  timeout: Maximum time (in seconds) to wait for the process to finish.
188
188
  None means wait indefinitely.
189
189
  terminate_on_timeout: If True, terminates the process if the timeout is reached.
190
-
190
+
191
191
  Returns:
192
192
  - Dict containing:
193
193
  - success: bool indicating if the operation was successful.
@@ -196,17 +196,17 @@ class ParallelRunner(Generic[T]):
196
196
  - traceback: full stack trace (if an error occurred).
197
197
  - execution_time: execution time in seconds.
198
198
  - terminated: True if the process was terminated due to timeout.
199
-
199
+
200
200
  pt-br
201
201
  ------
202
-
202
+
203
203
  Recupera o resultado da execução paralela.
204
-
204
+
205
205
  Args:
206
206
  timeout: Tempo máximo (em segundos) para aguardar o término do processo.
207
207
  None significa aguardar indefinidamente.
208
208
  terminate_on_timeout: Se True, termina o processo se o tempo limite for atingido.
209
-
209
+
210
210
  Retorna:
211
211
  - Dicionário contendo:
212
212
  - success: bool indicando se a operação foi bem-sucedida.
@@ -216,63 +216,73 @@ class ParallelRunner(Generic[T]):
216
216
  - execution_time: tempo de execução em segundos.
217
217
  - terminated: True se o processo foi terminado devido ao tempo limite.
218
218
  """
219
-
219
+
220
220
  if self._process is None:
221
221
  return {
222
- 'success': False,
223
- 'error': 'Nenhum processo foi iniciado',
224
- 'execution_time': 0,
225
- 'terminated': False
222
+ "success": False,
223
+ "error": "Nenhum processo foi iniciado",
224
+ "execution_time": 0,
225
+ "terminated": False,
226
226
  }
227
-
227
+
228
228
  # Aguarda o processo terminar com tempo limite
229
229
  self._process.join(timeout=timeout)
230
230
  execution_time = time.time() - self._start_time
231
-
231
+
232
232
  # Preparamos o dicionário de resposta
233
- result = {
234
- 'execution_time': execution_time,
235
- 'terminated': False
236
- }
237
-
233
+ result = {"execution_time": execution_time, "terminated": False}
234
+
238
235
  # Debug - mostra o dicionário compartilhado
239
- if self.display_message: print(f"[Processo Principal] Dicionário compartilhado: {dict(self._result_dict)}")
240
-
236
+ if self.display_message:
237
+ print(
238
+ f"[Processo Principal] Dicionário compartilhado: {dict(self._result_dict)}"
239
+ )
240
+
241
241
  # Verifica se o processo terminou ou se atingiu o timeout
242
242
  if self._process.is_alive():
243
243
  if terminate_on_timeout:
244
244
  self._process.terminate()
245
- self._process.join(timeout=1) # Pequeno timeout para garantir que o processo termine
246
- result['terminated'] = True
247
- result['success'] = False
248
- result['error'] = f'Operação cancelada por timeout após {execution_time:.2f} segundos'
245
+ self._process.join(
246
+ timeout=1
247
+ ) # Pequeno timeout para garantir que o processo termine
248
+ result["terminated"] = True
249
+ result["success"] = False
250
+ result["error"] = (
251
+ f"Operação cancelada por timeout após {execution_time:.2f} segundos"
252
+ )
249
253
  else:
250
- result['success'] = False
251
- result['error'] = f'Operação ainda em execução após {execution_time:.2f} segundos'
254
+ result["success"] = False
255
+ result["error"] = (
256
+ f"Operação ainda em execução após {execution_time:.2f} segundos"
257
+ )
252
258
  else:
253
259
  # Processo terminou normalmente - verificamos o status
254
- status = self._result_dict.get('status', 'unknown')
255
-
256
- if status == 'success':
257
- result['success'] = True
260
+ status = self._result_dict.get("status", "unknown")
261
+
262
+ if status == "success":
263
+ result["success"] = True
258
264
  # Garantimos que o resultado está sendo copiado corretamente
259
- if 'result' in self._result_dict:
260
- result['result'] = self._result_dict['result']
265
+ if "result" in self._result_dict:
266
+ result["result"] = self._result_dict["result"]
261
267
  else:
262
- result['success'] = False
263
- result['error'] = 'Resultado não encontrado no dicionário compartilhado'
268
+ result["success"] = False
269
+ result["error"] = (
270
+ "Resultado não encontrado no dicionário compartilhado"
271
+ )
264
272
  else:
265
- result['success'] = False
266
- result['error'] = self._result_dict.get('error', 'Erro desconhecido')
267
- if 'traceback' in self._result_dict:
268
- result['traceback'] = self._result_dict['traceback']
269
-
273
+ result["success"] = False
274
+ result["error"] = self._result_dict.get("error", "Erro desconhecido")
275
+ if "traceback" in self._result_dict:
276
+ result["traceback"] = self._result_dict["traceback"]
277
+
270
278
  # Finaliza o Manager se o processo terminou e não estamos mais esperando resultado
271
- if not self._process.is_alive() and (result.get('success', False) or result.get('terminated', False)):
279
+ if not self._process.is_alive() and (
280
+ result.get("success", False) or result.get("terminated", False)
281
+ ):
272
282
  self._cleanup()
273
-
283
+
274
284
  return result
275
-
285
+
276
286
  def terminate(self) -> None:
277
287
  """
278
288
  Terminates the running process.
@@ -285,7 +295,7 @@ class ParallelRunner(Generic[T]):
285
295
  self._process.terminate()
286
296
  self._process.join(timeout=1)
287
297
  self._cleanup()
288
-
298
+
289
299
  def _cleanup(self) -> None:
290
300
  """
291
301
  Cleans up resources used by the process.
@@ -294,7 +304,7 @@ class ParallelRunner(Generic[T]):
294
304
  ------
295
305
  Limpa os recursos utilizados pelo processo.
296
306
  """
297
- if hasattr(self, '_manager') and self._manager is not None:
307
+ if hasattr(self, "_manager") and self._manager is not None:
298
308
  try:
299
309
  self._manager.shutdown()
300
310
  except Exception:
rpa_suite/core/print.py CHANGED
@@ -5,22 +5,21 @@ from colorama import Fore
5
5
 
6
6
 
7
7
  # Windows bash colors
8
- class Colors():
9
- black = f'{Fore.BLACK}'
10
- blue = f'{Fore.BLUE}'
11
- green = f'{Fore.GREEN}'
12
- cyan = f'{Fore.CYAN}'
13
- red = f'{Fore.RED}'
14
- magenta = f'{Fore.MAGENTA}'
15
- yellow = f'{Fore.YELLOW}'
16
- white = f'{Fore.WHITE}'
17
- default = f'{Fore.WHITE}'
18
- call_fn = f'{Fore.LIGHTMAGENTA_EX}'
19
- retur_fn = f'{Fore.LIGHTYELLOW_EX}'
20
-
21
-
22
- class Print():
23
-
8
+ class Colors:
9
+ black = f"{Fore.BLACK}"
10
+ blue = f"{Fore.BLUE}"
11
+ green = f"{Fore.GREEN}"
12
+ cyan = f"{Fore.CYAN}"
13
+ red = f"{Fore.RED}"
14
+ magenta = f"{Fore.MAGENTA}"
15
+ yellow = f"{Fore.YELLOW}"
16
+ white = f"{Fore.WHITE}"
17
+ default = f"{Fore.WHITE}"
18
+ call_fn = f"{Fore.LIGHTMAGENTA_EX}"
19
+ retur_fn = f"{Fore.LIGHTYELLOW_EX}"
20
+
21
+
22
+ class Print:
24
23
  """
25
24
  Class that provides methods for formatted printing in the console, allowing for different types of messages to be displayed with specific colors.
26
25
 
@@ -35,7 +34,7 @@ class Print():
35
34
  ----------
36
35
  >>> from rpa_suite import rpa
37
36
  >>> rpa.alert_print('Hello World')
38
-
37
+
39
38
  pt-br
40
39
  ----
41
40
 
@@ -53,16 +52,12 @@ class Print():
53
52
  >>> from rpa_suite import rpa
54
53
  >>> rpa.alert_print('Hello World')
55
54
  """
55
+
56
56
  colors: Colors = Colors
57
-
58
- def __init__(self):
59
- ...
60
-
61
-
62
- def success_print(self,
63
- string_text: str,
64
- color=Colors.green,
65
- ending="\n") -> None:
57
+
58
+ def __init__(self): ...
59
+
60
+ def success_print(self, string_text: str, color=Colors.green, ending="\n") -> None:
66
61
  """
67
62
  Print that indicates ``SUCCESS``. Customized with the color Green \n
68
63
 
@@ -78,13 +73,9 @@ class Print():
78
73
  ----------
79
74
  >>> type:None
80
75
  """
81
- print(f'{color}{string_text}{Colors.default}', end=ending)
82
-
76
+ print(f"{color}{string_text}{Colors.default}", end=ending)
83
77
 
84
- def alert_print(self,
85
- string_text: str,
86
- color=Colors.yellow,
87
- ending="\n") -> None:
78
+ def alert_print(self, string_text: str, color=Colors.yellow, ending="\n") -> None:
88
79
  """
89
80
  Print that indicates ``ALERT``. Customized with the color Yellow \n
90
81
 
@@ -99,13 +90,9 @@ class Print():
99
90
  ----------
100
91
  >>> type:None
101
92
  """
102
- print(f'{color}{string_text}{Colors.default}', end=ending)
103
-
93
+ print(f"{color}{string_text}{Colors.default}", end=ending)
104
94
 
105
- def info_print(self,
106
- string_text: str,
107
- color=Colors.cyan,
108
- ending="\n") -> None:
95
+ def info_print(self, string_text: str, color=Colors.cyan, ending="\n") -> None:
109
96
  """
110
97
  Print that indicates ``INFORMATION``. Customized with the color Cyan \n
111
98
 
@@ -120,13 +107,9 @@ class Print():
120
107
  ----------
121
108
  >>> type:None
122
109
  """
123
- print(f'{color}{string_text}{Colors.default}', end=ending)
110
+ print(f"{color}{string_text}{Colors.default}", end=ending)
124
111
 
125
-
126
- def error_print(self,
127
- string_text: str,
128
- color=Colors.red,
129
- ending="\n") -> None:
112
+ def error_print(self, string_text: str, color=Colors.red, ending="\n") -> None:
130
113
  """
131
114
  Print that indicates ``ERROR``. Customized with the color Red \n
132
115
 
@@ -141,13 +124,11 @@ class Print():
141
124
  ----------
142
125
  >>> type:None
143
126
  """
144
- print(f'{color}{string_text}{Colors.default}', end=ending)
145
-
127
+ print(f"{color}{string_text}{Colors.default}", end=ending)
146
128
 
147
- def magenta_print(self,
148
- string_text: str,
149
- color=Colors.magenta,
150
- ending="\n") -> None:
129
+ def magenta_print(
130
+ self, string_text: str, color=Colors.magenta, ending="\n"
131
+ ) -> None:
151
132
  """
152
133
  Print customized with the color Magenta \n
153
134
 
@@ -162,13 +143,9 @@ class Print():
162
143
  ----------
163
144
  >>> type:None
164
145
  """
165
- print(f'{color}{string_text}{Colors.default}', end=ending)
166
-
146
+ print(f"{color}{string_text}{Colors.default}", end=ending)
167
147
 
168
- def blue_print(self,
169
- string_text: str,
170
- color=Colors.blue,
171
- ending="\n") -> None:
148
+ def blue_print(self, string_text: str, color=Colors.blue, ending="\n") -> None:
172
149
  """
173
150
  Print customized with the color Blue \n
174
151
 
@@ -183,13 +160,11 @@ class Print():
183
160
  ----------
184
161
  >>> type:None
185
162
  """
186
- print(f'{color}{string_text}{Colors.default}', end=ending)
163
+ print(f"{color}{string_text}{Colors.default}", end=ending)
187
164
 
188
-
189
- def print_call_fn(self,
190
- string_text: str,
191
- color=Colors.call_fn,
192
- ending="\n") -> None:
165
+ def print_call_fn(
166
+ self, string_text: str, color=Colors.call_fn, ending="\n"
167
+ ) -> None:
193
168
  """
194
169
  Print customized for function called (log) \n
195
170
  Color: Magenta Light
@@ -205,13 +180,11 @@ class Print():
205
180
  ----------
206
181
  >>> type:None
207
182
  """
208
- print(f'{color}{string_text}{Colors.default}', end=ending)
209
-
183
+ print(f"{color}{string_text}{Colors.default}", end=ending)
210
184
 
211
- def print_retur_fn(self,
212
- string_text: str,
213
- color=Colors.retur_fn,
214
- ending="\n") -> None:
185
+ def print_retur_fn(
186
+ self, string_text: str, color=Colors.retur_fn, ending="\n"
187
+ ) -> None:
215
188
  """
216
189
  Print customized for function return (log) \n
217
190
  Color: Yellow Light
@@ -227,5 +200,4 @@ class Print():
227
200
  ----------
228
201
  >>> type:None
229
202
  """
230
- print(f'{color}{string_text}{Colors.default}', end=ending)
231
-
203
+ print(f"{color}{string_text}{Colors.default}", end=ending)
rpa_suite/core/regex.py CHANGED
@@ -7,7 +7,7 @@ from rpa_suite.functions._printer import error_print, success_print
7
7
  import re
8
8
 
9
9
 
10
- class Regex():
10
+ class Regex:
11
11
  """
12
12
  Class that provides utilities for working with regular expressions.
13
13
 
@@ -27,15 +27,16 @@ class Regex():
27
27
 
28
28
  A classe Regex é parte do RPA Suite e pode ser usada para aprimorar as capacidades de processamento de texto.
29
29
  """
30
- def __init__(self):
31
- ...
32
-
33
- def check_pattern_in_text(self,
34
- origin_text: str,
35
- pattern_to_search: str,
36
- case_sensitive: bool = True,
37
- display_message: bool = False) -> bool:
38
30
 
31
+ def __init__(self): ...
32
+
33
+ def check_pattern_in_text(
34
+ self,
35
+ origin_text: str,
36
+ pattern_to_search: str,
37
+ case_sensitive: bool = True,
38
+ display_message: bool = False,
39
+ ) -> bool:
39
40
  """
40
41
  Function responsible for searching in a string ``origin_text`` a pattern ``pattern_to_search`` and returning True if the pattern is found, otherwise False. ``case_sensitive`` used for exact cases or cases with diferencce upper and lower cases
41
42
 
@@ -55,31 +56,37 @@ class Regex():
55
56
  try:
56
57
 
57
58
  if case_sensitive:
58
-
59
+
59
60
  # Check if the pattern is found in the text
60
61
  if re.search(pattern_to_search, origin_text):
61
- if display_message: success_print(f'Pattern found successfully!')
62
+ if display_message:
63
+ success_print(f"Pattern found successfully!")
62
64
  return True
63
-
65
+
64
66
  else:
65
- if display_message: success_print(f'Pattern not found.')
67
+ if display_message:
68
+ success_print(f"Pattern not found.")
66
69
  return False
67
70
  else:
68
-
71
+
69
72
  # normalize text to search without case sensitive
70
73
  origin_text = origin_text.lower()
71
74
  pattern_to_search = pattern_to_search.lower()
72
-
75
+
73
76
  # Check if the pattern is found in the text
74
77
  if re.search(pattern_to_search, origin_text):
75
- if display_message: success_print(f'Pattern found successfully!')
78
+ if display_message:
79
+ success_print(f"Pattern found successfully!")
76
80
  return True
77
-
81
+
78
82
  else:
79
- if display_message: success_print(f'Pattern not found.')
83
+ if display_message:
84
+ success_print(f"Pattern not found.")
80
85
  return False
81
-
86
+
82
87
  except Exception as e:
83
-
84
- error_print(f"Error function: {self.check_pattern_in_text.__name__} when trying to check pattern in text. Error: {str(e)}")
85
- return False
88
+
89
+ error_print(
90
+ f"Error function: {self.check_pattern_in_text.__name__} when trying to check pattern in text. Error: {str(e)}"
91
+ )
92
+ return False