### Start AIStudioBuildWS Service with Docker Compose Source: https://github.com/hkfires/aistudiobuildws/blob/main/README.md Build and start the AIStudioBuildWS service in detached mode using Docker Compose. This command initiates the deployment on your server. ```bash docker compose up -d --build ``` -------------------------------- ### Configure Environment Variables for Docker Deployment Source: https://github.com/hkfires/aistudiobuildws/blob/main/README.md Copy the example environment file and populate it with your specific configuration details, such as the AI Studio application URL and user cookies. Alternatively, place JSON-formatted cookie files in the 'cookies' directory. ```bash cp .env.example .env nano .env ``` -------------------------------- ### 配置日志记录 Source: https://context7.com/hkfires/aistudiobuildws/llms.txt 使用 setup_logging 函数配置日志输出,支持自定义前缀和时区。 ```python from utils.logger import setup_logging # 基础用法 logger = setup_logging("logs/app.log") logger.info("应用启动") # 带前缀的日志(用于区分不同实例) logger = setup_logging( "logs/app.log", prefix="account1.json", # 日志前缀 level=logging.INFO ) logger.info("实例启动成功") # 输出: 2024-01-15 10:30:00 - 12345 - INFO - account1.json - 实例启动成功 # 通过环境变量设置时区 # TZ_OFFSET=0 -> UTC 时间 # TZ_OFFSET=8 -> 北京时间(默认) # TZ_OFFSET=-5 -> 美东时间 ``` -------------------------------- ### Main Entry Point and Configuration Source: https://context7.com/hkfires/aistudiobuildws/llms.txt The main entry point initializes the application and registers signal handlers. Configuration is primarily managed through environment variables, dictating the operational mode and browser instance parameters. ```python import multiprocessing if __name__ == "__main__": multiprocessing.freeze_support() main() # 环境变量配置示例 # HG=true -> 启动 Flask 服务器模式(适用于 HuggingFace Spaces) # HG=false 或未设置 -> 独立 CLI 模式 # 必需的环境变量 # CAMOUFOX_INSTANCE_URL="https://aistudio.google.com/apps/drive/YOUR_APP_ID" # USER_COOKIE_1='[{"name": "__Secure-1PSID", "value": "..."}]' # 可选环境变量 # CAMOUFOX_HEADLESS="virtual" # true/false/virtual # CAMOUFOX_PROXY="http://proxy.example.com:8080" # INSTANCE_START_DELAY=30 # 实例启动间隔(秒) # MAX_RESTART_RETRIES=5 # 最大重试次数 # TZ_OFFSET=8 # 日志时区偏移量 ``` -------------------------------- ### run_browser_instance for Browser Lifecycle Source: https://context7.com/hkfires/aistudiobuildws/llms.txt This function is the core execution logic for each browser child process. It initializes Camoufox, loads cookies, navigates to the target URL, verifies login status, and enters a keep-alive loop. ```python from browser.instance import run_browser_instance import multiprocessing # 配置示例 config = { "url": "https://aistudio.google.com/apps/drive/YOUR_APP_ID", "headless": "virtual", # true/false/virtual "proxy": "http://proxy.example.com:8080", # 可选 "cookie_source": CookieSource( type="env_var", identifier="USER_COOKIE_1", display_name="USER_COOKIE_1" ) } # 创建关闭事件用于优雅退出 shutdown_event = multiprocessing.Event() # 在子进程中运行浏览器实例 process = multiprocessing.Process( target=run_browser_instance, args=(config, shutdown_event) ) process.start() # 发送关闭信号 shutdown_event.set() process.join(timeout=10) ``` -------------------------------- ### 检查 Flask 健康状态 Source: https://context7.com/hkfires/aistudiobuildws/llms.txt 通过 HTTP 请求检查服务器模式下的应用健康状态及运行信息。 ```bash # 健康检查端点 curl http://localhost:7860/health # 响应: # { # "status": "healthy", # "browser_instances": 3, # "running_instances": 3, # "message": "Application is running with 3 active browser instances" # } # 主页端点 curl http://localhost:7860/ # 响应: # { # "status": "running", # "browser_instances": 3, # "running_instances": 3, # "run_mode": "server", # "message": "Camoufox Browser Automation is running in server mode" # } ``` -------------------------------- ### Clone AIStudioBuildWS Repository Source: https://github.com/hkfires/aistudiobuildws/blob/main/README.md Clone the AIStudioBuildWS repository to your local machine to begin the Docker deployment process. ```bash git clone https://github.com/hkfires/AIStudioBuildWS.git cd AIStudioBuildWS ``` -------------------------------- ### 配置 Docker 部署 Source: https://context7.com/hkfires/aistudiobuildws/llms.txt 使用 Docker Compose 进行容器化部署,并包含部署步骤说明。 ```yaml # compose.yml services: aistudio-websocket-app: image: aistudio-websocket build: . pull_policy: never container_name: aistudio-websocket-app env_file: - .env volumes: - ./cookies:/app/cookies:rw # Cookie 文件目录 - ./logs:/app/logs:rw # 日志目录 restart: on-failure ``` ```bash # 部署步骤 git clone https://github.com/hkfires/AIStudioBuildWS.git cd AIStudioBuildWS # 配置环境变量 cp .env.example .env # 编辑 .env 文件设置 CAMOUFOX_INSTANCE_URL 和 USER_COOKIE_1 # 启动服务 docker compose up -d --build # 查看日志 docker logs -f aistudio-websocket-app ``` -------------------------------- ### 管理项目路径 Source: https://context7.com/hkfires/aistudiobuildws/llms.txt 通过 paths 模块获取项目根目录、日志目录及 Cookie 目录,支持环境变量覆盖。 ```python from utils.paths import project_root, logs_dir, cookies_dir # 获取项目根目录 root = project_root() print(f"项目根目录: {root}") # 自动检测逻辑: # 1. 检查环境变量 CAMOUFOX_PROJECT_ROOT # 2. 向上查找包含 "cookies" 目录的父目录 # 3. 回退到脚本文件所在目录 # 获取日志目录 log_path = logs_dir() print(f"日志目录: {log_path}") # -> /app/logs # 获取 Cookie 目录 cookie_path = cookies_dir() print(f"Cookie 目录: {cookie_path}") # -> /app/cookies # 在 Docker 环境中通过环境变量覆盖 # CAMOUFOX_PROJECT_ROOT="/app" ``` -------------------------------- ### 管理 WebSocket 连接 Source: https://context7.com/hkfires/aistudiobuildws/llms.txt 通过连接、等待连接状态及执行重连流程来维护 WebSocket 会话。 ```python # 建立 WebSocket 连接 success = click_connect(page, logger) # 等待 WebSocket 连接成功(带超时) connected = wait_for_ws_connected(page, logger, timeout=30) if connected: print("WebSocket 已连接") # 执行完整的断开-重连流程 final_status = reconnect_ws(page, logger) # 流程: 关闭遮罩 -> Disconnect -> 等待 IDLE -> Connect -> 等待 CONNECTED print(f"重连后状态: {final_status}") ``` -------------------------------- ### WebSocket Status Management Functions Source: https://context7.com/hkfires/aistudiobuildws/llms.txt The ws_helper module provides functions for monitoring and managing WebSocket connection states, including retrieving status, initiating disconnections, and handling reconnections. ```python from browser.ws_helper import ( get_ws_status, click_connect, click_disconnect, reconnect_ws, wait_for_ws_connected ) # 获取当前 WebSocket 连接状态 # 返回值: "CONNECTED", "IDLE", "CONNECTING", "UNKNOWN" status = get_ws_status(page, logger) print(f"当前 WS 状态: {status}") # 断开 WebSocket 连接 success = click_disconnect(page, logger) ``` -------------------------------- ### 验证 Cookie 有效性 Source: https://context7.com/hkfires/aistudiobuildws/llms.txt 使用 CookieValidator 类在新标签页中访问验证 URL,若验证失败则关闭实例。 ```python from browser.cookie_validator import CookieValidator # 在浏览器上下文中创建验证器 cookie_validator = CookieValidator(page, context, logger) # 执行 Cookie 验证(在主线程中调用) is_valid = cookie_validator.validate_cookies_in_main_thread() # 验证流程: # 1. 创建新标签页 # 2. 访问 https://aistudio.google.com/apps # 3. 检查是否被重定向到登录页面 # 4. 返回验证结果并关闭标签页 if not is_valid: # Cookie 已失效,关闭实例 cookie_validator.shutdown_instance_on_cookie_failure() # 调用 sys.exit(1) 退出进程 ``` -------------------------------- ### ProcessManager for Browser Child Processes Source: https://context7.com/hkfires/aistudiobuildws/llms.txt The ProcessManager class handles the lifecycle of browser child processes, offering functionalities for adding, removing, checking status, and terminating processes safely in a multi-process environment. ```python from main import ProcessManager import multiprocessing # 初始化进程管理器 process_manager = ProcessManager() # 创建并添加子进程 def worker_function(config, shutdown_event): # 工作进程逻辑 pass shutdown_event = multiprocessing.Event() config = {"url": "https://example.com", "headless": "virtual"} process = multiprocessing.Process(target=worker_function, args=(config, shutdown_event)) process.start() # 添加进程到管理器 process_manager.add_process(process, config) # 获取存活进程数量 alive_count = process_manager.get_alive_count() print(f"当前运行的进程数: {alive_count}") # 获取所有存活进程列表 alive_processes = process_manager.get_alive_processes() # 优雅终止所有进程(先发送 SIGTERM,等待后强制 KILL) process_manager.terminate_all(timeout=10) ``` -------------------------------- ### auto_convert_to_playwright for Cookie Format Conversion Source: https://context7.com/hkfires/aistudiobuildws/llms.txt This function automatically identifies and converts two common cookie formats (Cookie-Editor JSON array or key-value string) into the Playwright-compatible format. ```python from utils.cookie_handler import auto_convert_to_playwright # 格式 1: Cookie-Editor 导出的 JSON 数组 json_cookies = [ { "name": "__Secure-1PSID", "value": "abc123...", "domain": ".google.com", "path": "/", "expirationDate": 1735689600, "httpOnly": True, "secure": True, "sameSite": "no_restriction" } ] playwright_cookies = auto_convert_to_playwright(json_cookies) # 格式 2: 键值对字符串(从浏览器开发者工具复制) kv_string = "__Secure-1PSID=abc123...; __Secure-1PAPISID=xyz789...; NID=511=..." playwright_cookies = auto_convert_to_playwright( kv_string, default_domain=".google.com" ) # 输出格式(两种输入都转换为相同格式) # [ # {"name": "__Secure-1PSID", "value": "abc123...", "domain": ".google.com", ...} # ] ``` -------------------------------- ### CookieManager for Cookie Operations Source: https://context7.com/hkfires/aistudiobuildws/llms.txt The CookieManager class centralizes cookie management, supporting detection, loading, and caching from JSON files or environment variables, automatically converting them to a Playwright-compatible format. ```python from utils.cookie_manager import CookieManager, CookieSource from utils.logger import setup_logging logger = setup_logging("logs/app.log") cookie_manager = CookieManager(logger) # 检测所有可用的 Cookie 来源(JSON 文件 + 环境变量) sources = cookie_manager.detect_all_sources() # 返回: [CookieSource(type="file", identifier="account1.json", ...), # CookieSource(type="env_var", identifier="USER_COOKIE_1", ...)] # 从指定来源加载 Cookie for source in sources: cookies = cookie_manager.load_cookies(source) print(f"从 {source.display_name} 加载了 {len(cookies)} 个 Cookie") # Cookie 数据格式(Playwright 兼容) # [ # { # "name": "__Secure-1PSID", # "value": "xxx...", # "domain": ".google.com", # "path": "/", # "expires": -1, # "httpOnly": True, # "secure": True, # "sameSite": "Lax" # } # ] ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.