from playwright.sync_api import sync_playwright import json import time import os COOKIE_FILE = "cookies.json" def load_cookies(context, page): """Loads cookies from a file if available.""" try: with open(COOKIE_FILE, "r") as f: cookies = json.load(f) page.goto("https://www.youtube.com", wait_until="domcontentloaded") # Ensure page is loaded context.add_cookies(cookies) print("✅ Cookies loaded successfully.") except FileNotFoundError: print("⚠️ No cookies found. Logging in manually.") def save_cookies(context): """Saves cookies to a file.""" cookies = context.cookies() with open(COOKIE_FILE, "w") as f: json.dump(cookies, f) print("✅ Cookies saved successfully.") def is_logged_in_youtube(page): """Checks if the user is logged into YouTube.""" page.goto("https://www.youtube.com", wait_until="domcontentloaded") time.sleep(2) # Wait for elements to load try: page.wait_for_selector("button#avatar-btn", timeout=5000) print("✅ You are already logged in to YouTube!") return True except: print("❌ You are NOT logged in to YouTube.") return False def login_to_youtube(page): """Logs into YouTube manually if needed.""" email = os.getenv("YOUTUBE_EMAIL") password = os.getenv("YOUTUBE_PASSWORD") if not email or not password: print("❌ Missing login credentials! Set YOUTUBE_EMAIL and YOUTUBE_PASSWORD.") return False page.goto("https://accounts.google.com/signin/v2/identifier?service=youtube") # Enter email page.fill("input[type='email']", email) page.click("button:has-text('Next')") time.sleep(3) # Enter password page.fill("input[type='password']", password) page.click("button:has-text('Next')") time.sleep(5) if is_logged_in_youtube(page): print("✅ Login successful.") return True else: print("❌ Login failed.") return False def main(): with sync_playwright() as p: browser = p.chromium.launch(headless=False, executable_path="/home/user/.cache/ms-playwright/chromium/chrome-linux/chrome", args=["--no-sandbox"]) # Use --no-sandbox for Hugging Face Spaces context = browser.new_context() page = context.new_page() load_cookies(context, page) result=is_logged_in_youtube(page) browser.close() return result if __name__ == "__main__": main()