clean_processor.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import re
  2. class CleanProcessor:
  3. @classmethod
  4. def clean(cls, text: str, process_rule: dict) -> str:
  5. # default clean
  6. # remove invalid symbol
  7. text = re.sub(r"<\|", "<", text)
  8. text = re.sub(r"\|>", ">", text)
  9. text = re.sub(r"[\x00-\x08\x0B\x0C\x0E-\x1F\x7F\xEF\xBF\xBE]", "", text)
  10. # Unicode U+FFFE
  11. text = re.sub("\ufffe", "", text)
  12. rules = process_rule["rules"] if process_rule else {}
  13. if "pre_processing_rules" in rules:
  14. pre_processing_rules = rules["pre_processing_rules"]
  15. for pre_processing_rule in pre_processing_rules:
  16. if pre_processing_rule["id"] == "remove_extra_spaces" and pre_processing_rule["enabled"] is True:
  17. # Remove extra spaces
  18. pattern = r"\n{3,}"
  19. text = re.sub(pattern, "\n\n", text)
  20. pattern = r"[\t\f\r\x20\u00a0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000]{2,}"
  21. text = re.sub(pattern, " ", text)
  22. elif pre_processing_rule["id"] == "remove_urls_emails" and pre_processing_rule["enabled"] is True:
  23. # Remove email
  24. pattern = r"([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)"
  25. text = re.sub(pattern, "", text)
  26. # Remove URL but keep Markdown image URLs
  27. # First, temporarily replace Markdown image URLs with a placeholder
  28. markdown_image_pattern = r"!\[.*?\]\((https?://[^\s)]+)\)"
  29. placeholders: list[str] = []
  30. def replace_with_placeholder(match, placeholders=placeholders):
  31. url = match.group(1)
  32. placeholder = f"__MARKDOWN_IMAGE_URL_{len(placeholders)}__"
  33. placeholders.append(url)
  34. return f"![image]({placeholder})"
  35. text = re.sub(markdown_image_pattern, replace_with_placeholder, text)
  36. # Now remove all remaining URLs
  37. url_pattern = r"https?://[^\s)]+"
  38. text = re.sub(url_pattern, "", text)
  39. # Finally, restore the Markdown image URLs
  40. for i, url in enumerate(placeholders):
  41. text = text.replace(f"__MARKDOWN_IMAGE_URL_{i}__", url)
  42. return text
  43. def filter_string(self, text):
  44. return text