Source code for langchain_community.document_loaders.parsers.language.language_parser
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Dict, Iterator, Optional
from langchain_core.documents import Document
from langchain_community.document_loaders.base import BaseBlobParser
from langchain_community.document_loaders.blob_loaders import Blob
from langchain_community.document_loaders.parsers.language.cobol import CobolSegmenter
from langchain_community.document_loaders.parsers.language.javascript import (
    JavaScriptSegmenter,
)
from langchain_community.document_loaders.parsers.language.python import PythonSegmenter
if TYPE_CHECKING:
    from langchain.text_splitter import Language
try:
    from langchain.text_splitter import Language
    LANGUAGE_EXTENSIONS: Dict[str, str] = {
        "py": Language.PYTHON,
        "js": Language.JS,
        "cobol": Language.COBOL,
    }
    LANGUAGE_SEGMENTERS: Dict[str, Any] = {
        Language.PYTHON: PythonSegmenter,
        Language.JS: JavaScriptSegmenter,
        Language.COBOL: CobolSegmenter,
    }
except ImportError:
    LANGUAGE_EXTENSIONS = {}
    LANGUAGE_SEGMENTERS = {}
[docs]class LanguageParser(BaseBlobParser):
    """Parse using the respective programming language syntax.
    Each top-level function and class in the code is loaded into separate documents.
    Furthermore, an extra document is generated, containing the remaining top-level code
    that excludes the already segmented functions and classes.
    This approach can potentially improve the accuracy of QA models over source code.
    Currently, the supported languages for code parsing are Python and JavaScript.
    The language used for parsing can be configured, along with the minimum number of
    lines required to activate the splitting based on syntax.
    Examples: