scriptmonkey 0.1.1__tar.gz → 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. scriptmonkey-1.0.0/PKG-INFO +141 -0
  2. scriptmonkey-1.0.0/README.md +122 -0
  3. {scriptmonkey-0.1.1 → scriptmonkey-1.0.0}/scriptmonkey/__init__.py +1 -0
  4. scriptmonkey-1.0.0/scriptmonkey/__main__.py +4 -0
  5. scriptmonkey-1.0.0/scriptmonkey/core.py +321 -0
  6. scriptmonkey-1.0.0/scriptmonkey/openai_client/__init__.py +28 -0
  7. {scriptmonkey-0.1.1 → scriptmonkey-1.0.0}/scriptmonkey/openai_client/client.py +30 -7
  8. scriptmonkey-1.0.0/scriptmonkey/openai_client/prompts/project_description.txt +1 -0
  9. scriptmonkey-1.0.0/scriptmonkey.egg-info/PKG-INFO +141 -0
  10. {scriptmonkey-0.1.1 → scriptmonkey-1.0.0}/scriptmonkey.egg-info/SOURCES.txt +4 -1
  11. scriptmonkey-1.0.0/scriptmonkey.egg-info/entry_points.txt +2 -0
  12. {scriptmonkey-0.1.1 → scriptmonkey-1.0.0}/scriptmonkey.egg-info/requires.txt +1 -0
  13. {scriptmonkey-0.1.1 → scriptmonkey-1.0.0}/setup.py +18 -8
  14. scriptmonkey-0.1.1/PKG-INFO +0 -84
  15. scriptmonkey-0.1.1/README.md +0 -66
  16. scriptmonkey-0.1.1/scriptmonkey/core.py +0 -72
  17. scriptmonkey-0.1.1/scriptmonkey/openai_client/__init__.py +0 -12
  18. scriptmonkey-0.1.1/scriptmonkey.egg-info/PKG-INFO +0 -84
  19. {scriptmonkey-0.1.1 → scriptmonkey-1.0.0}/scriptmonkey/file_handler.py +0 -0
  20. {scriptmonkey-0.1.1 → scriptmonkey-1.0.0}/scriptmonkey/openai_client/basemodels.py +0 -0
  21. {scriptmonkey-0.1.1 → scriptmonkey-1.0.0}/scriptmonkey/openai_client/prompting.py +0 -0
  22. {scriptmonkey-0.1.1 → scriptmonkey-1.0.0}/scriptmonkey/openai_client/prompts/fix_error.txt +0 -0
  23. {scriptmonkey-0.1.1 → scriptmonkey-1.0.0}/scriptmonkey.egg-info/dependency_links.txt +0 -0
  24. {scriptmonkey-0.1.1 → scriptmonkey-1.0.0}/scriptmonkey.egg-info/top_level.txt +0 -0
  25. {scriptmonkey-0.1.1 → scriptmonkey-1.0.0}/setup.cfg +0 -0
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.1
2
+ Name: scriptmonkey
3
+ Version: 1.0.0
4
+ Summary: A Python package that generates complex Python projects and fixes errors in your code using OpenAI's GPT API.
5
+ Home-page: https://github.com/lukerbs/ScriptMonkey
6
+ Author: Luke Kerbs
7
+ Author-email: LDK.kerbs@gmail.com
8
+ License: MIT
9
+ Keywords: openai,GPT,AI,project generation,multi-file project,complex project generator,code error fixing,code automation,GPT API,error correction,code assistant,AI coding tools,script monkey,automation,development tools,python tools,code analysis,machine learning,project bootstrap,custom code generation,python package
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Requires-Python: >=3.6
14
+ Description-Content-Type: text/markdown
15
+ Requires-Dist: openai
16
+ Requires-Dist: pydantic
17
+ Requires-Dist: tqdm
18
+ Requires-Dist: python-dotenv
19
+
20
+
21
+ # ScriptMonkey 🐒
22
+
23
+ ScriptMonkey is an AI-powered Python package that reimagines how projects are built. It doesn’t just generate simple scripts or templates like traditional LLMs—it creates **entire, multi-file, multi-directory projects with fully custom code**. Complex Python projects can be generated in seconds based on your natural language descriptions, providing everything you need, from models and routes to templates and configuration files. With ScriptMonkey, you can instantly bootstrap new ideas or start complex projects without the tedious setup. And with built-in error detection and automatic fixes, ScriptMonkey keeps your development process smooth and stress-free, letting you focus on what matters most: building.
24
+
25
+ ## Features
26
+ - **Custom Project Generation**: Create entire Python projects, not just boilerplate code. ScriptMonkey generates the specific files and directories you need based on your description.
27
+ - **Lightning-Fast Setup**: Complex Python projects can be generated in seconds, saving you time and effort.
28
+ - **Automatic Error Detection**: Captures errors during runtime.
29
+ - **AI-Powered Fixes**: Uses OpenAI's GPT API to understand and resolve errors.
30
+ - **Code Auto-Correction**: Automatically updates your Python files with the fixes.
31
+ - **Cross-IDE Compatibility**: Works with any IDE or code editor.
32
+
33
+ ## Installation
34
+
35
+ To install ScriptMonkey, simply run:
36
+
37
+ ```bash
38
+ pip install scriptmonkey
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ ### Project Generation with `python3 -m scriptmonkey`
44
+
45
+ ScriptMonkey can generate a complete, custom-coded project structure based on a description you provide. This feature helps you quickly set up new projects with the necessary files and folders.
46
+
47
+ #### How to Use
48
+
49
+ 1. Run the following command in your terminal:
50
+
51
+ ```bash
52
+ python3 -m scriptmonkey
53
+ ```
54
+
55
+ 2. A text editor will open (e.g., `nano`, `vim`, or `notepad` depending on your environment). Follow the on-screen instructions to provide a detailed description of your project.
56
+
57
+ 3. Save and close the editor. ScriptMonkey will then:
58
+ - Generate a complete project structure based on your description.
59
+ - Create directories, code files, and templates.
60
+ - Automatically generate a `README.md` with installation instructions and usage details.
61
+
62
+ #### Example Project Description Prompt
63
+
64
+ ```
65
+ I need a Flask-based web application for managing a book library. The application should include:
66
+ - User authentication (login, registration, password reset).
67
+ - Models for Users, Books, and Authors using SQLAlchemy.
68
+ - A REST API with routes for adding, updating, and deleting books and authors.
69
+ - An admin dashboard for managing users and viewing statistics.
70
+ - HTML templates for user login, book list, and book detail views.
71
+ - The database should use PostgreSQL.
72
+ - Include environment-specific configurations for development and production.
73
+ ```
74
+
75
+ ScriptMonkey will use this description to create a project structure and code files for you in a directory named `generated_project`.
76
+
77
+ ### Error Handling with `scriptmonkey.run()`
78
+
79
+ ScriptMonkey doesn't just build projects; it also makes debugging a breeze.
80
+
81
+ 1. Import `scriptmonkey` in your Python script.
82
+ 2. Call `scriptmonkey.run()` to activate the error handler.
83
+ 3. Run your code, and let ScriptMonkey handle any errors that occur.
84
+
85
+ #### Example
86
+
87
+ ```python
88
+ import scriptmonkey
89
+
90
+ # Enable ScriptMonkey's error handler
91
+ scriptmonkey.run()
92
+
93
+ # Intentional error for testing
94
+ def add(a, b):
95
+ return a + b # This will fail if b is a string
96
+
97
+ print(add(2, "3")) # ScriptMonkey will automatically fix this error and update the file.
98
+ ```
99
+
100
+ Once an error occurs, ScriptMonkey will:
101
+ 1. Detect the error.
102
+ 2. Send the error and code to OpenAI for analysis.
103
+ 3. Provide a solution and automatically update the file with the corrected code.
104
+
105
+ ### Setting or Updating Your OpenAI API Key
106
+
107
+ If you haven't set your OpenAI API key yet or need to update it, you can do so with the following command:
108
+
109
+ ```bash
110
+ python3 -m scriptmonkey --set-api-key your-api-key
111
+ ```
112
+
113
+ This will store the API key in a config locally and use it for all future interactions with OpenAI.
114
+
115
+ ## Requirements
116
+ - Python 3.6 or later
117
+ - An OpenAI API key (follow the steps below if you don't have one)
118
+
119
+ ## Obtaining an OpenAI API Key
120
+
121
+ 1. Go to the OpenAI website: [OpenAI Platform](https://platform.openai.com/)
122
+ 2. Sign up or log in to your account.
123
+ 3. Navigate to the **API keys** section in your account dashboard.
124
+ 4. Create a new API key and copy it.
125
+
126
+ ## Configuring the API Key for ScriptMonkey
127
+
128
+ - **Option 1: Environment Variable**
129
+ You can set up your API key as an environment variable:
130
+
131
+ ```bash
132
+ export OPENAI_API_KEY='your-api-key'
133
+ ```
134
+
135
+ - **Option 2: Entering the API Key When Prompted**
136
+ If ScriptMonkey does not find an API key in your environment variables, it will prompt you to enter your key. Once entered, it will save the key to a configuration file for future use.
137
+
138
+ - **Option 3: Using the `--set-api-key` Command**
139
+ Use the `--set-api-key` command as shown above to set or update your API key easily.
140
+
141
+ Let ScriptMonkey take care of your Python errors and project setup so you can focus on building!
@@ -0,0 +1,122 @@
1
+
2
+ # ScriptMonkey 🐒
3
+
4
+ ScriptMonkey is an AI-powered Python package that reimagines how projects are built. It doesn’t just generate simple scripts or templates like traditional LLMs—it creates **entire, multi-file, multi-directory projects with fully custom code**. Complex Python projects can be generated in seconds based on your natural language descriptions, providing everything you need, from models and routes to templates and configuration files. With ScriptMonkey, you can instantly bootstrap new ideas or start complex projects without the tedious setup. And with built-in error detection and automatic fixes, ScriptMonkey keeps your development process smooth and stress-free, letting you focus on what matters most: building.
5
+
6
+ ## Features
7
+ - **Custom Project Generation**: Create entire Python projects, not just boilerplate code. ScriptMonkey generates the specific files and directories you need based on your description.
8
+ - **Lightning-Fast Setup**: Complex Python projects can be generated in seconds, saving you time and effort.
9
+ - **Automatic Error Detection**: Captures errors during runtime.
10
+ - **AI-Powered Fixes**: Uses OpenAI's GPT API to understand and resolve errors.
11
+ - **Code Auto-Correction**: Automatically updates your Python files with the fixes.
12
+ - **Cross-IDE Compatibility**: Works with any IDE or code editor.
13
+
14
+ ## Installation
15
+
16
+ To install ScriptMonkey, simply run:
17
+
18
+ ```bash
19
+ pip install scriptmonkey
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ ### Project Generation with `python3 -m scriptmonkey`
25
+
26
+ ScriptMonkey can generate a complete, custom-coded project structure based on a description you provide. This feature helps you quickly set up new projects with the necessary files and folders.
27
+
28
+ #### How to Use
29
+
30
+ 1. Run the following command in your terminal:
31
+
32
+ ```bash
33
+ python3 -m scriptmonkey
34
+ ```
35
+
36
+ 2. A text editor will open (e.g., `nano`, `vim`, or `notepad` depending on your environment). Follow the on-screen instructions to provide a detailed description of your project.
37
+
38
+ 3. Save and close the editor. ScriptMonkey will then:
39
+ - Generate a complete project structure based on your description.
40
+ - Create directories, code files, and templates.
41
+ - Automatically generate a `README.md` with installation instructions and usage details.
42
+
43
+ #### Example Project Description Prompt
44
+
45
+ ```
46
+ I need a Flask-based web application for managing a book library. The application should include:
47
+ - User authentication (login, registration, password reset).
48
+ - Models for Users, Books, and Authors using SQLAlchemy.
49
+ - A REST API with routes for adding, updating, and deleting books and authors.
50
+ - An admin dashboard for managing users and viewing statistics.
51
+ - HTML templates for user login, book list, and book detail views.
52
+ - The database should use PostgreSQL.
53
+ - Include environment-specific configurations for development and production.
54
+ ```
55
+
56
+ ScriptMonkey will use this description to create a project structure and code files for you in a directory named `generated_project`.
57
+
58
+ ### Error Handling with `scriptmonkey.run()`
59
+
60
+ ScriptMonkey doesn't just build projects; it also makes debugging a breeze.
61
+
62
+ 1. Import `scriptmonkey` in your Python script.
63
+ 2. Call `scriptmonkey.run()` to activate the error handler.
64
+ 3. Run your code, and let ScriptMonkey handle any errors that occur.
65
+
66
+ #### Example
67
+
68
+ ```python
69
+ import scriptmonkey
70
+
71
+ # Enable ScriptMonkey's error handler
72
+ scriptmonkey.run()
73
+
74
+ # Intentional error for testing
75
+ def add(a, b):
76
+ return a + b # This will fail if b is a string
77
+
78
+ print(add(2, "3")) # ScriptMonkey will automatically fix this error and update the file.
79
+ ```
80
+
81
+ Once an error occurs, ScriptMonkey will:
82
+ 1. Detect the error.
83
+ 2. Send the error and code to OpenAI for analysis.
84
+ 3. Provide a solution and automatically update the file with the corrected code.
85
+
86
+ ### Setting or Updating Your OpenAI API Key
87
+
88
+ If you haven't set your OpenAI API key yet or need to update it, you can do so with the following command:
89
+
90
+ ```bash
91
+ python3 -m scriptmonkey --set-api-key your-api-key
92
+ ```
93
+
94
+ This will store the API key in a config locally and use it for all future interactions with OpenAI.
95
+
96
+ ## Requirements
97
+ - Python 3.6 or later
98
+ - An OpenAI API key (follow the steps below if you don't have one)
99
+
100
+ ## Obtaining an OpenAI API Key
101
+
102
+ 1. Go to the OpenAI website: [OpenAI Platform](https://platform.openai.com/)
103
+ 2. Sign up or log in to your account.
104
+ 3. Navigate to the **API keys** section in your account dashboard.
105
+ 4. Create a new API key and copy it.
106
+
107
+ ## Configuring the API Key for ScriptMonkey
108
+
109
+ - **Option 1: Environment Variable**
110
+ You can set up your API key as an environment variable:
111
+
112
+ ```bash
113
+ export OPENAI_API_KEY='your-api-key'
114
+ ```
115
+
116
+ - **Option 2: Entering the API Key When Prompted**
117
+ If ScriptMonkey does not find an API key in your environment variables, it will prompt you to enter your key. Once entered, it will save the key to a configuration file for future use.
118
+
119
+ - **Option 3: Using the `--set-api-key` Command**
120
+ Use the `--set-api-key` command as shown above to set or update your API key easily.
121
+
122
+ Let ScriptMonkey take care of your Python errors and project setup so you can focus on building!
@@ -1 +1,2 @@
1
1
  from .core import run
2
+
@@ -0,0 +1,4 @@
1
+ from .core import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,321 @@
1
+ import sys
2
+ import traceback
3
+ from .openai_client import chatgpt_json, chatgpt, ScriptMonkeyResponse, ProjectStructureResponse, ProjectFile, default_prompts
4
+ from .openai_client.prompting import load_prompt
5
+ from .file_handler import read_file, write_file
6
+ import platform
7
+ import tempfile
8
+ import subprocess
9
+ import threading
10
+ import itertools
11
+ import time
12
+ from pprint import pprint
13
+ import os
14
+ import platform
15
+
16
+ def get_platform():
17
+ os_name = platform.system()
18
+ os_version = platform.release()
19
+ return f"# Operating System: {os_name}, Version: {os_version}\n\n"
20
+
21
+ class Spinner:
22
+ def __init__(self, message="Processing"):
23
+ self.spinner = itertools.cycle(["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"])
24
+ self.stop_running = threading.Event()
25
+ self.spin_thread = None
26
+ self.message = message
27
+
28
+ def spin(self):
29
+ while not self.stop_running.is_set():
30
+ sys.stdout.write(f"\r{self.message} {next(self.spinner)}")
31
+ sys.stdout.flush()
32
+ time.sleep(0.1)
33
+ sys.stdout.write("\r" + " " * (len(self.message) + 2) + "\r")
34
+ sys.stdout.flush()
35
+
36
+ def __enter__(self):
37
+ self.spin_thread = threading.Thread(target=self.spin)
38
+ self.spin_thread.start()
39
+
40
+ def __exit__(self, exc_type, exc_val, exc_tb):
41
+ self.stop_running.set()
42
+ self.spin_thread.join()
43
+
44
+ def codemonkey_exception_handler(exc_type, exc_value, exc_traceback):
45
+ if issubclass(exc_type, KeyboardInterrupt):
46
+ sys.__excepthook__(exc_type, exc_value, exc_traceback)
47
+ return
48
+
49
+ error_message = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
50
+
51
+ print(f"\n🐒 ScriptMonkey Detected an Error:")
52
+ print(error_message, "\n")
53
+
54
+ frame = traceback.extract_tb(exc_traceback)[-1]
55
+ file_path = frame.filename
56
+
57
+ original_code = read_file(file_path)
58
+ content = f"{get_platform()}# Original Code:\n```\n{original_code}\n```\n\n# Error Message:\n{error_message}"
59
+
60
+ solution = None
61
+ with Spinner("🐒 ScriptMonkey is working on a solution"):
62
+ solution = chatgpt_json(
63
+ instructions=default_prompts.fix_error, content=content, response_format=ScriptMonkeyResponse
64
+ )
65
+
66
+ print(f"\n🐒 ScriptMonkey Fixed It:\nProblem:\n{solution['problem']}\n")
67
+ print(f"Suggested Solution:\n{solution['solution']}\n")
68
+
69
+ corrected_code = solution["corrected_code"].replace("```python", "").replace("```", "")
70
+ write_file(file_path, corrected_code)
71
+ print(f"🐒 ScriptMonkey automatically fixed your code at: '{file_path}'.")
72
+
73
+
74
+ def run():
75
+ sys.excepthook = codemonkey_exception_handler
76
+
77
+
78
+ # - - - - - API KEY MANAGEMENT - - - - -
79
+
80
+ def save_api_key(api_key: str):
81
+ """Save the OpenAI API key to the configuration file and environment variable."""
82
+ with open(CONFIG_FILE, 'w') as file:
83
+ file.write(api_key)
84
+ os.environ['OPENAI_API_KEY'] = api_key
85
+ print(f"✅ OpenAI API key saved to {CONFIG_FILE}.")
86
+
87
+ def get_openai_api_key() -> str:
88
+ """Retrieve the OpenAI API key from environment or configuration file."""
89
+ api_key = os.getenv('OPENAI_API_KEY')
90
+
91
+ if not api_key:
92
+ # Check for API key in the configuration file
93
+ if os.path.exists(CONFIG_FILE):
94
+ with open(CONFIG_FILE, 'r') as file:
95
+ api_key = file.read().strip()
96
+
97
+ # Prompt user for API key if not found
98
+ if not api_key:
99
+ print("🐒 ScriptMonkey requires an OpenAI API key to function.")
100
+ api_key = getpass.getpass("Please enter your OpenAI API key (input hidden): ")
101
+
102
+ if api_key:
103
+ save_api_key(api_key)
104
+
105
+ if not api_key:
106
+ print("❌ No API key provided. Exiting ScriptMonkey.")
107
+ sys.exit(1)
108
+
109
+ return api_key
110
+
111
+ def update_api_key():
112
+ """Prompt the user to update the OpenAI API key."""
113
+ api_key = getpass.getpass("Enter the new OpenAI API key (input hidden): ")
114
+ if api_key:
115
+ save_api_key(api_key)
116
+ print("✅ OpenAI API key updated successfully.")
117
+ else:
118
+ print("❌ No API key provided. The API key was not updated.")
119
+
120
+ # - - - - - NEW FEATURES - - - - -
121
+
122
+ def get_multiline_input_with_editor() -> str:
123
+ """
124
+ Opens the user's default text editor for entering multi-line input.
125
+ The user is provided with instructions within the temporary file,
126
+ adjusted based on the detected editor.
127
+ """
128
+ with tempfile.NamedTemporaryFile(suffix=".txt") as temp_file:
129
+ # Detect the editor from the environment or default based on the OS
130
+ editor = os.environ.get('EDITOR')
131
+
132
+ # If no editor is set, choose a default based on the platform
133
+ if not editor:
134
+ if platform.system() == 'Windows':
135
+ editor = 'notepad'
136
+ else:
137
+ editor = 'nano' # Default for Unix-like systems
138
+
139
+ # Adjust instructions based on the detected editor
140
+ if 'vim' in editor.lower():
141
+ instructions = (
142
+ "!# 🐒 Welcome to ScriptMonkey's project generator!\n"
143
+ "!# Please describe your project in detail below.\n"
144
+ "!# Use 'i' to start editing, and when you're done, press 'Esc',\n"
145
+ "!# type ':wq' to save and exit.\n"
146
+ "!# (Lines starting with '!#' will be ignored.)\n\n"
147
+ )
148
+ elif 'nano' in editor.lower():
149
+ instructions = (
150
+ "!# 🐒 Welcome to ScriptMonkey's project generator!\n"
151
+ "!# Please describe your project in detail below.\n"
152
+ "!# When you're done, press 'Ctrl+O' to save and 'Ctrl+X' to exit.\n"
153
+ "!# (Lines starting with '!#' will be ignored.)\n\n"
154
+ )
155
+ elif 'notepad' in editor.lower():
156
+ instructions = (
157
+ "!# 🐒 Welcome to ScriptMonkey's project generator!\n"
158
+ "!# Please describe your project in detail below.\n"
159
+ "!# When you're done, save and close the Notepad window.\n"
160
+ "!# (Lines starting with '!#' will be ignored.)\n\n"
161
+ )
162
+ elif 'code' in editor.lower():
163
+ instructions = (
164
+ "!# 🐒 Welcome to ScriptMonkey's project generator!\n"
165
+ "!# Please describe your project in detail below.\n"
166
+ "!# When you're done, save the file and close the editor window.\n"
167
+ "!# (Lines starting with '!#' will be ignored.)\n\n"
168
+ )
169
+ else:
170
+ instructions = (
171
+ "!# 🐒 Welcome to ScriptMonkey's project generator!\n"
172
+ "!# Please describe your project in detail below.\n"
173
+ "!# Save and close the editor when you're done.\n"
174
+ "!# (Lines starting with '!#' will be ignored.)\n\n"
175
+ )
176
+
177
+ # Write the instructions to the temporary file
178
+ temp_file.write(instructions.encode('utf-8'))
179
+ temp_file.flush()
180
+
181
+ # Open the temporary file in the detected editor
182
+ subprocess.call([editor, temp_file.name])
183
+
184
+ # Read the user's input, ignoring lines starting with '!#'
185
+ temp_file.seek(0)
186
+ user_input = temp_file.read().decode('utf-8')
187
+ user_input = "\n".join(line for line in user_input.splitlines() if not line.startswith("!#"))
188
+
189
+ return user_input.strip()
190
+
191
+ def generate_project_structure(description: str) -> ProjectStructureResponse:
192
+ """Generates the project structure based on the user's project description using OpenAI."""
193
+ instructions = (
194
+ "Generate a detailed project structure for a multi-level application. The project will be placed directly inside a folder named 'generated_project'."
195
+ "\n- Do NOT include 'generated_project/' as part of the paths. All paths should be relative to the root of the project directory, meaning they should start directly with the file or folder names as if they are inside 'generated_project'."
196
+ "\n- Provide a list of directories and files with their full relative paths."
197
+ "\n- Each directory should end with a '/' to indicate that it is a folder."
198
+ "\n- For each file or directory, include a 'description' that explains its purpose."
199
+ "\n- If the file is a Python code file, also include a 'functions' list. For each function, include:"
200
+ "\n - 'function_name': The name of the function."
201
+ "\n - 'description': A description of what the function does."
202
+ "\n - 'inputs': A list of the function's expected inputs, including data types."
203
+ "\n - 'outputs': A list of the function's expected outputs, including data types."
204
+ "\n- Do not include any extra explanations, commentary, or introductory text. Only provide the structured data as requested."
205
+ )
206
+
207
+ # Call the chatgpt_json function to get structured project plan
208
+ project_structure = chatgpt_json(
209
+ instructions=instructions,
210
+ content=description,
211
+ response_format=ProjectStructureResponse
212
+ )
213
+
214
+ return project_structure
215
+
216
+ def create_project_structure(project_structure_response: dict, base_directory: str = "./generated_project"):
217
+ """Creates the directories and files for the project and generates code content for code files."""
218
+ for project_file in project_structure_response['files']:
219
+ file_path = os.path.join(base_directory, project_file['path'].lstrip('/'))
220
+
221
+ # Check if it's a directory or file (directories end with '/')
222
+ if file_path.endswith('/'):
223
+ os.makedirs(file_path, exist_ok=True)
224
+ print(f"🐒 ScriptMonkey created directory: {file_path}")
225
+ else:
226
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
227
+
228
+ # If it's a Python code file, generate code and write to the file
229
+ if file_path.endswith('.py'):
230
+ generated_code = generate_code_for_file(project_file)
231
+ if not os.path.exists(file_path):
232
+ with open(file_path, 'w') as f:
233
+ f.write(generated_code)
234
+ print(f"🐒 ScriptMonkey created file with generated code at: '{file_path}'.")
235
+ else:
236
+ print(f"File already exists, skipping: {file_path}")
237
+ else:
238
+ # Create other file types (HTML, CSS, etc.)
239
+ if not os.path.exists(file_path):
240
+ with open(file_path, 'w') as f:
241
+ pass # Create an empty file for non-code files
242
+ print(f"🐒 ScriptMonkey reated file: {file_path}")
243
+ else:
244
+ print(f"File already exists, skipping: {file_path}")
245
+
246
+
247
+ def generate_code_for_file(file_description: dict) -> str:
248
+ """Generates code content for a given file based on its description using the chatgpt() function."""
249
+ # Prepare instructions for OpenAI to generate code based on the file description
250
+ instructions = (
251
+ "Write the complete Python code based on the following file description without adding any additional commentary or explanation. "
252
+ "Ensure the code follows PEP8 standards, includes type hints, and contains relevant docstrings."
253
+ f"\n\nFile Description: {file_description['description']}"
254
+ )
255
+
256
+ # Check if the file has functions to include in the code
257
+ if file_description.get('functions'):
258
+ instructions += "\n\nFunctions:\n"
259
+ for function in file_description['functions']:
260
+ instructions += (
261
+ f"- {function['function_name']}: {function['description']} "
262
+ f"(Inputs: {function['inputs']}, Outputs: {function['outputs']})\n"
263
+ )
264
+
265
+ # Call the chatgpt function to generate the code
266
+ generated_code = chatgpt(prompt=instructions)
267
+
268
+ # Strip out any unintended extra explanations that might still slip through
269
+ if "```python" in generated_code:
270
+ generated_code = generated_code.split("```python")[1].split("```")[0].strip()
271
+
272
+ return generated_code
273
+
274
+ def generate_readme(description: str, project_structure: dict) -> str:
275
+ """Generates a README.md content based on the project description and structure."""
276
+ instructions = (
277
+ "Write a complete README.md file based on the following project details. "
278
+ "The README should include the project overview, installation instructions, usage guide, file structure summary, key features, and configuration details. "
279
+ "Make sure the README is well-structured and formatted using Markdown without wrapping the entire README in backticks or any other non-readme commentary."
280
+ "Do not include any commentary, explanations, or text outside of the README content."
281
+ f"\n\nProject Description: {description}\n"
282
+ f"\nProject Structure: {project_structure}\n"
283
+ )
284
+
285
+ readme_content = chatgpt(prompt=instructions)
286
+ readme_content = readme_content.strip("```markdown").strip("```")
287
+ return readme_content
288
+
289
+
290
+ # Example usage
291
+ def main():
292
+ if len(sys.argv) > 1 and sys.argv[1] == '--set-api-key':
293
+ update_api_key()
294
+ else:
295
+ print(f"\n- - 🐒 WELCOME TO SCRIPT MONKEY 🐒 - - -\n")
296
+ print(f"Opening prompt editor... ")
297
+ time.sleep(2)
298
+
299
+ # Step 1: Get multi-line project description from user
300
+ project_description = get_multiline_input_with_editor()
301
+ if not project_description:
302
+ print(f"\nNo Project Description Provided (Tip: Did you save before closing the editor?).\n🐒 Quitting ScriptMonkey...")
303
+ exit()
304
+ print(f"Project Description: {project_description}")
305
+
306
+ # Step 2: Generate the project structure using OpenAI API
307
+ project_structure = generate_project_structure(project_description)
308
+ print(f"\n🐒 ScriptMonkey created a project blueprint:")
309
+ pprint(project_structure)
310
+
311
+ # Step 3: Create the project structure (directories and files) on the filesystem
312
+ print(f"\n🐒 ScriptMonkey is coding...")
313
+ create_project_structure(project_structure)
314
+ print("\nProject structure creation complete.")
315
+
316
+ # Step 4: Generate the README.md content based on the project description and structure
317
+ readme_content = generate_readme(project_description, project_structure)
318
+ readme_path = "./generated_project/README.md"
319
+ with open(readme_path, 'w') as readme_file:
320
+ readme_file.write(readme_content)
321
+ print(f"🐒 ScriptMonkey wrote a README.md file at: '{readme_path}'")
@@ -0,0 +1,28 @@
1
+ from .prompting import DefaultPrompts
2
+ from .client import chatgpt_json, chatgpt
3
+ from pydantic import BaseModel
4
+ from typing import List, Optional
5
+
6
+ class FunctionDetails(BaseModel):
7
+ function_name: str
8
+ description: str
9
+ inputs: Optional[List[str]] # List of inputs with data types
10
+ outputs: Optional[List[str]] # List of outputs with data types
11
+
12
+
13
+ class ProjectFile(BaseModel):
14
+ path: str # The full path to the file or directory
15
+ description: str # High-level purpose of the directory or file
16
+ functions: Optional[List[FunctionDetails]] # List of functions/classes if it's a code file
17
+
18
+ class ProjectStructureResponse(BaseModel):
19
+ files: List[ProjectFile] # List of all files and directories in the project
20
+
21
+
22
+ class ScriptMonkeyResponse(BaseModel):
23
+ problem: str # A description of the error/problem
24
+ solution: str # The solution to the problem
25
+ corrected_code: str # The corrected version of the Python code
26
+
27
+
28
+ default_prompts = DefaultPrompts()
@@ -4,14 +4,37 @@ from dotenv import load_dotenv
4
4
  from pydantic import BaseModel
5
5
  import openai
6
6
 
7
- # Load the OpenAI API key from .env file
7
+ CONFIG_FILE = os.path.expanduser("~/.scriptmonkey_config")
8
+
9
+ # Load environment variables from the .env file if present
8
10
  load_dotenv()
9
- OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
10
- if OPENAI_API_KEY:
11
- # Initialize openai API client
12
- client = openai.OpenAI(api_key=OPENAI_API_KEY)
13
- else:
14
- raise ValueError("Missing OpenAI API Key. Please check your environment variables.")
11
+
12
+ def get_openai_api_key():
13
+ # Try to get the API key from environment variables
14
+ api_key = os.getenv("OPENAI_API_KEY")
15
+
16
+ # If not set, check the config file
17
+ if not api_key and os.path.exists(CONFIG_FILE):
18
+ with open(CONFIG_FILE, 'r') as f:
19
+ api_key = f.read().strip()
20
+
21
+ # If still not set, prompt the user for it
22
+ if not api_key:
23
+ print("It looks like your OpenAI API key isn't set.")
24
+ api_key = input("🐒 Please paste your OpenAI API key here and press ENTER: ").strip()
25
+
26
+ # Save the key to the config file for future use
27
+ with open(CONFIG_FILE, 'w') as f:
28
+ f.write(api_key)
29
+ print(f"Your API key has been saved to {CONFIG_FILE} for future use.")
30
+
31
+ return api_key
32
+
33
+ # Get the OpenAI API key using the function
34
+ OPENAI_API_KEY = get_openai_api_key()
35
+
36
+ # Initialize the OpenAI client with the obtained API key
37
+ client = openai.OpenAI(api_key=OPENAI_API_KEY)
15
38
 
16
39
 
17
40
  def chatgpt_json(instructions: str, content: str, response_format: BaseModel) -> dict:
@@ -0,0 +1 @@
1
+ Build a Flask web application with user authentication, a PostgreSQL database, and an admin dashboard.
@@ -0,0 +1,141 @@
1
+ Metadata-Version: 2.1
2
+ Name: scriptmonkey
3
+ Version: 1.0.0
4
+ Summary: A Python package that generates complex Python projects and fixes errors in your code using OpenAI's GPT API.
5
+ Home-page: https://github.com/lukerbs/ScriptMonkey
6
+ Author: Luke Kerbs
7
+ Author-email: LDK.kerbs@gmail.com
8
+ License: MIT
9
+ Keywords: openai,GPT,AI,project generation,multi-file project,complex project generator,code error fixing,code automation,GPT API,error correction,code assistant,AI coding tools,script monkey,automation,development tools,python tools,code analysis,machine learning,project bootstrap,custom code generation,python package
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Operating System :: OS Independent
13
+ Requires-Python: >=3.6
14
+ Description-Content-Type: text/markdown
15
+ Requires-Dist: openai
16
+ Requires-Dist: pydantic
17
+ Requires-Dist: tqdm
18
+ Requires-Dist: python-dotenv
19
+
20
+
21
+ # ScriptMonkey 🐒
22
+
23
+ ScriptMonkey is an AI-powered Python package that reimagines how projects are built. It doesn’t just generate simple scripts or templates like traditional LLMs—it creates **entire, multi-file, multi-directory projects with fully custom code**. Complex Python projects can be generated in seconds based on your natural language descriptions, providing everything you need, from models and routes to templates and configuration files. With ScriptMonkey, you can instantly bootstrap new ideas or start complex projects without the tedious setup. And with built-in error detection and automatic fixes, ScriptMonkey keeps your development process smooth and stress-free, letting you focus on what matters most: building.
24
+
25
+ ## Features
26
+ - **Custom Project Generation**: Create entire Python projects, not just boilerplate code. ScriptMonkey generates the specific files and directories you need based on your description.
27
+ - **Lightning-Fast Setup**: Complex Python projects can be generated in seconds, saving you time and effort.
28
+ - **Automatic Error Detection**: Captures errors during runtime.
29
+ - **AI-Powered Fixes**: Uses OpenAI's GPT API to understand and resolve errors.
30
+ - **Code Auto-Correction**: Automatically updates your Python files with the fixes.
31
+ - **Cross-IDE Compatibility**: Works with any IDE or code editor.
32
+
33
+ ## Installation
34
+
35
+ To install ScriptMonkey, simply run:
36
+
37
+ ```bash
38
+ pip install scriptmonkey
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ ### Project Generation with `python3 -m scriptmonkey`
44
+
45
+ ScriptMonkey can generate a complete, custom-coded project structure based on a description you provide. This feature helps you quickly set up new projects with the necessary files and folders.
46
+
47
+ #### How to Use
48
+
49
+ 1. Run the following command in your terminal:
50
+
51
+ ```bash
52
+ python3 -m scriptmonkey
53
+ ```
54
+
55
+ 2. A text editor will open (e.g., `nano`, `vim`, or `notepad` depending on your environment). Follow the on-screen instructions to provide a detailed description of your project.
56
+
57
+ 3. Save and close the editor. ScriptMonkey will then:
58
+ - Generate a complete project structure based on your description.
59
+ - Create directories, code files, and templates.
60
+ - Automatically generate a `README.md` with installation instructions and usage details.
61
+
62
+ #### Example Project Description Prompt
63
+
64
+ ```
65
+ I need a Flask-based web application for managing a book library. The application should include:
66
+ - User authentication (login, registration, password reset).
67
+ - Models for Users, Books, and Authors using SQLAlchemy.
68
+ - A REST API with routes for adding, updating, and deleting books and authors.
69
+ - An admin dashboard for managing users and viewing statistics.
70
+ - HTML templates for user login, book list, and book detail views.
71
+ - The database should use PostgreSQL.
72
+ - Include environment-specific configurations for development and production.
73
+ ```
74
+
75
+ ScriptMonkey will use this description to create a project structure and code files for you in a directory named `generated_project`.
76
+
77
+ ### Error Handling with `scriptmonkey.run()`
78
+
79
+ ScriptMonkey doesn't just build projects; it also makes debugging a breeze.
80
+
81
+ 1. Import `scriptmonkey` in your Python script.
82
+ 2. Call `scriptmonkey.run()` to activate the error handler.
83
+ 3. Run your code, and let ScriptMonkey handle any errors that occur.
84
+
85
+ #### Example
86
+
87
+ ```python
88
+ import scriptmonkey
89
+
90
+ # Enable ScriptMonkey's error handler
91
+ scriptmonkey.run()
92
+
93
+ # Intentional error for testing
94
+ def add(a, b):
95
+ return a + b # This will fail if b is a string
96
+
97
+ print(add(2, "3")) # ScriptMonkey will automatically fix this error and update the file.
98
+ ```
99
+
100
+ Once an error occurs, ScriptMonkey will:
101
+ 1. Detect the error.
102
+ 2. Send the error and code to OpenAI for analysis.
103
+ 3. Provide a solution and automatically update the file with the corrected code.
104
+
105
+ ### Setting or Updating Your OpenAI API Key
106
+
107
+ If you haven't set your OpenAI API key yet or need to update it, you can do so with the following command:
108
+
109
+ ```bash
110
+ python3 -m scriptmonkey --set-api-key your-api-key
111
+ ```
112
+
113
+ This will store the API key in a config locally and use it for all future interactions with OpenAI.
114
+
115
+ ## Requirements
116
+ - Python 3.6 or later
117
+ - An OpenAI API key (follow the steps below if you don't have one)
118
+
119
+ ## Obtaining an OpenAI API Key
120
+
121
+ 1. Go to the OpenAI website: [OpenAI Platform](https://platform.openai.com/)
122
+ 2. Sign up or log in to your account.
123
+ 3. Navigate to the **API keys** section in your account dashboard.
124
+ 4. Create a new API key and copy it.
125
+
126
+ ## Configuring the API Key for ScriptMonkey
127
+
128
+ - **Option 1: Environment Variable**
129
+ You can set up your API key as an environment variable:
130
+
131
+ ```bash
132
+ export OPENAI_API_KEY='your-api-key'
133
+ ```
134
+
135
+ - **Option 2: Entering the API Key When Prompted**
136
+ If ScriptMonkey does not find an API key in your environment variables, it will prompt you to enter your key. Once entered, it will save the key to a configuration file for future use.
137
+
138
+ - **Option 3: Using the `--set-api-key` Command**
139
+ Use the `--set-api-key` command as shown above to set or update your API key easily.
140
+
141
+ Let ScriptMonkey take care of your Python errors and project setup so you can focus on building!
@@ -1,15 +1,18 @@
1
1
  README.md
2
2
  setup.py
3
3
  scriptmonkey/__init__.py
4
+ scriptmonkey/__main__.py
4
5
  scriptmonkey/core.py
5
6
  scriptmonkey/file_handler.py
6
7
  scriptmonkey.egg-info/PKG-INFO
7
8
  scriptmonkey.egg-info/SOURCES.txt
8
9
  scriptmonkey.egg-info/dependency_links.txt
10
+ scriptmonkey.egg-info/entry_points.txt
9
11
  scriptmonkey.egg-info/requires.txt
10
12
  scriptmonkey.egg-info/top_level.txt
11
13
  scriptmonkey/openai_client/__init__.py
12
14
  scriptmonkey/openai_client/basemodels.py
13
15
  scriptmonkey/openai_client/client.py
14
16
  scriptmonkey/openai_client/prompting.py
15
- scriptmonkey/openai_client/prompts/fix_error.txt
17
+ scriptmonkey/openai_client/prompts/fix_error.txt
18
+ scriptmonkey/openai_client/prompts/project_description.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ scriptmonkey = scriptmonkey.core:main
@@ -1,3 +1,4 @@
1
1
  openai
2
2
  pydantic
3
3
  tqdm
4
+ python-dotenv
@@ -2,17 +2,22 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name="scriptmonkey",
5
- version="0.1.1", # Incremented version
6
- description="A Python package that automatically fixes errors in your code using OpenAI's GPT API",
5
+ version="1.0.0",
6
+ description="A Python package that generates complex Python projects and fixes errors in your code using OpenAI's GPT API.",
7
7
  long_description=open("README.md", "r").read(),
8
8
  long_description_content_type="text/markdown",
9
- url="https://github.com/lukerbs/CodeMonkey",
9
+ url="https://github.com/lukerbs/ScriptMonkey",
10
10
  author="Luke Kerbs",
11
11
  author_email="LDK.kerbs@gmail.com",
12
12
  license="MIT",
13
13
  packages=find_packages(),
14
- install_requires=["openai", "pydantic", "tqdm"],
15
- python_requires=">=3.6", # Minimum Python version
14
+ install_requires=["openai", "pydantic", "tqdm", "python-dotenv"],
15
+ python_requires=">=3.6",
16
+ entry_points={
17
+ "console_scripts": [
18
+ "scriptmonkey=scriptmonkey.core:main",
19
+ ],
20
+ },
16
21
  classifiers=[
17
22
  "Programming Language :: Python :: 3",
18
23
  "License :: OSI Approved :: MIT License",
@@ -22,20 +27,25 @@ setup(
22
27
  "openai",
23
28
  "GPT",
24
29
  "AI",
30
+ "project generation",
31
+ "multi-file project",
32
+ "complex project generator",
25
33
  "code error fixing",
26
34
  "code automation",
27
35
  "GPT API",
28
36
  "error correction",
29
37
  "code assistant",
30
38
  "AI coding tools",
31
- "code monkey",
32
39
  "script monkey",
33
40
  "automation",
34
41
  "development tools",
35
42
  "python tools",
36
43
  "code analysis",
37
44
  "machine learning",
38
- ], # Added relevant keywords
45
+ "project bootstrap",
46
+ "custom code generation",
47
+ "python package",
48
+ ],
39
49
  package_data={"scriptmonkey.openai_client": ["prompts/*.txt"]},
40
50
  include_package_data=True,
41
- )
51
+ )
@@ -1,84 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: scriptmonkey
3
- Version: 0.1.1
4
- Summary: A Python package that automatically fixes errors in your code using OpenAI's GPT API
5
- Home-page: https://github.com/lukerbs/CodeMonkey
6
- Author: Luke Kerbs
7
- Author-email: LDK.kerbs@gmail.com
8
- License: MIT
9
- Keywords: openai,GPT,AI,code error fixing,code automation,GPT API,error correction,code assistant,AI coding tools,code monkey,script monkey,automation,development tools,python tools,code analysis,machine learning
10
- Classifier: Programming Language :: Python :: 3
11
- Classifier: License :: OSI Approved :: MIT License
12
- Classifier: Operating System :: OS Independent
13
- Requires-Python: >=3.6
14
- Description-Content-Type: text/markdown
15
- Requires-Dist: openai
16
- Requires-Dist: pydantic
17
- Requires-Dist: tqdm
18
-
19
-
20
- # ScriptMonkey 🐒
21
-
22
- ScriptMonkey is a Python package that automatically detects and fixes errors in your code using OpenAI's GPT API. It works with any IDE or code editor, analyzing your code at runtime, providing solutions to errors, and even updating the file with the corrected code.
23
-
24
- ## Features
25
- - **Automatic error detection**: Captures errors during runtime.
26
- - **AI-powered fixes**: Uses OpenAI's GPT API to understand and resolve errors.
27
- - **Code auto-correction**: Automatically updates your Python files with the fixes.
28
- - **Cross-IDE compatibility**: Works with any IDE or code editor.
29
-
30
- ## Installation
31
-
32
- To install ScriptMonkey, simply run:
33
-
34
- ```bash
35
- pip install scriptmonkey
36
- ```
37
-
38
- ## Usage
39
-
40
- 1. Import `scriptmonkey` in your Python script.
41
- 2. Call `scriptmonkey.run()` to activate the error handler.
42
- 3. Run your code, and let ScriptMonkey handle any errors that occur.
43
-
44
- ### Example
45
-
46
- ```python
47
- import scriptmonkey
48
-
49
- # Enable Codemonkey's error handler
50
- scriptmonkey.run()
51
-
52
- # Intentional error for testing
53
- def add(a, b):
54
- return a + b # This will fail if b is a string
55
-
56
- print(add(2, "3")) # Codemonkey will automatically fix this error and update the file
57
- ```
58
-
59
- Once an error occurs, ScriptMonkey will:
60
- 1. Detect the error.
61
- 2. Send the error and code to OpenAI for analysis.
62
- 3. Provide a solution and automatically update the file with the correct code.
63
-
64
- ## How It Works
65
-
66
- ScriptMonkey replaces Python's default exception handling with a custom handler. When an error is caught, it:
67
- - Collects the traceback and the Python file that caused the error.
68
- - Sends the error message and code to OpenAI.
69
- - Receives the solution as structured JSON.
70
- - Applies the fix directly to the source file.
71
-
72
- ## Requirements
73
- - Python 3.6 or later
74
- - OpenAI API key
75
-
76
- ## Setup
77
-
78
- To use ScriptMonkey, you'll need an OpenAI API key. Set it up as follows:
79
-
80
- ```bash
81
- export OPENAI_API_KEY='your-api-key'
82
- ```
83
-
84
- Let ScriptMonkey take care of your Python errors so you can focus on building!
@@ -1,66 +0,0 @@
1
-
2
- # ScriptMonkey 🐒
3
-
4
- ScriptMonkey is a Python package that automatically detects and fixes errors in your code using OpenAI's GPT API. It works with any IDE or code editor, analyzing your code at runtime, providing solutions to errors, and even updating the file with the corrected code.
5
-
6
- ## Features
7
- - **Automatic error detection**: Captures errors during runtime.
8
- - **AI-powered fixes**: Uses OpenAI's GPT API to understand and resolve errors.
9
- - **Code auto-correction**: Automatically updates your Python files with the fixes.
10
- - **Cross-IDE compatibility**: Works with any IDE or code editor.
11
-
12
- ## Installation
13
-
14
- To install ScriptMonkey, simply run:
15
-
16
- ```bash
17
- pip install scriptmonkey
18
- ```
19
-
20
- ## Usage
21
-
22
- 1. Import `scriptmonkey` in your Python script.
23
- 2. Call `scriptmonkey.run()` to activate the error handler.
24
- 3. Run your code, and let ScriptMonkey handle any errors that occur.
25
-
26
- ### Example
27
-
28
- ```python
29
- import scriptmonkey
30
-
31
- # Enable Codemonkey's error handler
32
- scriptmonkey.run()
33
-
34
- # Intentional error for testing
35
- def add(a, b):
36
- return a + b # This will fail if b is a string
37
-
38
- print(add(2, "3")) # Codemonkey will automatically fix this error and update the file
39
- ```
40
-
41
- Once an error occurs, ScriptMonkey will:
42
- 1. Detect the error.
43
- 2. Send the error and code to OpenAI for analysis.
44
- 3. Provide a solution and automatically update the file with the correct code.
45
-
46
- ## How It Works
47
-
48
- ScriptMonkey replaces Python's default exception handling with a custom handler. When an error is caught, it:
49
- - Collects the traceback and the Python file that caused the error.
50
- - Sends the error message and code to OpenAI.
51
- - Receives the solution as structured JSON.
52
- - Applies the fix directly to the source file.
53
-
54
- ## Requirements
55
- - Python 3.6 or later
56
- - OpenAI API key
57
-
58
- ## Setup
59
-
60
- To use ScriptMonkey, you'll need an OpenAI API key. Set it up as follows:
61
-
62
- ```bash
63
- export OPENAI_API_KEY='your-api-key'
64
- ```
65
-
66
- Let ScriptMonkey take care of your Python errors so you can focus on building!
@@ -1,72 +0,0 @@
1
- import sys
2
- import traceback
3
- from .openai_client import chatgpt_json, ScriptMonkeyResponse, default_prompts
4
- from .file_handler import read_file, write_file
5
- import platform
6
- import threading
7
- import itertools
8
- import time
9
-
10
-
11
- def get_platform():
12
- os_name = platform.system()
13
- os_version = platform.release()
14
- return f"# Operating System: {os_name}, Version: {os_version}\n\n"
15
-
16
-
17
- class Spinner:
18
- def __init__(self, message="Processing"):
19
- self.spinner = itertools.cycle(["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"])
20
- self.stop_running = threading.Event()
21
- self.spin_thread = None
22
- self.message = message
23
-
24
- def spin(self):
25
- while not self.stop_running.is_set():
26
- sys.stdout.write(f"\r{self.message} {next(self.spinner)}")
27
- sys.stdout.flush()
28
- time.sleep(0.1)
29
- sys.stdout.write("\r" + " " * (len(self.message) + 2) + "\r")
30
- sys.stdout.flush()
31
-
32
- def __enter__(self):
33
- self.spin_thread = threading.Thread(target=self.spin)
34
- self.spin_thread.start()
35
-
36
- def __exit__(self, exc_type, exc_val, exc_tb):
37
- self.stop_running.set()
38
- self.spin_thread.join()
39
-
40
-
41
- def codemonkey_exception_handler(exc_type, exc_value, exc_traceback):
42
- if issubclass(exc_type, KeyboardInterrupt):
43
- sys.__excepthook__(exc_type, exc_value, exc_traceback)
44
- return
45
-
46
- error_message = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
47
-
48
- print(f"\n🐒 ScriptMonkey Detected an Error:")
49
- print(error_message, "\n")
50
-
51
- frame = traceback.extract_tb(exc_traceback)[-1]
52
- file_path = frame.filename
53
-
54
- original_code = read_file(file_path)
55
- content = f"{get_platform()}# Original Code:\n```\n{original_code}\n```\n\n# Error Message:\n{error_message}"
56
-
57
- solution = None
58
- with Spinner("🐒 ScriptMonkey is working on a solution"):
59
- solution = chatgpt_json(
60
- instructions=default_prompts.fix_error, content=content, response_format=ScriptMonkeyResponse
61
- )
62
-
63
- print(f"\n🐒 ScriptMonkey Fixed It:\nProblem:\n{solution['problem']}\n")
64
- print(f"Suggested Solution:\n{solution['solution']}\n")
65
-
66
- corrected_code = solution["corrected_code"].replace("```python", "").replace("```", "")
67
- write_file(file_path, corrected_code)
68
- print(f"🐒 ScriptMonkey automatically fixed your code at: '{file_path}'.")
69
-
70
-
71
- def run():
72
- sys.excepthook = codemonkey_exception_handler
@@ -1,12 +0,0 @@
1
- from .prompting import DefaultPrompts
2
- from .client import chatgpt_json
3
- from pydantic import BaseModel
4
-
5
-
6
- class ScriptMonkeyResponse(BaseModel):
7
- problem: str # A description of the error/problem
8
- solution: str # The solution to the problem
9
- corrected_code: str # The corrected version of the Python code
10
-
11
-
12
- default_prompts = DefaultPrompts()
@@ -1,84 +0,0 @@
1
- Metadata-Version: 2.1
2
- Name: scriptmonkey
3
- Version: 0.1.1
4
- Summary: A Python package that automatically fixes errors in your code using OpenAI's GPT API
5
- Home-page: https://github.com/lukerbs/CodeMonkey
6
- Author: Luke Kerbs
7
- Author-email: LDK.kerbs@gmail.com
8
- License: MIT
9
- Keywords: openai,GPT,AI,code error fixing,code automation,GPT API,error correction,code assistant,AI coding tools,code monkey,script monkey,automation,development tools,python tools,code analysis,machine learning
10
- Classifier: Programming Language :: Python :: 3
11
- Classifier: License :: OSI Approved :: MIT License
12
- Classifier: Operating System :: OS Independent
13
- Requires-Python: >=3.6
14
- Description-Content-Type: text/markdown
15
- Requires-Dist: openai
16
- Requires-Dist: pydantic
17
- Requires-Dist: tqdm
18
-
19
-
20
- # ScriptMonkey 🐒
21
-
22
- ScriptMonkey is a Python package that automatically detects and fixes errors in your code using OpenAI's GPT API. It works with any IDE or code editor, analyzing your code at runtime, providing solutions to errors, and even updating the file with the corrected code.
23
-
24
- ## Features
25
- - **Automatic error detection**: Captures errors during runtime.
26
- - **AI-powered fixes**: Uses OpenAI's GPT API to understand and resolve errors.
27
- - **Code auto-correction**: Automatically updates your Python files with the fixes.
28
- - **Cross-IDE compatibility**: Works with any IDE or code editor.
29
-
30
- ## Installation
31
-
32
- To install ScriptMonkey, simply run:
33
-
34
- ```bash
35
- pip install scriptmonkey
36
- ```
37
-
38
- ## Usage
39
-
40
- 1. Import `scriptmonkey` in your Python script.
41
- 2. Call `scriptmonkey.run()` to activate the error handler.
42
- 3. Run your code, and let ScriptMonkey handle any errors that occur.
43
-
44
- ### Example
45
-
46
- ```python
47
- import scriptmonkey
48
-
49
- # Enable Codemonkey's error handler
50
- scriptmonkey.run()
51
-
52
- # Intentional error for testing
53
- def add(a, b):
54
- return a + b # This will fail if b is a string
55
-
56
- print(add(2, "3")) # Codemonkey will automatically fix this error and update the file
57
- ```
58
-
59
- Once an error occurs, ScriptMonkey will:
60
- 1. Detect the error.
61
- 2. Send the error and code to OpenAI for analysis.
62
- 3. Provide a solution and automatically update the file with the correct code.
63
-
64
- ## How It Works
65
-
66
- ScriptMonkey replaces Python's default exception handling with a custom handler. When an error is caught, it:
67
- - Collects the traceback and the Python file that caused the error.
68
- - Sends the error message and code to OpenAI.
69
- - Receives the solution as structured JSON.
70
- - Applies the fix directly to the source file.
71
-
72
- ## Requirements
73
- - Python 3.6 or later
74
- - OpenAI API key
75
-
76
- ## Setup
77
-
78
- To use ScriptMonkey, you'll need an OpenAI API key. Set it up as follows:
79
-
80
- ```bash
81
- export OPENAI_API_KEY='your-api-key'
82
- ```
83
-
84
- Let ScriptMonkey take care of your Python errors so you can focus on building!
File without changes