test_scratchpad_regex.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import re
  2. def strip_scratchpad(text: str) -> str:
  3. # Strip out the XML <scratchpad> tag and everything in between, non-greedily
  4. clean_text = re.sub(r'<scratchpad>.*?</scratchpad>', '', text, flags=re.DOTALL)
  5. return clean_text.strip()
  6. def filter_scratchpad_stream(stream):
  7. buffer = ""
  8. in_scratchpad = False
  9. for content in stream:
  10. buffer += content
  11. while True:
  12. if not in_scratchpad:
  13. start_idx = buffer.find("<scratchpad>")
  14. if start_idx != -1:
  15. yield buffer[:start_idx]
  16. buffer = buffer[start_idx:]
  17. in_scratchpad = True
  18. else:
  19. yield_len = max(0, len(buffer) - 11)
  20. if yield_len > 0:
  21. yield buffer[:yield_len]
  22. buffer = buffer[yield_len:]
  23. break
  24. else:
  25. end_idx = buffer.find("</scratchpad>")
  26. if end_idx != -1:
  27. buffer = buffer[end_idx + 13:]
  28. in_scratchpad = False
  29. else:
  30. keep_len = 12
  31. if len(buffer) > keep_len:
  32. buffer = buffer[-keep_len:]
  33. break
  34. if not in_scratchpad and buffer:
  35. yield buffer
  36. # Test data
  37. test_input = """<scratchpad>
  38. - Cups to grams conversion
  39. - Calorie summation
  40. </scratchpad>
  41. | Meal Time | Exact Food | Portion Size | Calories | Protein |
  42. | --- | --- | --- | --- | --- |
  43. | Breakfast | Oatmeal | 1 cup | 150 kcal | 5g |"""
  44. # 1. Test strip_scratchpad
  45. stripped = strip_scratchpad(test_input)
  46. print("--- Test strip_scratchpad ---")
  47. print(repr(stripped))
  48. assert "<scratchpad>" not in stripped
  49. assert "</scratchpad>" not in stripped
  50. assert "Oatmeal" in stripped
  51. print("Pass!")
  52. # 2. Test filter_scratchpad_stream
  53. stream_chunks = [
  54. "| Meal Time | ",
  55. "<scrat",
  56. "chpad>\n- Co",
  57. "T\n</scrat",
  58. "chpad>\n| Breakfast |",
  59. " Oatmeal |",
  60. ]
  61. stream_result = "".join(filter_scratchpad_stream(stream_chunks))
  62. print("\n--- Test filter_scratchpad_stream ---")
  63. print(repr(stream_result))
  64. assert "<scratchpad>" not in stream_result
  65. assert "</scratchpad>" not in stream_result
  66. assert "Oatmeal" in stream_result
  67. print("Pass!")