code_utils.py 860 B

1234567891011121314151617181920212223242526272829
  1. import os
  2. import re
  3. import json5
  4. def replace_upload_fname(text, upload_fname_list):
  5. for full_input_fname in upload_fname_list:
  6. if full_input_fname not in text and os.path.basename(full_input_fname) in text:
  7. text = text.replace(os.path.basename(full_input_fname), full_input_fname)
  8. return text
  9. def extract_code(text):
  10. # Match triple backtick blocks first
  11. triple_match = re.search(r'```[^\n]*\n(.+?)```', text, re.DOTALL)
  12. # Match single backtick blocks second
  13. single_match = re.search(r'`([^`]*)`', text, re.DOTALL)
  14. if triple_match:
  15. text = triple_match.group(1)
  16. elif single_match:
  17. text = single_match.group(1)
  18. else:
  19. try:
  20. text = json5.loads(text)['code']
  21. except Exception:
  22. pass
  23. # If no code blocks found, return original text
  24. return text