joshuarauh commited on
Commit
777994f
·
verified ·
1 Parent(s): 24cbca4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -21
app.py CHANGED
@@ -319,56 +319,83 @@ def extract_and_run_sympy_code(response_text):
319
  Returns the execution output as a string.
320
  """
321
  try:
 
 
322
  # Find the SymPy code block
323
  sympy_start = response_text.find('```python')
324
  if sympy_start == -1:
 
325
  return "No SymPy code found in the response."
326
 
327
- # Extract the code (excluding the ```python and ``` markers)
328
  code_start = response_text.find('\n', sympy_start) + 1
329
  code_end = response_text.find('```', code_start)
330
  if code_end == -1:
 
331
  return "Malformed SymPy code block."
332
 
333
  sympy_code = response_text[code_start:code_end].strip()
 
334
 
335
- # Remove any sympy import lines since we've already imported everything
336
- sympy_code = '\n'.join(line for line in sympy_code.split('\n')
337
- if not line.strip().startswith('from sympy')
338
- and not line.strip().startswith('import sympy'))
 
 
 
339
 
340
- # Create a string buffer to capture print output
341
- import io
342
- import sys
343
- from contextlib import redirect_stdout
 
344
 
345
- # Create string buffer for output
346
- output_buffer = io.StringIO()
 
347
 
348
- # Create globals dict with all SymPy symbols and add sympy module itself
349
- sympy_globals = {'sympy': sympy} # Add sympy module itself
350
- sympy_globals.update({name: getattr(sympy, name) for name in dir(sympy)})
351
- sympy_globals['__builtins__'] = __builtins__ # Add built-ins
352
 
353
- # Create locals dict to capture new variables
354
  local_vars = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
355
 
356
- # Execute the original code
357
- exec(sympy_code, sympy_globals, local_vars)
358
 
359
- # Print all variables that were created (excluding built-ins and modules)
360
  with redirect_stdout(output_buffer):
361
  print("SymPy Calculation Results:")
362
  print("-" * 25)
363
  for var_name, value in local_vars.items():
364
  if (not var_name.startswith('__') and
365
  not hasattr(value, '__module__') and
366
- var_name != 'sympy'): # Don't print the sympy module itself
367
  print(f"{var_name}: {value}")
368
 
369
- return output_buffer.getvalue()
 
 
370
 
371
  except Exception as e:
 
 
 
372
  return f"Error executing SymPy code: {str(e)}"
373
 
374
  # Create Gradio interface
 
319
  Returns the execution output as a string.
320
  """
321
  try:
322
+ logger.debug("Starting SymPy code extraction")
323
+
324
  # Find the SymPy code block
325
  sympy_start = response_text.find('```python')
326
  if sympy_start == -1:
327
+ logger.debug("No SymPy code block found")
328
  return "No SymPy code found in the response."
329
 
330
+ # Extract the code
331
  code_start = response_text.find('\n', sympy_start) + 1
332
  code_end = response_text.find('```', code_start)
333
  if code_end == -1:
334
+ logger.debug("Malformed code block - couldn't find ending ```")
335
  return "Malformed SymPy code block."
336
 
337
  sympy_code = response_text[code_start:code_end].strip()
338
+ logger.debug(f"Extracted code:\n{sympy_code}")
339
 
340
+ # Remove sympy imports
341
+ original_lines = sympy_code.split('\n')
342
+ filtered_lines = [line for line in original_lines
343
+ if not line.strip().startswith('from sympy')
344
+ and not line.strip().startswith('import sympy')]
345
+ sympy_code = '\n'.join(filtered_lines)
346
+ logger.debug(f"Code after removing imports:\n{sympy_code}")
347
 
348
+ # Create globals dict
349
+ sympy_globals = {
350
+ 'sympy': sympy,
351
+ '__builtins__': __builtins__
352
+ }
353
 
354
+ # Add all sympy attributes
355
+ for name in dir(sympy):
356
+ sympy_globals[name] = getattr(sympy, name)
357
 
358
+ logger.debug(f"Global namespace keys: {list(sympy_globals.keys())}")
 
 
 
359
 
360
+ # Create locals dict and output buffer
361
  local_vars = {}
362
+ output_buffer = io.StringIO()
363
+
364
+ logger.debug("Attempting to execute code")
365
+ # Execute with try/except to catch specific error
366
+ try:
367
+ exec(sympy_code, sympy_globals, local_vars)
368
+ except NameError as e:
369
+ logger.error(f"NameError during execution: {str(e)}")
370
+ # Log the actual error traceback
371
+ import traceback
372
+ logger.error(f"Full traceback:\n{traceback.format_exc()}")
373
+ return f"Error executing SymPy code: {str(e)}"
374
+ except Exception as e:
375
+ logger.error(f"Other error during execution: {str(e)}")
376
+ return f"Error executing SymPy code: {str(e)}"
377
 
378
+ logger.debug("Code executed successfully")
379
+ logger.debug(f"Local variables created: {list(local_vars.keys())}")
380
 
381
+ # Print results
382
  with redirect_stdout(output_buffer):
383
  print("SymPy Calculation Results:")
384
  print("-" * 25)
385
  for var_name, value in local_vars.items():
386
  if (not var_name.startswith('__') and
387
  not hasattr(value, '__module__') and
388
+ var_name != 'sympy'):
389
  print(f"{var_name}: {value}")
390
 
391
+ result = output_buffer.getvalue()
392
+ logger.debug(f"Final output:\n{result}")
393
+ return result
394
 
395
  except Exception as e:
396
+ logger.error(f"Top-level error in extract_and_run_sympy_code: {str(e)}")
397
+ import traceback
398
+ logger.error(f"Full traceback:\n{traceback.format_exc()}")
399
  return f"Error executing SymPy code: {str(e)}"
400
 
401
  # Create Gradio interface