|
| 1 | +import json |
1 | 2 | from collections.abc import Generator
|
2 | 3 | from typing import TYPE_CHECKING
|
| 4 | +import os |
| 5 | +import gradio as gr |
| 6 | +from datetime import datetime |
3 | 7 |
|
4 |
| -if TYPE_CHECKING: |
5 |
| - from gradio.components import Component |
6 |
| - |
| 8 | +from gradio.components import Component |
7 | 9 | from browser_use.browser.browser import Browser
|
8 | 10 | from browser_use.browser.context import BrowserContext
|
9 | 11 | from browser_use.agent.service import Agent
|
10 | 12 |
|
11 | 13 |
|
12 | 14 | class WebuiManager:
|
13 |
| - def __init__(self): |
| 15 | + def __init__(self, settings_save_dir: str = "./tmp/webui_settings"): |
14 | 16 | self.id_to_component: dict[str, Component] = {}
|
15 | 17 | self.component_to_id: dict[Component, str] = {}
|
16 | 18 |
|
| 19 | + self.settings_save_dir = settings_save_dir |
| 20 | + os.makedirs(self.settings_save_dir, exist_ok=True) |
| 21 | + |
17 | 22 | self.browser: Browser = None
|
18 | 23 | self.browser_context: BrowserContext = None
|
19 | 24 | self.bu_agent: Agent = None
|
@@ -44,3 +49,33 @@ def get_id_by_component(self, comp: "Component") -> str:
|
44 | 49 | Get id by component
|
45 | 50 | """
|
46 | 51 | return self.component_to_id[comp]
|
| 52 | + |
| 53 | + def save_current_config(self): |
| 54 | + """ |
| 55 | + Save current config |
| 56 | + """ |
| 57 | + cur_settings = {} |
| 58 | + for comp_id, comp in self.id_to_component.items(): |
| 59 | + if not isinstance(comp, gr.Button) and not isinstance(comp, gr.File) and str( |
| 60 | + getattr(comp, "interactive", True)).lower() != "false": |
| 61 | + cur_settings[comp_id] = getattr(comp, "value", None) |
| 62 | + |
| 63 | + config_name = datetime.now().strftime("%Y%m%d-%H%M%S") |
| 64 | + with open(os.path.join(self.settings_save_dir, f"{config_name}.json"), "w") as fw: |
| 65 | + json.dump(cur_settings, fw, indent=4) |
| 66 | + |
| 67 | + return os.path.join(self.settings_save_dir, f"{config_name}.json") |
| 68 | + |
| 69 | + def load_config(self, config_path: str): |
| 70 | + """ |
| 71 | + Load config |
| 72 | + """ |
| 73 | + with open(config_path, "r") as fr: |
| 74 | + ui_settings = json.load(fr) |
| 75 | + |
| 76 | + update_components = {} |
| 77 | + for comp_id, comp_val in ui_settings.items(): |
| 78 | + if comp_id in self.id_to_component: |
| 79 | + update_components[self.id_to_component[comp_id]].value = comp_val |
| 80 | + |
| 81 | + return f"Successfully loaded config from {config_path}" |
0 commit comments