Spaces:
Running
Running
# 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() | |