Skip to content

Commit 4240865

Browse files
committed
Fixed Package manager Installation with Pip
1 parent 92b9af1 commit 4240865

File tree

4 files changed

+31
-58
lines changed

4 files changed

+31
-58
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -324,7 +324,7 @@ If you're interested in contributing to **Code-Interpreter**, we'd love to have
324324
- **v2.1.4** - Added **GPT-4o** models they are most effecient and cost effective models from **OpenAI**
325325
- **v2.1.5** - Fixed OS type detection **Bug** for MacOS and feautre to open file with default editor.
326326

327-
# 🔥 **v2.2**
327+
🔥 **v2.2** - Save/Execute _commands_ and _scripts_, Fixed **Logging** and **Package Manager**.
328328
- **Save/Execute**: Added support to **save and execute code, commands, and scripts** directly to external files.
329329
- **Updated Commands**:
330330
- Removed the `/debug` command and replaced it with the `/fix` command.

Diff for: libs/logger.py

+2-6
Original file line numberDiff line numberDiff line change
@@ -10,21 +10,17 @@ class Logger:
1010
@staticmethod
1111
def initialize(filename: str):
1212
if Logger._logger is None:
13-
# Create the root logger
1413
Logger._logger = logging.getLogger(filename)
1514
Logger._logger.setLevel(logging.DEBUG)
1615

1716
# Ensure no debug prints on console from any library
1817
Logger._logger.propagate = False
1918

2019
# Define the logging format
21-
log_format = ("%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] "
22-
"[%(funcName)s] - %(message)s")
20+
log_format = ("%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] [%(funcName)s] - %(message)s")
2321

2422
# Create a rotating file handler to manage log file sizes and backups
25-
Logger._file_handler = RotatingFileHandler(
26-
filename, maxBytes=5*1024*1024, backupCount=5
27-
) # 5MB per file
23+
Logger._file_handler = RotatingFileHandler(filename, maxBytes=5*1024*1024, backupCount=5) # 5MB per file
2824
Logger._file_handler.setFormatter(logging.Formatter(log_format))
2925
Logger._file_handler.setLevel(logging.DEBUG)
3026

Diff for: libs/package_manager.py

+28-48
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,17 @@
33
import logging
44
import requests
55
import stdlib_list
6+
from libs.logger import Logger
7+
68

79
class PackageManager:
10+
logger = None
11+
812
def __init__(self):
913
self.pip_command = "pip"
1014
self.pip3_command = "pip3"
1115
self.npm_command = "npm"
12-
self.logger = logging.getLogger(__name__)
13-
handler = logging.StreamHandler()
14-
formatter = logging.Formatter('%(asctime)s [%(levelname)s] [%(name)s:%(lineno)d] [%(funcName)s] - %(message)s')
15-
handler.setFormatter(formatter)
16-
self.logger.addHandler(handler)
17-
self.logger.setLevel(logging.INFO)
16+
self.logger = Logger.initialize("logs/interpreter.log")
1817

1918
def install_package(self, package_name, language):
2019
if language == "python":
@@ -23,7 +22,7 @@ def install_package(self, package_name, language):
2322
self.logger.error(exception)
2423
raise exception
2524

26-
if not self._is_package_installed(package_name,"pip"):
25+
if not self._is_package_installed(package_name, "pip"):
2726
try:
2827
# Try to install the package using pip
2928
self._install_package_with_pip(package_name)
@@ -58,7 +57,7 @@ def install_package(self, package_name, language):
5857
self.logger.error(exception)
5958
raise exception
6059

61-
def extract_package_name(self,error,language):
60+
def extract_package_name(self, error,language):
6261
if language == "python":
6362
return self._extract_python_package_name(error)
6463
elif language == "javascript":
@@ -76,31 +75,31 @@ def get_system_modules(self):
7675
except Exception as exception:
7776
raise ValueError("An error occurred while getting module names") from exception
7877

79-
def _install_package_with_pip(self, package_name):
78+
def _install_package_with_pip(self, package_name):
8079
try:
8180
subprocess.check_call([self.pip_command, "install", package_name])
8281
self.logger.info(f"Successfully installed package with pip: {package_name}")
8382
except subprocess.CalledProcessError as exception:
8483
self.logger.error(f"Failed to install package with pip: {package_name}")
8584
raise exception
8685

