Advertisement
egor230

Голосовой_ввод_текста_яндекс_в_linux.py

Oct 26th, 2024 (edited)
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 19.52 KB | Source Code | 0 0
  1. from libs_voice import *
  2. driver=0
  3. previous_message = None
  4. try:
  5.    option= get_option()
  6.    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()),
  7.                             options=option)
  8.    driver.set_window_size(553, 357) # optiol
  9.    driver.get("https://alice.yandex.ru/chat/01938823-14ea-4000-bd7a-3cca57830d6a/")# открыть сайт
  10.  
  11.    # driver.set_window_position(1, 505)
  12.    # Размер окна: Ширина = 693, Высота = 407
  13.    # Координаты окна: X = 662, Y = 292
  14.    # print(counts)
  15.    excluded_phrases = [
  16.     "С чего начнём?Нарисовать картинку",
  17.     "Для звонков телефон как-то удобнее, давайте попробую там.",
  18.     "Яндекс — с АлисойБыстрый поиск и Алиса всегда рядомПоиск текстом, картинкой или голосомУмная",
  19.     "Три заветных слова: мобильное приложение Яндекса. Там такое наверняка можно сделать."
  20.    ]   # input()      # Получение текущего адреса страницы
  21.  
  22.    # Даём странице время загрузиться
  23.    driver.implicitly_wait(5)
  24.    # Находим все кнопки с классом chat-list-item__chat svelte-tfr5dl
  25.    buttons = driver.find_elements(By.CSS_SELECTOR, "button.chat-list-item__chat.svelte-tfr5dl")
  26.    buttons[0].click()
  27.    button = WebDriverWait(driver, 5).until(
  28.      EC.element_to_be_clickable((By.CSS_SELECTOR, 'div[aria-label="Алиса, начни слушать"]'))
  29.    )
  30.    button.click()
  31.    # html_content = driver.page_source
  32.    # with open('page_content.html', 'w', encoding='utf-8') as file:
  33.    #    file.write(html_content)
  34.  
  35.    driver.execute_script("document.querySelector('.standalone__header').style.display='none';")
  36.    driver.execute_script(
  37.      "var element = document.querySelector('.standalone__sidebar'); element.parentNode.removeChild(element);")
  38.  
  39.    url = driver.current_url
  40.  
  41.    lottie = driver.find_element(By.CSS_SELECTOR, '[data-testid="oknyx-lottie-listening"]')
  42.  
  43.    # JavaScript для поиска активного <svg> и группы <g>
  44.    script = """
  45.   const lottie = document.querySelector('[data-testid="oknyx-lottie-listening"]');
  46.   const activeSvg = Array.from(lottie.querySelectorAll('svg')).find(svg =>
  47.       !svg.classList.contains('animation-hidden') && svg.style.display !== 'none'
  48.   );
  49.   if (activeSvg) {
  50.       const activeGroup = Array.from(activeSvg.querySelectorAll('g[filter]')).find(g =>
  51.           g.style.display !== 'none'
  52.       );
  53.       if (activeGroup) {
  54.           const filterAttr = activeGroup.getAttribute('filter');
  55.           const match = filterAttr.match(/#__lottie_element_(\\d+)/);
  56.           return match ? parseInt(match[1]) : null;
  57.       }
  58.   }
  59.   return null;
  60.   """
  61.  
  62.  
  63.    def get_last_three_messages(driver, class_name):
  64.     # Найти все элементы с заданным классом
  65.     messages = driver.find_elements(By.CLASS_NAME, class_name)
  66.     # Получить текст последних трех элементов
  67.     last_three_messages = [message.text.strip() for message in messages[-3:]]
  68.     return last_three_messages
  69.    def get_latest_message(driver, previous_message="", len_c=0):
  70.     try:
  71.        ms = driver.find_elements(By.CLASS_NAME, 'message-bubble')
  72.        counts = len(ms)
  73.        ms = driver.find_elements(By.CLASS_NAME, 'message-bubble_container_from-user')
  74.        # print( ms[-1].text.strip())
  75.        # print( ms[-1].find_element(By.CLASS_NAME, 'markdown-text').text.strip())
  76.        # print("user")
  77.        # ms = driver.find_elements(By.CLASS_NAME, 'message-bubble_container_from-user')
  78.        think= driver.find_element(By.CLASS_NAME, "chat__thinking")
  79.        ms = get_last_three_messages(driver, 'message-bubble_container_from-user')# Это все мои сообщения только от меня
  80.        print(ms)
  81.        previous_message = ms[-1]
  82.        if previous_message and think.is_displayed():#
  83.          return previous_message, counts
  84.        else:
  85.  
  86.          ms = get_last_three_messages(driver, 'message-bubble')
  87.          print(ms)
  88.          previous_message = ms[-2]
  89.          if counts % 2 == 0 and previous_message:
  90.           previous_message = ""
  91.           return previous_message, counts
  92.          else:
  93.           previous_message = ""
  94.           return previous_message, counts
  95.     except NoSuchElementException as ex:
  96.        return previous_message, len_c
  97.     except Exception as ex:       # Обработка неожиданных ошибок
  98.       # print(f"Произошла непредвиденная ошибка: {ex}")
  99.       pass       #
  100.    previous_message, counts = get_latest_message(driver)
  101.    while True:
  102.      try:
  103.       # time.sleep(0.33)      # Найдите кнопку микрофона
  104.       mic_button = driver.find_element(By.CSS_SELECTOR, 'div.yamb-oknyx')      # Получите значение aria-label
  105.       aria_label = mic_button.get_attribute('aria-label')      # Проверяем, активен ли микрофон   # print( counts1)
  106.       current_url = driver.current_url    # Получение текущего адреса страницы
  107.       if url not in current_url:   # Проверка, содержится ли в адресе строка "/alice.yandex.ru/chat/"     # Переход на нужный URL
  108.         driver.get(url)
  109.         pass
  110.       if  'Алиса, стоп'  in aria_label:#        print("on")
  111.        previous_message1, counts1 = get_latest_message(driver, previous_message, counts)
  112.        if (counts1 > counts and len(previous_message1) !=0 and not any(phrase in previous_message1 for phrase in excluded_phrases)):
  113.           print("+++++++")
  114.           counts=counts1          #  break
  115.           thread = threading.Thread(target=process_text, args=(previous_message1, k,))        #  break  #
  116.           #thread.daemon
  117.           thread.start()
  118.           thread.join()
  119.       else:        # print("ло")
  120.         button.click()
  121.        # Находим активный <svg> (без класса animation-hidden и без display: none)
  122.       # Выполняем скрипт и получаем результат
  123.       # number = driver.execute_script(script)
  124.      except Exception as ex2:
  125.        # print(ex2)
  126.        pass
  127.  
  128.    t1 = threading.Thread(target=a)
  129.    t1.start()
  130. except Exception as ex1:
  131.   pass  # print(number)
  132.  
  133.   # Находим элемент по data-testid
  134.   # Проверяем активный <svg>
  135.   # for svg in svg_elements:
  136.   #   class_attr = svg.get_attribute('class')
  137.   #   style_attr = svg.get_attribute('style')
  138.   #   if 'animation-hidden' not in class_attr and 'display: none' not in style_attr:
  139.   #     inner_html = svg.get_attribute('innerHTML')
  140.   #     print(inner_html)
  141.   # if '<circle' in inner_html:
  142.   #   print("Текущее состояние: пульсирующий кружочек")
  143.  
  144.  
  145.  
  146.  
  147.   #  # Получение размера окна
  148.   # window_size = driver.get_window_size()
  149.   # width = window_size['width']
  150.   # height = window_size['height']
  151.   # print(f"Размер окна: Ширина = {width}, Высота = {height}")
  152.   #
  153.   # # Получение координат окна
  154.   # window_position = driver.get_window_position()
  155.   # x = window_position['x']
  156.   # y = window_position['y']
  157.   # print(f"Координаты окна: X = {x}, Y = {y}")
  158.   # for message in messages:
  159.   #  print("Элемент найден:", message.get_attribute("outerHTML"))
  160.   # think = driver.find_element(By.CLASS_NAME, "animation-hidden")
  161.   # print("Элемент найден:", think.get_attribute("outerHTML"))
  162.   #  print("Элемент 'chat__thinking' найден.")
  163.   # # Получаем и выводим все атрибуты
  164.   #  print("HTML:", think.get_attribute("outerHTML"))
  165.   #  print("Классы:", think.get_attribute("class"))
  166.   #  print("Стили:", think.get_attribute("style"))
  167.   #  print("Видим ли:", think.is_displayed())
  168.   # if counts % 2 == 0 and counts != 0:       # Если текста напрямую нет, ищем вложенный элемент с классом markdown-text
  169.   # time.sleep(2.82)
  170.   # user_messages = driver.find_elements(By.CLASS_NAME, "message-bubble_container_from-user")
  171.   # previous_message1 = user_messages[-1].find_element(By.CLASS_NAME, "message-bubble").text
  172.   #
  173.   # messages = driver.find_elements(By.CLASS_NAME, 'message-bubble_container_from-user')
  174.   # counts = len(messages)
  175.   # if previous_message != previous_message1:
  176.   #   time.sleep(1.12)
  177.   #   return "", len_c
  178.   # else:
  179.   #   return previous_message1, counts
  180.   # # Ищем все элементы <button>
  181.   # buttons = driver.find_elements(By.TAG_NAME, "button")
  182.   #
  183.   # # Ищем все кликабельные элементы <a> (если они тоже могут быть кнопками)
  184.   # links = driver.find_elements(By.TAG_NAME, "a")
  185.  
  186.   # Ожидаем, пока кнопка переключения режима станет доступной и кликаем
  187.   # wait = WebDriverWait(driver, 4)
  188.   # switch_button = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "model-switcher__button")))
  189.   # switch_button.click()
  190.   #
  191.   # wait = WebDriverWait(driver, 4)
  192.   # basic_mode_button = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(., 'Базовый режим')]")))
  193.   # basic_mode_button.click()
  194.   # Ищем все кнопки с классом "chat-list-item__chat svelte-tfr5dl"
  195.   # buttons = driver.find_elements(By.CLASS_NAME, "chat-list-item__chat")
  196.   # Выводим полный список кнопок
  197.   # print("Найденные кнопки с классом 'chat-list-item__chat svelte-tfr5dl':")
  198.   # for i, button in enumerate(buttons, 1):    # Получаем текст кнопки (если есть)
  199.   #   button_text = button.text.strip() if button.text.strip() else "Без текста"
  200.   #   # Получаем HTML-код элемента
  201.   #   button_code = button.get_attribute("outerHTML")
  202.   #   print(f"Кнопка {i}: Текст - {button_text}, HTML - {button_code}")
  203.   # if i == 2:  # Сравниваем с номером кнопки         # Кликаем на сам элемент button (а не на его HTML-код)
  204.   # button.click()         # Ждём появления кнопки "Удалить"
  205.   # try:
  206.   #   b= driver.find_element(By.CSS_SELECTOR, "button.chat-list-item__more-btn.svelte-tfr5dl")
  207.   #   # print(f"  Код кнопки '3 точки': {b.get_attribute('outerHTML')}\n")
  208.   #        # Кликаем на "3 точки"
  209.   #   b.click()
  210.   # except:
  211.   #   print("Кнопка 'Удалить' не найдена в течение 10 секунд.")
  212.   # break  # Выходим из цикла после обработки 144-й кнопки
  213.   # Ищем кнопку с нужным текстом и нажимаем на нее
  214.   # for button in buttons:
  215.   #   print(button)
  216.   # if button.text == "напиши пожалуйста какие из этих пакетов надо установить и каких":
  217.   #   button.click()
  218.   #   break  # Выходим из цикла после нажатия на нужную кнопку
  219.   # # Проходим по каждой кнопке и нажимаем на нее
  220.   # for button in buttons:
  221.   #   button_text = button.text.strip() if button.text.strip() else "Без текста"
  222.   #   # Получаем HTML-код элемента
  223.   #   button_code = button.get_attribute("outerHTML")
  224.   #   print(f"Кнопка {button}: Текст - {button_text}, HTML - {button_code}")
  225.   # try:
  226.   #     think = WebDriverWait(driver, 2).until(
  227.   #         EC.presence_of_element_located((By.CLASS_NAME, "chat__thinking"))
  228.   #     )
  229.   # except TimeoutException:
  230.   #     print("Элемент с классом 'chat__thinking' не найден за 10 секунд.")
  231.   # think = driver.find_element(By.CLASS_NAME, "animation-hidden")
  232.   # Если элемент 'chat__thinking' не найден за 10 секунд
  233.   # if len(messages) % 2 == 0 and len(messages) != 0:
  234.   # print("2")
  235.   #      previous_message = messages[-2].text.strip()
  236.   #     if previous_message:
  237.   #      user_messages = soup.find_all("div", class_="chat__message")
  238.   #    print(user_messages.get_text(strip=True))
  239.   # messages1 = soup.find_all('div', class_='message-bubble_container')
  240.   # На случай, если что-то пошло не так с другими элементами
  241.   # print(f"Ошибка поиска элемента: {ex}")
  242.   # messages = soup.find_all('div', class_='message-bubble')
  243.   # counts = len(messages)
  244.   # user_messages = soup.find_all("div", class_="message-bubble_container_from-user")
  245.   # think = driver.find_element(By.CLASS_NAME, "chat__thinking")
  246.   # previous_message = user_messages[-1].find('div', class_='message-bubble').get_text(strip=True)
  247.   # if think and user_messages:  # Если сообщения найдены, берем последнее
  248.  
  249.  
  250.  
  251.    # user_messages = soup.find_all("div", class_="chat__message")
  252.    # if user_messages: # Если сообщения найдены, берем последнее
  253.    #   p = user_messages[-1].text.strip()
  254.    #   print(p)
  255.    # messages1 = soup.find_all('div', class_='message-bubble_container')
  256.    # if messages1:
  257.    #   if 'message-bubble_container_from-user' not in messages1[-1].get('class', []):
  258.    #     text = messages1[-1].find('div', class_='message-bubble').get_text(strip=True)
  259.        # print(text)
  260.     # print(previous_message)
  261.     #print(len(messages))
  262.     # Извлекаем текст из первого класса
  263.     # messages = soup.find_all('div', class_='message-bubble', attrs={'data-testid': ['message-bubble', 'data-id']})
  264.     # message = [message.get_text(strip=True) for message in messages]
  265.     # Если текста напрямую нет, ищем вложенный элемент с классом markdown-text
  266.     # previous_message = message[-2]#
  267.     # previous_message =messages[-2].get_text(strip=True)
  268.       # print("Последнее сообщение пользователя:", previous_message)
  269.           # t= time.time()
  270.           #thread.join()
  271.           #print(time.time()-t)
  272.   # input()
  273.   # # Получение размера окна
  274.   # window_size = driver.get_window_size()
  275.   # print(f"Ширина: {window_size['width']}, Высота: {window_size['height']}")
  276.             # Выводим только последнее сообщение
  277.         # input()
  278.          # time.sleep(3)
  279.     # input()
  280.     # driver.minimize_window()
  281.      # print("lkjn")
  282.      # if 'no such window: target window' in str(ex2):
  283.      #    print("exit no such window: target window already closed")
  284.      #    error_closse(driver)
  285.      # print(ex2)  # print("error")
  286.      # time.sleep(5)
  287.   # print(ex1)  # driver.close()  # driver.quit()
  288.     # html_content = driver.page_source
  289.     #
  290.     # # Сохраните HTML-код в файл
  291.     # with open('page_source.html', 'w', encoding='utf-8') as file:
  292.     #   file.write(html_content)
  293.     # time.sleep(6)
  294.     # input()
  295. #   input()
  296. #   # Найдите текущий текст
  297. #   current_message_text = soup.find('div', class_='message-bubble').get_text(strip=True)
  298. #
  299. #   # Сравните с предыдущим текстом
  300. #   if current_message_text != previous_message_text:
  301. #     print("Обновленный текст:", current_message_text)
  302. #     previous_message_text = current_message_text
  303. #
  304. #   # Подождите перед следующей проверкой
  305. #   time.sleep(3)  # Увеличьте или уменьшите время ожидания по необходимости
  306.  
  307. #   print("Остановка программы.")
  308. # # time.sleep(1.5)
  309. # # driver.find_element("id", "microphone").click()  # включить запись голоса
  310. # # time.sleep(2.91)
  311. # t2 = threading.Thread(target=t, args=(driver,))
  312. # t2.start()
  313. # while 1:
  314. #   try:
  315. #       # time.sleep(0.31)
  316. #       text0 = driver.find_element("id", "textEditor").text
  317. #       text = str(text0)
  318. #       if len(text) != 0 and text != None and text != "None":
  319. #         driver.find_element("id", "textEditor").clear()  # удалить старый текст.
  320. #         text = str(text.lower()) + str(" ")
  321. #         text = repeat(text, k)
  322. #         if k.get_flag() == True:
  323. #           k.set_flag(False)
  324. #           text0 = text[0].upper() + text[1:]
  325. #           press_keys(text0)
  326. #         else:
  327. #           press_keys(text)
  328. #         print("+++++++++++++++")
  329. #         mic(driver)
  330. #         # driver.find_element("id", "mic").click()  # включить запись голоса
  331. #         # time.sleep(0.35)
  332. #         # driver.find_element("id", "mic").click()  # включить запись голоса
  333. #         text = "None"
  334. #   except KeyboardInterrupt:
  335. #     error_closse(driver)
  336. #     break
  337. #
  338. #   except Exception as ex:    #
  339. #     print(ex)
  340. #     if 'HTTPConnectionPool'in str(ex):
  341. #       print("exit HTTPConnectionPool")    # except HTTPConnectionPool:
  342. #       error_closse(driver)
  343. #       break
  344. #
  345. #     if 'SIGKILL'in str(ex):
  346. #       print("exit SIGKILL")    # except HTTPConnectionPool:
  347. #       error_closse(driver)
  348. #       break
  349. #     if 'no such window: target window already closed'in str(ex):
  350. #       print("exit  target window  closed")
  351. #       error_closse(driver)
  352. #       break
  353. #     print("yex")
  354.  
  355.     # option.add_argument("--disable-dev-shm-usage")
  356.     # option.add_argument('--allow-running-insecure-content')
  357.     # adress = os.getcwd() + str('/chromedriver')
  358.     # s=Service(adress)
  359.     # # s=Service('/usr/local/bin/chromedriver')
  360.     # option.binary_location = '/usr/bin/google-chrome'
  361.     # s=Service('/mnt/89d7250f-eddb-4218-bdc6-018b7fdb958f/linux must have/chromedriver_linux64/chrome-linux64/chrome')
  362.     # driver.find_element("id","b-lang").click()
  363.     # res=driver.find_element("id","lang-menu-filter").send_keys("Russia")
  364.     #
  365.     # driver.execute_script("window.focus();")     # class ="wave effect-pulse"]     # class ="lang-option" data-code="ru-ru" data-country="Russia" data-language="Русский" >
  366.     # # < div class ="option-line-1" > Russian (Russia) < / div > < div class ="flag"
  367.     # # style="background-image: url(&quot;img/flags2/russia.webp&quot;);" > < / div > < div class ="option-line-2" > Русский (Россия) < / div > < / div >
  368.     # # driver.implicitly_wait(2)
  369.     # time.sleep(1.91)
  370.     # driver.execute_script("window.focus();")
  371.     # press_key_enter() # Клик по выбранному русскому языку
  372.     # time.sleep(2.81)
  373.     # driver.find_element("id", "modal-b-close-lang").click()  #
  374.     # time.sleep(2.81)
  375.  
  376.  
  377. # def t(driver):
  378. #  while 1:
  379. #     try:    # time.sleep(12.65)  # driver.find_element("class","p_edit dir_LTR").clear()  # удалить старый текст.
  380. #      text = driver.find_element("id", "speech-display").text
  381. #      text = str(text)
  382. #      if len(text) != 0 and text != '':      # print('time')
  383. #       time.sleep(5)
  384. #       text1 = str(driver.find_element("id", "speech-display").text)
  385. #       if text != text1 and len(text1) != 0 and text1 != None and text1 != "None":     #      print(time.time())        print("ch")
  386. #         pass
  387. #       else:
  388. #        text=""
  389. #        text1=''
  390. #        mic(driver)       # print("oikjuhyg")
  391. #        time.sleep(0.61)
  392. #      # else:
  393. #     except Exception as ex:
  394. #        # print(ex)
  395. #        pass
  396.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement