Merge pull request #116 from ThomasDh-C/demo
Init gradio demo of computer use
4
.gitignore
vendored
@@ -6,3 +6,7 @@ weights/icon_detect_v1_5_2/
|
||||
.gradio
|
||||
__pycache__/
|
||||
debug.ipynb
|
||||
util/__pycache__/
|
||||
index.html?linkid=2289031
|
||||
wget-log
|
||||
weights/omniv2/
|
||||
201
Dockerfile
@@ -1,201 +0,0 @@
|
||||
# Dockerfile for OmniParser with GPU support and OpenGL libraries
|
||||
#
|
||||
# This Dockerfile is intended to create an environment with NVIDIA CUDA
|
||||
# support and the necessary dependencies to run the OmniParser project.
|
||||
# The configuration is designed to support applications that rely on
|
||||
# Python 3.12, OpenCV, Hugging Face transformers, and Gradio. Additionally,
|
||||
# it includes steps to pull large files from Git LFS and a script to
|
||||
# convert model weights from .safetensor to .pt format. The container
|
||||
# runs a Gradio server by default, exposed on port 7861.
|
||||
#
|
||||
# Base image: nvidia/cuda:12.3.1-devel-ubuntu22.04
|
||||
#
|
||||
# Key features:
|
||||
# - System dependencies for OpenGL to support graphical libraries.
|
||||
# - Miniconda for Python 3.12, allowing for environment management.
|
||||
# - Git Large File Storage (LFS) setup for handling large model files.
|
||||
# - Requirement file installation, including specific versions of
|
||||
# OpenCV and Hugging Face Hub.
|
||||
# - Entrypoint script execution with Gradio server configuration for
|
||||
# external access.
|
||||
|
||||
FROM nvidia/cuda:12.3.1-devel-ubuntu22.04
|
||||
|
||||
# Install system dependencies with explicit OpenGL libraries
|
||||
RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y \
|
||||
git \
|
||||
git-lfs \
|
||||
wget \
|
||||
libgl1 \
|
||||
libglib2.0-0 \
|
||||
libsm6 \
|
||||
libxext6 \
|
||||
libxrender1 \
|
||||
libglu1-mesa \
|
||||
libglib2.0-0 \
|
||||
libsm6 \
|
||||
libxrender1 \
|
||||
libxext6 \
|
||||
python3-opencv \
|
||||
&& apt-get clean \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& git lfs install
|
||||
|
||||
# Install Miniconda for Python 3.12
|
||||
RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh && \
|
||||
bash miniconda.sh -b -p /opt/conda && \
|
||||
rm miniconda.sh
|
||||
ENV PATH="/opt/conda/bin:$PATH"
|
||||
|
||||
# Create and activate Conda environment with Python 3.12, and set it as the default
|
||||
RUN conda create -n omni python=3.12 && \
|
||||
echo "source activate omni" > ~/.bashrc
|
||||
ENV CONDA_DEFAULT_ENV=omni
|
||||
ENV PATH="/opt/conda/envs/omni/bin:$PATH"
|
||||
|
||||
# Set the working directory in the container
|
||||
WORKDIR /usr/src/app
|
||||
|
||||
# Copy project files and requirements
|
||||
COPY . .
|
||||
COPY requirements.txt /usr/src/app/requirements.txt
|
||||
|
||||
# Initialize Git LFS and pull LFS files
|
||||
RUN git lfs install && \
|
||||
git lfs pull
|
||||
|
||||
# Install dependencies from requirements.txt with specific opencv-python-headless version
|
||||
RUN . /opt/conda/etc/profile.d/conda.sh && conda activate omni && \
|
||||
pip uninstall -y opencv-python opencv-python-headless && \
|
||||
pip install --no-cache-dir opencv-python-headless==4.8.1.78 && \
|
||||
pip install -r requirements.txt && \
|
||||
pip install huggingface_hub
|
||||
|
||||
# Run download.py to fetch model weights and convert safetensors to .pt format
|
||||
# RUN . /opt/conda/etc/profile.d/conda.sh && conda activate omni && \
|
||||
# python download.py && \
|
||||
# echo "Contents of weights directory:" && \
|
||||
# ls -lR weights && \
|
||||
# python weights/convert_safetensor_to_pt.py
|
||||
|
||||
# Expose the default Gradio port
|
||||
EXPOSE 7861
|
||||
|
||||
# Configure Gradio to be accessible externally
|
||||
ENV GRADIO_SERVER_NAME="0.0.0.0"
|
||||
|
||||
# Copy and set permissions for entrypoint script
|
||||
# COPY entrypoint.sh /usr/src/app/entrypoint.sh
|
||||
# RUN chmod +x /usr/src/app/entrypoint.sh
|
||||
|
||||
# To debug, keep the container running
|
||||
# CMD ["tail", "-f", "/dev/null"]
|
||||
|
||||
################################################################################################
|
||||
# virtual display related setup --> from anthropic-quickstarts/computer-use-demo/Dockerfile
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive
|
||||
ENV DEBIAN_PRIORITY=high
|
||||
|
||||
RUN apt-get update && \
|
||||
apt-get -y upgrade && \
|
||||
apt-get -y install \
|
||||
# UI Requirements
|
||||
xvfb \
|
||||
xterm \
|
||||
xdotool \
|
||||
scrot \
|
||||
imagemagick \
|
||||
sudo \
|
||||
mutter \
|
||||
x11vnc \
|
||||
# Python/pyenv reqs
|
||||
build-essential \
|
||||
libssl-dev \
|
||||
zlib1g-dev \
|
||||
libbz2-dev \
|
||||
libreadline-dev \
|
||||
libsqlite3-dev \
|
||||
curl \
|
||||
git \
|
||||
libncursesw5-dev \
|
||||
xz-utils \
|
||||
tk-dev \
|
||||
libxml2-dev \
|
||||
libxmlsec1-dev \
|
||||
libffi-dev \
|
||||
liblzma-dev \
|
||||
# Network tools
|
||||
net-tools \
|
||||
netcat \
|
||||
# PPA req
|
||||
software-properties-common && \
|
||||
# Userland apps
|
||||
sudo add-apt-repository ppa:mozillateam/ppa && \
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
libreoffice \
|
||||
firefox-esr \
|
||||
x11-apps \
|
||||
xpdf \
|
||||
gedit \
|
||||
xpaint \
|
||||
tint2 \
|
||||
galculator \
|
||||
pcmanfm \
|
||||
unzip && \
|
||||
apt-get clean
|
||||
|
||||
# Install noVNC
|
||||
RUN git clone --branch v1.5.0 https://github.com/novnc/noVNC.git /opt/noVNC && \
|
||||
git clone --branch v0.12.0 https://github.com/novnc/websockify /opt/noVNC/utils/websockify && \
|
||||
ln -s /opt/noVNC/vnc.html /opt/noVNC/index.html
|
||||
|
||||
# setup user
|
||||
ENV USERNAME=computeruse
|
||||
ENV HOME=/home/$USERNAME
|
||||
RUN useradd -m -s /bin/bash -d $HOME $USERNAME
|
||||
RUN echo "${USERNAME} ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers
|
||||
USER computeruse
|
||||
WORKDIR $HOME
|
||||
|
||||
# setup python
|
||||
RUN git clone https://github.com/pyenv/pyenv.git ~/.pyenv && \
|
||||
cd ~/.pyenv && src/configure && make -C src && cd .. && \
|
||||
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc && \
|
||||
echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc && \
|
||||
echo 'eval "$(pyenv init -)"' >> ~/.bashrc
|
||||
ENV PYENV_ROOT="$HOME/.pyenv"
|
||||
ENV PATH="$PYENV_ROOT/bin:$PATH"
|
||||
ENV PYENV_VERSION_MAJOR=3
|
||||
ENV PYENV_VERSION_MINOR=11
|
||||
ENV PYENV_VERSION_PATCH=6
|
||||
ENV PYENV_VERSION=$PYENV_VERSION_MAJOR.$PYENV_VERSION_MINOR.$PYENV_VERSION_PATCH
|
||||
RUN eval "$(pyenv init -)" && \
|
||||
pyenv install $PYENV_VERSION && \
|
||||
pyenv global $PYENV_VERSION && \
|
||||
pyenv rehash
|
||||
|
||||
ENV PATH="$HOME/.pyenv/shims:$HOME/.pyenv/bin:$PATH"
|
||||
|
||||
RUN python -m pip install --upgrade pip==23.1.2 setuptools==58.0.4 wheel==0.40.0 && \
|
||||
python -m pip config set global.disable-pip-version-check true
|
||||
|
||||
# only reinstall if requirements.txt changes
|
||||
# COPY --chown=$USERNAME:$USERNAME computer_use_demo/requirements.txt $HOME/computer_use_demo/requirements.txt
|
||||
# RUN python -m pip install -r $HOME/computer_use_demo/requirements.txt
|
||||
|
||||
# setup desktop env & app
|
||||
# COPY --chown=$USERNAME:$USERNAME image/ $HOME
|
||||
# COPY --chown=$USERNAME:$USERNAME computer_use_demo/ $HOME/computer_use_demo/
|
||||
|
||||
ARG DISPLAY_NUM=1
|
||||
ARG HEIGHT=768
|
||||
ARG WIDTH=1024
|
||||
ENV DISPLAY_NUM=$DISPLAY_NUM
|
||||
ENV HEIGHT=$HEIGHT
|
||||
ENV WIDTH=$WIDTH
|
||||
|
||||
# Set the entrypoint
|
||||
# ENTRYPOINT ["/usr/src/app/entrypoint.sh"]
|
||||
|
||||
# docker build . -t omniparser-x-demo:local # manually build the docker image (optional)
|
||||
27
demo.ipynb
@@ -14,7 +14,7 @@
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"from utils import get_som_labeled_img, check_ocr_box, get_caption_model_processor, get_yolo_model\n",
|
||||
"from util.utils import get_som_labeled_img, check_ocr_box, get_caption_model_processor, get_yolo_model\n",
|
||||
"import torch\n",
|
||||
"from ultralytics import YOLO\n",
|
||||
"from PIL import Image\n",
|
||||
@@ -48,9 +48,9 @@
|
||||
"source": [
|
||||
"# two choices for caption model: fine-tuned blip2 or florence2\n",
|
||||
"import importlib\n",
|
||||
"import utils\n",
|
||||
"importlib.reload(utils)\n",
|
||||
"from utils import get_som_labeled_img, check_ocr_box, get_caption_model_processor, get_yolo_model\n",
|
||||
"import util.utils\n",
|
||||
"importlib.reload(util.utils)\n",
|
||||
"from util.utils import get_som_labeled_img, check_ocr_box, get_caption_model_processor, get_yolo_model\n",
|
||||
"# caption_model_processor = get_caption_model_processor(model_name=\"blip2\", model_name_or_path=\"weights/icon_caption_blip2\", device=device)\n",
|
||||
"caption_model_processor = get_caption_model_processor(model_name=\"florence2\", model_name_or_path=\"weights/icon_caption_florence\", device=device)\n",
|
||||
"\n"
|
||||
@@ -102,9 +102,9 @@
|
||||
"source": [
|
||||
"# reload utils\n",
|
||||
"import importlib\n",
|
||||
"import utils\n",
|
||||
"importlib.reload(utils)\n",
|
||||
"from utils import get_som_labeled_img, check_ocr_box, get_caption_model_processor, get_yolo_model\n",
|
||||
"import util.utils\n",
|
||||
"importlib.reload(util.utils)\n",
|
||||
"from util.utils import get_som_labeled_img, check_ocr_box, get_caption_model_processor, get_yolo_model\n",
|
||||
"\n",
|
||||
"image_path = 'imgs/google_page.png'\n",
|
||||
"image_path = 'imgs/windows_home.png'\n",
|
||||
@@ -167,9 +167,9 @@
|
||||
"# run on cpu!!!\n",
|
||||
"# reload utils\n",
|
||||
"import importlib\n",
|
||||
"import utils\n",
|
||||
"importlib.reload(utils)\n",
|
||||
"from utils import get_som_labeled_img, check_ocr_box, get_caption_model_processor, get_yolo_model\n",
|
||||
"import util.utils\n",
|
||||
"importlib.reload(util.utils)\n",
|
||||
"from util.utils import get_som_labeled_img, check_ocr_box, get_caption_model_processor, get_yolo_model\n",
|
||||
"\n",
|
||||
"image_path = 'imgs/google_page.png'\n",
|
||||
"image_path = 'imgs/windows_home.png'\n",
|
||||
@@ -447,13 +447,6 @@
|
||||
"source": [
|
||||
"parsed_content_list[-1]"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": []
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
import os
|
||||
import re
|
||||
import ast
|
||||
import base64
|
||||
|
||||
|
||||
def is_image_path(text):
|
||||
# Checking if the input text ends with typical image file extensions
|
||||
image_extensions = (".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".tif")
|
||||
if text.endswith(image_extensions):
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def encode_image(image_path):
|
||||
"""Encode image file to base64."""
|
||||
with open(image_path, "rb") as image_file:
|
||||
return base64.b64encode(image_file.read()).decode("utf-8")
|
||||
|
||||
|
||||
def is_url_or_filepath(input_string):
|
||||
# Check if input_string is a URL
|
||||
url_pattern = re.compile(
|
||||
r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
|
||||
)
|
||||
if url_pattern.match(input_string):
|
||||
return "URL"
|
||||
|
||||
# Check if input_string is a file path
|
||||
file_path = os.path.abspath(input_string)
|
||||
if os.path.exists(file_path):
|
||||
return "File path"
|
||||
|
||||
return "Invalid"
|
||||
|
||||
|
||||
def extract_data(input_string, data_type):
|
||||
# Regular expression to extract content starting from '```python' until the end if there are no closing backticks
|
||||
pattern = f"```{data_type}" + r"(.*?)(```|$)"
|
||||
# Extract content
|
||||
# re.DOTALL allows '.' to match newlines as well
|
||||
matches = re.findall(pattern, input_string, re.DOTALL)
|
||||
# Return the first match if exists, trimming whitespace and ignoring potential closing backticks
|
||||
return matches[0][0].strip() if matches else input_string
|
||||
|
||||
|
||||
def parse_input(code):
|
||||
"""Use AST to parse the input string and extract the function name, arguments, and keyword arguments."""
|
||||
|
||||
def get_target_names(target):
|
||||
"""Recursively get all variable names from the assignment target."""
|
||||
if isinstance(target, ast.Name):
|
||||
return [target.id]
|
||||
elif isinstance(target, ast.Tuple):
|
||||
names = []
|
||||
for elt in target.elts:
|
||||
names.extend(get_target_names(elt))
|
||||
return names
|
||||
return []
|
||||
|
||||
def extract_value(node):
|
||||
"""提取 AST 节点的实际值"""
|
||||
if isinstance(node, ast.Constant):
|
||||
return node.value
|
||||
elif isinstance(node, ast.Name):
|
||||
# TODO: a better way to handle variables
|
||||
raise ValueError(
|
||||
f"Arguments should be a Constant, got a variable {node.id} instead."
|
||||
)
|
||||
# 添加其他需要处理的 AST 节点类型
|
||||
return None
|
||||
|
||||
try:
|
||||
tree = ast.parse(code)
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Assign):
|
||||
targets = []
|
||||
for t in node.targets:
|
||||
targets.extend(get_target_names(t))
|
||||
if isinstance(node.value, ast.Call):
|
||||
func_name = node.value.func.id
|
||||
args = [ast.dump(arg) for arg in node.value.args]
|
||||
kwargs = {
|
||||
kw.arg: extract_value(kw.value) for kw in node.value.keywords
|
||||
}
|
||||
print(f"Input: {code.strip()}")
|
||||
print(f"Output Variables: {targets}")
|
||||
print(f"Function Name: {func_name}")
|
||||
print(f"Arguments: {args}")
|
||||
print(f"Keyword Arguments: {kwargs}")
|
||||
elif isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):
|
||||
targets = []
|
||||
func_name = extract_value(node.value.func)
|
||||
args = [extract_value(arg) for arg in node.value.args]
|
||||
kwargs = {kw.arg: extract_value(kw.value) for kw in node.value.keywords}
|
||||
|
||||
except SyntaxError:
|
||||
print(f"Input: {code.strip()}")
|
||||
print("No match found")
|
||||
|
||||
return targets, func_name, args, kwargs
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import json
|
||||
s='{"Reasoning": "The Docker icon has been successfully clicked, and the Docker application should now be opening. No further actions are required.", "Next Action": None}'
|
||||
json_str = json.loads(s)
|
||||
print(json_str)
|
||||
@@ -1,117 +0,0 @@
|
||||
|
||||
import os
|
||||
import logging
|
||||
import base64
|
||||
import requests
|
||||
|
||||
# from computer_use_demo.gui_agent.llm_utils import is_image_path, encode_image
|
||||
|
||||
def is_image_path(text):
|
||||
# Checking if the input text ends with typical image file extensions
|
||||
image_extensions = (".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".tif")
|
||||
if text.endswith(image_extensions):
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def encode_image(image_path):
|
||||
"""Encode image file to base64."""
|
||||
with open(image_path, "rb") as image_file:
|
||||
return base64.b64encode(image_file.read()).decode("utf-8")
|
||||
|
||||
|
||||
|
||||
# from openai import OpenAI
|
||||
# client = OpenAI(
|
||||
# api_key=os.environ.get("OPENAI_API_KEY")
|
||||
# )
|
||||
|
||||
|
||||
def run_oai_interleaved(messages: list, system: str, llm: str, api_key: str, max_tokens=256, temperature=0):
|
||||
|
||||
api_key = api_key or os.environ.get("OPENAI_API_KEY")
|
||||
if not api_key:
|
||||
raise ValueError("OPENAI_API_KEY is not set")
|
||||
|
||||
headers = {"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {api_key}"}
|
||||
|
||||
final_messages = [{"role": "system", "content": system}]
|
||||
|
||||
# image_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
|
||||
if type(messages) == list:
|
||||
for item in messages:
|
||||
contents = []
|
||||
if isinstance(item, dict):
|
||||
for cnt in item["content"]:
|
||||
if isinstance(cnt, str):
|
||||
if is_image_path(cnt):
|
||||
base64_image = encode_image(cnt)
|
||||
content = {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}}
|
||||
else:
|
||||
content = {"type": "text", "text": cnt}
|
||||
else:
|
||||
# in this case it is a text block from anthropic
|
||||
content = {"type": "text", "text": str(cnt)}
|
||||
|
||||
contents.append(content)
|
||||
|
||||
message = {"role": 'user', "content": contents}
|
||||
else: # str
|
||||
contents.append({"type": "text", "text": item})
|
||||
message = {"role": "user", "content": contents}
|
||||
|
||||
final_messages.append(message)
|
||||
|
||||
|
||||
elif isinstance(messages, str):
|
||||
final_messages = [{"role": "user", "content": messages}]
|
||||
# import pdb; pdb.set_trace()
|
||||
|
||||
print("[oai] sending messages:", {"role": "user", "content": messages})
|
||||
|
||||
payload = {
|
||||
"model": llm,
|
||||
"messages": final_messages,
|
||||
"max_tokens": max_tokens,
|
||||
"temperature": temperature,
|
||||
# "stop": stop,
|
||||
}
|
||||
|
||||
# from IPython.core.debugger import Pdb; Pdb().set_trace()
|
||||
|
||||
response = requests.post(
|
||||
"https://api.openai.com/v1/chat/completions", headers=headers, json=payload
|
||||
)
|
||||
|
||||
try:
|
||||
text = response.json()['choices'][0]['message']['content']
|
||||
token_usage = int(response.json()['usage']['total_tokens'])
|
||||
return text, token_usage
|
||||
|
||||
# return error message if the response is not successful
|
||||
except Exception as e:
|
||||
print(f"Error in interleaved openAI: {e}. This may due to your invalid OPENAI_API_KEY. Please check the response: {response.json()} ")
|
||||
return response.json()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
api_key = os.environ.get("OPENAI_API_KEY")
|
||||
if not api_key:
|
||||
raise ValueError("OPENAI_API_KEY is not set")
|
||||
|
||||
text, token_usage = run_oai_interleaved(
|
||||
messages= [{"content": [
|
||||
"What is in the screenshot?",
|
||||
"./tmp/outputs/screenshot_0b04acbb783d4706bc93873d17ba8c05.png"],
|
||||
"role": "user"
|
||||
}],
|
||||
llm="gpt-4o-mini",
|
||||
system="You are a helpful assistant",
|
||||
api_key=api_key,
|
||||
max_tokens=256,
|
||||
temperature=0)
|
||||
|
||||
print(text, token_usage)
|
||||
# There is an introduction describing the Calyx... 36986
|
||||
@@ -1,107 +0,0 @@
|
||||
|
||||
import os
|
||||
import logging
|
||||
import base64
|
||||
import requests
|
||||
|
||||
import dashscope
|
||||
# from computer_use_demo.gui_agent.llm_utils import is_image_path, encode_image
|
||||
|
||||
def is_image_path(text):
|
||||
return False
|
||||
|
||||
def encode_image(image_path):
|
||||
return ""
|
||||
|
||||
|
||||
def run_qwen(messages: list, system: str, llm: str, api_key: str, max_tokens=256, temperature=0):
|
||||
|
||||
api_key = api_key or os.environ.get("QWEN_API_KEY")
|
||||
if not api_key:
|
||||
raise ValueError("QWEN_API_KEY is not set")
|
||||
|
||||
dashscope.api_key = api_key
|
||||
|
||||
# from IPython.core.debugger import Pdb; Pdb().set_trace()
|
||||
|
||||
final_messages = [{"role": "system", "content": [{"text": system}]}]
|
||||
# image_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg"
|
||||
if type(messages) == list:
|
||||
for item in messages:
|
||||
contents = []
|
||||
if isinstance(item, dict):
|
||||
for cnt in item["content"]:
|
||||
if isinstance(cnt, str):
|
||||
if is_image_path(cnt):
|
||||
# base64_image = encode_image(cnt)
|
||||
content = [{"image": cnt}]
|
||||
# content = {"type": "image_url", "image_url": {"url": image_url}}
|
||||
else:
|
||||
content = {"text": cnt}
|
||||
contents.append(content)
|
||||
|
||||
message = {"role": item["role"], "content": contents}
|
||||
else: # str
|
||||
contents.append({"text": item})
|
||||
message = {"role": "user", "content": contents}
|
||||
|
||||
final_messages.append(message)
|
||||
|
||||
print("[qwen-vl] sending messages:", final_messages)
|
||||
|
||||
response = dashscope.MultiModalConversation.call(
|
||||
model='qwen-vl-max-0809',
|
||||
messages=final_messages
|
||||
)
|
||||
|
||||
# from IPython.core.debugger import Pdb; Pdb().set_trace()
|
||||
|
||||
try:
|
||||
text = response.output.choices[0].message.content[0]['text']
|
||||
usage = response.usage
|
||||
|
||||
if "total_tokens" not in usage:
|
||||
token_usage = int(usage["input_tokens"] + usage["output_tokens"])
|
||||
else:
|
||||
token_usage = int(usage["total_tokens"])
|
||||
|
||||
return text, token_usage
|
||||
# return response.json()['choices'][0]['message']['content']
|
||||
# return error message if the response is not successful
|
||||
except Exception as e:
|
||||
print(f"Error in interleaved openAI: {e}. This may due to your invalid OPENAI_API_KEY. Please check the response: {response.json()} ")
|
||||
return response.json()
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
api_key = os.environ.get("QWEN_API_KEY")
|
||||
if not api_key:
|
||||
raise ValueError("QWEN_API_KEY is not set")
|
||||
|
||||
dashscope.api_key = api_key
|
||||
|
||||
final_messages = [{"role": "user",
|
||||
"content": [
|
||||
{"text": "What is in the screenshot?"},
|
||||
{"image": "./tmp/outputs/screenshot_0b04acbb783d4706bc93873d17ba8c05.png"}
|
||||
]
|
||||
}
|
||||
]
|
||||
response = dashscope.MultiModalConversation.call(model='qwen-vl-max-0809', messages=final_messages)
|
||||
|
||||
print(response)
|
||||
|
||||
text = response.output.choices[0].message.content[0]['text']
|
||||
usage = response.usage
|
||||
|
||||
if "total_tokens" not in usage:
|
||||
if "image_tokens" in usage:
|
||||
token_usage = usage["input_tokens"] + usage["output_tokens"] + usage["image_tokens"]
|
||||
else:
|
||||
token_usage = usage["input_tokens"] + usage["output_tokens"]
|
||||
else:
|
||||
token_usage = usage["total_tokens"]
|
||||
|
||||
print(text, token_usage)
|
||||
# The screenshot is from a video game... 1387
|
||||
@@ -1,44 +0,0 @@
|
||||
import base64
|
||||
import logging
|
||||
from .oai import run_oai_interleaved
|
||||
from .gemini import run_gemini_interleaved
|
||||
|
||||
def run_llm(prompt, llm="gpt-4o-mini", max_tokens=256, temperature=0, stop=None):
|
||||
log_prompt(prompt)
|
||||
|
||||
# turn string prompt into list
|
||||
if isinstance(prompt, str):
|
||||
prompt = [prompt]
|
||||
elif isinstance(prompt, list):
|
||||
pass
|
||||
else:
|
||||
raise ValueError(f"Invalid prompt type: {type(prompt)}")
|
||||
|
||||
if llm.startswith("gpt"): # gpt series
|
||||
out = run_oai_interleaved(
|
||||
prompt,
|
||||
llm,
|
||||
max_tokens,
|
||||
temperature,
|
||||
stop
|
||||
)
|
||||
elif llm.startswith("gemini"): # gemini series
|
||||
out = run_gemini_interleaved(
|
||||
prompt,
|
||||
llm,
|
||||
max_tokens,
|
||||
temperature,
|
||||
stop
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Invalid llm: {llm}")
|
||||
logging.info(
|
||||
f"========Output for {llm}=======\n{out}\n============================")
|
||||
return out
|
||||
|
||||
def log_prompt(prompt):
|
||||
prompt_display = [prompt] if isinstance(prompt, str) else prompt
|
||||
prompt_display = "\n\n".join(prompt_display)
|
||||
logging.info(
|
||||
f"========Prompt=======\n{prompt_display}\n============================")
|
||||
|
||||
236
demo/loop.py
@@ -1,236 +0,0 @@
|
||||
"""
|
||||
Agentic sampling loop that calls the Anthropic API and local implenmentation of anthropic-defined computer use tools.
|
||||
"""
|
||||
import time
|
||||
import json
|
||||
import asyncio
|
||||
import platform
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import Any, cast, Dict
|
||||
|
||||
from anthropic import Anthropic, AnthropicBedrock, AnthropicVertex, APIResponse
|
||||
from anthropic.types import (
|
||||
ToolResultBlockParam,
|
||||
TextBlock,
|
||||
)
|
||||
from anthropic.types.beta import (
|
||||
BetaContentBlock,
|
||||
BetaContentBlockParam,
|
||||
BetaImageBlockParam,
|
||||
BetaMessage,
|
||||
BetaMessageParam,
|
||||
BetaTextBlockParam,
|
||||
BetaToolResultBlockParam,
|
||||
)
|
||||
from tools import BashTool, ComputerTool, EditTool, ToolCollection, ToolResult
|
||||
|
||||
import torch
|
||||
|
||||
from gui_agent.anthropic_agent import AnthropicActor
|
||||
from executor.anthropic_executor import AnthropicExecutor
|
||||
from omniparser_agent.vlm_agent import OmniParser, VLMAgent
|
||||
from tools.colorful_text import colorful_text_showui, colorful_text_vlm
|
||||
from tools.screen_capture import get_screenshot
|
||||
from gui_agent.llm_utils.oai import encode_image
|
||||
|
||||
|
||||
BETA_FLAG = "computer-use-2024-10-22"
|
||||
|
||||
|
||||
class APIProvider(StrEnum):
|
||||
ANTHROPIC = "anthropic"
|
||||
BEDROCK = "bedrock"
|
||||
VERTEX = "vertex"
|
||||
OPENAI = "openai"
|
||||
QWEN = "qwen"
|
||||
|
||||
|
||||
PROVIDER_TO_DEFAULT_MODEL_NAME: dict[APIProvider, str] = {
|
||||
APIProvider.ANTHROPIC: "claude-3-5-sonnet-20241022",
|
||||
APIProvider.BEDROCK: "anthropic.claude-3-5-sonnet-20241022-v2:0",
|
||||
APIProvider.VERTEX: "claude-3-5-sonnet-v2@20241022",
|
||||
# APIProvider.OPENAI: "gpt-4o",
|
||||
# APIProvider.QWEN: "qwen2vl",
|
||||
}
|
||||
|
||||
|
||||
# This system prompt is optimized for the Docker environment in this repository and
|
||||
# specific tool combinations enabled.
|
||||
# We encourage modifying this system prompt to ensure the model has context for the
|
||||
# environment it is running in, and to provide any additional information that may be
|
||||
# helpful for the task at hand.
|
||||
SYSTEM_PROMPT = f"""<SYSTEM_CAPABILITY>
|
||||
* You are utilizing a Windows system with internet access.
|
||||
* The current date is {datetime.today().strftime('%A, %B %d, %Y')}.
|
||||
</SYSTEM_CAPABILITY>
|
||||
"""
|
||||
|
||||
import base64
|
||||
from PIL import Image
|
||||
from io import BytesIO
|
||||
|
||||
def sampling_loop_sync(
|
||||
*,
|
||||
model: str,
|
||||
provider: APIProvider | None,
|
||||
system_prompt_suffix: str,
|
||||
messages: list[BetaMessageParam],
|
||||
output_callback: Callable[[BetaContentBlock], None],
|
||||
tool_output_callback: Callable[[ToolResult, str], None],
|
||||
api_response_callback: Callable[[APIResponse[BetaMessage]], None],
|
||||
api_key: str,
|
||||
only_n_most_recent_images: int | None = 2,
|
||||
max_tokens: int = 4096,
|
||||
selected_screen: int = 0
|
||||
):
|
||||
"""
|
||||
Synchronous agentic sampling loop for the assistant/tool interaction of computer use.
|
||||
"""
|
||||
print('in sampling_loop_sync, model:', model)
|
||||
if model == "claude-3-5-sonnet-20241022":
|
||||
omniparser = OmniParser(url="http://127.0.0.1:8000/send_text/",
|
||||
selected_screen=selected_screen,)
|
||||
|
||||
# Register Actor and Executor
|
||||
actor = AnthropicActor(
|
||||
model=model,
|
||||
provider=provider,
|
||||
system_prompt_suffix=system_prompt_suffix,
|
||||
api_key=api_key,
|
||||
api_response_callback=api_response_callback,
|
||||
max_tokens=max_tokens,
|
||||
only_n_most_recent_images=only_n_most_recent_images,
|
||||
selected_screen=selected_screen
|
||||
)
|
||||
|
||||
# from IPython.core.debugger import Pdb; Pdb().set_trace()
|
||||
executor = AnthropicExecutor(
|
||||
output_callback=output_callback,
|
||||
tool_output_callback=tool_output_callback,
|
||||
selected_screen=selected_screen
|
||||
)
|
||||
|
||||
elif model == "omniparser + gpt-4o" or model == "omniparser + phi35v":
|
||||
omniparser = OmniParser(url="http://127.0.0.1:8000/send_text/",
|
||||
selected_screen=selected_screen,)
|
||||
|
||||
actor = VLMAgent(
|
||||
model=model,
|
||||
provider=provider,
|
||||
system_prompt_suffix=system_prompt_suffix,
|
||||
api_key=api_key,
|
||||
api_response_callback=api_response_callback,
|
||||
selected_screen=selected_screen,
|
||||
output_callback=output_callback,
|
||||
)
|
||||
|
||||
executor = AnthropicExecutor(
|
||||
output_callback=output_callback,
|
||||
tool_output_callback=tool_output_callback,
|
||||
selected_screen=selected_screen
|
||||
)
|
||||
|
||||
# elif model == "gpt-4o + ShowUI" or model == "qwen2vl + ShowUI":
|
||||
# planner = VLMPlanner(
|
||||
# model=model,
|
||||
# provider=provider,
|
||||
# system_prompt_suffix=system_prompt_suffix,
|
||||
# api_key=api_key,
|
||||
# api_response_callback=api_response_callback,
|
||||
# selected_screen=selected_screen,
|
||||
# output_callback=output_callback,
|
||||
# )
|
||||
|
||||
# if torch.cuda.is_available(): device = torch.device("cuda")
|
||||
# elif torch.backends.mps.is_available(): device = torch.device("mps")
|
||||
# else: device = torch.device("cpu") # support: 'cpu', 'mps', 'cuda'
|
||||
# print(f"showUI-2B inited on device: {device}.")
|
||||
|
||||
# actor = ShowUIActor(
|
||||
# model_path="./showui-2b/",
|
||||
# # Replace with your local path, e.g., "C:\\code\\ShowUI-2B", "/Users/your_username/ShowUI-2B/".
|
||||
# device=device,
|
||||
# split='web', # 'web' or 'phone'
|
||||
# selected_screen=selected_screen,
|
||||
# output_callback=output_callback,
|
||||
# )
|
||||
|
||||
# executor = ShowUIExecutor(
|
||||
# output_callback=output_callback,
|
||||
# tool_output_callback=tool_output_callback,
|
||||
# selected_screen=selected_screen
|
||||
# )
|
||||
|
||||
else:
|
||||
raise ValueError(f"Model {model} not supported")
|
||||
print(f"Model Inited: {model}, Provider: {provider}")
|
||||
|
||||
tool_result_content = None
|
||||
|
||||
print(f"Start the message loop. User messages: {messages}")
|
||||
|
||||
if model == "claude-3-5-sonnet-20241022": # Anthropic loop
|
||||
while True:
|
||||
parsed_screen = omniparser() # parsed_screen: {"som_image_base64": dino_labled_img, "parsed_content_list": parsed_content_list, "screen_info"}
|
||||
import pdb; pdb.set_trace()
|
||||
screen_info_block = TextBlock(text='Below is the structured accessibility information of the current UI screen, which includes text and icons you can operate on, take these information into account when you are making the prediction for the next action. Note you will still need to take screenshot to get the image: \n' + parsed_screen['screen_info'], type='text')
|
||||
# # messages[-1]['content'].append(screen_info_block)
|
||||
screen_info_dict = {"role": "user", "content": [screen_info_block]}
|
||||
messages.append(screen_info_dict)
|
||||
response = actor(messages=messages)
|
||||
|
||||
for message, tool_result_content in executor(response, messages):
|
||||
yield message
|
||||
|
||||
if not tool_result_content:
|
||||
return messages
|
||||
|
||||
messages.append({"content": tool_result_content, "role": "user"})
|
||||
|
||||
elif model == "omniparser + gpt-4o" or model == "omniparser + phi35v":
|
||||
while True:
|
||||
parsed_screen = omniparser()
|
||||
response, vlm_response_json = actor(messages=messages, parsed_screen=parsed_screen)
|
||||
|
||||
for message, tool_result_content in executor(response, messages):
|
||||
yield message
|
||||
|
||||
if not tool_result_content:
|
||||
return messages
|
||||
|
||||
# import pdb; pdb.set_trace()
|
||||
# messages.append({"role": "user",
|
||||
# "content": ["History plan:\n" + str(vlm_response_json['Reasoning'])]})
|
||||
|
||||
# messages.append({"content": tool_result_content, "role": "user"})
|
||||
|
||||
elif model == "gpt-4o + ShowUI" or model == "qwen2vl + ShowUI": # ShowUI loop
|
||||
while True:
|
||||
vlm_response = planner(messages=messages)
|
||||
|
||||
next_action = json.loads(vlm_response).get("Next Action")
|
||||
yield next_action
|
||||
|
||||
if next_action == None or next_action == "" or next_action == "None":
|
||||
final_sc, final_sc_path = get_screenshot(selected_screen=selected_screen)
|
||||
output_callback(f'No more actions from {colorful_text_vlm}. End of task. Final State:\n<img src="data:image/png;base64,{encode_image(str(final_sc_path))}">',
|
||||
sender="bot")
|
||||
yield None
|
||||
|
||||
output_callback(f"{colorful_text_vlm} sending action to {colorful_text_showui}:\n{next_action}", sender="bot")
|
||||
|
||||
actor_response = actor(messages=next_action)
|
||||
yield actor_response
|
||||
|
||||
for message, tool_result_content in executor(actor_response, messages):
|
||||
time.sleep(1)
|
||||
yield message
|
||||
|
||||
# since showui executor has no feedback for now, we use "actor_response" to represent its response
|
||||
# update messages for the next loop
|
||||
messages.append({"role": "user",
|
||||
"content": ["History plan:\n" + str(json.loads(vlm_response)) +
|
||||
"\nHistory actions:\n" + str(actor_response["content"])]})
|
||||
print(f"End of loop. Messages: {str(messages)[:100000]}. Total cost: $USD{planner.total_cost:.5f}")
|
||||
@@ -1,417 +0,0 @@
|
||||
import json
|
||||
import asyncio
|
||||
import platform
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import Any, cast, Dict, Callable
|
||||
import uuid
|
||||
import requests
|
||||
from PIL import Image, ImageDraw
|
||||
import base64
|
||||
from io import BytesIO
|
||||
|
||||
from anthropic import Anthropic, AnthropicBedrock, AnthropicVertex, APIResponse
|
||||
from anthropic.types import TextBlock, ToolResultBlockParam
|
||||
from anthropic.types.beta import BetaMessage, BetaTextBlock, BetaToolUseBlock, BetaMessageParam, BetaUsage
|
||||
|
||||
from tools.screen_capture import get_screenshot
|
||||
from gui_agent.llm_utils.oai import run_oai_interleaved, encode_image
|
||||
from gui_agent.llm_utils.qwen import run_qwen
|
||||
from gui_agent.llm_utils.llm_utils import extract_data
|
||||
from tools.colorful_text import colorful_text_showui, colorful_text_vlm
|
||||
|
||||
|
||||
SYSTEM_PROMPT = f"""<SYSTEM_CAPABILITY>
|
||||
* You are utilizing a Windows system with internet access.
|
||||
* The current date is {datetime.today().strftime('%A, %B %d, %Y')}.
|
||||
</SYSTEM_CAPABILITY>
|
||||
"""
|
||||
|
||||
|
||||
class OmniParser:
|
||||
def __init__(self,
|
||||
url: str,
|
||||
selected_screen: int = 0) -> None:
|
||||
self.url = url
|
||||
self.selected_screen = selected_screen
|
||||
|
||||
def __call__(self,):
|
||||
screenshot, screenshot_path = get_screenshot(selected_screen=self.selected_screen)
|
||||
screenshot_path = str(screenshot_path)
|
||||
image_base64 = encode_image(screenshot_path)
|
||||
|
||||
# response = requests.post(self.url, json={"base64_image": image_base64, 'prompt': 'omniparser process'})
|
||||
# response_json = response.json()
|
||||
# example response_json: {"som_image_base64": dino_labled_img, "parsed_content_list": parsed_content_list, "latency": 0.1}
|
||||
# Debug
|
||||
response_json = {"som_image_base64": image_base64, "parsed_content_list": ['debug1', 'debug2'], "latency": 0.1}
|
||||
print('omniparser latency:', response_json['latency'])
|
||||
response_json = self.reformat_messages(response_json)
|
||||
return response_json
|
||||
|
||||
def reformat_messages(self, response_json: dict):
|
||||
parsed_content_list = response_json["parsed_content_list"]
|
||||
screen_info = ""
|
||||
# Debug
|
||||
# for idx, element in enumerate(parsed_content_list):
|
||||
# element['idx'] = idx
|
||||
# if element['type'] == 'text':
|
||||
# # screen_info += f'''<p id={idx} class="text" alt="{element['content']}"> </p>\n'''
|
||||
# screen_info += f'ID: {idx}, Text: {element["content"]}\n'
|
||||
# elif element['type'] == 'icon':
|
||||
# # screen_info += f'''<img id={idx} class="icon" alt="{element['content']}"> </img>\n'''
|
||||
# screen_info += f'ID: {idx}, Icon: {element["content"]}\n'
|
||||
response_json['screen_info'] = screen_info
|
||||
return response_json
|
||||
|
||||
|
||||
|
||||
class VLMAgent:
|
||||
def __init__(
|
||||
self,
|
||||
model: str,
|
||||
provider: str,
|
||||
system_prompt_suffix: str,
|
||||
api_key: str,
|
||||
output_callback: Callable,
|
||||
api_response_callback: Callable,
|
||||
max_tokens: int = 4096,
|
||||
only_n_most_recent_images: int | None = None,
|
||||
selected_screen: int = 0,
|
||||
print_usage: bool = True,
|
||||
):
|
||||
if model == "gpt-4o + ShowUI":
|
||||
self.model = "gpt-4o-2024-11-20"
|
||||
elif model == "gpt-4o-mini + ShowUI":
|
||||
self.model = "gpt-4o-mini" # "gpt-4o-mini"
|
||||
elif model == "qwen2vl + ShowUI":
|
||||
self.model = "qwen2vl"
|
||||
elif model == "omniparser + gpt-4o":
|
||||
self.model = "gpt-4o-2024-11-20"
|
||||
else:
|
||||
raise ValueError(f"Model {model} not supported")
|
||||
|
||||
self.provider = provider
|
||||
self.system_prompt_suffix = system_prompt_suffix
|
||||
self.api_key = api_key
|
||||
self.api_response_callback = api_response_callback
|
||||
self.max_tokens = max_tokens
|
||||
self.only_n_most_recent_images = only_n_most_recent_images
|
||||
self.selected_screen = selected_screen
|
||||
self.output_callback = output_callback
|
||||
|
||||
self.print_usage = print_usage
|
||||
self.total_token_usage = 0
|
||||
self.total_cost = 0
|
||||
|
||||
self.system = (
|
||||
# f"{SYSTEM_PROMPT}{' ' + system_prompt_suffix if system_prompt_suffix else ''}"
|
||||
f"{system_prompt_suffix}"
|
||||
)
|
||||
|
||||
def __call__(self, messages: list, parsed_screen: list[str, list]):
|
||||
# example parsed_screen: {"som_image_base64": dino_labled_img, "parsed_content_list": parsed_content_list, "screen_info"}
|
||||
screen_info = parsed_screen["screen_info"]
|
||||
# drop looping actions msg, byte image etc
|
||||
planner_messages = messages
|
||||
# planner_messages = _message_filter_callback(messages)
|
||||
|
||||
print(f"filtered_messages: {planner_messages}\n\n", "full messages:", messages)
|
||||
# import pdb; pdb.set_trace()
|
||||
planner_messages = _keep_latest_images(planner_messages)
|
||||
# if self.only_n_most_recent_images:
|
||||
# _maybe_filter_to_n_most_recent_images(planner_messages, self.only_n_most_recent_images)
|
||||
|
||||
system = self._get_system_prompt(screen_info) + self.system_prompt_suffix
|
||||
|
||||
# Take a screenshot
|
||||
screenshot, screenshot_path = get_screenshot(selected_screen=self.selected_screen)
|
||||
screen_width, screen_height = screenshot.size
|
||||
screenshot_path = str(screenshot_path)
|
||||
image_base64 = encode_image(screenshot_path)
|
||||
|
||||
som_image_data = base64.b64decode(parsed_screen['som_image_base64'])
|
||||
som_screenshot_path = f"./tmp/outputs/screenshot_som_{uuid.uuid4().hex}.png"
|
||||
with open(som_screenshot_path, "wb") as f:
|
||||
f.write(som_image_data)
|
||||
|
||||
self.output_callback(f'Screenshot for {colorful_text_vlm}:\n<img src="data:image/png;base64,{image_base64}">',
|
||||
sender="bot")
|
||||
self.output_callback(f'Set of Marks Screenshot for {colorful_text_vlm}:\n<img src="data:image/png;base64,{parsed_screen['som_image_base64']}">', sender="bot")
|
||||
|
||||
|
||||
if isinstance(planner_messages[-1], dict):
|
||||
if not isinstance(planner_messages[-1]["content"], list):
|
||||
planner_messages[-1]["content"] = [planner_messages[-1]["content"]]
|
||||
planner_messages[-1]["content"].append(screenshot_path)
|
||||
planner_messages[-1]["content"].append(som_screenshot_path)
|
||||
|
||||
print(f"Sending messages to VLMPlanner : {planner_messages}")
|
||||
|
||||
if "gpt" in self.model:
|
||||
vlm_response, token_usage = run_oai_interleaved(
|
||||
messages=planner_messages,
|
||||
system=system,
|
||||
llm=self.model,
|
||||
api_key=self.api_key,
|
||||
max_tokens=self.max_tokens,
|
||||
temperature=0,
|
||||
)
|
||||
print(f"oai token usage: {token_usage}")
|
||||
self.total_token_usage += token_usage
|
||||
self.total_cost += (token_usage * 0.15 / 1000000) # https://openai.com/api/pricing/
|
||||
|
||||
elif "qwen" in self.model:
|
||||
vlm_response, token_usage = run_qwen(
|
||||
messages=planner_messages,
|
||||
system=system,
|
||||
llm=self.model,
|
||||
api_key=self.api_key,
|
||||
max_tokens=self.max_tokens,
|
||||
temperature=0,
|
||||
)
|
||||
print(f"qwen token usage: {token_usage}")
|
||||
self.total_token_usage += token_usage
|
||||
self.total_cost += (token_usage * 0.02 / 7.25 / 1000) # 1USD=7.25CNY, https://help.aliyun.com/zh/dashscope/developer-reference/tongyi-qianwen-vl-plus-api
|
||||
elif "phi" in self.model:
|
||||
pass # TODO
|
||||
else:
|
||||
raise ValueError(f"Model {self.model} not supported")
|
||||
|
||||
print(f"VLMPlanner response: {vlm_response}")
|
||||
|
||||
if self.print_usage:
|
||||
print(f"VLMPlanner total token usage so far: {self.total_token_usage}. Total cost so far: $USD{self.total_cost:.5f}")
|
||||
|
||||
vlm_response_json = extract_data(vlm_response, "json")
|
||||
vlm_response_json = json.loads(vlm_response_json)
|
||||
|
||||
# map "box_id" to "idx" in parsed_screen, and output the xy coordinate of bbox
|
||||
# TODO add try except for the case when "box_id" is not in the response
|
||||
# if 'Box ID' in vlm_response_json:
|
||||
try:
|
||||
bbox = parsed_screen["parsed_content_list"][int(vlm_response_json["Box ID"])]["bbox"]
|
||||
vlm_response_json["coordinate"] = [int((bbox[0] + bbox[2]) / 2 * screen_width), int((bbox[1] + bbox[3]) / 2 * screen_height)]
|
||||
# draw a circle on the screenshot image to indicate the action
|
||||
self.draw_action(vlm_response_json, image_base64)
|
||||
except:
|
||||
print("No Box ID in the response.")
|
||||
|
||||
|
||||
# vlm_plan_str = '\n'.join([f'{key}: {value}' for key, value in json.loads(response).items()])
|
||||
vlm_plan_str = ""
|
||||
for key, value in vlm_response_json.items():
|
||||
if key == "Reasoning":
|
||||
vlm_plan_str += f'{value}'
|
||||
else:
|
||||
vlm_plan_str += f'\n{key}: {value}'
|
||||
|
||||
# self.output_callback(f"{colorful_text_vlm}:\n{vlm_plan_str}", sender="bot")
|
||||
|
||||
# construct the response so that anthropicExcutor can execute the tool
|
||||
analysis = BetaTextBlock(text=vlm_plan_str, type='text')
|
||||
if 'coordinate' in vlm_response_json:
|
||||
move_cursor_block = BetaToolUseBlock(id=f'toolu_{uuid.uuid4()}',
|
||||
input={'action': 'mouse_move', 'coordinate': vlm_response_json["coordinate"]},
|
||||
name='computer', type='tool_use')
|
||||
response_content = [analysis, move_cursor_block]
|
||||
else:
|
||||
response_content = [analysis]
|
||||
if vlm_response_json["Next Action"] == "type":
|
||||
click_block = BetaToolUseBlock(id=f'toolu_{uuid.uuid4()}', input={'action': 'left_click'}, name='computer', type='tool_use')
|
||||
sim_content_block = BetaToolUseBlock(id=f'toolu_{uuid.uuid4()}',
|
||||
input={'action': vlm_response_json["Next Action"], 'text': vlm_response_json["value"]},
|
||||
name='computer', type='tool_use')
|
||||
response_content.extend([click_block, sim_content_block])
|
||||
elif vlm_response_json["Next Action"] == "None":
|
||||
print("Task paused/completed.")
|
||||
else:
|
||||
sim_content_block = BetaToolUseBlock(id=f'toolu_{uuid.uuid4()}',
|
||||
input={'action': vlm_response_json["Next Action"]},
|
||||
name='computer', type='tool_use')
|
||||
response_content.append(sim_content_block)
|
||||
|
||||
response = BetaMessage(id=f'toolu_{uuid.uuid4()}', content=response_content, model='', role='assistant', type='message', stop_reason='tool_use', usage=BetaUsage(input_tokens=0, output_tokens=0))
|
||||
return response, vlm_response_json
|
||||
|
||||
|
||||
def _api_response_callback(self, response: APIResponse):
|
||||
self.api_response_callback(response)
|
||||
|
||||
|
||||
def reformat_messages(self, messages: list):
|
||||
pass
|
||||
|
||||
def _get_system_prompt(self, screen_info: str = ""):
|
||||
datetime_str = datetime.now().strftime("%A, %B %d, %Y")
|
||||
os_name = platform.system()
|
||||
return f"""
|
||||
You are using an {os_name} device.
|
||||
You are able to use a mouse and keyboard to interact with the computer based on the given task and screenshot.
|
||||
You can only interact with the desktop GUI (no terminal or application menu access).
|
||||
|
||||
You may be given some history plan and actions, this is the response from the previous loop.
|
||||
You should carefully consider your plan base on the task, screenshot, and history actions.
|
||||
|
||||
Here is the list of all detected bounding boxes by IDs on the screen and their description:{screen_info}
|
||||
|
||||
Your available "Next Action" only include:
|
||||
- type: type a string of text.
|
||||
- left_click: Describe the ui element to be clicked.
|
||||
- enter: Press an enter key.
|
||||
- escape: Press an ESCAPE key.
|
||||
- hover: Describe the ui element to be hovered.
|
||||
- scroll: Scroll the screen, you must specify up or down.
|
||||
- press: Describe the ui element to be pressed.
|
||||
|
||||
Based on the visual information from the screenshot image and the detected bounding boxes, please determine the next action, the Box ID you should operate on, and the value (if the action is 'type') in order to complete the task.
|
||||
|
||||
Output format:
|
||||
```json
|
||||
{{
|
||||
"Reasoning": str, # describe what is in the current screen, taking into account the history, then describe your step-by-step thoughts on how to achieve the task, choose one action from available actions at a time.
|
||||
"Next Action": "action_type, action description" | "None" # one action at a time, describe it in short and precisely.
|
||||
'Box ID': n,
|
||||
'value': "xxx" # if the action is type, you should provide the text to type.
|
||||
}}
|
||||
```
|
||||
|
||||
One Example:
|
||||
```json
|
||||
{{
|
||||
"Reasoning": "The current screen shows google result of amazon, in previous action I have searched amazon on google. Then I need to click on the first search results to go to amazon.com.",
|
||||
"Next Action": "left_click",
|
||||
'Box ID': m,
|
||||
}}
|
||||
```
|
||||
|
||||
Another Example:
|
||||
```json
|
||||
{{
|
||||
"Reasoning": "The current screen shows the front page of amazon. There is no previous action. Therefore I need to type "Apple watch" in the search bar.",
|
||||
"Next Action": "type",
|
||||
'Box ID': n,
|
||||
'value': "Apple watch"
|
||||
}}
|
||||
```
|
||||
|
||||
IMPORTANT NOTES:
|
||||
1. You should only give a single action at a time.
|
||||
2. You should give an analysis to the current screen, and reflect on what has been done by looking at the history, then describe your step-by-step thoughts on how to achieve the task.
|
||||
3. Attach the next action prediction in the "Next Action".
|
||||
4. You should not include other actions, such as keyboard shortcuts.
|
||||
5. When the task is completed, you should say "Next Action": "None" in the json field.
|
||||
"""
|
||||
def draw_action(self, vlm_response_json, image_base64):
|
||||
# draw a circle using the coordinate in parsed_screen['som_image_base64']
|
||||
image_data = base64.b64decode(image_base64)
|
||||
image = Image.open(BytesIO(image_data))
|
||||
|
||||
draw = ImageDraw.Draw(image)
|
||||
x, y = vlm_response_json["coordinate"]
|
||||
radius = 10
|
||||
draw.ellipse((x - radius, y - radius, x + radius, y + radius), outline='red', width=3)
|
||||
buffered = BytesIO()
|
||||
image.save('demo.png')
|
||||
image.save(buffered, format="PNG")
|
||||
image_with_circle_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
||||
self.output_callback(f'Action performed on the Screenshot (red circle), for {colorful_text_vlm}:\n<img src="data:image/png;base64,{image_with_circle_base64}">', sender="bot")
|
||||
|
||||
|
||||
def _keep_latest_images(messages):
|
||||
for i in range(len(messages)-1):
|
||||
if isinstance(messages[i]["content"], list):
|
||||
for cnt in messages[i]["content"]:
|
||||
if isinstance(cnt, str):
|
||||
if cnt.endswith((".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".tif")):
|
||||
messages[i]["content"].remove(cnt)
|
||||
return messages
|
||||
|
||||
|
||||
def _maybe_filter_to_n_most_recent_images(
|
||||
messages: list[BetaMessageParam],
|
||||
images_to_keep: int,
|
||||
min_removal_threshold: int = 10,
|
||||
):
|
||||
"""
|
||||
With the assumption that images are screenshots that are of diminishing value as
|
||||
the conversation progresses, remove all but the final `images_to_keep` tool_result
|
||||
images in place, with a chunk of min_removal_threshold to reduce the amount we
|
||||
break the implicit prompt cache.
|
||||
"""
|
||||
if images_to_keep is None:
|
||||
return messages
|
||||
|
||||
tool_result_blocks = cast(
|
||||
list[ToolResultBlockParam],
|
||||
[
|
||||
item
|
||||
for message in messages
|
||||
for item in (
|
||||
message["content"] if isinstance(message["content"], list) else []
|
||||
)
|
||||
if isinstance(item, dict) and item.get("type") == "tool_result"
|
||||
],
|
||||
)
|
||||
|
||||
total_images = sum(
|
||||
1
|
||||
for tool_result in tool_result_blocks
|
||||
for content in tool_result.get("content", [])
|
||||
if isinstance(content, dict) and content.get("type") == "image"
|
||||
)
|
||||
|
||||
images_to_remove = total_images - images_to_keep
|
||||
# for better cache behavior, we want to remove in chunks
|
||||
images_to_remove -= images_to_remove % min_removal_threshold
|
||||
|
||||
for tool_result in tool_result_blocks:
|
||||
if isinstance(tool_result.get("content"), list):
|
||||
new_content = []
|
||||
for content in tool_result.get("content", []):
|
||||
if isinstance(content, dict) and content.get("type") == "image":
|
||||
if images_to_remove > 0:
|
||||
images_to_remove -= 1
|
||||
continue
|
||||
new_content.append(content)
|
||||
tool_result["content"] = new_content
|
||||
|
||||
|
||||
def _message_filter_callback(messages):
|
||||
filtered_list = []
|
||||
try:
|
||||
for msg in messages:
|
||||
if msg.get('role') in ['user']:
|
||||
if not isinstance(msg["content"], list):
|
||||
msg["content"] = [msg["content"]]
|
||||
if isinstance(msg["content"][0], TextBlock):
|
||||
filtered_list.append(str(msg["content"][0].text)) # User message
|
||||
elif isinstance(msg["content"][0], str):
|
||||
filtered_list.append(msg["content"][0]) # User message
|
||||
else:
|
||||
print("[_message_filter_callback]: drop message", msg)
|
||||
continue
|
||||
|
||||
# elif msg.get('role') in ['assistant']:
|
||||
# if isinstance(msg["content"][0], TextBlock):
|
||||
# msg["content"][0] = str(msg["content"][0].text)
|
||||
# elif isinstance(msg["content"][0], BetaTextBlock):
|
||||
# msg["content"][0] = str(msg["content"][0].text)
|
||||
# elif isinstance(msg["content"][0], BetaToolUseBlock):
|
||||
# msg["content"][0] = str(msg['content'][0].input)
|
||||
# elif isinstance(msg["content"][0], Dict) and msg["content"][0]["content"][-1]["type"] == "image":
|
||||
# msg["content"][0] = f'<img src="data:image/png;base64,{msg["content"][0]["content"][-1]["source"]["data"]}">'
|
||||
# else:
|
||||
# print("[_message_filter_callback]: drop message", msg)
|
||||
# continue
|
||||
# filtered_list.append(msg["content"][0]) # User message
|
||||
|
||||
else:
|
||||
print("[_message_filter_callback]: drop message", msg)
|
||||
continue
|
||||
|
||||
except Exception as e:
|
||||
print("[_message_filter_callback]: error", e)
|
||||
|
||||
return filtered_list
|
||||
@@ -1,78 +0,0 @@
|
||||
# uvicorn remote_request:app --host 0.0.0.0 --port 8000 --reload
|
||||
|
||||
import sys
|
||||
import os
|
||||
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from utils import get_som_labeled_img, check_ocr_box, get_caption_model_processor, get_yolo_model
|
||||
import torch
|
||||
from PIL import Image
|
||||
from typing import Dict, Tuple, List
|
||||
import base64
|
||||
|
||||
|
||||
config = {
|
||||
'som_model_path': '../weights/icon_detect_v1_5/model_v1_5.pt',
|
||||
'device': 'cpu',
|
||||
'caption_model_name': 'florence2',
|
||||
'caption_model_path': '../weights/icon_caption_florence',
|
||||
'BOX_TRESHOLD': 0.05
|
||||
}
|
||||
|
||||
|
||||
class Omniparser(object):
|
||||
def __init__(self, config: Dict):
|
||||
self.config = config
|
||||
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||
|
||||
self.som_model = get_yolo_model(model_path=config['som_model_path'])
|
||||
self.caption_model_processor = get_caption_model_processor(model_name=config['caption_model_name'], model_name_or_path=config['caption_model_path'], device=device)
|
||||
print('Omniparser initialized!!!')
|
||||
|
||||
def parse(self, image_base64: str):
|
||||
image_path = '../imgs/demo_image.jpg'
|
||||
with open(image_path, "wb") as fh:
|
||||
fh.write(base64.b64decode(image_base64))
|
||||
print('Parsing image:', image_path)
|
||||
|
||||
image = Image.open(image_path)
|
||||
print('image size:', image.size)
|
||||
|
||||
box_overlay_ratio = max(image.size) / 3200
|
||||
draw_bbox_config = {
|
||||
'text_scale': 0.8 * box_overlay_ratio,
|
||||
'text_thickness': max(int(2 * box_overlay_ratio), 1),
|
||||
'text_padding': max(int(3 * box_overlay_ratio), 1),
|
||||
'thickness': max(int(3 * box_overlay_ratio), 1),
|
||||
}
|
||||
BOX_TRESHOLD = config['BOX_TRESHOLD']
|
||||
|
||||
ocr_bbox_rslt, is_goal_filtered = check_ocr_box(image_path, display_img = False, output_bb_format='xyxy', goal_filtering=None, easyocr_args={'paragraph': False, 'text_threshold':0.8}, use_paddleocr=True)
|
||||
text, ocr_bbox = ocr_bbox_rslt
|
||||
dino_labled_img, label_coordinates, parsed_content_list = get_som_labeled_img(image_path, self.som_model, BOX_TRESHOLD = BOX_TRESHOLD, output_coord_in_ratio=True, ocr_bbox=ocr_bbox,draw_bbox_config=draw_bbox_config, caption_model_processor=self.caption_model_processor, ocr_text=text,use_local_semantics=True, iou_threshold=0.7, scale_img=False, batch_size=128)
|
||||
with open('../imgs/demo_image_som.jpg', "wb") as fh:
|
||||
fh.write(base64.b64decode(dino_labled_img))
|
||||
|
||||
return dino_labled_img, parsed_content_list
|
||||
|
||||
|
||||
from fastapi import FastAPI
|
||||
from pydantic import BaseModel
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
class Item(BaseModel):
|
||||
base64_image: str
|
||||
prompt: str
|
||||
|
||||
Omniparser = Omniparser(config)
|
||||
|
||||
@app.post("/send_text/")
|
||||
async def send_text(item: Item):
|
||||
print('start parsing...')
|
||||
import time
|
||||
start = time.time()
|
||||
dino_labled_img, parsed_content_list = Omniparser.parse(item.base64_image)
|
||||
latency = time.time() - start
|
||||
print('time:', latency)
|
||||
return {"som_image_base64": dino_labled_img, "parsed_content_list": parsed_content_list, 'latency': latency}
|
||||
|
Before Width: | Height: | Size: 1.4 MiB |
@@ -1,136 +0,0 @@
|
||||
import asyncio
|
||||
import os
|
||||
from typing import ClassVar, Literal
|
||||
|
||||
from anthropic.types.beta import BetaToolBash20241022Param
|
||||
|
||||
from .base import BaseAnthropicTool, CLIResult, ToolError, ToolResult
|
||||
|
||||
|
||||
class _BashSession:
|
||||
"""A session of a bash shell."""
|
||||
|
||||
_started: bool
|
||||
_process: asyncio.subprocess.Process
|
||||
|
||||
command: str = "/bin/bash"
|
||||
_output_delay: float = 0.2 # seconds
|
||||
_timeout: float = 120.0 # seconds
|
||||
_sentinel: str = "<<exit>>"
|
||||
|
||||
def __init__(self):
|
||||
self._started = False
|
||||
self._timed_out = False
|
||||
|
||||
async def start(self):
|
||||
if self._started:
|
||||
return
|
||||
|
||||
self._process = await asyncio.create_subprocess_shell(
|
||||
self.command,
|
||||
shell=False,
|
||||
stdin=asyncio.subprocess.PIPE,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
|
||||
self._started = True
|
||||
|
||||
def stop(self):
|
||||
"""Terminate the bash shell."""
|
||||
if not self._started:
|
||||
raise ToolError("Session has not started.")
|
||||
if self._process.returncode is not None:
|
||||
return
|
||||
self._process.terminate()
|
||||
|
||||
async def run(self, command: str):
|
||||
"""Execute a command in the bash shell."""
|
||||
if not self._started:
|
||||
raise ToolError("Session has not started.")
|
||||
if self._process.returncode is not None:
|
||||
return ToolResult(
|
||||
system="tool must be restarted",
|
||||
error=f"bash has exited with returncode {self._process.returncode}",
|
||||
)
|
||||
if self._timed_out:
|
||||
raise ToolError(
|
||||
f"timed out: bash has not returned in {self._timeout} seconds and must be restarted",
|
||||
)
|
||||
|
||||
# we know these are not None because we created the process with PIPEs
|
||||
assert self._process.stdin
|
||||
assert self._process.stdout
|
||||
assert self._process.stderr
|
||||
|
||||
# send command to the process
|
||||
self._process.stdin.write(
|
||||
command.encode() + f"; echo '{self._sentinel}'\n".encode()
|
||||
)
|
||||
await self._process.stdin.drain()
|
||||
|
||||
# read output from the process, until the sentinel is found
|
||||
output = ""
|
||||
try:
|
||||
async with asyncio.timeout(self._timeout):
|
||||
while True:
|
||||
await asyncio.sleep(self._output_delay)
|
||||
data = await self._process.stdout.readline()
|
||||
if not data:
|
||||
break
|
||||
line = data.decode()
|
||||
output += line
|
||||
if self._sentinel in line:
|
||||
output = output.replace(self._sentinel, "")
|
||||
break
|
||||
except asyncio.TimeoutError:
|
||||
self._timed_out = True
|
||||
raise ToolError(
|
||||
f"timed out: bash has not returned in {self._timeout} seconds and must be restarted",
|
||||
) from None
|
||||
|
||||
error = await self._process.stderr.read()
|
||||
error = error.decode()
|
||||
|
||||
return CLIResult(output=output.strip(), error=error.strip())
|
||||
|
||||
|
||||
class BashTool(BaseAnthropicTool):
|
||||
"""
|
||||
A tool that allows the agent to run bash commands.
|
||||
The tool parameters are defined by Anthropic and are not editable.
|
||||
"""
|
||||
|
||||
_session: _BashSession | None
|
||||
name: ClassVar[Literal["bash"]] = "bash"
|
||||
api_type: ClassVar[Literal["bash_20241022"]] = "bash_20241022"
|
||||
|
||||
def __init__(self):
|
||||
self._session = None
|
||||
super().__init__()
|
||||
|
||||
async def __call__(
|
||||
self, command: str | None = None, restart: bool = False, **kwargs
|
||||
):
|
||||
if restart:
|
||||
if self._session:
|
||||
self._session.stop()
|
||||
self._session = _BashSession()
|
||||
await self._session.start()
|
||||
|
||||
return ToolResult(system="tool has been restarted.")
|
||||
|
||||
if self._session is None:
|
||||
self._session = _BashSession()
|
||||
await self._session.start()
|
||||
|
||||
if command is not None:
|
||||
return await self._session.run(command)
|
||||
|
||||
raise ToolError("no command provided.")
|
||||
|
||||
def to_params(self) -> BetaToolBash20241022Param:
|
||||
return {
|
||||
"type": self.api_type,
|
||||
"name": self.name,
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
"""
|
||||
Define some colorful stuffs for better visualization in the chat.
|
||||
"""
|
||||
|
||||
# Define the RGB colors for each letter
|
||||
colors = {
|
||||
'S': 'rgb(106, 158, 210)',
|
||||
'h': 'rgb(111, 163, 82)',
|
||||
'o': 'rgb(209, 100, 94)',
|
||||
'w': 'rgb(238, 171, 106)',
|
||||
'U': 'rgb(0, 0, 0)',
|
||||
'I': 'rgb(0, 0, 0)',
|
||||
}
|
||||
|
||||
# Construct the colorful "ShowUI" word
|
||||
colorful_text_showui = "**"+''.join(
|
||||
f'<span style="color:{colors.get(letter, "black")}">{letter}</span>'
|
||||
for letter in "ShowUI"
|
||||
)+"**"
|
||||
|
||||
|
||||
colorful_text_vlm = "**OmniParser Agent**"
|
||||
|
||||
colorful_text_user = "**User**"
|
||||
|
||||
# print(f"colorful_text_showui: {colorful_text_showui}")
|
||||
# **<span style="color:rgb(106, 158, 210)">S</span><span style="color:rgb(111, 163, 82)">h</span><span style="color:rgb(209, 100, 94)">o</span><span style="color:rgb(238, 171, 106)">w</span><span style="color:rgb(0, 0, 0)">U</span><span style="color:rgb(0, 0, 0)">I</span>**
|
||||
@@ -1,519 +0,0 @@
|
||||
import subprocess
|
||||
import platform
|
||||
import pyautogui
|
||||
import asyncio
|
||||
import base64
|
||||
import os
|
||||
import time
|
||||
if platform.system() == "Darwin":
|
||||
import Quartz # uncomment this line if you are on macOS
|
||||
from enum import StrEnum
|
||||
from pathlib import Path
|
||||
from typing import Literal, TypedDict
|
||||
from uuid import uuid4
|
||||
from screeninfo import get_monitors
|
||||
|
||||
from PIL import ImageGrab, Image
|
||||
from functools import partial
|
||||
|
||||
from anthropic.types.beta import BetaToolComputerUse20241022Param
|
||||
|
||||
from .base import BaseAnthropicTool, ToolError, ToolResult
|
||||
from .run import run
|
||||
|
||||
OUTPUT_DIR = "./tmp/outputs"
|
||||
|
||||
TYPING_DELAY_MS = 12
|
||||
TYPING_GROUP_SIZE = 50
|
||||
|
||||
Action = Literal[
|
||||
"key",
|
||||
"type",
|
||||
"mouse_move",
|
||||
"left_click",
|
||||
"left_click_drag",
|
||||
"right_click",
|
||||
"middle_click",
|
||||
"double_click",
|
||||
"screenshot",
|
||||
"cursor_position",
|
||||
]
|
||||
|
||||
|
||||
class Resolution(TypedDict):
|
||||
width: int
|
||||
height: int
|
||||
|
||||
|
||||
MAX_SCALING_TARGETS: dict[str, Resolution] = {
|
||||
"XGA": Resolution(width=1024, height=768), # 4:3
|
||||
"WXGA": Resolution(width=1280, height=800), # 16:10
|
||||
"FWXGA": Resolution(width=1366, height=768), # ~16:9
|
||||
}
|
||||
|
||||
|
||||
class ScalingSource(StrEnum):
|
||||
COMPUTER = "computer"
|
||||
API = "api"
|
||||
|
||||
|
||||
class ComputerToolOptions(TypedDict):
|
||||
display_height_px: int
|
||||
display_width_px: int
|
||||
display_number: int | None
|
||||
|
||||
|
||||
def chunks(s: str, chunk_size: int) -> list[str]:
|
||||
return [s[i : i + chunk_size] for i in range(0, len(s), chunk_size)]
|
||||
|
||||
|
||||
def get_screen_details():
|
||||
screens = get_monitors()
|
||||
screen_details = []
|
||||
|
||||
# Sort screens by x position to arrange from left to right
|
||||
sorted_screens = sorted(screens, key=lambda s: s.x)
|
||||
|
||||
# Loop through sorted screens and assign positions
|
||||
primary_index = 0
|
||||
for i, screen in enumerate(sorted_screens):
|
||||
if i == 0:
|
||||
layout = "Left"
|
||||
elif i == len(sorted_screens) - 1:
|
||||
layout = "Right"
|
||||
else:
|
||||
layout = "Center"
|
||||
|
||||
if screen.is_primary:
|
||||
position = "Primary"
|
||||
primary_index = i
|
||||
else:
|
||||
position = "Secondary"
|
||||
screen_info = f"Screen {i + 1}: {screen.width}x{screen.height}, {layout}, {position}"
|
||||
screen_details.append(screen_info)
|
||||
|
||||
return screen_details, primary_index
|
||||
|
||||
|
||||
class ComputerTool(BaseAnthropicTool):
|
||||
"""
|
||||
A tool that allows the agent to interact with the screen, keyboard, and mouse of the current computer.
|
||||
Adapted for Windows using 'pyautogui'.
|
||||
"""
|
||||
|
||||
name: Literal["computer"] = "computer"
|
||||
api_type: Literal["computer_20241022"] = "computer_20241022"
|
||||
width: int
|
||||
height: int
|
||||
display_num: int | None
|
||||
|
||||
_screenshot_delay = 2.0
|
||||
_scaling_enabled = True
|
||||
|
||||
@property
|
||||
def options(self) -> ComputerToolOptions:
|
||||
width, height = self.scale_coordinates(
|
||||
ScalingSource.COMPUTER, self.width, self.height
|
||||
)
|
||||
return {
|
||||
"display_width_px": width,
|
||||
"display_height_px": height,
|
||||
"display_number": self.display_num,
|
||||
}
|
||||
|
||||
def to_params(self) -> BetaToolComputerUse20241022Param:
|
||||
return {"name": self.name, "type": self.api_type, **self.options}
|
||||
|
||||
def __init__(self, selected_screen: int = 0, is_scaling: bool = False):
|
||||
super().__init__()
|
||||
|
||||
# Get screen width and height using Windows command
|
||||
self.display_num = None
|
||||
self.offset_x = 0
|
||||
self.offset_y = 0
|
||||
self.selected_screen = selected_screen
|
||||
self.is_scaling = is_scaling
|
||||
self.width, self.height = self.get_screen_size()
|
||||
|
||||
# Path to cliclick
|
||||
self.cliclick = "cliclick"
|
||||
self.key_conversion = {"Page_Down": "pagedown",
|
||||
"Page_Up": "pageup",
|
||||
"Super_L": "win",
|
||||
"Escape": "esc"}
|
||||
|
||||
system = platform.system() # Detect platform
|
||||
if system == "Windows":
|
||||
screens = get_monitors()
|
||||
sorted_screens = sorted(screens, key=lambda s: s.x)
|
||||
if self.selected_screen < 0 or self.selected_screen >= len(screens):
|
||||
raise IndexError("Invalid screen index.")
|
||||
screen = sorted_screens[self.selected_screen]
|
||||
bbox = (screen.x, screen.y, screen.x + screen.width, screen.y + screen.height)
|
||||
|
||||
elif system == "Darwin": # macOS
|
||||
max_displays = 32 # Maximum number of displays to handle
|
||||
active_displays = Quartz.CGGetActiveDisplayList(max_displays, None, None)[1]
|
||||
screens = []
|
||||
for display_id in active_displays:
|
||||
bounds = Quartz.CGDisplayBounds(display_id)
|
||||
screens.append({
|
||||
'id': display_id, 'x': int(bounds.origin.x), 'y': int(bounds.origin.y),
|
||||
'width': int(bounds.size.width), 'height': int(bounds.size.height),
|
||||
'is_primary': Quartz.CGDisplayIsMain(display_id) # Check if this is the primary display
|
||||
})
|
||||
sorted_screens = sorted(screens, key=lambda s: s['x'])
|
||||
if self.selected_screen < 0 or self.selected_screen >= len(screens):
|
||||
raise IndexError("Invalid screen index.")
|
||||
screen = sorted_screens[self.selected_screen]
|
||||
bbox = (screen['x'], screen['y'], screen['x'] + screen['width'], screen['y'] + screen['height'])
|
||||
else: # Linux or other OS
|
||||
cmd = "xrandr | grep ' primary' | awk '{print $4}'"
|
||||
try:
|
||||
# output = subprocess.check_output(cmd, shell=True).decode()
|
||||
# resolution = output.strip().split()[0]
|
||||
# width, height = map(int, resolution.split('x'))
|
||||
# bbox = (0, 0, width, height) # Assuming single primary screen for simplicity
|
||||
screen = get_monitors()[0]
|
||||
bbox = (screen.x, screen.y, screen.x + screen.width, screen.y + screen.height)
|
||||
except subprocess.CalledProcessError:
|
||||
raise RuntimeError("Failed to get screen resolution on Linux.")
|
||||
|
||||
self.offset_x = screen['x'] if system == "Darwin" else screen.x
|
||||
self.offset_y = screen['y'] if system == "Darwin" else screen.y
|
||||
self.bbox = bbox
|
||||
|
||||
|
||||
async def __call__(
|
||||
self,
|
||||
*,
|
||||
action: Action,
|
||||
text: str | None = None,
|
||||
coordinate: tuple[int, int] | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
print(f"action: {action}, text: {text}, coordinate: {coordinate}, is_scaling: {self.is_scaling}")
|
||||
if action in ("mouse_move", "left_click_drag"):
|
||||
if coordinate is None:
|
||||
raise ToolError(f"coordinate is required for {action}")
|
||||
if text is not None:
|
||||
raise ToolError(f"text is not accepted for {action}")
|
||||
if not isinstance(coordinate, (list, tuple)) or len(coordinate) != 2:
|
||||
raise ToolError(f"{coordinate} must be a tuple of length 2")
|
||||
# if not all(isinstance(i, int) and i >= 0 for i in coordinate):
|
||||
if not all(isinstance(i, int) for i in coordinate):
|
||||
raise ToolError(f"{coordinate} must be a tuple of non-negative ints")
|
||||
|
||||
if self.is_scaling:
|
||||
x, y = self.scale_coordinates(
|
||||
ScalingSource.API, coordinate[0], coordinate[1]
|
||||
)
|
||||
else:
|
||||
x, y = coordinate
|
||||
|
||||
# print(f"scaled_coordinates: {x}, {y}")
|
||||
# print(f"offset: {self.offset_x}, {self.offset_y}")
|
||||
|
||||
# x += self.offset_x # TODO - check if this is needed
|
||||
# y += self.offset_y
|
||||
|
||||
print(f"mouse move to {x}, {y}")
|
||||
|
||||
if action == "mouse_move":
|
||||
pyautogui.moveTo(x, y)
|
||||
return ToolResult(output=f"Moved mouse to ({x}, {y})")
|
||||
elif action == "left_click_drag":
|
||||
current_x, current_y = pyautogui.position()
|
||||
pyautogui.dragTo(x, y, duration=0.5) # Adjust duration as needed
|
||||
return ToolResult(output=f"Dragged mouse from ({current_x}, {current_y}) to ({x}, {y})")
|
||||
|
||||
if action in ("key", "type"):
|
||||
if text is None:
|
||||
raise ToolError(f"text is required for {action}")
|
||||
if coordinate is not None:
|
||||
raise ToolError(f"coordinate is not accepted for {action}")
|
||||
if not isinstance(text, str):
|
||||
raise ToolError(output=f"{text} must be a string")
|
||||
|
||||
if action == "key":
|
||||
# Handle key combinations
|
||||
keys = text.split('+')
|
||||
for key in keys:
|
||||
key = self.key_conversion.get(key.strip(), key.strip())
|
||||
key = key.lower()
|
||||
pyautogui.keyDown(key) # Press down each key
|
||||
for key in reversed(keys):
|
||||
key = self.key_conversion.get(key.strip(), key.strip())
|
||||
key = key.lower()
|
||||
pyautogui.keyUp(key) # Release each key in reverse order
|
||||
return ToolResult(output=f"Pressed keys: {text}")
|
||||
|
||||
elif action == "type":
|
||||
pyautogui.typewrite(text, interval=TYPING_DELAY_MS / 1000) # Convert ms to seconds
|
||||
pyautogui.press('enter')
|
||||
screenshot_base64 = (await self.screenshot()).base64_image
|
||||
return ToolResult(output=text, base64_image=screenshot_base64)
|
||||
|
||||
if action in (
|
||||
"left_click",
|
||||
"right_click",
|
||||
"double_click",
|
||||
"middle_click",
|
||||
"screenshot",
|
||||
"cursor_position",
|
||||
"left_press",
|
||||
):
|
||||
if text is not None:
|
||||
raise ToolError(f"text is not accepted for {action}")
|
||||
if coordinate is not None:
|
||||
raise ToolError(f"coordinate is not accepted for {action}")
|
||||
|
||||
if action == "screenshot":
|
||||
return await self.screenshot()
|
||||
elif action == "cursor_position":
|
||||
x, y = pyautogui.position()
|
||||
x, y = self.scale_coordinates(ScalingSource.COMPUTER, x, y)
|
||||
return ToolResult(output=f"X={x},Y={y}")
|
||||
else:
|
||||
if action == "left_click":
|
||||
pyautogui.click()
|
||||
elif action == "right_click":
|
||||
pyautogui.rightClick()
|
||||
elif action == "middle_click":
|
||||
pyautogui.middleClick()
|
||||
elif action == "double_click":
|
||||
pyautogui.doubleClick()
|
||||
elif action == "left_press":
|
||||
pyautogui.mouseDown()
|
||||
time.sleep(1)
|
||||
pyautogui.mouseUp()
|
||||
return ToolResult(output=f"Performed {action}")
|
||||
|
||||
raise ToolError(f"Invalid action: {action}")
|
||||
|
||||
async def screenshot(self):
|
||||
|
||||
import time
|
||||
time.sleep(1)
|
||||
|
||||
"""Take a screenshot of the current screen and return a ToolResult with the base64 encoded image."""
|
||||
output_dir = Path(OUTPUT_DIR)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
path = output_dir / f"screenshot_{uuid4().hex}.png"
|
||||
|
||||
ImageGrab.grab = partial(ImageGrab.grab, all_screens=True)
|
||||
|
||||
# Detect platform
|
||||
system = platform.system()
|
||||
|
||||
if system == "Windows":
|
||||
# Windows: Use screeninfo to get monitor details
|
||||
screens = get_monitors()
|
||||
|
||||
# Sort screens by x position to arrange from left to right
|
||||
sorted_screens = sorted(screens, key=lambda s: s.x)
|
||||
|
||||
if self.selected_screen < 0 or self.selected_screen >= len(screens):
|
||||
raise IndexError("Invalid screen index.")
|
||||
|
||||
screen = sorted_screens[self.selected_screen]
|
||||
bbox = (screen.x, screen.y, screen.x + screen.width, screen.y + screen.height)
|
||||
|
||||
elif system == "Darwin": # macOS
|
||||
# macOS: Use Quartz to get monitor details
|
||||
max_displays = 32 # Maximum number of displays to handle
|
||||
active_displays = Quartz.CGGetActiveDisplayList(max_displays, None, None)[1]
|
||||
|
||||
# Get the display bounds (resolution) for each active display
|
||||
screens = []
|
||||
for display_id in active_displays:
|
||||
bounds = Quartz.CGDisplayBounds(display_id)
|
||||
screens.append({
|
||||
'id': display_id,
|
||||
'x': int(bounds.origin.x),
|
||||
'y': int(bounds.origin.y),
|
||||
'width': int(bounds.size.width),
|
||||
'height': int(bounds.size.height),
|
||||
'is_primary': Quartz.CGDisplayIsMain(display_id) # Check if this is the primary display
|
||||
})
|
||||
|
||||
# Sort screens by x position to arrange from left to right
|
||||
sorted_screens = sorted(screens, key=lambda s: s['x'])
|
||||
|
||||
if self.selected_screen < 0 or self.selected_screen >= len(screens):
|
||||
raise IndexError("Invalid screen index.")
|
||||
|
||||
screen = sorted_screens[self.selected_screen]
|
||||
bbox = (screen['x'], screen['y'], screen['x'] + screen['width'], screen['y'] + screen['height'])
|
||||
|
||||
else: # Linux or other OS
|
||||
cmd = "xrandr | grep ' primary' | awk '{print $4}'"
|
||||
try:
|
||||
# output = subprocess.check_output(cmd, shell=True).decode()
|
||||
# resolution = output.strip().split()[0]
|
||||
# width, height = map(int, resolution.split('x'))
|
||||
# bbox = (0, 0, width, height) # Assuming single primary screen for simplicity
|
||||
screen = get_monitors()[0]
|
||||
bbox = (screen.x, screen.y, screen.x + screen.width, screen.y + screen.height)
|
||||
except subprocess.CalledProcessError:
|
||||
raise RuntimeError("Failed to get screen resolution on Linux.")
|
||||
|
||||
# Take screenshot using the bounding box
|
||||
screenshot = ImageGrab.grab(bbox=bbox)
|
||||
|
||||
# Set offsets (for potential future use)
|
||||
self.offset_x = screen['x'] if system == "Darwin" else screen.x
|
||||
self.offset_y = screen['y'] if system == "Darwin" else screen.y
|
||||
|
||||
print(f"target_dimension {self.target_dimension}")
|
||||
|
||||
if not hasattr(self, 'target_dimension'):
|
||||
screenshot = self.padding_image(screenshot)
|
||||
self.target_dimension = MAX_SCALING_TARGETS["WXGA"]
|
||||
|
||||
# Resize if target_dimensions are specified
|
||||
print(f"offset is {self.offset_x}, {self.offset_y}")
|
||||
print(f"target_dimension is {self.target_dimension}")
|
||||
screenshot = screenshot.resize((self.target_dimension["width"], self.target_dimension["height"]))
|
||||
|
||||
# Save the screenshot
|
||||
screenshot.save(str(path))
|
||||
|
||||
if path.exists():
|
||||
# Return a ToolResult instance instead of a dictionary
|
||||
return ToolResult(base64_image=base64.b64encode(path.read_bytes()).decode())
|
||||
|
||||
raise ToolError(f"Failed to take screenshot: {path} does not exist.")
|
||||
|
||||
def padding_image(self, screenshot):
|
||||
"""Pad the screenshot to 16:10 aspect ratio, when the aspect ratio is not 16:10."""
|
||||
_, height = screenshot.size
|
||||
new_width = height * 16 // 10
|
||||
|
||||
padding_image = Image.new("RGB", (new_width, height), (255, 255, 255))
|
||||
# padding to top left
|
||||
padding_image.paste(screenshot, (0, 0))
|
||||
return padding_image
|
||||
|
||||
async def shell(self, command: str, take_screenshot=True) -> ToolResult:
|
||||
"""Run a shell command and return the output, error, and optionally a screenshot."""
|
||||
_, stdout, stderr = await run(command)
|
||||
base64_image = None
|
||||
|
||||
if take_screenshot:
|
||||
# delay to let things settle before taking a screenshot
|
||||
await asyncio.sleep(self._screenshot_delay)
|
||||
base64_image = (await self.screenshot()).base64_image
|
||||
|
||||
return ToolResult(output=stdout, error=stderr, base64_image=base64_image)
|
||||
|
||||
def scale_coordinates(self, source: ScalingSource, x: int, y: int):
|
||||
"""Scale coordinates to a target maximum resolution."""
|
||||
if not self._scaling_enabled:
|
||||
return x, y
|
||||
ratio = self.width / self.height
|
||||
target_dimension = None
|
||||
|
||||
for target_name, dimension in MAX_SCALING_TARGETS.items():
|
||||
# allow some error in the aspect ratio - not ratios are exactly 16:9
|
||||
if abs(dimension["width"] / dimension["height"] - ratio) < 0.02:
|
||||
if dimension["width"] < self.width:
|
||||
target_dimension = dimension
|
||||
self.target_dimension = target_dimension
|
||||
# print(f"target_dimension: {target_dimension}")
|
||||
break
|
||||
|
||||
if target_dimension is None:
|
||||
# TODO: currently we force the target to be WXGA (16:10), when it cannot find a match
|
||||
target_dimension = MAX_SCALING_TARGETS["WXGA"]
|
||||
self.target_dimension = MAX_SCALING_TARGETS["WXGA"]
|
||||
|
||||
# should be less than 1
|
||||
x_scaling_factor = target_dimension["width"] / self.width
|
||||
y_scaling_factor = target_dimension["height"] / self.height
|
||||
if source == ScalingSource.API:
|
||||
if x > self.width or y > self.height:
|
||||
raise ToolError(f"Coordinates {x}, {y} are out of bounds")
|
||||
# scale up
|
||||
return round(x / x_scaling_factor), round(y / y_scaling_factor)
|
||||
# scale down
|
||||
return round(x * x_scaling_factor), round(y * y_scaling_factor)
|
||||
|
||||
def get_screen_size(self):
|
||||
if platform.system() == "Windows":
|
||||
# Use screeninfo to get primary monitor on Windows
|
||||
screens = get_monitors()
|
||||
|
||||
# Sort screens by x position to arrange from left to right
|
||||
sorted_screens = sorted(screens, key=lambda s: s.x)
|
||||
|
||||
if self.selected_screen is None:
|
||||
primary_monitor = next((m for m in get_monitors() if m.is_primary), None)
|
||||
return primary_monitor.width, primary_monitor.height
|
||||
elif self.selected_screen < 0 or self.selected_screen >= len(screens):
|
||||
raise IndexError("Invalid screen index.")
|
||||
else:
|
||||
screen = sorted_screens[self.selected_screen]
|
||||
return screen.width, screen.height
|
||||
|
||||
elif platform.system() == "Darwin":
|
||||
# macOS part using Quartz to get screen information
|
||||
max_displays = 32 # Maximum number of displays to handle
|
||||
active_displays = Quartz.CGGetActiveDisplayList(max_displays, None, None)[1]
|
||||
|
||||
# Get the display bounds (resolution) for each active display
|
||||
screens = []
|
||||
for display_id in active_displays:
|
||||
bounds = Quartz.CGDisplayBounds(display_id)
|
||||
screens.append({
|
||||
'id': display_id,
|
||||
'x': int(bounds.origin.x),
|
||||
'y': int(bounds.origin.y),
|
||||
'width': int(bounds.size.width),
|
||||
'height': int(bounds.size.height),
|
||||
'is_primary': Quartz.CGDisplayIsMain(display_id) # Check if this is the primary display
|
||||
})
|
||||
|
||||
# Sort screens by x position to arrange from left to right
|
||||
sorted_screens = sorted(screens, key=lambda s: s['x'])
|
||||
|
||||
if self.selected_screen is None:
|
||||
# Find the primary monitor
|
||||
primary_monitor = next((screen for screen in screens if screen['is_primary']), None)
|
||||
if primary_monitor:
|
||||
return primary_monitor['width'], primary_monitor['height']
|
||||
else:
|
||||
raise RuntimeError("No primary monitor found.")
|
||||
elif self.selected_screen < 0 or self.selected_screen >= len(screens):
|
||||
raise IndexError("Invalid screen index.")
|
||||
else:
|
||||
# Return the resolution of the selected screen
|
||||
screen = sorted_screens[self.selected_screen]
|
||||
return screen['width'], screen['height']
|
||||
|
||||
else: # Linux or other OS
|
||||
cmd = "xrandr | grep ' primary' | awk '{print $4}'"
|
||||
try:
|
||||
# output = subprocess.check_output(cmd, shell=True).decode()
|
||||
# resolution = output.strip().split()[0]
|
||||
# width, height = map(int, resolution.split('x'))
|
||||
# return width, height
|
||||
screen = get_monitors()[0]
|
||||
return screen.width, screen.height
|
||||
except subprocess.CalledProcessError:
|
||||
raise RuntimeError("Failed to get screen resolution on Linux.")
|
||||
|
||||
def get_mouse_position(self):
|
||||
# TODO: enhance this func
|
||||
from AppKit import NSEvent
|
||||
from Quartz import CGEventSourceCreate, kCGEventSourceStateCombinedSessionState
|
||||
|
||||
loc = NSEvent.mouseLocation()
|
||||
# Adjust for different coordinate system
|
||||
return int(loc.x), int(self.height - loc.y)
|
||||
|
||||
def map_keys(self, text: str):
|
||||
"""Map text to cliclick key codes if necessary."""
|
||||
# For simplicity, return text as is
|
||||
# Implement mapping if special keys are needed
|
||||
return text
|
||||
@@ -1,290 +0,0 @@
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
from typing import Literal, get_args
|
||||
|
||||
from anthropic.types.beta import BetaToolTextEditor20241022Param
|
||||
|
||||
from .base import BaseAnthropicTool, CLIResult, ToolError, ToolResult
|
||||
from .run import maybe_truncate, run
|
||||
|
||||
Command = Literal[
|
||||
"view",
|
||||
"create",
|
||||
"str_replace",
|
||||
"insert",
|
||||
"undo_edit",
|
||||
]
|
||||
SNIPPET_LINES: int = 4
|
||||
|
||||
|
||||
class EditTool(BaseAnthropicTool):
|
||||
"""
|
||||
An filesystem editor tool that allows the agent to view, create, and edit files.
|
||||
The tool parameters are defined by Anthropic and are not editable.
|
||||
"""
|
||||
|
||||
api_type: Literal["text_editor_20241022"] = "text_editor_20241022"
|
||||
name: Literal["str_replace_editor"] = "str_replace_editor"
|
||||
|
||||
_file_history: dict[Path, list[str]]
|
||||
|
||||
def __init__(self):
|
||||
self._file_history = defaultdict(list)
|
||||
super().__init__()
|
||||
|
||||
def to_params(self) -> BetaToolTextEditor20241022Param:
|
||||
return {
|
||||
"name": self.name,
|
||||
"type": self.api_type,
|
||||
}
|
||||
|
||||
async def __call__(
|
||||
self,
|
||||
*,
|
||||
command: Command,
|
||||
path: str,
|
||||
file_text: str | None = None,
|
||||
view_range: list[int] | None = None,
|
||||
old_str: str | None = None,
|
||||
new_str: str | None = None,
|
||||
insert_line: int | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
_path = Path(path)
|
||||
self.validate_path(command, _path)
|
||||
if command == "view":
|
||||
return await self.view(_path, view_range)
|
||||
elif command == "create":
|
||||
if not file_text:
|
||||
raise ToolError("Parameter `file_text` is required for command: create")
|
||||
self.write_file(_path, file_text)
|
||||
self._file_history[_path].append(file_text)
|
||||
return ToolResult(output=f"File created successfully at: {_path}")
|
||||
elif command == "str_replace":
|
||||
if not old_str:
|
||||
raise ToolError(
|
||||
"Parameter `old_str` is required for command: str_replace"
|
||||
)
|
||||
return self.str_replace(_path, old_str, new_str)
|
||||
elif command == "insert":
|
||||
if insert_line is None:
|
||||
raise ToolError(
|
||||
"Parameter `insert_line` is required for command: insert"
|
||||
)
|
||||
if not new_str:
|
||||
raise ToolError("Parameter `new_str` is required for command: insert")
|
||||
return self.insert(_path, insert_line, new_str)
|
||||
elif command == "undo_edit":
|
||||
return self.undo_edit(_path)
|
||||
raise ToolError(
|
||||
f'Unrecognized command {command}. The allowed commands for the {self.name} tool are: {", ".join(get_args(Command))}'
|
||||
)
|
||||
|
||||
def validate_path(self, command: str, path: Path):
|
||||
"""
|
||||
Check that the path/command combination is valid.
|
||||
"""
|
||||
# Check if its an absolute path
|
||||
if not path.is_absolute():
|
||||
suggested_path = Path("") / path
|
||||
raise ToolError(
|
||||
f"The path {path} is not an absolute path, it should start with `/`. Maybe you meant {suggested_path}?"
|
||||
)
|
||||
# Check if path exists
|
||||
if not path.exists() and command != "create":
|
||||
raise ToolError(
|
||||
f"The path {path} does not exist. Please provide a valid path."
|
||||
)
|
||||
if path.exists() and command == "create":
|
||||
raise ToolError(
|
||||
f"File already exists at: {path}. Cannot overwrite files using command `create`."
|
||||
)
|
||||
# Check if the path points to a directory
|
||||
if path.is_dir():
|
||||
if command != "view":
|
||||
raise ToolError(
|
||||
f"The path {path} is a directory and only the `view` command can be used on directories"
|
||||
)
|
||||
|
||||
async def view(self, path: Path, view_range: list[int] | None = None):
|
||||
"""Implement the view command"""
|
||||
if path.is_dir():
|
||||
if view_range:
|
||||
raise ToolError(
|
||||
"The `view_range` parameter is not allowed when `path` points to a directory."
|
||||
)
|
||||
|
||||
_, stdout, stderr = await run(
|
||||
rf"find {path} -maxdepth 2 -not -path '*/\.*'"
|
||||
)
|
||||
if not stderr:
|
||||
stdout = f"Here's the files and directories up to 2 levels deep in {path}, excluding hidden items:\n{stdout}\n"
|
||||
return CLIResult(output=stdout, error=stderr)
|
||||
|
||||
file_content = self.read_file(path)
|
||||
init_line = 1
|
||||
if view_range:
|
||||
if len(view_range) != 2 or not all(isinstance(i, int) for i in view_range):
|
||||
raise ToolError(
|
||||
"Invalid `view_range`. It should be a list of two integers."
|
||||
)
|
||||
file_lines = file_content.split("\n")
|
||||
n_lines_file = len(file_lines)
|
||||
init_line, final_line = view_range
|
||||
if init_line < 1 or init_line > n_lines_file:
|
||||
raise ToolError(
|
||||
f"Invalid `view_range`: {view_range}. It's first element `{init_line}` should be within the range of lines of the file: {[1, n_lines_file]}"
|
||||
)
|
||||
if final_line > n_lines_file:
|
||||
raise ToolError(
|
||||
f"Invalid `view_range`: {view_range}. It's second element `{final_line}` should be smaller than the number of lines in the file: `{n_lines_file}`"
|
||||
)
|
||||
if final_line != -1 and final_line < init_line:
|
||||
raise ToolError(
|
||||
f"Invalid `view_range`: {view_range}. It's second element `{final_line}` should be larger or equal than its first `{init_line}`"
|
||||
)
|
||||
|
||||
if final_line == -1:
|
||||
file_content = "\n".join(file_lines[init_line - 1 :])
|
||||
else:
|
||||
file_content = "\n".join(file_lines[init_line - 1 : final_line])
|
||||
|
||||
return CLIResult(
|
||||
output=self._make_output(file_content, str(path), init_line=init_line)
|
||||
)
|
||||
|
||||
def str_replace(self, path: Path, old_str: str, new_str: str | None):
|
||||
"""Implement the str_replace command, which replaces old_str with new_str in the file content"""
|
||||
# Read the file content
|
||||
file_content = self.read_file(path).expandtabs()
|
||||
old_str = old_str.expandtabs()
|
||||
new_str = new_str.expandtabs() if new_str is not None else ""
|
||||
|
||||
# Check if old_str is unique in the file
|
||||
occurrences = file_content.count(old_str)
|
||||
if occurrences == 0:
|
||||
raise ToolError(
|
||||
f"No replacement was performed, old_str `{old_str}` did not appear verbatim in {path}."
|
||||
)
|
||||
elif occurrences > 1:
|
||||
file_content_lines = file_content.split("\n")
|
||||
lines = [
|
||||
idx + 1
|
||||
for idx, line in enumerate(file_content_lines)
|
||||
if old_str in line
|
||||
]
|
||||
raise ToolError(
|
||||
f"No replacement was performed. Multiple occurrences of old_str `{old_str}` in lines {lines}. Please ensure it is unique"
|
||||
)
|
||||
|
||||
# Replace old_str with new_str
|
||||
new_file_content = file_content.replace(old_str, new_str)
|
||||
|
||||
# Write the new content to the file
|
||||
self.write_file(path, new_file_content)
|
||||
|
||||
# Save the content to history
|
||||
self._file_history[path].append(file_content)
|
||||
|
||||
# Create a snippet of the edited section
|
||||
replacement_line = file_content.split(old_str)[0].count("\n")
|
||||
start_line = max(0, replacement_line - SNIPPET_LINES)
|
||||
end_line = replacement_line + SNIPPET_LINES + new_str.count("\n")
|
||||
snippet = "\n".join(new_file_content.split("\n")[start_line : end_line + 1])
|
||||
|
||||
# Prepare the success message
|
||||
success_msg = f"The file {path} has been edited. "
|
||||
success_msg += self._make_output(
|
||||
snippet, f"a snippet of {path}", start_line + 1
|
||||
)
|
||||
success_msg += "Review the changes and make sure they are as expected. Edit the file again if necessary."
|
||||
|
||||
return CLIResult(output=success_msg)
|
||||
|
||||
def insert(self, path: Path, insert_line: int, new_str: str):
|
||||
"""Implement the insert command, which inserts new_str at the specified line in the file content."""
|
||||
file_text = self.read_file(path).expandtabs()
|
||||
new_str = new_str.expandtabs()
|
||||
file_text_lines = file_text.split("\n")
|
||||
n_lines_file = len(file_text_lines)
|
||||
|
||||
if insert_line < 0 or insert_line > n_lines_file:
|
||||
raise ToolError(
|
||||
f"Invalid `insert_line` parameter: {insert_line}. It should be within the range of lines of the file: {[0, n_lines_file]}"
|
||||
)
|
||||
|
||||
new_str_lines = new_str.split("\n")
|
||||
new_file_text_lines = (
|
||||
file_text_lines[:insert_line]
|
||||
+ new_str_lines
|
||||
+ file_text_lines[insert_line:]
|
||||
)
|
||||
snippet_lines = (
|
||||
file_text_lines[max(0, insert_line - SNIPPET_LINES) : insert_line]
|
||||
+ new_str_lines
|
||||
+ file_text_lines[insert_line : insert_line + SNIPPET_LINES]
|
||||
)
|
||||
|
||||
new_file_text = "\n".join(new_file_text_lines)
|
||||
snippet = "\n".join(snippet_lines)
|
||||
|
||||
self.write_file(path, new_file_text)
|
||||
self._file_history[path].append(file_text)
|
||||
|
||||
success_msg = f"The file {path} has been edited. "
|
||||
success_msg += self._make_output(
|
||||
snippet,
|
||||
"a snippet of the edited file",
|
||||
max(1, insert_line - SNIPPET_LINES + 1),
|
||||
)
|
||||
success_msg += "Review the changes and make sure they are as expected (correct indentation, no duplicate lines, etc). Edit the file again if necessary."
|
||||
return CLIResult(output=success_msg)
|
||||
|
||||
def undo_edit(self, path: Path):
|
||||
"""Implement the undo_edit command."""
|
||||
if not self._file_history[path]:
|
||||
raise ToolError(f"No edit history found for {path}.")
|
||||
|
||||
old_text = self._file_history[path].pop()
|
||||
self.write_file(path, old_text)
|
||||
|
||||
return CLIResult(
|
||||
output=f"Last edit to {path} undone successfully. {self._make_output(old_text, str(path))}"
|
||||
)
|
||||
|
||||
def read_file(self, path: Path):
|
||||
"""Read the content of a file from a given path; raise a ToolError if an error occurs."""
|
||||
try:
|
||||
return path.read_text()
|
||||
except Exception as e:
|
||||
raise ToolError(f"Ran into {e} while trying to read {path}") from None
|
||||
|
||||
def write_file(self, path: Path, file: str):
|
||||
"""Write the content of a file to a given path; raise a ToolError if an error occurs."""
|
||||
try:
|
||||
path.write_text(file)
|
||||
except Exception as e:
|
||||
raise ToolError(f"Ran into {e} while trying to write to {path}") from None
|
||||
|
||||
def _make_output(
|
||||
self,
|
||||
file_content: str,
|
||||
file_descriptor: str,
|
||||
init_line: int = 1,
|
||||
expand_tabs: bool = True,
|
||||
):
|
||||
"""Generate output for the CLI based on the content of a file."""
|
||||
file_content = maybe_truncate(file_content)
|
||||
if expand_tabs:
|
||||
file_content = file_content.expandtabs()
|
||||
file_content = "\n".join(
|
||||
[
|
||||
f"{i + init_line:6}\t{line}"
|
||||
for i, line in enumerate(file_content.split("\n"))
|
||||
]
|
||||
)
|
||||
return (
|
||||
f"Here's the result of running `cat -n` on {file_descriptor}:\n"
|
||||
+ file_content
|
||||
+ "\n"
|
||||
)
|
||||
@@ -1,42 +0,0 @@
|
||||
"""Utility to run shell commands asynchronously with a timeout."""
|
||||
|
||||
import asyncio
|
||||
|
||||
TRUNCATED_MESSAGE: str = "<response clipped><NOTE>To save on context only part of this file has been shown to you. You should retry this tool after you have searched inside the file with `grep -n` in order to find the line numbers of what you are looking for.</NOTE>"
|
||||
MAX_RESPONSE_LEN: int = 16000
|
||||
|
||||
|
||||
def maybe_truncate(content: str, truncate_after: int | None = MAX_RESPONSE_LEN):
|
||||
"""Truncate content and append a notice if content exceeds the specified length."""
|
||||
return (
|
||||
content
|
||||
if not truncate_after or len(content) <= truncate_after
|
||||
else content[:truncate_after] + TRUNCATED_MESSAGE
|
||||
)
|
||||
|
||||
|
||||
async def run(
|
||||
cmd: str,
|
||||
timeout: float | None = 120.0, # seconds
|
||||
truncate_after: int | None = MAX_RESPONSE_LEN,
|
||||
):
|
||||
"""Run a shell command asynchronously with a timeout."""
|
||||
process = await asyncio.create_subprocess_shell(
|
||||
cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
|
||||
)
|
||||
|
||||
try:
|
||||
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
|
||||
return (
|
||||
process.returncode or 0,
|
||||
maybe_truncate(stdout.decode(), truncate_after=truncate_after),
|
||||
maybe_truncate(stderr.decode(), truncate_after=truncate_after),
|
||||
)
|
||||
except asyncio.TimeoutError as exc:
|
||||
try:
|
||||
process.kill()
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
raise TimeoutError(
|
||||
f"Command '{cmd}' timed out after {timeout} seconds"
|
||||
) from exc
|
||||
@@ -1,185 +0,0 @@
|
||||
import subprocess
|
||||
import base64
|
||||
from pathlib import Path
|
||||
from PIL import ImageGrab
|
||||
from uuid import uuid4
|
||||
from screeninfo import get_monitors
|
||||
import platform
|
||||
if platform.system() == "Darwin":
|
||||
import Quartz # uncomment this line if you are on macOS
|
||||
|
||||
from PIL import ImageGrab
|
||||
from functools import partial
|
||||
from .base import BaseAnthropicTool, ToolError, ToolResult
|
||||
|
||||
|
||||
OUTPUT_DIR = "./tmp/outputs"
|
||||
|
||||
def get_screenshot(selected_screen: int = 0, resize: bool = True, target_width: int = 1920, target_height: int = 1080):
|
||||
# print(f"get_screenshot selected_screen: {selected_screen}")
|
||||
|
||||
# Get screen width and height using Windows command
|
||||
display_num = None
|
||||
offset_x = 0
|
||||
offset_y = 0
|
||||
selected_screen = selected_screen
|
||||
width, height = _get_screen_size()
|
||||
|
||||
"""Take a screenshot of the current screen and return a ToolResult with the base64 encoded image."""
|
||||
output_dir = Path(OUTPUT_DIR)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
path = output_dir / f"screenshot_{uuid4().hex}.png"
|
||||
|
||||
ImageGrab.grab = partial(ImageGrab.grab, all_screens=True)
|
||||
|
||||
# Detect platform
|
||||
system = platform.system()
|
||||
|
||||
if system == "Windows":
|
||||
# Windows: Use screeninfo to get monitor details
|
||||
screens = get_monitors()
|
||||
|
||||
# Sort screens by x position to arrange from left to right
|
||||
sorted_screens = sorted(screens, key=lambda s: s.x)
|
||||
|
||||
if selected_screen < 0 or selected_screen >= len(screens):
|
||||
raise IndexError("Invalid screen index.")
|
||||
|
||||
screen = sorted_screens[selected_screen]
|
||||
bbox = (screen.x, screen.y, screen.x + screen.width, screen.y + screen.height)
|
||||
|
||||
elif system == "Darwin": # macOS
|
||||
# macOS: Use Quartz to get monitor details
|
||||
max_displays = 32 # Maximum number of displays to handle
|
||||
active_displays = Quartz.CGGetActiveDisplayList(max_displays, None, None)[1]
|
||||
|
||||
# Get the display bounds (resolution) for each active display
|
||||
screens = []
|
||||
for display_id in active_displays:
|
||||
bounds = Quartz.CGDisplayBounds(display_id)
|
||||
screens.append({
|
||||
'id': display_id,
|
||||
'x': int(bounds.origin.x),
|
||||
'y': int(bounds.origin.y),
|
||||
'width': int(bounds.size.width),
|
||||
'height': int(bounds.size.height),
|
||||
'is_primary': Quartz.CGDisplayIsMain(display_id) # Check if this is the primary display
|
||||
})
|
||||
|
||||
# Sort screens by x position to arrange from left to right
|
||||
sorted_screens = sorted(screens, key=lambda s: s['x'])
|
||||
# print(f"Darwin sorted_screens: {sorted_screens}")
|
||||
|
||||
if selected_screen < 0 or selected_screen >= len(screens):
|
||||
raise IndexError("Invalid screen index.")
|
||||
|
||||
screen = sorted_screens[selected_screen]
|
||||
|
||||
bbox = (screen['x'], screen['y'], screen['x'] + screen['width'], screen['y'] + screen['height'])
|
||||
|
||||
else: # Linux or other OS
|
||||
cmd = "xrandr | grep ' primary' | awk '{print $4}'"
|
||||
try:
|
||||
# output = subprocess.check_output(cmd, shell=True).decode()
|
||||
# resolution = output.strip().split()[0]
|
||||
# width, height = map(int, resolution.split('x'))
|
||||
screen = get_monitors()[0]
|
||||
width, height = screen.width, screen.height
|
||||
bbox = (0, 0, width, height) # Assuming single primary screen for simplicity
|
||||
except subprocess.CalledProcessError:
|
||||
raise RuntimeError("Failed to get screen resolution on Linux.")
|
||||
|
||||
# Take screenshot using the bounding box
|
||||
screenshot = ImageGrab.grab(bbox=bbox)
|
||||
import os
|
||||
if (display_num := os.getenv("DISPLAY_NUM")) is not None:
|
||||
display_num = int(display_num)
|
||||
_display_prefix = f"DISPLAY=:{display_num} "
|
||||
else:
|
||||
display_num = None
|
||||
_display_prefix = ""
|
||||
screenshot_cmd = f"{_display_prefix}scrot -p {path}"
|
||||
import pdb; pdb.set_trace()
|
||||
result = subprocess.run(screenshot_cmd, shell=True, capture_output=True)
|
||||
|
||||
# Set offsets (for potential future use)
|
||||
offset_x = screen['x'] if system == "Darwin" else screen.x
|
||||
offset_y = screen['y'] if system == "Darwin" else screen.y
|
||||
|
||||
# # Resize if
|
||||
if resize:
|
||||
screenshot = screenshot.resize((target_width, target_height))
|
||||
|
||||
# Save the screenshot
|
||||
# screenshot.save(str(path))
|
||||
|
||||
if path.exists():
|
||||
# Return a ToolResult instance instead of a dictionary
|
||||
return screenshot, path
|
||||
|
||||
raise ToolError(f"Failed to take screenshot: {path} does not exist.")
|
||||
|
||||
|
||||
|
||||
|
||||
def _get_screen_size(selected_screen: int = 0):
|
||||
if platform.system() == "Windows":
|
||||
# Use screeninfo to get primary monitor on Windows
|
||||
screens = get_monitors()
|
||||
|
||||
# Sort screens by x position to arrange from left to right
|
||||
sorted_screens = sorted(screens, key=lambda s: s.x)
|
||||
if selected_screen is None:
|
||||
primary_monitor = next((m for m in get_monitors() if m.is_primary), None)
|
||||
return primary_monitor.width, primary_monitor.height
|
||||
elif selected_screen < 0 or selected_screen >= len(screens):
|
||||
raise IndexError("Invalid screen index.")
|
||||
else:
|
||||
screen = sorted_screens[selected_screen]
|
||||
return screen.width, screen.height
|
||||
elif platform.system() == "Darwin":
|
||||
# macOS part using Quartz to get screen information
|
||||
max_displays = 32 # Maximum number of displays to handle
|
||||
active_displays = Quartz.CGGetActiveDisplayList(max_displays, None, None)[1]
|
||||
|
||||
# Get the display bounds (resolution) for each active display
|
||||
screens = []
|
||||
for display_id in active_displays:
|
||||
bounds = Quartz.CGDisplayBounds(display_id)
|
||||
screens.append({
|
||||
'id': display_id,
|
||||
'x': int(bounds.origin.x),
|
||||
'y': int(bounds.origin.y),
|
||||
'width': int(bounds.size.width),
|
||||
'height': int(bounds.size.height),
|
||||
'is_primary': Quartz.CGDisplayIsMain(display_id) # Check if this is the primary display
|
||||
})
|
||||
|
||||
# Sort screens by x position to arrange from left to right
|
||||
sorted_screens = sorted(screens, key=lambda s: s['x'])
|
||||
|
||||
if selected_screen is None:
|
||||
# Find the primary monitor
|
||||
primary_monitor = next((screen for screen in screens if screen['is_primary']), None)
|
||||
if primary_monitor:
|
||||
return primary_monitor['width'], primary_monitor['height']
|
||||
else:
|
||||
raise RuntimeError("No primary monitor found.")
|
||||
elif selected_screen < 0 or selected_screen >= len(screens):
|
||||
raise IndexError("Invalid screen index.")
|
||||
else:
|
||||
# Return the resolution of the selected screen
|
||||
screen = sorted_screens[selected_screen]
|
||||
return screen['width'], screen['height']
|
||||
|
||||
else: # Linux or other OS
|
||||
cmd = "xrandr | grep ' primary' | awk '{print $4}'"
|
||||
try:
|
||||
# output = subprocess.check_output(cmd, shell=True).decode()
|
||||
# resolution = output.strip().split()[0]
|
||||
# width, height = map(int, resolution.split('x'))
|
||||
# return width, height
|
||||
screen = get_monitors()[0]
|
||||
return screen.width, screen.height
|
||||
except subprocess.CalledProcessError:
|
||||
raise RuntimeError("Failed to get screen resolution on Linux.")
|
||||
@@ -8,7 +8,7 @@ import io
|
||||
|
||||
|
||||
import base64, os
|
||||
from utils import check_ocr_box, get_yolo_model, get_caption_model_processor, get_som_labeled_img
|
||||
from util.utils import check_ocr_box, get_yolo_model, get_caption_model_processor, get_som_labeled_img
|
||||
import torch
|
||||
from PIL import Image
|
||||
|
||||
@@ -17,8 +17,6 @@ yolo_model = get_yolo_model(model_path='weights/icon_detect_v1_5/best.pt')
|
||||
caption_model_processor = get_caption_model_processor(model_name="florence2", model_name_or_path="weights/icon_caption_florence")
|
||||
# caption_model_processor = get_caption_model_processor(model_name="blip2", model_name_or_path="weights/icon_caption_blip2")
|
||||
|
||||
|
||||
|
||||
MARKDOWN = """
|
||||
# OmniParser for Pure Vision Based General GUI Agent 🔥
|
||||
<div>
|
||||
@@ -65,8 +63,6 @@ def process(
|
||||
# parsed_content_list = str(parsed_content_list)
|
||||
return image, str(parsed_content_list)
|
||||
|
||||
|
||||
|
||||
with gr.Blocks() as demo:
|
||||
gr.Markdown(MARKDOWN)
|
||||
with gr.Row():
|
||||
|
||||
BIN
imgs/gradioicon.png
Normal file
|
After Width: | Height: | Size: 33 KiB |
BIN
imgs/header_bar.png
Normal file
|
After Width: | Height: | Size: 210 KiB |
BIN
imgs/header_bar_thin.png
Normal file
|
After Width: | Height: | Size: 132 KiB |
BIN
imgs/omniboxicon.png
Normal file
|
After Width: | Height: | Size: 3.4 KiB |
BIN
imgs/omniparsericon.png
Normal file
|
After Width: | Height: | Size: 7.4 KiB |
BIN
imgs/som_overlaid_omni.png
Normal file
|
After Width: | Height: | Size: 279 KiB |
@@ -1,60 +0,0 @@
|
||||
from utils import get_som_labeled_img, check_ocr_box, get_yolo_model
|
||||
import torch
|
||||
from ultralytics import YOLO
|
||||
from PIL import Image
|
||||
from typing import Dict, Tuple, List
|
||||
import io
|
||||
import base64
|
||||
|
||||
|
||||
config = {
|
||||
'som_model_path': 'finetuned_icon_detect.pt',
|
||||
'device': 'cpu',
|
||||
'caption_model_path': 'Salesforce/blip2-opt-2.7b',
|
||||
'draw_bbox_config': {
|
||||
'text_scale': 0.8,
|
||||
'text_thickness': 2,
|
||||
'text_padding': 3,
|
||||
'thickness': 3,
|
||||
},
|
||||
'BOX_TRESHOLD': 0.05
|
||||
}
|
||||
|
||||
|
||||
class Omniparser(object):
|
||||
def __init__(self, config: Dict):
|
||||
self.config = config
|
||||
|
||||
self.som_model = get_yolo_model(model_path=config['som_model_path'])
|
||||
# self.caption_model_processor = get_caption_model_processor(config['caption_model_path'], device=cofig['device'])
|
||||
# self.caption_model_processor['model'].to(torch.float32)
|
||||
|
||||
def parse(self, image_path: str):
|
||||
print('Parsing image:', image_path)
|
||||
ocr_bbox_rslt, is_goal_filtered = check_ocr_box(image_path, display_img = False, output_bb_format='xyxy', goal_filtering=None, easyocr_args={'paragraph': False, 'text_threshold':0.9})
|
||||
text, ocr_bbox = ocr_bbox_rslt
|
||||
|
||||
draw_bbox_config = self.config['draw_bbox_config']
|
||||
BOX_TRESHOLD = self.config['BOX_TRESHOLD']
|
||||
dino_labled_img, label_coordinates, parsed_content_list = get_som_labeled_img(image_path, self.som_model, BOX_TRESHOLD = BOX_TRESHOLD, output_coord_in_ratio=False, ocr_bbox=ocr_bbox,draw_bbox_config=draw_bbox_config, caption_model_processor=None, ocr_text=text,use_local_semantics=False)
|
||||
|
||||
image = Image.open(io.BytesIO(base64.b64decode(dino_labled_img)))
|
||||
# formating output
|
||||
return_list = [{'from': 'omniparser', 'shape': {'x':coord[0], 'y':coord[1], 'width':coord[2], 'height':coord[3]},
|
||||
'text': parsed_content_list[i].split(': ')[1], 'type':'text'} for i, (k, coord) in enumerate(label_coordinates.items()) if i < len(parsed_content_list)]
|
||||
return_list.extend(
|
||||
[{'from': 'omniparser', 'shape': {'x':coord[0], 'y':coord[1], 'width':coord[2], 'height':coord[3]},
|
||||
'text': 'None', 'type':'icon'} for i, (k, coord) in enumerate(label_coordinates.items()) if i >= len(parsed_content_list)]
|
||||
)
|
||||
|
||||
return [image, return_list]
|
||||
|
||||
parser = Omniparser(config)
|
||||
image_path = 'examples/pc_1.png'
|
||||
|
||||
# time the parser
|
||||
import time
|
||||
s = time.time()
|
||||
image, parsed_content_list = parser.parse(image_path)
|
||||
device = config['device']
|
||||
print(f'Time taken for Omniparser on {device}:', time.time() - s)
|
||||
1
omnitool/gradio/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
tmp/
|
||||
@@ -1,207 +1,162 @@
|
||||
"""
|
||||
Agentic sampling loop that calls the Anthropic API and local implenmentation of anthropic-defined computer use tools.
|
||||
"""
|
||||
import asyncio
|
||||
import platform
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import Any, cast
|
||||
|
||||
from anthropic import Anthropic, AnthropicBedrock, AnthropicVertex, APIResponse
|
||||
from anthropic.types import (
|
||||
ToolResultBlockParam,
|
||||
)
|
||||
from anthropic.types.beta import (
|
||||
BetaContentBlock,
|
||||
BetaContentBlockParam,
|
||||
BetaImageBlockParam,
|
||||
BetaMessage,
|
||||
BetaMessageParam,
|
||||
BetaTextBlockParam,
|
||||
BetaToolResultBlockParam,
|
||||
)
|
||||
from anthropic.types import TextBlock
|
||||
from anthropic.types.beta import BetaMessage, BetaTextBlock, BetaToolUseBlock
|
||||
|
||||
from tools import BashTool, ComputerTool, EditTool, ToolCollection, ToolResult
|
||||
|
||||
from PIL import Image
|
||||
from io import BytesIO
|
||||
import gradio as gr
|
||||
from typing import Dict
|
||||
|
||||
|
||||
BETA_FLAG = "computer-use-2024-10-22"
|
||||
|
||||
|
||||
class APIProvider(StrEnum):
|
||||
ANTHROPIC = "anthropic"
|
||||
BEDROCK = "bedrock"
|
||||
VERTEX = "vertex"
|
||||
|
||||
|
||||
PROVIDER_TO_DEFAULT_MODEL_NAME: dict[APIProvider, str] = {
|
||||
APIProvider.ANTHROPIC: "claude-3-5-sonnet-20241022",
|
||||
APIProvider.BEDROCK: "anthropic.claude-3-5-sonnet-20241022-v2:0",
|
||||
APIProvider.VERTEX: "claude-3-5-sonnet-v2@20241022",
|
||||
}
|
||||
|
||||
|
||||
# Check OS
|
||||
|
||||
SYSTEM_PROMPT = f"""<SYSTEM_CAPABILITY>
|
||||
* You are utilizing a Windows system with internet access.
|
||||
* The current date is {datetime.today().strftime('%A, %B %d, %Y')}.
|
||||
</SYSTEM_CAPABILITY>
|
||||
"""
|
||||
|
||||
|
||||
class AnthropicActor:
|
||||
def __init__(
|
||||
self,
|
||||
model: str,
|
||||
provider: APIProvider,
|
||||
system_prompt_suffix: str,
|
||||
api_key: str,
|
||||
api_response_callback: Callable[[APIResponse[BetaMessage]], None],
|
||||
max_tokens: int = 4096,
|
||||
only_n_most_recent_images: int | None = None,
|
||||
selected_screen: int = 0,
|
||||
print_usage: bool = True,
|
||||
):
|
||||
self.model = model
|
||||
self.provider = provider
|
||||
self.system_prompt_suffix = system_prompt_suffix
|
||||
self.api_key = api_key
|
||||
self.api_response_callback = api_response_callback
|
||||
self.max_tokens = max_tokens
|
||||
self.only_n_most_recent_images = only_n_most_recent_images
|
||||
self.selected_screen = selected_screen
|
||||
|
||||
self.tool_collection = ToolCollection(
|
||||
ComputerTool(selected_screen=selected_screen),
|
||||
BashTool(),
|
||||
EditTool(),
|
||||
)
|
||||
|
||||
self.system = (
|
||||
f"{SYSTEM_PROMPT}{' ' + system_prompt_suffix if system_prompt_suffix else ''}"
|
||||
)
|
||||
|
||||
self.total_token_usage = 0
|
||||
self.total_cost = 0
|
||||
self.print_usage = print_usage
|
||||
|
||||
# Instantiate the appropriate API client based on the provider
|
||||
if provider == APIProvider.ANTHROPIC:
|
||||
self.client = Anthropic(api_key=api_key)
|
||||
elif provider == APIProvider.VERTEX:
|
||||
self.client = AnthropicVertex()
|
||||
elif provider == APIProvider.BEDROCK:
|
||||
self.client = AnthropicBedrock()
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
*,
|
||||
messages: list[BetaMessageParam]
|
||||
):
|
||||
"""
|
||||
Generate a response given history messages.
|
||||
"""
|
||||
if self.only_n_most_recent_images:
|
||||
_maybe_filter_to_n_most_recent_images(messages, self.only_n_most_recent_images)
|
||||
|
||||
# Call the API synchronously
|
||||
raw_response = self.client.beta.messages.with_raw_response.create(
|
||||
max_tokens=self.max_tokens,
|
||||
messages=messages,
|
||||
model=self.model,
|
||||
system=self.system,
|
||||
tools=self.tool_collection.to_params(),
|
||||
betas=["computer-use-2024-10-22"],
|
||||
)
|
||||
|
||||
self.api_response_callback(cast(APIResponse[BetaMessage], raw_response))
|
||||
|
||||
response = raw_response.parse()
|
||||
print(f"AnthropicActor response: {response}")
|
||||
|
||||
self.total_token_usage += response.usage.input_tokens + response.usage.output_tokens
|
||||
self.total_cost += (response.usage.input_tokens * 3 / 1000000 + response.usage.output_tokens * 15 / 1000000)
|
||||
|
||||
if self.print_usage:
|
||||
print(f"Claude total token usage so far: {self.total_token_usage}, total cost so far: $USD{self.total_cost}")
|
||||
|
||||
return response
|
||||
|
||||
|
||||
def _maybe_filter_to_n_most_recent_images(
|
||||
messages: list[BetaMessageParam],
|
||||
images_to_keep: int,
|
||||
min_removal_threshold: int = 10,
|
||||
):
|
||||
"""
|
||||
With the assumption that images are screenshots that are of diminishing value as
|
||||
the conversation progresses, remove all but the final `images_to_keep` tool_result
|
||||
images in place, with a chunk of min_removal_threshold to reduce the amount we
|
||||
break the implicit prompt cache.
|
||||
"""
|
||||
if images_to_keep is None:
|
||||
return messages
|
||||
|
||||
tool_result_blocks = cast(
|
||||
list[ToolResultBlockParam],
|
||||
[
|
||||
item
|
||||
for message in messages
|
||||
for item in (
|
||||
message["content"] if isinstance(message["content"], list) else []
|
||||
)
|
||||
if isinstance(item, dict) and item.get("type") == "tool_result"
|
||||
],
|
||||
)
|
||||
|
||||
total_images = sum(
|
||||
1
|
||||
for tool_result in tool_result_blocks
|
||||
for content in tool_result.get("content", [])
|
||||
if isinstance(content, dict) and content.get("type") == "image"
|
||||
)
|
||||
|
||||
images_to_remove = total_images - images_to_keep
|
||||
# for better cache behavior, we want to remove in chunks
|
||||
images_to_remove -= images_to_remove % min_removal_threshold
|
||||
|
||||
for tool_result in tool_result_blocks:
|
||||
if isinstance(tool_result.get("content"), list):
|
||||
new_content = []
|
||||
for content in tool_result.get("content", []):
|
||||
if isinstance(content, dict) and content.get("type") == "image":
|
||||
if images_to_remove > 0:
|
||||
images_to_remove -= 1
|
||||
continue
|
||||
new_content.append(content)
|
||||
tool_result["content"] = new_content
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pass
|
||||
# client = Anthropic(api_key="")
|
||||
# response = client.beta.messages.with_raw_response.create(
|
||||
# max_tokens=4096,
|
||||
# model="claude-3-5-sonnet-20241022",
|
||||
# system=SYSTEM_PROMPT,
|
||||
# # tools=ToolCollection(
|
||||
# # ComputerTool(selected_screen=0),
|
||||
# # BashTool(),
|
||||
# # EditTool(),
|
||||
# # ).to_params(),
|
||||
# betas=["computer-use-2024-10-22"],
|
||||
# messages=[
|
||||
# {"role": "user", "content": "click on (199, 199)."}
|
||||
# ],
|
||||
# )
|
||||
|
||||
# print(f"AnthropicActor response: {response.parse().usage.input_tokens+response.parse().usage.output_tokens}")
|
||||
"""
|
||||
Agentic sampling loop that calls the Anthropic API and local implenmentation of anthropic-defined computer use tools.
|
||||
"""
|
||||
import asyncio
|
||||
import platform
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import Any, cast
|
||||
|
||||
from anthropic import Anthropic, AnthropicBedrock, AnthropicVertex, APIResponse
|
||||
from anthropic.types import (
|
||||
ToolResultBlockParam,
|
||||
)
|
||||
from anthropic.types.beta import (
|
||||
BetaContentBlock,
|
||||
BetaContentBlockParam,
|
||||
BetaImageBlockParam,
|
||||
BetaMessage,
|
||||
BetaMessageParam,
|
||||
BetaTextBlockParam,
|
||||
BetaToolResultBlockParam,
|
||||
)
|
||||
from anthropic.types import TextBlock
|
||||
from anthropic.types.beta import BetaMessage, BetaTextBlock, BetaToolUseBlock
|
||||
|
||||
from tools import ComputerTool, ToolCollection, ToolResult
|
||||
|
||||
from PIL import Image
|
||||
from io import BytesIO
|
||||
import gradio as gr
|
||||
from typing import Dict
|
||||
|
||||
BETA_FLAG = "computer-use-2024-10-22"
|
||||
|
||||
class APIProvider(StrEnum):
|
||||
ANTHROPIC = "anthropic"
|
||||
BEDROCK = "bedrock"
|
||||
VERTEX = "vertex"
|
||||
|
||||
SYSTEM_PROMPT = f"""<SYSTEM_CAPABILITY>
|
||||
* You are utilizing a Windows system with internet access.
|
||||
* The current date is {datetime.today().strftime('%A, %B %d, %Y')}.
|
||||
</SYSTEM_CAPABILITY>
|
||||
"""
|
||||
|
||||
class AnthropicActor:
|
||||
def __init__(
|
||||
self,
|
||||
model: str,
|
||||
provider: APIProvider,
|
||||
api_key: str,
|
||||
api_response_callback: Callable[[APIResponse[BetaMessage]], None],
|
||||
max_tokens: int = 4096,
|
||||
only_n_most_recent_images: int | None = None,
|
||||
print_usage: bool = True,
|
||||
):
|
||||
self.model = model
|
||||
self.provider = provider
|
||||
self.api_key = api_key
|
||||
self.api_response_callback = api_response_callback
|
||||
self.max_tokens = max_tokens
|
||||
self.only_n_most_recent_images = only_n_most_recent_images
|
||||
|
||||
self.tool_collection = ToolCollection(ComputerTool())
|
||||
|
||||
self.system = SYSTEM_PROMPT
|
||||
|
||||
self.total_token_usage = 0
|
||||
self.total_cost = 0
|
||||
self.print_usage = print_usage
|
||||
|
||||
# Instantiate the appropriate API client based on the provider
|
||||
if provider == APIProvider.ANTHROPIC:
|
||||
self.client = Anthropic(api_key=api_key)
|
||||
elif provider == APIProvider.VERTEX:
|
||||
self.client = AnthropicVertex()
|
||||
elif provider == APIProvider.BEDROCK:
|
||||
self.client = AnthropicBedrock()
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
*,
|
||||
messages: list[BetaMessageParam]
|
||||
):
|
||||
"""
|
||||
Generate a response given history messages.
|
||||
"""
|
||||
if self.only_n_most_recent_images:
|
||||
_maybe_filter_to_n_most_recent_images(messages, self.only_n_most_recent_images)
|
||||
|
||||
# Call the API synchronously
|
||||
raw_response = self.client.beta.messages.with_raw_response.create(
|
||||
max_tokens=self.max_tokens,
|
||||
messages=messages,
|
||||
model=self.model,
|
||||
system=self.system,
|
||||
tools=self.tool_collection.to_params(),
|
||||
betas=["computer-use-2024-10-22"],
|
||||
)
|
||||
|
||||
self.api_response_callback(cast(APIResponse[BetaMessage], raw_response))
|
||||
|
||||
response = raw_response.parse()
|
||||
print(f"AnthropicActor response: {response}")
|
||||
|
||||
self.total_token_usage += response.usage.input_tokens + response.usage.output_tokens
|
||||
self.total_cost += (response.usage.input_tokens * 3 / 1000000 + response.usage.output_tokens * 15 / 1000000)
|
||||
|
||||
if self.print_usage:
|
||||
print(f"Claude total token usage so far: {self.total_token_usage}, total cost so far: $USD{self.total_cost}")
|
||||
|
||||
return response
|
||||
|
||||
|
||||
def _maybe_filter_to_n_most_recent_images(
|
||||
messages: list[BetaMessageParam],
|
||||
images_to_keep: int,
|
||||
min_removal_threshold: int = 10,
|
||||
):
|
||||
"""
|
||||
With the assumption that images are screenshots that are of diminishing value as
|
||||
the conversation progresses, remove all but the final `images_to_keep` tool_result
|
||||
images in place, with a chunk of min_removal_threshold to reduce the amount we
|
||||
break the implicit prompt cache.
|
||||
"""
|
||||
if images_to_keep is None:
|
||||
return messages
|
||||
|
||||
tool_result_blocks = cast(
|
||||
list[ToolResultBlockParam],
|
||||
[
|
||||
item
|
||||
for message in messages
|
||||
for item in (
|
||||
message["content"] if isinstance(message["content"], list) else []
|
||||
)
|
||||
if isinstance(item, dict) and item.get("type") == "tool_result"
|
||||
],
|
||||
)
|
||||
|
||||
total_images = sum(
|
||||
1
|
||||
for tool_result in tool_result_blocks
|
||||
for content in tool_result.get("content", [])
|
||||
if isinstance(content, dict) and content.get("type") == "image"
|
||||
)
|
||||
|
||||
images_to_remove = total_images - images_to_keep
|
||||
# for better cache behavior, we want to remove in chunks
|
||||
images_to_remove -= images_to_remove % min_removal_threshold
|
||||
|
||||
for tool_result in tool_result_blocks:
|
||||
if isinstance(tool_result.get("content"), list):
|
||||
new_content = []
|
||||
for content in tool_result.get("content", []):
|
||||
if isinstance(content, dict) and content.get("type") == "image":
|
||||
if images_to_remove > 0:
|
||||
images_to_remove -= 1
|
||||
continue
|
||||
new_content.append(content)
|
||||
tool_result["content"] = new_content
|
||||
59
omnitool/gradio/agent/llm_utils/groqclient.py
Normal file
@@ -0,0 +1,59 @@
|
||||
from groq import Groq
|
||||
import os
|
||||
from .utils import is_image_path
|
||||
|
||||
def run_groq_interleaved(messages: list, system: str, model_name: str, api_key: str, max_tokens=256, temperature=0.6):
|
||||
"""
|
||||
Run a chat completion through Groq's API, ignoring any images in the messages.
|
||||
"""
|
||||
api_key = api_key or os.environ.get("GROQ_API_KEY")
|
||||
if not api_key:
|
||||
raise ValueError("GROQ_API_KEY is not set")
|
||||
|
||||
client = Groq(api_key=api_key)
|
||||
# avoid using system messages for R1
|
||||
final_messages = [{"role": "user", "content": system}]
|
||||
|
||||
if isinstance(messages, list):
|
||||
for item in messages:
|
||||
if isinstance(item, dict):
|
||||
# For dict items, concatenate all text content, ignoring images
|
||||
text_contents = []
|
||||
for cnt in item["content"]:
|
||||
if isinstance(cnt, str):
|
||||
if not is_image_path(cnt): # Skip image paths
|
||||
text_contents.append(cnt)
|
||||
else:
|
||||
text_contents.append(str(cnt))
|
||||
|
||||
if text_contents: # Only add if there's text content
|
||||
message = {"role": "user", "content": " ".join(text_contents)}
|
||||
final_messages.append(message)
|
||||
else: # str
|
||||
message = {"role": "user", "content": item}
|
||||
final_messages.append(message)
|
||||
|
||||
elif isinstance(messages, str):
|
||||
final_messages.append({"role": "user", "content": messages})
|
||||
|
||||
try:
|
||||
completion = client.chat.completions.create(
|
||||
model="deepseek-r1-distill-llama-70b",
|
||||
messages=final_messages,
|
||||
temperature=0.6,
|
||||
max_completion_tokens=max_tokens,
|
||||
top_p=0.95,
|
||||
stream=False,
|
||||
reasoning_format="raw"
|
||||
)
|
||||
|
||||
response = completion.choices[0].message.content
|
||||
final_answer = response.split('</think>\n')[-1] if '</think>' in response else response
|
||||
final_answer = final_answer.replace("<output>", "").replace("</output>", "")
|
||||
token_usage = completion.usage.total_tokens
|
||||
|
||||
return final_answer, token_usage
|
||||
except Exception as e:
|
||||
print(f"Error in interleaved Groq: {e}")
|
||||
|
||||
return str(e), 0
|
||||
62
omnitool/gradio/agent/llm_utils/oaiclient.py
Normal file
@@ -0,0 +1,62 @@
|
||||
import os
|
||||
import logging
|
||||
import base64
|
||||
import requests
|
||||
from .utils import is_image_path, encode_image
|
||||
|
||||
def run_oai_interleaved(messages: list, system: str, model_name: str, api_key: str, max_tokens=256, temperature=0, provider_base_url: str = "https://api.openai.com/v1"):
|
||||
headers = {"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {api_key}"}
|
||||
final_messages = [{"role": "system", "content": system}]
|
||||
|
||||
if type(messages) == list:
|
||||
for item in messages:
|
||||
contents = []
|
||||
if isinstance(item, dict):
|
||||
for cnt in item["content"]:
|
||||
if isinstance(cnt, str):
|
||||
if is_image_path(cnt) and 'o3-mini' not in model_name:
|
||||
# 03 mini does not support images
|
||||
base64_image = encode_image(cnt)
|
||||
content = {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}}
|
||||
else:
|
||||
content = {"type": "text", "text": cnt}
|
||||
else:
|
||||
# in this case it is a text block from anthropic
|
||||
content = {"type": "text", "text": str(cnt)}
|
||||
|
||||
contents.append(content)
|
||||
|
||||
message = {"role": 'user', "content": contents}
|
||||
else: # str
|
||||
contents.append({"type": "text", "text": item})
|
||||
message = {"role": "user", "content": contents}
|
||||
|
||||
final_messages.append(message)
|
||||
|
||||
|
||||
elif isinstance(messages, str):
|
||||
final_messages = [{"role": "user", "content": messages}]
|
||||
|
||||
payload = {
|
||||
"model": model_name,
|
||||
"messages": final_messages,
|
||||
}
|
||||
if 'o1' in model_name or 'o3-mini' in model_name:
|
||||
payload['reasoning_effort'] = 'low'
|
||||
payload['max_completion_tokens'] = max_tokens
|
||||
else:
|
||||
payload['max_tokens'] = max_tokens
|
||||
|
||||
response = requests.post(
|
||||
f"{provider_base_url}/chat/completions", headers=headers, json=payload
|
||||
)
|
||||
|
||||
|
||||
try:
|
||||
text = response.json()['choices'][0]['message']['content']
|
||||
token_usage = int(response.json()['usage']['total_tokens'])
|
||||
return text, token_usage
|
||||
except Exception as e:
|
||||
print(f"Error in interleaved openAI: {e}. This may due to your invalid API key. Please check the response: {response.json()} ")
|
||||
return response.json()
|
||||
44
omnitool/gradio/agent/llm_utils/omniparserclient.py
Normal file
@@ -0,0 +1,44 @@
|
||||
import requests
|
||||
import base64
|
||||
from pathlib import Path
|
||||
from tools.screen_capture import get_screenshot
|
||||
from agent.llm_utils.utils import encode_image
|
||||
|
||||
OUTPUT_DIR = "./tmp/outputs"
|
||||
|
||||
class OmniParserClient:
|
||||
def __init__(self,
|
||||
url: str) -> None:
|
||||
self.url = url
|
||||
|
||||
def __call__(self,):
|
||||
screenshot, screenshot_path = get_screenshot()
|
||||
screenshot_path = str(screenshot_path)
|
||||
image_base64 = encode_image(screenshot_path)
|
||||
response = requests.post(self.url, json={"base64_image": image_base64})
|
||||
response_json = response.json()
|
||||
print('omniparser latency:', response_json['latency'])
|
||||
|
||||
som_image_data = base64.b64decode(response_json['som_image_base64'])
|
||||
screenshot_path_uuid = Path(screenshot_path).stem.replace("screenshot_", "")
|
||||
som_screenshot_path = f"{OUTPUT_DIR}/screenshot_som_{screenshot_path_uuid}.png"
|
||||
with open(som_screenshot_path, "wb") as f:
|
||||
f.write(som_image_data)
|
||||
|
||||
response_json['width'] = screenshot.size[0]
|
||||
response_json['height'] = screenshot.size[1]
|
||||
response_json['original_screenshot_base64'] = image_base64
|
||||
response_json['screenshot_uuid'] = screenshot_path_uuid
|
||||
response_json = self.reformat_messages(response_json)
|
||||
return response_json
|
||||
|
||||
def reformat_messages(self, response_json: dict):
|
||||
screen_info = ""
|
||||
for idx, element in enumerate(response_json["parsed_content_list"]):
|
||||
element['idx'] = idx
|
||||
if element['type'] == 'text':
|
||||
screen_info += f'ID: {idx}, Text: {element["content"]}\n'
|
||||
elif element['type'] == 'icon':
|
||||
screen_info += f'ID: {idx}, Icon: {element["content"]}\n'
|
||||
response_json['screen_info'] = screen_info
|
||||
return response_json
|
||||
13
omnitool/gradio/agent/llm_utils/utils.py
Normal file
@@ -0,0 +1,13 @@
|
||||
import base64
|
||||
|
||||
def is_image_path(text):
|
||||
image_extensions = (".jpg", ".jpeg", ".png", ".gif", ".bmp", ".tiff", ".tif")
|
||||
if text.endswith(image_extensions):
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def encode_image(image_path):
|
||||
"""Encode image file to base64."""
|
||||
with open(image_path, "rb") as image_file:
|
||||
return base64.b64encode(image_file.read()).decode("utf-8")
|
||||
338
omnitool/gradio/agent/vlm_agent.py
Normal file
@@ -0,0 +1,338 @@
|
||||
import json
|
||||
from collections.abc import Callable
|
||||
from typing import cast, Callable
|
||||
import uuid
|
||||
from PIL import Image, ImageDraw
|
||||
import base64
|
||||
from io import BytesIO
|
||||
|
||||
from anthropic import APIResponse
|
||||
from anthropic.types import ToolResultBlockParam
|
||||
from anthropic.types.beta import BetaMessage, BetaTextBlock, BetaToolUseBlock, BetaMessageParam, BetaUsage
|
||||
|
||||
from agent.llm_utils.oaiclient import run_oai_interleaved
|
||||
from agent.llm_utils.groqclient import run_groq_interleaved
|
||||
from agent.llm_utils.utils import is_image_path
|
||||
import time
|
||||
import re
|
||||
|
||||
OUTPUT_DIR = "./tmp/outputs"
|
||||
|
||||
def extract_data(input_string, data_type):
|
||||
# Regular expression to extract content starting from '```python' until the end if there are no closing backticks
|
||||
pattern = f"```{data_type}" + r"(.*?)(```|$)"
|
||||
# Extract content
|
||||
# re.DOTALL allows '.' to match newlines as well
|
||||
matches = re.findall(pattern, input_string, re.DOTALL)
|
||||
# Return the first match if exists, trimming whitespace and ignoring potential closing backticks
|
||||
return matches[0][0].strip() if matches else input_string
|
||||
|
||||
class VLMAgent:
|
||||
def __init__(
|
||||
self,
|
||||
model: str,
|
||||
provider: str,
|
||||
api_key: str,
|
||||
output_callback: Callable,
|
||||
api_response_callback: Callable,
|
||||
max_tokens: int = 4096,
|
||||
only_n_most_recent_images: int | None = None,
|
||||
print_usage: bool = True,
|
||||
):
|
||||
if model == "omniparser + gpt-4o":
|
||||
self.model = "gpt-4o-2024-11-20"
|
||||
elif model == "omniparser + R1":
|
||||
self.model = "deepseek-r1-distill-llama-70b"
|
||||
elif model == "omniparser + qwen2.5vl":
|
||||
self.model = "qwen2.5-vl-72b-instruct"
|
||||
elif model == "omniparser + o1":
|
||||
self.model = "o1"
|
||||
elif model == "omniparser + o3-mini":
|
||||
self.model = "o3-mini"
|
||||
else:
|
||||
raise ValueError(f"Model {model} not supported")
|
||||
|
||||
|
||||
self.provider = provider
|
||||
self.api_key = api_key
|
||||
self.api_response_callback = api_response_callback
|
||||
self.max_tokens = max_tokens
|
||||
self.only_n_most_recent_images = only_n_most_recent_images
|
||||
self.output_callback = output_callback
|
||||
|
||||
self.print_usage = print_usage
|
||||
self.total_token_usage = 0
|
||||
self.total_cost = 0
|
||||
self.step_count = 0
|
||||
|
||||
self.system = ''
|
||||
|
||||
def __call__(self, messages: list, parsed_screen: list[str, list, dict]):
|
||||
self.step_count += 1
|
||||
image_base64 = parsed_screen['original_screenshot_base64']
|
||||
latency_omniparser = parsed_screen['latency']
|
||||
self.output_callback(f'-- Step {self.step_count}: --', sender="bot")
|
||||
screen_info = str(parsed_screen['screen_info'])
|
||||
screenshot_uuid = parsed_screen['screenshot_uuid']
|
||||
screen_width, screen_height = parsed_screen['width'], parsed_screen['height']
|
||||
|
||||
boxids_and_labels = parsed_screen["screen_info"]
|
||||
system = self._get_system_prompt(boxids_and_labels)
|
||||
|
||||
# drop looping actions msg, byte image etc
|
||||
planner_messages = messages
|
||||
_remove_som_images(planner_messages)
|
||||
_maybe_filter_to_n_most_recent_images(planner_messages, self.only_n_most_recent_images)
|
||||
|
||||
if isinstance(planner_messages[-1], dict):
|
||||
if not isinstance(planner_messages[-1]["content"], list):
|
||||
planner_messages[-1]["content"] = [planner_messages[-1]["content"]]
|
||||
planner_messages[-1]["content"].append(f"{OUTPUT_DIR}/screenshot_{screenshot_uuid}.png")
|
||||
planner_messages[-1]["content"].append(f"{OUTPUT_DIR}/screenshot_som_{screenshot_uuid}.png")
|
||||
|
||||
start = time.time()
|
||||
if "gpt" in self.model or "o1" in self.model or "o3-mini" in self.model:
|
||||
vlm_response, token_usage = run_oai_interleaved(
|
||||
messages=planner_messages,
|
||||
system=system,
|
||||
model_name=self.model,
|
||||
api_key=self.api_key,
|
||||
max_tokens=self.max_tokens,
|
||||
provider_base_url="https://api.openai.com/v1",
|
||||
temperature=0,
|
||||
)
|
||||
print(f"oai token usage: {token_usage}")
|
||||
self.total_token_usage += token_usage
|
||||
if 'gpt' in self.model:
|
||||
self.total_cost += (token_usage * 2.5 / 1000000) # https://openai.com/api/pricing/
|
||||
elif 'o1' in self.model:
|
||||
self.total_cost += (token_usage * 15 / 1000000) # https://openai.com/api/pricing/
|
||||
elif 'o3-mini' in self.model:
|
||||
self.total_cost += (token_usage * 1.1 / 1000000) # https://openai.com/api/pricing/
|
||||
elif "r1" in self.model:
|
||||
vlm_response, token_usage = run_groq_interleaved(
|
||||
messages=planner_messages,
|
||||
system=system,
|
||||
model_name=self.model,
|
||||
api_key=self.api_key,
|
||||
max_tokens=self.max_tokens,
|
||||
)
|
||||
print(f"groq token usage: {token_usage}")
|
||||
self.total_token_usage += token_usage
|
||||
self.total_cost += (token_usage * 0.99 / 1000000)
|
||||
elif "qwen" in self.model:
|
||||
vlm_response, token_usage = run_oai_interleaved(
|
||||
messages=planner_messages,
|
||||
system=system,
|
||||
model_name=self.model,
|
||||
api_key=self.api_key,
|
||||
max_tokens=min(2048, self.max_tokens),
|
||||
provider_base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
|
||||
temperature=0,
|
||||
)
|
||||
print(f"qwen token usage: {token_usage}")
|
||||
self.total_token_usage += token_usage
|
||||
self.total_cost += (token_usage * 2.2 / 1000000) # https://help.aliyun.com/zh/model-studio/getting-started/models?spm=a2c4g.11186623.0.0.74b04823CGnPv7#fe96cfb1a422a
|
||||
else:
|
||||
raise ValueError(f"Model {self.model} not supported")
|
||||
latency_vlm = time.time() - start
|
||||
self.output_callback(f"LLM: {latency_vlm:.2f}s, OmniParser: {latency_omniparser:.2f}s", sender="bot")
|
||||
|
||||
print(f"{vlm_response}")
|
||||
|
||||
if self.print_usage:
|
||||
print(f"Total token so far: {self.total_token_usage}. Total cost so far: $USD{self.total_cost:.5f}")
|
||||
|
||||
vlm_response_json = extract_data(vlm_response, "json")
|
||||
vlm_response_json = json.loads(vlm_response_json)
|
||||
|
||||
img_to_show_base64 = parsed_screen["som_image_base64"]
|
||||
if "Box ID" in vlm_response_json:
|
||||
bbox = parsed_screen["parsed_content_list"][int(vlm_response_json["Box ID"])]["bbox"]
|
||||
vlm_response_json["box_centroid_coordinate"] = [int((bbox[0] + bbox[2]) / 2 * screen_width), int((bbox[1] + bbox[3]) / 2 * screen_height)]
|
||||
img_to_show_data = base64.b64decode(img_to_show_base64)
|
||||
img_to_show = Image.open(BytesIO(img_to_show_data))
|
||||
|
||||
draw = ImageDraw.Draw(img_to_show)
|
||||
x, y = vlm_response_json["box_centroid_coordinate"]
|
||||
radius = 10
|
||||
draw.ellipse((x - radius, y - radius, x + radius, y + radius), fill='red')
|
||||
draw.ellipse((x - radius*3, y - radius*3, x + radius*3, y + radius*3), fill=None, outline='red', width=2)
|
||||
|
||||
buffered = BytesIO()
|
||||
img_to_show.save(buffered, format="PNG")
|
||||
img_to_show_base64 = base64.b64encode(buffered.getvalue()).decode("utf-8")
|
||||
self.output_callback(f'<img src="data:image/png;base64,{img_to_show_base64}">', sender="bot")
|
||||
self.output_callback(
|
||||
f'<details>'
|
||||
f' <summary>Parsed Screen elemetns by OmniParser</summary>'
|
||||
f' <pre>{screen_info}</pre>'
|
||||
f'</details>',
|
||||
sender="bot"
|
||||
)
|
||||
vlm_plan_str = ""
|
||||
for key, value in vlm_response_json.items():
|
||||
if key == "Reasoning":
|
||||
vlm_plan_str += f'{value}'
|
||||
else:
|
||||
vlm_plan_str += f'\n{key}: {value}'
|
||||
|
||||
# construct the response so that anthropicExcutor can execute the tool
|
||||
response_content = [BetaTextBlock(text=vlm_plan_str, type='text')]
|
||||
if 'box_centroid_coordinate' in vlm_response_json:
|
||||
move_cursor_block = BetaToolUseBlock(id=f'toolu_{uuid.uuid4()}',
|
||||
input={'action': 'mouse_move', 'coordinate': vlm_response_json["box_centroid_coordinate"]},
|
||||
name='computer', type='tool_use')
|
||||
response_content.append(move_cursor_block)
|
||||
|
||||
if vlm_response_json["Next Action"] == "None":
|
||||
print("Task paused/completed.")
|
||||
elif vlm_response_json["Next Action"] == "type":
|
||||
sim_content_block = BetaToolUseBlock(id=f'toolu_{uuid.uuid4()}',
|
||||
input={'action': vlm_response_json["Next Action"], 'text': vlm_response_json["value"]},
|
||||
name='computer', type='tool_use')
|
||||
response_content.append(sim_content_block)
|
||||
else:
|
||||
sim_content_block = BetaToolUseBlock(id=f'toolu_{uuid.uuid4()}',
|
||||
input={'action': vlm_response_json["Next Action"]},
|
||||
name='computer', type='tool_use')
|
||||
response_content.append(sim_content_block)
|
||||
response_message = BetaMessage(id=f'toolu_{uuid.uuid4()}', content=response_content, model='', role='assistant', type='message', stop_reason='tool_use', usage=BetaUsage(input_tokens=0, output_tokens=0))
|
||||
return response_message, vlm_response_json
|
||||
|
||||
def _api_response_callback(self, response: APIResponse):
|
||||
self.api_response_callback(response)
|
||||
|
||||
def _get_system_prompt(self, screen_info: str = ""):
|
||||
main_section = f"""
|
||||
You are using a Windows device.
|
||||
You are able to use a mouse and keyboard to interact with the computer based on the given task and screenshot.
|
||||
You can only interact with the desktop GUI (no terminal or application menu access).
|
||||
|
||||
You may be given some history plan and actions, this is the response from the previous loop.
|
||||
You should carefully consider your plan base on the task, screenshot, and history actions.
|
||||
|
||||
Here is the list of all detected bounding boxes by IDs on the screen and their description:{screen_info}
|
||||
|
||||
Your available "Next Action" only include:
|
||||
- type: types a string of text.
|
||||
- left_click: move mouse to box id and left clicks.
|
||||
- right_click: move mouse to box id and right clicks.
|
||||
- double_click: move mouse to box id and double clicks.
|
||||
- hover: move mouse to box id.
|
||||
- scroll_up: scrolls the screen up.
|
||||
- scroll_down: scrolls the screen down.
|
||||
- wait: waits for 1 second for the device to load or respond.
|
||||
|
||||
Based on the visual information from the screenshot image and the detected bounding boxes, please determine the next action, the Box ID you should operate on (if action is not 'type', 'hover', 'scroll_up', 'scroll_down', 'wait'), and the value (if the action is 'type') in order to complete the task.
|
||||
|
||||
Output format:
|
||||
```json
|
||||
{{
|
||||
"Reasoning": str, # describe what is in the current screen, taking into account the history, then describe your step-by-step thoughts on how to achieve the task, choose one action from available actions at a time.
|
||||
"Next Action": "action_type, action description" | "None" # one action at a time, describe it in short and precisely.
|
||||
"Box ID": n,
|
||||
"value": "xxx" # only provide value field if the action is type, else don't include value key
|
||||
}}
|
||||
```
|
||||
|
||||
One Example:
|
||||
```json
|
||||
{{
|
||||
"Reasoning": "The current screen shows google result of amazon, in previous action I have searched amazon on google. Then I need to click on the first search results to go to amazon.com.",
|
||||
"Next Action": "left_click",
|
||||
"Box ID": m
|
||||
}}
|
||||
```
|
||||
|
||||
Another Example:
|
||||
```json
|
||||
{{
|
||||
"Reasoning": "The current screen shows the front page of amazon. There is no previous action. Therefore I need to type "Apple watch" in the search bar.",
|
||||
"Next Action": "type",
|
||||
"Box ID": n,
|
||||
"value": "Apple watch"
|
||||
}}
|
||||
```
|
||||
|
||||
IMPORTANT NOTES:
|
||||
1. You should only give a single action at a time.
|
||||
|
||||
"""
|
||||
thinking_model = "r1" in self.model
|
||||
if not thinking_model:
|
||||
main_section += """
|
||||
2. You should give an analysis to the current screen, and reflect on what has been done by looking at the history, then describe your step-by-step thoughts on how to achieve the task.
|
||||
|
||||
"""
|
||||
else:
|
||||
main_section += """
|
||||
2. In <think> XML tags give an analysis to the current screen, and reflect on what has been done by looking at the history, then describe your step-by-step thoughts on how to achieve the task. In <output> XML tags put the next action prediction JSON.
|
||||
|
||||
"""
|
||||
main_section += """
|
||||
3. Attach the next action prediction in the "Next Action".
|
||||
4. You should not include other actions, such as keyboard shortcuts.
|
||||
5. When the task is completed, don't complete additional actions. You should say "Next Action": "None" in the json field.
|
||||
"""
|
||||
|
||||
return main_section
|
||||
|
||||
def _remove_som_images(messages):
|
||||
for msg in messages:
|
||||
msg_content = msg["content"]
|
||||
if isinstance(msg_content, list):
|
||||
msg["content"] = [
|
||||
cnt for cnt in msg_content
|
||||
if not (isinstance(cnt, str) and 'som' in cnt and is_image_path(cnt))
|
||||
]
|
||||
|
||||
|
||||
def _maybe_filter_to_n_most_recent_images(
|
||||
messages: list[BetaMessageParam],
|
||||
images_to_keep: int,
|
||||
min_removal_threshold: int = 10,
|
||||
):
|
||||
"""
|
||||
With the assumption that images are screenshots that are of diminishing value as
|
||||
the conversation progresses, remove all but the final `images_to_keep` tool_result
|
||||
images in place
|
||||
"""
|
||||
if images_to_keep is None:
|
||||
return messages
|
||||
|
||||
total_images = 0
|
||||
for msg in messages:
|
||||
for cnt in msg.get("content", []):
|
||||
if isinstance(cnt, str) and is_image_path(cnt):
|
||||
total_images += 1
|
||||
elif isinstance(cnt, dict) and cnt.get("type") == "tool_result":
|
||||
for content in cnt.get("content", []):
|
||||
if isinstance(content, dict) and content.get("type") == "image":
|
||||
total_images += 1
|
||||
|
||||
images_to_remove = total_images - images_to_keep
|
||||
|
||||
for msg in messages:
|
||||
msg_content = msg["content"]
|
||||
if isinstance(msg_content, list):
|
||||
new_content = []
|
||||
for cnt in msg_content:
|
||||
# Remove images from SOM or screenshot as needed
|
||||
if isinstance(cnt, str) and is_image_path(cnt):
|
||||
if images_to_remove > 0:
|
||||
images_to_remove -= 1
|
||||
continue
|
||||
# VLM shouldn't use anthropic screenshot tool so shouldn't have these but in case it does, remove as needed
|
||||
elif isinstance(cnt, dict) and cnt.get("type") == "tool_result":
|
||||
new_tool_result_content = []
|
||||
for tool_result_entry in cnt.get("content", []):
|
||||
if isinstance(tool_result_entry, dict) and tool_result_entry.get("type") == "image":
|
||||
if images_to_remove > 0:
|
||||
images_to_remove -= 1
|
||||
continue
|
||||
new_tool_result_content.append(tool_result_entry)
|
||||
cnt["content"] = new_tool_result_content
|
||||
# Append fixed content to current message's content list
|
||||
new_content.append(cnt)
|
||||
msg["content"] = new_content
|
||||
@@ -1,479 +1,422 @@
|
||||
"""
|
||||
Entrypoint for Gradio, see https://gradio.app/
|
||||
"""
|
||||
|
||||
import platform
|
||||
import asyncio
|
||||
import base64
|
||||
import os
|
||||
import io
|
||||
import json
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import cast, Dict
|
||||
from PIL import Image
|
||||
|
||||
import gradio as gr
|
||||
from anthropic import APIResponse
|
||||
from anthropic.types import TextBlock
|
||||
from anthropic.types.beta import BetaMessage, BetaTextBlock, BetaToolUseBlock
|
||||
from anthropic.types.tool_use_block import ToolUseBlock
|
||||
|
||||
from screeninfo import get_monitors
|
||||
|
||||
screens = get_monitors()
|
||||
print(screens)
|
||||
from loop import (
|
||||
PROVIDER_TO_DEFAULT_MODEL_NAME,
|
||||
APIProvider,
|
||||
sampling_loop_sync,
|
||||
)
|
||||
|
||||
from tools import ToolResult
|
||||
from tools.computer import get_screen_details
|
||||
SCREEN_NAMES, SELECTED_SCREEN_INDEX = get_screen_details()
|
||||
# SELECTED_SCREEN_INDEX = None
|
||||
# SCREEN_NAMES = None
|
||||
|
||||
CONFIG_DIR = Path("~/.anthropic").expanduser()
|
||||
API_KEY_FILE = CONFIG_DIR / "api_key"
|
||||
|
||||
INTRO_TEXT = '''
|
||||
🚀🤖✨ It's Play Time!
|
||||
|
||||
Welcome to the OmniParser+X Demo! X = [GPT-4o/4o-mini, Claude, Phi, Llama]. Let OmniParser turn your general purpose vision-langauge model to an AI agent. Type a message to play with your beloved assistant.
|
||||
'''
|
||||
|
||||
class Sender(StrEnum):
|
||||
USER = "user"
|
||||
BOT = "assistant"
|
||||
TOOL = "tool"
|
||||
|
||||
|
||||
def setup_state(state):
|
||||
|
||||
if "messages" not in state:
|
||||
state["messages"] = []
|
||||
if "model" not in state:
|
||||
# state["model"] = "gpt-4o + ShowUI"
|
||||
state["model"] = "omniparser + gpt-4o"
|
||||
# _reset_model(state)
|
||||
if "provider" not in state:
|
||||
if state["model"] == "qwen2vl + ShowUI":
|
||||
state["provider"] = "DashScopeAPI"
|
||||
elif state["model"] == "gpt-4o + ShowUI":
|
||||
state["provider"] = "openai"
|
||||
else:
|
||||
state["provider"] = os.getenv("API_PROVIDER", "anthropic") or "anthropic"
|
||||
|
||||
if "provider_radio" not in state:
|
||||
state["provider_radio"] = state["provider"]
|
||||
|
||||
if "openai_api_key" not in state: # Fetch API keys from environment variables
|
||||
state["openai_api_key"] = os.getenv("OPENAI_API_KEY", "")
|
||||
if "anthropic_api_key" not in state:
|
||||
state["anthropic_api_key"] = os.getenv("ANTHROPIC_API_KEY", "")
|
||||
if "qwen_api_key" not in state:
|
||||
state["qwen_api_key"] = os.getenv("QWEN_API_KEY", "")
|
||||
|
||||
# Set the initial api_key based on the provider
|
||||
if "api_key" not in state:
|
||||
if state["provider"] == "openai":
|
||||
state["api_key"] = state["openai_api_key"]
|
||||
elif state["provider"] == "anthropic":
|
||||
state["api_key"] = state["anthropic_api_key"]
|
||||
elif state["provider"] == "qwen":
|
||||
state["api_key"] = state["qwen_api_key"]
|
||||
else:
|
||||
state["api_key"] = ""
|
||||
# print(f"state['api_key']: {state['api_key']}")
|
||||
if not state["api_key"]:
|
||||
print("API key not found. Please set it in the environment or paste in textbox.")
|
||||
|
||||
if "selected_screen" not in state:
|
||||
state['selected_screen'] = SELECTED_SCREEN_INDEX if SCREEN_NAMES else 0
|
||||
|
||||
if "auth_validated" not in state:
|
||||
state["auth_validated"] = False
|
||||
if "responses" not in state:
|
||||
state["responses"] = {}
|
||||
if "tools" not in state:
|
||||
state["tools"] = {}
|
||||
if "only_n_most_recent_images" not in state:
|
||||
state["only_n_most_recent_images"] = 10 # 10
|
||||
if "custom_system_prompt" not in state:
|
||||
state["custom_system_prompt"] = load_from_storage("system_prompt") or ""
|
||||
# remove if want to use default system prompt
|
||||
device_os_name = "Windows" if platform.system() == "Windows" else "Mac" if platform.system() == "Darwin" else "Linux"
|
||||
state["custom_system_prompt"] += f"\n\nNOTE: you are operating a {device_os_name} machine"
|
||||
if "hide_images" not in state:
|
||||
state["hide_images"] = False
|
||||
if 'chatbot_messages' not in state:
|
||||
state['chatbot_messages'] = []
|
||||
|
||||
|
||||
|
||||
def _reset_model(state):
|
||||
state["model"] = PROVIDER_TO_DEFAULT_MODEL_NAME[cast(APIProvider, state["provider"])]
|
||||
|
||||
|
||||
async def main(state):
|
||||
"""Render loop for Gradio"""
|
||||
setup_state(state)
|
||||
return "Setup completed"
|
||||
|
||||
|
||||
def validate_auth(provider: APIProvider, api_key: str | None):
|
||||
if provider == APIProvider.ANTHROPIC:
|
||||
if not api_key:
|
||||
return "Enter your Anthropic API key to continue."
|
||||
if provider == APIProvider.BEDROCK:
|
||||
import boto3
|
||||
|
||||
if not boto3.Session().get_credentials():
|
||||
return "You must have AWS credentials set up to use the Bedrock API."
|
||||
if provider == APIProvider.VERTEX:
|
||||
import google.auth
|
||||
from google.auth.exceptions import DefaultCredentialsError
|
||||
|
||||
if not os.environ.get("CLOUD_ML_REGION"):
|
||||
return "Set the CLOUD_ML_REGION environment variable to use the Vertex API."
|
||||
try:
|
||||
google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
|
||||
except DefaultCredentialsError:
|
||||
return "Your google cloud credentials are not set up correctly."
|
||||
|
||||
|
||||
def load_from_storage(filename: str) -> str | None:
|
||||
"""Load data from a file in the storage directory."""
|
||||
try:
|
||||
file_path = CONFIG_DIR / filename
|
||||
if file_path.exists():
|
||||
data = file_path.read_text().strip()
|
||||
if data:
|
||||
return data
|
||||
except Exception as e:
|
||||
print(f"Debug: Error loading {filename}: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def save_to_storage(filename: str, data: str) -> None:
|
||||
"""Save data to a file in the storage directory."""
|
||||
try:
|
||||
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
file_path = CONFIG_DIR / filename
|
||||
file_path.write_text(data)
|
||||
# Ensure only user can read/write the file
|
||||
file_path.chmod(0o600)
|
||||
except Exception as e:
|
||||
print(f"Debug: Error saving {filename}: {e}")
|
||||
|
||||
|
||||
def _api_response_callback(response: APIResponse[BetaMessage], response_state: dict):
|
||||
response_id = datetime.now().isoformat()
|
||||
response_state[response_id] = response
|
||||
|
||||
|
||||
def _tool_output_callback(tool_output: ToolResult, tool_id: str, tool_state: dict):
|
||||
tool_state[tool_id] = tool_output
|
||||
|
||||
|
||||
def chatbot_output_callback(message, chatbot_state, hide_images=False, sender="bot"):
|
||||
|
||||
def _render_message(message: str | BetaTextBlock | BetaToolUseBlock | ToolResult, hide_images=False):
|
||||
|
||||
print(f"_render_message: {str(message)[:100]}")
|
||||
|
||||
if isinstance(message, str):
|
||||
return message
|
||||
|
||||
is_tool_result = not isinstance(message, str) and (
|
||||
isinstance(message, ToolResult)
|
||||
or message.__class__.__name__ == "ToolResult"
|
||||
or message.__class__.__name__ == "CLIResult"
|
||||
)
|
||||
if not message or (
|
||||
is_tool_result
|
||||
and hide_images
|
||||
and not hasattr(message, "error")
|
||||
and not hasattr(message, "output")
|
||||
): # return None if hide_images is True
|
||||
return
|
||||
# render tool result
|
||||
if is_tool_result:
|
||||
message = cast(ToolResult, message)
|
||||
if message.output:
|
||||
return message.output
|
||||
if message.error:
|
||||
return f"Error: {message.error}"
|
||||
if message.base64_image and not hide_images:
|
||||
# somehow can't display via gr.Image
|
||||
# image_data = base64.b64decode(message.base64_image)
|
||||
# return gr.Image(value=Image.open(io.BytesIO(image_data)))
|
||||
return f'<img src="data:image/png;base64,{message.base64_image}">'
|
||||
|
||||
elif isinstance(message, BetaTextBlock) or isinstance(message, TextBlock):
|
||||
return f"Analysis: {message.text}"
|
||||
elif isinstance(message, BetaToolUseBlock) or isinstance(message, ToolUseBlock):
|
||||
# return f"Tool Use: {message.name}\nInput: {message.input}"
|
||||
return f"Next I will perform the following action: {message.input}"
|
||||
else:
|
||||
return message
|
||||
|
||||
def _truncate_string(s, max_length=500):
|
||||
"""Truncate long strings for concise printing."""
|
||||
if isinstance(s, str) and len(s) > max_length:
|
||||
return s[:max_length] + "..."
|
||||
return s
|
||||
# processing Anthropic messages
|
||||
message = _render_message(message, hide_images)
|
||||
|
||||
if sender == "bot":
|
||||
chatbot_state.append((None, message))
|
||||
else:
|
||||
chatbot_state.append((message, None))
|
||||
|
||||
# Create a concise version of the chatbot state for printing
|
||||
concise_state = [(_truncate_string(user_msg), _truncate_string(bot_msg))
|
||||
for user_msg, bot_msg in chatbot_state]
|
||||
# print(f"chatbot_output_callback chatbot_state: {concise_state} (truncated)")
|
||||
|
||||
def process_input(user_input, state):
|
||||
|
||||
setup_state(state)
|
||||
|
||||
# Append the user message to state["messages"]
|
||||
if state["model"] == "gpt-4o + ShowUI" or state["model"] == "qwen2vl + ShowUI":
|
||||
state["messages"].append(
|
||||
{
|
||||
"role": "user",
|
||||
"content": [TextBlock(type="text", text=user_input)],
|
||||
}
|
||||
)
|
||||
elif state["model"] == "claude-3-5-sonnet-20241022":
|
||||
state["messages"].append(
|
||||
{
|
||||
"role": Sender.USER,
|
||||
"content": [TextBlock(type="text", text=user_input)],
|
||||
}
|
||||
)
|
||||
elif state["model"] == "omniparser + gpt-4o" or state["model"] == "omniparser + phi35v":
|
||||
state["messages"].append(
|
||||
{
|
||||
"role": "user",
|
||||
"content": [TextBlock(type="text", text=user_input)],
|
||||
}
|
||||
)
|
||||
|
||||
# Append the user's message to chatbot_messages with None for the assistant's reply
|
||||
state['chatbot_messages'].append((user_input, None))
|
||||
yield state['chatbot_messages'] # Yield to update the chatbot UI with the user's message
|
||||
|
||||
# Run sampling_loop_sync with the chatbot_output_callback
|
||||
for loop_msg in sampling_loop_sync(
|
||||
system_prompt_suffix=state["custom_system_prompt"],
|
||||
model=state["model"],
|
||||
provider=state["provider"],
|
||||
messages=state["messages"],
|
||||
output_callback=partial(chatbot_output_callback, chatbot_state=state['chatbot_messages'], hide_images=state["hide_images"]),
|
||||
tool_output_callback=partial(_tool_output_callback, tool_state=state["tools"]),
|
||||
api_response_callback=partial(_api_response_callback, response_state=state["responses"]),
|
||||
api_key=state["api_key"],
|
||||
only_n_most_recent_images=state["only_n_most_recent_images"],
|
||||
selected_screen=state['selected_screen']
|
||||
):
|
||||
if loop_msg is None:
|
||||
yield state['chatbot_messages']
|
||||
print("End of task. Close the loop.")
|
||||
break
|
||||
|
||||
yield state['chatbot_messages'] # Yield the updated chatbot_messages to update the chatbot UI
|
||||
|
||||
|
||||
# with gr.Blocks(theme=gr.themes.Default()) as demo:
|
||||
with gr.Blocks(theme='YTheme/Minecraft') as demo:
|
||||
state = gr.State({}) # Use Gradio's state management
|
||||
|
||||
setup_state(state.value) # Initialize the state
|
||||
|
||||
# Retrieve screen details
|
||||
gr.Markdown("# OmniParser + ✖️ Demo")
|
||||
|
||||
if not os.getenv("HIDE_WARNING", False):
|
||||
gr.Markdown(INTRO_TEXT)
|
||||
|
||||
with gr.Accordion("Settings", open=True):
|
||||
with gr.Row():
|
||||
with gr.Column():
|
||||
model = gr.Dropdown(
|
||||
label="Model",
|
||||
choices=["omniparser + gpt-4o", "omniparser + phi35v", "claude-3-5-sonnet-20241022"],
|
||||
value="omniparser + gpt-4o", # Set to one of the choices
|
||||
interactive=True,
|
||||
)
|
||||
with gr.Column():
|
||||
provider = gr.Dropdown(
|
||||
label="API Provider",
|
||||
choices=[option.value for option in APIProvider],
|
||||
value="openai",
|
||||
interactive=False,
|
||||
)
|
||||
with gr.Column():
|
||||
api_key = gr.Textbox(
|
||||
label="API Key",
|
||||
type="password",
|
||||
value=state.value.get("api_key", ""),
|
||||
placeholder="Paste your API key here",
|
||||
interactive=True,
|
||||
)
|
||||
with gr.Column():
|
||||
custom_prompt = gr.Textbox(
|
||||
label="System Prompt Suffix",
|
||||
value="",
|
||||
interactive=True,
|
||||
)
|
||||
with gr.Column():
|
||||
screen_options, primary_index = get_screen_details()
|
||||
SCREEN_NAMES = screen_options
|
||||
SELECTED_SCREEN_INDEX = primary_index
|
||||
screen_selector = gr.Dropdown(
|
||||
label="Select Screen",
|
||||
choices=screen_options,
|
||||
value=screen_options[primary_index] if screen_options else None,
|
||||
interactive=True,
|
||||
)
|
||||
with gr.Column():
|
||||
only_n_images = gr.Slider(
|
||||
label="N most recent screenshots",
|
||||
minimum=0,
|
||||
maximum=10,
|
||||
step=1,
|
||||
value=2,
|
||||
interactive=True,
|
||||
)
|
||||
# hide_images = gr.Checkbox(label="Hide screenshots", value=False)
|
||||
|
||||
# Define the merged dictionary with task mappings
|
||||
# merged_dict = json.load(open("examples/ootb_examples.json", "r"))
|
||||
merged_dict = {}
|
||||
|
||||
def update_only_n_images(only_n_images_value, state):
|
||||
state["only_n_most_recent_images"] = only_n_images_value
|
||||
|
||||
# Callback to update the second dropdown based on the first selection
|
||||
def update_second_menu(selected_category):
|
||||
return gr.update(choices=list(merged_dict.get(selected_category, {}).keys()))
|
||||
|
||||
# Callback to update the third dropdown based on the second selection
|
||||
def update_third_menu(selected_category, selected_option):
|
||||
return gr.update(choices=list(merged_dict.get(selected_category, {}).get(selected_option, {}).keys()))
|
||||
|
||||
# Callback to update the textbox based on the third selection
|
||||
def update_textbox(selected_category, selected_option, selected_task):
|
||||
task_data = merged_dict.get(selected_category, {}).get(selected_option, {}).get(selected_task, {})
|
||||
prompt = task_data.get("prompt", "")
|
||||
preview_image = task_data.get("initial_state", "")
|
||||
task_hint = "Task Hint: " + task_data.get("hint", "")
|
||||
return prompt, preview_image, task_hint
|
||||
|
||||
# Function to update the global variable when the dropdown changes
|
||||
def update_selected_screen(selected_screen_name, state):
|
||||
global SCREEN_NAMES
|
||||
global SELECTED_SCREEN_INDEX
|
||||
SELECTED_SCREEN_INDEX = SCREEN_NAMES.index(selected_screen_name)
|
||||
print(f"Selected screen updated to: {SELECTED_SCREEN_INDEX}")
|
||||
state['selected_screen'] = SELECTED_SCREEN_INDEX
|
||||
|
||||
def update_model(model_selection, state):
|
||||
state["model"] = model_selection
|
||||
print(f"Model updated to: {state['model']}")
|
||||
|
||||
if model_selection == "claude-3-5-sonnet-20241022":
|
||||
# Provider can be any of the current choices except 'openai'
|
||||
provider_choices = [option.value for option in APIProvider if option.value != "openai"]
|
||||
provider_value = "anthropic" # Set default to 'anthropic'
|
||||
provider_interactive = True
|
||||
api_key_placeholder = "claude API key"
|
||||
elif model_selection == "omniparser + gpt-4o" or model_selection == "omniparser + phi35v":
|
||||
# Provider can be any of the current choices except 'openai'
|
||||
provider_choices = ["openai"]
|
||||
provider_value = "openai"
|
||||
provider_interactive = False
|
||||
api_key_placeholder = "openai API key"
|
||||
else:
|
||||
# Default case
|
||||
provider_choices = [option.value for option in APIProvider]
|
||||
provider_value = state.get("provider", provider_choices[0])
|
||||
provider_interactive = True
|
||||
api_key_placeholder = ""
|
||||
|
||||
# Update the provider in state
|
||||
state["provider"] = provider_value
|
||||
|
||||
# Update api_key in state based on the provider
|
||||
if provider_value == "openai":
|
||||
state["api_key"] = state.get("openai_api_key", "")
|
||||
elif provider_value == "anthropic":
|
||||
state["api_key"] = state.get("anthropic_api_key", "")
|
||||
elif provider_value == "qwen":
|
||||
state["api_key"] = state.get("qwen_api_key", "")
|
||||
else:
|
||||
state["api_key"] = ""
|
||||
|
||||
# Use gr.update() instead of gr.Dropdown.update()
|
||||
provider_update = gr.update(
|
||||
choices=provider_choices,
|
||||
value=provider_value,
|
||||
interactive=provider_interactive
|
||||
)
|
||||
|
||||
# Update the API Key textbox
|
||||
api_key_update = gr.update(
|
||||
placeholder=api_key_placeholder,
|
||||
value=state["api_key"]
|
||||
)
|
||||
|
||||
return provider_update, api_key_update
|
||||
|
||||
def update_api_key_placeholder(provider_value, model_selection):
|
||||
if model_selection == "claude-3-5-sonnet-20241022":
|
||||
if provider_value == "anthropic":
|
||||
return gr.update(placeholder="anthropic API key")
|
||||
elif provider_value == "bedrock":
|
||||
return gr.update(placeholder="bedrock API key")
|
||||
elif provider_value == "vertex":
|
||||
return gr.update(placeholder="vertex API key")
|
||||
else:
|
||||
return gr.update(placeholder="")
|
||||
elif model_selection == "gpt-4o + ShowUI":
|
||||
return gr.update(placeholder="openai API key")
|
||||
else:
|
||||
return gr.update(placeholder="")
|
||||
|
||||
def update_system_prompt_suffix(system_prompt_suffix, state):
|
||||
state["custom_system_prompt"] = system_prompt_suffix
|
||||
|
||||
|
||||
api_key.change(fn=lambda key: save_to_storage(API_KEY_FILE, key), inputs=api_key)
|
||||
|
||||
with gr.Row():
|
||||
# submit_button = gr.Button("Submit") # Add submit button
|
||||
with gr.Column(scale=8):
|
||||
chat_input = gr.Textbox(show_label=False, placeholder="Type a message to send to Computer Use OOTB...", container=False)
|
||||
with gr.Column(scale=1, min_width=50):
|
||||
submit_button = gr.Button(value="Send", variant="primary")
|
||||
|
||||
chatbot = gr.Chatbot(label="Chatbot History", autoscroll=True, height=580)
|
||||
|
||||
model.change(fn=update_model, inputs=[model, state], outputs=[provider, api_key])
|
||||
provider.change(fn=update_api_key_placeholder, inputs=[provider, model], outputs=api_key)
|
||||
screen_selector.change(fn=update_selected_screen, inputs=[screen_selector, state], outputs=None)
|
||||
only_n_images.change(fn=update_only_n_images, inputs=[only_n_images, state], outputs=None)
|
||||
|
||||
|
||||
# chat_input.submit(process_input, [chat_input, state], chatbot)
|
||||
submit_button.click(process_input, [chat_input, state], chatbot)
|
||||
|
||||
demo.launch(share=True, server_port=7861, server_name='0.0.0.0') # TODO: allowed_paths
|
||||
"""
|
||||
python app.py --windows_host_url localhost:8006 --omniparser_server_url localhost:8000
|
||||
"""
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from functools import partial
|
||||
from pathlib import Path
|
||||
from typing import cast
|
||||
import argparse
|
||||
import gradio as gr
|
||||
from anthropic import APIResponse
|
||||
from anthropic.types import TextBlock
|
||||
from anthropic.types.beta import BetaMessage, BetaTextBlock, BetaToolUseBlock
|
||||
from anthropic.types.tool_use_block import ToolUseBlock
|
||||
from loop import (
|
||||
APIProvider,
|
||||
sampling_loop_sync,
|
||||
)
|
||||
from tools import ToolResult
|
||||
import requests
|
||||
from requests.exceptions import RequestException
|
||||
import base64
|
||||
|
||||
CONFIG_DIR = Path("~/.anthropic").expanduser()
|
||||
API_KEY_FILE = CONFIG_DIR / "api_key"
|
||||
|
||||
INTRO_TEXT = '''
|
||||
OmniParser lets you turn any vision-langauge model into an AI agent. We currently support OpenAI (4o/o1/o3-mini), DeepSeek (R1), Qwen (2.5VL) or Anthropic Computer Use (Sonnet).
|
||||
|
||||
Type a message and press submit to start OmniTool. Press stop to pause, and press the trash icon in the chat to clear the message history.
|
||||
'''
|
||||
|
||||
def parse_arguments():
|
||||
|
||||
parser = argparse.ArgumentParser(description="Gradio App")
|
||||
parser.add_argument("--windows_host_url", type=str, default='localhost:8006')
|
||||
parser.add_argument("--omniparser_server_url", type=str, default="localhost:8000")
|
||||
return parser.parse_args()
|
||||
args = parse_arguments()
|
||||
|
||||
|
||||
class Sender(StrEnum):
|
||||
USER = "user"
|
||||
BOT = "assistant"
|
||||
TOOL = "tool"
|
||||
|
||||
|
||||
def setup_state(state):
|
||||
if "messages" not in state:
|
||||
state["messages"] = []
|
||||
if "model" not in state:
|
||||
state["model"] = "omniparser + gpt-4o"
|
||||
if "provider" not in state:
|
||||
state["provider"] = "openai"
|
||||
if "openai_api_key" not in state: # Fetch API keys from environment variables
|
||||
state["openai_api_key"] = os.getenv("OPENAI_API_KEY", "")
|
||||
if "anthropic_api_key" not in state:
|
||||
state["anthropic_api_key"] = os.getenv("ANTHROPIC_API_KEY", "")
|
||||
if "api_key" not in state:
|
||||
state["api_key"] = ""
|
||||
if "auth_validated" not in state:
|
||||
state["auth_validated"] = False
|
||||
if "responses" not in state:
|
||||
state["responses"] = {}
|
||||
if "tools" not in state:
|
||||
state["tools"] = {}
|
||||
if "only_n_most_recent_images" not in state:
|
||||
state["only_n_most_recent_images"] = 2
|
||||
if 'chatbot_messages' not in state:
|
||||
state['chatbot_messages'] = []
|
||||
if 'stop' not in state:
|
||||
state['stop'] = False
|
||||
|
||||
async def main(state):
|
||||
"""Render loop for Gradio"""
|
||||
setup_state(state)
|
||||
return "Setup completed"
|
||||
|
||||
def validate_auth(provider: APIProvider, api_key: str | None):
|
||||
if provider == APIProvider.ANTHROPIC:
|
||||
if not api_key:
|
||||
return "Enter your Anthropic API key to continue."
|
||||
if provider == APIProvider.BEDROCK:
|
||||
import boto3
|
||||
|
||||
if not boto3.Session().get_credentials():
|
||||
return "You must have AWS credentials set up to use the Bedrock API."
|
||||
if provider == APIProvider.VERTEX:
|
||||
import google.auth
|
||||
from google.auth.exceptions import DefaultCredentialsError
|
||||
|
||||
if not os.environ.get("CLOUD_ML_REGION"):
|
||||
return "Set the CLOUD_ML_REGION environment variable to use the Vertex API."
|
||||
try:
|
||||
google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
|
||||
except DefaultCredentialsError:
|
||||
return "Your google cloud credentials are not set up correctly."
|
||||
|
||||
def load_from_storage(filename: str) -> str | None:
|
||||
"""Load data from a file in the storage directory."""
|
||||
try:
|
||||
file_path = CONFIG_DIR / filename
|
||||
if file_path.exists():
|
||||
data = file_path.read_text().strip()
|
||||
if data:
|
||||
return data
|
||||
except Exception as e:
|
||||
print(f"Debug: Error loading {filename}: {e}")
|
||||
return None
|
||||
|
||||
def save_to_storage(filename: str, data: str) -> None:
|
||||
"""Save data to a file in the storage directory."""
|
||||
try:
|
||||
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
file_path = CONFIG_DIR / filename
|
||||
file_path.write_text(data)
|
||||
# Ensure only user can read/write the file
|
||||
file_path.chmod(0o600)
|
||||
except Exception as e:
|
||||
print(f"Debug: Error saving {filename}: {e}")
|
||||
|
||||
def _api_response_callback(response: APIResponse[BetaMessage], response_state: dict):
|
||||
response_id = datetime.now().isoformat()
|
||||
response_state[response_id] = response
|
||||
|
||||
def _tool_output_callback(tool_output: ToolResult, tool_id: str, tool_state: dict):
|
||||
tool_state[tool_id] = tool_output
|
||||
|
||||
def chatbot_output_callback(message, chatbot_state, hide_images=False, sender="bot"):
|
||||
def _render_message(message: str | BetaTextBlock | BetaToolUseBlock | ToolResult, hide_images=False):
|
||||
|
||||
print(f"_render_message: {str(message)[:100]}")
|
||||
|
||||
if isinstance(message, str):
|
||||
return message
|
||||
|
||||
is_tool_result = not isinstance(message, str) and (
|
||||
isinstance(message, ToolResult)
|
||||
or message.__class__.__name__ == "ToolResult"
|
||||
)
|
||||
if not message or (
|
||||
is_tool_result
|
||||
and hide_images
|
||||
and not hasattr(message, "error")
|
||||
and not hasattr(message, "output")
|
||||
): # return None if hide_images is True
|
||||
return
|
||||
# render tool result
|
||||
if is_tool_result:
|
||||
message = cast(ToolResult, message)
|
||||
if message.output:
|
||||
return message.output
|
||||
if message.error:
|
||||
return f"Error: {message.error}"
|
||||
if message.base64_image and not hide_images:
|
||||
# somehow can't display via gr.Image
|
||||
# image_data = base64.b64decode(message.base64_image)
|
||||
# return gr.Image(value=Image.open(io.BytesIO(image_data)))
|
||||
return f'<img src="data:image/png;base64,{message.base64_image}">'
|
||||
|
||||
elif isinstance(message, BetaTextBlock) or isinstance(message, TextBlock):
|
||||
return f"Analysis: {message.text}"
|
||||
elif isinstance(message, BetaToolUseBlock) or isinstance(message, ToolUseBlock):
|
||||
# return f"Tool Use: {message.name}\nInput: {message.input}"
|
||||
return f"Next I will perform the following action: {message.input}"
|
||||
else:
|
||||
return message
|
||||
|
||||
def _truncate_string(s, max_length=500):
|
||||
"""Truncate long strings for concise printing."""
|
||||
if isinstance(s, str) and len(s) > max_length:
|
||||
return s[:max_length] + "..."
|
||||
return s
|
||||
# processing Anthropic messages
|
||||
message = _render_message(message, hide_images)
|
||||
|
||||
if sender == "bot":
|
||||
chatbot_state.append((None, message))
|
||||
else:
|
||||
chatbot_state.append((message, None))
|
||||
|
||||
# Create a concise version of the chatbot state for printing
|
||||
concise_state = [(_truncate_string(user_msg), _truncate_string(bot_msg))
|
||||
for user_msg, bot_msg in chatbot_state]
|
||||
# print(f"chatbot_output_callback chatbot_state: {concise_state} (truncated)")
|
||||
|
||||
def valid_params(user_input, state):
|
||||
"""Validate all requirements and return a list of error messages."""
|
||||
errors = []
|
||||
|
||||
for server_name, url in [('Windows Host', 'localhost:5000'), ('OmniParser Server', args.omniparser_server_url)]:
|
||||
try:
|
||||
url = f'http://{url}/probe'
|
||||
response = requests.get(url, timeout=3)
|
||||
if response.status_code != 200:
|
||||
errors.append(f"{server_name} is not responding")
|
||||
except RequestException as e:
|
||||
errors.append(f"{server_name} is not responding")
|
||||
|
||||
if not state["api_key"].strip():
|
||||
errors.append("LLM API Key is not set")
|
||||
|
||||
if not user_input:
|
||||
errors.append("no computer use request provided")
|
||||
|
||||
return errors
|
||||
|
||||
def process_input(user_input, state):
|
||||
# Reset the stop flag
|
||||
if state["stop"]:
|
||||
state["stop"] = False
|
||||
|
||||
errors = valid_params(user_input, state)
|
||||
if errors:
|
||||
raise gr.Error("Validation errors: " + ", ".join(errors))
|
||||
|
||||
# Append the user message to state["messages"]
|
||||
state["messages"].append(
|
||||
{
|
||||
"role": Sender.USER,
|
||||
"content": [TextBlock(type="text", text=user_input)],
|
||||
}
|
||||
)
|
||||
|
||||
# Append the user's message to chatbot_messages with None for the assistant's reply
|
||||
state['chatbot_messages'].append((user_input, None))
|
||||
yield state['chatbot_messages'] # Yield to update the chatbot UI with the user's message
|
||||
|
||||
print("state")
|
||||
print(state)
|
||||
|
||||
# Run sampling_loop_sync with the chatbot_output_callback
|
||||
for loop_msg in sampling_loop_sync(
|
||||
model=state["model"],
|
||||
provider=state["provider"],
|
||||
messages=state["messages"],
|
||||
output_callback=partial(chatbot_output_callback, chatbot_state=state['chatbot_messages'], hide_images=False),
|
||||
tool_output_callback=partial(_tool_output_callback, tool_state=state["tools"]),
|
||||
api_response_callback=partial(_api_response_callback, response_state=state["responses"]),
|
||||
api_key=state["api_key"],
|
||||
only_n_most_recent_images=state["only_n_most_recent_images"],
|
||||
max_tokens=16384,
|
||||
omniparser_url=args.omniparser_server_url
|
||||
):
|
||||
if loop_msg is None or state.get("stop"):
|
||||
yield state['chatbot_messages']
|
||||
print("End of task. Close the loop.")
|
||||
break
|
||||
|
||||
yield state['chatbot_messages'] # Yield the updated chatbot_messages to update the chatbot UI
|
||||
|
||||
def stop_app(state):
|
||||
state["stop"] = True
|
||||
return "App stopped"
|
||||
|
||||
def get_header_image_base64():
|
||||
try:
|
||||
# Get the absolute path to the image relative to this script
|
||||
script_dir = Path(__file__).parent
|
||||
image_path = script_dir.parent.parent / "imgs" / "header_bar_thin.png"
|
||||
|
||||
with open(image_path, "rb") as image_file:
|
||||
encoded_string = base64.b64encode(image_file.read()).decode()
|
||||
return f'data:image/png;base64,{encoded_string}'
|
||||
except Exception as e:
|
||||
print(f"Failed to load header image: {e}")
|
||||
return None
|
||||
|
||||
with gr.Blocks(theme=gr.themes.Default()) as demo:
|
||||
gr.HTML("""
|
||||
<style>
|
||||
.no-padding {
|
||||
padding: 0 !important;
|
||||
}
|
||||
.no-padding > div {
|
||||
padding: 0 !important;
|
||||
}
|
||||
</style>
|
||||
""")
|
||||
state = gr.State({})
|
||||
|
||||
setup_state(state.value)
|
||||
|
||||
header_image = get_header_image_base64()
|
||||
if header_image:
|
||||
gr.HTML(f'<img src="{header_image}" alt="OmniTool Header" width="100%">', elem_classes="no-padding")
|
||||
gr.HTML('<h1 style="text-align: center; font-weight: normal;">Omni<span style="font-weight: bold;">Tool</span></h1>')
|
||||
else:
|
||||
gr.Markdown("# OmniTool")
|
||||
|
||||
if not os.getenv("HIDE_WARNING", False):
|
||||
gr.Markdown(INTRO_TEXT)
|
||||
|
||||
with gr.Accordion("Settings", open=True):
|
||||
with gr.Row():
|
||||
with gr.Column():
|
||||
model = gr.Dropdown(
|
||||
label="Model",
|
||||
choices=["omniparser + gpt-4o", "omniparser + o1", "omniparser + o3-mini", "omniparser + R1", "omniparser + qwen2.5vl", "claude-3-5-sonnet-20241022"],
|
||||
value="omniparser + gpt-4o",
|
||||
interactive=True,
|
||||
)
|
||||
with gr.Column():
|
||||
only_n_images = gr.Slider(
|
||||
label="N most recent screenshots",
|
||||
minimum=0,
|
||||
maximum=10,
|
||||
step=1,
|
||||
value=2,
|
||||
interactive=True
|
||||
)
|
||||
with gr.Row():
|
||||
with gr.Column(1):
|
||||
provider = gr.Dropdown(
|
||||
label="API Provider",
|
||||
choices=[option.value for option in APIProvider],
|
||||
value="openai",
|
||||
interactive=False,
|
||||
)
|
||||
with gr.Column(2):
|
||||
api_key = gr.Textbox(
|
||||
label="API Key",
|
||||
type="password",
|
||||
value=state.value.get("api_key", ""),
|
||||
placeholder="Paste your API key here",
|
||||
interactive=True,
|
||||
)
|
||||
|
||||
with gr.Row():
|
||||
with gr.Column(scale=8):
|
||||
chat_input = gr.Textbox(show_label=False, placeholder="Type a message to send to Omniparser + X ...", container=False)
|
||||
with gr.Column(scale=1, min_width=50):
|
||||
submit_button = gr.Button(value="Send", variant="primary")
|
||||
with gr.Column(scale=1, min_width=50):
|
||||
stop_button = gr.Button(value="Stop", variant="secondary")
|
||||
|
||||
with gr.Row():
|
||||
with gr.Column(scale=1):
|
||||
chatbot = gr.Chatbot(label="Chatbot History", autoscroll=True, height=580)
|
||||
with gr.Column(scale=3):
|
||||
iframe = gr.HTML(
|
||||
f'<iframe src="http://{args.windows_host_url}/vnc.html?view_only=1&autoconnect=1&resize=scale" width="100%" height="580" allow="fullscreen"></iframe>',
|
||||
container=False,
|
||||
elem_classes="no-padding"
|
||||
)
|
||||
|
||||
def update_model(model_selection, state):
|
||||
state["model"] = model_selection
|
||||
print(f"Model updated to: {state['model']}")
|
||||
|
||||
if model_selection == "claude-3-5-sonnet-20241022":
|
||||
provider_choices = [option.value for option in APIProvider if option.value != "openai"]
|
||||
elif model_selection in set(["omniparser + gpt-4o", "omniparser + o1", "omniparser + o3-mini"]):
|
||||
provider_choices = ["openai"]
|
||||
elif model_selection == "omniparser + R1":
|
||||
provider_choices = ["groq"]
|
||||
elif model_selection == "omniparser + qwen2.5vl":
|
||||
provider_choices = ["dashscope"]
|
||||
else:
|
||||
provider_choices = [option.value for option in APIProvider]
|
||||
default_provider_value = provider_choices[0]
|
||||
|
||||
provider_interactive = len(provider_choices) > 1
|
||||
api_key_placeholder = f"{default_provider_value.title()} API Key"
|
||||
|
||||
# Update state
|
||||
state["provider"] = default_provider_value
|
||||
state["api_key"] = state.get(f"{default_provider_value}_api_key", "")
|
||||
|
||||
# Calls to update other components UI
|
||||
provider_update = gr.update(
|
||||
choices=provider_choices,
|
||||
value=default_provider_value,
|
||||
interactive=provider_interactive
|
||||
)
|
||||
api_key_update = gr.update(
|
||||
placeholder=api_key_placeholder,
|
||||
value=state["api_key"]
|
||||
)
|
||||
|
||||
return provider_update, api_key_update
|
||||
|
||||
def update_only_n_images(only_n_images_value, state):
|
||||
state["only_n_most_recent_images"] = only_n_images_value
|
||||
|
||||
def update_provider(provider_value, state):
|
||||
# Update state
|
||||
state["provider"] = provider_value
|
||||
state["api_key"] = state.get(f"{provider_value}_api_key", "")
|
||||
|
||||
# Calls to update other components UI
|
||||
api_key_update = gr.update(
|
||||
placeholder=f"{provider_value.title()} API Key",
|
||||
value=state["api_key"]
|
||||
)
|
||||
return api_key_update
|
||||
|
||||
def update_api_key(api_key_value, state):
|
||||
state["api_key"] = api_key_value
|
||||
state[f'{state["provider"]}_api_key'] = api_key_value
|
||||
|
||||
def clear_chat(state):
|
||||
# Reset message-related state
|
||||
state["messages"] = []
|
||||
state["responses"] = {}
|
||||
state["tools"] = {}
|
||||
state['chatbot_messages'] = []
|
||||
return state['chatbot_messages']
|
||||
|
||||
model.change(fn=update_model, inputs=[model, state], outputs=[provider, api_key])
|
||||
only_n_images.change(fn=update_only_n_images, inputs=[only_n_images, state], outputs=None)
|
||||
provider.change(fn=update_provider, inputs=[provider, state], outputs=api_key)
|
||||
api_key.change(fn=update_api_key, inputs=[api_key, state], outputs=None)
|
||||
chatbot.clear(fn=clear_chat, inputs=[state], outputs=[chatbot])
|
||||
|
||||
submit_button.click(process_input, [chat_input, state], chatbot)
|
||||
stop_button.click(stop_app, [state], None)
|
||||
|
||||
if __name__ == "__main__":
|
||||
demo.launch(server_name="0.0.0.0", server_port=7888)
|
||||
@@ -1,136 +1,132 @@
|
||||
import asyncio
|
||||
from typing import Any, Dict, cast
|
||||
from collections.abc import Callable
|
||||
from anthropic.types.beta import (
|
||||
BetaContentBlock,
|
||||
BetaContentBlockParam,
|
||||
BetaImageBlockParam,
|
||||
BetaMessage,
|
||||
BetaMessageParam,
|
||||
BetaTextBlockParam,
|
||||
BetaToolResultBlockParam,
|
||||
)
|
||||
from anthropic.types import TextBlock
|
||||
from anthropic.types.beta import BetaMessage, BetaTextBlock, BetaToolUseBlock
|
||||
from tools import BashTool, ComputerTool, EditTool, ToolCollection, ToolResult
|
||||
|
||||
|
||||
class AnthropicExecutor:
|
||||
def __init__(
|
||||
self,
|
||||
output_callback: Callable[[BetaContentBlockParam], None],
|
||||
tool_output_callback: Callable[[Any, str], None],
|
||||
selected_screen: int = 0
|
||||
):
|
||||
self.tool_collection = ToolCollection(
|
||||
ComputerTool(selected_screen=selected_screen),
|
||||
BashTool(),
|
||||
EditTool(),
|
||||
)
|
||||
self.output_callback = output_callback
|
||||
self.tool_output_callback = tool_output_callback
|
||||
|
||||
def __call__(self, response: BetaMessage, messages: list[BetaMessageParam]):
|
||||
new_message = {
|
||||
"role": "assistant",
|
||||
"content": cast(list[BetaContentBlockParam], response.content),
|
||||
}
|
||||
if new_message not in messages:
|
||||
messages.append(new_message)
|
||||
else:
|
||||
print("new_message already in messages, there are duplicates.")
|
||||
|
||||
tool_result_content: list[BetaToolResultBlockParam] = []
|
||||
for content_block in cast(list[BetaContentBlock], response.content):
|
||||
|
||||
self.output_callback(content_block, sender="bot")
|
||||
# Execute the tool
|
||||
if content_block.type == "tool_use":
|
||||
# Run the asynchronous tool execution in a synchronous context
|
||||
result = asyncio.run(self.tool_collection.run(
|
||||
name=content_block.name,
|
||||
tool_input=cast(dict[str, Any], content_block.input),
|
||||
))
|
||||
|
||||
self.output_callback(result, sender="bot")
|
||||
|
||||
tool_result_content.append(
|
||||
_make_api_tool_result(result, content_block.id)
|
||||
)
|
||||
self.tool_output_callback(result, content_block.id)
|
||||
|
||||
# Craft messages based on the content_block
|
||||
# Note: to display the messages in the gradio, you should organize the messages in the following way (user message, bot message)
|
||||
|
||||
display_messages = _message_display_callback(messages)
|
||||
# display_messages = []
|
||||
|
||||
# Send the messages to the gradio
|
||||
for user_msg, bot_msg in display_messages:
|
||||
# yield [user_msg, bot_msg], tool_result_content
|
||||
yield [None, None], tool_result_content
|
||||
|
||||
if not tool_result_content:
|
||||
return messages
|
||||
|
||||
return tool_result_content
|
||||
|
||||
def _message_display_callback(messages):
|
||||
display_messages = []
|
||||
for msg in messages:
|
||||
try:
|
||||
if isinstance(msg["content"][0], TextBlock):
|
||||
display_messages.append((msg["content"][0].text, None)) # User message
|
||||
elif isinstance(msg["content"][0], BetaTextBlock):
|
||||
display_messages.append((None, msg["content"][0].text)) # Bot message
|
||||
elif isinstance(msg["content"][0], BetaToolUseBlock):
|
||||
display_messages.append((None, f"Tool Use: {msg['content'][0].name}\nInput: {msg['content'][0].input}")) # Bot message
|
||||
elif isinstance(msg["content"][0], Dict) and msg["content"][0]["content"][-1]["type"] == "image":
|
||||
display_messages.append((None, f'<img src="data:image/png;base64,{msg["content"][0]["content"][-1]["source"]["data"]}">')) # Bot message
|
||||
else:
|
||||
print(msg["content"][0])
|
||||
except Exception as e:
|
||||
print("error", e)
|
||||
pass
|
||||
return display_messages
|
||||
|
||||
def _make_api_tool_result(
|
||||
result: ToolResult, tool_use_id: str
|
||||
) -> BetaToolResultBlockParam:
|
||||
"""Convert an agent ToolResult to an API ToolResultBlockParam."""
|
||||
tool_result_content: list[BetaTextBlockParam | BetaImageBlockParam] | str = []
|
||||
is_error = False
|
||||
if result.error:
|
||||
is_error = True
|
||||
tool_result_content = _maybe_prepend_system_tool_result(result, result.error)
|
||||
else:
|
||||
if result.output:
|
||||
tool_result_content.append(
|
||||
{
|
||||
"type": "text",
|
||||
"text": _maybe_prepend_system_tool_result(result, result.output),
|
||||
}
|
||||
)
|
||||
if result.base64_image:
|
||||
tool_result_content.append(
|
||||
{
|
||||
"type": "image",
|
||||
"source": {
|
||||
"type": "base64",
|
||||
"media_type": "image/png",
|
||||
"data": result.base64_image,
|
||||
},
|
||||
}
|
||||
)
|
||||
return {
|
||||
"type": "tool_result",
|
||||
"content": tool_result_content,
|
||||
"tool_use_id": tool_use_id,
|
||||
"is_error": is_error,
|
||||
}
|
||||
|
||||
|
||||
def _maybe_prepend_system_tool_result(result: ToolResult, result_text: str):
|
||||
if result.system:
|
||||
result_text = f"<system>{result.system}</system>\n{result_text}"
|
||||
import asyncio
|
||||
from typing import Any, Dict, cast
|
||||
from collections.abc import Callable
|
||||
from anthropic.types.beta import (
|
||||
BetaContentBlock,
|
||||
BetaContentBlockParam,
|
||||
BetaImageBlockParam,
|
||||
BetaMessage,
|
||||
BetaMessageParam,
|
||||
BetaTextBlockParam,
|
||||
BetaToolResultBlockParam,
|
||||
)
|
||||
from anthropic.types import TextBlock
|
||||
from anthropic.types.beta import BetaMessage, BetaTextBlock, BetaToolUseBlock
|
||||
from tools import ComputerTool, ToolCollection, ToolResult
|
||||
|
||||
|
||||
class AnthropicExecutor:
|
||||
def __init__(
|
||||
self,
|
||||
output_callback: Callable[[BetaContentBlockParam], None],
|
||||
tool_output_callback: Callable[[Any, str], None],
|
||||
):
|
||||
self.tool_collection = ToolCollection(
|
||||
ComputerTool()
|
||||
)
|
||||
self.output_callback = output_callback
|
||||
self.tool_output_callback = tool_output_callback
|
||||
|
||||
def __call__(self, response: BetaMessage, messages: list[BetaMessageParam]):
|
||||
new_message = {
|
||||
"role": "assistant",
|
||||
"content": cast(list[BetaContentBlockParam], response.content),
|
||||
}
|
||||
if new_message not in messages:
|
||||
messages.append(new_message)
|
||||
else:
|
||||
print("new_message already in messages, there are duplicates.")
|
||||
|
||||
tool_result_content: list[BetaToolResultBlockParam] = []
|
||||
for content_block in cast(list[BetaContentBlock], response.content):
|
||||
self.output_callback(content_block, sender="bot")
|
||||
# Execute the tool
|
||||
if content_block.type == "tool_use":
|
||||
# Run the asynchronous tool execution in a synchronous context
|
||||
result = asyncio.run(self.tool_collection.run(
|
||||
name=content_block.name,
|
||||
tool_input=cast(dict[str, Any], content_block.input),
|
||||
))
|
||||
|
||||
self.output_callback(result, sender="bot")
|
||||
|
||||
tool_result_content.append(
|
||||
_make_api_tool_result(result, content_block.id)
|
||||
)
|
||||
self.tool_output_callback(result, content_block.id)
|
||||
|
||||
# Craft messages based on the content_block
|
||||
# Note: to display the messages in the gradio, you should organize the messages in the following way (user message, bot message)
|
||||
|
||||
display_messages = _message_display_callback(messages)
|
||||
# display_messages = []
|
||||
|
||||
# Send the messages to the gradio
|
||||
for user_msg, bot_msg in display_messages:
|
||||
# yield [user_msg, bot_msg], tool_result_content
|
||||
yield [None, None], tool_result_content
|
||||
|
||||
if not tool_result_content:
|
||||
return messages
|
||||
|
||||
return tool_result_content
|
||||
|
||||
def _message_display_callback(messages):
|
||||
display_messages = []
|
||||
for msg in messages:
|
||||
try:
|
||||
if isinstance(msg["content"][0], TextBlock):
|
||||
display_messages.append((msg["content"][0].text, None)) # User message
|
||||
elif isinstance(msg["content"][0], BetaTextBlock):
|
||||
display_messages.append((None, msg["content"][0].text)) # Bot message
|
||||
elif isinstance(msg["content"][0], BetaToolUseBlock):
|
||||
display_messages.append((None, f"Tool Use: {msg['content'][0].name}\nInput: {msg['content'][0].input}")) # Bot message
|
||||
elif isinstance(msg["content"][0], Dict) and msg["content"][0]["content"][-1]["type"] == "image":
|
||||
display_messages.append((None, f'<img src="data:image/png;base64,{msg["content"][0]["content"][-1]["source"]["data"]}">')) # Bot message
|
||||
else:
|
||||
print(msg["content"][0])
|
||||
except Exception as e:
|
||||
print("error", e)
|
||||
pass
|
||||
return display_messages
|
||||
|
||||
def _make_api_tool_result(
|
||||
result: ToolResult, tool_use_id: str
|
||||
) -> BetaToolResultBlockParam:
|
||||
"""Convert an agent ToolResult to an API ToolResultBlockParam."""
|
||||
tool_result_content: list[BetaTextBlockParam | BetaImageBlockParam] | str = []
|
||||
is_error = False
|
||||
if result.error:
|
||||
is_error = True
|
||||
tool_result_content = _maybe_prepend_system_tool_result(result, result.error)
|
||||
else:
|
||||
if result.output:
|
||||
tool_result_content.append(
|
||||
{
|
||||
"type": "text",
|
||||
"text": _maybe_prepend_system_tool_result(result, result.output),
|
||||
}
|
||||
)
|
||||
if result.base64_image:
|
||||
tool_result_content.append(
|
||||
{
|
||||
"type": "image",
|
||||
"source": {
|
||||
"type": "base64",
|
||||
"media_type": "image/png",
|
||||
"data": result.base64_image,
|
||||
},
|
||||
}
|
||||
)
|
||||
return {
|
||||
"type": "tool_result",
|
||||
"content": tool_result_content,
|
||||
"tool_use_id": tool_use_id,
|
||||
"is_error": is_error,
|
||||
}
|
||||
|
||||
|
||||
def _maybe_prepend_system_tool_result(result: ToolResult, result_text: str):
|
||||
if result.system:
|
||||
result_text = f"<system>{result.system}</system>\n{result_text}"
|
||||
return result_text
|
||||
114
omnitool/gradio/loop.py
Normal file
@@ -0,0 +1,114 @@
|
||||
"""
|
||||
Agentic sampling loop that calls the Anthropic API and local implenmentation of anthropic-defined computer use tools.
|
||||
"""
|
||||
from collections.abc import Callable
|
||||
from enum import StrEnum
|
||||
|
||||
from anthropic import APIResponse
|
||||
from anthropic.types import (
|
||||
TextBlock,
|
||||
)
|
||||
from anthropic.types.beta import (
|
||||
BetaContentBlock,
|
||||
BetaMessage,
|
||||
BetaMessageParam
|
||||
)
|
||||
from tools import ToolResult
|
||||
|
||||
from agent.llm_utils.omniparserclient import OmniParserClient
|
||||
from agent.anthropic_agent import AnthropicActor
|
||||
from agent.vlm_agent import VLMAgent
|
||||
from executor.anthropic_executor import AnthropicExecutor
|
||||
|
||||
BETA_FLAG = "computer-use-2024-10-22"
|
||||
|
||||
class APIProvider(StrEnum):
|
||||
ANTHROPIC = "anthropic"
|
||||
BEDROCK = "bedrock"
|
||||
VERTEX = "vertex"
|
||||
OPENAI = "openai"
|
||||
|
||||
|
||||
PROVIDER_TO_DEFAULT_MODEL_NAME: dict[APIProvider, str] = {
|
||||
APIProvider.ANTHROPIC: "claude-3-5-sonnet-20241022",
|
||||
APIProvider.BEDROCK: "anthropic.claude-3-5-sonnet-20241022-v2:0",
|
||||
APIProvider.VERTEX: "claude-3-5-sonnet-v2@20241022",
|
||||
APIProvider.OPENAI: "gpt-4o",
|
||||
}
|
||||
|
||||
def sampling_loop_sync(
|
||||
*,
|
||||
model: str,
|
||||
provider: APIProvider | None,
|
||||
messages: list[BetaMessageParam],
|
||||
output_callback: Callable[[BetaContentBlock], None],
|
||||
tool_output_callback: Callable[[ToolResult, str], None],
|
||||
api_response_callback: Callable[[APIResponse[BetaMessage]], None],
|
||||
api_key: str,
|
||||
only_n_most_recent_images: int | None = 2,
|
||||
max_tokens: int = 4096,
|
||||
omniparser_url: str
|
||||
):
|
||||
"""
|
||||
Synchronous agentic sampling loop for the assistant/tool interaction of computer use.
|
||||
"""
|
||||
print('in sampling_loop_sync, model:', model)
|
||||
omniparser_client = OmniParserClient(url=f"http://{omniparser_url}/parse/")
|
||||
if model == "claude-3-5-sonnet-20241022":
|
||||
# Register Actor and Executor
|
||||
actor = AnthropicActor(
|
||||
model=model,
|
||||
provider=provider,
|
||||
api_key=api_key,
|
||||
api_response_callback=api_response_callback,
|
||||
max_tokens=max_tokens,
|
||||
only_n_most_recent_images=only_n_most_recent_images
|
||||
)
|
||||
elif model in set(["omniparser + gpt-4o", "omniparser + o1", "omniparser + o3-mini", "omniparser + R1", "omniparser + qwen2.5vl"]):
|
||||
actor = VLMAgent(
|
||||
model=model,
|
||||
provider=provider,
|
||||
api_key=api_key,
|
||||
api_response_callback=api_response_callback,
|
||||
output_callback=output_callback,
|
||||
max_tokens=max_tokens,
|
||||
only_n_most_recent_images=only_n_most_recent_images
|
||||
)
|
||||
else:
|
||||
raise ValueError(f"Model {model} not supported")
|
||||
executor = AnthropicExecutor(
|
||||
output_callback=output_callback,
|
||||
tool_output_callback=tool_output_callback,
|
||||
)
|
||||
print(f"Model Inited: {model}, Provider: {provider}")
|
||||
|
||||
tool_result_content = None
|
||||
|
||||
print(f"Start the message loop. User messages: {messages}")
|
||||
|
||||
if model == "claude-3-5-sonnet-20241022": # Anthropic loop
|
||||
while True:
|
||||
parsed_screen = omniparser_client() # parsed_screen: {"som_image_base64": dino_labled_img, "parsed_content_list": parsed_content_list, "screen_info"}
|
||||
screen_info_block = TextBlock(text='Below is the structured accessibility information of the current UI screen, which includes text and icons you can operate on, take these information into account when you are making the prediction for the next action. Note you will still need to take screenshot to get the image: \n' + parsed_screen['screen_info'], type='text')
|
||||
screen_info_dict = {"role": "user", "content": [screen_info_block]}
|
||||
messages.append(screen_info_dict)
|
||||
tools_use_needed = actor(messages=messages)
|
||||
|
||||
for message, tool_result_content in executor(tools_use_needed, messages):
|
||||
yield message
|
||||
|
||||
if not tool_result_content:
|
||||
return messages
|
||||
|
||||
messages.append({"content": tool_result_content, "role": "user"})
|
||||
|
||||
elif model in set(["omniparser + gpt-4o", "omniparser + o1", "omniparser + o3-mini", "omniparser + R1", "omniparser + qwen2.5vl"]):
|
||||
while True:
|
||||
parsed_screen = omniparser_client()
|
||||
tools_use_needed, vlm_response_json = actor(messages=messages, parsed_screen=parsed_screen)
|
||||
|
||||
for message, tool_result_content in executor(tools_use_needed, messages):
|
||||
yield message
|
||||
|
||||
if not tool_result_content:
|
||||
return messages
|
||||
@@ -1,16 +1,11 @@
|
||||
from .base import CLIResult, ToolResult
|
||||
from .bash import BashTool
|
||||
from .collection import ToolCollection
|
||||
from .computer import ComputerTool
|
||||
from .edit import EditTool
|
||||
from .screen_capture import get_screenshot
|
||||
|
||||
__ALL__ = [
|
||||
BashTool,
|
||||
CLIResult,
|
||||
ComputerTool,
|
||||
EditTool,
|
||||
ToolCollection,
|
||||
ToolResult,
|
||||
get_screenshot,
|
||||
]
|
||||
from .base import ToolResult
|
||||
from .collection import ToolCollection
|
||||
from .computer import ComputerTool
|
||||
from .screen_capture import get_screenshot
|
||||
|
||||
__ALL__ = [
|
||||
ComputerTool,
|
||||
ToolCollection,
|
||||
ToolResult,
|
||||
get_screenshot,
|
||||
]
|
||||
@@ -1,69 +1,65 @@
|
||||
from abc import ABCMeta, abstractmethod
|
||||
from dataclasses import dataclass, fields, replace
|
||||
from typing import Any
|
||||
|
||||
from anthropic.types.beta import BetaToolUnionParam
|
||||
|
||||
|
||||
class BaseAnthropicTool(metaclass=ABCMeta):
|
||||
"""Abstract base class for Anthropic-defined tools."""
|
||||
|
||||
@abstractmethod
|
||||
def __call__(self, **kwargs) -> Any:
|
||||
"""Executes the tool with the given arguments."""
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
def to_params(
|
||||
self,
|
||||
) -> BetaToolUnionParam:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
@dataclass(kw_only=True, frozen=True)
|
||||
class ToolResult:
|
||||
"""Represents the result of a tool execution."""
|
||||
|
||||
output: str | None = None
|
||||
error: str | None = None
|
||||
base64_image: str | None = None
|
||||
system: str | None = None
|
||||
|
||||
def __bool__(self):
|
||||
return any(getattr(self, field.name) for field in fields(self))
|
||||
|
||||
def __add__(self, other: "ToolResult"):
|
||||
def combine_fields(
|
||||
field: str | None, other_field: str | None, concatenate: bool = True
|
||||
):
|
||||
if field and other_field:
|
||||
if concatenate:
|
||||
return field + other_field
|
||||
raise ValueError("Cannot combine tool results")
|
||||
return field or other_field
|
||||
|
||||
return ToolResult(
|
||||
output=combine_fields(self.output, other.output),
|
||||
error=combine_fields(self.error, other.error),
|
||||
base64_image=combine_fields(self.base64_image, other.base64_image, False),
|
||||
system=combine_fields(self.system, other.system),
|
||||
)
|
||||
|
||||
def replace(self, **kwargs):
|
||||
"""Returns a new ToolResult with the given fields replaced."""
|
||||
return replace(self, **kwargs)
|
||||
|
||||
|
||||
class CLIResult(ToolResult):
|
||||
"""A ToolResult that can be rendered as a CLI output."""
|
||||
|
||||
|
||||
class ToolFailure(ToolResult):
|
||||
"""A ToolResult that represents a failure."""
|
||||
|
||||
|
||||
class ToolError(Exception):
|
||||
"""Raised when a tool encounters an error."""
|
||||
|
||||
def __init__(self, message):
|
||||
self.message = message
|
||||
from abc import ABCMeta, abstractmethod
|
||||
from dataclasses import dataclass, fields, replace
|
||||
from typing import Any
|
||||
|
||||
from anthropic.types.beta import BetaToolUnionParam
|
||||
|
||||
|
||||
class BaseAnthropicTool(metaclass=ABCMeta):
|
||||
"""Abstract base class for Anthropic-defined tools."""
|
||||
|
||||
@abstractmethod
|
||||
def __call__(self, **kwargs) -> Any:
|
||||
"""Executes the tool with the given arguments."""
|
||||
...
|
||||
|
||||
@abstractmethod
|
||||
def to_params(
|
||||
self,
|
||||
) -> BetaToolUnionParam:
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
@dataclass(kw_only=True, frozen=True)
|
||||
class ToolResult:
|
||||
"""Represents the result of a tool execution."""
|
||||
|
||||
output: str | None = None
|
||||
error: str | None = None
|
||||
base64_image: str | None = None
|
||||
system: str | None = None
|
||||
|
||||
def __bool__(self):
|
||||
return any(getattr(self, field.name) for field in fields(self))
|
||||
|
||||
def __add__(self, other: "ToolResult"):
|
||||
def combine_fields(
|
||||
field: str | None, other_field: str | None, concatenate: bool = True
|
||||
):
|
||||
if field and other_field:
|
||||
if concatenate:
|
||||
return field + other_field
|
||||
raise ValueError("Cannot combine tool results")
|
||||
return field or other_field
|
||||
|
||||
return ToolResult(
|
||||
output=combine_fields(self.output, other.output),
|
||||
error=combine_fields(self.error, other.error),
|
||||
base64_image=combine_fields(self.base64_image, other.base64_image, False),
|
||||
system=combine_fields(self.system, other.system),
|
||||
)
|
||||
|
||||
def replace(self, **kwargs):
|
||||
"""Returns a new ToolResult with the given fields replaced."""
|
||||
return replace(self, **kwargs)
|
||||
|
||||
|
||||
class ToolFailure(ToolResult):
|
||||
"""A ToolResult that represents a failure."""
|
||||
|
||||
|
||||
class ToolError(Exception):
|
||||
"""Raised when a tool encounters an error."""
|
||||
|
||||
def __init__(self, message):
|
||||
self.message = message
|
||||
@@ -1,34 +1,34 @@
|
||||
"""Collection classes for managing multiple tools."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from anthropic.types.beta import BetaToolUnionParam
|
||||
|
||||
from .base import (
|
||||
BaseAnthropicTool,
|
||||
ToolError,
|
||||
ToolFailure,
|
||||
ToolResult,
|
||||
)
|
||||
|
||||
|
||||
class ToolCollection:
|
||||
"""A collection of anthropic-defined tools."""
|
||||
|
||||
def __init__(self, *tools: BaseAnthropicTool):
|
||||
self.tools = tools
|
||||
self.tool_map = {tool.to_params()["name"]: tool for tool in tools}
|
||||
|
||||
def to_params(
|
||||
self,
|
||||
) -> list[BetaToolUnionParam]:
|
||||
return [tool.to_params() for tool in self.tools]
|
||||
|
||||
async def run(self, *, name: str, tool_input: dict[str, Any]) -> ToolResult:
|
||||
tool = self.tool_map.get(name)
|
||||
if not tool:
|
||||
return ToolFailure(error=f"Tool {name} is invalid")
|
||||
try:
|
||||
return await tool(**tool_input)
|
||||
except ToolError as e:
|
||||
return ToolFailure(error=e.message)
|
||||
"""Collection classes for managing multiple tools."""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from anthropic.types.beta import BetaToolUnionParam
|
||||
|
||||
from .base import (
|
||||
BaseAnthropicTool,
|
||||
ToolError,
|
||||
ToolFailure,
|
||||
ToolResult,
|
||||
)
|
||||
|
||||
|
||||
class ToolCollection:
|
||||
"""A collection of anthropic-defined tools."""
|
||||
|
||||
def __init__(self, *tools: BaseAnthropicTool):
|
||||
self.tools = tools
|
||||
self.tool_map = {tool.to_params()["name"]: tool for tool in tools}
|
||||
|
||||
def to_params(
|
||||
self,
|
||||
) -> list[BetaToolUnionParam]:
|
||||
return [tool.to_params() for tool in self.tools]
|
||||
|
||||
async def run(self, *, name: str, tool_input: dict[str, Any]) -> ToolResult:
|
||||
tool = self.tool_map.get(name)
|
||||
if not tool:
|
||||
return ToolFailure(error=f"Tool {name} is invalid")
|
||||
try:
|
||||
return await tool(**tool_input)
|
||||
except ToolError as e:
|
||||
return ToolFailure(error=e.message)
|
||||
326
omnitool/gradio/tools/computer.py
Normal file
@@ -0,0 +1,326 @@
|
||||
import base64
|
||||
import time
|
||||
from enum import StrEnum
|
||||
from typing import Literal, TypedDict
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from anthropic.types.beta import BetaToolComputerUse20241022Param
|
||||
|
||||
from .base import BaseAnthropicTool, ToolError, ToolResult
|
||||
from .screen_capture import get_screenshot
|
||||
import requests
|
||||
import re
|
||||
|
||||
OUTPUT_DIR = "./tmp/outputs"
|
||||
|
||||
TYPING_DELAY_MS = 12
|
||||
TYPING_GROUP_SIZE = 50
|
||||
|
||||
Action = Literal[
|
||||
"key",
|
||||
"type",
|
||||
"mouse_move",
|
||||
"left_click",
|
||||
"left_click_drag",
|
||||
"right_click",
|
||||
"middle_click",
|
||||
"double_click",
|
||||
"screenshot",
|
||||
"cursor_position",
|
||||
"hover",
|
||||
"wait"
|
||||
]
|
||||
|
||||
|
||||
class Resolution(TypedDict):
|
||||
width: int
|
||||
height: int
|
||||
|
||||
|
||||
MAX_SCALING_TARGETS: dict[str, Resolution] = {
|
||||
"XGA": Resolution(width=1024, height=768), # 4:3
|
||||
"WXGA": Resolution(width=1280, height=800), # 16:10
|
||||
"FWXGA": Resolution(width=1366, height=768), # ~16:9
|
||||
}
|
||||
|
||||
|
||||
class ScalingSource(StrEnum):
|
||||
COMPUTER = "computer"
|
||||
API = "api"
|
||||
|
||||
|
||||
class ComputerToolOptions(TypedDict):
|
||||
display_height_px: int
|
||||
display_width_px: int
|
||||
display_number: int | None
|
||||
|
||||
|
||||
def chunks(s: str, chunk_size: int) -> list[str]:
|
||||
return [s[i : i + chunk_size] for i in range(0, len(s), chunk_size)]
|
||||
|
||||
class ComputerTool(BaseAnthropicTool):
|
||||
"""
|
||||
A tool that allows the agent to interact with the screen, keyboard, and mouse of the current computer.
|
||||
Adapted for Windows using 'pyautogui'.
|
||||
"""
|
||||
|
||||
name: Literal["computer"] = "computer"
|
||||
api_type: Literal["computer_20241022"] = "computer_20241022"
|
||||
width: int
|
||||
height: int
|
||||
display_num: int | None
|
||||
|
||||
_screenshot_delay = 2.0
|
||||
_scaling_enabled = True
|
||||
|
||||
@property
|
||||
def options(self) -> ComputerToolOptions:
|
||||
width, height = self.scale_coordinates(
|
||||
ScalingSource.COMPUTER, self.width, self.height
|
||||
)
|
||||
return {
|
||||
"display_width_px": width,
|
||||
"display_height_px": height,
|
||||
"display_number": self.display_num,
|
||||
}
|
||||
|
||||
def to_params(self) -> BetaToolComputerUse20241022Param:
|
||||
return {"name": self.name, "type": self.api_type, **self.options}
|
||||
|
||||
def __init__(self, is_scaling: bool = False):
|
||||
super().__init__()
|
||||
|
||||
# Get screen width and height using Windows command
|
||||
self.display_num = None
|
||||
self.offset_x = 0
|
||||
self.offset_y = 0
|
||||
self.is_scaling = is_scaling
|
||||
self.width, self.height = self.get_screen_size()
|
||||
print(f"screen size: {self.width}, {self.height}")
|
||||
|
||||
self.key_conversion = {"Page_Down": "pagedown",
|
||||
"Page_Up": "pageup",
|
||||
"Super_L": "win",
|
||||
"Escape": "esc"}
|
||||
|
||||
|
||||
async def __call__(
|
||||
self,
|
||||
*,
|
||||
action: Action,
|
||||
text: str | None = None,
|
||||
coordinate: tuple[int, int] | None = None,
|
||||
**kwargs,
|
||||
):
|
||||
print(f"action: {action}, text: {text}, coordinate: {coordinate}, is_scaling: {self.is_scaling}")
|
||||
if action in ("mouse_move", "left_click_drag"):
|
||||
if coordinate is None:
|
||||
raise ToolError(f"coordinate is required for {action}")
|
||||
if text is not None:
|
||||
raise ToolError(f"text is not accepted for {action}")
|
||||
if not isinstance(coordinate, (list, tuple)) or len(coordinate) != 2:
|
||||
raise ToolError(f"{coordinate} must be a tuple of length 2")
|
||||
# if not all(isinstance(i, int) and i >= 0 for i in coordinate):
|
||||
if not all(isinstance(i, int) for i in coordinate):
|
||||
raise ToolError(f"{coordinate} must be a tuple of non-negative ints")
|
||||
|
||||
if self.is_scaling:
|
||||
x, y = self.scale_coordinates(
|
||||
ScalingSource.API, coordinate[0], coordinate[1]
|
||||
)
|
||||
else:
|
||||
x, y = coordinate
|
||||
|
||||
# print(f"scaled_coordinates: {x}, {y}")
|
||||
# print(f"offset: {self.offset_x}, {self.offset_y}")
|
||||
|
||||
# x += self.offset_x # TODO - check if this is needed
|
||||
# y += self.offset_y
|
||||
|
||||
print(f"mouse move to {x}, {y}")
|
||||
|
||||
if action == "mouse_move":
|
||||
self.send_to_vm(f"pyautogui.moveTo({x}, {y})")
|
||||
return ToolResult(output=f"Moved mouse to ({x}, {y})")
|
||||
elif action == "left_click_drag":
|
||||
current_x, current_y = self.send_to_vm("pyautogui.position()")
|
||||
self.send_to_vm(f"pyautogui.dragTo({x}, {y}, duration=0.5)")
|
||||
return ToolResult(output=f"Dragged mouse from ({current_x}, {current_y}) to ({x}, {y})")
|
||||
|
||||
if action in ("key", "type"):
|
||||
if text is None:
|
||||
raise ToolError(f"text is required for {action}")
|
||||
if coordinate is not None:
|
||||
raise ToolError(f"coordinate is not accepted for {action}")
|
||||
if not isinstance(text, str):
|
||||
raise ToolError(output=f"{text} must be a string")
|
||||
|
||||
if action == "key":
|
||||
# Handle key combinations
|
||||
keys = text.split('+')
|
||||
for key in keys:
|
||||
key = self.key_conversion.get(key.strip(), key.strip())
|
||||
key = key.lower()
|
||||
self.send_to_vm(f"pyautogui.keyDown('{key}')") # Press down each key
|
||||
for key in reversed(keys):
|
||||
key = self.key_conversion.get(key.strip(), key.strip())
|
||||
key = key.lower()
|
||||
self.send_to_vm(f"pyautogui.keyUp('{key}')") # Release each key in reverse order
|
||||
return ToolResult(output=f"Pressed keys: {text}")
|
||||
|
||||
elif action == "type":
|
||||
self.send_to_vm(f"pyautogui.typewrite('{text}', interval={TYPING_DELAY_MS / 1000})")
|
||||
screenshot_base64 = (await self.screenshot()).base64_image
|
||||
return ToolResult(output=text, base64_image=screenshot_base64)
|
||||
|
||||
if action in (
|
||||
"left_click",
|
||||
"right_click",
|
||||
"double_click",
|
||||
"middle_click",
|
||||
"screenshot",
|
||||
"cursor_position",
|
||||
"left_press",
|
||||
):
|
||||
if text is not None:
|
||||
raise ToolError(f"text is not accepted for {action}")
|
||||
if coordinate is not None:
|
||||
raise ToolError(f"coordinate is not accepted for {action}")
|
||||
|
||||
if action == "screenshot":
|
||||
return await self.screenshot()
|
||||
elif action == "cursor_position":
|
||||
x, y = self.send_to_vm("pyautogui.position()")
|
||||
x, y = self.scale_coordinates(ScalingSource.COMPUTER, x, y)
|
||||
return ToolResult(output=f"X={x},Y={y}")
|
||||
else:
|
||||
if action == "left_click":
|
||||
self.send_to_vm("pyautogui.click()")
|
||||
elif action == "right_click":
|
||||
self.send_to_vm("pyautogui.rightClick()")
|
||||
elif action == "middle_click":
|
||||
self.send_to_vm("pyautogui.middleClick()")
|
||||
elif action == "double_click":
|
||||
self.send_to_vm("pyautogui.doubleClick()")
|
||||
elif action == "left_press":
|
||||
self.send_to_vm("pyautogui.mouseDown()")
|
||||
time.sleep(1)
|
||||
self.send_to_vm("pyautogui.mouseUp()")
|
||||
return ToolResult(output=f"Performed {action}")
|
||||
if action in ("scroll_up", "scroll_down"):
|
||||
if action == "scroll_up":
|
||||
self.send_to_vm("pyautogui.scroll(100)")
|
||||
elif action == "scroll_down":
|
||||
self.send_to_vm("pyautogui.scroll(-100)")
|
||||
return ToolResult(output=f"Performed {action}")
|
||||
if action == "hover":
|
||||
return ToolResult(output=f"Performed {action}")
|
||||
if action == "wait":
|
||||
time.sleep(1)
|
||||
return ToolResult(output=f"Performed {action}")
|
||||
raise ToolError(f"Invalid action: {action}")
|
||||
|
||||
def send_to_vm(self, action: str):
|
||||
"""
|
||||
Executes a python command on the server. Only return tuple of x,y when action is "pyautogui.position()"
|
||||
"""
|
||||
prefix = "import pyautogui; pyautogui.FAILSAFE = False;"
|
||||
command_list = ["python", "-c", f"{prefix} {action}"]
|
||||
parse = action == "pyautogui.position()"
|
||||
if parse:
|
||||
command_list[-1] = f"{prefix} print({action})"
|
||||
|
||||
try:
|
||||
print(f"sending to vm: {command_list}")
|
||||
response = requests.post(
|
||||
f"http://localhost:5000/execute",
|
||||
headers={'Content-Type': 'application/json'},
|
||||
json={"command": command_list},
|
||||
timeout=90
|
||||
)
|
||||
time.sleep(0.7) # avoid async error as actions take time to complete
|
||||
print(f"action executed")
|
||||
if response.status_code != 200:
|
||||
raise ToolError(f"Failed to execute command. Status code: {response.status_code}")
|
||||
if parse:
|
||||
output = response.json()['output'].strip()
|
||||
match = re.search(r'Point\(x=(\d+),\s*y=(\d+)\)', output)
|
||||
if not match:
|
||||
raise ToolError(f"Could not parse coordinates from output: {output}")
|
||||
x, y = map(int, match.groups())
|
||||
return x, y
|
||||
except requests.exceptions.RequestException as e:
|
||||
raise ToolError(f"An error occurred while trying to execute the command: {str(e)}")
|
||||
|
||||
async def screenshot(self):
|
||||
if not hasattr(self, 'target_dimension'):
|
||||
screenshot = self.padding_image(screenshot)
|
||||
self.target_dimension = MAX_SCALING_TARGETS["WXGA"]
|
||||
width, height = self.target_dimension["width"], self.target_dimension["height"]
|
||||
screenshot, path = get_screenshot(resize=True, target_width=width, target_height=height)
|
||||
time.sleep(0.7) # avoid async error as actions take time to complete
|
||||
return ToolResult(base64_image=base64.b64encode(path.read_bytes()).decode())
|
||||
|
||||
def padding_image(self, screenshot):
|
||||
"""Pad the screenshot to 16:10 aspect ratio, when the aspect ratio is not 16:10."""
|
||||
_, height = screenshot.size
|
||||
new_width = height * 16 // 10
|
||||
|
||||
padding_image = Image.new("RGB", (new_width, height), (255, 255, 255))
|
||||
# padding to top left
|
||||
padding_image.paste(screenshot, (0, 0))
|
||||
return padding_image
|
||||
|
||||
def scale_coordinates(self, source: ScalingSource, x: int, y: int):
|
||||
"""Scale coordinates to a target maximum resolution."""
|
||||
if not self._scaling_enabled:
|
||||
return x, y
|
||||
ratio = self.width / self.height
|
||||
target_dimension = None
|
||||
|
||||
for target_name, dimension in MAX_SCALING_TARGETS.items():
|
||||
# allow some error in the aspect ratio - not ratios are exactly 16:9
|
||||
if abs(dimension["width"] / dimension["height"] - ratio) < 0.02:
|
||||
if dimension["width"] < self.width:
|
||||
target_dimension = dimension
|
||||
self.target_dimension = target_dimension
|
||||
# print(f"target_dimension: {target_dimension}")
|
||||
break
|
||||
|
||||
if target_dimension is None:
|
||||
# TODO: currently we force the target to be WXGA (16:10), when it cannot find a match
|
||||
target_dimension = MAX_SCALING_TARGETS["WXGA"]
|
||||
self.target_dimension = MAX_SCALING_TARGETS["WXGA"]
|
||||
|
||||
# should be less than 1
|
||||
x_scaling_factor = target_dimension["width"] / self.width
|
||||
y_scaling_factor = target_dimension["height"] / self.height
|
||||
if source == ScalingSource.API:
|
||||
if x > self.width or y > self.height:
|
||||
raise ToolError(f"Coordinates {x}, {y} are out of bounds")
|
||||
# scale up
|
||||
return round(x / x_scaling_factor), round(y / y_scaling_factor)
|
||||
# scale down
|
||||
return round(x * x_scaling_factor), round(y * y_scaling_factor)
|
||||
|
||||
def get_screen_size(self):
|
||||
"""Return width and height of the screen"""
|
||||
try:
|
||||
response = requests.post(
|
||||
f"http://localhost:5000/execute",
|
||||
headers={'Content-Type': 'application/json'},
|
||||
json={"command": ["python", "-c", "import pyautogui; print(pyautogui.size())"]},
|
||||
timeout=90
|
||||
)
|
||||
if response.status_code != 200:
|
||||
raise ToolError(f"Failed to get screen size. Status code: {response.status_code}")
|
||||
|
||||
output = response.json()['output'].strip()
|
||||
match = re.search(r'Size\(width=(\d+),\s*height=(\d+)\)', output)
|
||||
if not match:
|
||||
raise ToolError(f"Could not parse screen size from output: {output}")
|
||||
width, height = map(int, match.groups())
|
||||
return width, height
|
||||
except requests.exceptions.RequestException as e:
|
||||
raise ToolError(f"An error occurred while trying to get screen size: {str(e)}")
|
||||
29
omnitool/gradio/tools/screen_capture.py
Normal file
@@ -0,0 +1,29 @@
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
import requests
|
||||
from PIL import Image
|
||||
from .base import BaseAnthropicTool, ToolError
|
||||
from io import BytesIO
|
||||
|
||||
OUTPUT_DIR = "./tmp/outputs"
|
||||
|
||||
def get_screenshot(resize: bool = False, target_width: int = 1920, target_height: int = 1080):
|
||||
"""Capture screenshot by requesting from HTTP endpoint - returns native resolution unless resized"""
|
||||
output_dir = Path(OUTPUT_DIR)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
path = output_dir / f"screenshot_{uuid4().hex}.png"
|
||||
|
||||
try:
|
||||
response = requests.get('http://localhost:5000/screenshot')
|
||||
if response.status_code != 200:
|
||||
raise ToolError(f"Failed to capture screenshot: HTTP {response.status_code}")
|
||||
|
||||
# (1280, 800)
|
||||
screenshot = Image.open(BytesIO(response.content))
|
||||
|
||||
if resize and screenshot.size != (target_width, target_height):
|
||||
screenshot = screenshot.resize((target_width, target_height))
|
||||
screenshot.save(path)
|
||||
return screenshot, path
|
||||
except Exception as e:
|
||||
raise ToolError(f"Failed to capture screenshot: {str(e)}")
|
||||
4
omnitool/omnibox/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
vm/win11iso/custom.iso
|
||||
vm/win11storage
|
||||
vm/win11setup/setupscripts/firstboot_log.txt
|
||||
vm/win11setup/setupscripts/server/server.log
|
||||
48
omnitool/omnibox/Dockerfile
Normal file
@@ -0,0 +1,48 @@
|
||||
ARG VERSION_ARG="latest"
|
||||
FROM scratch AS build-amd64
|
||||
|
||||
COPY --from=qemux/qemu-docker:6.08 / /
|
||||
|
||||
ARG DEBCONF_NOWARNINGS="yes"
|
||||
ARG DEBIAN_FRONTEND="noninteractive"
|
||||
ARG DEBCONF_NONINTERACTIVE_SEEN="true"
|
||||
|
||||
RUN set -eu && \
|
||||
apt-get update && \
|
||||
apt-get --no-install-recommends -y install \
|
||||
bc \
|
||||
jq \
|
||||
curl \
|
||||
7zip \
|
||||
wsdd \
|
||||
samba \
|
||||
xz-utils \
|
||||
wimtools \
|
||||
dos2unix \
|
||||
cabextract \
|
||||
genisoimage \
|
||||
libxml2-utils \
|
||||
libarchive-tools && \
|
||||
apt-get clean && \
|
||||
rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
||||
|
||||
COPY --chmod=755 ./vm/buildcontainer /run/
|
||||
RUN dos2unix /run/*
|
||||
|
||||
COPY --chmod=755 ./vm/win11def /run/assets
|
||||
RUN dos2unix /run/assets/*
|
||||
|
||||
ADD --chmod=755 https://raw.githubusercontent.com/christgau/wsdd/v0.8/src/wsdd.py /usr/sbin/wsdd
|
||||
ADD --chmod=664 https://github.com/qemus/virtiso-whql/releases/download/v1.9.43-0/virtio-win-1.9.43.tar.xz /drivers.txz
|
||||
|
||||
FROM dockurr/windows-arm:${VERSION_ARG} AS build-arm64
|
||||
FROM build-${TARGETARCH}
|
||||
|
||||
ARG VERSION_ARG="0.00"
|
||||
RUN echo "$VERSION_ARG" > /run/version
|
||||
|
||||
EXPOSE 8006 3389
|
||||
|
||||
ENV VERSION="win11e"
|
||||
|
||||
ENTRYPOINT ["/usr/bin/tini", "-s", "/run/entry.sh"]
|
||||
23
omnitool/omnibox/compose.yml
Normal file
@@ -0,0 +1,23 @@
|
||||
services:
|
||||
windows:
|
||||
image: windows-local
|
||||
container_name: omni-windows
|
||||
privileged: true
|
||||
environment:
|
||||
RAM_SIZE: "8G"
|
||||
CPU_CORES: "4"
|
||||
DISK_SIZE: "20G"
|
||||
devices:
|
||||
- /dev/kvm
|
||||
- /dev/net/tun
|
||||
cap_add:
|
||||
- NET_ADMIN
|
||||
ports:
|
||||
- 8006:8006 # Web Viewer access
|
||||
- 5000:5000 # Computer control server
|
||||
volumes:
|
||||
- ./vm/win11iso/custom.iso:/custom.iso
|
||||
- ./vm/win11setup/firstboot:/oem
|
||||
- ./vm/win11setup/setupscripts:/data
|
||||
- ./vm/win11storage:/storage
|
||||
|
||||
70
omnitool/omnibox/scripts/manage_vm.ps1
Normal file
@@ -0,0 +1,70 @@
|
||||
function Create-VM {
|
||||
if (-not (docker images windows-local -q)) {
|
||||
Write-Host "Image not found locally. Building..."
|
||||
docker build -t windows-local ..
|
||||
} else {
|
||||
Write-Host "Image found locally. Skipping build."
|
||||
}
|
||||
|
||||
docker compose -f ../compose.yml up -d
|
||||
|
||||
while ($true) {
|
||||
try {
|
||||
$response = Invoke-WebRequest -Uri "http://localhost:5000/probe" -Method GET -UseBasicParsing
|
||||
if ($response.StatusCode -eq 200) {
|
||||
break
|
||||
}
|
||||
} catch {
|
||||
Write-Host "Waiting for a response from the computer control server. When first building the VM storage folder this can take a while..."
|
||||
Start-Sleep -Seconds 5
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "VM + server is up and running!"
|
||||
}
|
||||
|
||||
function Start-LocalVM {
|
||||
Write-Host "Starting VM..."
|
||||
docker compose -f ../compose.yml start
|
||||
while ($true) {
|
||||
try {
|
||||
$response = Invoke-WebRequest -Uri "http://localhost:5000/probe" -Method GET -UseBasicParsing
|
||||
if ($response.StatusCode -eq 200) {
|
||||
break
|
||||
}
|
||||
} catch {
|
||||
Write-Host "Waiting for a response from the computer control server"
|
||||
Start-Sleep -Seconds 5
|
||||
}
|
||||
}
|
||||
Write-Host "VM started"
|
||||
}
|
||||
|
||||
function Stop-LocalVM {
|
||||
Write-Host "Stopping VM..."
|
||||
docker compose -f ../compose.yml stop
|
||||
Write-Host "VM stopped"
|
||||
}
|
||||
|
||||
function Remove-VM {
|
||||
Write-Host "Removing VM and associated containers..."
|
||||
docker compose -f ../compose.yml down
|
||||
Write-Host "VM removed"
|
||||
}
|
||||
|
||||
if (-not $args[0]) {
|
||||
Write-Host "Usage: $($MyInvocation.MyCommand.Name) [create|start|stop|delete]"
|
||||
exit 1
|
||||
}
|
||||
|
||||
switch ($args[0]) {
|
||||
"create" { Create-VM }
|
||||
"start" { Start-LocalVM }
|
||||
"stop" { Stop-LocalVM }
|
||||
"delete" { Remove-VM }
|
||||
default {
|
||||
Write-Host "Invalid option: $($args[0])"
|
||||
Write-Host "Usage: $($MyInvocation.MyCommand.Name) [create|start|stop|delete]"
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
77
omnitool/omnibox/scripts/manage_vm.sh
Executable file
@@ -0,0 +1,77 @@
|
||||
#!/bin/bash
|
||||
|
||||
create_vm() {
|
||||
if ! docker images windows-local -q | grep -q .; then
|
||||
echo "Image not found locally. Building..."
|
||||
docker build -t windows-local ..
|
||||
else
|
||||
echo "Image found locally. Skipping build."
|
||||
fi
|
||||
|
||||
docker compose -f ../compose.yml up -d
|
||||
|
||||
# Wait for the VM to start up
|
||||
while true; do
|
||||
response=$(curl --write-out '%{http_code}' --silent --output /dev/null localhost:5000/probe)
|
||||
if [ $response -eq 200 ]; then
|
||||
break
|
||||
fi
|
||||
echo "Waiting for a response from the computer control server. When first building the VM storage folder this can take a while..."
|
||||
sleep 5
|
||||
done
|
||||
|
||||
echo "VM + server is up and running!"
|
||||
}
|
||||
|
||||
start_vm() {
|
||||
echo "Starting VM..."
|
||||
docker compose -f ../compose.yml start
|
||||
while true; do
|
||||
response=$(curl --write-out '%{http_code}' --silent --output /dev/null localhost:5000/probe)
|
||||
if [ $response -eq 200 ]; then
|
||||
break
|
||||
fi
|
||||
echo "Waiting for a response from the computer control server"
|
||||
sleep 5
|
||||
done
|
||||
echo "VM started"
|
||||
}
|
||||
|
||||
stop_vm() {
|
||||
echo "Stopping VM..."
|
||||
docker compose -f ../compose.yml stop
|
||||
echo "VM stopped"
|
||||
}
|
||||
|
||||
delete_vm() {
|
||||
echo "Removing VM and associated containers..."
|
||||
docker compose -f ../compose.yml down
|
||||
echo "VM removed"
|
||||
}
|
||||
|
||||
# Check if control parameter is provided
|
||||
if [ -z "$1" ]; then
|
||||
echo "Usage: $0 [create|start|stop|delete]"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Execute the appropriate function based on the control parameter
|
||||
case "$1" in
|
||||
"create")
|
||||
create_vm
|
||||
;;
|
||||
"start")
|
||||
start_vm
|
||||
;;
|
||||
"stop")
|
||||
stop_vm
|
||||
;;
|
||||
"delete")
|
||||
delete_vm
|
||||
;;
|
||||
*)
|
||||
echo "Invalid option: $1"
|
||||
echo "Usage: $0 [create|start|stop|delete]"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
410
omnitool/omnibox/vm/buildcontainer/define.sh
Normal file
@@ -0,0 +1,410 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
: "${WIDTH:=""}"
|
||||
: "${HEIGHT:=""}"
|
||||
: "${VERIFY:=""}"
|
||||
: "${REGION:=""}"
|
||||
: "${MANUAL:=""}"
|
||||
: "${REMOVE:=""}"
|
||||
: "${VERSION:=""}"
|
||||
: "${DETECTED:=""}"
|
||||
: "${KEYBOARD:=""}"
|
||||
: "${LANGUAGE:=""}"
|
||||
: "${USERNAME:=""}"
|
||||
: "${PASSWORD:=""}"
|
||||
|
||||
MIRRORS=4
|
||||
PLATFORM="x64"
|
||||
|
||||
parseVersion() {
|
||||
|
||||
if [[ "${VERSION}" == \"*\" || "${VERSION}" == \'*\' ]]; then
|
||||
VERSION="${VERSION:1:-1}"
|
||||
fi
|
||||
|
||||
[ -z "$VERSION" ] && VERSION="win11"
|
||||
|
||||
case "${VERSION,,}" in
|
||||
"11" | "11p" | "win11" | "pro11" | "win11p" | "windows11" | "windows 11" )
|
||||
VERSION="win11x64"
|
||||
;;
|
||||
"11e" | "win11e" | "windows11e" | "windows 11e" | "win11x64-enterprise-eval" )
|
||||
VERSION="win11x64-enterprise-eval"
|
||||
;;
|
||||
esac
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
getLanguage() {
|
||||
|
||||
local id="$1"
|
||||
local ret="$2"
|
||||
local lang=""
|
||||
local desc=""
|
||||
local culture=""
|
||||
|
||||
case "${id,,}" in
|
||||
"ar" | "ar-"* )
|
||||
lang="Arabic"
|
||||
desc="$lang"
|
||||
culture="ar-SA" ;;
|
||||
"bg" | "bg-"* )
|
||||
lang="Bulgarian"
|
||||
desc="$lang"
|
||||
culture="bg-BG" ;;
|
||||
"cs" | "cs-"* | "cz" | "cz-"* )
|
||||
lang="Czech"
|
||||
desc="$lang"
|
||||
culture="cs-CZ" ;;
|
||||
"da" | "da-"* | "dk" | "dk-"* )
|
||||
lang="Danish"
|
||||
desc="$lang"
|
||||
culture="da-DK" ;;
|
||||
"de" | "de-"* )
|
||||
lang="German"
|
||||
desc="$lang"
|
||||
culture="de-DE" ;;
|
||||
"el" | "el-"* | "gr" | "gr-"* )
|
||||
lang="Greek"
|
||||
desc="$lang"
|
||||
culture="el-GR" ;;
|
||||
"gb" | "en-gb" )
|
||||
lang="English International"
|
||||
desc="English"
|
||||
culture="en-GB" ;;
|
||||
"en" | "en-"* )
|
||||
lang="English"
|
||||
desc="English"
|
||||
culture="en-US" ;;
|
||||
"mx" | "es-mx" )
|
||||
lang="Spanish (Mexico)"
|
||||
desc="Spanish"
|
||||
culture="es-MX" ;;
|
||||
"es" | "es-"* )
|
||||
lang="Spanish"
|
||||
desc="$lang"
|
||||
culture="es-ES" ;;
|
||||
"et" | "et-"* )
|
||||
lang="Estonian"
|
||||
desc="$lang"
|
||||
culture="et-EE" ;;
|
||||
"fi" | "fi-"* )
|
||||
lang="Finnish"
|
||||
desc="$lang"
|
||||
culture="fi-FI" ;;
|
||||
"ca" | "fr-ca" )
|
||||
lang="French Canadian"
|
||||
desc="French"
|
||||
culture="fr-CA" ;;
|
||||
"fr" | "fr-"* )
|
||||
lang="French"
|
||||
desc="$lang"
|
||||
culture="fr-FR" ;;
|
||||
"he" | "he-"* | "il" | "il-"* )
|
||||
lang="Hebrew"
|
||||
desc="$lang"
|
||||
culture="he-IL" ;;
|
||||
"hr" | "hr-"* | "cr" | "cr-"* )
|
||||
lang="Croatian"
|
||||
desc="$lang"
|
||||
culture="hr-HR" ;;
|
||||
"hu" | "hu-"* )
|
||||
lang="Hungarian"
|
||||
desc="$lang"
|
||||
culture="hu-HU" ;;
|
||||
"it" | "it-"* )
|
||||
lang="Italian"
|
||||
desc="$lang"
|
||||
culture="it-IT" ;;
|
||||
"ja" | "ja-"* | "jp" | "jp-"* )
|
||||
lang="Japanese"
|
||||
desc="$lang"
|
||||
culture="ja-JP" ;;
|
||||
"ko" | "ko-"* | "kr" | "kr-"* )
|
||||
lang="Korean"
|
||||
desc="$lang"
|
||||
culture="ko-KR" ;;
|
||||
"lt" | "lt-"* )
|
||||
lang="Lithuanian"
|
||||
desc="$lang"
|
||||
culture="lv-LV" ;;
|
||||
"lv" | "lv-"* )
|
||||
lang="Latvian"
|
||||
desc="$lang"
|
||||
culture="lt-LT" ;;
|
||||
"nb" | "nb-"* |"nn" | "nn-"* | "no" | "no-"* )
|
||||
lang="Norwegian"
|
||||
desc="$lang"
|
||||
culture="nb-NO" ;;
|
||||
"nl" | "nl-"* )
|
||||
lang="Dutch"
|
||||
desc="$lang"
|
||||
culture="nl-NL" ;;
|
||||
"pl" | "pl-"* )
|
||||
lang="Polish"
|
||||
desc="$lang"
|
||||
culture="pl-PL" ;;
|
||||
"br" | "pt-br" )
|
||||
lang="Brazilian Portuguese"
|
||||
desc="Portuguese"
|
||||
culture="pt-BR" ;;
|
||||
"pt" | "pt-"* )
|
||||
lang="Portuguese"
|
||||
desc="$lang"
|
||||
culture="pt-BR" ;;
|
||||
"ro" | "ro-"* )
|
||||
lang="Romanian"
|
||||
desc="$lang"
|
||||
culture="ro-RO" ;;
|
||||
"ru" | "ru-"* )
|
||||
lang="Russian"
|
||||
desc="$lang"
|
||||
culture="ru-RU" ;;
|
||||
"sk" | "sk-"* )
|
||||
lang="Slovak"
|
||||
desc="$lang"
|
||||
culture="sk-SK" ;;
|
||||
"sl" | "sl-"* | "si" | "si-"* )
|
||||
lang="Slovenian"
|
||||
desc="$lang"
|
||||
culture="sl-SI" ;;
|
||||
"sr" | "sr-"* )
|
||||
lang="Serbian Latin"
|
||||
desc="Serbian"
|
||||
culture="sr-Latn-RS" ;;
|
||||
"sv" | "sv-"* | "se" | "se-"* )
|
||||
lang="Swedish"
|
||||
desc="$lang"
|
||||
culture="sv-SE" ;;
|
||||
"th" | "th-"* )
|
||||
lang="Thai"
|
||||
desc="$lang"
|
||||
culture="th-TH" ;;
|
||||
"tr" | "tr-"* )
|
||||
lang="Turkish"
|
||||
desc="$lang"
|
||||
culture="tr-TR" ;;
|
||||
"ua" | "ua-"* | "uk" | "uk-"* )
|
||||
lang="Ukrainian"
|
||||
desc="$lang"
|
||||
culture="uk-UA" ;;
|
||||
"hk" | "zh-hk" | "cn-hk" )
|
||||
lang="Chinese (Traditional)"
|
||||
desc="Chinese HK"
|
||||
culture="zh-TW" ;;
|
||||
"tw" | "zh-tw" | "cn-tw" )
|
||||
lang="Chinese (Traditional)"
|
||||
desc="Chinese TW"
|
||||
culture="zh-TW" ;;
|
||||
"zh" | "zh-"* | "cn" | "cn-"* )
|
||||
lang="Chinese (Simplified)"
|
||||
desc="Chinese"
|
||||
culture="zh-CN" ;;
|
||||
esac
|
||||
|
||||
case "${ret,,}" in
|
||||
"desc" ) echo "$desc" ;;
|
||||
"name" ) echo "$lang" ;;
|
||||
"culture" ) echo "$culture" ;;
|
||||
*) echo "$desc";;
|
||||
esac
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
parseLanguage() {
|
||||
|
||||
REGION="${REGION//_/-/}"
|
||||
KEYBOARD="${KEYBOARD//_/-/}"
|
||||
LANGUAGE="${LANGUAGE//_/-/}"
|
||||
|
||||
[ -z "$LANGUAGE" ] && LANGUAGE="en"
|
||||
|
||||
case "${LANGUAGE,,}" in
|
||||
"arabic" | "arab" ) LANGUAGE="ar" ;;
|
||||
"bulgarian" | "bu" ) LANGUAGE="bg" ;;
|
||||
"chinese" | "cn" ) LANGUAGE="zh" ;;
|
||||
"croatian" | "cr" | "hrvatski" ) LANGUAGE="hr" ;;
|
||||
"czech" | "cz" | "cesky" ) LANGUAGE="cs" ;;
|
||||
"danish" | "dk" | "danske" ) LANGUAGE="da" ;;
|
||||
"dutch" | "nederlands" ) LANGUAGE="nl" ;;
|
||||
"english" | "gb" | "british" ) LANGUAGE="en" ;;
|
||||
"estonian" | "eesti" ) LANGUAGE="et" ;;
|
||||
"finnish" | "suomi" ) LANGUAGE="fi" ;;
|
||||
"french" | "français" | "francais" ) LANGUAGE="fr" ;;
|
||||
"german" | "deutsch" ) LANGUAGE="de" ;;
|
||||
"greek" | "gr" ) LANGUAGE="el" ;;
|
||||
"hebrew" | "il" ) LANGUAGE="he" ;;
|
||||
"hungarian" | "magyar" ) LANGUAGE="hu" ;;
|
||||
"italian" | "italiano" ) LANGUAGE="it" ;;
|
||||
"japanese" | "jp" ) LANGUAGE="ja" ;;
|
||||
"korean" | "kr" ) LANGUAGE="ko" ;;
|
||||
"latvian" | "latvijas" ) LANGUAGE="lv" ;;
|
||||
"lithuanian" | "lietuvos" ) LANGUAGE="lt" ;;
|
||||
"norwegian" | "no" | "nb" | "norsk" ) LANGUAGE="nn" ;;
|
||||
"polish" | "polski" ) LANGUAGE="pl" ;;
|
||||
"portuguese" | "pt" | "br" ) LANGUAGE="pt-br" ;;
|
||||
"português" | "portugues" ) LANGUAGE="pt-br" ;;
|
||||
"romanian" | "română" | "romana" ) LANGUAGE="ro" ;;
|
||||
"russian" | "ruski" ) LANGUAGE="ru" ;;
|
||||
"serbian" | "serbian latin" ) LANGUAGE="sr" ;;
|
||||
"slovak" | "slovenský" | "slovensky" ) LANGUAGE="sk" ;;
|
||||
"slovenian" | "si" | "slovenski" ) LANGUAGE="sl" ;;
|
||||
"spanish" | "espanol" | "español" ) LANGUAGE="es" ;;
|
||||
"swedish" | "se" | "svenska" ) LANGUAGE="sv" ;;
|
||||
"turkish" | "türk" | "turk" ) LANGUAGE="tr" ;;
|
||||
"thai" ) LANGUAGE="th" ;;
|
||||
"ukrainian" | "ua" ) LANGUAGE="uk" ;;
|
||||
esac
|
||||
|
||||
local culture
|
||||
culture=$(getLanguage "$LANGUAGE" "culture")
|
||||
[ -n "$culture" ] && return 0
|
||||
|
||||
error "Invalid LANGUAGE specified, value \"$LANGUAGE\" is not recognized!"
|
||||
return 1
|
||||
}
|
||||
|
||||
printVersion() {
|
||||
|
||||
local id="$1"
|
||||
local desc="$2"
|
||||
|
||||
case "${id,,}" in
|
||||
"win11"* ) desc="Windows 11" ;;
|
||||
esac
|
||||
|
||||
if [ -z "$desc" ]; then
|
||||
desc="Windows"
|
||||
[[ "${PLATFORM,,}" != "x64" ]] && desc+=" for ${PLATFORM}"
|
||||
fi
|
||||
|
||||
echo "$desc"
|
||||
return 0
|
||||
}
|
||||
|
||||
printEdition() {
|
||||
|
||||
local id="$1"
|
||||
local desc="$2"
|
||||
local result=""
|
||||
local edition=""
|
||||
|
||||
result=$(printVersion "$id" "x")
|
||||
[[ "$result" == "x" ]] && echo "$desc" && return 0
|
||||
|
||||
case "${id,,}" in
|
||||
*"-enterprise" )
|
||||
edition="Enterprise"
|
||||
;;
|
||||
*"-enterprise-eval" )
|
||||
edition="Enterprise (Evaluation)"
|
||||
;;
|
||||
esac
|
||||
|
||||
[ -n "$edition" ] && result+=" $edition"
|
||||
|
||||
echo "$result"
|
||||
return 0
|
||||
}
|
||||
|
||||
fromName() {
|
||||
|
||||
local id=""
|
||||
local name="$1"
|
||||
local arch="$2"
|
||||
|
||||
local add=""
|
||||
[[ "$arch" != "x64" ]] && add="$arch"
|
||||
|
||||
case "${name,,}" in
|
||||
*"windows 11"* ) id="win11${arch}" ;;
|
||||
esac
|
||||
|
||||
echo "$id"
|
||||
return 0
|
||||
}
|
||||
|
||||
getVersion() {
|
||||
|
||||
local id
|
||||
local name="$1"
|
||||
local arch="$2"
|
||||
|
||||
id=$(fromName "$name" "$arch")
|
||||
|
||||
case "${id,,}" in
|
||||
"win11"* )
|
||||
case "${name,,}" in
|
||||
*" enterprise evaluation"* ) id="$id-enterprise-eval" ;;
|
||||
*" enterprise"* ) id="$id-enterprise" ;;
|
||||
esac
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "$id"
|
||||
return 0
|
||||
}
|
||||
|
||||
addFolder() {
|
||||
|
||||
local src="$1"
|
||||
local folder="/oem"
|
||||
|
||||
[ ! -d "$folder" ] && folder="/OEM"
|
||||
[ ! -d "$folder" ] && folder="$STORAGE/oem"
|
||||
[ ! -d "$folder" ] && folder="$STORAGE/OEM"
|
||||
[ ! -d "$folder" ] && return 0
|
||||
|
||||
local msg="Adding OEM folder to image..."
|
||||
info "$msg" && html "$msg"
|
||||
|
||||
local dest="$src/\$OEM\$/\$1/OEM"
|
||||
mkdir -p "$dest" || return 1
|
||||
cp -Lr "$folder/." "$dest" || return 1
|
||||
|
||||
local file
|
||||
file=$(find "$dest" -maxdepth 1 -type f -iname install.bat | head -n 1)
|
||||
[ -f "$file" ] && unix2dos -q "$file"
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# migrateFiles() {
|
||||
|
||||
# local base="$1"
|
||||
# local version="$2"
|
||||
# local file=""
|
||||
|
||||
# [ -f "$base" ] && return 0
|
||||
|
||||
# [[ "${version,,}" == "tiny10" ]] && file="tiny10_x64_23h2.iso"
|
||||
# [[ "${version,,}" == "tiny11" ]] && file="tiny11_2311_x64.iso"
|
||||
# [[ "${version,,}" == "core11" ]] && file="tiny11_core_x64_beta_1.iso"
|
||||
# [[ "${version,,}" == "winxpx86" ]] && file="en_windows_xp_professional_with_service_pack_3_x86_cd_x14-80428.iso"
|
||||
# [[ "${version,,}" == "winvistax64" ]] && file="en_windows_vista_sp2_x64_dvd_342267.iso"
|
||||
# [[ "${version,,}" == "win7x64" ]] && file="en_windows_7_enterprise_with_sp1_x64_dvd_u_677651.iso"
|
||||
|
||||
# [ ! -f "$STORAGE/$file" ] && return 0
|
||||
# mv -f "$STORAGE/$file" "$base" || return 1
|
||||
|
||||
# return 0
|
||||
# }
|
||||
|
||||
migrateFiles() {
|
||||
|
||||
local base="$1"
|
||||
local version="$2"
|
||||
local file=""
|
||||
|
||||
[ -f "$base" ] && return 0
|
||||
|
||||
[ ! -f "$STORAGE/$file" ] && return 0
|
||||
mv -f "$STORAGE/$file" "$base" || return 1
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
return 0
|
||||
38
omnitool/omnibox/vm/buildcontainer/entry.sh
Normal file
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
: "${BOOT_MODE:="windows"}"
|
||||
|
||||
APP="OmniParser Windows"
|
||||
SUPPORT="https://github.com/microsoft/OmniParser"
|
||||
|
||||
cd /run
|
||||
|
||||
. reset.sh # Initialize system
|
||||
. define.sh # Define versions
|
||||
. install.sh # Run installation
|
||||
. disk.sh # Initialize disks
|
||||
. display.sh # Initialize graphics
|
||||
. network.sh # Initialize network
|
||||
. samba.sh # Configure samba
|
||||
. boot.sh # Configure boot
|
||||
. proc.sh # Initialize processor
|
||||
. power.sh # Configure shutdown
|
||||
. config.sh # Configure arguments
|
||||
|
||||
trap - ERR
|
||||
|
||||
version=$(qemu-system-x86_64 --version | head -n 1 | cut -d '(' -f 1 | awk '{ print $NF }')
|
||||
info "Booting ${APP}${BOOT_DESC} using QEMU v$version..."
|
||||
|
||||
{ qemu-system-x86_64 ${ARGS:+ $ARGS} >"$QEMU_OUT" 2>"$QEMU_LOG"; rc=$?; } || :
|
||||
(( rc != 0 )) && error "$(<"$QEMU_LOG")" && exit 15
|
||||
|
||||
terminal
|
||||
( sleep 30; boot ) &
|
||||
tail -fn +0 "$QEMU_LOG" 2>/dev/null &
|
||||
cat "$QEMU_TERM" 2> /dev/null | tee "$QEMU_PTY" &
|
||||
wait $! || :
|
||||
|
||||
sleep 1 & wait $!
|
||||
[ ! -f "$QEMU_END" ] && finish 0
|
||||
1024
omnitool/omnibox/vm/buildcontainer/install.sh
Normal file
223
omnitool/omnibox/vm/buildcontainer/power.sh
Normal file
@@ -0,0 +1,223 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
# Configure QEMU for graceful shutdown
|
||||
|
||||
QEMU_TERM=""
|
||||
QEMU_PORT=7100
|
||||
QEMU_TIMEOUT=110
|
||||
QEMU_DIR="/run/shm"
|
||||
QEMU_PID="$QEMU_DIR/qemu.pid"
|
||||
QEMU_PTY="$QEMU_DIR/qemu.pty"
|
||||
QEMU_LOG="$QEMU_DIR/qemu.log"
|
||||
QEMU_OUT="$QEMU_DIR/qemu.out"
|
||||
QEMU_END="$QEMU_DIR/qemu.end"
|
||||
|
||||
rm -f "$QEMU_DIR/qemu.*"
|
||||
touch "$QEMU_LOG"
|
||||
|
||||
_trap() {
|
||||
func="$1" ; shift
|
||||
for sig ; do
|
||||
trap "$func $sig" "$sig"
|
||||
done
|
||||
}
|
||||
|
||||
boot() {
|
||||
|
||||
[ -f "$QEMU_END" ] && return 0
|
||||
|
||||
if [ -s "$QEMU_PTY" ]; then
|
||||
if [ "$(stat -c%s "$QEMU_PTY")" -gt 7 ]; then
|
||||
local fail=""
|
||||
if [[ "${BOOT_MODE,,}" == "windows_legacy" ]]; then
|
||||
grep -Fq "No bootable device." "$QEMU_PTY" && fail="y"
|
||||
grep -Fq "BOOTMGR is missing" "$QEMU_PTY" && fail="y"
|
||||
fi
|
||||
if [ -z "$fail" ]; then
|
||||
info "Windows has started successfully. You can directly view the VM at http://localhost:8006/vnc.html?view_only=1&autoconnect=1&resize=scale. Wait until setup is complete before interacting manually."
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
error "Timeout while waiting for QEMU to boot the machine!"
|
||||
|
||||
local pid
|
||||
pid=$(<"$QEMU_PID")
|
||||
{ kill -15 "$pid" || true; } 2>/dev/null
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
ready() {
|
||||
|
||||
[ -f "$STORAGE/windows.boot" ] && return 0
|
||||
[ ! -s "$QEMU_PTY" ] && return 1
|
||||
|
||||
if [[ "${BOOT_MODE,,}" == "windows_legacy" ]]; then
|
||||
local last
|
||||
local bios="Booting from Hard"
|
||||
last=$(grep "^Booting.*" "$QEMU_PTY" | tail -1)
|
||||
[[ "${last,,}" != "${bios,,}"* ]] && return 1
|
||||
grep -Fq "No bootable device." "$QEMU_PTY" && return 1
|
||||
grep -Fq "BOOTMGR is missing" "$QEMU_PTY" && return 1
|
||||
return 0
|
||||
fi
|
||||
|
||||
local line="\"Windows Boot Manager\""
|
||||
grep -Fq "$line" "$QEMU_PTY" && return 0
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
finish() {
|
||||
|
||||
local pid
|
||||
local reason=$1
|
||||
|
||||
touch "$QEMU_END"
|
||||
|
||||
if [ -s "$QEMU_PID" ]; then
|
||||
|
||||
pid=$(<"$QEMU_PID")
|
||||
error "Forcefully terminating Windows, reason: $reason..."
|
||||
{ kill -15 "$pid" || true; } 2>/dev/null
|
||||
|
||||
while isAlive "$pid"; do
|
||||
sleep 1
|
||||
# Workaround for zombie pid
|
||||
[ ! -s "$QEMU_PID" ] && break
|
||||
done
|
||||
fi
|
||||
|
||||
if [ ! -f "$STORAGE/windows.boot" ] && [ -f "$BOOT" ]; then
|
||||
# Remove CD-ROM ISO after install
|
||||
if ready; then
|
||||
touch "$STORAGE/windows.boot"
|
||||
if [[ "$REMOVE" != [Nn]* ]]; then
|
||||
rm -f "$BOOT" 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
pid="/var/run/tpm.pid"
|
||||
[ -s "$pid" ] && pKill "$(<"$pid")"
|
||||
|
||||
pid="/var/run/wsdd.pid"
|
||||
[ -s "$pid" ] && pKill "$(<"$pid")"
|
||||
|
||||
fKill "smbd"
|
||||
|
||||
closeNetwork
|
||||
|
||||
sleep 0.5
|
||||
echo "❯ Shutdown completed!"
|
||||
|
||||
exit "$reason"
|
||||
}
|
||||
|
||||
terminal() {
|
||||
|
||||
local dev=""
|
||||
|
||||
if [ -s "$QEMU_OUT" ]; then
|
||||
|
||||
local msg
|
||||
msg=$(<"$QEMU_OUT")
|
||||
|
||||
if [ -n "$msg" ]; then
|
||||
|
||||
if [[ "${msg,,}" != "char"* || "$msg" != *"serial0)" ]]; then
|
||||
echo "$msg"
|
||||
fi
|
||||
|
||||
dev="${msg#*/dev/p}"
|
||||
dev="/dev/p${dev%% *}"
|
||||
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ ! -c "$dev" ]; then
|
||||
dev=$(echo 'info chardev' | nc -q 1 -w 1 localhost "$QEMU_PORT" | tr -d '\000')
|
||||
dev="${dev#*serial0}"
|
||||
dev="${dev#*pty:}"
|
||||
dev="${dev%%$'\n'*}"
|
||||
dev="${dev%%$'\r'*}"
|
||||
fi
|
||||
|
||||
if [ ! -c "$dev" ]; then
|
||||
error "Device '$dev' not found!"
|
||||
finish 34 && return 34
|
||||
fi
|
||||
|
||||
QEMU_TERM="$dev"
|
||||
return 0
|
||||
}
|
||||
|
||||
_graceful_shutdown() {
|
||||
|
||||
local code=$?
|
||||
|
||||
set +e
|
||||
|
||||
if [ -f "$QEMU_END" ]; then
|
||||
info "Received $1 while already shutting down..."
|
||||
return
|
||||
fi
|
||||
|
||||
touch "$QEMU_END"
|
||||
info "Received $1, sending ACPI shutdown signal..."
|
||||
|
||||
if [ ! -s "$QEMU_PID" ]; then
|
||||
error "QEMU PID file does not exist?"
|
||||
finish "$code" && return "$code"
|
||||
fi
|
||||
|
||||
local pid=""
|
||||
pid=$(<"$QEMU_PID")
|
||||
|
||||
if ! isAlive "$pid"; then
|
||||
error "QEMU process does not exist?"
|
||||
finish "$code" && return "$code"
|
||||
fi
|
||||
|
||||
if ! ready; then
|
||||
info "Cannot send ACPI signal during Windows setup, aborting..."
|
||||
finish "$code" && return "$code"
|
||||
fi
|
||||
|
||||
# Send ACPI shutdown signal
|
||||
echo 'system_powerdown' | nc -q 1 -w 1 localhost "${QEMU_PORT}" > /dev/null
|
||||
|
||||
local cnt=0
|
||||
while [ "$cnt" -lt "$QEMU_TIMEOUT" ]; do
|
||||
|
||||
sleep 1
|
||||
cnt=$((cnt+1))
|
||||
|
||||
! isAlive "$pid" && break
|
||||
# Workaround for zombie pid
|
||||
[ ! -s "$QEMU_PID" ] && break
|
||||
|
||||
info "Waiting for Windows to shutdown... ($cnt/$QEMU_TIMEOUT)"
|
||||
|
||||
# Send ACPI shutdown signal
|
||||
echo 'system_powerdown' | nc -q 1 -w 1 localhost "${QEMU_PORT}" > /dev/null
|
||||
|
||||
done
|
||||
|
||||
if [ "$cnt" -ge "$QEMU_TIMEOUT" ]; then
|
||||
error "Shutdown timeout reached, aborting..."
|
||||
fi
|
||||
|
||||
finish "$code" && return "$code"
|
||||
}
|
||||
|
||||
SERIAL="pty"
|
||||
MONITOR="telnet:localhost:$QEMU_PORT,server,nowait,nodelay"
|
||||
MONITOR+=" -daemonize -D $QEMU_LOG -pidfile $QEMU_PID"
|
||||
|
||||
_trap _graceful_shutdown SIGTERM SIGHUP SIGINT SIGABRT SIGQUIT
|
||||
|
||||
return 0
|
||||
109
omnitool/omnibox/vm/buildcontainer/samba.sh
Normal file
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env bash
|
||||
set -Eeuo pipefail
|
||||
|
||||
: "${SAMBA:="Y"}"
|
||||
|
||||
[[ "$SAMBA" == [Nn]* ]] && return 0
|
||||
[[ "$NETWORK" == [Nn]* ]] && return 0
|
||||
|
||||
hostname="host.lan"
|
||||
interface="dockerbridge"
|
||||
|
||||
if [[ "$DHCP" == [Yy1]* ]]; then
|
||||
hostname="$IP"
|
||||
interface="$VM_NET_DEV"
|
||||
fi
|
||||
|
||||
addShare() {
|
||||
local dir="$1"
|
||||
local name="$2"
|
||||
local comment="$3"
|
||||
|
||||
mkdir -p "$dir" || return 1
|
||||
|
||||
if [ -z "$(ls -A "$dir")" ]; then
|
||||
|
||||
chmod 777 "$dir"
|
||||
|
||||
{ echo "--------------------------------------------------------"
|
||||
echo " $APP"
|
||||
echo " For support visit $SUPPORT"
|
||||
echo "--------------------------------------------------------"
|
||||
echo ""
|
||||
echo "Using this folder you can share files with the host machine."
|
||||
echo ""
|
||||
echo "To change its location, include the following bind mount in your compose file:"
|
||||
echo ""
|
||||
echo " volumes:"
|
||||
echo " - \"/home/example:/${name,,}\""
|
||||
echo ""
|
||||
echo "Or in your run command:"
|
||||
echo ""
|
||||
echo " -v \"/home/example:/${name,,}\""
|
||||
echo ""
|
||||
echo "Replace the example path /home/example with the desired shared folder."
|
||||
echo ""
|
||||
} | unix2dos > "$dir/readme.txt"
|
||||
|
||||
fi
|
||||
|
||||
{ echo ""
|
||||
echo "[$name]"
|
||||
echo " path = $dir"
|
||||
echo " comment = $comment"
|
||||
echo " writable = yes"
|
||||
echo " guest ok = yes"
|
||||
echo " guest only = yes"
|
||||
echo " force user = root"
|
||||
echo " force group = root"
|
||||
} >> "/etc/samba/smb.conf"
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
{ echo "[global]"
|
||||
echo " server string = Dockur"
|
||||
echo " netbios name = $hostname"
|
||||
echo " workgroup = WORKGROUP"
|
||||
echo " interfaces = $interface"
|
||||
echo " bind interfaces only = yes"
|
||||
echo " security = user"
|
||||
echo " guest account = nobody"
|
||||
echo " map to guest = Bad User"
|
||||
echo " server min protocol = NT1"
|
||||
echo ""
|
||||
echo " # disable printing services"
|
||||
echo " load printers = no"
|
||||
echo " printing = bsd"
|
||||
echo " printcap name = /dev/null"
|
||||
echo " disable spoolss = yes"
|
||||
} > "/etc/samba/smb.conf"
|
||||
|
||||
share="/data"
|
||||
[ ! -d "$share" ] && [ -d "$STORAGE/data" ] && share="$STORAGE/data"
|
||||
[ ! -d "$share" ] && [ -d "/shared" ] && share="/shared"
|
||||
[ ! -d "$share" ] && [ -d "$STORAGE/shared" ] && share="$STORAGE/shared"
|
||||
|
||||
addShare "$share" "Data" "Shared" || error "Failed to create shared folder!"
|
||||
|
||||
[ -d "/data2" ] && addShare "/data2" "Data2" "Shared"
|
||||
[ -d "/data3" ] && addShare "/data3" "Data3" "Shared"
|
||||
|
||||
if ! smbd; then
|
||||
error "Samba daemon failed to start!"
|
||||
smbd -i --debug-stdout || true
|
||||
fi
|
||||
|
||||
if [[ "${BOOT_MODE:-}" == "windows_legacy" ]]; then
|
||||
# Enable NetBIOS on Windows 7 and lower
|
||||
if ! nmbd; then
|
||||
error "NetBIOS daemon failed to start!"
|
||||
nmbd -i --debug-stdout || true
|
||||
fi
|
||||
else
|
||||
# Enable Web Service Discovery on Vista and up
|
||||
wsdd -i "$interface" -p -n "$hostname" &
|
||||
echo "$!" > /var/run/wsdd.pid
|
||||
fi
|
||||
|
||||
return 0
|
||||
462
omnitool/omnibox/vm/win11def/win11x64-enterprise-eval.xml
Normal file
@@ -0,0 +1,462 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<unattend xmlns="urn:schemas-microsoft-com:unattend" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State">
|
||||
<settings pass="windowsPE">
|
||||
<component name="Microsoft-Windows-International-Core-WinPE" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<SetupUILanguage>
|
||||
<UILanguage>en-US</UILanguage>
|
||||
</SetupUILanguage>
|
||||
<InputLocale>0409:00000409</InputLocale>
|
||||
<SystemLocale>en-US</SystemLocale>
|
||||
<UILanguage>en-US</UILanguage>
|
||||
<UserLocale>en-US</UserLocale>
|
||||
</component>
|
||||
<component name="Microsoft-Windows-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<DiskConfiguration>
|
||||
<Disk wcm:action="add">
|
||||
<DiskID>0</DiskID>
|
||||
<WillWipeDisk>true</WillWipeDisk>
|
||||
<CreatePartitions>
|
||||
<!-- System partition (ESP) -->
|
||||
<CreatePartition wcm:action="add">
|
||||
<Order>1</Order>
|
||||
<Type>EFI</Type>
|
||||
<Size>128</Size>
|
||||
</CreatePartition>
|
||||
<!-- Microsoft reserved partition (MSR) -->
|
||||
<CreatePartition wcm:action="add">
|
||||
<Order>2</Order>
|
||||
<Type>MSR</Type>
|
||||
<Size>128</Size>
|
||||
</CreatePartition>
|
||||
<!-- Windows partition -->
|
||||
<CreatePartition wcm:action="add">
|
||||
<Order>3</Order>
|
||||
<Type>Primary</Type>
|
||||
<Extend>true</Extend>
|
||||
</CreatePartition>
|
||||
</CreatePartitions>
|
||||
<ModifyPartitions>
|
||||
<!-- System partition (ESP) -->
|
||||
<ModifyPartition wcm:action="add">
|
||||
<Order>1</Order>
|
||||
<PartitionID>1</PartitionID>
|
||||
<Label>System</Label>
|
||||
<Format>FAT32</Format>
|
||||
</ModifyPartition>
|
||||
<!-- MSR partition does not need to be modified -->
|
||||
<ModifyPartition wcm:action="add">
|
||||
<Order>2</Order>
|
||||
<PartitionID>2</PartitionID>
|
||||
</ModifyPartition>
|
||||
<!-- Windows partition -->
|
||||
<ModifyPartition wcm:action="add">
|
||||
<Order>3</Order>
|
||||
<PartitionID>3</PartitionID>
|
||||
<Label>Windows</Label>
|
||||
<Letter>C</Letter>
|
||||
<Format>NTFS</Format>
|
||||
</ModifyPartition>
|
||||
</ModifyPartitions>
|
||||
</Disk>
|
||||
</DiskConfiguration>
|
||||
<ImageInstall>
|
||||
<OSImage>
|
||||
<InstallTo>
|
||||
<DiskID>0</DiskID>
|
||||
<PartitionID>3</PartitionID>
|
||||
</InstallTo>
|
||||
<InstallToAvailablePartition>false</InstallToAvailablePartition>
|
||||
</OSImage>
|
||||
</ImageInstall>
|
||||
<DynamicUpdate>
|
||||
<Enable>true</Enable>
|
||||
<WillShowUI>Never</WillShowUI>
|
||||
</DynamicUpdate>
|
||||
<UpgradeData>
|
||||
<Upgrade>false</Upgrade>
|
||||
<WillShowUI>Never</WillShowUI>
|
||||
</UpgradeData>
|
||||
<UserData>
|
||||
<AcceptEula>true</AcceptEula>
|
||||
<FullName>Docker</FullName>
|
||||
<Organization>Windows for Docker</Organization>
|
||||
</UserData>
|
||||
<EnableFirewall>false</EnableFirewall>
|
||||
<Diagnostics>
|
||||
<OptIn>false</OptIn>
|
||||
</Diagnostics>
|
||||
<RunSynchronous>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>1</Order>
|
||||
<Path>reg.exe add "HKLM\SYSTEM\Setup\LabConfig" /v BypassTPMCheck /t REG_DWORD /d 1 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>2</Order>
|
||||
<Path>reg.exe add "HKLM\SYSTEM\Setup\LabConfig" /v BypassSecureBootCheck /t REG_DWORD /d 1 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>3</Order>
|
||||
<Path>reg.exe add "HKLM\SYSTEM\Setup\LabConfig" /v BypassRAMCheck /t REG_DWORD /d 1 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>4</Order>
|
||||
<Path>reg.exe add "HKLM\SYSTEM\Setup\MoSetup" /v AllowUpgradesWithUnsupportedTPMOrCPU /t REG_DWORD /d 1 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
</RunSynchronous>
|
||||
</component>
|
||||
</settings>
|
||||
<settings pass="offlineServicing">
|
||||
<component name="Microsoft-Windows-LUA-Settings" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<EnableLUA>false</EnableLUA>
|
||||
</component>
|
||||
</settings>
|
||||
<settings pass="generalize">
|
||||
<component name="Microsoft-Windows-PnPSysprep" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<PersistAllDeviceInstalls>true</PersistAllDeviceInstalls>
|
||||
</component>
|
||||
<component name="Microsoft-Windows-Security-SPP" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<SkipRearm>1</SkipRearm>
|
||||
</component>
|
||||
</settings>
|
||||
<settings pass="specialize">
|
||||
<component name="Microsoft-Windows-Security-SPP-UX" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<SkipAutoActivation>true</SkipAutoActivation>
|
||||
</component>
|
||||
<component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<ComputerName>*</ComputerName>
|
||||
<OEMInformation>
|
||||
<Manufacturer>Dockur</Manufacturer>
|
||||
<Model>Windows for Docker</Model>
|
||||
<SupportHours>24/7</SupportHours>
|
||||
<SupportPhone />
|
||||
<SupportProvider>Dockur</SupportProvider>
|
||||
<SupportURL>https://github.com/dockur/windows/issues</SupportURL>
|
||||
</OEMInformation>
|
||||
<OEMName>Windows for Docker</OEMName>
|
||||
</component>
|
||||
<component name="Microsoft-Windows-ErrorReportingCore" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<DisableWER>1</DisableWER>
|
||||
</component>
|
||||
<component name="Microsoft-Windows-IE-InternetExplorer" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<DisableAccelerators>true</DisableAccelerators>
|
||||
<DisableFirstRunWizard>true</DisableFirstRunWizard>
|
||||
<Home_Page>https://google.com</Home_Page>
|
||||
<Help_Page>about:blank</Help_Page>
|
||||
</component>
|
||||
<component name="Microsoft-Windows-IE-InternetExplorer" processorArchitecture="wow64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<DisableAccelerators>true</DisableAccelerators>
|
||||
<DisableFirstRunWizard>true</DisableFirstRunWizard>
|
||||
<Home_Page>https://google.com</Home_Page>
|
||||
<Help_Page>about:blank</Help_Page>
|
||||
</component>
|
||||
<component name="Microsoft-Windows-SQMApi" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<CEIPEnabled>0</CEIPEnabled>
|
||||
</component>
|
||||
<component name="Microsoft-Windows-SystemRestore-Main" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<DisableSR>1</DisableSR>
|
||||
</component>
|
||||
<component name="Microsoft-Windows-International-Core" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<InputLocale>0409:00000409</InputLocale>
|
||||
<SystemLocale>en-US</SystemLocale>
|
||||
<UILanguage>en-US</UILanguage>
|
||||
<UserLocale>en-US</UserLocale>
|
||||
</component>
|
||||
<component name="Microsoft-Windows-Deployment" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<RunSynchronous>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>1</Order>
|
||||
<Path>reg.exe add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\OOBE" /v BypassNRO /t REG_DWORD /d 1 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>2</Order>
|
||||
<Path>reg.exe load "HKU\mount" "C:\Users\Default\NTUSER.DAT"</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>3</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /v "ContentDeliveryAllowed" /t REG_DWORD /d 0 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>4</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /v "FeatureManagementEnabled" /t REG_DWORD /d 0 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>5</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /v "OEMPreInstalledAppsEnabled" /t REG_DWORD /d 0 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>6</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /v "PreInstalledAppsEnabled" /t REG_DWORD /d 0 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>7</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /v "PreInstalledAppsEverEnabled" /t REG_DWORD /d 0 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>8</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /v "SilentInstalledAppsEnabled" /t REG_DWORD /d 0 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>9</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /v "SoftLandingEnabled" /t REG_DWORD /d 0 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>10</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /v "SubscribedContentEnabled" /t REG_DWORD /d 0 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>11</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /v "SubscribedContent-310093Enabled" /t REG_DWORD /d 0 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>12</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /v "SubscribedContent-338387Enabled" /t REG_DWORD /d 0 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>13</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /v "SubscribedContent-338388Enabled" /t REG_DWORD /d 0 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>14</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /v "SubscribedContent-338389Enabled" /t REG_DWORD /d 0 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>15</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /v "SubscribedContent-338393Enabled" /t REG_DWORD /d 0 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>16</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /v "SubscribedContent-353698Enabled" /t REG_DWORD /d 0 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>17</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Microsoft\Windows\CurrentVersion\ContentDeliveryManager" /v "SystemPaneSuggestionsEnabled" /t REG_DWORD /d 0 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>18</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Policies\Microsoft\Windows\CloudContent" /v "DisableCloudOptimizedContent" /t REG_DWORD /d 1 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>19</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Policies\Microsoft\Windows\CloudContent" /v "DisableWindowsConsumerFeatures" /t REG_DWORD /d 1 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>20</Order>
|
||||
<Path>reg.exe add "HKU\mount\Software\Policies\Microsoft\Windows\CloudContent" /v "DisableConsumerAccountStateContent" /t REG_DWORD /d 1 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>21</Order>
|
||||
<Path>reg.exe unload "HKU\mount"</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>22</Order>
|
||||
<Path>reg.exe add "HKLM\Software\Policies\Microsoft\Windows\CloudContent" /v "DisableCloudOptimizedContent" /t REG_DWORD /d 1 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>23</Order>
|
||||
<Path>reg.exe add "HKLM\Software\Policies\Microsoft\Windows\CloudContent" /v "DisableWindowsConsumerFeatures" /t REG_DWORD /d 1 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>24</Order>
|
||||
<Path>reg.exe add "HKLM\Software\Policies\Microsoft\Windows\CloudContent" /v "DisableConsumerAccountStateContent" /t REG_DWORD /d 1 /f</Path>
|
||||
</RunSynchronousCommand>
|
||||
<RunSynchronousCommand wcm:action="add">
|
||||
<Order>25</Order>
|
||||
<Path>reg.exe add "HKLM\SOFTWARE\Policies\Microsoft\Windows NT\CurrentVersion\NetworkList\Signatures\FirstNetwork" /v Category /t REG_DWORD /d 1 /f</Path>
|
||||
<Description>Set Network Location to Home</Description>
|
||||
</RunSynchronousCommand>
|
||||
</RunSynchronous>
|
||||
</component>
|
||||
<component name="Microsoft-Windows-TerminalServices-LocalSessionManager" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<fDenyTSConnections>false</fDenyTSConnections>
|
||||
</component>
|
||||
<component name="Microsoft-Windows-TerminalServices-RDP-WinStationExtensions" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<UserAuthentication>0</UserAuthentication>
|
||||
</component>
|
||||
<component name="Networking-MPSSVC-Svc" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<FirewallGroups>
|
||||
<FirewallGroup wcm:action="add" wcm:keyValue="RemoteDesktop">
|
||||
<Active>true</Active>
|
||||
<Profile>all</Profile>
|
||||
<Group>@FirewallAPI.dll,-28752</Group>
|
||||
</FirewallGroup>
|
||||
</FirewallGroups>
|
||||
</component>
|
||||
</settings>
|
||||
<settings pass="auditSystem" />
|
||||
<settings pass="auditUser" />
|
||||
<settings pass="oobeSystem">
|
||||
<component name="Microsoft-Windows-SecureStartup-FilterDriver" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<PreventDeviceEncryption>true</PreventDeviceEncryption>
|
||||
</component>
|
||||
<component name="Microsoft-Windows-EnhancedStorage-Adm" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<TCGSecurityActivationDisabled>1</TCGSecurityActivationDisabled>
|
||||
</component>
|
||||
<component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
|
||||
<UserAccounts>
|
||||
<LocalAccounts>
|
||||
<LocalAccount wcm:action="add">
|
||||
<Name>Docker</Name>
|
||||
<Group>Administrators</Group>
|
||||
<Password>
|
||||
<Value />
|
||||
<PlainText>true</PlainText>
|
||||
</Password>
|
||||
</LocalAccount>
|
||||
</LocalAccounts>
|
||||
<AdministratorPassword>
|
||||
<Value>password</Value>
|
||||
<PlainText>true</PlainText>
|
||||
</AdministratorPassword>
|
||||
</UserAccounts>
|
||||
<AutoLogon>
|
||||
<Username>Docker</Username>
|
||||
<Enabled>true</Enabled>
|
||||
<LogonCount>65432</LogonCount>
|
||||
<Password>
|
||||
<Value />
|
||||
<PlainText>true</PlainText>
|
||||
</Password>
|
||||
</AutoLogon>
|
||||
<Display>
|
||||
<ColorDepth>32</ColorDepth>
|
||||
<HorizontalResolution>1920</HorizontalResolution>
|
||||
<VerticalResolution>1080</VerticalResolution>
|
||||
</Display>
|
||||
<OOBE>
|
||||
<HideEULAPage>true</HideEULAPage>
|
||||
<HideLocalAccountScreen>true</HideLocalAccountScreen>
|
||||
<HideOEMRegistrationScreen>true</HideOEMRegistrationScreen>
|
||||
<HideOnlineAccountScreens>true</HideOnlineAccountScreens>
|
||||
<HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE>
|
||||
<NetworkLocation>Home</NetworkLocation>
|
||||
<ProtectYourPC>3</ProtectYourPC>
|
||||
<SkipUserOOBE>true</SkipUserOOBE>
|
||||
<SkipMachineOOBE>true</SkipMachineOOBE>
|
||||
</OOBE>
|
||||
<RegisteredOrganization>Dockur</RegisteredOrganization>
|
||||
<RegisteredOwner>Windows for Docker</RegisteredOwner>
|
||||
<FirstLogonCommands>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>1</Order>
|
||||
<CommandLine>reg.exe add "HKLM\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters" /v "AllowInsecureGuestAuth" /t REG_DWORD /d 1 /f</CommandLine>
|
||||
<Description>Allow guest access to network shares</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>2</Order>
|
||||
<CommandLine>reg.exe add "HKLM\SYSTEM\CurrentControlSet\Services\LanmanWorkstation\Parameters" /v "RequireSecuritySignature" /t REG_DWORD /d 0 /f</CommandLine>
|
||||
<Description>Disable SMB signing requirement</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>3</Order>
|
||||
<CommandLine>reg.exe add "HKLM\SYSTEM\CurrentControlSet\Control\Lsa" /v LimitBlankPasswordUse /t REG_DWORD /d 0 /f</CommandLine>
|
||||
<Description>Allow RDP login with blank password</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>4</Order>
|
||||
<CommandLine>reg.exe add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\PasswordLess\Device" /v "DevicePasswordLessBuildVersion" /t REG_DWORD /d 0 /f</CommandLine>
|
||||
<Description>Enable option for passwordless sign-in</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>5</Order>
|
||||
<CommandLine>cmd /C wmic useraccount where name="Docker" set PasswordExpires=false</CommandLine>
|
||||
<Description>Password Never Expires</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>6</Order>
|
||||
<CommandLine>cmd /C POWERCFG -H OFF</CommandLine>
|
||||
<Description>Disable Hibernation</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>7</Order>
|
||||
<CommandLine>cmd /C POWERCFG -X -monitor-timeout-ac 0</CommandLine>
|
||||
<Description>Disable monitor blanking</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>8</Order>
|
||||
<CommandLine>reg.exe add "HKLM\SOFTWARE\Policies\Microsoft\Edge" /v "HideFirstRunExperience" /t REG_DWORD /d 1 /f</CommandLine>
|
||||
<Description>Disable first-run experience in Edge</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>9</Order>
|
||||
<CommandLine>reg.exe add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced" /v "HideFileExt" /t REG_DWORD /d 0 /f</CommandLine>
|
||||
<Description>Show file extensions in Explorer</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>10</Order>
|
||||
<CommandLine>reg.exe add "HKLM\SYSTEM\CurrentControlSet\Control\Power" /v "HibernateFileSizePercent" /t REG_DWORD /d 0 /f</CommandLine>
|
||||
<Description>Zero Hibernation File</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>11</Order>
|
||||
<CommandLine>reg.exe add "HKLM\SYSTEM\CurrentControlSet\Control\Power" /v "HibernateEnabled" /t REG_DWORD /d 0 /f</CommandLine>
|
||||
<Description>Disable Hibernation</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>12</Order>
|
||||
<CommandLine>cmd /C POWERCFG -X -standby-timeout-ac 0</CommandLine>
|
||||
<Description>Disable Sleep</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>13</Order>
|
||||
<CommandLine>reg.exe add "HKLM\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services" /v "fAllowUnlistedRemotePrograms" /t REG_DWORD /d 1 /f</CommandLine>
|
||||
<Description>Enable RemoteAPP to launch unlisted programs</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>14</Order>
|
||||
<CommandLine>reg.exe add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced" /v "ShowTaskViewButton" /t REG_DWORD /d 0 /f</CommandLine>
|
||||
<Description>Remove Task View from the Taskbar</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>15</Order>
|
||||
<CommandLine>reg.exe add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced" /v "TaskbarDa" /t REG_DWORD /d 0 /f</CommandLine>
|
||||
<Description>Remove Widgets from the Taskbar</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>16</Order>
|
||||
<CommandLine>reg.exe add "HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced" /v "TaskbarMn" /t REG_DWORD /d 0 /f</CommandLine>
|
||||
<Description>Remove Chat from the Taskbar</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>17</Order>
|
||||
<CommandLine>reg.exe add "HKLM\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU" /v "NoAutoUpdate" /t REG_DWORD /d 1 /f</CommandLine>
|
||||
<Description>Turn off Windows Update auto download</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>18</Order>
|
||||
<CommandLine>netsh advfirewall firewall set rule group="@FirewallAPI.dll,-32752" new enable=Yes</CommandLine>
|
||||
<Description>Enable Network Discovery</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>19</Order>
|
||||
<CommandLine>netsh advfirewall firewall set rule group="@FirewallAPI.dll,-28502" new enable=Yes</CommandLine>
|
||||
<Description>Enable File Sharing</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>20</Order>
|
||||
<CommandLine>reg.exe add "HKCU\Control Panel\UnsupportedHardwareNotificationCache" /v SV1 /d 0 /t REG_DWORD /f</CommandLine>
|
||||
<Description>Disable unsupported hardware notifications</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>21</Order>
|
||||
<CommandLine>reg.exe add "HKCU\Control Panel\UnsupportedHardwareNotificationCache" /v SV2 /d 0 /t REG_DWORD /f</CommandLine>
|
||||
<Description>Disable unsupported hardware notifications</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>22</Order>
|
||||
<CommandLine>pnputil -i -a C:\Windows\Drivers\viogpudo\viogpudo.inf</CommandLine>
|
||||
<Description>Install VirtIO display driver</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>23</Order>
|
||||
<CommandLine>cmd /C rd /q C:\Windows.old</CommandLine>
|
||||
<Description>Remove empty Windows.old folder</Description>
|
||||
</SynchronousCommand>
|
||||
<SynchronousCommand wcm:action="add">
|
||||
<Order>24</Order>
|
||||
<CommandLine>cmd /C if exist "C:\OEM\install.bat" start "Install" "cmd /C C:\OEM\install.bat"</CommandLine>
|
||||
<Description>Execute custom script from the OEM folder if exists</Description>
|
||||
</SynchronousCommand>
|
||||
</FirstLogonCommands>
|
||||
</component>
|
||||
</settings>
|
||||
</unattend>
|
||||
1
omnitool/omnibox/vm/win11iso/README.md
Normal file
@@ -0,0 +1 @@
|
||||
Add your Win11E setup.iso to this folder
|
||||
31
omnitool/omnibox/vm/win11setup/firstboot/install.bat
Normal file
@@ -0,0 +1,31 @@
|
||||
@echo off
|
||||
|
||||
SET ScriptFolder=\\host.lan\Data
|
||||
SET LogFile=%ScriptFolder%\firstboot_log.txt
|
||||
|
||||
echo Running PowerShell script... > %LogFile%
|
||||
|
||||
:: Check for PowerShell availability
|
||||
where powershell >> %LogFile% 2>&1
|
||||
if %ERRORLEVEL% neq 0 (
|
||||
echo PowerShell is not available! >> %LogFile%
|
||||
echo PowerShell is not available!
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
:: Add a 30-second delay
|
||||
echo Waiting for 30 seconds before continuing... >> %LogFile%
|
||||
timeout /t 30 /nobreak >> %LogFile% 2>&1
|
||||
|
||||
:: Run PowerShell script with ExecutionPolicy Bypass and log errors
|
||||
echo Running setup.ps1... >> %LogFile%
|
||||
|
||||
powershell -ExecutionPolicy Bypass -File "%ScriptFolder%\setup.ps1" >> %LogFile% 2>&1
|
||||
|
||||
if %ERRORLEVEL% neq 0 (
|
||||
echo An error occurred. See %LogFile% for details.
|
||||
) else (
|
||||
echo PowerShell script has completed successfully.
|
||||
)
|
||||
|
||||
echo PowerShell script has completed.
|
||||
7
omnitool/omnibox/vm/win11setup/setupscripts/on-logon.ps1
Normal file
@@ -0,0 +1,7 @@
|
||||
$scriptFolder = "\\host.lan\Data"
|
||||
$pythonScriptFile = "$scriptFolder\server\main.py"
|
||||
$pythonServerPort = 5000
|
||||
|
||||
# Start the flask computer use server
|
||||
Write-Host "Running the server on port $pythonServerPort"
|
||||
python $pythonScriptFile --port $pythonServerPort
|
||||
BIN
omnitool/omnibox/vm/win11setup/setupscripts/server/cursor.png
Normal file
|
After Width: | Height: | Size: 3.1 KiB |
81
omnitool/omnibox/vm/win11setup/setupscripts/server/main.py
Normal file
@@ -0,0 +1,81 @@
|
||||
import os
|
||||
import logging
|
||||
import argparse
|
||||
import shlex
|
||||
import subprocess
|
||||
from flask import Flask, request, jsonify, send_file
|
||||
import threading
|
||||
import traceback
|
||||
import pyautogui
|
||||
from PIL import Image
|
||||
from io import BytesIO
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--log_file", help="log file path", type=str,
|
||||
default=os.path.join(os.path.dirname(__file__), "server.log"))
|
||||
parser.add_argument("--port", help="port", type=int, default=5000)
|
||||
args = parser.parse_args()
|
||||
|
||||
logging.basicConfig(filename=args.log_file,level=logging.DEBUG, filemode='w' )
|
||||
logger = logging.getLogger('werkzeug')
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
computer_control_lock = threading.Lock()
|
||||
|
||||
@app.route('/probe', methods=['GET'])
|
||||
def probe_endpoint():
|
||||
return jsonify({"status": "Probe successful", "message": "Service is operational"}), 200
|
||||
|
||||
@app.route('/execute', methods=['POST'])
|
||||
def execute_command():
|
||||
# Only execute one command at a time
|
||||
with computer_control_lock:
|
||||
data = request.json
|
||||
# The 'command' key in the JSON request should contain the command to be executed.
|
||||
shell = data.get('shell', False)
|
||||
command = data.get('command', "" if shell else [])
|
||||
|
||||
if isinstance(command, str) and not shell:
|
||||
command = shlex.split(command)
|
||||
|
||||
# Expand user directory
|
||||
for i, arg in enumerate(command):
|
||||
if arg.startswith("~/"):
|
||||
command[i] = os.path.expanduser(arg)
|
||||
|
||||
# Execute the command without any safety checks.
|
||||
try:
|
||||
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell, text=True, timeout=120)
|
||||
return jsonify({
|
||||
'status': 'success',
|
||||
'output': result.stdout,
|
||||
'error': result.stderr,
|
||||
'returncode': result.returncode
|
||||
})
|
||||
except Exception as e:
|
||||
logger.error("\n" + traceback.format_exc() + "\n")
|
||||
return jsonify({
|
||||
'status': 'error',
|
||||
'message': str(e)
|
||||
}), 500
|
||||
|
||||
@app.route('/screenshot', methods=['GET'])
|
||||
def capture_screen_with_cursor():
|
||||
cursor_path = os.path.join(os.path.dirname(__file__), "cursor.png")
|
||||
screenshot = pyautogui.screenshot()
|
||||
cursor_x, cursor_y = pyautogui.position()
|
||||
cursor = Image.open(cursor_path)
|
||||
# make the cursor smaller
|
||||
cursor = cursor.resize((int(cursor.width / 1.5), int(cursor.height / 1.5)))
|
||||
screenshot.paste(cursor, (cursor_x, cursor_y), cursor)
|
||||
|
||||
|
||||
# Convert PIL Image to bytes and send
|
||||
img_io = BytesIO()
|
||||
screenshot.save(img_io, 'PNG')
|
||||
img_io.seek(0)
|
||||
return send_file(img_io, mimetype='image/png')
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True, host="0.0.0.0", port=args.port)
|
||||
@@ -0,0 +1,2 @@
|
||||
flask
|
||||
PyAutoGUI
|
||||
197
omnitool/omnibox/vm/win11setup/setupscripts/setup-tools.psm1
Normal file
@@ -0,0 +1,197 @@
|
||||
function Get-Tools {
|
||||
param(
|
||||
[string]$toolsConfigJson
|
||||
)
|
||||
|
||||
# Convert the JSON string to a PowerShell object
|
||||
$toolsList = $toolsConfigJson | ConvertFrom-Json
|
||||
|
||||
return $toolsList
|
||||
}
|
||||
|
||||
function Get-ToolDetails {
|
||||
param(
|
||||
$toolsList,
|
||||
[string]$toolName
|
||||
)
|
||||
|
||||
# Check if the program exists in the JSON data
|
||||
if ($toolsList.PSObject.Properties.Name -contains $toolName) {
|
||||
# Return the program details as a PowerShell object
|
||||
return $toolsList.$toolName
|
||||
} else {
|
||||
# Handle the case where the program is not found
|
||||
Write-Host "Program '$toolName' not found in the list."
|
||||
return $null
|
||||
}
|
||||
}
|
||||
|
||||
function Invoke-DownloadFileFromAvailableMirrors {
|
||||
param (
|
||||
[string[]]$mirrorUrls,
|
||||
[string]$outfile
|
||||
)
|
||||
foreach ($url in $mirrorUrls) {
|
||||
try {
|
||||
$result = Invoke-DownloadFile -url $url -outfile $outfile
|
||||
if ($result -eq $true) {
|
||||
Write-Host "Downloaded using $url"
|
||||
return $true
|
||||
}
|
||||
} catch {
|
||||
Write-Host "Error downloading from $url. Please check and update the mirrors."
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "Downloading from the provided mirrors failed. Please check and update the mirrors."
|
||||
return $false
|
||||
}
|
||||
|
||||
function Invoke-DownloadFile {
|
||||
param (
|
||||
[string]$url,
|
||||
[string]$outfile
|
||||
)
|
||||
# Makes download faster by disabling progress bar
|
||||
$ProgressPreference = "SilentlyContinue"
|
||||
|
||||
$retryCount = 0
|
||||
$maxRetries = 3
|
||||
$sleepSeconds = 2
|
||||
$maxSleepSeconds = 10
|
||||
$userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
|
||||
|
||||
# Ensure directory exists
|
||||
$directory = Split-Path -Path $outfile -Parent
|
||||
if (-Not (Test-Path -Path $directory)) {
|
||||
Write-Host "Creating directory $directory..."
|
||||
New-Item -Path $directory -ItemType Directory -Force | Out-Null
|
||||
}
|
||||
|
||||
while ($retryCount -lt $maxRetries) {
|
||||
try {
|
||||
Invoke-RestMethod -Uri $url -OutFile $outfile -Headers @{"User-Agent" = $userAgent}
|
||||
Write-Host "Download successful, file saved to: $outfile"
|
||||
break
|
||||
} catch {
|
||||
$retryCount++
|
||||
Write-Host "Attempt $retryCount of $maxRetries failed. Error: $($_.Exception.Message)"
|
||||
Start-Sleep -Seconds $sleepSeconds
|
||||
$sleepSeconds = [Math]::Min($sleepSeconds * 2, $maxSleepSeconds) # Exponential backoff with a cap
|
||||
}
|
||||
}
|
||||
|
||||
if ($retryCount -eq $maxRetries) {
|
||||
Write-Host "Failed to download the file after $maxRetries attempts."
|
||||
return $false
|
||||
}
|
||||
|
||||
return $true
|
||||
}
|
||||
|
||||
function Add-ToEnvPath {
|
||||
param (
|
||||
[string]$NewPath
|
||||
)
|
||||
|
||||
# Get the current PATH environment variable
|
||||
$envPath = [Environment]::GetEnvironmentVariable("PATH", "Machine")
|
||||
|
||||
# Append the new path to the existing PATH
|
||||
$newPath = "$envPath;$NewPath"
|
||||
|
||||
# Set the updated PATH environment variable
|
||||
[Environment]::SetEnvironmentVariable("PATH", $newPath, "Machine")
|
||||
|
||||
# Fetch updates from the shell
|
||||
$env:PATH += ";${newPath}"
|
||||
}
|
||||
|
||||
function Register-LogonTask {
|
||||
param(
|
||||
|
||||
[parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = "Name of the scheduled task")]
|
||||
[string]
|
||||
$TaskName,
|
||||
|
||||
[parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = "Path to the .py script")]
|
||||
[string]
|
||||
$ScriptPath,
|
||||
|
||||
[parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true, HelpMessage = "Arguments to the .py script")]
|
||||
[string]
|
||||
$Arguments = "",
|
||||
|
||||
[parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true, HelpMessage = "Local Account username")]
|
||||
[string]
|
||||
$LocalUser,
|
||||
|
||||
[parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true, HelpMessage = "Local Account password")]
|
||||
[string]
|
||||
$LocalPassword,
|
||||
|
||||
[parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true, HelpMessage = "Whether to execute the command as SYSTEM")]
|
||||
[switch]
|
||||
$AsSystem = $false,
|
||||
|
||||
[parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true, HelpMessage = "logging file")]
|
||||
[string]
|
||||
$LogFilePath
|
||||
)
|
||||
|
||||
$scriptDirectory = Split-Path $ScriptPath
|
||||
|
||||
$taskActionArgument = "-ExecutionPolicy Bypass -windowstyle hidden -Command `"try { . '$ScriptPath' $Arguments } catch { Write `$_.Exception.Message | Out-File $($TaskName)_Log.txt } finally { } `""
|
||||
$taskAction = New-ScheduledTaskAction -Execute "$PSHome\powershell.exe" -Argument $taskActionArgument -WorkingDirectory $scriptDirectory
|
||||
|
||||
$params = @{
|
||||
Force = $True
|
||||
Action = $taskAction
|
||||
RunLevel = "Highest"
|
||||
TaskName = $TaskName
|
||||
}
|
||||
|
||||
$taskTrigger = New-ScheduledTaskTrigger -AtLogOn
|
||||
$params.Add("Trigger", $taskTrigger)
|
||||
|
||||
if ($AsSystem) {
|
||||
$params.Add("User", "NT AUTHORITY\SYSTEM")
|
||||
}
|
||||
else {
|
||||
$params.Add("User", $LocalUser)
|
||||
if ($LocalPassword) {
|
||||
$params.Add("Password", $LocalPassword)
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "Registering scheduled task '$TaskName' to run 'powershell.exe $taskActionArgument'..."
|
||||
Register-ScheduledTask @params
|
||||
}
|
||||
|
||||
# Function to attempt pip install and handle failures
|
||||
function Install-PythonPackages {
|
||||
param (
|
||||
[string]$Package = "",
|
||||
[string]$Arguments = "",
|
||||
[string]$RequirementsPath = ""
|
||||
)
|
||||
$RetryCount = 3
|
||||
$currentAttempt = 0
|
||||
while ($currentAttempt -lt $RetryCount) {
|
||||
if (-not [string]::IsNullOrWhiteSpace($RequirementsPath)) {
|
||||
& python -m pip install --no-cache-dir -r $RequirementsPath $Arguments
|
||||
} else {
|
||||
& python -m pip install --no-cache-dir $Package $Arguments
|
||||
}
|
||||
if ($LASTEXITCODE -eq 0) {
|
||||
Write-Host "Installation successful."
|
||||
return
|
||||
} else {
|
||||
Write-Host "Attempt $($currentAttempt + 1) failed. Retrying..."
|
||||
Start-Sleep -Seconds 10
|
||||
$currentAttempt++
|
||||
}
|
||||
}
|
||||
Write-Error "Failed to install after $RetryCount attempts."
|
||||
exit
|
||||
}
|
||||
392
omnitool/omnibox/vm/win11setup/setupscripts/setup.ps1
Normal file
@@ -0,0 +1,392 @@
|
||||
$ErrorActionPreference = "Continue" # until downloading from mirrors is more stable
|
||||
|
||||
# Section - General Setup
|
||||
$scriptFolder = "\\host.lan\Data"
|
||||
$toolsFolder = "C:\Users\$env:USERNAME\Tools"
|
||||
|
||||
# Load the shared setup-tools module
|
||||
Import-Module (Join-Path $scriptFolder -ChildPath "setup-tools.psm1")
|
||||
|
||||
# Check if profile exists
|
||||
if (-not (Test-Path $PROFILE)) {
|
||||
New-Item -ItemType File -Path $PROFILE -Force
|
||||
}
|
||||
|
||||
# Create a folder where we store all the standalone executables
|
||||
if (-not (Test-Path $toolsFolder)) {
|
||||
New-Item -ItemType Directory -Path $toolsFolder -Force
|
||||
$envPath = [Environment]::GetEnvironmentVariable("PATH", "Machine")
|
||||
$newPath = "$envPath;$toolsFolder"
|
||||
[Environment]::SetEnvironmentVariable("PATH", $newPath, "Machine")
|
||||
}
|
||||
|
||||
# Section - Tools Installation
|
||||
|
||||
# Set TLS version to 1.2 or higher
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls13
|
||||
|
||||
# Load the tools config json listing mirrors and aliases used for installing tools
|
||||
$toolsConfigJsonPath = Join-Path $scriptFolder -ChildPath "tools_config.json"
|
||||
$toolsConfigJson = Get-Content -Path $toolsConfigJsonPath -Raw
|
||||
$toolsList = Get-Tools -toolsConfigJson $toolsConfigJson
|
||||
|
||||
## - Python
|
||||
$pythonToolName = "Python"
|
||||
$userPythonPath = "$env:LOCALAPPDATA\Programs\Python"
|
||||
$pythonDetails = Get-ToolDetails -toolsList $toolsList -toolName $pythonToolName
|
||||
$pythonAlias = $pythonDetails.alias
|
||||
|
||||
# Check for Python installation
|
||||
$pythonExecutablePath = Get-ChildItem -Path $userPythonPath -Filter python.exe -Recurse -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty FullName
|
||||
|
||||
# Force to install Python 3.10 as the pre-installed version on Windows may not work sometimes
|
||||
Write-Host "Downloading Python $pythonVersion..."
|
||||
$pythonInstallerFilePath = "$env:TEMP\python_installer.exe"
|
||||
$downloadResult = Invoke-DownloadFileFromAvailableMirrors -mirrorUrls $pythonDetails.mirrors -outfile $pythonInstallerFilePath
|
||||
if (-not $downloadResult) {
|
||||
Write-Host "Failed to download Python. Please try again later or install manually."
|
||||
} else {
|
||||
Write-Host "Installing Python for current user..."
|
||||
Start-Process -FilePath $pythonInstallerFilePath -Args "/quiet InstallAllUsers=0 PrependPath=0" -NoNewWindow -Wait
|
||||
$pythonExecutablePath = "$userPythonPath\Python310\python.exe"
|
||||
$setAliasExpression = "Set-Alias -Name $pythonAlias -Value `"$pythonExecutablePath`""
|
||||
Add-Content -Path $PROFILE -Value $setAliasExpression
|
||||
Invoke-Expression $setAliasExpression
|
||||
}
|
||||
|
||||
## - Git
|
||||
$gitToolName = "git"
|
||||
$gitToolDetails = Get-ToolDetails -toolsList $toolsList -toolName $gitToolName
|
||||
|
||||
# Check for Git installation
|
||||
try {
|
||||
git --version | Out-Null
|
||||
Write-Host "Git is already installed."
|
||||
} catch {
|
||||
Write-Host "Git is not installed. Downloading and installing Git..."
|
||||
$gitInstallerFilePath = "$env:TEMP\git_installer.exe"
|
||||
$downloadResult = Invoke-DownloadFileFromAvailableMirrors -mirrorUrls $gitToolDetails.mirrors -outfile $gitInstallerFilePath
|
||||
if (-not $downloadResult) {
|
||||
Write-Host "Failed to download Git. Please try again later or install manually."
|
||||
} else {
|
||||
Start-Process -FilePath $gitInstallerFilePath -Args "/VERYSILENT /NORESTART /NOCANCEL /SP-" -Wait
|
||||
Add-ToEnvPath -NewPath "C:\Program Files\Git\bin"
|
||||
|
||||
Write-Host "Git has been installed."
|
||||
}
|
||||
}
|
||||
|
||||
# - 7zip
|
||||
$7ZipToolName = "7zip"
|
||||
$7ZipToolDetails = Get-ToolDetails -toolsList $toolsList -toolName $7ZipToolName
|
||||
Write-Host "$7ZipToolDetails"
|
||||
|
||||
if (Get-Command 7z -ErrorAction SilentlyContinue) {
|
||||
Write-Host "7-Zip is already installed."
|
||||
}
|
||||
else {
|
||||
Write-Host "Installing 7-Zip..."
|
||||
|
||||
$7ZipInstallerFilePath = "$env:TEMP\7_zip.exe"
|
||||
Write-Host "$($7ZipToolDetails.mirrors)"
|
||||
$downloadResult = Invoke-DownloadFileFromAvailableMirrors -mirrorUrls $7ZipToolDetails.mirrors -outfile $7ZipInstallerFilePath
|
||||
if (-not $downloadResult) {
|
||||
Write-Host "Failed to download 7-Zip. Please try again later or install manually."
|
||||
} else {
|
||||
Start-Process -FilePath $7ZipInstallerFilePath -Args "/S" -Verb RunAs -Wait
|
||||
Remove-Item $7ZipInstallerFilePath
|
||||
|
||||
# add 7z to PATH
|
||||
Add-ToEnvPath -NewPath "${env:ProgramFiles}\7-Zip"
|
||||
}
|
||||
}
|
||||
|
||||
# - ffpmeg
|
||||
$ffpmegToolName = "ffmpeg"
|
||||
$ffpmegToolDetails = Get-ToolDetails -toolsList $toolsList -toolName $ffpmegToolName
|
||||
|
||||
if (Get-Command ffmpeg -ErrorAction SilentlyContinue) {
|
||||
Write-Host "ffmpeg is already installed."
|
||||
} else {
|
||||
Write-Host "ffmpeg is not installed. Installing it."
|
||||
$ffpmegInstallerFilePath = "C:\ffmpeg.7z"
|
||||
$downloadResult = Invoke-DownloadFileFromAvailableMirrors -mirrorUrls $ffpmegToolDetails.mirrors -outfile $ffpmegInstallerFilePath
|
||||
if (-not $downloadResult) {
|
||||
Write-Host "Failed to download ffmpeg. Please try again later or install manually."
|
||||
} else {
|
||||
Write-Host "Extracting $ffpmegInstallerFilePath..."
|
||||
7z x -y -o"C:\" "C:\ffmpeg.7z"
|
||||
|
||||
$ffmpegFolder = Get-ChildItem -Path "C:\" -Filter "ffmpeg-*" -Directory
|
||||
$ffmpegFolder = -join ("C:\", $ffmpegFolder)
|
||||
#remove ffmpeg folder if exists
|
||||
if (Test-Path "C:\ffmpeg") {
|
||||
Remove-Item -Path "C:\ffmpeg" -Recurse -Force
|
||||
}
|
||||
Rename-Item -Path "$ffmpegFolder" -NewName "ffmpeg"
|
||||
|
||||
Write-Host "Adding ffmpeg to PATH..."
|
||||
Add-ToEnvPath -NewPath "C:\ffmpeg\bin"
|
||||
|
||||
Write-Host "ffmpeg is installed"
|
||||
}
|
||||
}
|
||||
|
||||
# Disable Edge Auto Updates
|
||||
Stop-Process -Name "MicrosoftEdgeUpdate" -Force -ErrorAction SilentlyContinue
|
||||
$edgeUpdatePath = "${env:ProgramFiles(x86)}\Microsoft\EdgeUpdate"
|
||||
Remove-Item -Path $edgeUpdatePath -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Write-Host "Edge Update processes terminated and directory removed."
|
||||
|
||||
# - Google Chrome
|
||||
$chromeToolName = "Google Chrome"
|
||||
$chromeToolDetails = Get-ToolDetails -toolsList $toolsList -toolName $chromeToolName
|
||||
$chromeExePath = "C:\Program Files\Google\Chrome\Application\chrome.exe"
|
||||
$chromeAlias = $chromeToolDetails.alias
|
||||
|
||||
# Check if Google Chrome is already installed by its alias
|
||||
if (Get-Command $chromeAlias -ErrorAction SilentlyContinue) {
|
||||
Write-Host "Google Chrome is already installed."
|
||||
} else {
|
||||
# Download the installer to the Temp directory
|
||||
$chromeInstallerFilePath = "$env:TEMP\chrome_installer.exe"
|
||||
$downloadResult = Invoke-DownloadFileFromAvailableMirrors -mirrorUrls $chromeToolDetails.mirrors -outfile $chromeInstallerFilePath
|
||||
if (-not $downloadResult) {
|
||||
Write-Host "Failed to download Google Chrome. Please try again later or install manually."
|
||||
} else {
|
||||
# Execute the installer silently with elevated permissions
|
||||
Start-Process -FilePath $chromeInstallerFilePath -ArgumentList "/silent", "/install" -Verb RunAs -Wait
|
||||
|
||||
# Remove the installer file after installation
|
||||
Remove-Item -Path $chromeInstallerFilePath
|
||||
|
||||
# Set alias
|
||||
$setAliasExpression = "Set-Alias -Name $chromeAlias -Value `"$chromeExePath`""
|
||||
Add-Content -Path $PROFILE -Value $setAliasExpression
|
||||
Invoke-Expression $setAliasExpression
|
||||
|
||||
# Add Chrome to the system PATH environment variable
|
||||
Add-ToEnvPath -NewPath "${env:ProgramFiles}\Google\Chrome\Application"
|
||||
|
||||
# Disable Google Chrome Auto Updates
|
||||
$chromeRegPath = "HKLM:\SOFTWARE\Policies\Google\Update"
|
||||
if (-not (Test-Path $chromeRegPath)) {
|
||||
New-Item -Path $chromeRegPath -Force
|
||||
}
|
||||
Set-ItemProperty -Path $chromeRegPath -Name "AutoUpdateCheckPeriodMinutes" -Value 0
|
||||
Set-ItemProperty -Path $chromeRegPath -Name "UpdateDefault" -Value 0
|
||||
}
|
||||
}
|
||||
|
||||
# - LibreOffice
|
||||
$libreOfficeToolName = "LibreOffice"
|
||||
$libreOfficeToolDetails = Get-ToolDetails -toolsList $toolsList -toolName $libreOfficeToolName
|
||||
|
||||
# Check for LibreOffice installation
|
||||
$installedVersion = (Get-WmiObject -Query "SELECT * FROM Win32_Product WHERE Name like 'LibreOffice%'").Version
|
||||
if (-not [string]::IsNullOrWhiteSpace($installedVersion)) {
|
||||
Write-Host "LibreOffice $version is already installed."
|
||||
} else {
|
||||
Write-Host "LibreOffice is not installed. Downloading and installing LibreOffice..."
|
||||
$libreOfficeInstallerFilePath = "$env:TEMP\libreOffice_installer.exe"
|
||||
|
||||
$downloadResult = Invoke-DownloadFileFromAvailableMirrors -mirrorUrls $libreOfficeToolDetails.mirrors -outfile $libreOfficeInstallerFilePath
|
||||
if (-not $downloadResult) {
|
||||
Write-Host "Failed to download LibreOffice. Please try again later or install manually."
|
||||
} else {
|
||||
Start-Process "msiexec.exe" -ArgumentList "/i `"$libreOfficeInstallerFilePath`" /quiet" -Wait -NoNewWindow
|
||||
Write-Host "LibreOffice has been installed."
|
||||
|
||||
# Add LibreOffice to the system PATH environment variable
|
||||
Add-ToEnvPath -NewPath "C:\Program Files\LibreOffice\program"
|
||||
}
|
||||
}
|
||||
|
||||
# - VLC
|
||||
$vlcToolName = "VLC"
|
||||
$vlcToolDetails = Get-ToolDetails -toolsList $toolsList -toolName $vlcToolName
|
||||
$vlcAlias = $vlcToolDetails.alias
|
||||
$vlcExecutableFilePath = "C:\Program Files\VideoLAN\VLC\vlc.exe"
|
||||
|
||||
# Check if VLC is already installed by checking the VLC command
|
||||
if (Test-Path $vlcExecutableFilePath) {
|
||||
Write-Host "VLC is already installed."
|
||||
} else {
|
||||
# Download the installer to the Temp directory
|
||||
$vlcInstallerFilePath = "$env:TEMP\vlc_installer.exe"
|
||||
$downloadResult = Invoke-DownloadFileFromAvailableMirrors -mirrorUrls $vlcToolDetails.mirrors -outfile $vlcInstallerFilePath
|
||||
if (-not $downloadResult) {
|
||||
Write-Host "Failed to download VLC. Please try again later or install manually."
|
||||
} else {
|
||||
# Execute the installer silently with elevated permissions
|
||||
Start-Process -FilePath $vlcInstallerFilePath -ArgumentList "/S" -Verb RunAs -Wait
|
||||
|
||||
# Remove the installer file after installation
|
||||
Remove-Item -Path $vlcInstallerFilePath
|
||||
|
||||
# Set alias
|
||||
$setAliasExpression = "Set-Alias -Name $vlcAlias -Value `"$vlcExecutableFilePath`""
|
||||
Add-Content -Path $PROFILE -Value $setAliasExpression
|
||||
Invoke-Expression $setAliasExpression
|
||||
|
||||
# Add VLC to the system PATH environment variable
|
||||
Add-ToEnvPath -NewPath "C:\Program Files\VideoLAN\VLC"
|
||||
}
|
||||
}
|
||||
|
||||
# - GIMP
|
||||
$gimpToolName = "GIMP"
|
||||
$gimpToolDetails = Get-ToolDetails -toolsList $toolsList -toolName $gimpToolName
|
||||
$gimpAlias = $gimpToolDetails.alias
|
||||
$gimpExecutablePath = "C:\Program Files\GIMP 2\bin\gimp-2.10.exe"
|
||||
|
||||
# Check if GIMP is already installed by checking the GIMP executable path
|
||||
if (Test-Path $gimpExecutablePath) {
|
||||
Write-Host "GIMP is already installed."
|
||||
} else {
|
||||
# Download the installer to the Temp directory
|
||||
$gimpInstallerFilePath = "$env:TEMP\gimp_installer.exe"
|
||||
$downloadResult = Invoke-DownloadFileFromAvailableMirrors -mirrorUrls $gimpToolDetails.mirrors -outfile $gimpInstallerFilePath
|
||||
if (-not $downloadResult) {
|
||||
Write-Host "Failed to download GIMP. Please try again later or install manually."
|
||||
} else {
|
||||
# Execute the installer silently with elevated permissions
|
||||
Start-Process -FilePath $gimpInstallerFilePath -ArgumentList "/VERYSILENT /ALLUSERS" -Verb RunAs -Wait
|
||||
|
||||
# Remove the installer file after installation
|
||||
Remove-Item -Path $gimpInstallerFilePath
|
||||
|
||||
# Set alias
|
||||
$setAliasExpression = "Set-Alias -Name $gimpAlias -Value `"$gimpExecutablePath`""
|
||||
Add-Content -Path $PROFILE -Value $setAliasExpression
|
||||
Invoke-Expression $setAliasExpression
|
||||
|
||||
# Add GIMP to the system PATH environment variable
|
||||
Add-ToEnvPath -NewPath "C:\Program Files\GIMP 2\bin"
|
||||
}
|
||||
}
|
||||
|
||||
# - VS Code
|
||||
$vsCodeToolName = "VS Code"
|
||||
$vsCodeToolDetails = Get-ToolDetails -toolsList $toolsList -toolName $vsCodeToolName
|
||||
$vsCodeAlias = $gimpToolDetails.alias
|
||||
$vsCodeExecutablePath = "C:\Users\$env:USERNAME\AppData\Local\Programs\Microsoft VS Code\Code.exe"
|
||||
|
||||
# Check if VS Code is already installed by checking the VS Code executable path
|
||||
if (Test-Path $vsCodeExecutablePath) {
|
||||
Write-Host "VS Code is already installed."
|
||||
} else {
|
||||
# Download the installer to the Temp directory
|
||||
$vsCodeInstallerFilePath = "$env:TEMP\VSCodeSetup.exe"
|
||||
$downloadResult = Invoke-DownloadFileFromAvailableMirrors -mirrorUrls $vsCodeToolDetails.mirrors -outfile $vsCodeInstallerFilePath
|
||||
if (-not $downloadResult) {
|
||||
Write-Host "Failed to download VS Code. Please try again later or install manually."
|
||||
} else {
|
||||
# Execute the installer silently with elevated permissions
|
||||
Start-Process -FilePath $vsCodeInstallerFilePath -ArgumentList "/VERYSILENT", "/mergetasks=!runcode" -Verb RunAs -Wait
|
||||
|
||||
# Remove the installer file after installation
|
||||
Remove-Item -Path $vsCodeInstallerFilePath
|
||||
|
||||
# Set alias
|
||||
$setAliasExpression = "Set-Alias -Name $vsCodeAlias -Value `"$vsCodeExecutablePath`""
|
||||
Add-Content -Path $PROFILE -Value $setAliasExpression
|
||||
Invoke-Expression $setAliasExpression
|
||||
|
||||
# Add VS Code to the system PATH environment variable
|
||||
Add-ToEnvPath -NewPath "C:\Users\$env:USERNAME\AppData\Local\Programs\Microsoft VS Code\bin"
|
||||
|
||||
# Disable Visual Studio Code Auto Updates
|
||||
$vsCodeSettingsPath = "${env:APPDATA}\Code\User\settings.json"
|
||||
if (-not (Test-Path $vsCodeSettingsPath)) {
|
||||
# Create the directory if it doesn't exist
|
||||
$dirPath = Split-Path -Path $vsCodeSettingsPath -Parent
|
||||
if (-not (Test-Path $dirPath)) {
|
||||
New-Item -ItemType Directory -Path $dirPath -Force
|
||||
}
|
||||
# Initialize an empty hashtable to act as the JSON object
|
||||
$settingsObj = @{}
|
||||
$settingsObj["update.mode"] = "none" # Set update mode to none
|
||||
$settingsObj | ConvertTo-Json | Set-Content $vsCodeSettingsPath
|
||||
} else {
|
||||
# If the file exists, modify it
|
||||
$settingsObj = Get-Content $vsCodeSettingsPath | ConvertFrom-Json
|
||||
$settingsObj["update.mode"] = "none"
|
||||
$settingsObj | ConvertTo-Json | Set-Content $vsCodeSettingsPath
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# - Thunderbird
|
||||
$thunderbirdToolName = "Thunderbird"
|
||||
$thunderbirdToolDetails = Get-ToolDetails -toolsList $toolsList -toolName $thunderbirdToolName
|
||||
$thunderbirdAlias = $thunderbirdToolDetails.alias
|
||||
$thunderbirdExecutablePath = "C:\Program Files\Mozilla Thunderbird\thunderbird.exe"
|
||||
|
||||
# Check if Thunderbird is already installed by checking the Thunderbird executable path
|
||||
if (Test-Path $thunderbirdExecutablePath) {
|
||||
Write-Host "Thunderbird is already installed."
|
||||
} else {
|
||||
# Download the installer to the Temp directory
|
||||
$thunderbirdInstallerFilePath = "$env:TEMP\ThunderbirdSetup.exe"
|
||||
$downloadResult = Invoke-DownloadFileFromAvailableMirrors -mirrorUrls $thunderbirdToolDetails.mirrors -outfile $thunderbirdInstallerFilePath
|
||||
if (-not $downloadResult) {
|
||||
Write-Host "Failed to download Thunderbird. Please try again later or install manually."
|
||||
} else {
|
||||
# Execute the installer silently with elevated permissions
|
||||
Start-Process -FilePath $thunderbirdInstallerFilePath -ArgumentList "/S" -Verb RunAs -Wait
|
||||
|
||||
# Remove the installer file after installation
|
||||
Remove-Item -Path $thunderbirdInstallerFilePath
|
||||
|
||||
# Set alias
|
||||
$setAliasExpression = "Set-Alias -Name $thunderbirdAlias -Value `"$thunderbirdExecutablePath`""
|
||||
Add-Content -Path $PROFILE -Value $setAliasExpression
|
||||
Invoke-Expression $setAliasExpression
|
||||
|
||||
# Add Thunderbird to the system PATH environment variable
|
||||
Add-ToEnvPath -NewPath "C:\Program Files\Mozilla Thunderbird"
|
||||
}
|
||||
}
|
||||
|
||||
# - Server Setup
|
||||
|
||||
$pythonServerPort = 5000
|
||||
$onLogonTaskName = "Server_OnLogon"
|
||||
$requirementsFile = "$scriptFolder\server\requirements.txt"
|
||||
|
||||
# Ensure pip is updated to the latest version
|
||||
Install-PythonPackages -Package "pip" -Arguments "--upgrade"
|
||||
|
||||
Install-PythonPackages -Package "wheel"
|
||||
Install-PythonPackages -Package "pywinauto"
|
||||
|
||||
# Install Python packages from requirements.txt using Python's pip module
|
||||
if (Test-Path $requirementsFile) {
|
||||
Write-Host "Installing required Python packages using pip from requirements file..."
|
||||
Install-PythonPackages -RequirementsPath $requirementsFile
|
||||
} else {
|
||||
Write-Error "Requirements file not found: $requirementsFile"
|
||||
exit
|
||||
}
|
||||
|
||||
# Add a firewall rule to allow incoming connections on the specified port for the Python executable
|
||||
$pythonServerRuleName = "PythonHTTPServer-$pythonServerPort"
|
||||
if (-not (Get-NetFirewallRule -Name $pythonServerRuleName -ErrorAction SilentlyContinue)) {
|
||||
New-NetFirewallRule -DisplayName $pythonServerRuleName -Direction Inbound -Program $pythonExecutablePath -Protocol TCP -LocalPort $pythonServerPort -Action Allow -Profile Any
|
||||
Write-Host "Firewall rule added to allow traffic on port $pythonServerPort for Python"
|
||||
} else {
|
||||
Write-Host "Firewall rule already exists. $pythonServerRuleName "
|
||||
}
|
||||
|
||||
$onLogonScriptPath = "$scriptFolder\on-logon.ps1"
|
||||
# Check if the scheduled task exists before unregistering it
|
||||
if (Get-ScheduledTask -TaskName $onLogonTaskName -ErrorAction SilentlyContinue) {
|
||||
Write-Host "Scheduled task $onLogonTaskName already exists."
|
||||
} else {
|
||||
Write-Host "Registering new task $onLogonTaskName..."
|
||||
Register-LogonTask -TaskName $onLogonTaskName -ScriptPath $onLogonScriptPath -LocalUser "Docker"
|
||||
}
|
||||
|
||||
Start-Sleep -Seconds 10
|
||||
Start-ScheduledTask -TaskName $onLogonTaskName
|
||||
@@ -0,0 +1,71 @@
|
||||
{
|
||||
"Python": {
|
||||
"mirrors": [
|
||||
"https://www.python.org/ftp/python/3.10.0/python-3.10.0-amd64.exe"
|
||||
],
|
||||
"alias": "python"
|
||||
},
|
||||
"git": {
|
||||
"mirrors": [
|
||||
"https://github.com/git-for-windows/git/releases/download/v2.37.1.windows.1/Git-2.37.1-64-bit.exe"
|
||||
]
|
||||
},
|
||||
"7zip": {
|
||||
"mirrors": [
|
||||
"https://www.7-zip.org/a/7z2407-x64.exe"
|
||||
]
|
||||
},
|
||||
"ffmpeg": {
|
||||
"mirrors": [
|
||||
"https://www.gyan.dev/ffmpeg/builds/ffmpeg-release-essentials.7z"
|
||||
]
|
||||
},
|
||||
"Google Chrome": {
|
||||
"mirrors": [
|
||||
"https://dl.google.com/chrome/install/latest/chrome_installer.exe"
|
||||
],
|
||||
"alias": "google-chrome"
|
||||
},
|
||||
"LibreOffice": {
|
||||
"mirrors": [
|
||||
"https://mirror.raiolanetworks.com/tdf/libreoffice/stable/24.8.4/win/x86_64/LibreOffice_24.8.4_Win_x86-64.msi",
|
||||
"https://mirrors.iu13.net/tdf/libreoffice/stable/24.8.4/win/x86_64/LibreOffice_24.8.4_Win_x86-64.msi",
|
||||
"https://download.documentfoundation.org/libreoffice/stable/24.8.4/win/x86_64/LibreOffice_24.8.4_Win_x86-64.msi"
|
||||
]
|
||||
},
|
||||
"VLC": {
|
||||
"mirrors": [
|
||||
"https://ftp.free.org/mirrors/videolan/vlc/3.0.21/win64/vlc-3.0.21-win64.exe",
|
||||
"https://mirror.fcix.net/videolan-ftp/vlc/3.0.21/win64/vlc-3.0.21-win64.exe",
|
||||
"https://mirror.raiolanetworks.com/videolan/vlc/3.0.21/win64/vlc-3.0.21-win64.exe"
|
||||
],
|
||||
"alias": "vlc"
|
||||
},
|
||||
"GIMP": {
|
||||
"mirrors": [
|
||||
"https://www-ftp.lip6.fr/pub/gimp/gimp/v2.10/windows/gimp-2.10.38-setup.exe",
|
||||
"https://download.gimp.org/gimp/v2.10/windows/gimp-2.10.38-setup.exe",
|
||||
"https://www-ftp.lip6.fr/pub/gimp/gimp/v2.10/windows/gimp-2.10.0-setup.exe"
|
||||
],
|
||||
"alias": "gimp"
|
||||
},
|
||||
"VS Code": {
|
||||
"mirrors": [
|
||||
"https://update.code.visualstudio.com/latest/win32-x64-user/stable"
|
||||
],
|
||||
"alias": "code"
|
||||
},
|
||||
"Thunderbird": {
|
||||
"mirrors": [
|
||||
"https://download-installer.cdn.mozilla.net/pub/thunderbird/releases/115.12.1/win64/en-US/Thunderbird%20Setup%20115.12.1.exe",
|
||||
"https://archive.mozilla.org/pub/thunderbird/releases/115.12.1/win64/en-US/Thunderbird%20Setup%20115.12.1.exe"
|
||||
],
|
||||
"alias": "thunderbird"
|
||||
},
|
||||
"Caddy Proxy": {
|
||||
"mirrors": [
|
||||
"https://caddyserver.com/api/download?os=windows&arch=amd64"
|
||||
],
|
||||
"alias": "caddy"
|
||||
}
|
||||
}
|
||||
51
omnitool/omniparserserver/omniparserserver.py
Normal file
@@ -0,0 +1,51 @@
|
||||
'''
|
||||
python -m omniparserserver --som_model_path ../../weights/icon_detect_v1_5/model_v1_5.pt --caption_model_name florence2 --caption_model_path ../../weights/icon_caption_florence --device cuda --BOX_TRESHOLD 0.05
|
||||
'''
|
||||
|
||||
import sys
|
||||
import os
|
||||
import time
|
||||
from fastapi import FastAPI
|
||||
from pydantic import BaseModel
|
||||
import argparse
|
||||
import uvicorn
|
||||
root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.path.append(root_dir)
|
||||
from util.omniparser import Omniparser
|
||||
|
||||
def parse_arguments():
|
||||
parser = argparse.ArgumentParser(description='Omniparser API')
|
||||
parser.add_argument('--som_model_path', type=str, default='../../weights/icon_detect_v1_5/model_v1_5.pt', help='Path to the som model')
|
||||
parser.add_argument('--caption_model_name', type=str, default='florence2', help='Name of the caption model')
|
||||
parser.add_argument('--caption_model_path', type=str, default='../../weights/icon_caption_florence', help='Path to the caption model')
|
||||
parser.add_argument('--device', type=str, default='cpu', help='Device to run the model')
|
||||
parser.add_argument('--BOX_TRESHOLD', type=float, default=0.05, help='Threshold for box detection')
|
||||
parser.add_argument('--host', type=str, default='0.0.0.0', help='Host for the API')
|
||||
parser.add_argument('--port', type=int, default=8000, help='Port for the API')
|
||||
args = parser.parse_args()
|
||||
return args
|
||||
|
||||
args = parse_arguments()
|
||||
config = vars(args)
|
||||
|
||||
app = FastAPI()
|
||||
omniparser = Omniparser(config)
|
||||
|
||||
class ParseRequest(BaseModel):
|
||||
base64_image: str
|
||||
|
||||
@app.post("/parse/")
|
||||
async def parse(parse_request: ParseRequest):
|
||||
print('start parsing...')
|
||||
start = time.time()
|
||||
dino_labled_img, parsed_content_list = omniparser.parse(parse_request.base64_image)
|
||||
latency = time.time() - start
|
||||
print('time:', latency)
|
||||
return {"som_image_base64": dino_labled_img, "parsed_content_list": parsed_content_list, 'latency': latency}
|
||||
|
||||
@app.get("/probe/")
|
||||
async def root():
|
||||
return {"message": "Omniparser API ready"}
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run("omniparserserver:app", host=args.host, port=args.port, reload=True)
|
||||
95
omnitool/readme.md
Normal file
@@ -0,0 +1,95 @@
|
||||
<img src="../imgs/header_bar.png" alt="OmniTool Header" width="100%">
|
||||
|
||||
# OmniTool
|
||||
|
||||
Control a Windows 11 VM with OmniParser + your vision model of choice.
|
||||
|
||||
## Highlights:
|
||||
|
||||
1. **OmniParser V2** is 60% faster than V1 and now understands a wide variety of OS, app and inside app icons!
|
||||
2. **OmniBox** uses 50% less disk space than other Windows VMs for agent testing, whilst providing the same computer use API
|
||||
3. **OmniTool** supports out of the box the following vision models - OpenAI (4o/o1/o3-mini), DeepSeek (R1), Qwen (2.5VL) or Anthropic Computer Use
|
||||
|
||||
## Overview
|
||||
|
||||
There are three components:
|
||||
|
||||
<table style="border-collapse: collapse; border: none;">
|
||||
<tr>
|
||||
<td style="border: none;"><img src="../imgs/omniparsericon.png" width="50"></td>
|
||||
<td style="border: none;"><strong>omniparserserver</strong></td>
|
||||
<td style="border: none;">FastAPI server running OmniParser V2.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="border: none;"><img src="../imgs/omniboxicon.png" width="50"></td>
|
||||
<td style="border: none;"><strong>omnibox</strong></td>
|
||||
<td style="border: none;">A Windows 11 VM running in a Docker container.</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="border: none;"><img src="../imgs/gradioicon.png" width="50"></td>
|
||||
<td style="border: none;"><strong>gradio</strong></td>
|
||||
<td style="border: none;">UI to provide commands and watch reasoning + execution on OmniBox</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## Notes:
|
||||
|
||||
1. Though **OmniParser V2** can run on a CPU, we have separated this out if you want to run it fast on a GPU machine
|
||||
2. The **OmniBox** Windows 11 VM docker is dependent on KVM so can only run quickly on Windows and Linux. This can run on a CPU machine (doesn't need GPU).
|
||||
3. The Gradio UI can also run on a CPU machine. We suggest running **omnibox** and **gradio** on the same CPU machine and **omniparserserver** on a GPU server.
|
||||
|
||||
## Setup
|
||||
|
||||
1. **omniparserserver**:
|
||||
|
||||
a. If you already have a conda environment for OmniParser, you can use that. Else follow the following steps to create one
|
||||
|
||||
b. Ensure conda is installed with `conda --version` or install from the [Anaconda website](https://www.anaconda.com/download/success)
|
||||
|
||||
c. Navigate to the root of the repo with `cd OmniParser`
|
||||
|
||||
d. Create a conda python environment with `conda create -n "omni" python==3.12`
|
||||
|
||||
e. Set the python environment to be used with `conda activate omni`
|
||||
|
||||
f. Install the dependencies with `pip install -r requirements.txt`
|
||||
|
||||
g. Continue from here if you already had the conda environment.
|
||||
|
||||
h. Ensure you have the weights downloaded in weights folder. If not download them with:
|
||||
`for folder in icon_caption_florence icon_detect icon_detect_v1_5; do huggingface-cli download microsoft/OmniParser --local-dir weights/ --repo-type model --include "$folder/*"; done`
|
||||
|
||||
h. Navigate to the server directory with `cd OmniParser/omnitool/omniparserserver`
|
||||
|
||||
i. Start the server with `python -m omniparserserver`
|
||||
|
||||
2. **omnibox**:
|
||||
|
||||
a. Install Docker Desktop
|
||||
|
||||
b. Visit [Microsoft Evaluation Center](https://info.microsoft.com/ww-landing-windows-11-enterprise.html), accept the Terms of Service, and download a **Windows 11 Enterprise Evaluation (90-day trial, English, United States)** ISO file [~6GB]. Rename the file to `custom.iso` and copy it to the directory `OmniParser/omnitool/omnibox/vm/win11iso`
|
||||
|
||||
c. Navigate to vm management script directory with`cd OmniParser/omnitool/omnibox/scripts`
|
||||
|
||||
d. Build the docker container [400MB] and install the ISO to a storage folder [20GB] with `./manage_vm.sh create`
|
||||
|
||||
e. After creating the first time it will store a save of the VM state in `vm/win11storage`. You can then manage the VM with `./manage_vm.sh start` and `./manage_vm.sh stop`. To delete the VM, use `./manage_vm.sh delete` and delete the `OmniParser/omnitool/omnibox/vm/win11storage` directory.
|
||||
|
||||
3. **gradio**:
|
||||
|
||||
a. Navigate to the gradio directory with `cd OmniParser/omnitool/gradio`
|
||||
|
||||
b. Ensure you have activated the conda python environment with `conda activate omni`
|
||||
|
||||
c. Start the server with `python app.py --windows_host_url localhost:8006 --omniparser_server_url localhost:8000`
|
||||
|
||||
d. Open the URL in the terminal output, set your API Key and start playing with the AI agent!
|
||||
|
||||
|
||||
|
||||
## Risks and Mitigations
|
||||
To align with the Microsoft AI principles and Responsible AI practices, we conduct risk mitigation by training the icon caption model with Responsible AI data, which helps the model avoid inferring sensitive attributes (e.g.race, religion etc.) of the individuals which happen to be in icon images as much as possible. At the same time, we encourage user to apply OmniParser only for screenshot that does not contain harmful/violent content. For the OmniTool, we conduct threat model analysis using Microsoft Threat Modeling Tool overview - Azure | Microsoft Learn. We provide a sandbox docker container, and provide safety guidance and examples in our GitHub Repository. We advise human to stay in the loop in order to minimize risk.
|
||||
|
||||
## Acknowledgment
|
||||
Kudos to the amazing resources that are indispensable in the development of our code: [Claude Computer Use](https://github.com/anthropics/anthropic-quickstarts/blob/main/computer-use-demo/README.md), [OS World](https://github.com/xlang-ai/OSWorld), [Windows Agent Arena](https://github.com/microsoft/WindowsAgentArena), and [computer_use_ootb](https://github.com/showlab/computer_use_ootb).
|
||||
We are grateful for helpful suggestions and feedbacks provided by Francesco Bonacci, Jianwei Yang, Dillon DuPont, Yue Wu, Anh Nguyen.
|
||||
@@ -4,7 +4,7 @@ torchvision
|
||||
supervision==0.18.0
|
||||
openai==1.3.5
|
||||
transformers
|
||||
ultralytics==8.1.24
|
||||
ultralytics==8.3.70
|
||||
azure-identity
|
||||
numpy
|
||||
opencv-python
|
||||
@@ -28,4 +28,5 @@ boto3>=1.28.57
|
||||
google-auth<3,>=2
|
||||
screeninfo
|
||||
uiautomation
|
||||
dashscope
|
||||
dashscope
|
||||
groq
|
||||
@@ -1,425 +0,0 @@
|
||||
'''
|
||||
Adapted from https://github.com/google-research/google-research/tree/master/android_in_the_wild
|
||||
'''
|
||||
|
||||
import jax
|
||||
import jax.numpy as jnp
|
||||
import numpy as np
|
||||
|
||||
# import action_type as action_type_lib
|
||||
import enum
|
||||
|
||||
class ActionType(enum.IntEnum):
|
||||
# Placeholders for unused enum values
|
||||
UNUSED_0 = 0
|
||||
UNUSED_1 = 1
|
||||
UNUSED_2 = 2
|
||||
UNUSED_8 = 8
|
||||
UNUSED_9 = 9
|
||||
|
||||
########### Agent actions ###########
|
||||
|
||||
# A type action that sends text to the emulator. Note that this simply sends
|
||||
# text and does not perform any clicks for element focus or enter presses for
|
||||
# submitting text.
|
||||
TYPE = 3
|
||||
|
||||
# The dual point action used to represent all gestures.
|
||||
DUAL_POINT = 4
|
||||
|
||||
# These actions differentiate pressing the home and back button from touches.
|
||||
# They represent explicit presses of back and home performed using ADB.
|
||||
PRESS_BACK = 5
|
||||
PRESS_HOME = 6
|
||||
|
||||
# An action representing that ADB command for hitting enter was performed.
|
||||
PRESS_ENTER = 7
|
||||
|
||||
########### Episode status actions ###########
|
||||
|
||||
# An action used to indicate the desired task has been completed and resets
|
||||
# the environment. This action should also be used in the case that the task
|
||||
# has already been completed and there is nothing to do.
|
||||
# e.g. The task is to turn on the Wi-Fi when it is already on
|
||||
STATUS_TASK_COMPLETE = 10
|
||||
|
||||
# An action used to indicate that desired task is impossible to complete and
|
||||
# resets the environment. This can be a result of many different things
|
||||
# including UI changes, Android version differences, etc.
|
||||
STATUS_TASK_IMPOSSIBLE = 11
|
||||
|
||||
|
||||
_TAP_DISTANCE_THRESHOLD = 0.14 # Fraction of the screen
|
||||
ANNOTATION_WIDTH_AUGMENT_FRACTION = 1.4
|
||||
ANNOTATION_HEIGHT_AUGMENT_FRACTION = 1.4
|
||||
|
||||
# Interval determining if an action is a tap or a swipe.
|
||||
_SWIPE_DISTANCE_THRESHOLD = 0.04
|
||||
|
||||
|
||||
def _yx_in_bounding_boxes(
|
||||
yx, bounding_boxes
|
||||
):
|
||||
"""Check if the (y,x) point is contained in each bounding box.
|
||||
|
||||
Args:
|
||||
yx: The (y, x) coordinate in pixels of the point.
|
||||
bounding_boxes: A 2D int array of shape (num_bboxes, 4), where each row
|
||||
represents a bounding box: (y_top_left, x_top_left, box_height,
|
||||
box_width). Note: containment is inclusive of the bounding box edges.
|
||||
|
||||
Returns:
|
||||
is_inside: A 1D bool array where each element specifies if the point is
|
||||
contained within the respective box.
|
||||
"""
|
||||
y, x = yx
|
||||
|
||||
# `bounding_boxes` has shape (n_elements, 4); we extract each array along the
|
||||
# last axis into shape (n_elements, 1), then squeeze unneeded dimension.
|
||||
top, left, height, width = [
|
||||
jnp.squeeze(v, axis=-1) for v in jnp.split(bounding_boxes, 4, axis=-1)
|
||||
]
|
||||
|
||||
# The y-axis is inverted for AndroidEnv, so bottom = top + height.
|
||||
bottom, right = top + height, left + width
|
||||
|
||||
return jnp.logical_and(y >= top, y <= bottom) & jnp.logical_and(
|
||||
x >= left, x <= right)
|
||||
|
||||
|
||||
def _resize_annotation_bounding_boxes(
|
||||
annotation_positions, annotation_width_augment_fraction,
|
||||
annotation_height_augment_fraction):
|
||||
"""Resize the bounding boxes by the given fractions.
|
||||
|
||||
Args:
|
||||
annotation_positions: Array of shape (N, 4), where each row represents the
|
||||
(y, x, height, width) of the bounding boxes.
|
||||
annotation_width_augment_fraction: The fraction to augment the box widths,
|
||||
E.g., 1.4 == 240% total increase.
|
||||
annotation_height_augment_fraction: Same as described for width, but for box
|
||||
height.
|
||||
|
||||
Returns:
|
||||
Resized bounding box.
|
||||
|
||||
"""
|
||||
height_change = (
|
||||
annotation_height_augment_fraction * annotation_positions[:, 2])
|
||||
width_change = (
|
||||
annotation_width_augment_fraction * annotation_positions[:, 3])
|
||||
|
||||
# Limit bounding box positions to the screen.
|
||||
resized_annotations = jnp.stack([
|
||||
jnp.maximum(0, annotation_positions[:, 0] - (height_change / 2)),
|
||||
jnp.maximum(0, annotation_positions[:, 1] - (width_change / 2)),
|
||||
jnp.minimum(1, annotation_positions[:, 2] + height_change),
|
||||
jnp.minimum(1, annotation_positions[:, 3] + width_change),
|
||||
],
|
||||
axis=1)
|
||||
return resized_annotations
|
||||
|
||||
|
||||
def is_tap_action(normalized_start_yx,
|
||||
normalized_end_yx):
|
||||
distance = jnp.linalg.norm(
|
||||
jnp.array(normalized_start_yx) - jnp.array(normalized_end_yx))
|
||||
return distance <= _SWIPE_DISTANCE_THRESHOLD
|
||||
|
||||
|
||||
def _is_non_dual_point_action(action_type):
|
||||
return jnp.not_equal(action_type, ActionType.DUAL_POINT)
|
||||
|
||||
|
||||
def _check_tap_actions_match(
|
||||
tap_1_yx,
|
||||
tap_2_yx,
|
||||
annotation_positions,
|
||||
matching_tap_distance_threshold_screen_percentage,
|
||||
annotation_width_augment_fraction,
|
||||
annotation_height_augment_fraction,
|
||||
):
|
||||
"""Determines if two tap actions are the same."""
|
||||
resized_annotation_positions = _resize_annotation_bounding_boxes(
|
||||
annotation_positions,
|
||||
annotation_width_augment_fraction,
|
||||
annotation_height_augment_fraction,
|
||||
)
|
||||
|
||||
# Check if the ground truth tap action falls in an annotation's bounding box.
|
||||
tap1_in_box = _yx_in_bounding_boxes(tap_1_yx, resized_annotation_positions)
|
||||
tap2_in_box = _yx_in_bounding_boxes(tap_2_yx, resized_annotation_positions)
|
||||
both_in_box = jnp.max(tap1_in_box & tap2_in_box)
|
||||
|
||||
# If the ground-truth tap action falls outside any of the annotation
|
||||
# bounding boxes or one of the actions is inside a bounding box and the other
|
||||
# is outside bounding box or vice versa, compare the points using Euclidean
|
||||
# distance.
|
||||
within_threshold = (
|
||||
jnp.linalg.norm(jnp.array(tap_1_yx) - jnp.array(tap_2_yx))
|
||||
<= matching_tap_distance_threshold_screen_percentage
|
||||
)
|
||||
return jnp.logical_or(both_in_box, within_threshold)
|
||||
|
||||
|
||||
def _check_drag_actions_match(
|
||||
drag_1_touch_yx,
|
||||
drag_1_lift_yx,
|
||||
drag_2_touch_yx,
|
||||
drag_2_lift_yx,
|
||||
):
|
||||
"""Determines if two drag actions are the same."""
|
||||
# Store drag deltas (the change in the y and x coordinates from touch to
|
||||
# lift), magnitudes, and the index of the main axis, which is the axis with
|
||||
# the greatest change in coordinate value (e.g. a drag starting at (0, 0) and
|
||||
# ending at (0.3, 0.5) has a main axis index of 1).
|
||||
drag_1_deltas = drag_1_lift_yx - drag_1_touch_yx
|
||||
drag_1_magnitudes = jnp.abs(drag_1_deltas)
|
||||
drag_1_main_axis = np.argmax(drag_1_magnitudes)
|
||||
drag_2_deltas = drag_2_lift_yx - drag_2_touch_yx
|
||||
drag_2_magnitudes = jnp.abs(drag_2_deltas)
|
||||
drag_2_main_axis = np.argmax(drag_2_magnitudes)
|
||||
|
||||
return jnp.equal(drag_1_main_axis, drag_2_main_axis)
|
||||
|
||||
|
||||
def check_actions_match(
|
||||
action_1_touch_yx,
|
||||
action_1_lift_yx,
|
||||
action_1_action_type,
|
||||
action_2_touch_yx,
|
||||
action_2_lift_yx,
|
||||
action_2_action_type,
|
||||
annotation_positions,
|
||||
tap_distance_threshold = _TAP_DISTANCE_THRESHOLD,
|
||||
annotation_width_augment_fraction = ANNOTATION_WIDTH_AUGMENT_FRACTION,
|
||||
annotation_height_augment_fraction = ANNOTATION_HEIGHT_AUGMENT_FRACTION,
|
||||
):
|
||||
"""Determines if two actions are considered to be the same.
|
||||
|
||||
Two actions being "the same" is defined here as two actions that would result
|
||||
in a similar screen state.
|
||||
|
||||
Args:
|
||||
action_1_touch_yx: The (y, x) coordinates of the first action's touch.
|
||||
action_1_lift_yx: The (y, x) coordinates of the first action's lift.
|
||||
action_1_action_type: The action type of the first action.
|
||||
action_2_touch_yx: The (y, x) coordinates of the second action's touch.
|
||||
action_2_lift_yx: The (y, x) coordinates of the second action's lift.
|
||||
action_2_action_type: The action type of the second action.
|
||||
annotation_positions: The positions of the UI annotations for the screen. It
|
||||
is A 2D int array of shape (num_bboxes, 4), where each row represents a
|
||||
bounding box: (y_top_left, x_top_left, box_height, box_width). Note that
|
||||
containment is inclusive of the bounding box edges.
|
||||
tap_distance_threshold: The threshold that determines if two taps result in
|
||||
a matching screen state if they don't fall the same bounding boxes.
|
||||
annotation_width_augment_fraction: The fraction to increase the width of the
|
||||
bounding box by.
|
||||
annotation_height_augment_fraction: The fraction to increase the height of
|
||||
of the bounding box by.
|
||||
|
||||
Returns:
|
||||
A boolean representing whether the two given actions are the same or not.
|
||||
"""
|
||||
action_1_touch_yx = jnp.asarray(action_1_touch_yx)
|
||||
action_1_lift_yx = jnp.asarray(action_1_lift_yx)
|
||||
action_2_touch_yx = jnp.asarray(action_2_touch_yx)
|
||||
action_2_lift_yx = jnp.asarray(action_2_lift_yx)
|
||||
|
||||
# Checks if at least one of the actions is global (i.e. not DUAL_POINT),
|
||||
# because if that is the case, only the actions' types need to be compared.
|
||||
has_non_dual_point_action = jnp.logical_or(
|
||||
_is_non_dual_point_action(action_1_action_type),
|
||||
_is_non_dual_point_action(action_2_action_type),
|
||||
)
|
||||
#print("non dual point: "+str(has_non_dual_point_action))
|
||||
|
||||
different_dual_point_types = jnp.logical_xor(
|
||||
is_tap_action(action_1_touch_yx, action_1_lift_yx),
|
||||
is_tap_action(action_2_touch_yx, action_2_lift_yx),
|
||||
)
|
||||
#print("different dual type: "+str(different_dual_point_types))
|
||||
|
||||
is_tap = jnp.logical_and(
|
||||
is_tap_action(action_1_touch_yx, action_1_lift_yx),
|
||||
is_tap_action(action_2_touch_yx, action_2_lift_yx),
|
||||
)
|
||||
#print("is tap: "+str(is_tap))
|
||||
|
||||
taps_match = _check_tap_actions_match(
|
||||
action_1_touch_yx,
|
||||
action_2_touch_yx,
|
||||
annotation_positions,
|
||||
tap_distance_threshold,
|
||||
annotation_width_augment_fraction,
|
||||
annotation_height_augment_fraction,
|
||||
)
|
||||
#print("tap match: "+str(taps_match))
|
||||
|
||||
taps_match = jnp.logical_and(is_tap, taps_match)
|
||||
#print("tap match: "+str(taps_match))
|
||||
|
||||
drags_match = _check_drag_actions_match(
|
||||
action_1_touch_yx, action_1_lift_yx, action_2_touch_yx, action_2_lift_yx
|
||||
)
|
||||
drags_match = jnp.where(is_tap, False, drags_match)
|
||||
#print("drag match: "+str(drags_match))
|
||||
|
||||
return jnp.where(
|
||||
has_non_dual_point_action,
|
||||
jnp.equal(action_1_action_type, action_2_action_type),
|
||||
jnp.where(
|
||||
different_dual_point_types,
|
||||
False,
|
||||
jnp.logical_or(taps_match, drags_match),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def action_2_format(step_data):
|
||||
# 把test数据集中的动作格式转换为计算matching score的格式
|
||||
action_type = step_data["action_type_id"]
|
||||
|
||||
if action_type == 4:
|
||||
if step_data["action_type_text"] == 'click': # 点击
|
||||
touch_point = step_data["touch"]
|
||||
lift_point = step_data["lift"]
|
||||
else: # 上下左右滑动
|
||||
if step_data["action_type_text"] == 'scroll down':
|
||||
touch_point = [0.5, 0.8]
|
||||
lift_point = [0.5, 0.2]
|
||||
elif step_data["action_type_text"] == 'scroll up':
|
||||
touch_point = [0.5, 0.2]
|
||||
lift_point = [0.5, 0.8]
|
||||
elif step_data["action_type_text"] == 'scroll left':
|
||||
touch_point = [0.2, 0.5]
|
||||
lift_point = [0.8, 0.5]
|
||||
elif step_data["action_type_text"] == 'scroll right':
|
||||
touch_point = [0.8, 0.5]
|
||||
lift_point = [0.2, 0.5]
|
||||
else:
|
||||
touch_point = [-1.0, -1.0]
|
||||
lift_point = [-1.0, -1.0]
|
||||
|
||||
if action_type == 3:
|
||||
typed_text = step_data["type_text"]
|
||||
else:
|
||||
typed_text = ""
|
||||
|
||||
action = {"action_type": action_type, "touch_point": touch_point, "lift_point": lift_point,
|
||||
"typed_text": typed_text}
|
||||
|
||||
action["touch_point"] = [action["touch_point"][1], action["touch_point"][0]]
|
||||
action["lift_point"] = [action["lift_point"][1], action["lift_point"][0]]
|
||||
action["typed_text"] = action["typed_text"].lower()
|
||||
|
||||
return action
|
||||
|
||||
|
||||
def pred_2_format(step_data):
|
||||
# 把模型输出的内容转换为计算action_matching的格式
|
||||
action_type = step_data["action_type"]
|
||||
|
||||
if action_type == 4: # 点击
|
||||
action_type_new = 4
|
||||
touch_point = step_data["click_point"]
|
||||
lift_point = step_data["click_point"]
|
||||
typed_text = ""
|
||||
elif action_type == 0:
|
||||
action_type_new = 4
|
||||
touch_point = [0.5, 0.8]
|
||||
lift_point = [0.5, 0.2]
|
||||
typed_text = ""
|
||||
elif action_type == 1:
|
||||
action_type_new = 4
|
||||
touch_point = [0.5, 0.2]
|
||||
lift_point = [0.5, 0.8]
|
||||
typed_text = ""
|
||||
elif action_type == 8:
|
||||
action_type_new = 4
|
||||
touch_point = [0.2, 0.5]
|
||||
lift_point = [0.8, 0.5]
|
||||
typed_text = ""
|
||||
elif action_type == 9:
|
||||
action_type_new = 4
|
||||
touch_point = [0.8, 0.5]
|
||||
lift_point = [0.2, 0.5]
|
||||
typed_text = ""
|
||||
else:
|
||||
action_type_new = action_type
|
||||
touch_point = [-1.0, -1.0]
|
||||
lift_point = [-1.0, -1.0]
|
||||
typed_text = ""
|
||||
if action_type_new == 3:
|
||||
typed_text = step_data["typed_text"]
|
||||
|
||||
action = {"action_type": action_type_new, "touch_point": touch_point, "lift_point": lift_point,
|
||||
"typed_text": typed_text}
|
||||
|
||||
action["touch_point"] = [action["touch_point"][1], action["touch_point"][0]]
|
||||
action["lift_point"] = [action["lift_point"][1], action["lift_point"][0]]
|
||||
action["typed_text"] = action["typed_text"].lower()
|
||||
|
||||
return action
|
||||
|
||||
|
||||
def pred_2_format_simplified(step_data):
|
||||
# 把模型输出的内容转换为计算action_matching的格式
|
||||
action_type = step_data["action_type"]
|
||||
|
||||
if action_type == 'click' : # 点击
|
||||
action_type_new = 4
|
||||
touch_point = step_data["click_point"]
|
||||
lift_point = step_data["click_point"]
|
||||
typed_text = ""
|
||||
elif action_type == 'scroll' and step_data["direction"] == 'down':
|
||||
action_type_new = 4
|
||||
touch_point = [0.5, 0.8]
|
||||
lift_point = [0.5, 0.2]
|
||||
typed_text = ""
|
||||
elif action_type == 'scroll' and step_data["direction"] == 'up':
|
||||
action_type_new = 4
|
||||
touch_point = [0.5, 0.2]
|
||||
lift_point = [0.5, 0.8]
|
||||
typed_text = ""
|
||||
elif action_type == 'scroll' and step_data["direction"] == 'left':
|
||||
action_type_new = 4
|
||||
touch_point = [0.2, 0.5]
|
||||
lift_point = [0.8, 0.5]
|
||||
typed_text = ""
|
||||
elif action_type == 'scroll' and step_data["direction"] == 'right':
|
||||
action_type_new = 4
|
||||
touch_point = [0.8, 0.5]
|
||||
lift_point = [0.2, 0.5]
|
||||
typed_text = ""
|
||||
elif action_type == 'type':
|
||||
action_type_new = 3
|
||||
touch_point = [-1.0, -1.0]
|
||||
lift_point = [-1.0, -1.0]
|
||||
typed_text = step_data["text"]
|
||||
elif action_type == 'navigate_back':
|
||||
action_type_new = 5
|
||||
touch_point = [-1.0, -1.0]
|
||||
lift_point = [-1.0, -1.0]
|
||||
typed_text = ""
|
||||
elif action_type == 'navigate_home':
|
||||
action_type_new = 6
|
||||
touch_point = [-1.0, -1.0]
|
||||
lift_point = [-1.0, -1.0]
|
||||
typed_text = ""
|
||||
else:
|
||||
action_type_new = action_type
|
||||
touch_point = [-1.0, -1.0]
|
||||
lift_point = [-1.0, -1.0]
|
||||
typed_text = ""
|
||||
# if action_type_new == 'type':
|
||||
# typed_text = step_data["text"]
|
||||
|
||||
action = {"action_type": action_type_new, "touch_point": touch_point, "lift_point": lift_point,
|
||||
"typed_text": typed_text}
|
||||
|
||||
action["touch_point"] = [action["touch_point"][1], action["touch_point"][0]]
|
||||
action["lift_point"] = [action["lift_point"][1], action["lift_point"][0]]
|
||||
action["typed_text"] = action["typed_text"].lower()
|
||||
|
||||
return action
|
||||
@@ -1,45 +0,0 @@
|
||||
'''
|
||||
Adapted from https://github.com/google-research/google-research/tree/master/android_in_the_wild
|
||||
'''
|
||||
|
||||
import enum
|
||||
|
||||
class ActionType(enum.IntEnum):
|
||||
|
||||
# Placeholders for unused enum values
|
||||
UNUSED_0 = 0
|
||||
UNUSED_1 = 1
|
||||
UNUSED_2 = 2
|
||||
UNUSED_8 = 8
|
||||
UNUSED_9 = 9
|
||||
|
||||
########### Agent actions ###########
|
||||
|
||||
# A type action that sends text to the emulator. Note that this simply sends
|
||||
# text and does not perform any clicks for element focus or enter presses for
|
||||
# submitting text.
|
||||
TYPE = 3
|
||||
|
||||
# The dual point action used to represent all gestures.
|
||||
DUAL_POINT = 4
|
||||
|
||||
# These actions differentiate pressing the home and back button from touches.
|
||||
# They represent explicit presses of back and home performed using ADB.
|
||||
PRESS_BACK = 5
|
||||
PRESS_HOME = 6
|
||||
|
||||
# An action representing that ADB command for hitting enter was performed.
|
||||
PRESS_ENTER = 7
|
||||
|
||||
########### Episode status actions ###########
|
||||
|
||||
# An action used to indicate the desired task has been completed and resets
|
||||
# the environment. This action should also be used in the case that the task
|
||||
# has already been completed and there is nothing to do.
|
||||
# e.g. The task is to turn on the Wi-Fi when it is already on
|
||||
STATUS_TASK_COMPLETE = 10
|
||||
|
||||
# An action used to indicate that desired task is impossible to complete and
|
||||
# resets the environment. This can be a result of many different things
|
||||
# including UI changes, Android version differences, etc.
|
||||
STATUS_TASK_IMPOSSIBLE = 11
|
||||
32
util/omniparser.py
Normal file
@@ -0,0 +1,32 @@
|
||||
from util.utils import get_som_labeled_img, get_caption_model_processor, get_yolo_model, check_ocr_box
|
||||
import torch
|
||||
from PIL import Image
|
||||
import io
|
||||
import base64
|
||||
from typing import Dict
|
||||
class Omniparser(object):
|
||||
def __init__(self, config: Dict):
|
||||
self.config = config
|
||||
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
||||
|
||||
self.som_model = get_yolo_model(model_path=config['som_model_path'])
|
||||
self.caption_model_processor = get_caption_model_processor(model_name=config['caption_model_name'], model_name_or_path=config['caption_model_path'], device=device)
|
||||
print('Omniparser initialized!!!')
|
||||
|
||||
def parse(self, image_base64: str):
|
||||
image_bytes = base64.b64decode(image_base64)
|
||||
image = Image.open(io.BytesIO(image_bytes))
|
||||
print('image size:', image.size)
|
||||
|
||||
box_overlay_ratio = max(image.size) / 3200
|
||||
draw_bbox_config = {
|
||||
'text_scale': 0.8 * box_overlay_ratio,
|
||||
'text_thickness': max(int(2 * box_overlay_ratio), 1),
|
||||
'text_padding': max(int(3 * box_overlay_ratio), 1),
|
||||
'thickness': max(int(3 * box_overlay_ratio), 1),
|
||||
}
|
||||
|
||||
(text, ocr_bbox), _ = check_ocr_box(image, display_img=False, output_bb_format='xyxy', easyocr_args={'text_threshold': 0.8}, use_paddleocr=False)
|
||||
dino_labled_img, label_coordinates, parsed_content_list = get_som_labeled_img(image, self.som_model, BOX_TRESHOLD = self.config['BOX_TRESHOLD'], output_coord_in_ratio=True, ocr_bbox=ocr_bbox,draw_bbox_config=draw_bbox_config, caption_model_processor=self.caption_model_processor, ocr_text=text,use_local_semantics=True, iou_threshold=0.7, scale_img=False, batch_size=128)
|
||||
|
||||
return dino_labled_img, parsed_content_list
|
||||
108
utils.py → util/utils.py
Executable file → Normal file
@@ -35,12 +35,13 @@ import base64
|
||||
import os
|
||||
import ast
|
||||
import torch
|
||||
from typing import Tuple, List
|
||||
from typing import Tuple, List, Union
|
||||
from torchvision.ops import box_convert
|
||||
import re
|
||||
from torchvision.transforms import ToPILImage
|
||||
import supervision as sv
|
||||
import torchvision.transforms as T
|
||||
from util.box_annotator import BoxAnnotator
|
||||
|
||||
|
||||
def get_caption_model_processor(model_name, model_name_or_path="Salesforce/blip2-opt-2.7b", device=None):
|
||||
@@ -77,22 +78,21 @@ def get_yolo_model(model_path):
|
||||
@torch.inference_mode()
|
||||
def get_parsed_content_icon(filtered_boxes, starting_idx, image_source, caption_model_processor, prompt=None, batch_size=None):
|
||||
# Number of samples per batch, --> 256 roughly takes 23 GB of GPU memory for florence model
|
||||
|
||||
to_pil = ToPILImage()
|
||||
if starting_idx:
|
||||
non_ocr_boxes = filtered_boxes[starting_idx:]
|
||||
else:
|
||||
non_ocr_boxes = filtered_boxes
|
||||
croped_pil_image = []
|
||||
t0 = time.time()
|
||||
for i, coord in enumerate(non_ocr_boxes):
|
||||
xmin, xmax = int(coord[0]*image_source.shape[1]), int(coord[2]*image_source.shape[1])
|
||||
ymin, ymax = int(coord[1]*image_source.shape[0]), int(coord[3]*image_source.shape[0])
|
||||
cropped_image = image_source[ymin:ymax, xmin:xmax, :]
|
||||
# resize the image to 224x224 to avoid long overhead in clipimageprocessor # TODO
|
||||
cropped_image = cv2.resize(cropped_image, (224, 224))
|
||||
croped_pil_image.append(to_pil(cropped_image))
|
||||
print('time to prepare bbox:', time.time()-t0)
|
||||
try:
|
||||
xmin, xmax = int(coord[0]*image_source.shape[1]), int(coord[2]*image_source.shape[1])
|
||||
ymin, ymax = int(coord[1]*image_source.shape[0]), int(coord[3]*image_source.shape[0])
|
||||
cropped_image = image_source[ymin:ymax, xmin:xmax, :]
|
||||
cropped_image = cv2.resize(cropped_image, (64, 64))
|
||||
croped_pil_image.append(to_pil(cropped_image))
|
||||
except:
|
||||
continue
|
||||
|
||||
model, processor = caption_model_processor['model'], caption_model_processor['processor']
|
||||
if not prompt:
|
||||
@@ -112,14 +112,10 @@ def get_parsed_content_icon(filtered_boxes, starting_idx, image_source, caption_
|
||||
inputs = processor(images=batch, text=[prompt]*len(batch), return_tensors="pt", do_resize=False).to(device=device, dtype=torch.float16)
|
||||
else:
|
||||
inputs = processor(images=batch, text=[prompt]*len(batch), return_tensors="pt").to(device=device)
|
||||
t2 = time.time()
|
||||
print('time to process image + tokenize text inputs:', t2-t1)
|
||||
if 'florence' in model.config.name_or_path:
|
||||
generated_ids = model.generate(input_ids=inputs["input_ids"],pixel_values=inputs["pixel_values"],max_new_tokens=20,num_beams=1, do_sample=False)
|
||||
else:
|
||||
generated_ids = model.generate(**inputs, max_length=100, num_beams=5, no_repeat_ngram_size=2, early_stopping=True, num_return_sequences=1) # temperature=0.01, do_sample=True,
|
||||
t3 = time.time()
|
||||
print('time to generate:', t3-t2)
|
||||
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)
|
||||
generated_text = [gen.strip() for gen in generated_text]
|
||||
generated_texts.extend(generated_text)
|
||||
@@ -282,10 +278,10 @@ def remove_overlap_new(boxes, iou_threshold, ocr_bbox=None):
|
||||
is_valid_box = False
|
||||
break
|
||||
if is_valid_box:
|
||||
# add the following 2 lines to include ocr bbox
|
||||
if ocr_bbox:
|
||||
# keep yolo boxes + prioritize ocr label
|
||||
box_added = False
|
||||
ocr_labels = ''
|
||||
for box3_elem in ocr_bbox:
|
||||
if not box_added:
|
||||
box3 = box3_elem['bbox']
|
||||
@@ -293,25 +289,22 @@ def remove_overlap_new(boxes, iou_threshold, ocr_bbox=None):
|
||||
# box_added = True
|
||||
# delete the box3_elem from ocr_bbox
|
||||
try:
|
||||
filtered_boxes.append({'type': 'text', 'bbox': box1_elem['bbox'], 'interactivity': True, 'content': box3_elem['content']})
|
||||
# gather all ocr labels
|
||||
ocr_labels += box3_elem['content'] + ' '
|
||||
filtered_boxes.remove(box3_elem)
|
||||
# print('remove ocr bbox:', box3_elem)
|
||||
except:
|
||||
continue
|
||||
# break
|
||||
elif is_inside(box1, box3): # icon inside ocr
|
||||
elif is_inside(box1, box3): # icon inside ocr, don't added this icon box, no need to check other ocr bbox bc no overlap between ocr bbox, icon can only be in one ocr box
|
||||
box_added = True
|
||||
# try:
|
||||
# filtered_boxes.append({'type': 'icon', 'bbox': box1_elem['bbox'], 'interactivity': True, 'content': None})
|
||||
# filtered_boxes.remove(box3_elem)
|
||||
# except:
|
||||
# continue
|
||||
break
|
||||
else:
|
||||
continue
|
||||
if not box_added:
|
||||
filtered_boxes.append({'type': 'icon', 'bbox': box1_elem['bbox'], 'interactivity': True, 'content': None})
|
||||
|
||||
if ocr_labels:
|
||||
filtered_boxes.append({'type': 'icon', 'bbox': box1_elem['bbox'], 'interactivity': True, 'content': ocr_labels, 'source':'box_yolo_content_ocr'})
|
||||
else:
|
||||
filtered_boxes.append({'type': 'icon', 'bbox': box1_elem['bbox'], 'interactivity': True, 'content': None, 'source':'box_yolo_content_yolo'})
|
||||
else:
|
||||
filtered_boxes.append(box1)
|
||||
return filtered_boxes # torch.tensor(filtered_boxes)
|
||||
@@ -354,7 +347,6 @@ def annotate(image_source: np.ndarray, boxes: torch.Tensor, logits: torch.Tensor
|
||||
|
||||
labels = [f"{phrase}" for phrase in range(boxes.shape[0])]
|
||||
|
||||
from util.box_annotator import BoxAnnotator
|
||||
box_annotator = BoxAnnotator(text_scale=text_scale, text_padding=text_padding,text_thickness=text_thickness,thickness=thickness) # 0.8 for mobile/web, 0.3 for desktop # 0.4 for mind2web
|
||||
annotated_frame = image_source.copy()
|
||||
annotated_frame = box_annotator.annotate(scene=annotated_frame, detections=detections, labels=labels, image_size=(w,h))
|
||||
@@ -384,20 +376,20 @@ def predict(model, image, caption, box_threshold, text_threshold):
|
||||
return boxes, logits, phrases
|
||||
|
||||
|
||||
def predict_yolo(model, image_path, box_threshold, imgsz, scale_img, iou_threshold=0.7):
|
||||
def predict_yolo(model, image, box_threshold, imgsz, scale_img, iou_threshold=0.7):
|
||||
""" Use huggingface model to replace the original model
|
||||
"""
|
||||
# model = model['model']
|
||||
if scale_img:
|
||||
result = model.predict(
|
||||
source=image_path,
|
||||
source=image,
|
||||
conf=box_threshold,
|
||||
imgsz=imgsz,
|
||||
iou=iou_threshold, # default 0.7
|
||||
)
|
||||
else:
|
||||
result = model.predict(
|
||||
source=image_path,
|
||||
source=image,
|
||||
conf=box_threshold,
|
||||
iou=iou_threshold, # default 0.7
|
||||
)
|
||||
@@ -407,34 +399,41 @@ def predict_yolo(model, image_path, box_threshold, imgsz, scale_img, iou_thresho
|
||||
|
||||
return boxes, conf, phrases
|
||||
|
||||
def int_box_area(box, w, h):
|
||||
x1, y1, x2, y2 = box
|
||||
int_box = [int(x1*w), int(y1*h), int(x2*w), int(y2*h)]
|
||||
area = (int_box[2] - int_box[0]) * (int_box[3] - int_box[1])
|
||||
return area
|
||||
|
||||
def get_som_labeled_img(img_path, model=None, BOX_TRESHOLD = 0.01, output_coord_in_ratio=False, ocr_bbox=None, text_scale=0.4, text_padding=5, draw_bbox_config=None, caption_model_processor=None, ocr_text=[], use_local_semantics=True, iou_threshold=0.9,prompt=None, scale_img=False, imgsz=None, batch_size=64):
|
||||
""" ocr_bbox: list of xyxy format bbox
|
||||
def get_som_labeled_img(image_source: Union[str, Image.Image], model=None, BOX_TRESHOLD=0.01, output_coord_in_ratio=False, ocr_bbox=None, text_scale=0.4, text_padding=5, draw_bbox_config=None, caption_model_processor=None, ocr_text=[], use_local_semantics=True, iou_threshold=0.9,prompt=None, scale_img=False, imgsz=None, batch_size=64):
|
||||
"""Process either an image path or Image object
|
||||
|
||||
Args:
|
||||
image_source: Either a file path (str) or PIL Image object
|
||||
...
|
||||
"""
|
||||
image_source = Image.open(img_path).convert("RGB")
|
||||
if isinstance(image_source, str):
|
||||
image_source = Image.open(image_source).convert("RGB")
|
||||
|
||||
w, h = image_source.size
|
||||
if not imgsz:
|
||||
imgsz = (h, w)
|
||||
# print('image size:', w, h)
|
||||
xyxy, logits, phrases = predict_yolo(model=model, image_path=img_path, box_threshold=BOX_TRESHOLD, imgsz=imgsz, scale_img=scale_img, iou_threshold=0.1)
|
||||
xyxy, logits, phrases = predict_yolo(model=model, image=image_source, box_threshold=BOX_TRESHOLD, imgsz=imgsz, scale_img=scale_img, iou_threshold=0.1)
|
||||
xyxy = xyxy / torch.Tensor([w, h, w, h]).to(xyxy.device)
|
||||
image_source = np.asarray(image_source)
|
||||
phrases = [str(i) for i in range(len(phrases))]
|
||||
|
||||
# annotate the image with labels
|
||||
h, w, _ = image_source.shape
|
||||
if ocr_bbox:
|
||||
ocr_bbox = torch.tensor(ocr_bbox) / torch.Tensor([w, h, w, h])
|
||||
ocr_bbox=ocr_bbox.tolist()
|
||||
else:
|
||||
print('no ocr bbox!!!')
|
||||
ocr_bbox = None
|
||||
# filtered_boxes = remove_overlap(boxes=xyxy, iou_threshold=iou_threshold, ocr_bbox=ocr_bbox)
|
||||
# starting_idx = len(ocr_bbox)
|
||||
# print('len(filtered_boxes):', len(filtered_boxes), starting_idx)
|
||||
|
||||
ocr_bbox_elem = [{'type': 'text', 'bbox':box, 'interactivity':False, 'content':txt} for box, txt in zip(ocr_bbox, ocr_text)]
|
||||
xyxy_elem = [{'type': 'icon', 'bbox':box, 'interactivity':True, 'content':None} for box in xyxy.tolist()]
|
||||
ocr_bbox_elem = [{'type': 'text', 'bbox':box, 'interactivity':False, 'content':txt, 'source': 'box_ocr_content_ocr'} for box, txt in zip(ocr_bbox, ocr_text) if int_box_area(box, w, h) > 0]
|
||||
xyxy_elem = [{'type': 'icon', 'bbox':box, 'interactivity':True, 'content':None} for box in xyxy.tolist() if int_box_area(box, w, h) > 0]
|
||||
filtered_boxes = remove_overlap_new(boxes=xyxy_elem, iou_threshold=iou_threshold, ocr_bbox=ocr_bbox_elem)
|
||||
|
||||
# sort the filtered_boxes so that the one with 'content': None is at the end, and get the index of the first 'content': None
|
||||
@@ -444,7 +443,6 @@ def get_som_labeled_img(img_path, model=None, BOX_TRESHOLD = 0.01, output_coord_
|
||||
filtered_boxes = torch.tensor([box['bbox'] for box in filtered_boxes_elem])
|
||||
print('len(filtered_boxes):', len(filtered_boxes), starting_idx)
|
||||
|
||||
|
||||
# get parsed icon local semantics
|
||||
time1 = time.time()
|
||||
if use_local_semantics:
|
||||
@@ -483,7 +481,6 @@ def get_som_labeled_img(img_path, model=None, BOX_TRESHOLD = 0.01, output_coord_
|
||||
pil_img.save(buffered, format="PNG")
|
||||
encoded_image = base64.b64encode(buffered.getvalue()).decode('ascii')
|
||||
if output_coord_in_ratio:
|
||||
# h, w, _ = image_source.shape
|
||||
label_coordinates = {k: [v[0]/w, v[1]/h, v[2]/w, v[3]/h] for k, v in label_coordinates.items()}
|
||||
assert w == annotated_frame.shape[1] and h == annotated_frame.shape[0]
|
||||
|
||||
@@ -504,46 +501,43 @@ def get_xywh_yolo(input):
|
||||
x, y, w, h = input[0], input[1], input[2] - input[0], input[3] - input[1]
|
||||
x, y, w, h = int(x), int(y), int(w), int(h)
|
||||
return x, y, w, h
|
||||
|
||||
|
||||
|
||||
def check_ocr_box(image_path, display_img = True, output_bb_format='xywh', goal_filtering=None, easyocr_args=None, use_paddleocr=False):
|
||||
def check_ocr_box(image_source: Union[str, Image.Image], display_img = True, output_bb_format='xywh', goal_filtering=None, easyocr_args=None, use_paddleocr=False):
|
||||
if isinstance(image_source, str):
|
||||
image_source = Image.open(image_source)
|
||||
if image_source.mode == 'RGBA':
|
||||
# Convert RGBA to RGB to avoid alpha channel issues
|
||||
image_source = image_source.convert('RGB')
|
||||
image_np = np.array(image_source)
|
||||
w, h = image_source.size
|
||||
if use_paddleocr:
|
||||
if easyocr_args is None:
|
||||
text_threshold = 0.5
|
||||
else:
|
||||
text_threshold = easyocr_args['text_threshold']
|
||||
result = paddle_ocr.ocr(image_path, cls=False)[0]
|
||||
# conf = [item[1] for item in result]
|
||||
result = paddle_ocr.ocr(image_np, cls=False)[0]
|
||||
coord = [item[0] for item in result if item[1][1] > text_threshold]
|
||||
text = [item[1][0] for item in result if item[1][1] > text_threshold]
|
||||
else: # EasyOCR
|
||||
if easyocr_args is None:
|
||||
easyocr_args = {}
|
||||
result = reader.readtext(image_path, **easyocr_args)
|
||||
# print('goal filtering pred:', result[-5:])
|
||||
result = reader.readtext(image_np, **easyocr_args)
|
||||
coord = [item[0] for item in result]
|
||||
text = [item[1] for item in result]
|
||||
# read the image using cv2
|
||||
if display_img:
|
||||
opencv_img = cv2.imread(image_path)
|
||||
opencv_img = cv2.cvtColor(opencv_img, cv2.COLOR_RGB2BGR)
|
||||
opencv_img = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
|
||||
bb = []
|
||||
for item in coord:
|
||||
x, y, a, b = get_xywh(item)
|
||||
# print(x, y, a, b)
|
||||
bb.append((x, y, a, b))
|
||||
cv2.rectangle(opencv_img, (x, y), (x+a, y+b), (0, 255, 0), 2)
|
||||
|
||||
# Display the image
|
||||
plt.imshow(opencv_img)
|
||||
# matplotlib expects RGB
|
||||
plt.imshow(cv2.cvtColor(opencv_img, cv2.COLOR_BGR2RGB))
|
||||
else:
|
||||
if output_bb_format == 'xywh':
|
||||
bb = [get_xywh(item) for item in coord]
|
||||
elif output_bb_format == 'xyxy':
|
||||
bb = [get_xyxy(item) for item in coord]
|
||||
# print('bounding box!!!', bb)
|
||||
return (text, bb), goal_filtering
|
||||
|
||||
|
||||
|
||||