Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Back . and isort . #1115

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion interpreter/core/computer/clipboard/clipboard.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import os

from ...utils.lazy_import import lazy_import

# Lazy import of optional packages
pyperclip = lazy_import('pyperclip')
pyperclip = lazy_import("pyperclip")


class Clipboard:
def __init__(self, computer):
Expand Down
38 changes: 18 additions & 20 deletions interpreter/core/computer/contacts/contacts.py
Original file line number Diff line number Diff line change
@@ -1,73 +1,72 @@
import platform

from ..utils.run_applescript import run_applescript_capture


class Contacts:
def __init__(self, computer):
self.computer = computer


def get_phone_number(self, contact_name):
"""
Returns the phone number of a contact by name.
"""
if platform.system() != 'Darwin':
if platform.system() != "Darwin":
return "This method is only supported on MacOS"
script = f'''

script = f"""
tell application "Contacts"
set thePerson to first person whose name is "{contact_name}"
set theNumber to value of first phone of thePerson
return theNumber
end tell
'''
"""
stout, stderr = run_applescript_capture(script)
# If the person is not found, we will try to find similar contacts
if "Can’t get person" in stderr:
names= self.get_full_names_from_first_name(contact_name)
names = self.get_full_names_from_first_name(contact_name)
if names == "No contacts found":
return "No contacts found"
else:
# Language model friendly error message
return f"A contact for '{contact_name}' was not found, perhaps one of these similar contacts might be what you are looking for? {names} \n Please try again and provide a more specific contact name."
else:
return stout.replace('\n', '')

return stout.replace("\n", "")

def get_email_address(self, contact_name):
"""
Returns the email address of a contact by name.
"""
if platform.system() != 'Darwin':
if platform.system() != "Darwin":
return "This method is only supported on MacOS"
script = f'''

script = f"""
tell application "Contacts"
set thePerson to first person whose name is "{contact_name}"
set theEmail to value of first email of thePerson
return theEmail
end tell
'''
"""
stout, stderr = run_applescript_capture(script)
# If the person is not found, we will try to find similar contacts
if "Can’t get person" in stderr:
names= self.get_full_names_from_first_name(contact_name)
names = self.get_full_names_from_first_name(contact_name)
if names == "No contacts found":
return "No contacts found"
else:
# Language model friendly error message
return f"A contact for '{contact_name}' was not found, perhaps one of these similar contacts might be what you are looking for? {names} \n Please try again and provide a more specific contact name."
else:
return stout.replace('\n', '')

return stout.replace("\n", "")

def get_full_names_from_first_name(self, first_name):
"""
Returns a list of full names of contacts that contain the first name provided.
"""
if platform.system() != 'Darwin':
if platform.system() != "Darwin":
return "This method is only supported on MacOS"
script = f'''

script = f"""
tell application "Contacts"
set matchingPeople to every person whose name contains "{first_name}"
set namesList to {{}}
Expand All @@ -76,10 +75,9 @@ def get_full_names_from_first_name(self, first_name):
end repeat
return namesList
end tell
'''
"""
names, _ = run_applescript_capture(script)
if names:
return names
else:
return "No contacts found."

3 changes: 2 additions & 1 deletion interpreter/core/computer/docs/docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
from ...utils.lazy_import import lazy_import

# Lazy import of aifs, imported when needed to speed up start time
aifs = lazy_import('aifs')
aifs = lazy_import("aifs")


class Docs:
def __init__(self, computer):
Expand Down
3 changes: 2 additions & 1 deletion interpreter/core/computer/files/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
from ...utils.lazy_import import lazy_import

# Lazy import of aifs, imported when needed
aifs = lazy_import('aifs')
aifs = lazy_import("aifs")


class Files:
def __init__(self, computer):
Expand Down
6 changes: 4 additions & 2 deletions interpreter/core/computer/keyboard/keyboard.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import os
import platform
import time

from ...utils.lazy_import import lazy_import

# Lazy import of pyautogui
pyautogui = lazy_import('pyautogui')
pyautogui = lazy_import("pyautogui")


class Keyboard:
"""A class to simulate keyboard inputs"""
Expand All @@ -14,7 +16,7 @@ def __init__(self, computer):

def write(self, text, interval=None, **kwargs):
"""
Type out a string of characters.
Type out a string of characters.
"""
time.sleep(0.15)

Expand Down
9 changes: 4 additions & 5 deletions interpreter/core/computer/sms/sms.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import subprocess
import platform
import subprocess

from ..utils.run_applescript import run_applescript


Expand All @@ -8,16 +9,14 @@ def __init__(self, computer):
self.computer = computer
self.messages_app = "Messages"



def send(self, to, message):
"""
Sends an SMS message to the specified recipient using the Messages app.
"""
# Check if the operating system is MacOS, as this functionality is MacOS-specific.
if platform.system() != 'Darwin':
if platform.system() != "Darwin":
return "This method is only supported on MacOS"

