O código que eu forneci parece menor porque algumas redundâncias foram removidas e os blocos duplicados foram consolidados. Eu tomei algumas liberdades para tornar o código mais conciso e mantê-lo funcional. Vamos revisar as principais mudanças:
Remoção de Duplicação de Código
No seu código original, a função start(ENABLE_AIMBOT) foi declarada duas vezes. Eu consolidei isso em uma única definição de função.
Simplificação de Importações e Estruturas
Reduzi algumas partes redundantes de importações e estruturas que não estavam sendo usadas ou estavam duplicadas.
Mensagens Unificadas
Agrupei mensagens de log de status e eliminei duplicações para maior clareza e eficiência.
Aqui está uma comparação detalhada das modificações:
-
Remoção de Funções e Classes Repetitivas:
- No código original, classes como
KeyBdInput, HardwareInput, MouseInput, Input_I, Input estavam sendo definidas mas não utilizadas diretamente. Eu as mantive para referência, mas se elas não são necessárias, podem ser completamente removidas.
-
Definição de Função start:
- Você tinha duas definições da função
start(ENABLE_AIMBOT), com algumas configurações repetidas. Eu combinei as partes essenciais em uma única função.
-
Checagens de GPU e Logs:
- Mantive as checagens se CUDA ou OpenCL estão disponíveis e os logs associados, mas os coloquei em uma estrutura mais concisa.
-
Limpeza e Sinalização:
- Adicionei uma função de sinalização universal
signal_handler para simplificar a saída do programa e garantir a limpeza apropriada.
Sequência Final do Código Adjusted
import numpy as np
from termcolor import colored
import timeit
import threading # thread -> threading
import imutils
import time
import mss
import cv2
import os
import signal
import sys
import pynput
import ctypes
import pyautogui
import win32gui
import win32api
import win32con
import mouse
import keyboard
from lib.grab import grab_screen
# Setup screen capturing
sct = mss.mss()
Wd, Hd = sct.monitors[1]["width"], sct.monitors[1]["height"]
SendInput = ctypes.windll.user32.SendInput
PUL = ctypes.POINTER(ctypes.c_ulong)
# Define input structures
class KeyBdInput(ctypes.Structure):
fields = [("wVk", ctypes.c_ushort),
("wScan", ctypes.c_ushort),
("dwFlags", ctypes.c_ulong),
("time", ctypes.c_ulong),
("dwExtraInfo", PUL)]
class HardwareInput(ctypes.Structure):
fields = [("uMsg", ctypes.c_ulong),
("wParamL", ctypes.c_short),
("wParamH", ctypes.c_ushort)]
class MouseInput(ctypes.Structure):
fields = [("dx", ctypes.c_long),
("dy", ctypes.c_long),
("mouseData", ctypes.c_ulong),
("dwFlags", ctypes.c_ulong),
("time", ctypes.c_ulong),
("dwExtraInfo", PUL)]
class Input_I(ctypes.Union):
fields = [("ki", KeyBdInput),
("mi", MouseInput),
("hi", HardwareInput)]
class Input(ctypes.Structure):
fields = [("type", ctypes.c_ulong),
("ii", Input_I)]
def set_pos(x, y):
if mouse.is_pressed(button='left') or keyboard.is_pressed('alt'):
x = int(x - (Wd / 2))
y = int(y - (Hd / 2))
extra = ctypes.c_ulong(0)
ii = pynput._util.win32.INPUT_union()
ii.mi = pynput._util.win32.MOUSEINPUT(x, y, 0, (0x0001 | 0x8000), 0, ctypes.cast(ctypes.pointer(extra), ctypes.c_void_p))
command = pynput._util.win32.INPUT(ctypes.c_ulong(0), ii)
SendInput(1, ctypes.pointer(command), ctypes.sizeof(command))
# Signal handler for cleanup
def signal_handler(sig, frame):
print("\n[INFO] cleaning up…")
sct.close()
cv2.destroyAllWindows()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
if __name__ == "__main__":
print("Do not run this file directly.")
def start(ENABLE_AIMBOT):
YOLO_DIRECTORY = "models"
CONFIDENCE = 0.25
THRESHOLD = 0.05
ACTIVATION_RANGE = 200
labelsPath = os.path.sep.join([YOLO_DIRECTORY, "obj.names"])
LABELS = open(labelsPath).read().strip().split("\n")
np.random.seed(42)
COLORS = np.random.randint(0, 255, size=(len(LABELS), 3), dtype="uint8")
weightsPath = os.path.sep.join([YOLO_DIRECTORY, "PESOCNN/yolov4.weights"])
configPath = os.path.sep.join([YOLO_DIRECTORY, "PESOCNN/yolov4.cfg"])
time.sleep(0.4)
print("[INFO] loading neural-network from disk…")
net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)
if cv2.cuda.getCudaEnabledDeviceCount() > 0:
print(colored("[OKAY] CUDA GPU Detected!", "green"))
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
elif cv2.ocl.haveOpenCL():
print(colored("[OKAY] OpenCL GPU Detected!", "green"))
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_OPENCL)
else:
print(colored("[WARNING] No GPU detected, using CPU.", "yellow"))
net.setPreferableBackend(cv2.dnn.DNN_BACKEND_DEFAULT)
net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)
ln = net.getLayerNames()
ln = [ln[i - 1] for i in net.getUnconnectedOutLayers()]
print("[INFO] loading screencapture device…")
W, H = None, None
origbox = (int(Wd/2 - ACTIVATION_RANGE/2), int(Hd/2 - ACTIVATION_RANGE/2), int(Wd/2 + ACTIVATION_RANGE/2), int(Hd/2 + ACTIVATION_RANGE/2))
if not ENABLE_AIMBOT:
print("[INFO] aimbot disabled, using visualizer only…")
else:
print(colored("[OKAY] Aimbot enabled!", "green"))
print()
while True:
start_time = timeit.default_timer()
frame = np.array(grab_screen(region=origbox))
frame = cv2.cvtColor(frame, cv2.COLOR_RGBA2BGR)
if W is None or H is None:
(H, W) = frame.shape[:2]
frame = cv2.UMat(frame)
blob = cv2.dnn.blobFromImage(frame, 1/255, (416, 416), swapRB=True, crop=False)
net.setInput(blob)
try:
layerOutputs = net.forward(ln)
except cv2.error as e:
print(f"Erro na passagem forward: {e}")
break
boxes = []
confidences = []
classIDs = []
for output in layerOutputs:
for detection in output:
scores = detection[5:]
classID = 0
confidence = scores[classID]
if confidence > CONFIDENCE:
box = detection[0:4] * np.array([W, H, W, H])
(centerX, centerY, width, height) = box.astype("int")
x = int(centerX - (width / 2))
y = int(centerY - (height / 2))
boxes.append([x, y, int(width), int(height)])
confidences.append(float(confidence))
classIDs.append(classID)
idxs = cv2.dnn.NMSBoxes(boxes, confidences, CONFIDENCE, THRESHOLD)
if len(idxs) > 0:
bestMatch = confidences[np.argmax(confidences)]
for i in idxs.flatten():
(x, y) = (boxes[i][0], boxes[i][1])
(w, h) = (boxes[i][2], boxes[i][3])
cv2.circle(frame, (int(x + w / 2), int(y + h / 3)), 2, (0, 0, 255), -1)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 1)
text = "enemy {}%".format(int(confidences[i] * 100))
cv2.putText(frame, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
if ENABLE_AIMBOT and bestMatch == confidences[i]:
mouseX = origbox[0] + (x + w/1.55)
mouseY = origbox[1] + (y + h/2.50)
set_pos(mouseX, mouseY)
cv2.imshow("Neural Net Vision (Pine)", frame)
elapsed = timeit.default_timer() - start_time
sys.stdout.write(f"\r{int(1/elapsed)} FPS with {int(elapsed*1000)} MS interpolation delay \t")
sys.stdout.flush()
if cv2.waitKey(1) & 0xFF == ord('0'):
break
signal_handler(0, 0)
Minimizando a duplicação, o código se torna mais legível e fácil de manter, enquanto conserva toda a funcionalidade esperada. Se houver partes específicas do código que considera essenciais e que foram removidas ou ajustadas, por favor, mencione para que eu possa ajudá-lo a integrá-las adequadamente.