Prepare code for safe execution by removing problematic visualization code.
(code: str)
| 105 | return blocks |
| 106 | |
| 107 | def sanitize_code(code: str) -> str: |
| 108 | """Prepare code for safe execution by removing problematic visualization code.""" |
| 109 | # Remove or modify problematic visualization code |
| 110 | lines = code.split('\n') |
| 111 | safe_lines = [] |
| 112 | for line in lines: |
| 113 | # Skip matplotlib-related imports and plotting commands that could cause issues |
| 114 | if any(x in line.lower() for x in ['matplotlib', 'plt.', '.plot(', '.show(', 'figure', 'subplot']): |
| 115 | # Replace with a comment to maintain code structure |
| 116 | safe_lines.append(f"# {line} # Removed for safety") |
| 117 | else: |
| 118 | # Keep the line if it's not visualization-related |
| 119 | safe_lines.append(line) |
| 120 | |
| 121 | return '\n'.join(safe_lines) |
| 122 | |
| 123 | def execute_code(code: str) -> Tuple[Any, str]: |
| 124 | """Attempt to execute the code using Jupyter notebook kernel and return result or error.""" |