87-
def _install_package_with_pip3(self, package_name):
86+
def _install_package_with_pip3(self, package_name):
8887
try:
8988
subprocess.check_call([self.pip3_command, "install", package_name])
9089
self.logger.info(f"Successfully installed package with pip3: {package_name}")
9190
except subprocess.CalledProcessError as exception:
9291
self.logger.error(f"Failed to install package with pip3: {package_name}")
9392
raise exception
9493

95-
def _install_package_with_npm(self, package_name):
94+
def _install_package_with_npm(self, package_name):
9695
try:
9796
subprocess.check_call([self.npm_command, "install", package_name])
9897
self.logger.info(f"Successfully installed package with npm: {package_name}")
9998
except subprocess.CalledProcessError as exception:
10099
self.logger.error(f"Failed to install package with npm: {package_name}")
101100
raise exception
102101

103-
def _is_package_installed(self, package_name, package_manager):
102+
def _is_package_installed(self, package_name, package_manager):
104103
if package_manager == "pip":
105104
try:
106105
subprocess.check_call([self.pip_command, "show", package_name])
@@ -126,17 +125,8 @@ def _is_package_installed(self, package_name, package_manager):
126125
exception = ValueError("Invalid package manager selected.")
127126
self.logger.error(exception)
128127
raise exception
129-
130-
def _install_package_with_npm(self, package_name):
131-
try:
132-
subprocess.check_call([self.npm_command, "install", package_name])
133-
self.logger.info(f"Successfully installed package with npm: {package_name}")
134-
except subprocess.CalledProcessError as exception:
135-
self.logger.error(f"Failed to install package with npm: {package_name}")
136-
raise exception
137-
138-
139-
def _extract_python_package_name(self, error_message):
128+
129+
def _extract_python_package_name(self, error_message):
140130
# Regular expression pattern to match the error message
141131
pattern = r"ModuleNotFoundError: No module named '(\w+)'|ModuleNotFoundError: '(\w+)'"
142132
match = re.search(pattern, error_message)
@@ -150,7 +140,7 @@ def _extract_python_package_name(self, error_message):
150140
self.logger.error(exception)
151141
raise exception
152142

153-
def _extract_javascript_package_name(self,error_message):
143+
def _extract_javascript_package_name(self, error_message):
154144
try:
155145
lines = error_message.split('\n')
156146
for line in lines:
@@ -162,32 +152,22 @@ def _extract_javascript_package_name(self,error_message):
162152
self.logger.error(f"Failed to extract package name from error message: {exception}")
163153
raise exception
164154

165-
def _check_package_exists_pip(self,package_name):
166-
import requests
167-
from bs4 import BeautifulSoup
168-
155+
def _check_package_exists_pip(self, package_name):
169156
try:
170-
# Send a GET request to the PyPI search page
171-
response = requests.get(f"https://pypi.org/search/?q={package_name}")
172-
response.raise_for_status()
173-
174-
# Parse the HTML content of the page
175-
soup = BeautifulSoup(response.text, 'html.parser')
176-
177-
# Search for the package name in the parsed HTML
178-
search_results = soup.find_all('span', class_='package-snippet__name')
179-
for result in search_results:
180-
if result.text.strip() == package_name:
181-
return True
182-
183-
# If the package name was not found in the search results, log an error and raise an exception
184-
exception = ValueError(f"Package {package_name} does not exist on PyPI")
185-
self.logger.error(exception)
186-
raise exception
187-
except requests.exceptions.RequestException as exception:
188-
raise exception
157+
api_url = f"https://pypi.org/pypi/{package_name}/json"
158+
self.logger.info("API Url is {}".format(api_url))
159+
response = requests.get(api_url)
160+
if response.status_code == 200:
161+
return True
162+
else:
163+
error_message = f"Package {package_name} does not exist on PyPI"
164+
self.logger.error(error_message)
165+
raise ValueError(error_message)
166+
except requests.exceptions.RequestException as request_exception:
167+
self.logger.error(f"Request failed: {request_exception}")
168+
raise request_exception
189169

190-
def _check_package_exists_npm(self, package_name):
170+
def _check_package_exists_npm(self, package_name):
191171
try:
192172
response = requests.get(f"https://www.npmjs.com/package/{package_name}")
193173
if response.status_code == 200:

Diff for: requirements.txt

-3
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,3 @@ plotly
1515

1616
# Libraries for standard libries
1717
stdlib_list
18-
19-
# Beatiful Soup library
20-
beautifulsoup4

0 commit comments

Comments
 (0)