# Remove any newline characters from the recipient number.
to = to.replace("\n", "")
# Escape double quotes in the message and recipient variables to prevent script errors.
Expand Down
5 changes: 1 addition & 4 deletions interpreter/core/respond.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,7 @@ def respond(interpreter):
)
elif interpreter.offline and not interpreter.os:
print(traceback.format_exc())
raise Exception(
"Error occurred. "
+ str(e)
)
raise Exception("Error occurred. " + str(e))
else:
raise

Expand Down
1 change: 1 addition & 0 deletions interpreter/core/utils/lazy_import.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import importlib.util
import sys


def lazy_import(name, optional=True):
"""Lazily import a module, specified by the name. Useful for optional packages, to speed up startup times."""
# Check if module is already imported
Expand Down
79 changes: 43 additions & 36 deletions interpreter/terminal_interface/magic_commands.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import json
import os
import subprocess
import time
import sys

import time
from datetime import datetime

from ..core.utils.system_debug_info import system_info
from .utils.count_tokens import count_messages_tokens
from .utils.display_markdown_message import display_markdown_message
Expand Down Expand Up @@ -175,15 +175,17 @@ def handle_count_tokens(self, prompt):

display_markdown_message("\n".join(outputs))


def get_downloads_path():
if os.name == 'nt':
if os.name == "nt":
# For Windows
downloads = os.path.join(os.environ['USERPROFILE'], 'Downloads')
downloads = os.path.join(os.environ["USERPROFILE"], "Downloads")
else:
# For MacOS and Linux
downloads = os.path.join(os.path.expanduser('~'), 'Downloads')
downloads = os.path.join(os.path.expanduser("~"), "Downloads")
return downloads


def install_and_import(package):
try:
module = __import__(package)
Expand All @@ -193,29 +195,32 @@ def install_and_import(package):
print("")
print(f"Installing {package}...")
print("")
subprocess.check_call([sys.executable, "-m", "pip", "install", package],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
subprocess.check_call(
[sys.executable, "-m", "pip", "install", package],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
module = __import__(package)
except subprocess.CalledProcessError:
# If pip fails, try pip3
try:
subprocess.check_call([sys.executable, "-m", "pip3", "install", package],
subprocess.check_call(
[sys.executable, "-m", "pip3", "install", package],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
stderr=subprocess.DEVNULL,
)
except subprocess.CalledProcessError:
print(f"Failed to install package {package}.")
return
finally:
globals()[package] = module
return module
return module


def jupyter(self, arguments):
# Dynamically install nbformat if not already installed
nbformat = install_and_import('nbformat')
from nbformat.v4 import new_notebook, new_code_cell, new_markdown_cell
nbformat = install_and_import("nbformat")
from nbformat.v4 import new_code_cell, new_markdown_cell, new_notebook

downloads = get_downloads_path()
current_time = datetime.now()
Expand All @@ -224,31 +229,33 @@ def jupyter(self, arguments):
notebook_path = os.path.join(downloads, filename)
nb = new_notebook()
cells = []

for msg in self.messages:
if msg['role'] == 'user' and msg['type'] == 'message':
# Prefix user messages with '>' to render them as block quotes, so they stand out
content = f"> {msg['content']}"
cells.append(new_markdown_cell(content))
elif msg['role'] == 'assistant' and msg['type'] == 'message':
cells.append(new_markdown_cell(msg['content']))
elif msg['type'] == 'code':
# Handle the language of the code cell
if 'format' in msg and msg['format']:
language = msg['format']
else:
language = 'python' # Default to Python if no format specified
code_cell = new_code_cell(msg['content'])
code_cell.metadata.update({"language": language})
cells.append(code_cell)
nb['cells'] = cells
with open(notebook_path, 'w', encoding='utf-8') as f:
if msg["role"] == "user" and msg["type"] == "message":
# Prefix user messages with '>' to render them as block quotes, so they stand out
content = f"> {msg['content']}"
cells.append(new_markdown_cell(content))
elif msg["role"] == "assistant" and msg["type"] == "message":
cells.append(new_markdown_cell(msg["content"]))
elif msg["type"] == "code":
# Handle the language of the code cell
if "format" in msg and msg["format"]:
language = msg["format"]
else:
language = "python" # Default to Python if no format specified
code_cell = new_code_cell(msg["content"])
code_cell.metadata.update({"language": language})
cells.append(code_cell)

nb["cells"] = cells

with open(notebook_path, "w", encoding="utf-8") as f:
nbformat.write(nb, f)

print("")
display_markdown_message(f"Jupyter notebook file exported to {os.path.abspath(notebook_path)}")
display_markdown_message(
f"Jupyter notebook file exported to {os.path.abspath(notebook_path)}"
)


def handle_magic_command(self, user_input):
Expand Down