id stringlengths 14 15 | text stringlengths 49 2.47k | source stringlengths 61 166 |
|---|---|---|
365a40336446-0 | Source code for langchain.document_loaders.googledrive
"""Loads data from Google Drive."""
# Prerequisites:
# 1. Create a Google Cloud project
# 2. Enable the Google Drive API:
# https://console.cloud.google.com/flows/enableapi?apiid=drive.googleapis.com
# 3. Authorize credentials for desktop app:
# https://develop... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
365a40336446-1 | """Whether to load recursively. Only applies when folder_id is given."""
file_types: Optional[Sequence[str]] = None
"""The file types to load. Only applies when folder_id is given."""
load_trashed_files: bool = False
"""Whether to load trashed files. Only applies when folder_id is given."""
# NOTE(M... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
365a40336446-2 | type_mapping = {
"document": "application/vnd.google-apps.document",
"sheet": "application/vnd.google-apps.spreadsheet",
"pdf": "application/pdf",
}
allowed_types = list(type_mapping.keys()) + list(type_mapping.values())
short_names = "... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
365a40336446-3 | from google_auth_oauthlib.flow import InstalledAppFlow
except ImportError:
raise ImportError(
"You must run "
"`pip install --upgrade "
"google-api-python-client google-auth-httplib2 "
"google-auth-oauthlib` "
"to use th... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
365a40336446-4 | sheets = spreadsheet.get("sheets", [])
documents = []
for sheet in sheets:
sheet_name = sheet["properties"]["title"]
result = (
sheets_service.spreadsheets()
.values()
.get(spreadsheetId=id, range=sheet_name)
.execut... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
365a40336446-5 | fh = BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
try:
while done is False:
status, done = downloader.next_chunk()
except HttpError as e:
if e.resp.status == 404:
print("File not found: {}".format(id))
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
365a40336446-6 | elif file["mimeType"] == "application/vnd.google-apps.spreadsheet":
returns.extend(self._load_sheet_from_id(file["id"])) # type: ignore
elif (
file["mimeType"] == "application/pdf"
or self.file_loader_cls is not None
):
returns.ext... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
365a40336446-7 | """Load a file from an ID."""
from io import BytesIO
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
creds = self._load_credentials()
service = build("drive", "v3", credentials=creds)
file = service.files().get(fileId=id, s... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
365a40336446-8 | docs.extend(self._load_file_from_id(file_id))
return docs
[docs] def load(self) -> List[Document]:
"""Load documents."""
if self.folder_id:
return self._load_documents_from_folder(
self.folder_id, file_types=self.file_types
)
elif self.document_... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/googledrive.html |
16bd9e50cd74-0 | Source code for langchain.document_loaders.blockchain
import os
import re
import time
from enum import Enum
from typing import List, Optional
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class BlockchainType(Enum):
"""Enumerator of the... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html |
16bd9e50cd74-1 | """
[docs] def __init__(
self,
contract_address: str,
blockchainType: BlockchainType = BlockchainType.ETH_MAINNET,
api_key: str = "docs-demo",
startToken: str = "",
get_all_tokens: bool = False,
max_execution_time: Optional[int] = None,
):
"""
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html |
16bd9e50cd74-2 | f"&startToken={current_start_token}"
)
response = requests.get(url)
if response.status_code != 200:
raise ValueError(
f"Request failed with status code {response.status_code}"
)
items = response.json()["nfts"]
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html |
16bd9e50cd74-3 | else:
value_int = int(tokenId)
result = value_int + 1
if value_type == "hex_0x":
return "0x" + format(result, "0" + str(len(tokenId) - 2) + "x")
elif value_type == "hex_0xbf":
return "0xbf" + format(result, "0" + str(len(tokenId) - 4) + "x")
else:
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html |
9bfa200fb9ad-0 | Source code for langchain.document_loaders.news
"""Loader that uses unstructured to load HTML files."""
import logging
from typing import Any, Iterator, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
logger = logging.getLogger(__name__)
[docs]class NewsURLLo... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/news.html |
9bfa200fb9ad-1 | ) -> None:
"""Initialize with file path."""
try:
import newspaper # noqa:F401
self.__version = newspaper.__version__
except ImportError:
raise ImportError(
"newspaper package not found, please install it with "
"`pip install ne... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/news.html |
9bfa200fb9ad-2 | continue
else:
raise e
metadata = {
"title": getattr(article, "title", ""),
"link": getattr(article, "url", getattr(article, "canonical_link", "")),
"authors": getattr(article, "authors", []),
"language": get... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/news.html |
eed5fef15e79-0 | Source code for langchain.document_loaders.pyspark_dataframe
"""Load from a Spark Dataframe object"""
import itertools
import logging
import sys
from typing import TYPE_CHECKING, Any, Iterator, List, Optional, Tuple
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pyspark_dataframe.html |
eed5fef15e79-1 | self.fraction_of_memory = fraction_of_memory
self.num_rows, self.max_num_rows = self.get_num_rows()
self.rdd_df = self.df.rdd.map(list)
self.column_names = self.df.columns
[docs] def get_num_rows(self) -> Tuple[int, int]:
"""Gets the number of "feasible" rows for the DataFrame"""
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pyspark_dataframe.html |
eed5fef15e79-2 | )
lazy_load_iterator = self.lazy_load()
return list(itertools.islice(lazy_load_iterator, self.num_rows)) | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pyspark_dataframe.html |
dc7acb147068-0 | Source code for langchain.document_loaders.rocksetdb
from typing import Any, Callable, Iterator, List, Optional, Tuple
from langchain.document_loaders.base import BaseLoader
from langchain.schema import Document
[docs]def default_joiner(docs: List[Tuple[str, Any]]) -> str:
"""Default joiner for content columns."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rocksetdb.html |
dc7acb147068-1 | ):
"""Initialize with Rockset client.
Args:
client: Rockset client object.
query: Rockset query object.
content_keys: The collection columns to be written into the `page_content`
of the Documents.
metadata_keys: The collection columns to be... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rocksetdb.html |
dc7acb147068-2 | self.paginator = QueryPaginator
self.request_model = QueryRequestSql
[docs] def load(self) -> List[Document]:
return list(self.lazy_load())
[docs] def lazy_load(self) -> Iterator[Document]:
query_results = self.client.Queries.query(
sql=self.query
).results # execute t... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rocksetdb.html |
95a4315057fb-0 | Source code for langchain.document_loaders.odt
"""Loads OpenOffice ODT files."""
from typing import Any, List
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
validate_unstructured_version,
)
[docs]class UnstructuredODTLoader(UnstructuredFileLoader):
"""Loader that uses unstruct... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/odt.html |
95a4315057fb-1 | """
validate_unstructured_version(min_unstructured_version="0.6.3")
super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
def _get_elements(self) -> List:
from unstructured.partition.odt import partition_odt
return partition_odt(filename=self.file_path, **self.unstr... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/odt.html |
4ed3dc34e3cf-0 | Source code for langchain.document_loaders.spreedly
"""Loader that fetches data from Spreedly API."""
import json
import urllib.request
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utils import stringify_dict
SPREEDLY_ENDP... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/spreedly.html |
4ed3dc34e3cf-1 | }
def _make_request(self, url: str) -> List[Document]:
request = urllib.request.Request(url, headers=self.headers)
with urllib.request.urlopen(request) as response:
json_data = json.loads(response.read().decode())
text = stringify_dict(json_data)
metadata = {"sour... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/spreedly.html |
b277cd8106f6-0 | Source code for langchain.document_loaders.concurrent
from __future__ import annotations
import concurrent.futures
from pathlib import Path
from typing import Iterator, Literal, Optional, Sequence, Union
from langchain.document_loaders.base import BaseBlobParser
from langchain.document_loaders.blob_loaders import BlobL... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/concurrent.html |
b277cd8106f6-1 | num_workers: int = 4,
) -> ConcurrentLoader:
"""
Create a concurrent generic document loader using a
filesystem blob loader.
"""
blob_loader = FileSystemBlobLoader(
path, glob=glob, suffixes=suffixes, show_progress=show_progress
)
if isinstance(par... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/concurrent.html |
6c551eeaf2ce-0 | Source code for langchain.document_loaders.html_bs
"""Loader that uses bs4 to load HTML files, enriching metadata with page title."""
import logging
from typing import Dict, List, Union
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
logger = logging.getLogger(__n... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/html_bs.html |
6c551eeaf2ce-1 | """Load HTML document into document objects."""
from bs4 import BeautifulSoup
with open(self.file_path, "r", encoding=self.open_encoding) as f:
soup = BeautifulSoup(f, **self.bs_kwargs)
text = soup.get_text(self.get_text_separator)
if soup.title:
title = str(soup.... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/html_bs.html |
4e2421f26a1a-0 | Source code for langchain.document_loaders.rst
"""Loads RST files."""
from typing import Any, List
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
validate_unstructured_version,
)
[docs]class UnstructuredRSTLoader(UnstructuredFileLoader):
"""Loader that uses unstructured to loa... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rst.html |
4e2421f26a1a-1 | """
validate_unstructured_version(min_unstructured_version="0.7.5")
super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs)
def _get_elements(self) -> List:
from unstructured.partition.rst import partition_rst
return partition_rst(filename=self.file_path, **self.unstr... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rst.html |
66075a72188d-0 | Source code for langchain.document_loaders.acreom
"""Loads acreom vault from a directory."""
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):
"""Loader th... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/acreom.html |
66075a72188d-1 | """Remove front matter metadata from the given content."""
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 con... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/acreom.html |
8a107bb6afcf-0 | Source code for langchain.document_loaders.word_document
"""Loads word documents."""
import os
import tempfile
from abc import ABC
from typing import List
from urllib.parse import urlparse
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langch... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html |
8a107bb6afcf-1 | if hasattr(self, "temp_file"):
self.temp_file.close()
[docs] def load(self) -> List[Document]:
"""Load given path as single page."""
import docx2txt
return [
Document(
page_content=docx2txt.process(self.file_path),
metadata={"source": se... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html |
8a107bb6afcf-2 | from unstructured.file_utils.filetype import FileType, detect_filetype
unstructured_version = tuple(
[int(x) for x in __unstructured_version__.split(".")]
)
# NOTE(MthwRobinson) - magic will raise an import error if the libmagic
# system dependency isn't installed. If it's no... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html |
97abf29fa7a0-0 | Source code for langchain.document_loaders.github
from abc import ABC
from datetime import datetime
from typing import Dict, Iterator, List, Literal, Optional, Union
import requests
from pydantic import BaseModel, root_validator, validator
from langchain.docstore.document import Document
from langchain.document_loaders... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/github.html |
97abf29fa7a0-1 | state: Optional[Literal["open", "closed", "all"]] = None
"""Filter on issue state. Can be one of: 'open', 'closed', 'all'."""
assignee: Optional[str] = None
"""Filter on assigned user. Pass 'none' for no user and '*' for any user."""
creator: Optional[str] = None
"""Filter on the user that created t... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/github.html |
97abf29fa7a0-2 | [docs] def lazy_load(self) -> Iterator[Document]:
"""
Get issues of a GitHub repository.
Returns:
A list of Documents with attributes:
- page_content
- metadata
- url
- title
- creator
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/github.html |
97abf29fa7a0-3 | """Create Document objects from a list of GitHub issues."""
metadata = {
"url": issue["html_url"],
"title": issue["title"],
"creator": issue["user"]["login"],
"created_at": issue["created_at"],
"comments": issue["comments"],
"state": issue[... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/github.html |
97abf29fa7a0-4 | return query_params
@property
def url(self) -> str:
"""Create URL for GitHub API."""
return f"https://api.github.com/repos/{self.repo}/issues?{self.query_params}" | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/github.html |
151c7d800637-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):
"""Loads the content of webpages using Browserless' /cont... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/browserless.html |
151c7d800637-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 |
c06ba5e8541c-0 | Source code for langchain.document_loaders.notion
"""Loads Notion directory dump."""
from pathlib import Path
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class NotionDirectoryLoader(BaseLoader):
"""Loads Notion directory dump.... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/notion.html |
58d9e6fc45bb-0 | Source code for langchain.document_loaders.tensorflow_datasets
from typing import Callable, Dict, Iterator, List, Optional
from langchain.document_loaders.base import BaseLoader
from langchain.schema import Document
from langchain.utilities.tensorflow_datasets import TensorflowDatasets
[docs]class TensorflowDatasetLoad... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tensorflow_datasets.html |
58d9e6fc45bb-1 | ):
"""Initialize the TensorflowDatasetLoader.
Args:
dataset_name: the name of the dataset to load
split_name: the name of the split to load.
load_max_docs: a limit to the number of loaded documents. Defaults to 100.
sample_to_document_function: a function ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tensorflow_datasets.html |
bf4cfdcd3152-0 | Source code for langchain.document_loaders.slack_directory
"""Loader for documents from a Slack export."""
import json
import zipfile
from pathlib import Path
from typing import Dict, List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class Slack... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/slack_directory.html |
bf4cfdcd3152-1 | if not channel_name:
continue
if channel_path.endswith(".json"):
messages = self._read_json(zip_file, channel_path)
for message in messages:
document = self._convert_message_to_document(
messa... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/slack_directory.html |
bf4cfdcd3152-2 | "timestamp": timestamp,
"user": user,
}
def _get_message_source(self, channel_name: str, user: str, timestamp: str) -> str:
"""
Get the message source as a string.
Args:
channel_name (str): The name of the channel the message belongs to.
user (str)... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/slack_directory.html |
ce275bcdecac-0 | Source code for langchain.document_loaders.hugging_face_dataset
"""Loads HuggingFace datasets."""
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)... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html |
ce275bcdecac-1 | """
self.path = path
self.page_content_column = page_content_column
self.name = name
self.data_dir = data_dir
self.data_files = data_files
self.cache_dir = cache_dir
self.keep_in_memory = keep_in_memory
self.save_infos = save_infos
self.use_auth_to... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html |
f2cc23a810a0-0 | Source code for langchain.document_loaders.tsv
from typing import Any, List
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
validate_unstructured_version,
)
[docs]class UnstructuredTSVLoader(UnstructuredFileLoader):
"""Loader that uses unstructured to load TSV files. Like other... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/tsv.html |
ce0b10d669af-0 | Source code for langchain.document_loaders.geodataframe
"""Load from Dataframe object"""
from typing import Any, Iterator, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class GeoDataFrameLoader(BaseLoader):
"""Load geopandas Dataframe."""
[docs] ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/geodataframe.html |
f03acb6952b1-0 | Source code for langchain.document_loaders.html
"""Loader that uses unstructured to load HTML files."""
from typing import List
from langchain.document_loaders.unstructured import UnstructuredFileLoader
[docs]class UnstructuredHTMLLoader(UnstructuredFileLoader):
"""Loader that uses Unstructured to load HTML files.
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/html.html |
b599a17a3f8c-0 | Source code for langchain.document_loaders.college_confidential
"""Loads College Confidential."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.web_base import WebBaseLoader
[docs]class CollegeConfidentialLoader(WebBaseLoader):
"""Loads College Confidential... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/college_confidential.html |
ded42ce1fdfe-0 | Source code for langchain.document_loaders.mastodon
"""Mastodon document loader."""
from __future__ import annotations
import os
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
if TYPE... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mastodon.html |
ded42ce1fdfe-1 | Defaults to "https://mastodon.social".
"""
mastodon = _dependable_mastodon_import()
access_token = access_token or os.environ.get("MASTODON_ACCESS_TOKEN")
self.api = mastodon.Mastodon(
access_token=access_token, api_base_url=api_base_url
)
self.mastodon_accoun... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mastodon.html |
542244ea6e20-0 | Source code for langchain.document_loaders.image_captions
"""Loads image captions.
By default, the loader utilizes the pre-trained BLIP image captioning model.
https://huggingface.co/Salesforce/blip-image-captioning-base
"""
from typing import Any, List, Tuple, Union
import requests
from langchain.docstore.document imp... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html |
542244ea6e20-1 | model = BlipForConditionalGeneration.from_pretrained(self.blip_model)
results = []
for path_image in self.image_paths:
caption, metadata = self._get_captions_and_metadata(
model=model, processor=processor, path_image=path_image
)
doc = Document(page_co... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html |
dc1e1802cab0-0 | Source code for langchain.document_loaders.bibtex
import logging
import re
from pathlib import Path
from typing import Any, Iterator, List, Mapping, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utilities.bibtex import BibtexparserWrapper... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bibtex.html |
dc1e1802cab0-1 | """
self.file_path = file_path
self.parser = parser or BibtexparserWrapper()
self.max_docs = max_docs
self.max_content_chars = max_content_chars
self.load_extra_metadata = load_extra_metadata
self.file_regex = re.compile(file_pattern)
def _load_entry(self, entry: Mapp... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bibtex.html |
dc1e1802cab0-2 | raise ImportError(
"PyMuPDF package not found, please install it with "
"`pip install pymupdf`"
)
entries = self.parser.load_bibtex_entries(self.file_path)
if self.max_docs:
entries = entries[: self.max_docs]
for entry in entries:
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bibtex.html |
94c89bb862a4-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 |
94c89bb862a4-1 | *,
glob: str = "**/[!.]*",
suffixes: Optional[Sequence[str]] = None,
show_progress: bool = False,
) -> None:
"""Initialize with path to directory and how to glob over it.
Args:
path: Path to directory to load from
glob: Glob pattern relative to the spe... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html |
94c89bb862a4-2 | self,
) -> Iterable[Blob]:
"""Yield blobs that match the requested pattern."""
iterator = _make_iterator(
length_func=self.count_matching_files, show_progress=self.show_progress
)
for path in iterator(self._yield_paths()):
yield Blob.from_path(path)
def _y... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html |
bb25e63f4842-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 |
6c1960077bda-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 |
6c1960077bda-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 |
6c1960077bda-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 |
6c1960077bda-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 |
ee72afc3877b-0 | Source code for langchain.document_loaders.parsers.pdf
"""Module contains common parsers for PDFs."""
from typing import Any, Iterator, Mapping, Optional, Sequence, Union
from urllib.parse import urlparse
from langchain.document_loaders.base import BaseBlobParser
from langchain.document_loaders.blob_loaders import Blob... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
ee72afc3877b-1 | """Parse PDFs with 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()``.
"""
self.text_kwargs = text_kwargs or {}
[docs] def laz... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
ee72afc3877b-2 | """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() as file_path:
pdf_reader = pypdfium2.PdfDocument(file_path, autoclose=True)
try:
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
ee72afc3877b-3 | "total_pages": len(doc.pages),
},
**{
k: doc.metadata[k]
for k in doc.metadata
if type(doc.metadata[k]) in [str, int]
},
),
)
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
ee72afc3877b-4 | raise ImportError(
"Could not import boto3 python package. "
"Please install it with `pip install boto3`."
)
else:
self.boto3_textract_client = client
[docs] def lazy_parse(self, blob: Blob) -> Iterator[Document]:
"""Iterates over th... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
ee72afc3877b-5 | )
current_text = ""
current_page = int(block["Page"])
if "Text" in block:
current_text += block["Text"] + " "
yield Document(
page_content=current_text,
metadata={"source": blob.source, "page": current_page},
) | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/pdf.html |
76ad9265f680-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.pdf import PyMuPDFP... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/registry.html |
85583c300aba-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 |
386cc420576e-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 |
386cc420576e-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 |
7d9267c44d13-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 |
7d9267c44d13-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 |
7d9267c44d13-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 |
7d9267c44d13-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 |
91271c883130-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 |
91271c883130-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 |
91271c883130-2 | task="transcribe")
forced_decoder_ids = WhisperProcessor.get_decoder_prompt_ids(language="french",
task="translate")
"""
[docs] def __init__(
self,
device: str = "0",
lang_model: Optional[str] = None,
forced_decoder_ids: Optional[Tuple[Dict]] = None,
):
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html |
91271c883130-3 | rec_model = "openai/whisper-medium"
else:
rec_model = "openai/whisper-large"
# check if model is overridden
if lang_model is not None:
self.lang_model = lang_model
print("WARNING! Model override. Might not fit in... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html |
91271c883130-4 | file_obj = io.BytesIO(audio.export(format="mp3").read())
# Transcribe
print(f"Transcribing part {blob.path}!")
y, sr = librosa.load(file_obj, sr=16000)
prediction = self.pipe(y.copy(), batch_size=8)["text"]
yield Document(
page_content=prediction,
metadata... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/audio.html |
4af1401b8c78-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):
"""The 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 |
4af1401b8c78-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 |
9ac418e3a027-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 |
9ac418e3a027-1 | docs = loader.load()
Example instantiations to manually select the language:
... code-block:: python
from langchain.text_splitter import Language
loader = GenericLoader.from_filesystem(
"./code",
glob="**/*",
suffixes=[".py"],
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/language_parser.html |
9ac418e3a027-2 | "source": blob.source,
"language": language,
},
)
return
self.Segmenter = LANGUAGE_SEGMENTERS[language]
segmenter = self.Segmenter(blob.as_string())
if not segmenter.is_valid():
yield Document(
page_content=c... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/language_parser.html |
586f10c5273d-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):
"""The 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 |
586f10c5273d-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 |
1466f91bfb91-0 | Source code for langchain.document_loaders.parsers.language.code_segmenter
from abc import ABC, abstractmethod
from typing import List
[docs]class CodeSegmenter(ABC):
"""The abstract class for the code segmenter."""
[docs] def __init__(self, code: str):
self.code = code
[docs] def is_valid(self) -> bo... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/parsers/language/code_segmenter.html |
5d0c53f7f09d-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 |
1a31b8ea94ee-0 | Source code for langchain._api.deprecation
"""Helper functions for deprecating parts of the LangChain API.
This module was adapted from matplotlibs _api/deprecation.py module:
https://github.com/matplotlib/matplotlib/blob/main/lib/matplotlib/_api/deprecation.py
.. warning::
This module is for internal use only. Do... | https://api.python.langchain.com/en/latest/_modules/langchain/_api/deprecation.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.