|
| 1 | +import atexit |
| 2 | +import base64 |
| 3 | +import io |
| 4 | +import multiprocessing |
| 5 | +import time |
| 6 | +import uuid |
| 7 | + |
| 8 | +import browsergym.core # noqa F401 (we register the openended task as a gym environment) |
| 9 | +import gymnasium as gym |
| 10 | +import html2text |
| 11 | +import numpy as np |
| 12 | +from browsergym.utils.obs import flatten_dom_to_str |
| 13 | +from PIL import Image |
| 14 | + |
| 15 | +from opendevin.logger import opendevin_logger as logger |
| 16 | + |
| 17 | + |
| 18 | +class BrowserException(Exception): |
| 19 | + pass |
| 20 | + |
| 21 | +class BrowserEnv: |
| 22 | + |
| 23 | + def __init__(self): |
| 24 | + self.html_text_converter = html2text.HTML2Text() |
| 25 | + # ignore links and images |
| 26 | + self.html_text_converter.ignore_links = True |
| 27 | + self.html_text_converter.ignore_images = True |
| 28 | + # use alt text for images |
| 29 | + self.html_text_converter.images_to_alt = True |
| 30 | + # disable auto text wrapping |
| 31 | + self.html_text_converter.body_width = 0 |
| 32 | + # Initialize browser environment process |
| 33 | + multiprocessing.set_start_method('spawn', force=True) |
| 34 | + self.browser_side, self.agent_side = multiprocessing.Pipe() |
| 35 | + self.process = multiprocessing.Process(target=self.browser_process,) |
| 36 | + logger.info('Starting browser env...') |
| 37 | + self.process.start() |
| 38 | + atexit.register(self.close) |
| 39 | + |
| 40 | + def browser_process(self): |
| 41 | + env = gym.make( |
| 42 | + 'browsergym/openended', |
| 43 | + start_url='about:blank', |
| 44 | + wait_for_user_message=False, |
| 45 | + headless=True, |
| 46 | + disable_env_checker=True, |
| 47 | + ) |
| 48 | + obs, info = env.reset() |
| 49 | + logger.info('Browser env started.') |
| 50 | + while True: |
| 51 | + try: |
| 52 | + if self.browser_side.poll(timeout=0.01): |
| 53 | + unique_request_id , action_data = self.browser_side.recv() |
| 54 | + # shutdown the browser environment |
| 55 | + if unique_request_id == 'SHUTDOWN': |
| 56 | + env.close() |
| 57 | + return |
| 58 | + action = action_data['action'] |
| 59 | + obs, reward, terminated, truncated, info = env.step(action) |
| 60 | + # add text content of the page |
| 61 | + html_str = flatten_dom_to_str(obs['dom_object']) |
| 62 | + obs['text_content'] = self.html_text_converter.handle(html_str) |
| 63 | + # make observation serializable |
| 64 | + obs['screenshot'] = self.image_to_png_base64_url(obs['screenshot']) |
| 65 | + obs['active_page_index'] = obs['active_page_index'].item() |
| 66 | + obs['elapsed_time'] = obs['elapsed_time'].item() |
| 67 | + self.browser_side.send((unique_request_id, obs)) |
| 68 | + except KeyboardInterrupt: |
| 69 | + logger.info('Browser env process interrupted by user.') |
| 70 | + return |
| 71 | + |
| 72 | + def step(self, action_str: str, timeout: float = 10) -> dict: |
| 73 | + unique_request_id = str(uuid.uuid4()) |
| 74 | + self.agent_side.send((unique_request_id, {'action': action_str})) |
| 75 | + start_time = time.time() |
| 76 | + while True: |
| 77 | + if time.time() - start_time > timeout: |
| 78 | + raise TimeoutError('Browser environment took too long to respond.') |
| 79 | + if self.agent_side.poll(timeout=0.01): |
| 80 | + response_id, obs = self.agent_side.recv() |
| 81 | + if response_id == unique_request_id: |
| 82 | + if obs['last_action_error']: |
| 83 | + raise BrowserException(obs['last_action_error']) |
| 84 | + return obs |
| 85 | + |
| 86 | + def close(self): |
| 87 | + self.agent_side.send(('SHUTDOWN', None)) |
| 88 | + self.process.join() |
| 89 | + |
| 90 | + @staticmethod |
| 91 | + def image_to_png_base64_url(image: np.ndarray | Image.Image): |
| 92 | + """Convert a numpy array to a base64 encoded png image url.""" |
| 93 | + |
| 94 | + if isinstance(image, np.ndarray): |
| 95 | + image = Image.fromarray(image) |
| 96 | + if image.mode in ('RGBA', 'LA'): |
| 97 | + image = image.convert('RGB') |
| 98 | + buffered = io.BytesIO() |
| 99 | + image.save(buffered, format='PNG') |
| 100 | + |
| 101 | + image_base64 = base64.b64encode(buffered.getvalue()).decode() |
| 102 | + return f'{image_base64}' |
0 commit comments