nano-wait 1.3__py3-none-any.whl → 3.0__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.

Potentially problematic release.


This version of nano-wait might be problematic. Click here for more details.

nano_wait/__init__.py CHANGED
@@ -1 +1,38 @@
1
- from .nano_wait import *
1
+ from .core import NanoWait
2
+
3
+ def wait(t: float, wifi: str = None, speed: float = 1.5, smart: bool = False, verbose: bool = False, log: bool = False):
4
+ """
5
+ Main API function to wait adaptively.
6
+
7
+ Args:
8
+ t (float): Base wait time in seconds
9
+ wifi (str, optional): Wi-Fi SSID to consider
10
+ speed (float, optional): Speed factor (ignored if smart=True)
11
+ smart (bool, optional): Enable Smart Context Mode
12
+ verbose (bool): Print debug info
13
+ log (bool): Save log
14
+ """
15
+ nw = NanoWait()
16
+
17
+ if smart:
18
+ pc_score = nw.get_pc_score()
19
+ wifi_score = nw.get_wifi_signal(wifi) if wifi else 5
20
+ risk_score = (pc_score + wifi_score) / 2
21
+ speed = max(0.5, min(5.0, risk_score))
22
+ if verbose:
23
+ print(f"[Smart Context] PC={pc_score:.2f}, Wi-Fi={wifi_score:.2f}, risk={risk_score:.2f}, speed={speed:.2f}")
24
+
25
+ if wifi:
26
+ wait_time = nw.wait_wifi(speed=speed, ssid=wifi)
27
+ else:
28
+ wait_time = nw.wait_n_wifi(speed=speed)
29
+
30
+ if verbose:
31
+ print(f"[NanoWait] PC+WiFi wait = {wait_time:.2f}s")
32
+
33
+ import time
34
+ time.sleep(wait_time)
35
+
36
+ if log:
37
+ with open("nano_wait.log", "a") as f:
38
+ f.write(f"{time.strftime('%Y-%m-%d %H:%M:%S')} - Waited {wait_time:.2f}s\n")
nano_wait/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
nano_wait/cli.py ADDED
@@ -0,0 +1,58 @@
1
+ import argparse
2
+ from . import wait as nano_wait_func
3
+ from .core import NanoWait
4
+
5
+ # Presets tradicionais
6
+ SPEED_PRESETS = {
7
+ "slow": 0.5,
8
+ "normal": 1.5,
9
+ "fast": 3.0,
10
+ "ultra": 5.0
11
+ }
12
+
13
+ def main():
14
+ parser = argparse.ArgumentParser(
15
+ description="Nano-Wait — Adaptive smart wait for Python."
16
+ )
17
+ parser.add_argument("time", type=float, help="Base time in seconds (e.g. 2.5)")
18
+ parser.add_argument("--wifi", type=str, help="Wi-Fi SSID to use (optional)")
19
+ parser.add_argument(
20
+ "--speed",
21
+ type=str,
22
+ default="auto",
23
+ help="Speed preset (slow, normal, fast, ultra) or 'auto'"
24
+ )
25
+ parser.add_argument("--smart", action="store_true", help="Enable Smart Context Mode")
26
+ parser.add_argument("--verbose", action="store_true", help="Show debug output")
27
+ parser.add_argument("--log", action="store_true", help="Write result to log file")
28
+
29
+ args = parser.parse_args()
30
+
31
+ nw = NanoWait()
32
+
33
+ # Determina o speed
34
+ if args.smart:
35
+ # Smart Context Mode
36
+ pc_score = nw.get_pc_score()
37
+ wifi_score = nw.get_wifi_signal(args.wifi) if args.wifi else 5
38
+ risk_score = (pc_score + wifi_score) / 2
39
+ # Quanto maior o risco (pior PC/Wi-Fi), menor o speed → espera maior
40
+ speed_value = max(0.5, min(5.0, risk_score))
41
+ if args.verbose:
42
+ print(f"[Smart Context] PC={pc_score:.2f}, Wi-Fi={wifi_score:.2f}, risk={risk_score:.2f}, speed={speed_value:.2f}")
43
+ elif args.speed.lower() == "auto":
44
+ # Auto-speed simples (sem Smart Context Mode)
45
+ speed_value = 1.5
46
+ else:
47
+ speed_value = SPEED_PRESETS.get(args.speed.lower(), 1.5)
48
+
49
+ nano_wait_func(
50
+ t=args.time,
51
+ wifi=args.wifi,
52
+ speed=speed_value,
53
+ verbose=args.verbose,
54
+ log=args.log
55
+ )
56
+
57
+ if __name__ == "__main__":
58
+ main()
nano_wait/core.py ADDED
@@ -0,0 +1,68 @@
1
+ class NanoWait:
2
+ def __init__(self):
3
+ import platform
4
+ self.system = platform.system().lower()
5
+ # Apenas Windows precisa de pywifi
6
+ if self.system == "windows":
7
+ import pywifi
8
+ self.wifi = pywifi.PyWiFi()
9
+ self.interface = self.wifi.interfaces()[0]
10
+ else:
11
+ self.wifi = None
12
+ self.interface = None
13
+
14
+ def get_pc_score(self):
15
+ import psutil
16
+ try:
17
+ cpu = psutil.cpu_percent(interval=1)
18
+ mem = psutil.virtual_memory().percent
19
+ return (max(0, min(10, 10 - cpu / 10)) + max(0, min(10, 10 - mem / 10))) / 2
20
+ except:
21
+ return 0
22
+
23
+ def get_wifi_signal(self, ssid=None):
24
+ # Retorna 0 se Wi-Fi não disponível
25
+ if self.system == "windows" and self.interface:
26
+ try:
27
+ self.interface.scan()
28
+ import time
29
+ time.sleep(2)
30
+ for net in self.interface.scan_results():
31
+ if ssid is None or net.ssid == ssid:
32
+ return max(0, min(10, (net.signal + 100) / 10))
33
+ except:
34
+ return 0
35
+ elif self.system == "darwin":
36
+ import subprocess
37
+ try:
38
+ out = subprocess.check_output([
39
+ "/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport",
40
+ "-I"
41
+ ], text=True)
42
+ line = [l for l in out.split("\n") if "agrCtlRSSI" in l][0]
43
+ rssi = int(line.split(":")[1].strip())
44
+ return max(0, min(10, (rssi + 100) / 10))
45
+ except:
46
+ return 0
47
+ elif self.system == "linux":
48
+ import subprocess
49
+ try:
50
+ out = subprocess.check_output(["nmcli", "-t", "-f", "ACTIVE,SSID,SIGNAL", "dev", "wifi"], text=True)
51
+ for l in out.splitlines():
52
+ active, name, sig = l.split(":")
53
+ if active == "yes" or (ssid and name == ssid):
54
+ return max(0, min(10, int(sig)/10))
55
+ except:
56
+ return 0
57
+ return 0
58
+
59
+ def wait_wifi(self, speed=1.5, ssid=None):
60
+ """Sempre disponível, mesmo sem pywifi"""
61
+ pc = self.get_pc_score()
62
+ wifi = self.get_wifi_signal(ssid)
63
+ risk = (pc + wifi) / 2
64
+ return max(0.2, (10 - risk)/speed)
65
+
66
+ def wait_n_wifi(self, speed=1.5):
67
+ pc = self.get_pc_score()
68
+ return max(0.2, (10 - pc)/speed)
nano_wait/nano_wait.py CHANGED
@@ -1,76 +1,32 @@
1
- import pywifi
2
- import psutil
3
- import time
4
-
5
- class NanoWait:
6
- def __init__(self):
7
- self.wifi = pywifi.PyWiFi()
8
- self.interface = self.wifi.interfaces()[0]
9
-
10
- def get_wifi_signal(self, ssid):
11
- try:
12
- self.interface.scan()
13
- time.sleep(2) # Wait for WiFi scan
14
- scan_results = self.interface.scan_results()
15
-
16
- signal_strength = -100 # Default value for poor signal
17
-
18
- for network in scan_results:
19
- if network.ssid == ssid:
20
- signal_strength = network.signal
21
- break
22
- else:
23
- raise ValueError(f"WiFi network '{ssid}' not found.")
24
-
25
- # Convert signal strength to a scale of 0 to 10
26
- wifi_score = max(0, min(10, (signal_strength + 100) / 10))
27
- return wifi_score
28
-
29
- except Exception as e:
30
- print(f"Error getting WiFi signal: {e}")
31
- return 0
32
-
33
- def get_pc_score(self):
34
- try:
35
- cpu_usage = psutil.cpu_percent(interval=1)
36
- memory_usage = psutil.virtual_memory().percent
37
-
38
- # Convert CPU and memory usage to a scale of 0 to 10
39
- cpu_score = max(0, min(10, 10 - cpu_usage / 10))
40
- memory_score = max(0, min(10, 10 - memory_usage / 10))
41
-
42
- # Average score of CPU and memory
43
- pc_score = (cpu_score + memory_score) / 2
44
- return pc_score
45
-
46
- except Exception as e:
47
- print(f"Error getting PC score: {e}")
48
- return 0
49
-
50
- def wait_wifi(self, speed, ssid):
51
- try:
52
- pc_score = self.get_pc_score()
53
- wifi_score = self.get_wifi_signal(ssid)
54
-
55
- # Combined risk score
56
- risk_score = (pc_score + wifi_score) / 2
57
-
58
- # Calculate wait time based on speed and risk score
59
- wait_time = max(1, (10 - risk_score) / speed)
60
- return wait_time
61
-
62
- except Exception as e:
63
- print(f"Error in wait_wifi: {e}")
64
- return 1
65
-
66
- def wait_n_wifi(self, speed):
67
- try:
68
- pc_score = self.get_pc_score()
69
-
70
- # Calculate wait time based on speed and risk score
71
- wait_time = max(1, (10 - pc_score) / speed)
72
- return wait_time
73
-
74
- except Exception as e:
75
- print(f"Error in wait_n_wifi: {e}")
76
- return 1
1
+ from .core import NanoWait
2
+ from .utils import log_message, get_speed_value
3
+
4
+ def wait(t: float, wifi: str = None, speed: str | float = "normal", verbose=False, log=False) -> float:
5
+ """
6
+ Adaptive smart wait — replaces time.sleep() with intelligence.
7
+
8
+ Args:
9
+ t (float): Base wait time in seconds.
10
+ wifi (str, optional): Wi-Fi SSID to evaluate. Defaults to None.
11
+ speed (str|float): 'slow', 'normal', 'fast', 'ultra', or custom float.
12
+ verbose (bool): Print details. Defaults to False.
13
+ log (bool): Write log to file. Defaults to False.
14
+
15
+ Returns:
16
+ float: Wait time executed (seconds).
17
+ """
18
+ speed_value = get_speed_value(speed)
19
+ nw = NanoWait()
20
+
21
+ factor = nw.wait_wifi(speed_value, wifi) if wifi else nw.wait_n_wifi(speed_value)
22
+ wait_time = round(max(0.05, min(t / factor, t)), 3)
23
+
24
+ if verbose:
25
+ print(f"[NanoWait] 🧠 speed={speed_value}, wait={wait_time:.3f}s")
26
+
27
+ if log:
28
+ log_message(f"Wait={wait_time:.3f}s | speed={speed_value}")
29
+
30
+ import time
31
+ time.sleep(wait_time)
32
+ return wait_time
nano_wait/utils.py ADDED
@@ -0,0 +1,13 @@
1
+ from datetime import datetime
2
+
3
+ def get_speed_value(speed):
4
+ """Converts speed preset or numeric input to float."""
5
+ speed_map = {"slow": 0.8, "normal": 1.5, "fast": 3.0, "ultra": 6.0}
6
+ if isinstance(speed, str):
7
+ return speed_map.get(speed.lower(), 1.5)
8
+ return float(speed)
9
+
10
+ def log_message(text: str):
11
+ """Saves messages to nano_wait.log."""
12
+ with open("nano_wait.log", "a") as f:
13
+ f.write(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {text}\n")
nano_wait/vision.py ADDED
@@ -0,0 +1,111 @@
1
+ import time
2
+ import pytesseract
3
+ import pyautogui
4
+ from pynput.mouse import Controller, Button
5
+ from PIL import ImageGrab, ImageOps
6
+ import re
7
+
8
+ class VisionMode:
9
+ """
10
+ Classe para captura e interpretação visual da tela.
11
+ Modos disponíveis:
12
+ - "observe": apenas lê e exibe dados detectados.
13
+ - "decision": lê dados e toma decisões automáticas.
14
+ - "learn": registra padrões visuais para uso futuro.
15
+ """
16
+
17
+ def __init__(self, mode="observe"):
18
+ self.mode = mode
19
+ self.mouse = Controller()
20
+ print(f"🔍 VisionMode iniciado no modo '{self.mode}'")
21
+
22
+ def capture_numbers(self, regions=None):
23
+ results = {}
24
+ if not regions:
25
+ regions = [None]
26
+
27
+ for idx, region in enumerate(regions):
28
+ print(f"📸 Capturando região {idx + 1}...")
29
+ if region:
30
+ x, y, w, h = region
31
+ if w <= 0 or h <= 0:
32
+ raise ValueError("Largura e altura devem ser maiores que 0")
33
+ bbox = (x, y, x + w, y + h)
34
+ img = ImageGrab.grab(bbox=bbox)
35
+ else:
36
+ img = ImageGrab.grab()
37
+
38
+ img = ImageOps.grayscale(img)
39
+ text = pytesseract.image_to_string(img)
40
+ print(f"🧠 Texto detectado na região {idx + 1}: {text}")
41
+
42
+ match = re.findall(r'\d+', text)
43
+ numbers = [int(m) for m in match] if match else [0]
44
+
45
+ results[region or f"full_screen_{idx}"] = numbers
46
+
47
+ return results
48
+
49
+ def perform_action(self, action):
50
+ if action == "like_post":
51
+ self.mouse.click(Button.left, 2)
52
+ print("❤️ Ação: clique duplo executado.")
53
+ elif action == "skip_post":
54
+ self.mouse.move(100, 0)
55
+ print("⏭ Ação: pulando item.")
56
+ else:
57
+ print(f"⚙️ Ação desconhecida: {action}")
58
+
59
+ def run(self, regions=None):
60
+ numbers_per_region = self.capture_numbers(regions)
61
+
62
+ if self.mode == "observe":
63
+ for reg, nums in numbers_per_region.items():
64
+ print(f"👁 Região {reg}: números detectados = {nums}")
65
+
66
+ elif self.mode == "decision":
67
+ for reg, nums in numbers_per_region.items():
68
+ for number in nums:
69
+ if number > 1000:
70
+ self.perform_action("like_post")
71
+ else:
72
+ self.perform_action("skip_post")
73
+
74
+ elif self.mode == "learn":
75
+ print("📚 Modo aprendizado ativado: coletando dados...")
76
+ for _ in range(3):
77
+ self.capture_numbers(regions)
78
+ time.sleep(2)
79
+ else:
80
+ print(f"❌ Modo '{self.mode}' inválido.")
81
+
82
+ # ------------------------
83
+ # Nova função: mark_region
84
+ # ------------------------
85
+ @staticmethod
86
+ def mark_region():
87
+ """
88
+ Captura região usando PyAutoGUI.
89
+ O usuário clica no canto superior esquerdo e inferior direito.
90
+ Retorna (x, y, largura, altura)
91
+ """
92
+ print("📌 Marque a região desejada:")
93
+ print("Clique no canto superior esquerdo da área desejada e pressione Enter...")
94
+ input("Pressione Enter quando estiver pronto...")
95
+ x1, y1 = pyautogui.position()
96
+ print(f"📍 Ponto superior esquerdo: ({x1}, {y1})")
97
+
98
+ print("Clique no canto inferior direito da área desejada e pressione Enter...")
99
+ input("Pressione Enter quando estiver pronto...")
100
+ x2, y2 = pyautogui.position()
101
+ print(f"📍 Ponto inferior direito: ({x2}, {y2})")
102
+
103
+ x, y = min(x1, x2), min(y1, y2)
104
+ w, h = abs(x2 - x1), abs(y2 - y1)
105
+
106
+ if w == 0 or h == 0:
107
+ print("❌ Largura ou altura inválida. Tente novamente.")
108
+ return None
109
+
110
+ print(f"✅ Região marcada: (x={x}, y={y}, largura={w}, altura={h})")
111
+ return (x, y, w, h)
@@ -0,0 +1,61 @@
1
+ Metadata-Version: 2.4
2
+ Name: nano_wait
3
+ Version: 3.0
4
+ Summary: Adaptive waiting and smart automation library — includes Wi-Fi, system context, and Vision Mode for screen-based decisions.
5
+ Author: Luiz Filipe Seabra de Marco
6
+ Author-email: luizfilipeseabra@icloud.com
7
+ License: MIT License
8
+ Keywords: automation automação wifi wait vision ocr screen adaptive ai
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
13
+ Classifier: Topic :: Utilities
14
+ Classifier: Intended Audience :: Developers
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: psutil
19
+ Requires-Dist: pywifi
20
+ Provides-Extra: vision
21
+ Requires-Dist: pyautogui; extra == "vision"
22
+ Requires-Dist: pytesseract; extra == "vision"
23
+ Requires-Dist: pynput; extra == "vision"
24
+ Requires-Dist: opencv-python; extra == "vision"
25
+ Requires-Dist: numpy; extra == "vision"
26
+ Dynamic: author
27
+ Dynamic: author-email
28
+ Dynamic: classifier
29
+ Dynamic: description
30
+ Dynamic: description-content-type
31
+ Dynamic: keywords
32
+ Dynamic: license
33
+ Dynamic: license-file
34
+ Dynamic: provides-extra
35
+ Dynamic: requires-dist
36
+ Dynamic: requires-python
37
+ Dynamic: summary
38
+
39
+ # Nano-Wait Vision Module
40
+
41
+ Nano-Wait agora inclui um módulo de **Visão Inteligente**, capaz de ler números diretamente da tela e tomar decisões automáticas em aplicativos ou vídeos.
42
+
43
+ ## Funcionalidades principais
44
+
45
+ - **Múltiplas regiões**: capture números de várias áreas da tela ao mesmo tempo.
46
+ - **Marcação interativa**: selecione regiões da tela facilmente usando o mouse com `mark_region()`.
47
+ - **Modos inteligentes**:
48
+ - `observe`: apenas lê e exibe números.
49
+ - `decision`: lê números e executa ações automáticas com base em valores.
50
+ - `learn`: registra padrões visuais para uso futuro.
51
+ - **Ações automatizadas**: clique duplo, pular itens, etc.
52
+ - Compatível com macOS, Windows e Linux.
53
+
54
+ ## Instalação
55
+
56
+ ```bash
57
+ pip install -e .
58
+ # Dependências para o módulo de visão
59
+ pip install pyautogui pytesseract pynput opencv-python-headless
60
+ # macOS: instale o Tesseract OCR
61
+ brew install tesseract
@@ -0,0 +1,13 @@
1
+ nano_wait/__init__.py,sha256=e2HO0pyr_xEYzPE-FD-Sq8gL3qRWdaovvpYv4uG608U,1287
2
+ nano_wait/__main__.py,sha256=MSmt_5Xg84uHqzTN38JwgseJK8rsJn_11A8WD99VtEo,61
3
+ nano_wait/cli.py,sha256=clYKsF36N4Fij6bH5vkzC4kXdOelpz32RcjoloHoZdY,1854
4
+ nano_wait/core.py,sha256=n8bp7EI6lNwd-uceclHVmF49ZuxQItbI7etdijB5zFQ,2551
5
+ nano_wait/nano_wait.py,sha256=XfefZQ0RgT3lhC2UZ1rQS-UC9HoG8sP3XMH3RjZUoG4,1091
6
+ nano_wait/utils.py,sha256=28qjlES2Yw69mvaj52mmnRqWjtpxu3aG1GwG29dvBYw,486
7
+ nano_wait/vision.py,sha256=4lx4pfbbhHpNby83A1vJDB7k38YVBc3Sym5O0O7nUwc,3912
8
+ nano_wait-3.0.dist-info/licenses/LICENSE,sha256=iu3NnVehM00ZoIpIVkl44-9mCgXVh9iGYMZYXtMv0Mc,1084
9
+ nano_wait-3.0.dist-info/METADATA,sha256=Q2jmJS9M_NcWxZWFA8FiZsxS-ZC471i8MZ-XW21C2v0,2206
10
+ nano_wait-3.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
11
+ nano_wait-3.0.dist-info/entry_points.txt,sha256=IISprKfo-qF43ML7ywqV22rUrTm0Gi2y_DpAN03kZhA,49
12
+ nano_wait-3.0.dist-info/top_level.txt,sha256=dSiF3Wc3ZEB1pzcp_ubHZeb0OE7n1nPMntkL48uz6aI,10
13
+ nano_wait-3.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (70.1.0)
2
+ Generator: setuptools (80.9.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ nano-wait = nano_wait.cli:main
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Luiz Filipe Seabra de marco
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Luiz Filipe Seabra de marco
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,388 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: nano_wait
3
- Version: 1.3
4
- Summary: Waiting Time Calculation for Automations Based on WiFi and PC Processing
5
- Author: Luiz Filipe Seabra de Marco
6
- Author-email: luizfilipeseabra@icloud.com
7
- License: MIT License
8
- Keywords: automation automação wifi wait
9
- Description-Content-Type: text/markdown
10
- License-File: LICENSE
11
- Requires-Dist: psutil
12
- Requires-Dist: pywifi
13
-
14
- """
15
- nano_wait.py
16
-
17
- Official Nano-Wait Library: Precise and Adaptive Waiting in Python ⚡
18
-
19
- Description: This library allows you to perform adaptive waiting based on the current performance of your computer
20
-
21
- ### 📦 Installation
22
-
23
-
24
- ⚠️ To download it is necessary to have two libraries to work, run in the terminal 'pip install psutil pywifi⚠️
25
-
26
- ### Compatibility
27
-
28
- ⚠️ Compatibility: For now it only works on Windows, we are working on it now :) ⚠️
29
-
30
- ### Version
31
-
32
- Version: 1.2
33
- License: MIT
34
-
35
- ### formulas
36
-
37
- Formulas used in the NanoWait library:
38
-
39
- 1) PC Score Calculation:
40
- Evaluates how "free" your computer is based on CPU and memory usage::
41
-
42
- cpu_score = max(0, min(10, 10 - cpu_usage / 10))
43
-
44
- memory_score = max(0, min(10, 10 - memory_usage / 10))
45
-
46
- pc_score = (cpu_score + memory_score) / 2
47
-
48
- 2) Wi-Fi Score calculation:
49
- Converts Wi-Fi signal strength (in dBm) to a scale of 0 to 10:
50
-
51
- wifi_score = max(0, min(10, (signal_strength + 100) / 10))
52
-
53
- Example: If the signal is -60 dBm,
54
- wifi_score = (-60 + 100) / 10 = 4
55
-
56
- 3) Combined Risk Score Calculation (PC + Wi-Fi):
57
-
58
- risk_score = (pc_score + wifi_score) / 2
59
-
60
- 4) Wi-Fi standby time (wait_wifi):
61
-
62
- wait_time = max(1, (10 - risk_score) / speed)
63
-
64
- 5) Waiting time without Wi-Fi (wait_n_wifi):
65
-
66
- wait_time = max(1, (10 - pc_score) / speed)
67
-
68
- Variable legend:
69
-
70
- | Variable | Description |
71
- |------------------|---------------------------------------|
72
- | cpu_usage | Current CPU usage (%) |
73
- | memory_usage | Current RAM usage (%) |
74
- | signal_strength | Wi-Fi signal strength (in dBm) |
75
- | speed | Speed factor (example: 1 to 10) |
76
- """
77
-
78
- import pywifi
79
- import psutil
80
- import time
81
-
82
-
83
- class NanoWait:
84
- """
85
- Core class of the Nano-Wait library.
86
- Allows you to calculate wait times based on the machine's current performance and Wi-Fi quality.
87
- """
88
-
89
- def __init__(self):
90
- """
91
- Initializes Wi-Fi modules, if available.
92
- """
93
- self.wifi = pywifi.PyWiFi()
94
- self.interface = self.wifi.interfaces()[0]
95
-
96
- def get_wifi_signal(self, ssid: str) -> float:7
97
-
98
- """Returns a score from 0 to 10 based on the Wi-Fi signal strength for the given SSID.
99
-
100
- Args:
101
- ssid (str): Name of the Wi-Fi network to be analyzed.
102
-
103
- Returns:
104
- float: Wi-Fi quality rating between 0 (poor) and 10 (excellent).
105
- """
106
- try:
107
- self.interface.scan()
108
- time.sleep(2) # Wait for the scan to complete
109
- scan_results = self.interface.scan_results()
110
-
111
- signal_strength = -100 # Default weak signal value
112
-
113
- for network in scan_results:
114
- if network.ssid == ssid:
115
- signal_strength = network.signal
116
- break
117
- else:
118
- raise ValueError(f"Wi-Fi network '{ssid}' not found.")
119
-
120
- wifi_score = max(0, min(10, (signal_strength + 100) / 10))
121
- return wifi_score
122
-
123
- except Exception as e:
124
- print(f"[WiFi Error] {e}")
125
- return 0
126
-
127
- def get_pc_score(self) -> float:
128
- """
129
- Returns a score from 0 to 10 based on current CPU and RAM usage.
130
-
131
- Returns:
132
- float: Rating between 0 (overload) and 10 (light performance).
133
- """
134
- try:
135
- cpu_usage = psutil.cpu_percent(interval=1)
136
- memory_usage = psutil.virtual_memory().percent
137
-
138
- cpu_score = max(0, min(10, 10 - cpu_usage / 10))
139
- memory_score = max(0, min(10, 10 - memory_usage / 10))
140
-
141
- pc_score = (cpu_score + memory_score) / 2
142
- return pc_score
143
-
144
- except Exception as e:
145
- print(f"[PC Score Error] {e}")
146
- return 0
147
-
148
- def wait_wifi(self, speed: float, ssid: str) -> float:
149
- """
150
- Calculates the wait time based on PC performance and Wi-Fi quality.
151
-
152
- Args:
153
- speed (float): Speed factor. Higher values result in shorter wait times.
154
- ssid (str): Name of the Wi-Fi network to be analyzed.
155
-
156
- Returns:
157
- float: Recommended wait time.
158
- """
159
- try:
160
- pc_score = self.get_pc_score()
161
- wifi_score = self.get_wifi_signal(ssid)
162
-
163
- risk_score = (pc_score + wifi_score) / 2
164
- wait_time = max(1, (10 - risk_score) / speed)
165
- return wait_time
166
-
167
- except Exception as e:
168
- print(f"[Wait_wifi Error] {e}")
169
- return 1
170
-
171
- def wait_n_wifi(self, speed: float) -> float:
172
- """
173
- Calculates the wait time based only on the PC's performance (no Wi-Fi).
174
-
175
- Args:
176
- speed (float): Speed factor.
177
-
178
- Returns:
179
- float: Recommended wait time.
180
- """
181
- try:
182
- pc_score = self.get_pc_score()
183
- wait_time = max(1, (10 - pc_score) / speed)
184
- return wait_time
185
-
186
- except Exception as e:
187
- print(f"[Error wait_n_wifi] {e}")
188
- return 1
189
-
190
- def nano_wait(self, t: float, use_wifi: bool = False, ssid: str = "", speed: float = 1.5) -> None:
191
- """
192
- Main library function. Adaptively waits for precisely t seconds.
193
-
194
- The wait is divided between passive time (with time.sleep) and active time (status check).
195
-
196
- Args:
197
- t (float): Desired total wait time, in seconds.
198
- use_wifi (bool): If True, considers the Wi-Fi network status in the analysis.
199
- ssid (str): Wi-Fi network name (required if use_wifi=True).
200
- speed (float): Adaptive speed. Higher values result in shorter waits.
201
- """
202
- try:
203
- if use_wifi:
204
- if not ssid:
205
- raise ValueError("SSID required when use_wifi=True")
206
- wait_time = self.wait_wifi(speed, ssid)
207
- else:
208
- wait_time = self.wait_n_wifi(speed)
209
-
210
- t_passive = max(0, t - wait_time)
211
- t_active = min(t, wait_time)
212
-
213
- time.sleep(t_passive)
214
-
215
- start = time.time()
216
- while (time.time() - start) < t_active:
217
- continue # Active wait — ensures accuracy at the end of the wait
218
-
219
- except Exception as e:
220
- print(f"[Error nano_wait] {e}")
221
- time.sleep(t) # fallback: simple wait
222
-
223
- # Usage examples (to put in a separate file or test interactively):
224
-
225
- # Usage example without Wi-Fi
226
- # import time
227
- # from nano_wait.nano_wait import NanoWait
228
-
229
- # automation = NanoWait()
230
- # speeds = 10
231
- # wait_time = automation.wait_n_wifi(speed=speeds)
232
- # time.sleep(wait_time)
233
-
234
- # Usage example with Wi-Fi
235
- # ssid = "WiFiNetworkName"
236
- # wait_time = automation.wait_wifi(speed=speeds, ssid=ssid)
237
- # time.sleep(wait_time)
238
-
239
- # How much more efficient would it be?
240
- # Efficiency Comparison: NanoWait vs. Fixed Wait (Guess)
241
-
242
- This snippet mathematically explains how much the NanoWait library can improve wait time efficiency compared to a fixed wait performed by "guessing."
243
-
244
- ---
245
-
246
- ## Formula for calculating adaptive wait time (NanoWait)
247
-
248
- For Wi-Fi, the wait time is calculated by:
249
-
250
- \[
251
- wait\_time = \max\left(min\_wait, \frac{10 - risk\_score}{speed}\right)
252
- \]
253
-
254
- Where:
255
-
256
- - \( risk\_score = \frac{pc\_score + wifi\_score}{2} \) — combined score of the computer's performance and Wi-Fi network quality (varies between 0 and 10).
257
- - \( speed \) — configurable factor that indicates the desired speed (higher values generate shorter wait times).
258
- - \( min\_wait \) — minimum wait time allowed (example: 0.05 seconds).
259
-
260
- ---
261
-
262
- ## Percentage Gain Calculation
263
-
264
- The percentage gain in efficiency, comparing the fixed wait \( t_{fixed} \) with the adaptive wait time \( wait\_time \), is:
265
-
266
- \[
267
- G = \frac{t_{fixed} - wait\_time}{t_{fixed}} \times 100\%
268
- \]
269
-
270
- ---
271
-
272
- ## Example Scenarios
273
-
274
- ### Scenario A — Very Good PC and Wi-Fi
275
-
276
- - \( pc\_score = 9 \)
277
- - \( wifi\_score = 9 \)
278
- - \( risk\_score = 9 \)
279
- - \( speed = 10 \)
280
- - \( min\_wait = 0.05 \) seconds
281
-
282
- Calculating the wait time:
283
-
284
- \[
285
- wait\_time = \max(0.05, \frac{10 - 9}{10}) = \max(0.05, 0.1) = 0.1 \text{ seconds}
286
- \]
287
-
288
- If the fixed time is 0.2 seconds, the gain is:
289
-
290
- \[
291
- G = \frac{0.2 - 0.1}{0.2} \times 100\% = 50\%
292
- \]
293
-
294
- **Conclusion:** NanoWait halves the wait time.
295
-
296
- ---
297
-
298
- ### Scenario B — Reasonable PC and Poor Wi-Fi
299
-
300
- - \( pc\_score = 5 \)
301
- - \( wifi\_score = 3 \)
302
- - \( risk\_score = 4 \)
303
- - \( speed = 5 \)
304
- - \( min\_wait = 0.05 \) seconds
305
-
306
- Calculating the wait time:
307
-
308
- \[
309
- wait\_time = \max(0.05, \frac{10 - 4}{5}) = \max(0.05, 1.2) = 1.2 \text{ seconds}
310
- \]
311
-
312
- If the fixed time is 1 second, the gain is:
313
-
314
- \[
315
- G = \frac{1 - 1.2}{1} \times 100\% = -20\%
316
- \]
317
-
318
- **Conclusion:** Longer wait to ensure stability, which is important to avoid errors.
319
-
320
- ---
321
-
322
- ### Scenario C — Good PC, Average Wi-Fi
323
-
324
- - \( pc\_score = 8 \)
325
- - \( wifi\_score = 5 \)
326
- - \( risk\_score = 6.5 \)
327
- - \( speed = 10 \)
328
- - \( min\_wait = 0.05 \) seconds
329
-
330
- Calculating the wait time:
331
-
332
- \[
333
- wait\_time = \max(0.05, \frac{10 - 6.5}{10}) = \max(0.05, 0.35) = 0.35 \text{ seconds}
334
- \]
335
-
336
- If the fixed time is 0.5 seconds, the gain is:
337
-
338
- \[
339
- G = \frac{0.5 - 0.35}{0.5} \times 100\% = 30%
340
- \]
341
-
342
- **Conclusion:** 30% savings in total wait time.
343
-
344
- ---
345
- ## Summary
346
-
347
- | Condition | Estimated Gain (%) |
348
- |-------------------|-----------------------------------|
349
- | Very good PC and Wi-Fi | Up to 50% reduction in wait time |
350
- | Reasonable PC, poor Wi-Fi | Can increase the time for robustness |
351
- | Good PC, average Wi-Fi | Approximately 20% to 35% savings |
352
-
353
- ---
354
-
355
- ## Practical Benefits of NanoWait
356
-
357
- - **Adaptive time savings**: wait time decreases when the system is under stress.
358
- - **Robustness**: time increases when the system is under stress, avoiding errors.
359
- - **Customization**: the `speed` parameter allows you to adjust the behavior to your needs.
360
-
361
- ---
362
-
363
- In other words, on average, it's a 20% to 50% increase in efficiency.
364
-
365
- ---
366
-
367
- ### ⚠️ Error Handling
368
-
369
- The **Nano-Wait** library is designed with robust fallback mechanisms to ensure stability, even under unexpected conditions.
370
-
371
- #### ✅ How the library behaves in case of failures:
372
-
373
- | Scenario | Behavior |
374
- |---------------------------------|--------------------------------------------------------------------------|
375
- | **Wi-Fi network not found** | Returns a Wi-Fi score of `0` and logs: `[WiFi Error]` |
376
- | **CPU or RAM usage unavailable**| Returns a PC score of `0` and logs: `[PC Score Error]` |
377
- | **Unexpected internal error** | Falls back to `time.sleep(t)` and logs: `[Error nano_wait]` |
378
-
379
- #### 🔐 Why this matters:
380
-
381
- - Ensures **safe execution** even when the system is under high load or lacks necessary permissions.
382
- - Avoids crashes by using default behaviors in case of unexpected conditions.
383
- - Ideal for **automation scripts** and **real-time systems** that require reliability and resilience.
384
-
385
- ### Authors
386
-
387
- Author: Luiz Filipe Seabra de Marco and Vitor Seabra
388
- (and optionally the Wi-Fi network), ideal for applications that disable more intelligent waiting time control.Official Nano-Wait Library: Accurate and Adaptive Waiting in Python ⚡
@@ -1,7 +0,0 @@
1
- nano_wait/__init__.py,sha256=I5jtVftNdesvR689O2eOz3CeTAtFs8ZP5GJhn7RrQvA,24
2
- nano_wait/nano_wait.py,sha256=k1ENwE77qY687iAdMGIVZYlrDpV_ErNpXeOIX7JdWH0,2431
3
- nano_wait-1.3.dist-info/LICENSE,sha256=h77N3ma56KwtT-tI-UQ8LntVneq5t506SCJXmdTx5-Y,1105
4
- nano_wait-1.3.dist-info/METADATA,sha256=be9LJw0AjtT9aoE8S5TeliTItQorq2kJJawpDm6pvsg,10719
5
- nano_wait-1.3.dist-info/WHEEL,sha256=cpQTJ5IWu9CdaPViMhC9YzF8gZuS5-vlfoFihTBC86A,91
6
- nano_wait-1.3.dist-info/top_level.txt,sha256=dSiF3Wc3ZEB1pzcp_ubHZeb0OE7n1nPMntkL48uz6aI,10
7
- nano_wait-1.3.dist-info/RECORD,,