test3.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. import os
  2. # import requests
  3. # from bs4 import BeautifulSoup
  4. from selenium.webdriver.common.by import By
  5. # import re
  6. import time
  7. # from fake_useragent import UserAgent
  8. import undetected_chromedriver as uc
  9. from datetime import datetime
  10. import random
  11. import string
  12. # from selenium.webdriver.common.action_chains import ActionChains
  13. # from selenium.webdriver.common.keys import Keys
  14. # from selenium.webdriver.support.ui import WebDriverWait
  15. # from selenium.webdriver.support import expected_conditions as EC
  16. # from ga4mp import FirebaseMP
  17. from dotenv import load_dotenv
  18. import os
  19. # import shutil
  20. import logging
  21. from fastapi import APIRouter, FastAPI
  22. import uvicorn
  23. from fastapi.middleware.cors import CORSMiddleware
  24. from supabase import create_client, Client
  25. load_dotenv()
  26. logging.basicConfig(level=logging.INFO)
  27. SUPABASE_URL: str = os.environ.get('SUPABASE_URL')
  28. SUPABASE_KEY: str = os.environ.get('SUPABASE_KEY')
  29. supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
  30. def download_blob(browser, blob_url, filename='output.mp3'):
  31. # 使用 Selenium 獲取 Blob 內容
  32. js_code = f"""
  33. fetch('{blob_url}')
  34. .then(response => response.blob())
  35. .then(blob => {{
  36. const url = URL.createObjectURL(blob);
  37. const a = document.createElement('a');
  38. a.href = url;
  39. a.download = '{filename}';
  40. document.body.appendChild(a);
  41. a.click();
  42. document.body.removeChild(a);
  43. }})
  44. .catch(error => console.error('Error downloading file:', error));
  45. """
  46. browser.execute_script(js_code)
  47. def tts_downloadfile(text):
  48. start_time = time.time()
  49. print(f'text長度: {len(text)}')
  50. num = random.randint(3,5)
  51. url = 'http://tts001.iptcloud.net:8804/'
  52. # default_download_folder = os.path.join(os.path.expanduser('~'), 'Downloads')
  53. download_folder = '/var/www/html/innolux/downloads'
  54. file_name = datetime.now().strftime(f"%Y%m%d%H%M%S_{''.join(random.sample(string.ascii_lowercase, 3))}.wav")
  55. # 替換為你希望的文件夾路徑
  56. os.makedirs(download_folder, exist_ok=True)
  57. options = uc.ChromeOptions()
  58. options.add_argument('--ignore-certificate-errors')
  59. prefs = {
  60. "download.default_directory": download_folder, # 設定預設下載文件夾
  61. "download.prompt_for_download": False,
  62. "safebrowsing.enabled": True, # 確保安全瀏覽
  63. }
  64. options.add_experimental_option("prefs", prefs)
  65. # options.add_argument('--incognito')
  66. options.add_argument('--headless') # 如果不想顯示瀏覽器可以啟用這行
  67. options.add_argument("--disable-gpu") # 禁用 GPU 加速
  68. # 設置自定義 headers
  69. with uc.Chrome(options=options, version_main=129) as browser:
  70. try:
  71. browser.get(url)
  72. time.sleep(num)
  73. # 轉中文成台語拼音
  74. browser.find_element(By.XPATH, '//*[@id="js-input"]').send_keys(text)
  75. time.sleep(0.1)
  76. browser.find_element(By.XPATH, '//*[@id="js-translate"]').click()
  77. time.sleep(0.1 + len(text)*0.01)
  78. browser.execute_script('window.scrollBy(0, 200);')
  79. # 轉語音
  80. browser.find_element(By.XPATH, '//*[@id="button1"]').click()
  81. time.sleep(len(text)*0.5)
  82. audio_element = browser.find_element(By.XPATH, '//*[@id="audio1"]')
  83. time.sleep(0.2)
  84. # # 取得 <audio> 標籤的屬性(例如 src)
  85. audio_src = audio_element.get_attribute('src')
  86. print("音頻來源:", audio_src)
  87. # 下載音檔
  88. download_blob(browser, audio_src, file_name)
  89. # check 是否下載完成
  90. file_path = os.path.normpath(os.path.join(download_folder, file_name))
  91. while not os.path.exists(file_path):
  92. print('...')
  93. time.sleep(0.01)
  94. print(file_path)
  95. # destination_path = os.path.join(download_folder, datetime.now().strftime(f"%Y%m%d%H%M%S_{''.join(random.sample(string.ascii_lowercase, 3))}.wav"))
  96. # shutil.move(file_path, destination_path)
  97. print(f"下載完成: {file_path}")
  98. print(time.time() - start_time)
  99. return file_path
  100. except Exception as e:
  101. print(f'Error: {e}')
  102. return e
  103. tts_downloadfile('沒問題,可以試著從包包自己拿出來放桌上,也可以請老師協助你唷')