markdown_parser.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. """Markdown parser.
  2. Contains parser for md files.
  3. """
  4. import re
  5. from pathlib import Path
  6. from typing import Any, Dict, List, Optional, Tuple, Union, cast
  7. from llama_index.readers.file.base_parser import BaseParser
  8. class MarkdownParser(BaseParser):
  9. """Markdown parser.
  10. Extract text from markdown files.
  11. Returns dictionary with keys as headers and values as the text between headers.
  12. """
  13. def __init__(
  14. self,
  15. *args: Any,
  16. remove_hyperlinks: bool = True,
  17. remove_images: bool = True,
  18. **kwargs: Any,
  19. ) -> None:
  20. """Init params."""
  21. super().__init__(*args, **kwargs)
  22. self._remove_hyperlinks = remove_hyperlinks
  23. self._remove_images = remove_images
  24. def markdown_to_tups(self, markdown_text: str) -> List[Tuple[Optional[str], str]]:
  25. """Convert a markdown file to a dictionary.
  26. The keys are the headers and the values are the text under each header.
  27. """
  28. markdown_tups: List[Tuple[Optional[str], str]] = []
  29. lines = markdown_text.split("\n")
  30. current_header = None
  31. current_text = ""
  32. for line in lines:
  33. header_match = re.match(r"^#+\s", line)
  34. if header_match:
  35. if current_header is not None:
  36. markdown_tups.append((current_header, current_text))
  37. current_header = line
  38. current_text = ""
  39. else:
  40. current_text += line + "\n"
  41. markdown_tups.append((current_header, current_text))
  42. if current_header is not None:
  43. # pass linting, assert keys are defined
  44. markdown_tups = [
  45. (re.sub(r"#", "", cast(str, key)).strip(), re.sub(r"<.*?>", "", value))
  46. for key, value in markdown_tups
  47. ]
  48. else:
  49. markdown_tups = [
  50. (key, re.sub("\n", "", value)) for key, value in markdown_tups
  51. ]
  52. return markdown_tups
  53. def remove_images(self, content: str) -> str:
  54. """Get a dictionary of a markdown file from its path."""
  55. pattern = r"!{1}\[\[(.*)\]\]"
  56. content = re.sub(pattern, "", content)
  57. return content
  58. def remove_hyperlinks(self, content: str) -> str:
  59. """Get a dictionary of a markdown file from its path."""
  60. pattern = r"\[(.*?)\]\((.*?)\)"
  61. content = re.sub(pattern, r"\1", content)
  62. return content
  63. def _init_parser(self) -> Dict:
  64. """Initialize the parser with the config."""
  65. return {}
  66. def parse_tups(
  67. self, filepath: Path, errors: str = "ignore"
  68. ) -> List[Tuple[Optional[str], str]]:
  69. """Parse file into tuples."""
  70. with open(filepath, "r", encoding="utf-8") as f:
  71. content = f.read()
  72. if self._remove_hyperlinks:
  73. content = self.remove_hyperlinks(content)
  74. if self._remove_images:
  75. content = self.remove_images(content)
  76. markdown_tups = self.markdown_to_tups(content)
  77. return markdown_tups
  78. def parse_file(
  79. self, filepath: Path, errors: str = "ignore"
  80. ) -> Union[str, List[str]]:
  81. """Parse file into string."""
  82. tups = self.parse_tups(filepath, errors=errors)
  83. results = []
  84. # TODO: don't include headers right now
  85. for header, value in tups:
  86. if header is None:
  87. results.append(value)
  88. else:
  89. results.append(f"\n\n{header}\n{value}")
  90. return results