1010
1111def extract_python_code (text : str ) -> List [str ]:
1212 """Extract Python code blocks from text."""
13+ # print(f"Extracting code: {text}")
1314 pattern = r'```python\s*(.*?)\s*```'
1415 return re .findall (pattern , text , re .DOTALL )
1516
1617def execute_code (code : str ) -> str :
1718 """Execute Python code in a Jupyter notebook environment."""
18- with tempfile .NamedTemporaryFile (suffix = '.ipynb' , delete = False ) as tmp :
19- notebook = nbformat .v4 .new_notebook ()
20- notebook ['cells' ] = [nbformat .v4 .new_code_cell (code )]
21- nbformat .write (notebook , tmp )
19+
20+ notebook = nbformat .v4 .new_notebook ()
21+ notebook ['cells' ] = [nbformat .v4 .new_code_cell (code )]
22+
23+ # Convert notebook to JSON string
24+ notebook_json = nbformat .writes (notebook )
25+
26+ # Convert JSON string to bytes
27+ notebook_bytes = notebook_json .encode ('utf-8' )
28+
29+ with tempfile .NamedTemporaryFile (mode = 'wb' , suffix = '.ipynb' , delete = False ) as tmp :
30+ tmp .write (notebook_bytes )
31+ tmp .flush ()
32+ tmp_name = tmp .name
2233
2334 try :
24- with open (tmp . name ) as f :
35+ with open (tmp_name , 'r' , encoding = 'utf-8' ) as f :
2536 nb = nbformat .read (f , as_version = 4 )
2637 ep = ExecutePreprocessor (timeout = 30 , kernel_name = 'python3' )
2738 ep .preprocess (nb , {'metadata' : {'path' : './' }})
@@ -38,7 +49,7 @@ def execute_code(code: str) -> str:
3849
3950 return output .strip ()
4051 finally :
41- os .unlink (tmp . name )
52+ os .unlink (tmp_name )
4253
4354def should_execute_request_code (query : str ) -> bool :
4455 """Decide whether to execute code from the request based on the query."""
0 commit comments