Spaces:
Running
Running
import tempfile | |
import browser_cookie3 | |
from yt_dlp import YoutubeDL | |
from agents.video_analyzer_agent import env_to_cookies_from_env | |
def export_youtube_cookies_netscape(domain: str = "youtube.com") -> str: | |
""" | |
Exporte les cookies du navigateur (Chrome/Firefox) pour le domaine | |
spécifié dans un fichier au format Netscape (standard .txt). | |
Retourne le chemin du fichier temporaire. | |
""" | |
# Récupère les cookies du navigateur | |
# browser_cookie3 supporte 'chrome', 'firefox', 'edge'… | |
# cj = browser_cookie3.brave(domain_name=domain) | |
cj = browser_cookie3.librewolf(domain_name=domain) | |
# Crée un fichier temporaire en mode écriture texte | |
tmp = tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".txt") | |
# Format Netscape : | |
# domain \t include_subdomains \t path \t secure \t expires \t name \t value | |
for cookie in cj: | |
include_sub = "TRUE" if cookie.domain.startswith('.') else "FALSE" | |
secure_flag = "TRUE" if cookie.secure else "FALSE" | |
expires = cookie.expires or 0 | |
line = "\t".join([ | |
cookie.domain, | |
include_sub, | |
cookie.path, | |
secure_flag, | |
str(expires), | |
cookie.name, | |
cookie.value, | |
]) | |
tmp.write(line + "\n") | |
tmp.flush() | |
return tmp.name | |
def cookies_to_content(cookie_file_path: str) -> str: | |
"""Convert cookie file content to environment variable format""" | |
try: | |
with open(cookie_file_path, 'r') as f: | |
lines = f.readlines() | |
# Keep header comments | |
header = [line.strip() for line in lines if line.startswith('#')] | |
# Get cookie content (non-comment lines) | |
cookies = [line.strip() for line in lines if line.strip() and not line.startswith('#')] | |
# Join with escaped newlines | |
content = '\\n'.join(header + [''] + cookies) # Empty line after headers | |
# Create env file content | |
return content | |
except Exception as e: | |
raise ValueError(f"Error converting cookie file: {str(e)}") | |
def save_to_env_file(env_content: str, env_file: str = '.env') -> None: | |
"""Save environment variable content to .env file""" | |
try: | |
with open(env_file, 'w') as f: | |
f.write(env_content) | |
#print(f"Successfully saved to {env_file}") | |
except Exception as e: | |
raise ValueError(f"Error saving to env file: {str(e)}") | |
def content_to_cookies(env_content: str, output_file: str) -> None: | |
"""Convert environment variable content back to cookie file""" | |
try: | |
# Replace escaped newlines with actual newlines | |
cookie_content = env_content.replace('\\n', '\n') | |
# Write to cookie file | |
with open(output_file, 'w') as f: | |
f.write(cookie_content) | |
except Exception as e: | |
raise ValueError(f"Error converting to cookie file: {str(e)}") | |
content_to_cookies(cookies_to_content(export_youtube_cookies_netscape("youtube.com")), "cookies.txt") |