id stringlengths 14 16 | text stringlengths 4 1.28k | source stringlengths 54 121 |
|---|---|---|
93d6d48400eb-1 | file_extension: NotRequired[str]
"""The file extension of the document."""
file_name: NotRequired[str]
"""The file name of the document."""
should_chunk: NotRequired[bool]
"""Whether to chunk the document into pages."""
chunk_size: NotRequired[int]
"""The maximum size of the text chunks."""
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
93d6d48400eb-2 | instruction: NotRequired[str]
"""The instruction to pass to the Embaas document extraction API."""
class EmbaasDocumentExtractionPayload(EmbaasDocumentExtractionParameters):
"""Payload for the Embaas document extraction API."""
bytes: str
"""The base64 encoded bytes of the document to extract text from.... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
93d6d48400eb-3 | embaas_api_key = get_from_dict_or_env(
values, "embaas_api_key", "EMBAAS_API_KEY"
)
values["embaas_api_key"] = embaas_api_key
return values
[docs]class EmbaasBlobLoader(BaseEmbaasLoader, BaseBlobParser):
"""Wrapper around embaas's document byte loader service.
To use, you sho... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
93d6d48400eb-4 | documents = loader.parse(blob=blob)
# Custom api parameters (create embeddings automatically)
from langchain.document_loaders.embaas import EmbaasBlobLoader
loader = EmbaasBlobLoader(
params={
"should_embed": True,
"model": "e5-... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
93d6d48400eb-5 | docs = []
for chunk in chunks:
metadata = chunk["metadata"]
if chunk.get("embedding", None) is not None:
metadata["embedding"] = chunk["embedding"]
doc = Document(page_content=chunk["text"], metadata=metadata)
docs.append(doc)
return docs
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
93d6d48400eb-6 | **self.params,
)
if blob.mimetype is not None and payload.get("mime_type", None) is None:
payload["mime_type"] = blob.mimetype
return payload
def _handle_request(
self, payload: EmbaasDocumentExtractionPayload
) -> List[Document]:
"""Sends a request to the emb... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
93d6d48400eb-7 | )
def _get_documents(self, blob: Blob) -> Iterator[Document]:
"""Get the documents from the blob."""
payload = self._generate_payload(blob=blob)
try:
documents = self._handle_request(payload=payload)
except requests.exceptions.RequestException as e:
if e.respo... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
93d6d48400eb-8 | To use, you should have the
environment variable ``EMBAAS_API_KEY`` set with your API key, or pass
it as a named parameter to the constructor.
Example:
.. code-block:: python
# Default parsing
from langchain.document_loaders.embaas import EmbaasLoader
loader = Emb... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
93d6d48400eb-9 | )
documents = loader.load()
"""
file_path: str
"""The path to the file to load."""
blob_loader: Optional[EmbaasBlobLoader]
"""The blob loader to use. If not provided, a default one will be created."""
@validator("blob_loader", always=True)
def validate_blob_loader(
cls, v... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
93d6d48400eb-10 | assert self.blob_loader is not None
# Should never be None, but mypy doesn't know that.
yield from self.blob_loader.lazy_parse(blob=blob)
[docs] def load(self) -> List[Document]:
return list(self.lazy_load())
[docs] def load_and_split(
self, text_splitter: Optional[TextSplitter] = ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html |
30c981747396-0 | Source code for langchain.document_loaders.airtable
from typing import Iterator, List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class AirtableLoader(BaseLoader):
"""Loader for Airtable tables."""
def __init__(self, api_token: str, table_id: str... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airtable.html |
30c981747396-1 | yield Document(
page_content=str(record),
metadata={
"source": self.base_id + "_" + self.table_id,
"base_id": self.base_id,
"table_id": self.table_id,
},
)
[docs] def load(self) -> List[Document]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/airtable.html |
906ebea63a04-0 | Source code for langchain.document_loaders.pdf
"""Loader that loads PDF files."""
import json
import logging
import os
import tempfile
import time
from abc import ABC
from io import StringIO
from pathlib import Path
from typing import Any, Iterator, List, Mapping, Optional
from urllib.parse import urlparse
import reque... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
906ebea63a04-1 | """Loader that uses unstructured to load PDF files."""
def _get_elements(self) -> List:
from unstructured.partition.pdf import partition_pdf
return partition_pdf(filename=self.file_path, **self.unstructured_kwargs)
class BasePDFLoader(BaseLoader, ABC):
"""Base loader class for PDF files.
Def... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
906ebea63a04-2 | if not os.path.isfile(self.file_path) and self._is_valid_url(self.file_path):
r = requests.get(self.file_path)
if r.status_code != 200:
raise ValueError(
"Check the url of your file; returned status code %s"
% r.status_code
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
906ebea63a04-3 | self.temp_dir.cleanup()
@staticmethod
def _is_valid_url(url: str) -> bool:
"""Check if the url is valid."""
parsed = urlparse(url)
return bool(parsed.netloc) and bool(parsed.scheme)
@property
def source(self) -> str:
return self.web_path if self.web_path is not None else ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
906ebea63a04-4 | """
def __init__(self, file_path: str) -> None:
"""Initialize with file path."""
try:
import pypdf # noqa:F401
except ImportError:
raise ImportError(
"pypdf package not found, please install it with " "`pip install pypdf`"
)
self.p... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
906ebea63a04-5 | """Loads a PDF with pypdfium2 and chunks at character level."""
def __init__(self, file_path: str):
"""Initialize with file path."""
super().__init__(file_path)
self.parser = PyPDFium2Parser()
[docs] def load(self) -> List[Document]:
"""Load given path as pages."""
return ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
906ebea63a04-6 | def __init__(
self,
path: str,
glob: str = "**/[!.]*.pdf",
silent_errors: bool = False,
load_hidden: bool = False,
recursive: bool = False,
):
self.path = path
self.glob = glob
self.load_hidden = load_hidden
self.recursive = recursive
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
906ebea63a04-7 | if i.is_file():
if self._is_visible(i.relative_to(p)) or self.load_hidden:
try:
loader = PyPDFLoader(str(i))
sub_docs = loader.load()
for doc in sub_docs:
doc.metadata["source"] = str(... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
906ebea63a04-8 | "`pip install pdfminer.six`"
)
super().__init__(file_path)
self.parser = PDFMinerParser()
[docs] def load(self) -> List[Document]:
"""Eagerly load the content."""
return list(self.lazy_load())
[docs] def lazy_load(
self,
) -> Iterator[Document]:
"""L... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
906ebea63a04-9 | except ImportError:
raise ImportError(
"`pdfminer` package not found, please install it with "
"`pip install pdfminer.six`"
)
super().__init__(file_path)
[docs] def load(self) -> List[Document]:
"""Load file."""
from pdfminer.high_level ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
906ebea63a04-10 | [docs]class PyMuPDFLoader(BasePDFLoader):
"""Loader that uses PyMuPDF to load PDF files."""
def __init__(self, file_path: str) -> None:
"""Initialize with file path."""
try:
import fitz # noqa:F401
except ImportError:
raise ImportError(
"`PyMuPDF`... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
906ebea63a04-11 | # https://gist.github.com/danielgross/3ab4104e14faccc12b49200843adab21
[docs]class MathpixPDFLoader(BasePDFLoader):
def __init__(
self,
file_path: str,
processed_file_format: str = "mmd",
max_wait_time_seconds: int = 500,
should_clean_pdf: bool = False,
**kwargs: Any,... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
906ebea63a04-12 | self.max_wait_time_seconds = max_wait_time_seconds
self.should_clean_pdf = should_clean_pdf
@property
def headers(self) -> dict:
return {"app_id": self.mathpix_api_id, "app_key": self.mathpix_api_key}
@property
def url(self) -> str:
return "https://api.mathpix.com/v3/pdf"
@pr... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
906ebea63a04-13 | response_data = response.json()
if "pdf_id" in response_data:
pdf_id = response_data["pdf_id"]
return pdf_id
else:
raise ValueError("Unable to send PDF to Mathpix.")
[docs] def wait_for_processing(self, pdf_id: str) -> None:
url = self.url + "/" + pdf_id
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
906ebea63a04-14 | raise TimeoutError
[docs] def get_processed_pdf(self, pdf_id: str) -> str:
self.wait_for_processing(pdf_id)
url = f"{self.url}/{pdf_id}.{self.processed_file_format}"
response = requests.get(url, headers=self.headers)
return response.content.decode("utf-8")
[docs] def clean_pdf(self... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
906ebea63a04-15 | .replace(r"\%", "%")
.replace(r"\(", "(")
.replace(r"\)", ")")
)
return contents
[docs] def load(self) -> List[Document]:
pdf_id = self.send_pdf()
contents = self.get_processed_pdf(pdf_id)
if self.should_clean_pdf:
contents = self.clean_pdf(... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
906ebea63a04-16 | except ImportError:
raise ImportError(
"pdfplumber package not found, please install it with "
"`pip install pdfplumber`"
)
super().__init__(file_path)
self.text_kwargs = text_kwargs or {}
[docs] def load(self) -> List[Document]:
"""Load... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html |
37069995414e-0 | Source code for langchain.document_loaders.epub
"""Loader that loads EPub files."""
from typing import List
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
satisfies_min_unstructured_version,
)
[docs]class UnstructuredEPubLoader(UnstructuredFileLoader):
"""Loader that uses unst... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/epub.html |
abaed366013c-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 |
abaed366013c-1 | mastodon_accounts: Sequence[str],
number_toots: Optional[int] = 100,
exclude_replies: bool = False,
access_token: Optional[str] = None,
api_base_url: str = "https://mastodon.social",
):
"""Instantiate Mastodon toots loader.
Args:
mastodon_accounts: The lis... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mastodon.html |
abaed366013c-2 | 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_accounts = mastodon_accounts
self.number_toots = number_toots
self.exclude_replies = exclude_repli... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mastodon.html |
abaed366013c-3 | )
docs = self._format_toots(toots, user)
results.extend(docs)
return results
def _format_toots(
self, toots: List[Dict[str, Any]], user_info: dict
) -> Iterable[Document]:
"""Format toots into documents.
Adding user info, and selected toot fields into the ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/mastodon.html |
68b56152951e-0 | Source code for langchain.document_loaders.college_confidential
"""Loader that 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):
"""Loader that lo... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/college_confidential.html |
1ade4497171f-0 | Source code for langchain.document_loaders.whatsapp_chat
import re
from pathlib import Path
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
def concatenate_rows(date: str, sender: str, text: str) -> str:
"""Combine message information i... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/whatsapp_chat.html |
1ade4497171f-1 | lines = f.readlines()
message_line_regex = r"""
\[?
(
\d{1,4}
[\/.]
\d{1,2}
[\/.]
\d{1,4}
,\s
\d{1,2}
:\d{2}
(?:
:\d{2}
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/whatsapp_chat.html |
1ade4497171f-2 | text_content += concatenate_rows(date, sender, text)
metadata = {"source": str(p)}
return [Document(page_content=text_content, metadata=metadata)] | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/whatsapp_chat.html |
36e36e172bf6-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 |
36e36e172bf6-1 | "certificates": "https://core.spreedly.com/v1/certificates.json",
"transactions": "https://core.spreedly.com/v1/transactions.json",
"environments": "https://core.spreedly.com/v1/environments.json",
}
[docs]class SpreedlyLoader(BaseLoader):
"""Loader that fetches data from Spreedly API."""
def __init__(s... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/spreedly.html |
36e36e172bf6-2 | json_data = json.loads(response.read().decode())
text = stringify_dict(json_data)
metadata = {"source": url}
return [Document(page_content=text, metadata=metadata)]
def _get_resource(self) -> List[Document]:
endpoint = SPREEDLY_ENDPOINTS.get(self.resource)
if endp... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/spreedly.html |
5d2af2e0af6f-0 | Source code for langchain.document_loaders.youtube
"""Loader that loads YouTube transcript."""
from __future__ import annotations
import logging
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Union
from urllib.parse import parse_qs, urlparse
from pydantic import root_validator
from pyd... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
5d2af2e0af6f-1 | register your Service. "https://developers.google.com/docs/api/quickstart/python"
Example:
.. code-block:: python
from langchain.document_loaders import GoogleApiClient
google_api_client = GoogleApiClient(
service_account_path=Path("path_to_your_sec_file.json")
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
5d2af2e0af6f-2 | ) -> Dict[str, Any]:
"""Validate that either folder_id or document_ids is set, but not both."""
if not values.get("credentials_path") and not values.get(
"service_account_path"
):
raise ValueError("Must specify either channel_name or video_ids")
return values
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
5d2af2e0af6f-3 | "`pip install --upgrade "
"google-api-python-client google-auth-httplib2 "
"google-auth-oauthlib "
"youtube-transcript-api` "
"to use the Google Drive loader"
)
creds = None
if self.service_account_path.exists():
ret... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
5d2af2e0af6f-4 | with open(self.token_path, "w") as token:
token.write(creds.to_json())
return creds
ALLOWED_SCHEMAS = {"http", "https"}
ALLOWED_NETLOCK = {
"youtu.be",
"m.youtube.com",
"youtube.com",
"www.youtube.com",
"www.youtube-nocookie.com",
"vid.plus",
}
def _parse_video_id(url: st... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
5d2af2e0af6f-5 | parsed_query = parse_qs(query)
if "v" in parsed_query:
ids = parsed_query["v"]
video_id = ids if isinstance(ids, str) else ids[0]
else:
return None
else:
path = parsed_url.path.lstrip("/")
video_id = path.split("/")[-1]
if len(video_id) != 11: ... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
5d2af2e0af6f-6 | """Initialize with YouTube video ID."""
self.video_id = video_id
self.add_video_info = add_video_info
self.language = language
if isinstance(language, str):
self.language = [language]
else:
self.language = language
self.translation = translation
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
5d2af2e0af6f-7 | """Given youtube URL, load video."""
video_id = cls.extract_video_id(youtube_url)
return cls(video_id, **kwargs)
[docs] def load(self) -> List[Document]:
"""Load documents."""
try:
from youtube_transcript_api import (
NoTranscriptFound,
Tran... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
5d2af2e0af6f-8 | try:
transcript_list = YouTubeTranscriptApi.list_transcripts(self.video_id)
except TranscriptsDisabled:
return []
try:
transcript = transcript_list.find_transcript(self.language)
except NoTranscriptFound:
en_transcript = transcript_list.find_transc... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
5d2af2e0af6f-9 | except ImportError:
raise ImportError(
"Could not import pytube python package. "
"Please install it with `pip install pytube`."
)
yt = YouTube(f"https://www.youtube.com/watch?v={self.video_id}")
video_info = {
"title": yt.title or "Unk... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
5d2af2e0af6f-10 | class GoogleApiYoutubeLoader(BaseLoader):
"""Loader that loads all Videos from a Channel
To use, you should have the ``googleapiclient,youtube_transcript_api``
python package installed.
As the service needs a google_api_client, you first have to initialize
the GoogleApiClient.
Additionally you h... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
5d2af2e0af6f-11 | )
load.load()
"""
google_api_client: GoogleApiClient
channel_name: Optional[str] = None
video_ids: Optional[List[str]] = None
add_video_info: bool = True
captions_language: str = "en"
continue_on_failure: bool = False
def __post_init__(self) -> None:
self.youtube_clie... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
5d2af2e0af6f-12 | "google-auth-oauthlib "
"youtube-transcript-api` "
"to use the Google Drive loader"
)
return build("youtube", "v3", credentials=creds)
[docs] @root_validator
def validate_channel_or_videoIds_is_set(
cls, values: Dict[str, Any]
) -> Dict[str, Any]:
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
5d2af2e0af6f-13 | try:
transcript = transcript_list.find_transcript([self.captions_language])
except NoTranscriptFound:
for available_transcript in transcript_list:
transcript = available_transcript.translate(self.captions_language)
continue
transcript_pieces = tran... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
5d2af2e0af6f-14 | )
def _get_channel_id(self, channel_name: str) -> str:
request = self.youtube_client.search().list(
part="id",
q=channel_name,
type="channel",
maxResults=1, # we only need one result since channel names are unique
)
response = request.execute(... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
5d2af2e0af6f-15 | )
channel_id = self._get_channel_id(channel)
request = self.youtube_client.search().list(
part="id,snippet",
channelId=channel_id,
maxResults=50, # adjust this value to retrieve more or fewer videos
)
video_ids = []
while request is not None:
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
5d2af2e0af6f-16 | )
video_ids.append(
Document(
page_content=page_content,
metadata=meta_data,
)
)
except (TranscriptsDisabled, NoTranscriptFound) as e:
if se... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
5d2af2e0af6f-17 | document_list.extend(
[
self._get_document_for_video_id(video_id)
for video_id in self.video_ids
]
)
else:
raise ValueError("Must specify either channel_name or video_ids")
return document_list | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html |
c5dd482cf647-0 | Source code for langchain.document_loaders.hugging_face_dataset
"""Loader that 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... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html |
c5dd482cf647-1 | save_infos: bool = False,
use_auth_token: Optional[Union[bool, str]] = None,
num_proc: Optional[int] = None,
):
"""Initialize the HuggingFaceDatasetLoader.
Args:
path: Path or name of the dataset.
page_content_column: Page content column name.
name... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html |
c5dd482cf647-2 | """
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 |
c5dd482cf647-3 | data_files=self.data_files,
cache_dir=self.cache_dir,
keep_in_memory=self.keep_in_memory,
save_infos=self.save_infos,
use_auth_token=self.use_auth_token,
num_proc=self.num_proc,
)
yield from (
Document(
page_content=... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html |
1c6989168f0e-0 | Source code for langchain.document_loaders.chatgpt
"""Load conversations from ChatGPT data export"""
import datetime
import json
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
def concatenate_rows(message: dict, title: str) -> str:
"""... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/chatgpt.html |
1c6989168f0e-1 | )
return f"{title} - {sender} on {date}: {text}\n\n"
[docs]class ChatGPTLoader(BaseLoader):
"""Loader that loads conversations from exported ChatGPT data."""
def __init__(self, log_file: str, num_logs: int = -1):
self.log_file = log_file
self.num_logs = num_logs
[docs] def load(self) -> L... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/chatgpt.html |
1c6989168f0e-2 | for idx, key in enumerate(messages)
if not (
idx == 0
and messages[key]["message"]["author"]["role"] == "system"
)
]
)
metadata = {"source": str(self.log_file)}
documents.append(Do... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/chatgpt.html |
81122cde2b40-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 |
81122cde2b40-1 | except ImportError:
raise ValueError(
"beautifulsoup4 package not found, please install it with "
"`pip install beautifulsoup4`"
)
self.file_path = file_path
self.open_encoding = open_encoding
if bs_kwargs is None:
bs_kwargs = {... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/html_bs.html |
81122cde2b40-2 | else:
title = ""
metadata: Dict[str, Union[str, None]] = {
"source": self.file_path,
"title": title,
}
return [Document(page_content=text, metadata=metadata)] | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/html_bs.html |
d68609496361-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 |
d68609496361-1 | # a progress bar that takes into account the total number of files.
def _with_tqdm(iterable: Iterable[T]) -> Iterator[T]:
"""Wrap an iterable in a tqdm progress bar."""
return tqdm(iterable, total=length_func())
iterator = _with_tqdm
else:
iterator = iter # type: ign... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html |
d68609496361-2 | *,
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 |
d68609496361-3 | loader = FileSystemBlobLoader("/path/to/directory", glob="**/*.txt")
# Recursively load all non-hidden files in a directory.
loader = FileSystemBlobLoader("/path/to/directory", glob="**/[!.]*")
# Load all files in a directory without recursion.
loader = FileSystemBlobLoad... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html |
d68609496361-4 | ) -> 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 _yield_paths... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html |
d68609496361-5 | num = 0
for _ in self._yield_paths():
num += 1
return num | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/file_system.html |
5e781d3cee23-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 |
5e781d3cee23-1 | "`pip install yt_dlp`"
)
# Use yt_dlp to download audio given a YouTube url
ydl_opts = {
"format": "m4a/bestaudio/best",
"noplaylist": True,
"outtmpl": self.save_dir + "/%(title)s.%(ext)s",
"postprocessors": [
{
... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/youtube_audio.html |
15611f489b9f-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 |
15611f489b9f-1 | the raw data.
Inspired by: https://developer.mozilla.org/en-US/docs/Web/API/Blob
"""
data: Union[bytes, str, None] # Raw data
mimetype: Optional[str] = None # Not to be confused with a file extension
encoding: str = "utf-8" # Use utf-8 as default encoding, if decoding to string
# Location whe... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html |
15611f489b9f-2 | 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 |
15611f489b9f-3 | [docs] def as_bytes(self) -> bytes:
"""Read data as bytes."""
if isinstance(self.data, bytes):
return self.data
elif isinstance(self.data, str):
return self.data.encode(self.encoding)
elif self.data is None and self.path:
with open(str(self.path), "... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html |
15611f489b9f-4 | 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 |
15611f489b9f-5 | _mimetype = mimetypes.guess_type(path)[0] if guess_type else None
else:
_mimetype = mime_type
# We do not load the data immediately, instead we treat the blob as a
# reference to the underlying data.
return cls(data=None, mimetype=_mimetype, encoding=encoding, path=path)
[doc... | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html |
15611f489b9f-6 | 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 |
15611f489b9f-7 | self,
) -> Iterable[Blob]:
"""A lazy loader for raw data represented by LangChain's Blob object.
Returns:
A generator over blobs
""" | https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blob_loaders/schema.html |
08bc658d11d6-0 | Source code for langchain.embeddings.bedrock
import json
import os
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, Extra, root_validator
from langchain.embeddings.base import Embeddings
[docs]class BedrockEmbeddings(BaseModel, Embeddings):
"""Embeddings provider to invoke Bedrock embedd... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
08bc658d11d6-1 | region_name ="us-east-1"
credentials_profile_name = "default"
model_id = "amazon.titan-e1t-medium"
be = BedrockEmbeddings(
credentials_profile_name=credentials_profile_name,
region_name=region_name,
model_id=model_id
)
"... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
08bc658d11d6-2 | credentials from IMDS will be used.
See: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html
"""
model_id: str = "amazon.titan-e1t-medium"
"""Id of the model to call, e.g., amazon.titan-e1t-medium, this is
equivalent to the modelId property in the list-foundation-models ap... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
08bc658d11d6-3 | try:
import boto3
if values["credentials_profile_name"] is not None:
session = boto3.Session(profile_name=values["credentials_profile_name"])
else:
# use default credentials
session = boto3.Session()
client_params = {}
... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
08bc658d11d6-4 | ) from e
return values
def _embedding_func(self, text: str) -> List[float]:
"""Call out to Bedrock embedding endpoint."""
# replace newlines, which can negatively affect performance.
text = text.replace(os.linesep, " ")
_model_kwargs = self.model_kwargs or {}
input_bo... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
08bc658d11d6-5 | except Exception as e:
raise ValueError(f"Error raised by inference endpoint: {e}")
return embeddings
[docs] def embed_documents(
self, texts: List[str], chunk_size: int = 1
) -> List[List[float]]:
"""Compute doc embeddings using a Bedrock model.
Args:
text... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
08bc658d11d6-6 | """Compute query embeddings using a Bedrock model.
Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
return self._embedding_func(text) | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/bedrock.html |
d200fd73f9eb-0 | Source code for langchain.embeddings.self_hosted
"""Running custom embedding models on self-hosted remote hardware."""
from typing import Any, Callable, List
from pydantic import Extra
from langchain.embeddings.base import Embeddings
from langchain.llms import SelfHostedPipeline
def _embed_documents(pipeline: Any, *arg... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html |
d200fd73f9eb-1 | and Lambda, as well as servers specified
by IP address and SSH credentials (such as on-prem, or another
cloud like Paperspace, Coreweave, etc.).
To use, you should have the ``runhouse`` python package installed.
Example using a model load function:
.. code-block:: python
from langcha... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html |
d200fd73f9eb-2 | embeddings = SelfHostedEmbeddings(
model_load_fn=get_pipeline,
hardware=gpu
model_reqs=["./", "torch", "transformers"],
)
Example passing in a pipeline path:
.. code-block:: python
from langchain.embeddings import SelfHostedHFEmbeddings... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html |
d200fd73f9eb-3 | )
"""
inference_fn: Callable = _embed_documents
"""Inference function to extract the embeddings on the remote hardware."""
inference_kwargs: Any = None
"""Any kwargs to pass to the model's inference function."""
class Config:
"""Configuration for this pydantic object."""
extra = ... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html |
d200fd73f9eb-4 | return embeddings.tolist()
return embeddings
[docs] def embed_query(self, text: str) -> List[float]:
"""Compute query embeddings using a HuggingFace transformer model.
Args:
text: The text to embed.
Returns:
Embeddings for the text.
"""
text = t... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/self_hosted.html |
3637c2e10665-0 | Source code for langchain.embeddings.aleph_alpha
from typing import Any, Dict, List, Optional
from pydantic import BaseModel, root_validator
from langchain.embeddings.base import Embeddings
from langchain.utils import get_from_dict_or_env
[docs]class AlephAlphaAsymmetricSemanticEmbedding(BaseModel, Embeddings):
"""... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
3637c2e10665-1 | document = "This is a content of the document"
query = "What is the content of the document?"
doc_result = embeddings.embed_documents([document])
query_result = embeddings.embed_query(query)
"""
client: Any #: :meta private:
model: Optional[str] = "luminous-base"
"""... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
3637c2e10665-2 | """Attention control parameters only apply to those tokens that have
explicitly been set in the request."""
control_log_additive: Optional[bool] = True
"""Apply controls on prompt items by adding the log(control_factor)
to attention scores."""
aleph_alpha_api_key: Optional[str] = None
"""API k... | https://api.python.langchain.com/en/latest/_modules/langchain/embeddings/aleph_alpha.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.