id stringlengths 14 15 | text stringlengths 44 2.47k | source stringlengths 61 181 |
|---|---|---|
5e9227db1f74-0 | Source code for langchain.document_loaders.mediawikidump
import logging
from pathlib import Path
from typing import List, Optional, Sequence, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
logger = logging.getLogger(__name__)
[docs]class MWDumpLoader(BaseLo... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mediawikidump.html |
5e9227db1f74-1 | """
[docs] def __init__(
self,
file_path: Union[str, Path],
encoding: Optional[str] = "utf8",
namespaces: Optional[Sequence[int]] = None,
skip_redirects: Optional[bool] = False,
stop_on_error: Optional[bool] = True,
):
self.file_path = file_path if isinstan... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mediawikidump.html |
5e9227db1f74-2 | except Exception as e:
logger.error("Parsing error: {}".format(e))
if self.stop_on_error:
raise e
else:
continue
return docs | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mediawikidump.html |
b3d242302893-0 | Source code for langchain.document_loaders.imsdb
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.web_base import WebBaseLoader
[docs]class IMSDbLoader(WebBaseLoader):
"""Load `IMSDb` webpages."""
[docs] def load(self) -> List[Document]:
"""Load web... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/imsdb.html |
1a821b172f91-0 | Source code for langchain.document_loaders.notebook
"""Loads .ipynb notebook files."""
import json
from pathlib import Path
from typing import Any, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]def concatenate_cells(
cell: dict, include_outputs: b... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html |
1a821b172f91-1 | output = output[0]["text"]
min_output = min(max_output_length, len(output))
return (
f"'{cell_type}' cell: '{source}'\n with "
f"output: '{output[:min_output]}'\n\n"
)
else:
return f"'{cell_type}' cell: '{source}'\n\n"
return ""
[docs]d... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html |
1a821b172f91-2 | Defaults to False.
"""
self.file_path = path
self.include_outputs = include_outputs
self.max_output_length = max_output_length
self.remove_newline = remove_newline
self.traceback = traceback
[docs] def load(
self,
) -> List[Document]:
"""Load docume... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html |
61919a8078c3-0 | Source code for langchain.document_loaders.web_base
"""Web base loader class."""
import asyncio
import logging
import warnings
from typing import Any, Dict, Iterator, List, Optional, Sequence, Union
import aiohttp
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base impo... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
61919a8078c3-1 | verify_ssl: bool = True,
proxies: Optional[dict] = None,
continue_on_failure: bool = False,
autoset_encoding: bool = True,
encoding: Optional[str] = None,
web_paths: Sequence[str] = (),
requests_per_second: int = 2,
default_parser: str = "html.parser",
req... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
61919a8078c3-2 | f" web_paths must be Sequence[str] got ({type(web_paths)})"
)
self.requests_per_second = requests_per_second
self.default_parser = default_parser
self.requests_kwargs = requests_kwargs or {}
self.raise_for_status = raise_for_status
self.bs_get_text_kwargs = bs_get_tex... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
61919a8078c3-3 | async with session.get(
url,
headers=self.session.headers,
ssl=None if self.session.verify else False,
) as response:
return await response.text()
except aiohttp.ClientConnectionError as e... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
61919a8078c3-4 | )
except ImportError:
warnings.warn("For better logging of progress, `pip install tqdm`")
return await asyncio.gather(*tasks)
@staticmethod
def _check_parser(parser: str) -> None:
"""Check that parser is valid for bs4."""
valid_parsers = ["html.parser", "lxml", "x... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
61919a8078c3-5 | if self.raise_for_status:
html_doc.raise_for_status()
if self.encoding is not None:
html_doc.encoding = self.encoding
elif self.autoset_encoding:
html_doc.encoding = html_doc.apparent_encoding
return BeautifulSoup(html_doc.text, parser, **(bs_kwargs or {}))
[d... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/web_base.html |
97bbf8345b16-0 | Source code for langchain.document_loaders.text
import logging
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.helpers import detect_file_encodings
logger = logging.getLogger(__name__)
[docs]class T... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/text.html |
97bbf8345b16-1 | except Exception as e:
raise RuntimeError(f"Error loading {self.file_path}") from e
metadata = {"source": self.file_path}
return [Document(page_content=text, metadata=metadata)] | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/text.html |
5f5ef7a6ee0d-0 | Source code for langchain.document_loaders.wikipedia
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utilities.wikipedia import WikipediaAPIWrapper
[docs]class WikipediaLoader(BaseLoader):
"""Load from `Wikipedi... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/wikipedia.html |
5f5ef7a6ee0d-1 | Loads the query result from Wikipedia into a list of Documents.
Returns:
List[Document]: A list of Document objects representing the loaded
Wikipedia pages.
"""
client = WikipediaAPIWrapper(
lang=self.lang,
top_k_results=self.load_max_docs,
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/wikipedia.html |
9fee4b183c50-0 | Source code for langchain.document_loaders.powerpoint
import os
from typing import List
from langchain.document_loaders.unstructured import UnstructuredFileLoader
[docs]class UnstructuredPowerPointLoader(UnstructuredFileLoader):
"""Load `Microsoft PowerPoint` files using `Unstructured`.
Works with both .ppt and... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html |
9fee4b183c50-1 | try:
import magic # noqa: F401
is_ppt = detect_filetype(self.file_path) == FileType.PPT
except ImportError:
_, extension = os.path.splitext(str(self.file_path))
is_ppt = extension == ".ppt"
if is_ppt and unstructured_version < (0, 4, 11):
rais... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html |
976b6aaac5f0-0 | Source code for langchain.document_loaders.assemblyai
from __future__ import annotations
from enum import Enum
from typing import TYPE_CHECKING, List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
if TYPE_CHECKING:
import assemblyai
[docs]class Tran... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/assemblyai.html |
976b6aaac5f0-1 | config: Optional[assemblyai.TranscriptionConfig] = None,
api_key: Optional[str] = None,
):
"""
Initializes the AssemblyAI AudioTranscriptLoader.
Args:
file_path: An URL or a local file path.
transcript_format: Transcript format to use.
See clas... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/assemblyai.html |
976b6aaac5f0-2 | sentences = transcript.get_sentences()
return [
Document(page_content=s.text, metadata=s.dict(exclude={"text"}))
for s in sentences
]
elif self.transcript_format == TranscriptFormat.PARAGRAPHS:
paragraphs = transcript.get_paragraphs()
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/assemblyai.html |
2d496ad6c051-0 | Source code for langchain.document_loaders.acreom
import re
from pathlib import Path
from typing import Iterator, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class AcreomLoader(BaseLoader):
"""Load `acreom` vault from a directory."""
FRONT_M... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/acreom.html |
2d496ad6c051-1 | if not self.collect_metadata:
return content
return self.FRONT_MATTER_REGEX.sub("", content)
def _process_acreom_content(self, content: str) -> str:
# remove acreom specific elements from content that
# do not contribute to the context of current document
content = re.sub... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/acreom.html |
16497252c868-0 | Source code for langchain.document_loaders.hugging_face_dataset
from typing import Iterator, List, Mapping, Optional, Sequence, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class HuggingFaceDatasetLoader(BaseLoader):
"""Load from `Hugging Face H... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html |
16497252c868-1 | save_infos: Save the dataset information (checksums/size/splits/...).
Default is False.
use_auth_token: Bearer token for remote files on the Dataset Hub.
num_proc: Number of processes.
"""
self.path = path
self.page_content_column = page_content_column
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html |
41a1135a6acb-0 | Source code for langchain.document_loaders.duckdb_loader
from typing import Dict, List, Optional, cast
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class DuckDBLoader(BaseLoader):
"""Load from `DuckDB`.
Each document represents one row of the resu... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/duckdb_loader.html |
41a1135a6acb-1 | [docs] def load(self) -> List[Document]:
try:
import duckdb
except ImportError:
raise ImportError(
"Could not import duckdb python package. "
"Please install it with `pip install duckdb`."
)
docs = []
with duckdb.conn... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/duckdb_loader.html |
ab0e3a8b84ea-0 | Source code for langchain.document_loaders.browserless
from typing import Iterator, List, Union
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class BrowserlessLoader(BaseLoader):
"""Load webpages with `Browserless` /content endpoint."""... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/browserless.html |
ab0e3a8b84ea-1 | metadata={
"source": url,
},
)
[docs] def load(self) -> List[Document]:
"""Load Documents from URLs."""
return list(self.lazy_load()) | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/browserless.html |
fa8c8756a37b-0 | Source code for langchain.document_loaders.trello
from __future__ import annotations
from typing import TYPE_CHECKING, Any, List, Literal, Optional, Tuple
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utils import get_from_env
if TYPE_CHECKING:
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/trello.html |
fa8c8756a37b-1 | self.include_card_name = include_card_name
self.include_comments = include_comments
self.include_checklist = include_checklist
self.extra_metadata = extra_metadata
self.card_filter = card_filter
[docs] @classmethod
def from_credentials(
cls,
board_name: str,
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/trello.html |
fa8c8756a37b-2 | token = token or get_from_env("token", "TRELLO_TOKEN")
client = TrelloClient(api_key=api_key, token=token)
return cls(client, board_name, **kwargs)
[docs] def load(self) -> List[Document]:
"""Loads all cards from the specified Trello board.
You can filter the cards, metadata and text ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/trello.html |
fa8c8756a37b-3 | if self.include_card_name:
text_content = card.name + "\n"
if card.description.strip():
text_content += BeautifulSoup(card.description, "lxml").get_text()
if self.include_checklist:
# Get all the checklist items on the card
for checklist in card.checklists... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/trello.html |
f1faf3665b62-0 | Source code for langchain.document_loaders.parsers.pdf
"""Module contains common parsers for PDFs."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Iterator, Mapping, Optional, Sequence, Union
from urllib.parse import urlparse
from langchain.document_loaders.base import BaseBlobParser
from l... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
f1faf3665b62-1 | [docs]class PyMuPDFParser(BaseBlobParser):
"""Parse `PDF` using `PyMuPDF`."""
[docs] def __init__(self, text_kwargs: Optional[Mapping[str, Any]] = None) -> None:
"""Initialize the parser.
Args:
text_kwargs: Keyword arguments to pass to ``fitz.Page.get_text()``.
"""
sel... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
f1faf3665b62-2 | " `pip install pypdfium2`"
)
[docs] def lazy_parse(self, blob: Blob) -> Iterator[Document]:
"""Lazily parse the blob."""
import pypdfium2
# pypdfium2 is really finicky with respect to closing things,
# if done incorrectly creates seg faults.
with blob.as_bytes_io()... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
f1faf3665b62-3 | doc = pdfplumber.open(file_path) # open document
yield from [
Document(
page_content=self._process_page_content(page),
metadata=dict(
{
"source": blob.source,
"file_path":... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
f1faf3665b62-4 | self.tc = tc
if textract_features is not None:
self.textract_features = [
tc.Textract_Features(f) for f in textract_features
]
else:
self.textract_features = []
except ImportError:
raise ImportError(
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
f1faf3665b62-5 | )
else:
textract_response_json = self.tc.call_textract(
input_document=blob.as_bytes(),
features=self.textract_features,
call_mode=self.tc.Textract_Call_Mode.FORCE_SYNC,
boto3_textract_client=self.boto3_textract_client,
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
f1faf3665b62-6 | """Lazily parse the blob."""
with blob.as_bytes_io() as file_obj:
poller = self.client.begin_analyze_document(self.model, file_obj)
result = poller.result()
docs = self._generate_docs(blob, result)
yield from docs | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
b9f4bb3a3670-0 | Source code for langchain.document_loaders.parsers.registry
"""Module includes a registry of default parser configurations."""
from langchain.document_loaders.base import BaseBlobParser
from langchain.document_loaders.parsers.generic import MimeTypeBasedParser
from langchain.document_loaders.parsers.msword import MsWor... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/registry.html |
137bbb06a147-0 | Source code for langchain.document_loaders.parsers.audio
import logging
import time
from typing import Dict, Iterator, Optional, Tuple
from langchain.document_loaders.base import BaseBlobParser
from langchain.document_loaders.blob_loaders import Blob
from langchain.schema import Document
logger = logging.getLogger(__na... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html |
137bbb06a147-1 | # Audio chunk
chunk = audio[i : i + chunk_duration_ms]
file_obj = io.BytesIO(chunk.export(format="mp3").read())
if blob.source is not None:
file_obj.name = blob.source + f"_part_{split_number}.mp3"
else:
file_obj.name = f"part_{split_number... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html |
137bbb06a147-2 | forced_decoder_ids = WhisperProcessor.get_decoder_prompt_ids(language="french",
task="transcribe")
forced_decoder_ids = WhisperProcessor.get_decoder_prompt_ids(language="french",
task="translate")
"""
[docs] def __init__(
self,
device: str = "0",
lang_model: Opti... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html |
137bbb06a147-3 | # check GPU memory and select automatically the model
mem = torch.cuda.get_device_properties(self.device).total_memory / (
1024**2
)
if mem < 5000:
rec_model = "openai/whisper-base"
elif mem < 7000:
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html |
137bbb06a147-4 | from pydub import AudioSegment
except ImportError:
raise ImportError(
"pydub package not found, please install it with `pip install pydub`"
)
try:
import librosa
except ImportError:
raise ImportError(
"librosa packag... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html |
8b3d70943c57-0 | Source code for langchain.document_loaders.parsers.msword
from typing import Iterator
from langchain.document_loaders.base import BaseBlobParser
from langchain.document_loaders.blob_loaders import Blob
from langchain.schema import Document
[docs]class MsWordParser(BaseBlobParser):
[docs] def lazy_parse(self, blob: B... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/msword.html |
a637ec961ff4-0 | Source code for langchain.document_loaders.parsers.txt
"""Module for parsing text files.."""
from typing import Iterator
from langchain.document_loaders.base import BaseBlobParser
from langchain.document_loaders.blob_loaders import Blob
from langchain.schema import Document
[docs]class TextParser(BaseBlobParser):
"... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/txt.html |
3acc07287a73-0 | Source code for langchain.document_loaders.parsers.grobid
import logging
from typing import Dict, Iterator, List, Union
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseBlobParser
from langchain.document_loaders.blob_loaders import Blob
logger = logging.ge... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/grobid.html |
3acc07287a73-1 | chunks = []
for section in sections:
sect = section.find("head")
if sect is not None:
for i, paragraph in enumerate(section.find_all("p")):
chunk_bboxes = []
paragraph_text = []
for i, sentence in enumerate(parag... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/grobid.html |
3acc07287a73-2 | "pages": (fpage, lpage),
}
chunks.append(paragraph_dict)
yield from [
Document(
page_content=chunk["text"],
metadata=dict(
{
"text": str(chunk["text"]),
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/grobid.html |
3acc07287a73-3 | xml_data = None
if xml_data is None:
return iter([])
else:
return self.process_xml(file_path, xml_data, self.segment_sentences) | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/grobid.html |
ad08fb0aba3c-0 | Source code for langchain.document_loaders.parsers.generic
"""Code for generic / auxiliary parsers.
This module contains some logic to help assemble more sophisticated parsers.
"""
from typing import Iterator, Mapping, Optional
from langchain.document_loaders.base import BaseBlobParser
from langchain.document_loaders.b... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/generic.html |
ad08fb0aba3c-1 | """
self.handlers = handlers
self.fallback_parser = fallback_parser
[docs] def lazy_parse(self, blob: Blob) -> Iterator[Document]:
"""Load documents from a blob."""
mimetype = blob.mimetype
if mimetype is None:
raise ValueError(f"{blob} does not have a mimetype.")
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/generic.html |
dcb5b41e36e7-0 | Source code for langchain.document_loaders.parsers.docai
"""Module contains a PDF parser based on DocAI from Google Cloud.
You need to install two libraries to use this parser:
pip install google-cloud-documentai
pip install google-cloud-documentai-toolbox
"""
import logging
import time
from dataclasses import dataclas... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html |
dcb5b41e36e7-1 | "You should provide either a client or a location but not both "
"of them."
)
if not client and not location:
raise ValueError(
"You must specify either a client or a location to instantiate "
"a client."
)
self._gcs_out... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html |
dcb5b41e36e7-2 | Args:
blobs: a list of blobs to parse
gcs_output_path: a path on GCS to store parsing results
timeout_sec: a timeout to wait for DocAI to complete, in seconds
check_in_interval_sec: an interval to wait until next check
whether parsing operations have been ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html |
dcb5b41e36e7-3 | )
logger.debug(".")
results = self.get_results(operations=operations)
yield from self.parse_from_results(results)
[docs] def parse_from_results(
self, results: List[DocAIParsingResults]
) -> Iterator[Document]:
try:
from google.cloud.documentai_toolbox.wrap... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html |
dcb5b41e36e7-4 | " `pip install gapic-google-longrunning`"
)
operations = []
for name in operation_names:
request = GetOperationRequest(name=name)
operations.append(self._client.get_operation(request=request))
return operations
[docs] def is_running(self, operations: List["... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html |
dcb5b41e36e7-5 | raise ValueError("Processor name is not defined, aborting!")
output_path = gcs_output_path if gcs_output_path else self._gcs_output_path
if output_path is None:
raise ValueError("An output path on GCS should be provided!")
operations = []
for batch in batch_iterate(size=batch... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html |
dcb5b41e36e7-6 | except ImportError:
raise ImportError(
"documentai package not found, please install it with"
" `pip install google-cloud-documentai`"
)
results = []
for op in operations:
if isinstance(op.metadata, BatchProcessMetadata):
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/docai.html |
8a5cca43d64c-0 | Source code for langchain.document_loaders.parsers.language.code_segmenter
from abc import ABC, abstractmethod
from typing import List
[docs]class CodeSegmenter(ABC):
"""Abstract class for the code segmenter."""
[docs] def __init__(self, code: str):
self.code = code
[docs] def is_valid(self) -> bool:
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/code_segmenter.html |
2ee25cba7b9c-0 | Source code for langchain.document_loaders.parsers.language.language_parser
from typing import Any, Dict, Iterator, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseBlobParser
from langchain.document_loaders.blob_loaders import Blob
from langchain.document_loader... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/language_parser.html |
2ee25cba7b9c-1 | Example instantiations to manually select the language:
.. code-block:: python
from langchain.text_splitter import Language
loader = GenericLoader.from_filesystem(
"./code",
glob="**/*",
suffixes=[".py"],
parser=LanguagePars... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/language_parser.html |
2ee25cba7b9c-2 | "language": language,
},
)
return
self.Segmenter = LANGUAGE_SEGMENTERS[language]
segmenter = self.Segmenter(blob.as_string())
if not segmenter.is_valid():
yield Document(
page_content=code,
metadata={
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/language_parser.html |
c79bdd12d8dd-0 | Source code for langchain.document_loaders.parsers.language.python
import ast
from typing import Any, List
from langchain.document_loaders.parsers.language.code_segmenter import CodeSegmenter
[docs]class PythonSegmenter(CodeSegmenter):
"""Code segmenter for `Python`."""
[docs] def __init__(self, code: str):
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/python.html |
c79bdd12d8dd-1 | simplified_lines[line_num] = None # type: ignore
return "\n".join(line for line in simplified_lines if line is not None) | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/python.html |
5459b375101d-0 | Source code for langchain.document_loaders.parsers.language.javascript
from typing import Any, List
from langchain.document_loaders.parsers.language.code_segmenter import CodeSegmenter
[docs]class JavaScriptSegmenter(CodeSegmenter):
"""Code segmenter for JavaScript."""
[docs] def __init__(self, code: str):
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/javascript.html |
5459b375101d-1 | for node in tree.body:
if isinstance(
node,
(esprima.nodes.FunctionDeclaration, esprima.nodes.ClassDeclaration),
):
start = node.loc.start.line - 1
simplified_lines[start] = f"// Code for: {simplified_lines[start]}"
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/javascript.html |
e3fe7c059402-0 | Source code for langchain.document_loaders.parsers.html.bs4
"""Loader that uses bs4 to load HTML files, enriching metadata with page title."""
import logging
from typing import Any, Dict, Iterator, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseBlobParser
from lan... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/html/bs4.html |
732d15c59dc4-0 | Source code for langchain.document_loaders.blob_loaders.file_system
"""Use to load blobs from the local file system."""
from pathlib import Path
from typing import Callable, Iterable, Iterator, Optional, Sequence, TypeVar, Union
from langchain.document_loaders.blob_loaders.schema import Blob, BlobLoader
T = TypeVar("T"... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html |
732d15c59dc4-1 | *,
glob: str = "**/[!.]*",
exclude: Sequence[str] = (),
suffixes: Optional[Sequence[str]] = None,
show_progress: bool = False,
) -> None:
"""Initialize with a path to directory and how to glob over it.
Args:
path: Path to directory to load from
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html |
732d15c59dc4-2 | elif isinstance(path, str):
_path = Path(path)
else:
raise TypeError(f"Expected str or Path, got {type(path)}")
self.path = _path.expanduser() # Expand user to handle ~
self.glob = glob
self.suffixes = set(suffixes or [])
self.show_progress = show_progres... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html |
59d6cb26dd27-0 | Source code for langchain.document_loaders.blob_loaders.schema
"""Schema for Blobs and Blob Loaders.
The goal is to facilitate decoupling of content loading from content parsing code.
In addition, content loading code should provide a lazy loading interface by default.
"""
from __future__ import annotations
import cont... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html |
59d6cb26dd27-1 | return str(self.path) if self.path else None
@root_validator(pre=True)
def check_blob_is_valid(cls, values: Mapping[str, Any]) -> Mapping[str, Any]:
"""Verify that either data or path is provided."""
if "data" not in values and "path" not in values:
raise ValueError("Either data or p... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html |
59d6cb26dd27-2 | yield f
else:
raise NotImplementedError(f"Unable to convert blob {self}")
[docs] @classmethod
def from_path(
cls,
path: PathLike,
*,
encoding: str = "utf-8",
mime_type: Optional[str] = None,
guess_type: bool = True,
) -> Blob:
"""Loa... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html |
59d6cb26dd27-3 | mime_type: if provided, will be set as the mime-type of the data
path: if provided, will be set as the source from which the data came
Returns:
Blob instance
"""
return cls(data=data, mimetype=mime_type, encoding=encoding, path=path)
def __repr__(self) -> str:
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html |
72d1bb8e609a-0 | Source code for langchain.document_loaders.blob_loaders.youtube_audio
from typing import Iterable, List
from langchain.document_loaders.blob_loaders import FileSystemBlobLoader
from langchain.document_loaders.blob_loaders.schema import Blob, BlobLoader
[docs]class YoutubeAudioLoader(BlobLoader):
"""Load YouTube url... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/youtube_audio.html |
b8058e01c197-0 | Source code for langchain.smith.evaluation.string_run_evaluator
"""Run evaluator wrapper for string evaluators."""
from __future__ import annotations
from abc import abstractmethod
from typing import Any, Dict, List, Optional
from langsmith import EvaluationResult, RunEvaluator
from langsmith.schemas import DataType, E... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
b8058e01c197-1 | return self.map(run)
[docs]class LLMStringRunMapper(StringRunMapper):
"""Extract items to evaluate from the run object."""
[docs] def serialize_chat_messages(self, messages: List[Dict]) -> str:
"""Extract the input messages from the run."""
if isinstance(messages, list) and messages:
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
b8058e01c197-2 | first_generation: Dict = generations[0]
if isinstance(first_generation, list):
# Runs from Tracer have generations as a list of lists of dicts
# Whereas Runs from the API have a list of dicts
first_generation = first_generation[0]
if "message" in first_generation:
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
b8058e01c197-3 | """The key from the model Run's inputs to use as the eval input.
If not provided, will use the only input key or raise an
error if there are multiple."""
prediction_key: Optional[str] = None
"""The key from the model Run's outputs to use as the eval prediction.
If not provided, will use the only out... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
b8058e01c197-4 | available_keys = ", ".join(run.outputs.keys())
raise ValueError(
f"Run with ID {run.id} doesn't have the expected prediction key"
f" '{self.prediction_key}'. Available prediction keys in this Run are:"
f" {available_keys}. Adjust the evaluator's prediction_key... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
b8058e01c197-5 | """Maps the Example, or dataset row to a dictionary."""
if not example.outputs:
raise ValueError(
f"Example {example.id} has no outputs to use as a reference."
)
if self.reference_key is None:
if len(example.outputs) > 1:
raise ValueErr... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
b8058e01c197-6 | """The name of the evaluation metric."""
string_evaluator: StringEvaluator
"""The evaluation chain."""
@property
def input_keys(self) -> List[str]:
return ["run", "example"]
@property
def output_keys(self) -> List[str]:
return ["feedback"]
def _prepare_input(self, inputs: Dic... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
b8058e01c197-7 | """Call the evaluation chain."""
evaluate_strings_inputs = self._prepare_input(inputs)
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
callbacks = _run_manager.get_child()
chain_output = self.string_evaluator.evaluate_strings(
**evaluate_strings_in... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
b8058e01c197-8 | return EvaluationResult(
key=self.string_evaluator.evaluation_name,
comment=f"Error evaluating run {run.id}: {e}",
# TODO: Add run ID once we can declare it via callbacks
)
[docs] async def aevaluate_run(
self, run: Run, example: Optional[Example] =... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
b8058e01c197-9 | data_type (DataType): The type of dataset used in the run.
input_key (str, optional): The key used to map the input from the run.
prediction_key (str, optional): The key used to map the prediction from the run.
reference_key (str, optional): The key used to map the reference from the... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
b8058e01c197-10 | )
else:
example_mapper = None
return cls(
name=evaluator.evaluation_name,
run_mapper=run_mapper,
example_mapper=example_mapper,
string_evaluator=evaluator,
tags=tags,
) | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/string_run_evaluator.html |
8b66c083e60d-0 | Source code for langchain.smith.evaluation.name_generation
import random
adjectives = [
"abandoned",
"aching",
"advanced",
"ample",
"artistic",
"back",
"best",
"bold",
"brief",
"clear",
"cold",
"complicated",
"cooked",
"crazy",
"crushing",
"damp",
"dea... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html |
8b66c083e60d-1 | "sunny",
"tart",
"terrific",
"timely",
"unique",
"upbeat",
"vacant",
"virtual",
"warm",
"weary",
"whispered",
"worthwhile",
"yellow",
]
nouns = [
"account",
"acknowledgment",
"address",
"advertising",
"airplane",
"animal",
"appointment",
"a... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html |
8b66c083e60d-2 | "cheek",
"cheese",
"chef",
"cherry",
"chicken",
"child",
"church",
"circle",
"class",
"clay",
"click",
"clock",
"cloth",
"cloud",
"clove",
"club",
"coach",
"coal",
"coast",
"coat",
"cod",
"coffee",
"collar",
"color",
"comb",... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html |
8b66c083e60d-3 | "discussion",
"disease",
"disgust",
"distance",
"distribution",
"division",
"doctor",
"dog",
"door",
"drain",
"drawer",
"dress",
"drink",
"driving",
"dust",
"ear",
"earth",
"edge",
"education",
"effect",
"egg",
"end",
"energy",
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html |
8b66c083e60d-4 | "group",
"growth",
"guide",
"guitar",
"hair",
"hall",
"hand",
"harbor",
"harmony",
"hat",
"head",
"health",
"heart",
"heat",
"hill",
"history",
"hobbies",
"hole",
"hope",
"horn",
"horse",
"hospital",
"hour",
"house",
"humor"... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html |
8b66c083e60d-5 | "list",
"look",
"loss",
"love",
"lunch",
"machine",
"man",
"manager",
"map",
"marble",
"mark",
"market",
"mass",
"match",
"meal",
"measure",
"meat",
"meeting",
"memory",
"metal",
"middle",
"milk",
"mind",
"mine",
"minute",
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html |
8b66c083e60d-6 | "pear",
"pen",
"pencil",
"person",
"pest",
"pet",
"picture",
"pie",
"pin",
"pipe",
"pizza",
"place",
"plane",
"plant",
"plastic",
"plate",
"play",
"pleasure",
"plot",
"plough",
"pocket",
"point",
"poison",
"police",
"polluti... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html |
8b66c083e60d-7 | "rice",
"river",
"road",
"roll",
"room",
"root",
"rose",
"route",
"rub",
"rule",
"run",
"sack",
"sail",
"salt",
"sand",
"scale",
"scarecrow",
"scarf",
"scene",
"scent",
"school",
"science",
"scissors",
"screw",
"sea",
"s... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html |
8b66c083e60d-8 | "sound",
"soup",
"space",
"spark",
"speed",
"sponge",
"spoon",
"spray",
"spring",
"spy",
"square",
"stamp",
"star",
"start",
"statement",
"station",
"steam",
"steel",
"stem",
"step",
"stew",
"stick",
"stitch",
"stocking",
"s... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html |
8b66c083e60d-9 | "toad",
"toe",
"tooth",
"toothpaste",
"touch",
"town",
"toy",
"trade",
"train",
"transport",
"tray",
"treatment",
"tree",
"trick",
"trip",
"trouble",
"trousers",
"truck",
"tub",
"turkey",
"turn",
"twist",
"umbrella",
"uncle",
... | https://api.python.langchain.com/en/latest/_modules/langchain/smith/evaluation/name_generation.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.