Spaces:
Running
Running
File size: 6,378 Bytes
2ab9c74 ba3da14 2ab9c74 ba3da14 2ab9c74 59e3fab 2ab9c74 59e3fab 2ab9c74 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
# General imports
import json
import os
import shutil
import threading
import time
import undetected_chromedriver as uc
from selenium import webdriver
from selenium.webdriver.common.by import By
# Chrome driver setup
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
# Firefox driver setup
from selenium.webdriver.firefox.service import Service as FirefoxService
from webdriver_manager.firefox import GeckoDriverManager
# Selenium options for headless mode
from selenium.webdriver.chrome.options import Options
# Import important variables (make sure you have this file or define them manually)
import ImportantVariables as imp_val
# Imp variables
user_data_directory = imp_val.new_user_data_directory
profile_directory = "Default"
driver = None
CHROME_PATH = "/usr/bin/google-chrome"
def install_chrome():
"""Downloads and installs Google Chrome on Hugging Face Spaces."""
if shutil.which("google-chrome") is None: # Check if Chrome is already installed
print("π½ Installing Google Chrome...")
os.system(
"wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && "
"apt-get update && "
"apt-get install -y ./google-chrome-stable_current_amd64.deb && "
"rm -f google-chrome-stable_current_amd64.deb"
)
print("β
Google Chrome installed successfully!")
install_chrome()
def is_logged_in_youtube(driver):
try:
# Open YouTube
driver.get("https://www.youtube.com")
# Check for the profile icon (appears only when logged in)
driver.find_element(By.XPATH, "//button[@id='avatar-btn']")
print("β
You are already logged in to YouTube!")
return True
except:
print("β You are NOT logged in to YouTube.")
return False
def save_cookies_json(driver, filename="cookies.json"):
if driver is None:
print("Driver is not initialized. Skipping cookie save.")
return
cookies = driver.get_cookies()
with open(filename, "w") as file:
json.dump(cookies, file, indent=4)
def get_youtube_cookies(driver):
driver.get("https://www.youtube.com/account")
driver.implicitly_wait(5)
save_cookies_json(driver, imp_val.save_cookies_json)
driver.save_screenshot(imp_val.screenshot_path + '3_1.png')
print("cookies")
def load_cookies(driver):
try:
with open(imp_val.cookies_file, "r") as file:
cookies = json.load(file)
for cookie in cookies:
driver.add_cookie(cookie)
print("Cookies loaded successfully!")
# Refresh to apply cookies
driver.refresh()
time.sleep(5) # Wait for the page to reload with cookies
except Exception as e:
print(f"Error loading cookies: {e}")
def cookie_capture_loop():
"""Runs in a separate thread to capture cookies every 5 minutes."""
global driver
while True:
time.sleep(300) # Wait for 5 minutes
save_cookies_json(driver, imp_val.save_cookies_json)
print("Cookies saved to JSON file.")
# Refresh browser to keep session active
if driver is not None:
try:
driver.refresh()
print("π Browser refreshed successfully!")
except Exception as e:
print(f"β οΈ Error refreshing browser: {e}")
def setup_browser(browser="chrome"):
""" Set up the browser (Chrome or Firefox) for automation """
global driver # Ensure we use the same instance
if driver is not None:
print("Browser is already running. Returning existing driver instance.")
return driver
# Chrome options
chrome_options = uc.ChromeOptions()
if user_data_directory:
chrome_options.add_argument(f'--user-data-dir={user_data_directory}')
if profile_directory:
chrome_options.add_argument(f'--profile-directory={profile_directory}')
# Additional options for stability
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-gpu")
chrome_options.binary_location = CHROME_PATH
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
chrome_options.add_argument('--headless') # Run in headless mode
chrome_options.add_argument('--no-sandbox') # Recommended for CI environments
chrome_options.add_argument('--disable-dev-shm-usage') # Avoid /dev/shm issues in CI
chrome_options.add_argument('--disable-gpu') # Optional: Disable GPU usage
chrome_options.add_argument('--window-size=1920,1080') # Ensure proper resolution
print(f"\nSetting up: {browser} driver")
if browser == "chrome":
print("Using ChromeDriverManager:", ChromeDriverManager().install())
driver = uc.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
elif browser == "firefox":
print("Using GeckoDriverManager:", GeckoDriverManager().install())
driver = webdriver.Firefox(service=FirefoxService(GeckoDriverManager().install()))
else:
raise ValueError("Unsupported browser. Use 'chrome' or 'firefox'.")
driver.implicitly_wait(10) # Set implicit wait
return driver
def main():
""" Main function to run browser automation """
# browser_choice = input("Enter browser (chrome/firefox): ").strip().lower()
global driver
browser_choice = "chrome"
try:
driver = setup_browser(browser_choice)
# Example: Open YouTube
driver.get("https://www.youtube.com")
print("Opened YouTube successfully!")
time.sleep(5) # Keep browser open for demonstration
load_cookies(driver)
time.sleep(5)
driver.save_screenshot(imp_val.screenshot_path + '3_1.png')
is_logged_in_youtube(driver)
# Start cookie capture thread
cookie_thread = threading.Thread(target=cookie_capture_loop, daemon=True)
cookie_thread.start()
print("Driver is running. Cookie capture thread started.")
# Keep the browser open indefinitely
while True:
time.sleep(1)
except Exception as e:
print(f"Error: {e}")
finally:
print("\nClosing browser...")
# driver.quit()
if __name__ == "__main__":
main()
|