Skip to content

Commit

Permalink
feat: added screenshot tool (#92)
Browse files Browse the repository at this point in the history
* feat: started working on screenshot tool

* fix: updated the screenshot tool

* fix: completed screenshot tool
  • Loading branch information
ErikBjare authored Oct 2, 2024
1 parent a3bcf49 commit f4c63c2
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
2 changes: 2 additions & 0 deletions gptme/tools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from .tmux import tool as tmux_tool
from .vision import tool as vision_tool
from .youtube import tool as youtube_tool
from .screenshot import tool as screenshot_tool

logger = logging.getLogger(__name__)

Expand All @@ -40,6 +41,7 @@
gh_tool,
chats_tool,
youtube_tool,
screenshot_tool,
vision_tool,
# python tool is loaded last to ensure all functions are registered
python_tool,
Expand Down
53 changes: 53 additions & 0 deletions gptme/tools/screenshot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""
A simple screenshot tool, using `screencapture` on macOS and `scrot` on Linux.
"""

import os
import subprocess
from collections.abc import Generator
from datetime import datetime
from pathlib import Path

from ..message import Message
from .base import ToolSpec


def _screenshot(path: Path) -> Path:
path = Path(path).resolve()

if os.name == "posix":
if os.uname().sysname == "Darwin": # macOS
subprocess.run(["screencapture", str(path)], check=True)
else: # Linux
subprocess.run(["scrot", "-s", str(path)], check=True)
else:
raise NotImplementedError(
"Screenshot functionality is only available on macOS and Linux."
)

return path


def screenshot(path: Path | None = None) -> Generator[Message, None, None]:
"""
Take a screenshot and save it to a file.
"""
if path is None:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
path = Path(f"screenshot_{timestamp}.png")

try:
path = _screenshot(path)
yield Message("system", f"Screenshot saved to: {path}")
except NotImplementedError as e:
yield Message("system", str(e))
except subprocess.CalledProcessError:
yield Message("system", "Failed to capture screenshot.")


tool = ToolSpec(
name="screenshot",
desc="Take a screenshot",
instructions="Use this tool to capture a screenshot. You can optionally specify a filename.",
functions=[screenshot],
)

0 comments on commit f4c63c2

Please sign in to comment.