├── .github └── FUNDING.yml ├── LICENSE ├── README.md ├── advanced-1.md └── settings-ci.png /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [volkansah] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 12 | polar: # Replace with a single Polar username 13 | buy_me_a_coffee: volkansah 14 | thanks_dev: # Replace with a single thanks.dev username 15 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Volkan Şah //NCF 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Exploring the Code Interpreter in OpenAI (GPT) 2 | ###### (version 21.05.2024) 3 | 4 | The code interpreter is an advanced feature of OpenAI's GPTs.x & ChatGPT that brings a new level of interactivity to the AI model. 5 | It is designed to execute Python code in a sandboxed environment and provide real-time results, making it a powerful 6 | tool for a wide range of tasks from mathematical computations to data analysis, from code prototyping to teaching and 7 | learning Python programming interactively. While there are certain limitations to its functionality due to security 8 | reasons, it opens up a whole new set of possibilities for how users can interact with ChatGPT. 9 | 10 | ## Table of Contents 11 | 12 | - [What is the Code Interpreter?](#what-is-the-code-interpreter) 13 | - [What is the Code Interpreter used for?](#what-is-the-code-interpreter-used-for) 14 | - [How can ChatGPT assist with programming?](#how-can-chatgpt-assist-with-programming) 15 | - [What are the limitations?](#what-are-the-limitations) 16 | - [What are the benefits?](#what-are-the-benefits) 17 | - [Installation and Setup](#installation-and-setup) 18 | - [Data Storage](#data-storage) 19 | - [Detailed Explanation of the Data Storage](#detailed-explanation-of-the-data-storage) 20 | - [Working with Images](#working-with-images) 21 | - [Working with Exel-Files](#working-with-excel-files) 22 | - [Advanced Excel Processing](#advanced-excel-processing) 23 | - [Working with Word-Files](#working-with-word-files) 24 | - [Advanced Word Processing](#advanced-word-processing) 25 | - [Working with PDF-Files](#working-with-pdf-files) 26 | - [Advanced PDF Processing](#advanced-pdf-processing) 27 | - [other advanced Applications of the Code Interpreter](advanced-1.md) 28 | - [Contributing](#contributing) 29 | - [Credits](#credits) 30 | 31 | 32 | 33 | 34 | ## The Code Interpreter in OpenAI ChatGPT 35 | 36 | ### What is the Code Interpreter? 37 | 38 | The code interpreter is a tool developed by OpenAI to execute programming code in an interactive environment. It is capable of running Python code and displaying the results in real-time. 39 | 40 | ### What is the Code Interpreter used for? 41 | 42 | The code interpreter can be used for a variety of tasks, including: 43 | 44 | - Performing complex mathematical calculations 45 | - Analyzing and visualizing data 46 | - Prototyping and debugging Python code 47 | - Interactive learning and practicing Python programming 48 | 49 | ## How can ChatGPT assist with programming? 50 | 51 | ChatGPT can generate, review, and debug code based on the provided requirements. It can also assist in structuring code and provide suggestions for improvements. Moreover, it can explain complex programming concepts and assist in solving coding problems. 52 | 53 | ## What are the limitations? 54 | 55 | While the code interpreter is a powerful tool, it has certain limitations: 56 | 57 | - It does not have access to the internet. This means it cannot make external requests. 58 | - It runs in an isolated environment and does not have access to the operating system or its resources. 59 | - Code execution that takes longer than 120 seconds is automatically stopped. 60 | - It has access to a special location, '/mnt/data', where it can read and write files. 61 | 62 | Despite these limitations, the code interpreter is a versatile tool that can greatly assist programmers of all skill levels. 63 | 64 | ## What are the benefits? 65 | 66 | The code interpreter offers several benefits: 67 | 68 | - It provides a safe environment to run code without the risk of affecting the operating system or data. 69 | - It allows for real-time interaction with the code, providing immediate feedback. 70 | - It can assist in learning Python programming and improving coding skills. 71 | - It can handle a variety of tasks, from simple calculations to data analysis and visualization. 72 | 73 | ## Installation and Setup 74 | 75 | To execute the examples mentioned in this README, you need to install some Python libraries. You can install them using pip: 76 | 77 | ```shell 78 | pip install pandas openpyxl python-docx PyPDF2 fpdf2 matplotlib pillow 79 | ``` 80 | 81 | ## Data Storage 82 | 83 | The code interpreter has access to a special directory, '/mnt/data', where it can read and write files. This can be used for operations that need to save or load data, like writing logs, saving plots, or loading data for analysis. However, no other locations on the filesystem can be accessed. 84 | 85 | ### Detailed Explanation of the Data Storage 86 | 87 | The '/mnt/data' directory is a special storage location that the code interpreter can access to read and write files. This is especially useful for operations that require persistent storage or the exchange of data between different code executions. 88 | 89 | Here are some ways you can use the '/mnt/data' directory: 90 | 91 | 1. **Saving and Loading Data Files:** If you're working with data in formats like .csv, .json, .txt, etc., you can read from and write to these files directly in this directory. For instance, to write a list of numbers to a .txt file, you would do: 92 | 93 | ```python 94 | with open('/mnt/data/numbers.txt', 'w') as file: 95 | for num in range(10): 96 | file.write(str(num) + '\n') 97 | ``` 98 | 99 | To read the file, you would do: 100 | 101 | ```python 102 | with open('/mnt/data/numbers.txt', 'r') as file: 103 | numbers = file.readlines() 104 | ``` 105 | 106 | 2. **Storing Logs:** If you're running code that generates logs (like debugging information, progress of a task, etc.), you can write these logs to a file in '/mnt/data'. 107 | 108 | ```python 109 | with open('/mnt/data/log.txt', 'w') as file: 110 | file.write('This is a log message.') 111 | ``` 112 | 113 | 3. **Saving Plots and Images:** If you're generating plots or other images with your code, you can save them to '/mnt/data' as .png, .jpg, or other image formats. For instance, if you're using matplotlib to create a plot, you can save it with: 114 | 115 | ```python 116 | import matplotlib.pyplot as plt 117 | 118 | plt.plot([0, 1, 2, 3, 4], [0, 1, 4, 9, 16]) 119 | plt.savefig('/mnt/data/plot.png') 120 | ``` 121 | 122 | You can then download the image file directly from the generated sandbox link. 123 | 124 | Remember, any file operations need to be done using the '/mnt/data' path. The code interpreter does not have access to any other locations on the filesystem. 125 | 126 | ## Working with Images 127 | 128 | With the help of various Python libraries such as PIL (Python Imaging Library), OpenCV, and matplotlib, a variety of operations can be performed on images. Here are some examples: 129 | 130 | 1. **Displaying Image:** Display an image. 131 | 132 | ```python 133 | from PIL import Image 134 | import matplotlib.pyplot as plt 135 | 136 | # Open the image file 137 | img = Image.open('/mnt/data/your_image.jpg') 138 | 139 | # Display the image 140 | plt.imshow(img) 141 | plt.axis('off') # Turn off the axis 142 | plt.show() 143 | ``` 144 | 145 | 2. **Resizing Image:** Change the size of an image, enlarge or shrink it. 146 | 147 | ```python 148 | # Resize the image 149 | img_resized = img.resize((new_width, new_height)) 150 | ``` 151 | 152 | 3. **Rotating or Flipping Image:** Rotate an image or flip it horizontally or vertically. 153 | 154 | ```python 155 | # Rotate the image 156 | img_rotated = img.rotate(angle) 157 | 158 | # Flip the image 159 | img_flipped = img.transpose(Image.FLIP_LEFT_RIGHT) 160 | ``` 161 | 162 | 4. **Color Conversions:** Convert an image to grayscale or change the color mode. 163 | 164 | ```python 165 | # Convert the image to grayscale 166 | img_gray = img.convert('L') 167 | ``` 168 | 169 | 5. **Adjusting Brightness, Contrast, and Saturation:** Adjust the brightness, contrast, or saturation of an image. 170 | 171 | ```python 172 | from PIL import ImageEnhance 173 | 174 | # Increase the brightness 175 | enhancer = ImageEnhance.Brightness(img) 176 | img_brighter = enhancer.enhance(1.5) 177 | ``` 178 | 179 | 6. **Applying Filters:** Apply different types of filters, like Gaussian blur, edge detection, etc. 180 | 181 | ```python 182 | from PIL import ImageFilter 183 | 184 | # Apply a filter 185 | img_blurred = img.filter(ImageFilter.GaussianBlur(radius=5)) 186 | ``` 187 | 188 | 7. **Image Analysis:** Perform simple image analysis, like calculating the histogram. 189 | 190 | ```python 191 | # Get the histogram 192 | hist = img.histogram() 193 | ``` 194 | 195 | 8. **Image Merging:** Merge multiple images into a single image. 196 | 197 | ```python 198 | # Merge images 199 | img_merged = Image.merge('RGB', [img1, img2, img3]) 200 | ``` 201 | 202 | 203 | # Working with Excel Files 204 | 205 | Handling Excel files is a common task that can range from data analysis to generating reports. Here's a guide on basic and advanced operations with Excel files using Python: 206 | 207 | #### Reading and Writing Excel Files 208 | 209 | To read and write Excel files, `pandas` along with `openpyxl` is commonly used. Here's how to read from and write to an Excel file: 210 | 211 | ```python 212 | import pandas as pd 213 | 214 | # Load an Excel file 215 | df = pd.read_excel('/mnt/data/example.xlsx') 216 | 217 | # Display data 218 | print(df.head()) 219 | ``` 220 | 221 | ###To write data to an Excel file: 222 | 223 | ```python 224 | # Create a DataFrame 225 | data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]} 226 | df = pd.DataFrame(data) 227 | 228 | # Write DataFrame to an Excel file 229 | df.to_excel('/mnt/data/saved_data.xlsx', index=False) 230 | ``` 231 | 232 | ### Filtering and Manipulating Data 233 | 234 | You can filter data based on conditions, add new columns, or transform existing data: 235 | 236 | ```python 237 | # Filter rows where age is greater than 28 238 | filtered_df = df[df['Age'] > 28] 239 | 240 | # Add a new column 241 | df['Age Next Year'] = df['Age'] + 1 242 | 243 | # Sort data 244 | sorted_df = df.sort_values(by='Age', ascending=False) 245 | ``` 246 | 247 | ## Advanced Excel Processing 248 | 249 | Besides reading and writing Excel files, you can also perform advanced data processing tasks such as creating pivot tables or merging multiple Excel files. 250 | ### Creating a Pivot Table 251 | 252 | ```python 253 | import pandas as pd 254 | 255 | # Load example data 256 | df = pd.read_excel('/mnt/data/example.xlsx') 257 | 258 | # Create a pivot table 259 | pivot_table = df.pivot_table(index='Category', values='Sales', aggfunc='sum') 260 | 261 | # Display the pivot table 262 | print(pivot_table) 263 | ``` 264 | ### Merging Multiple Excel Files 265 | 266 | ```python 267 | import pandas as pd 268 | import glob 269 | 270 | # Read all Excel files in the directory 271 | files = glob.glob('/mnt/data/*.xlsx') 272 | 273 | # Merge data from all files 274 | df_list = [pd.read_excel(file) for file in files] 275 | merged_df = pd.concat(df_list, ignore_index=True) 276 | 277 | # Display the merged data 278 | print(merged_df.head()) 279 | ``` 280 | 281 | ## Troubleshooting 282 | Here are some common issues and their solutions: 283 | 284 | 1. ImportError: No module named '...': 285 | - Ensure that all required libraries are installed. Use pip install to install any missing libraries. 286 | 287 | 2. FileNotFoundError: [Errno 2] No such file or directory: '...': 288 | - Check the file path and ensure that the file is in the correct directory. Use absolute paths or ensure that the file is saved in /mnt/data. 289 | 290 | 3. PermissionError: [Errno 13] Permission denied: '...': 291 | - Ensure that you have permissions to read and write in the /mnt/data directory. 292 | 293 | **If you encounter further issues, open an issue on GitHub or contact the project maintainer.** 294 | 295 | 296 | # Working with Word Files 297 | 298 | Handling Microsoft Word files involves reading, writing, and modifying documents. Here’s how you can manage Word files using Python: 299 | 300 | ### Reading from Word Files 301 | 302 | To read text from Word documents, the `python-docx` library is used: 303 | 304 | ```python 305 | from docx import Document 306 | 307 | # Load a Word document 308 | doc = Document('/mnt/data/example.docx') 309 | 310 | # Read each paragraph 311 | for para in doc.paragraphs: 312 | print(para.text) 313 | ``` 314 | 315 | ### Writing to Word Files 316 | 317 | To create and write to Word documents: 318 | 319 | ```python 320 | from docx import Document 321 | 322 | # Create a new Word document 323 | doc = Document() 324 | doc.add_paragraph('Hello, this is a test document.') 325 | 326 | # Save the document 327 | doc.save('/mnt/data/new_example.docx') 328 | ``` 329 | 330 | ## Advanced Word Processing 331 | 332 | ```python 333 | from docx import Document 334 | 335 | # Create a new Word document 336 | doc = Document() 337 | 338 | # Add a table with specified number of rows and columns 339 | table = doc.add_table(rows=3, cols=3) 340 | 341 | # Add data to the table 342 | data = [ 343 | ["Header 1", "Header 2", "Header 3"], 344 | ["Row 1, Col 1", "Row 1, Col 2", "Row 1, Col 3"], 345 | ["Row 2, Col 1", "Row 2, Col 2", "Row 2, Col 3"] 346 | ] 347 | 348 | for row_index, row_data in enumerate(data): 349 | row = table.rows[row_index] 350 | for col_index, cell_data in enumerate(row_data): 351 | row.cells[col_index].text = cell_data 352 | 353 | # Save the document 354 | doc.save('/mnt/data/table_example.docx') 355 | ``` 356 | ### Formatting Text in a Word Document 357 | ```python 358 | from docx import Document 359 | from docx.shared import Pt, RGBColor 360 | 361 | # Load a Word document 362 | doc = Document('/mnt/data/example.docx') 363 | 364 | # Add a paragraph with specific formatting 365 | paragraph = doc.add_paragraph() 366 | run = paragraph.add_run('This is a formatted text.') 367 | run.font.size = Pt(14) # Font size 368 | run.font.bold = True # Bold text 369 | run.font.color.rgb = RGBColor(255, 0, 0) # Red color text 370 | 371 | # Save the document 372 | doc.save('/mnt/data/formatted_text.docx') 373 | ``` 374 | ### Adding Images to a Word Document 375 | ```python 376 | from docx import Document 377 | from docx.shared import Inches 378 | 379 | # Create a new Word document 380 | doc = Document() 381 | 382 | # Add a paragraph 383 | doc.add_paragraph('Below is an image:') 384 | 385 | # Add an image to the document 386 | doc.add_picture('/mnt/data/your_image.jpg', width=Inches(4), height=Inches(3)) 387 | 388 | # Save the document 389 | doc.save('/mnt/data/image_example.docx') 390 | ``` 391 | ### Inserting Headers and Footers 392 | ```python 393 | from docx import Document 394 | 395 | # Create a new Word document 396 | doc = Document() 397 | 398 | # Add a header 399 | header = doc.sections[0].header 400 | header_paragraph = header.paragraphs[0] 401 | header_paragraph.text = "This is the header" 402 | 403 | # Add a footer 404 | footer = doc.sections[0].footer 405 | footer_paragraph = footer.paragraphs[0] 406 | footer_paragraph.text = "This is the footer" 407 | 408 | # Add some body text 409 | doc.add_paragraph("This is the body text of the document.") 410 | 411 | # Save the document 412 | doc.save('/mnt/data/header_footer_example.docx') 413 | ``` 414 | 415 | 416 | 417 | 418 | 419 | # Working with PDF Files 420 | 421 | Managing PDF files often involves reading, extracting text, and sometimes converting them to other formats. Here’s how to handle PDF files using Python: 422 | 423 | ### Reading and Extracting Text from PDF Files 424 | 425 | To read and extract text from PDF files, the `PyPDF2` library is commonly used: 426 | 427 | ```python 428 | import PyPDF2 429 | 430 | # Open a PDF file 431 | with open('/mnt/data/example.pdf', 'rb') as file: 432 | pdf_reader = PyPDF2.PdfReader(file) 433 | 434 | # Extract text from the first page 435 | page = pdf_reader.pages[0] 436 | text = page.extract_text() 437 | print(text) 438 | ``` 439 | 440 | ## Creating and Writing to PDF Files 441 | 442 | Creating and writing text to PDF files can be done using the `fpdf2` library: 443 | 444 | ```python 445 | from fpdf import FPDF 446 | 447 | # Create instance of FPDF class 448 | pdf = FPDF() 449 | 450 | # Add a page 451 | pdf.add_page() 452 | 453 | # Set font 454 | pdf.set_font("Arial", size = 12) 455 | 456 | # Add a cell 457 | pdf.cell(200, 10, txt = "Welcome to PDF handling with Python!", ln = True, align = 'C') 458 | 459 | # Save the PDF to a file 460 | pdf.output('/mnt/data/new_example.pdf') 461 | ``` 462 | 463 | # Advanced PDF Processing 464 | Handling PDF files often involves reading, extracting text, merging, splitting, and modifying documents. Here are some advanced operations using Python: 465 | ### Merging Multiple PDF Files 466 | 467 | ```python 468 | import PyPDF2 469 | 470 | # List of PDF files to be merged 471 | pdf_files = ['/mnt/data/file1.pdf', '/mnt/data/file2.pdf', '/mnt/data/file3.pdf'] 472 | 473 | # Create a PDF merger object 474 | pdf_merger = PyPDF2.PdfMerger() 475 | 476 | # Append each PDF file 477 | for pdf in pdf_files: 478 | pdf_merger.append(pdf) 479 | 480 | # Write out the merged PDF 481 | with open('/mnt/data/merged.pdf', 'wb') as merged_pdf: 482 | pdf_merger.write(merged_pdf) 483 | ``` 484 | ### Splitting a PDF into Multiple Files 485 | 486 | ```python 487 | import PyPDF2 488 | 489 | # Path to the PDF file 490 | pdf_path = '/mnt/data/example.pdf' 491 | 492 | # Create a PDF reader object 493 | pdf_reader = PyPDF2.PdfReader(pdf_path) 494 | 495 | # Split the PDF into separate pages 496 | for page_num in range(len(pdf_reader.pages)): 497 | pdf_writer = PyPDF2.PdfWriter() 498 | pdf_writer.add_page(pdf_reader.pages[page_num]) 499 | 500 | # Save each page as a separate PDF 501 | output_path = f'/mnt/data/split_page_{page_num + 1}.pdf' 502 | with open(output_path, 'wb') as output_pdf: 503 | pdf_writer.write(output_pdf) 504 | ``` 505 | ### Adding a Watermark to a PDF 506 | 507 | ```python 508 | import PyPDF2 509 | 510 | # Paths to the original PDF and the watermark PDF 511 | original_pdf_path = '/mnt/data/original.pdf' 512 | watermark_pdf_path = '/mnt/data/watermark.pdf' 513 | 514 | # Create PDF reader objects 515 | original_pdf = PyPDF2.PdfReader(original_pdf_path) 516 | watermark_pdf = PyPDF2.PdfReader(watermark_pdf_path) 517 | 518 | # Create a PDF writer object 519 | pdf_writer = PyPDF2.PdfWriter() 520 | 521 | # Apply the watermark to each page 522 | for page_num in range(len(original_pdf.pages)): 523 | original_page = original_pdf.pages[page_num] 524 | watermark_page = watermark_pdf.pages[0] 525 | original_page.merge_page(watermark_page) 526 | pdf_writer.add_page(original_page) 527 | 528 | # Save the watermarked PDF 529 | with open('/mnt/data/watermarked.pdf', 'wb') as watermarked_pdf: 530 | pdf_writer.write(watermarked_pdf) 531 | ``` 532 | ### Extracting Text from a Specific Page Range 533 | ```python 534 | import PyPDF2 535 | 536 | # Path to the PDF file 537 | pdf_path = '/mnt/data/example.pdf' 538 | 539 | # Create a PDF reader object 540 | pdf_reader = PyPDF2.PdfReader(pdf_path) 541 | 542 | # Specify the range of pages to extract text from 543 | start_page = 1 544 | end_page = 3 545 | 546 | # Extract text from the specified page range 547 | extracted_text = '' 548 | for page_num in range(start_page - 1, end_page): 549 | page = pdf_reader.pages[page_num] 550 | extracted_text += page.extract_text() 551 | 552 | print(extracted_text) 553 | ``` 554 | ### Adding Metadata to a PDF 555 | ```python 556 | import PyPDF2 557 | 558 | # Path to the PDF file 559 | pdf_path = '/mnt/data/example.pdf' 560 | 561 | # Create a PDF reader object 562 | pdf_reader = PyPDF2.PdfReader(pdf_path) 563 | pdf_writer = PyPDF2.PdfWriter() 564 | 565 | # Copy all pages to the writer object 566 | for page_num in range(len(pdf_reader.pages)): 567 | pdf_writer.add_page(pdf_reader.pages[page_num]) 568 | 569 | # Add metadata 570 | metadata = { 571 | '/Title': 'Example PDF', 572 | '/Author': 'Your Name', 573 | '/Subject': 'Example Subject', 574 | '/Keywords': 'PDF, example, metadata' 575 | } 576 | pdf_writer.add_metadata(metadata) 577 | 578 | # Save the PDF with metadata 579 | with open('/mnt/data/metadata_example.pdf', 'wb') as metadata_pdf: 580 | pdf_writer.write(metadata_pdf) 581 | 582 | ``` 583 | 584 | ## Contributing 585 | Contributions are welcome! Please feel free to submit a pull request. 586 | 587 | ## [❤️](https://jugendamt-deutschland.de) Thank you for your support! 588 | If you appreciate my work, please consider supporting me: 589 | 590 | 591 | ### 👣 other GPT stuff 592 | - [Link to ChatGPT Shellmaster](https://github.com/VolkanSah/ChatGPT-ShellMaster/) 593 | - [GPT-Security-Best-Practices](https://github.com/VolkanSah/GPT-Security-Best-Practices) 594 | - [OpenAi cost calculator](https://github.com/VolkanSah/OpenAI-Cost-Calculator) 595 | - [GPT over CLI](https://github.com/VolkanSah/GPT-over-CLI) 596 | - [Secure Implementation of Artificial Intelligence (AI)](https://github.com/VolkanSah/Implementing-AI-Systems-Whitepaper) 597 | - [Comments Reply with GPT (davinci3)](https://github.com/VolkanSah/GPT-Comments-Reply-WordPress-Plugin) 598 | - [Basic GPT Webinterface](https://github.com/VolkanSah/GPT-API-Integration-in-HTML-CSS-with-JS-PHP) 599 | 600 | 601 | ### Credits 602 | - [Volkan Kücükbudak //NCF](https://gihub.com/volkansah) 603 | - and OpenAI's ChatGPT4 with Code Interpreter for providing interactive coding assistance and insights & tipps. 604 | - Become a Sponsor: [Link to my sponsorship page](https://github.com/sponsors/volkansah) 605 | - :star: my projects: Starring projects on GitHub helps increase their visibility and can help others find my work. 606 | - Follow me: Stay updated with my latest projects and releases. 607 | - [Source of this resposerity](https://github.com/VolkanSah/The-Code-Interpreter-in-OpenAI-GPT/) 608 | 609 | -------------------------------------------------------------------------------- /advanced-1.md: -------------------------------------------------------------------------------- 1 | 2 | # Advanced Applications of the Code Interpreter (GPT) 3 | 4 | [Go Back](https://volkansah.github.io/The-Code-Interpreter-in-OpenAI-GPT/) 5 | 6 | The code interpreter in OpenAI's GPT is a powerful tool that enables complex and interactive coding capabilities within a safe and sandboxed environment. This README provides examples of advanced applications, demonstrating how to leverage this tool for sophisticated tasks. 7 | 8 | ## Table of Contents 9 | 10 | - [Introduction](#introduction) 11 | - [Data Analysis and Visualization](#data-analysis-and-visualization) 12 | - [Machine Learning Applications](#machine-learning-applications) 13 | - [Advanced Data Processing](#advanced-data-processing) 14 | - [Web Scraping](#web-scraping) 15 | - [Natural Language Processing](#natural-language-processing) 16 | - [Image Processing](#image-processing) 17 | - [Interactive Widgets](#interactive-widgets) 18 | - [Troubleshooting](#troubleshooting) 19 | - [Contributing](#contributing) 20 | - [Credits](#credits) 21 | 22 | ## Introduction 23 | 24 | This document aims to showcase the advanced capabilities of the code interpreter in OpenAI's GPT. From data analysis and machine learning to web scraping and image processing, the examples provided here are intended to help users unlock the full potential of this tool. 25 | 26 | ## Data Analysis and Visualization 27 | 28 | ### Complex Data Analysis with Pandas and Matplotlib 29 | 30 | Performing advanced data analysis and visualizing the results using `pandas` and `matplotlib`. 31 | 32 | ```python 33 | import pandas as pd 34 | import matplotlib.pyplot as plt 35 | 36 | # Load a complex dataset 37 | df = pd.read_csv('/mnt/data/complex_data.csv') 38 | 39 | # Perform data cleaning and preprocessing 40 | df = df.dropna() 41 | df['date'] = pd.to_datetime(df['date']) 42 | 43 | # Analyze and visualize data 44 | pivot_table = df.pivot_table(index='date', values='sales', aggfunc='sum') 45 | pivot_table.plot(figsize=(10, 6), title='Sales Over Time') 46 | plt.xlabel('Date') 47 | plt.ylabel('Sales') 48 | plt.grid(True) 49 | plt.savefig('/mnt/data/sales_over_time.png') 50 | plt.show() 51 | ``` 52 | 53 | ## Machine Learning Applications 54 | 55 | ### Building a Predictive Model with Scikit-Learn 56 | 57 | #### Creating a machine learning model to predict outcomes based on complex datasets. 58 | 59 | ```python 60 | import pandas as pd 61 | from sklearn.model_selection import train_test_split 62 | from sklearn.ensemble import RandomForestRegressor 63 | from sklearn.metrics import mean_squared_error 64 | 65 | # Load the dataset 66 | df = pd.read_csv('/mnt/data/ml_dataset.csv') 67 | 68 | # Prepare the data 69 | X = df.drop('target', axis=1) 70 | y = df['target'] 71 | X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) 72 | 73 | # Train a Random Forest model 74 | model = RandomForestRegressor(n_estimators=100, random_state=42) 75 | model.fit(X_train, y_train) 76 | 77 | # Make predictions and evaluate the model 78 | y_pred = model.predict(X_test) 79 | mse = mean_squared_error(y_test, y_pred) 80 | print(f'Mean Squared Error: {mse}') 81 | ``` 82 | 83 | ## Advanced Data Processing 84 | 85 | ### Merging Multiple DataFrames 86 | 87 | #### Merging multiple dataframes to create a comprehensive dataset for analysis. 88 | 89 | ```python 90 | import pandas as pd 91 | 92 | # Load multiple datasets 93 | df1 = pd.read_csv('/mnt/data/data1.csv') 94 | df2 = pd.read_csv('/mnt/data/data2.csv') 95 | df3 = pd.read_csv('/mnt/data/data3.csv') 96 | 97 | # Merge datasets 98 | merged_df = pd.merge(df1, df2, on='common_column') 99 | merged_df = pd.merge(merged_df, df3, on='another_common_column') 100 | 101 | # Display the merged dataframe 102 | print(merged_df.head()) 103 | ``` 104 | 105 | ## Web Scraping 106 | 107 | ### Scraping Data from Web Pages with BeautifulSoup 108 | 109 | #### Using BeautifulSoup to scrape data from web pages for analysis. 110 | maybe usefull? [Python-XPath Tutorial](https://github.com/VolkanSah/Python-XPath-Tutorial) | [JavaScript-XPath Tutorial](https://github.com/VolkanSah/JavaScript-XPath-Tutorial) 111 | 112 | ```python 113 | import requests 114 | from bs4 import BeautifulSoup 115 | 116 | # Send a request to the webpage 117 | url = 'https://example.com/data-page' 118 | response = requests.get(url) 119 | 120 | # Parse the HTML content 121 | soup = BeautifulSoup(response.content, 'html.parser') 122 | 123 | # Extract specific data 124 | data = [] 125 | table = soup.find('table', {'id': 'data-table'}) 126 | for row in table.find_all('tr'): 127 | columns = row.find_all('td') 128 | row_data = [col.text for col in columns] 129 | data.append(row_data) 130 | 131 | # Display the scraped data 132 | for item in data: 133 | print(item) 134 | ``` 135 | 136 | ## Natural Language Processing 137 | 138 | ### Sentiment Analysis with TextBlob 139 | 140 | #### Performing sentiment analysis on text data using TextBlob. 141 | 142 | ```python 143 | from textblob import TextBlob 144 | 145 | # Example text 146 | text = "OpenAI's GPT is amazing. I'm so happy with the results!" 147 | 148 | # Perform sentiment analysis 149 | blob = TextBlob(text) 150 | sentiment = blob.sentiment 151 | 152 | # Display the sentiment 153 | print(f'Sentiment: {sentiment}') 154 | ``` 155 | 156 | ## Image Processing 157 | 158 | ### Advanced Image Manipulations with PIL 159 | 160 | #### Performing advanced image manipulations using the Python Imaging Library (PIL). 161 | 162 | ```python 163 | from PIL import Image, ImageEnhance, ImageFilter 164 | 165 | # Open an image file 166 | img = Image.open('/mnt/data/sample_image.jpg') 167 | 168 | # Apply enhancements and filters 169 | enhancer = ImageEnhance.Contrast(img) 170 | img_enhanced = enhancer.enhance(2) 171 | img_filtered = img_enhanced.filter(ImageFilter.DETAIL) 172 | 173 | # Save the processed image 174 | img_filtered.save('/mnt/data/processed_image.jpg') 175 | 176 | # Display the processed image 177 | img_filtered.show() 178 | ``` 179 | 180 | ## Interactive Widgets 181 | 182 | ### Creating Interactive Widgets with ipywidgets 183 | 184 | #### Creating interactive widgets to enhance user interaction within Jupyter notebooks. 185 | 186 | ```python 187 | import ipywidgets as widgets 188 | from IPython.display import display 189 | 190 | # Create a slider widget 191 | slider = widgets.IntSlider(value=10, min=0, max=100, step=1, description='Value:') 192 | 193 | # Define an event handler 194 | def on_value_change(change): 195 | print(f'Slider value: {change["new"]}') 196 | 197 | # Attach the event handler to the slider 198 | slider.observe(on_value_change, names='value') 199 | 200 | # Display the slider 201 | display(slider) 202 | ``` 203 | 204 | ## Troubleshooting 205 | 206 | ### Here are some common issues and their solutions: 207 | 208 | - `ImportError: No module named '...'`: Ensure that all required libraries are installed. Use `pip install ` to install any missing libraries. 209 | - `FileNotFoundError: [Errno 2] No such file or directory: '...'`: Check the file path and ensure that the file is in the correct directory. Use absolute paths or ensure that the file is saved in `/mnt/data`. 210 | - `PermissionError: [Errno 13] Permission denied: '...'`: Ensure that you have permissions to read and write in the `/mnt/data` directory. 211 | 212 | #### If you encounter further issues, open an issue on GitHub or contact the project maintainer. 213 | 214 | ## Contributing 215 | Contributions are welcome! Please feel free to submit a pull request. 216 | 217 | ### 👣 other GPT stuff 218 | - [Link to ChatGPT Shellmaster](https://github.com/VolkanSah/ChatGPT-ShellMaster/) 219 | - [GPT-Security-Best-Practices](https://github.com/VolkanSah/GPT-Security-Best-Practices) 220 | - [OpenAi cost calculator](https://github.com/VolkanSah/OpenAI-Cost-Calculator) 221 | - [GPT over CLI](https://github.com/VolkanSah/GPT-over-CLI) 222 | - [Secure Implementation of Artificial Intelligence (AI)](https://github.com/VolkanSah/Implementing-AI-Systems-Whitepaper) 223 | - [Comments Reply with GPT (davinci3)](https://github.com/VolkanSah/GPT-Comments-Reply-WordPress-Plugin) 224 | - [Basic GPT Webinterface](https://github.com/VolkanSah/GPT-API-Integration-in-HTML-CSS-with-JS-PHP) 225 | 226 | 227 | 228 | ### Credits 229 | - [Volkan Kücükbudak //NCF](https://gihub.com/volkansah) 230 | - and OpenAI's ChatGPT4 with Code Interpreter for providing interactive coding assistance and insights & tipps. 231 | - Become a Sponsor: [Link to my sponsorship page](https://github.com/sponsors/volkansah) 232 | - :star: my projects: Starring projects on GitHub helps increase their visibility and can help others find my work. 233 | - Follow me: Stay updated with my latest projects and releases. 234 | - [Source of this resposerity](https://github.com/VolkanSah/The-Code-Interpreter-in-OpenAI-GPT/) 235 | -------------------------------------------------------------------------------- /settings-ci.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/VolkanSah/Exploring-the-Code-Interpreter-in-OpenAI-GPT/d82089de553e7cca6ee45bdafb85b2fcf5d38e65/settings-ci.png --------------------------------------------------------------------------------