Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os, time, json, time, subprocess, re, threading, socket, uuid, time, glob, sys, threading
- from selenium import webdriver
- from selenium.common import TimeoutException, NoSuchElementException
- from webdriver_manager.chrome import ChromeDriverManager
- from selenium.webdriver.chrome.service import Service
- from selenium.webdriver.chrome.options import Options
- from selenium.webdriver.common.keys import Keys
- from pynput.keyboard import Key, Controller
- from pynput import *
- from urllib3 import HTTPConnectionPool
- from selenium.webdriver.common.by import By
- from selenium.webdriver.support.wait import WebDriverWait
- from selenium.webdriver.support import expected_conditions as EC
- from bs4 import BeautifulSoup
- from PIL import Image
- from io import BytesIO
- import pyaudio
- # import numpy as np
- # select,
- # import speech_recognition as sr
- def a():
- while 1:
- with keyboard.Listener(on_release=on_release, on_press=on_press) as listener:
- listener.join()
- def del_all_chats(driver):
- # Находим все чаты
- chat_items = driver.find_elements(By.CSS_SELECTOR, "li[class*='chat-list-item']")
- # Удаляем все, кроме первого
- for item in chat_items[1:]:
- more_button = item.find_element(By.CSS_SELECTOR, "button.chat-list-item__more-btn")
- more_button.click()
- try:
- delete_button = WebDriverWait(driver, 10).until(
- EC.element_to_be_clickable(
- (By.XPATH, "//div[contains(@class, 'context-menu-item') and .//span[text()='Удалить чат']]"))
- )
- delete_button.click()
- except:
- print(f"Не удалось удалить чат.")
- def cut_image(driver):# Получение скриншота всей страницы и сохранение его в файл
- screenshot = driver.get_screenshot_as_png()
- with open('screenshot.png', 'wb') as file:
- file.write(screenshot)
- # Открываем файл в бинарном режиме
- with open('screenshot.png', 'rb') as file:
- screenshot = file.read()
- # Загружаем скриншот в объект Image
- image = Image.open(BytesIO(screenshot))
- # Определяем размеры изображения
- width, height = image.size # Определяем координаты для правого нижнего угла
- # Например, вырезаем угол размером 200x200 пикселей
- left = width - 100
- top = height - 100
- right = width
- bottom = height
- # Обрезаем изображение
- cropped_image = image.crop((left + 50, top + 15, right - 13, bottom - 43))
- # Сохраняем или показываем результат
- cropped_image.save("cropped_corner.png")
- # with open('page_content.html', 'w', encoding='utf-8') as file:
- # file.write(html_content)
- # Найдите все элементы с классом message-bubble
- # html_content = driver.page_source # Используйте BeautifulSoup для парсинга HTML
- # soup = BeautifulSoup(html_content, 'html.parser')
- class save_key:
- def __init__(self):
- self.text = ""
- self.flag = False
- self.word = []
- self.res = {}
- self.new_res = {}
- self.driver = None
- def save_driver(self, driver):
- self.driver = driver
- def get_driver(self):
- return self.driver
- def save_text(self, text):
- self.text = text
- def get_text(self):
- return self.text
- def get_flag(self):
- return self.flag
- def set_flag(self, value):
- self.flag = value
- def update_dict(self):
- data = "/mnt/807EB5FA7EB5E954/Program Files/list for replacements.json" # файл настроек.
- if os.path.exists(data): # есть ли этот файл.
- with open(data, encoding="cp1251") as json_file: # загрузка настроек из файла.
- self.res = json.load(json_file) # проходимся по каждому элементу словаря
- for key in self.res.keys(): # Если ключ содержит '*', добавляем его в новый словарь
- if '*' in key:
- self.new_res[key] = self.res[key]
- for key in self.new_res.keys():
- del self.res[key]
- def get_dict(self): # словарь без *
- return self.res
- def get_new_dict(self): # словарь с *
- return self.new_res
- def save_words(self, w):
- self.word.clear()
- for i in w:
- self.word.append(i)
- def get_words(self):
- return self.word
- class get_lang:
- def __init__(self):
- self.text = ""
- def save_text(self, text):
- self.text = text
- def get_text(self):
- return self.text
- script = '''#!/bin/bash
- # Ищем идентификаторы процессов, содержащих слово "chrome"
- pids=$(pgrep -f "chrome")
- # Перебираем найденные идентификаторы процессов и отправляем им сигнал завершения
- for pid in $pids; do
- kill $pid
- done
- pids=$(pgrep -f "chromedriver")
- # Перебираем найденные идентификаторы процессов и отправляем им сигнал завершения
- for pid in $pids; do
- kill $pid
- done
- '''
- subprocess.call(['bash', '-c', script])
- k = save_key()
- k.update_dict()
- time.sleep(2.2)
- def error_closse(driver):
- # print("quit")
- subprocess.call(['bash', '-c', script])
- script1 = '''#!/bin/bash
- echo $pid
- kill $pid
- '''
- subprocess.call(['bash', '-c', script1])
- driver.close()
- driver.quit()
- # Завершение Python-скрипта
- sys.exit()
- def replace(match):
- res = k.get_dict()
- return res[match.group(0)]
- def repeat(text, k):
- k.save_text(text)
- text1 = ""
- res = k.get_dict()
- k.save_words(res)
- words = k.get_words()
- try:
- for i in words:
- text = k.get_text()
- reg = r'\b' + r'\b|\b'.join([i]) + r'\b'
- text1 = re.sub(reg, replace, text)
- k.save_text(text1)
- new_res = k.get_new_dict()
- for word, i in new_res.items():
- text = k.get_text()
- pattern = re.compile(re.escape(word), re.IGNORECASE)
- text1 = pattern.sub(i, text)
- k.save_text(text1)
- except Exception as ex:
- pass
- return text1
- def is_connected():
- try: # попытаемся установить соединение с google.com на порту 80
- socket.create_connection(('www.google.com', 80))
- return True
- except OSError:
- pass
- return False
- def process_text(previous_message1, k):
- text = repeat(previous_message1 + str(" "), k)
- if k.get_flag() == True:
- k.set_flag(False)
- text0 = text[0].upper() + text[1:]
- press_keys(text0)
- else:
- press_keys(text)
- def on_press(key): # обработчик клави. # print(key )
- key = str(key).replace(" ", "")
- if key == "Key.shift_r": # print("okl")
- k.set_flag(True)
- return True
- if key == "Key.space" or key =="Key.right" or key =="Key.left"\
- or key =="Key.down" or key =="Key.up":
- k.set_flag(False)
- return True
- if key == "Key.alt":
- driver=k.get_driver()
- k.update_dict()
- driver.find_element("id", "mic").click() # включить запись голоса
- time.sleep(2.5)
- driver.find_element("id", "mic").click() # включить запись голоса
- return True
- else:
- return True
- def on_release(key):
- pass
- return True
- def press_key_enter():
- script = '''#!/bin/bash
- xte 'key Return'
- '''
- subprocess.call(['bash', '-c', script])
- class save_ln:
- def __init__(self):
- self.text = ""
- def save_text(self, text):
- self.text = text
- def get_text(self):
- return self.text
- def press_keys(text): # xte 'keyup Shift_L'
- try:
- print(text)
- for char in text:
- if char == ' ':
- subprocess.call(['xdotool', 'key', '--delay', '9', 'space'])
- else:
- subprocess.call(['xdotool', 'type', '--delay', '9', char])
- time.sleep(0.03) # Уменьшение задержки
- except Exception as ex1:
- print(ex1)
- return
- def get_option():
- prefs = {'safebrowsing.enabled': True, "credentials_enable_service": False,
- "profile.password_manager_enabled": False, "profile.managed_default_content_settings.images": 0,
- # - Отключить загрузку CSS:
- # "profile.default_content_setting_values.javascript": 2, # - Отключить загрузку JavaScript:
- "profile.default_content_setting_values.cache": 0 # - Включить кэширование:
- }
- option = webdriver.ChromeOptions()
- option.add_experimental_option("prefs", prefs)
- option.add_experimental_option("excludeSwitches", ['enable-automation']) # убрать окно
- option.add_argument(
- "user-agent=Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.6367.118 Safari/537.36")
- option.add_argument("--disable-gpu")
- option.add_argument('--disable-infobars')
- option.add_experimental_option("excludeSwitches", ['enable-automation']) # убрать окно
- option.add_argument("--use-fake-ui-for-media-stream") # звук
- option.add_argument("--disable-popup-blocking") # блок всплывающих окон.
- option.add_argument("--disable-blink-features=AutomationControlled")
- option.add_argument('--disable-web-security')
- option.add_argument("--disk-cache-size=0")
- option.add_argument("--media-cache-size=0")
- option.add_argument("--automatic-wait-for-preview")
- option.add_argument("--enable-features=WebRtcHideLocalIpsWithMdns")
- option.add_argument("--disable-images")
- option.add_argument("--disable-extensions")
- option.add_argument("--no-sandbox")
- option.add_argument("--disable-autofill")
- option.add_argument("--disable-background-timer-throttling") # Отключение ограничения фоновых таймеров
- option.add_argument("--disable-background-networking") # Отключение фоновой сетевой активности
- option.add_argument(
- '--user-data-dir=/mnt/807EB5FA7EB5E954/софт/виртуальная машина/linux must have/python_linux/Project/google-chrome')
- return option
- # en = ['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F', 'g', 'G', 'h', 'H', 'i', 'I', 'j', 'J', 'k', 'K',
- # 'l', 'L', 'm', 'M', 'n', 'N', 'o', 'O', 'p', 'P', 'q', 'Q', 'r', 'R', 's', 'S', 't', 'T', 'u', 'U', 'v', 'V',
- # 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z', '.', ',']
- # ru = ['а', 'А', 'б', 'Б', 'в', 'В', 'г', 'Г', 'д', 'Д', 'е', 'Е', 'ё', 'Ё', 'ж', 'Ж', 'з', 'З', 'и', 'И', 'й', 'Й', 'к',
- # 'К', 'л', 'Л', 'м', 'М', 'н', 'Н', 'о', 'О', 'п', 'П', 'р', 'Р', 'с', 'С', 'т', 'Т', 'у', 'У', 'ф', 'Ф', 'х', 'Х',
- # 'ц', 'Ц', 'ч', 'Ч', 'ш', 'Ш', 'щ', 'Щ', 'ъ', 'Ъ', 'ы', 'Ы', 'ь', 'Ь', 'э', 'Э', 'ю', 'Ю', 'я', 'Я', '-', '+', ' ']
- #
- # ln = save_ln()
- #
- #
- # def get_current_keyboard_layout():
- # result = subprocess.run(['xset', 'q'], capture_output=True, text=True) # Проверка успешного выполнения команды
- # if result.returncode == 0: # Получение вывода команды
- # output = result.stdout # Определение текущей раскладки
- # if '00001000' in output: # print("en")
- # return "en"
- # elif '00000000' in output: # print("ru")
- # return "ru"
- # return None
- #
- #
- # def switch_language(ln): # print("opl")
- # script = f'''#!/bin/bash
- #
- # xte 'keydown Shift_L' 'keydown Alt_L' 'keyup Shift_L' 'keyup Alt_L'
- # '''
- # subprocess.call(['bash', '-c', script, '_'])
- # time.sleep(0.8)
- # # print(ln) # input() # print(get_current_keyboard_layout())
- # while (ln != get_current_keyboard_layout()):
- # time.sleep(1.9)
- # # print("ok")
- # ln.save_text(get_current_keyboard_layout()) # язык по умолчанию.
- # if ln.get_text() != get_current_keyboard_layout(): # print("sw")
- # switch_language(ln.get_text())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement