id
stringlengths
14
16
text
stringlengths
44
2.73k
source
stringlengths
49
114
e4fee00b7c77-0
Source code for langchain.text_splitter """Functionality for splitting text.""" from __future__ import annotations import copy import logging from abc import ABC, abstractmethod from typing import ( AbstractSet, Any, Callable, Collection, Iterable, List, Literal, Optional, Sequence, Union, ) from langchain.docstore.document import Document from langchain.schema import BaseDocumentTransformer logger = logging.getLogger(__name__) [docs]class TextSplitter(BaseDocumentTransformer, ABC): """Interface for splitting text into chunks.""" def __init__( self, chunk_size: int = 4000, chunk_overlap: int = 200, length_function: Callable[[str], int] = len, ): """Create a new TextSplitter.""" if chunk_overlap > chunk_size: raise ValueError( f"Got a larger chunk overlap ({chunk_overlap}) than chunk size " f"({chunk_size}), should be smaller." ) self._chunk_size = chunk_size self._chunk_overlap = chunk_overlap self._length_function = length_function [docs] @abstractmethod def split_text(self, text: str) -> List[str]: """Split text into multiple components.""" [docs] def create_documents( self, texts: List[str], metadatas: Optional[List[dict]] = None ) -> List[Document]: """Create documents from a list of texts.""" _metadatas = metadatas or [{}] * len(texts) documents = [] for i, text in enumerate(texts): for chunk in self.split_text(text): new_doc = Document(
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
e4fee00b7c77-1
for chunk in self.split_text(text): new_doc = Document( page_content=chunk, metadata=copy.deepcopy(_metadatas[i]) ) documents.append(new_doc) return documents [docs] def split_documents(self, documents: List[Document]) -> List[Document]: """Split documents.""" texts = [doc.page_content for doc in documents] metadatas = [doc.metadata for doc in documents] return self.create_documents(texts, metadatas=metadatas) def _join_docs(self, docs: List[str], separator: str) -> Optional[str]: text = separator.join(docs) text = text.strip() if text == "": return None else: return text def _merge_splits(self, splits: Iterable[str], separator: str) -> List[str]: # We now want to combine these smaller pieces into medium size # chunks to send to the LLM. separator_len = self._length_function(separator) docs = [] current_doc: List[str] = [] total = 0 for d in splits: _len = self._length_function(d) if ( total + _len + (separator_len if len(current_doc) > 0 else 0) > self._chunk_size ): if total > self._chunk_size: logger.warning( f"Created a chunk of size {total}, " f"which is longer than the specified {self._chunk_size}" ) if len(current_doc) > 0: doc = self._join_docs(current_doc, separator) if doc is not None: docs.append(doc) # Keep on popping if:
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
e4fee00b7c77-2
docs.append(doc) # Keep on popping if: # - we have a larger chunk than in the chunk overlap # - or if we still have any chunks and the length is long while total > self._chunk_overlap or ( total + _len + (separator_len if len(current_doc) > 0 else 0) > self._chunk_size and total > 0 ): total -= self._length_function(current_doc[0]) + ( separator_len if len(current_doc) > 1 else 0 ) current_doc = current_doc[1:] current_doc.append(d) total += _len + (separator_len if len(current_doc) > 1 else 0) doc = self._join_docs(current_doc, separator) if doc is not None: docs.append(doc) return docs [docs] @classmethod def from_huggingface_tokenizer(cls, tokenizer: Any, **kwargs: Any) -> TextSplitter: """Text splitter that uses HuggingFace tokenizer to count length.""" try: from transformers import PreTrainedTokenizerBase if not isinstance(tokenizer, PreTrainedTokenizerBase): raise ValueError( "Tokenizer received was not an instance of PreTrainedTokenizerBase" ) def _huggingface_tokenizer_length(text: str) -> int: return len(tokenizer.encode(text)) except ImportError: raise ValueError( "Could not import transformers python package. " "Please install it with `pip install transformers`." ) return cls(length_function=_huggingface_tokenizer_length, **kwargs) [docs] @classmethod def from_tiktoken_encoder( cls,
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
e4fee00b7c77-3
[docs] @classmethod def from_tiktoken_encoder( cls, encoding_name: str = "gpt2", model_name: Optional[str] = None, allowed_special: Union[Literal["all"], AbstractSet[str]] = set(), disallowed_special: Union[Literal["all"], Collection[str]] = "all", **kwargs: Any, ) -> TextSplitter: """Text splitter that uses tiktoken encoder to count length.""" try: import tiktoken except ImportError: raise ValueError( "Could not import tiktoken python package. " "This is needed in order to calculate max_tokens_for_prompt. " "Please install it with `pip install tiktoken`." ) if model_name is not None: enc = tiktoken.encoding_for_model(model_name) else: enc = tiktoken.get_encoding(encoding_name) def _tiktoken_encoder(text: str, **kwargs: Any) -> int: return len( enc.encode( text, allowed_special=allowed_special, disallowed_special=disallowed_special, **kwargs, ) ) return cls(length_function=_tiktoken_encoder, **kwargs) [docs] def transform_documents( self, documents: Sequence[Document], **kwargs: Any ) -> Sequence[Document]: """Transform sequence of documents by splitting them.""" return self.split_documents(list(documents)) [docs] async def atransform_documents( self, documents: Sequence[Document], **kwargs: Any ) -> Sequence[Document]: """Asynchronously transform a sequence of documents by splitting them.""" raise NotImplementedError
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
e4fee00b7c77-4
"""Asynchronously transform a sequence of documents by splitting them.""" raise NotImplementedError [docs]class CharacterTextSplitter(TextSplitter): """Implementation of splitting text that looks at characters.""" def __init__(self, separator: str = "\n\n", **kwargs: Any): """Create a new TextSplitter.""" super().__init__(**kwargs) self._separator = separator [docs] def split_text(self, text: str) -> List[str]: """Split incoming text and return chunks.""" # First we naively split the large input into a bunch of smaller ones. if self._separator: splits = text.split(self._separator) else: splits = list(text) return self._merge_splits(splits, self._separator) [docs]class TokenTextSplitter(TextSplitter): """Implementation of splitting text that looks at tokens.""" def __init__( self, encoding_name: str = "gpt2", model_name: Optional[str] = None, allowed_special: Union[Literal["all"], AbstractSet[str]] = set(), disallowed_special: Union[Literal["all"], Collection[str]] = "all", **kwargs: Any, ): """Create a new TextSplitter.""" super().__init__(**kwargs) try: import tiktoken except ImportError: raise ValueError( "Could not import tiktoken python package. " "This is needed in order to for TokenTextSplitter. " "Please install it with `pip install tiktoken`." ) if model_name is not None: enc = tiktoken.encoding_for_model(model_name) else:
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
e4fee00b7c77-5
enc = tiktoken.encoding_for_model(model_name) else: enc = tiktoken.get_encoding(encoding_name) self._tokenizer = enc self._allowed_special = allowed_special self._disallowed_special = disallowed_special [docs] def split_text(self, text: str) -> List[str]: """Split incoming text and return chunks.""" splits = [] input_ids = self._tokenizer.encode( text, allowed_special=self._allowed_special, disallowed_special=self._disallowed_special, ) start_idx = 0 cur_idx = min(start_idx + self._chunk_size, len(input_ids)) chunk_ids = input_ids[start_idx:cur_idx] while start_idx < len(input_ids): splits.append(self._tokenizer.decode(chunk_ids)) start_idx += self._chunk_size - self._chunk_overlap cur_idx = min(start_idx + self._chunk_size, len(input_ids)) chunk_ids = input_ids[start_idx:cur_idx] return splits [docs]class RecursiveCharacterTextSplitter(TextSplitter): """Implementation of splitting text that looks at characters. Recursively tries to split by different characters to find one that works. """ def __init__(self, separators: Optional[List[str]] = None, **kwargs: Any): """Create a new TextSplitter.""" super().__init__(**kwargs) self._separators = separators or ["\n\n", "\n", " ", ""] [docs] def split_text(self, text: str) -> List[str]: """Split incoming text and return chunks.""" final_chunks = [] # Get appropriate separator to use separator = self._separators[-1]
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
e4fee00b7c77-6
# Get appropriate separator to use separator = self._separators[-1] for _s in self._separators: if _s == "": separator = _s break if _s in text: separator = _s break # Now that we have the separator, split the text if separator: splits = text.split(separator) else: splits = list(text) # Now go merging things, recursively splitting longer texts. _good_splits = [] for s in splits: if self._length_function(s) < self._chunk_size: _good_splits.append(s) else: if _good_splits: merged_text = self._merge_splits(_good_splits, separator) final_chunks.extend(merged_text) _good_splits = [] other_info = self.split_text(s) final_chunks.extend(other_info) if _good_splits: merged_text = self._merge_splits(_good_splits, separator) final_chunks.extend(merged_text) return final_chunks [docs]class NLTKTextSplitter(TextSplitter): """Implementation of splitting text that looks at sentences using NLTK.""" def __init__(self, separator: str = "\n\n", **kwargs: Any): """Initialize the NLTK splitter.""" super().__init__(**kwargs) try: from nltk.tokenize import sent_tokenize self._tokenizer = sent_tokenize except ImportError: raise ImportError( "NLTK is not installed, please install it with `pip install nltk`." ) self._separator = separator [docs] def split_text(self, text: str) -> List[str]:
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
e4fee00b7c77-7
[docs] def split_text(self, text: str) -> List[str]: """Split incoming text and return chunks.""" # First we naively split the large input into a bunch of smaller ones. splits = self._tokenizer(text) return self._merge_splits(splits, self._separator) [docs]class SpacyTextSplitter(TextSplitter): """Implementation of splitting text that looks at sentences using Spacy.""" def __init__( self, separator: str = "\n\n", pipeline: str = "en_core_web_sm", **kwargs: Any ): """Initialize the spacy text splitter.""" super().__init__(**kwargs) try: import spacy except ImportError: raise ImportError( "Spacy is not installed, please install it with `pip install spacy`." ) self._tokenizer = spacy.load(pipeline) self._separator = separator [docs] def split_text(self, text: str) -> List[str]: """Split incoming text and return chunks.""" splits = (str(s) for s in self._tokenizer(text).sents) return self._merge_splits(splits, self._separator) [docs]class MarkdownTextSplitter(RecursiveCharacterTextSplitter): """Attempts to split the text along Markdown-formatted headings.""" def __init__(self, **kwargs: Any): """Initialize a MarkdownTextSplitter.""" separators = [ # First, try to split along Markdown headings (starting with level 2) "\n## ", "\n### ", "\n#### ", "\n##### ", "\n###### ", # Note the alternative syntax for headings (below) is not handled here
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
e4fee00b7c77-8
# Note the alternative syntax for headings (below) is not handled here # Heading level 2 # --------------- # End of code block "```\n\n", # Horizontal lines "\n\n***\n\n", "\n\n---\n\n", "\n\n___\n\n", # Note that this splitter doesn't handle horizontal lines defined # by *three or more* of ***, ---, or ___, but this is not handled "\n\n", "\n", " ", "", ] super().__init__(separators=separators, **kwargs) [docs]class LatexTextSplitter(RecursiveCharacterTextSplitter): """Attempts to split the text along Latex-formatted layout elements.""" def __init__(self, **kwargs: Any): """Initialize a LatexTextSplitter.""" separators = [ # First, try to split along Latex sections "\n\\chapter{", "\n\\section{", "\n\\subsection{", "\n\\subsubsection{", # Now split by environments "\n\\begin{enumerate}", "\n\\begin{itemize}", "\n\\begin{description}", "\n\\begin{list}", "\n\\begin{quote}", "\n\\begin{quotation}", "\n\\begin{verse}", "\n\\begin{verbatim}", ## Now split by math environments "\n\\begin{align}", "$$", "$", # Now split by the normal type of lines " ", "", ]
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
e4fee00b7c77-9
# Now split by the normal type of lines " ", "", ] super().__init__(separators=separators, **kwargs) [docs]class PythonCodeTextSplitter(RecursiveCharacterTextSplitter): """Attempts to split the text along Python syntax.""" def __init__(self, **kwargs: Any): """Initialize a MarkdownTextSplitter.""" separators = [ # First, try to split along class definitions "\nclass ", "\ndef ", "\n\tdef ", # Now split by the normal type of lines "\n\n", "\n", " ", "", ] super().__init__(separators=separators, **kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/text_splitter.html
b62758071a62-0
Source code for langchain.requests """Lightweight wrapper around requests library, with async support.""" from contextlib import asynccontextmanager from typing import Any, AsyncGenerator, Dict, Optional import aiohttp import requests from pydantic import BaseModel, Extra class Requests(BaseModel): """Wrapper around requests to handle auth and async. The main purpose of this wrapper is to handle authentication (by saving headers) and enable easy async methods on the same base object. """ headers: Optional[Dict[str, str]] = None aiosession: Optional[aiohttp.ClientSession] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True def get(self, url: str, **kwargs: Any) -> requests.Response: """GET the URL and return the text.""" return requests.get(url, headers=self.headers, **kwargs) def post(self, url: str, data: Dict[str, Any], **kwargs: Any) -> requests.Response: """POST to the URL and return the text.""" return requests.post(url, json=data, headers=self.headers, **kwargs) def patch(self, url: str, data: Dict[str, Any], **kwargs: Any) -> requests.Response: """PATCH the URL and return the text.""" return requests.patch(url, json=data, headers=self.headers, **kwargs) def put(self, url: str, data: Dict[str, Any], **kwargs: Any) -> requests.Response: """PUT the URL and return the text.""" return requests.put(url, json=data, headers=self.headers, **kwargs) def delete(self, url: str, **kwargs: Any) -> requests.Response:
https://python.langchain.com/en/latest/_modules/langchain/requests.html
b62758071a62-1
def delete(self, url: str, **kwargs: Any) -> requests.Response: """DELETE the URL and return the text.""" return requests.delete(url, headers=self.headers, **kwargs) @asynccontextmanager async def _arequest( self, method: str, url: str, **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: """Make an async request.""" if not self.aiosession: async with aiohttp.ClientSession() as session: async with session.request( method, url, headers=self.headers, **kwargs ) as response: yield response else: async with self.aiosession.request( method, url, headers=self.headers, **kwargs ) as response: yield response @asynccontextmanager async def aget( self, url: str, **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: """GET the URL and return the text asynchronously.""" async with self._arequest("GET", url, **kwargs) as response: yield response @asynccontextmanager async def apost( self, url: str, data: Dict[str, Any], **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: """POST to the URL and return the text asynchronously.""" async with self._arequest("POST", url, **kwargs) as response: yield response @asynccontextmanager async def apatch( self, url: str, data: Dict[str, Any], **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: """PATCH the URL and return the text asynchronously."""
https://python.langchain.com/en/latest/_modules/langchain/requests.html
b62758071a62-2
"""PATCH the URL and return the text asynchronously.""" async with self._arequest("PATCH", url, **kwargs) as response: yield response @asynccontextmanager async def aput( self, url: str, data: Dict[str, Any], **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: """PUT the URL and return the text asynchronously.""" async with self._arequest("PUT", url, **kwargs) as response: yield response @asynccontextmanager async def adelete( self, url: str, **kwargs: Any ) -> AsyncGenerator[aiohttp.ClientResponse, None]: """DELETE the URL and return the text asynchronously.""" async with self._arequest("DELETE", url, **kwargs) as response: yield response [docs]class TextRequestsWrapper(BaseModel): """Lightweight wrapper around requests library. The main purpose of this wrapper is to always return a text output. """ headers: Optional[Dict[str, str]] = None aiosession: Optional[aiohttp.ClientSession] = None class Config: """Configuration for this pydantic object.""" extra = Extra.forbid arbitrary_types_allowed = True @property def requests(self) -> Requests: return Requests(headers=self.headers, aiosession=self.aiosession) [docs] def get(self, url: str, **kwargs: Any) -> str: """GET the URL and return the text.""" return self.requests.get(url, **kwargs).text [docs] def post(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str: """POST to the URL and return the text."""
https://python.langchain.com/en/latest/_modules/langchain/requests.html
b62758071a62-3
"""POST to the URL and return the text.""" return self.requests.post(url, data, **kwargs).text [docs] def patch(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str: """PATCH the URL and return the text.""" return self.requests.patch(url, data, **kwargs).text [docs] def put(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str: """PUT the URL and return the text.""" return self.requests.put(url, data, **kwargs).text [docs] def delete(self, url: str, **kwargs: Any) -> str: """DELETE the URL and return the text.""" return self.requests.delete(url, **kwargs).text [docs] async def aget(self, url: str, **kwargs: Any) -> str: """GET the URL and return the text asynchronously.""" async with self.requests.aget(url, **kwargs) as response: return await response.text() [docs] async def apost(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str: """POST to the URL and return the text asynchronously.""" async with self.requests.apost(url, **kwargs) as response: return await response.text() [docs] async def apatch(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str: """PATCH the URL and return the text asynchronously.""" async with self.requests.apatch(url, **kwargs) as response: return await response.text() [docs] async def aput(self, url: str, data: Dict[str, Any], **kwargs: Any) -> str:
https://python.langchain.com/en/latest/_modules/langchain/requests.html
b62758071a62-4
"""PUT the URL and return the text asynchronously.""" async with self.requests.aput(url, **kwargs) as response: return await response.text() [docs] async def adelete(self, url: str, **kwargs: Any) -> str: """DELETE the URL and return the text asynchronously.""" async with self.requests.adelete(url, **kwargs) as response: return await response.text() # For backwards compatibility RequestsWrapper = TextRequestsWrapper By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/requests.html
a65302edb897-0
Source code for langchain.document_loaders.directory """Loading logic for loading documents from a directory.""" import logging from pathlib import Path from typing import List, Type, Union from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders.html_bs import BSHTMLLoader from langchain.document_loaders.text import TextLoader from langchain.document_loaders.unstructured import UnstructuredFileLoader FILE_LOADER_TYPE = Union[ Type[UnstructuredFileLoader], Type[TextLoader], Type[BSHTMLLoader] ] logger = logging.getLogger(__name__) def _is_visible(p: Path) -> bool: parts = p.parts for _p in parts: if _p.startswith("."): return False return True [docs]class DirectoryLoader(BaseLoader): """Loading logic for loading documents from a directory.""" def __init__( self, path: str, glob: str = "**/[!.]*", silent_errors: bool = False, load_hidden: bool = False, loader_cls: FILE_LOADER_TYPE = UnstructuredFileLoader, loader_kwargs: Union[dict, None] = None, recursive: bool = False, show_progress: bool = False, ): """Initialize with path to directory and how to glob over it.""" if loader_kwargs is None: loader_kwargs = {} self.path = path self.glob = glob self.load_hidden = load_hidden self.loader_cls = loader_cls self.loader_kwargs = loader_kwargs self.silent_errors = silent_errors self.recursive = recursive self.show_progress = show_progress [docs] def load(self) -> List[Document]: """Load documents."""
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html
a65302edb897-1
[docs] def load(self) -> List[Document]: """Load documents.""" p = Path(self.path) docs = [] items = list(p.rglob(self.glob) if self.recursive else p.glob(self.glob)) pbar = None if self.show_progress: try: from tqdm import tqdm pbar = tqdm(total=len(items)) except ImportError as e: logger.warning( "To log the progress of DirectoryLoader you need to install tqdm, " "`pip install tqdm`" ) if self.silent_errors: logger.warning(e) else: raise e for i in items: if i.is_file(): if _is_visible(i.relative_to(p)) or self.load_hidden: try: sub_docs = self.loader_cls(str(i), **self.loader_kwargs).load() docs.extend(sub_docs) except Exception as e: if self.silent_errors: logger.warning(e) else: raise e finally: if pbar: pbar.update(1) if pbar: pbar.close() return docs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/directory.html
bf3694ef718e-0
Source code for langchain.document_loaders.s3_directory """Loading logic for loading documents from an s3 directory.""" from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders.s3_file import S3FileLoader [docs]class S3DirectoryLoader(BaseLoader): """Loading logic for loading documents from s3.""" def __init__(self, bucket: str, prefix: str = ""): """Initialize with bucket and key name.""" self.bucket = bucket self.prefix = prefix [docs] def load(self) -> List[Document]: """Load documents.""" try: import boto3 except ImportError: raise ValueError( "Could not import boto3 python package. " "Please install it with `pip install boto3`." ) s3 = boto3.resource("s3") bucket = s3.Bucket(self.bucket) docs = [] for obj in bucket.objects.filter(Prefix=self.prefix): loader = S3FileLoader(self.bucket, obj.key) docs.extend(loader.load()) return docs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/s3_directory.html
854d2d929986-0
Source code for langchain.document_loaders.telegram """Loader that loads Telegram chat json dump.""" import json from pathlib import Path from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader def concatenate_rows(row: dict) -> str: """Combine message information in a readable format ready to be used.""" date = row["date"] sender = row["from"] text = row["text"] return f"{sender} on {date}: {text}\n\n" [docs]class TelegramChatLoader(BaseLoader): """Loader that loads Telegram chat json directory dump.""" def __init__(self, path: str): """Initialize with path.""" self.file_path = path [docs] def load(self) -> List[Document]: """Load documents.""" try: import pandas as pd except ImportError: raise ValueError( "pandas is needed for Telegram loader, " "please install with `pip install pandas`" ) p = Path(self.file_path) with open(p, encoding="utf8") as f: d = json.load(f) normalized_messages = pd.json_normalize(d["messages"]) df_normalized_messages = pd.DataFrame(normalized_messages) # Only keep plain text messages (no services, links, hashtags, code, bold...) df_filtered = df_normalized_messages[ (df_normalized_messages.type == "message") & (df_normalized_messages.text.apply(lambda x: type(x) == str)) ] df_filtered = df_filtered[["date", "text", "from"]] text = df_filtered.apply(concatenate_rows, axis=1).str.cat(sep="") metadata = {"source": str(p)}
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
854d2d929986-1
metadata = {"source": str(p)} return [Document(page_content=text, metadata=metadata)] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
3d547963749d-0
Source code for langchain.document_loaders.rtf """Loader that loads rich text files.""" from typing import Any, List from langchain.document_loaders.unstructured import ( UnstructuredFileLoader, satisfies_min_unstructured_version, ) [docs]class UnstructuredRTFLoader(UnstructuredFileLoader): """Loader that uses unstructured to load rtf files.""" def __init__( self, file_path: str, mode: str = "single", **unstructured_kwargs: Any ): min_unstructured_version = "0.5.12" if not satisfies_min_unstructured_version(min_unstructured_version): raise ValueError( "Partitioning rtf files is only supported in " f"unstructured>={min_unstructured_version}." ) super().__init__(file_path=file_path, mode=mode, **unstructured_kwargs) def _get_elements(self) -> List: from unstructured.partition.rtf import partition_rtf return partition_rtf(filename=self.file_path, **self.unstructured_kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/rtf.html
20d968fa761f-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 from pydantic import root_validator from pydantic.dataclasses import dataclass from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader logger = logging.getLogger(__name__) SCOPES = ["https://www.googleapis.com/auth/youtube.readonly"] [docs]@dataclass class GoogleApiClient: """A Generic Google Api Client. To use, you should have the ``google_auth_oauthlib,youtube_transcript_api,google`` python package installed. As the google api expects credentials you need to set up a google account and 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") ) """ credentials_path: Path = Path.home() / ".credentials" / "credentials.json" service_account_path: Path = Path.home() / ".credentials" / "credentials.json" token_path: Path = Path.home() / ".credentials" / "token.json" def __post_init__(self) -> None: self.creds = self._load_credentials() [docs] @root_validator def validate_channel_or_videoIds_is_set( cls, values: Dict[str, Any] ) -> 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(
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html
20d968fa761f-1
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 def _load_credentials(self) -> Any: """Load credentials.""" # Adapted from https://developers.google.com/drive/api/v3/quickstart/python try: from google.auth.transport.requests import Request from google.oauth2 import service_account from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from youtube_transcript_api import YouTubeTranscriptApi # noqa: F401 except ImportError: raise ImportError( "You must run" "`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(): return service_account.Credentials.from_service_account_file( str(self.service_account_path) ) if self.token_path.exists(): creds = Credentials.from_authorized_user_file(str(self.token_path), SCOPES) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( str(self.credentials_path), SCOPES ) creds = flow.run_local_server(port=0) with open(self.token_path, "w") as token: token.write(creds.to_json()) return creds [docs]class YoutubeLoader(BaseLoader): """Loader that loads Youtube transcripts.""" def __init__(
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html
20d968fa761f-2
"""Loader that loads Youtube transcripts.""" def __init__( self, video_id: str, add_video_info: bool = False, language: str = "en", continue_on_failure: bool = False, ): """Initialize with YouTube video ID.""" self.video_id = video_id self.add_video_info = add_video_info self.language = language self.continue_on_failure = continue_on_failure [docs] @classmethod def from_youtube_url(cls, youtube_url: str, **kwargs: Any) -> YoutubeLoader: """Given youtube URL, load video.""" video_id = youtube_url.split("youtube.com/watch?v=")[-1] return cls(video_id, **kwargs) [docs] def load(self) -> List[Document]: """Load documents.""" try: from youtube_transcript_api import ( NoTranscriptFound, TranscriptsDisabled, YouTubeTranscriptApi, ) except ImportError: raise ImportError( "Could not import youtube_transcript_api python package. " "Please install it with `pip install youtube-transcript-api`." ) metadata = {"source": self.video_id} if self.add_video_info: # Get more video meta info # Such as title, description, thumbnail url, publish_date video_info = self._get_video_info() metadata.update(video_info) 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_transcript(["en"])
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html
20d968fa761f-3
en_transcript = transcript_list.find_transcript(["en"]) transcript = en_transcript.translate(self.language) transcript_pieces = transcript.fetch() transcript = " ".join([t["text"].strip(" ") for t in transcript_pieces]) return [Document(page_content=transcript, metadata=metadata)] def _get_video_info(self) -> dict: """Get important video information. Components are: - title - description - thumbnail url, - publish_date - channel_author - and more. """ try: from pytube import YouTube 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, "description": yt.description, "view_count": yt.views, "thumbnail_url": yt.thumbnail_url, "publish_date": yt.publish_date, "length": yt.length, "author": yt.author, } return video_info [docs]@dataclass 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 have to either provide a channel name or a list of videoids "https://developers.google.com/docs/api/quickstart/python" Example: .. code-block:: python from langchain.document_loaders import GoogleApiClient
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html
20d968fa761f-4
.. code-block:: python from langchain.document_loaders import GoogleApiClient from langchain.document_loaders import GoogleApiYoutubeLoader google_api_client = GoogleApiClient( service_account_path=Path("path_to_your_sec_file.json") ) loader = GoogleApiYoutubeLoader( google_api_client=google_api_client, channel_name = "CodeAesthetic" ) 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_client = self._build_youtube_client(self.google_api_client.creds) def _build_youtube_client(self, creds: Any) -> Any: try: from googleapiclient.discovery import build from youtube_transcript_api import YouTubeTranscriptApi # noqa: F401 except ImportError: raise ImportError( "You must run" "`pip install --upgrade " "google-api-python-client google-auth-httplib2 " "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]: """Validate that either folder_id or document_ids is set, but not both.""" if not values.get("channel_name") and not values.get("video_ids"):
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html
20d968fa761f-5
if not values.get("channel_name") and not values.get("video_ids"): raise ValueError("Must specify either channel_name or video_ids") return values def _get_transcripe_for_video_id(self, video_id: str) -> str: from youtube_transcript_api import NoTranscriptFound, YouTubeTranscriptApi transcript_list = YouTubeTranscriptApi.list_transcripts(video_id) 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 = transcript.fetch() return " ".join([t["text"].strip(" ") for t in transcript_pieces]) def _get_document_for_video_id(self, video_id: str, **kwargs: Any) -> Document: captions = self._get_transcripe_for_video_id(video_id) video_response = ( self.youtube_client.videos() .list( part="id,snippet", id=video_id, ) .execute() ) return Document( page_content=captions, metadata=video_response.get("items")[0], ) 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() channel_id = response["items"][0]["id"]["channelId"] return channel_id
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html
20d968fa761f-6
channel_id = response["items"][0]["id"]["channelId"] return channel_id def _get_document_for_channel(self, channel: str, **kwargs: Any) -> List[Document]: try: from youtube_transcript_api import ( NoTranscriptFound, TranscriptsDisabled, ) except ImportError: raise ImportError( "You must run" "`pip install --upgrade " "youtube-transcript-api`" "to use the youtube loader" ) 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: response = request.execute() # Add each video ID to the list for item in response["items"]: if not item["id"].get("videoId"): continue meta_data = {"videoId": item["id"]["videoId"]} if self.add_video_info: item["snippet"].pop("thumbnails") meta_data.update(item["snippet"]) try: page_content = self._get_transcripe_for_video_id( item["id"]["videoId"] ) video_ids.append( Document( page_content=page_content, metadata=meta_data, ) ) except (TranscriptsDisabled, NoTranscriptFound) as e: if self.continue_on_failure: logger.error( "Error fetching transscript " + f" {item['id']['videoId']}, exception: {e}" )
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html
20d968fa761f-7
) else: raise e pass request = self.youtube_client.search().list_next(request, response) return video_ids [docs] def load(self) -> List[Document]: """Load documents.""" document_list = [] if self.channel_name: document_list.extend(self._get_document_for_channel(self.channel_name)) elif self.video_ids: 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 By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html
171269e676c3-0
Source code for langchain.document_loaders.hn """Loader that loads HN.""" from typing import Any, List from langchain.docstore.document import Document from langchain.document_loaders.web_base import WebBaseLoader [docs]class HNLoader(WebBaseLoader): """Load Hacker News data from either main page results or the comments page.""" [docs] def load(self) -> List[Document]: """Get important HN webpage information. Components are: - title - content - source url, - time of post - author of the post - number of comments - rank of the post """ soup_info = self.scrape() if "item" in self.web_path: return self.load_comments(soup_info) else: return self.load_results(soup_info) [docs] def load_comments(self, soup_info: Any) -> List[Document]: """Load comments from a HN post.""" comments = soup_info.select("tr[class='athing comtr']") title = soup_info.select_one("tr[id='pagespace']").get("title") return [ Document( page_content=comment.text.strip(), metadata={"source": self.web_path, "title": title}, ) for comment in comments ] [docs] def load_results(self, soup: Any) -> List[Document]: """Load items from an HN page.""" items = soup.select("tr[class='athing']") documents = [] for lineItem in items: ranking = lineItem.select_one("span[class='rank']").text link = lineItem.find("span", {"class": "titleline"}).find("a").get("href")
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/hn.html
171269e676c3-1
title = lineItem.find("span", {"class": "titleline"}).text.strip() metadata = { "source": self.web_path, "title": title, "link": link, "ranking": ranking, } documents.append( Document( page_content=title, link=link, ranking=ranking, metadata=metadata ) ) return documents By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/hn.html
7c186e362c51-0
Source code for langchain.document_loaders.pdf """Loader that loads PDF files.""" import os import tempfile from abc import ABC from io import StringIO from typing import Any, List, Optional from urllib.parse import urlparse import requests from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders.unstructured import UnstructuredFileLoader [docs]class UnstructuredPDFLoader(UnstructuredFileLoader): """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. Defaults to check for local file, but if the file is a web path, it will download it to a temporary file, and use that, then clean up the temporary file after completion """ file_path: str web_path: Optional[str] = None def __init__(self, file_path: str): """Initialize with file path.""" self.file_path = file_path if "~" in self.file_path: self.file_path = os.path.expanduser(self.file_path) # If the file is a web path, download it to a temporary file, and use that 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 ) self.web_path = self.file_path self.temp_file = tempfile.NamedTemporaryFile()
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
7c186e362c51-1
self.web_path = self.file_path self.temp_file = tempfile.NamedTemporaryFile() self.temp_file.write(r.content) self.file_path = self.temp_file.name elif not os.path.isfile(self.file_path): raise ValueError("File path %s is not a valid file or url" % self.file_path) def __del__(self) -> None: if hasattr(self, "temp_file"): self.temp_file.close() @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) [docs]class OnlinePDFLoader(BasePDFLoader): """Loader that loads online PDFs.""" [docs] def load(self) -> List[Document]: """Load documents.""" loader = UnstructuredPDFLoader(str(self.file_path)) return loader.load() [docs]class PyPDFLoader(BasePDFLoader): """Loads a PDF with pypdf and chunks at character level. Loader also stores page numbers in metadatas. """ def __init__(self, file_path: str): """Initialize with file path.""" try: import pypdf # noqa:F401 except ImportError: raise ValueError( "pypdf package not found, please install it with " "`pip install pypdf`" ) super().__init__(file_path) [docs] def load(self) -> List[Document]: """Load given path as pages.""" import pypdf with open(self.file_path, "rb") as pdf_file_obj: pdf_reader = pypdf.PdfReader(pdf_file_obj) return [ Document(
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
7c186e362c51-2
return [ Document( page_content=page.extract_text(), metadata={"source": self.file_path, "page": i}, ) for i, page in enumerate(pdf_reader.pages) ] [docs]class PDFMinerLoader(BasePDFLoader): """Loader that uses PDFMiner to load PDF files.""" def __init__(self, file_path: str): """Initialize with file path.""" try: from pdfminer.high_level import extract_text # noqa:F401 except ImportError: raise ValueError( "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 import extract_text text = extract_text(self.file_path) metadata = {"source": self.file_path} return [Document(page_content=text, metadata=metadata)] [docs]class PDFMinerPDFasHTMLLoader(BasePDFLoader): """Loader that uses PDFMiner to load PDF files as HTML content.""" def __init__(self, file_path: str): """Initialize with file path.""" try: from pdfminer.high_level import extract_text_to_fp # noqa:F401 except ImportError: raise ValueError( "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 import extract_text_to_fp from pdfminer.layout import LAParams from pdfminer.utils import open_filename
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
7c186e362c51-3
from pdfminer.layout import LAParams from pdfminer.utils import open_filename output_string = StringIO() with open_filename(self.file_path, "rb") as fp: extract_text_to_fp( fp, # type: ignore[arg-type] output_string, codec="", laparams=LAParams(), output_type="html", ) metadata = {"source": self.file_path} return [Document(page_content=output_string.getvalue(), metadata=metadata)] [docs]class PyMuPDFLoader(BasePDFLoader): """Loader that uses PyMuPDF to load PDF files.""" def __init__(self, file_path: str): """Initialize with file path.""" try: import fitz # noqa:F401 except ImportError: raise ValueError( "PyMuPDF package not found, please install it with " "`pip install pymupdf`" ) super().__init__(file_path) [docs] def load(self, **kwargs: Optional[Any]) -> List[Document]: """Load file.""" import fitz doc = fitz.open(self.file_path) # open document file_path = self.file_path if self.web_path is None else self.web_path return [ Document( page_content=page.get_text(**kwargs).encode("utf-8"), metadata=dict( { "source": file_path, "file_path": file_path, "page_number": page.number + 1, "total_pages": len(doc), }, **{ k: doc.metadata[k] for k in doc.metadata if type(doc.metadata[k]) in [str, int] } ),
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
7c186e362c51-4
if type(doc.metadata[k]) in [str, int] } ), ) for page in doc ] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
6ae3e2faf4a0-0
Source code for langchain.document_loaders.conllu """Load CoNLL-U files.""" import csv from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class CoNLLULoader(BaseLoader): """Load CoNLL-U files.""" def __init__(self, file_path: str): """Initialize with file path.""" self.file_path = file_path [docs] def load(self) -> List[Document]: """Load from file path.""" with open(self.file_path, encoding="utf8") as f: tsv = list(csv.reader(f, delimiter="\t")) # If len(line) > 1, the line is not a comment lines = [line for line in tsv if len(line) > 1] text = "" for i, line in enumerate(lines): # Do not add a space after a punctuation mark or at the end of the sentence if line[9] == "SpaceAfter=No" or i == len(lines) - 1: text += line[1] else: text += line[1] + " " metadata = {"source": self.file_path} return [Document(page_content=text, metadata=metadata)] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/conllu.html
0e4ead873d92-0
Source code for langchain.document_loaders.markdown """Loader that loads Markdown files.""" from typing import List from langchain.document_loaders.unstructured import UnstructuredFileLoader [docs]class UnstructuredMarkdownLoader(UnstructuredFileLoader): """Loader that uses unstructured to load markdown files.""" def _get_elements(self) -> List: from unstructured.__version__ import __version__ as __unstructured_version__ from unstructured.partition.md import partition_md # NOTE(MthwRobinson) - enables the loader to work when you're using pre-release # versions of unstructured like 0.4.17-dev1 _unstructured_version = __unstructured_version__.split("-")[0] unstructured_version = tuple([int(x) for x in _unstructured_version.split(".")]) if unstructured_version < (0, 4, 16): raise ValueError( f"You are on unstructured version {__unstructured_version__}. " "Partitioning markdown files is only supported in unstructured>=0.4.16." ) return partition_md(filename=self.file_path, **self.unstructured_kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/markdown.html
352723a7da3b-0
Source code for langchain.document_loaders.image_captions """ Loader that 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 import Document from langchain.document_loaders.base import BaseLoader [docs]class ImageCaptionLoader(BaseLoader): """Loader that loads the captions of an image""" def __init__( self, path_images: Union[str, List[str]], blip_processor: str = "Salesforce/blip-image-captioning-base", blip_model: str = "Salesforce/blip-image-captioning-base", ): """ Initialize with a list of image paths """ if isinstance(path_images, str): self.image_paths = [path_images] else: self.image_paths = path_images self.blip_processor = blip_processor self.blip_model = blip_model [docs] def load(self) -> List[Document]: """ Load from a list of image files """ try: from transformers import BlipForConditionalGeneration, BlipProcessor except ImportError: raise ValueError( "transformers package not found, please install with" "`pip install transformers`" ) processor = BlipProcessor.from_pretrained(self.blip_processor) 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 )
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html
352723a7da3b-1
model=model, processor=processor, path_image=path_image ) doc = Document(page_content=caption, metadata=metadata) results.append(doc) return results def _get_captions_and_metadata( self, model: Any, processor: Any, path_image: str ) -> Tuple[str, dict]: """ Helper function for getting the captions and metadata of an image """ try: from PIL import Image except ImportError: raise ValueError( "PIL package not found, please install with `pip install pillow`" ) try: if path_image.startswith("http://") or path_image.startswith("https://"): image = Image.open(requests.get(path_image, stream=True).raw).convert( "RGB" ) else: image = Image.open(path_image).convert("RGB") except Exception: raise ValueError(f"Could not get image data for {path_image}") inputs = processor(image, "an image of", return_tensors="pt") output = model.generate(**inputs) caption: str = processor.decode(output[0]) metadata: dict = {"image_path": path_image} return caption, metadata By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/image_captions.html
10213a5d109b-0
Source code for langchain.document_loaders.url """Loader that uses unstructured to load HTML files.""" import logging from typing import Any, List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader logger = logging.getLogger(__name__) [docs]class UnstructuredURLLoader(BaseLoader): """Loader that uses unstructured to load HTML files.""" def __init__( self, urls: List[str], continue_on_failure: bool = True, **unstructured_kwargs: Any, ): """Initialize with file path.""" try: import unstructured # noqa:F401 from unstructured.__version__ import __version__ as __unstructured_version__ self.__version = __unstructured_version__ except ImportError: raise ValueError( "unstructured package not found, please install it with " "`pip install unstructured`" ) headers = unstructured_kwargs.pop("headers", {}) if len(headers.keys()) != 0: warn_about_headers = False if self.__is_non_html_available(): warn_about_headers = not self.__is_headers_available_for_non_html() else: warn_about_headers = not self.__is_headers_available_for_html() if warn_about_headers: logger.warning( "You are using an old version of unstructured. " "The headers parameter is ignored" ) self.urls = urls self.continue_on_failure = continue_on_failure self.headers = headers self.unstructured_kwargs = unstructured_kwargs def __is_headers_available_for_html(self) -> bool: _unstructured_version = self.__version.split("-")[0]
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html
10213a5d109b-1
_unstructured_version = self.__version.split("-")[0] unstructured_version = tuple([int(x) for x in _unstructured_version.split(".")]) return unstructured_version >= (0, 5, 7) def __is_headers_available_for_non_html(self) -> bool: _unstructured_version = self.__version.split("-")[0] unstructured_version = tuple([int(x) for x in _unstructured_version.split(".")]) return unstructured_version >= (0, 5, 13) def __is_non_html_available(self) -> bool: _unstructured_version = self.__version.split("-")[0] unstructured_version = tuple([int(x) for x in _unstructured_version.split(".")]) return unstructured_version >= (0, 5, 12) [docs] def load(self) -> List[Document]: """Load file.""" from unstructured.partition.auto import partition from unstructured.partition.html import partition_html docs: List[Document] = list() for url in self.urls: try: if self.__is_non_html_available(): if self.__is_headers_available_for_non_html(): elements = partition( url=url, headers=self.headers, **self.unstructured_kwargs ) else: elements = partition(url=url, **self.unstructured_kwargs) else: if self.__is_headers_available_for_html(): elements = partition_html( url=url, headers=self.headers, **self.unstructured_kwargs ) else: elements = partition_html(url=url, **self.unstructured_kwargs) except Exception as e: if self.continue_on_failure:
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html
10213a5d109b-2
except Exception as e: if self.continue_on_failure: logger.error(f"Error fetching or processing {url}, exeption: {e}") continue else: raise e text = "\n\n".join([str(el) for el in elements]) metadata = {"source": url} docs.append(Document(page_content=text, metadata=metadata)) return docs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html
cfc6b3852b6b-0
Source code for langchain.document_loaders.gcs_file """Loading logic for loading documents from a GCS file.""" import os import tempfile from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders.unstructured import UnstructuredFileLoader [docs]class GCSFileLoader(BaseLoader): """Loading logic for loading documents from GCS.""" def __init__(self, project_name: str, bucket: str, blob: str): """Initialize with bucket and key name.""" self.bucket = bucket self.blob = blob self.project_name = project_name [docs] def load(self) -> List[Document]: """Load documents.""" try: from google.cloud import storage except ImportError: raise ValueError( "Could not import google-cloud-storage python package. " "Please install it with `pip install google-cloud-storage`." ) # Initialise a client storage_client = storage.Client(self.project_name) # Create a bucket object for our bucket bucket = storage_client.get_bucket(self.bucket) # Create a blob object from the filepath blob = bucket.blob(self.blob) with tempfile.TemporaryDirectory() as temp_dir: file_path = f"{temp_dir}/{self.blob}" os.makedirs(os.path.dirname(file_path), exist_ok=True) # Download the file to a destination blob.download_to_filename(file_path) loader = UnstructuredFileLoader(file_path) return loader.load() By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_file.html
24b65ea2e2cf-0
Source code for langchain.document_loaders.unstructured """Loader that uses unstructured to load files.""" from abc import ABC, abstractmethod from typing import IO, Any, List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader def satisfies_min_unstructured_version(min_version: str) -> bool: """Checks to see if the installed unstructured version exceeds the minimum version for the feature in question.""" from unstructured.__version__ import __version__ as __unstructured_version__ min_version_tuple = tuple([int(x) for x in min_version.split(".")]) # NOTE(MthwRobinson) - enables the loader to work when you're using pre-release # versions of unstructured like 0.4.17-dev1 _unstructured_version = __unstructured_version__.split("-")[0] unstructured_version_tuple = tuple( [int(x) for x in _unstructured_version.split(".")] ) return unstructured_version_tuple >= min_version_tuple class UnstructuredBaseLoader(BaseLoader, ABC): """Loader that uses unstructured to load files.""" def __init__(self, mode: str = "single", **unstructured_kwargs: Any): """Initialize with file path.""" try: import unstructured # noqa:F401 except ImportError: raise ValueError( "unstructured package not found, please install it with " "`pip install unstructured`" ) _valid_modes = {"single", "elements"} if mode not in _valid_modes: raise ValueError( f"Got {mode} for `mode`, but should be one of `{_valid_modes}`" ) self.mode = mode
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html
24b65ea2e2cf-1
) self.mode = mode if not satisfies_min_unstructured_version("0.5.4"): if "strategy" in unstructured_kwargs: unstructured_kwargs.pop("strategy") self.unstructured_kwargs = unstructured_kwargs @abstractmethod def _get_elements(self) -> List: """Get elements.""" @abstractmethod def _get_metadata(self) -> dict: """Get metadata.""" def load(self) -> List[Document]: """Load file.""" elements = self._get_elements() if self.mode == "elements": docs: List[Document] = list() for element in elements: metadata = self._get_metadata() # NOTE(MthwRobinson) - the attribute check is for backward compatibility # with unstructured<0.4.9. The metadata attributed was added in 0.4.9. if hasattr(element, "metadata"): metadata.update(element.metadata.to_dict()) if hasattr(element, "category"): metadata["category"] = element.category docs.append(Document(page_content=str(element), metadata=metadata)) elif self.mode == "single": metadata = self._get_metadata() text = "\n\n".join([str(el) for el in elements]) docs = [Document(page_content=text, metadata=metadata)] else: raise ValueError(f"mode of {self.mode} not supported.") return docs [docs]class UnstructuredFileLoader(UnstructuredBaseLoader): """Loader that uses unstructured to load files.""" def __init__( self, file_path: str, mode: str = "single", **unstructured_kwargs: Any ): """Initialize with file path.""" self.file_path = file_path
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html
24b65ea2e2cf-2
): """Initialize with file path.""" self.file_path = file_path super().__init__(mode=mode, **unstructured_kwargs) def _get_elements(self) -> List: from unstructured.partition.auto import partition return partition(filename=self.file_path, **self.unstructured_kwargs) def _get_metadata(self) -> dict: return {"source": self.file_path} [docs]class UnstructuredFileIOLoader(UnstructuredBaseLoader): """Loader that uses unstructured to load file IO objects.""" def __init__(self, file: IO, mode: str = "single", **unstructured_kwargs: Any): """Initialize with file path.""" self.file = file super().__init__(mode=mode, **unstructured_kwargs) def _get_elements(self) -> List: from unstructured.partition.auto import partition return partition(file=self.file, **self.unstructured_kwargs) def _get_metadata(self) -> dict: return {} By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html
988b8eafa250-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 loads College Confidential webpages.""" [docs] def load(self) -> List[Document]: """Load webpage.""" soup = self.scrape() text = soup.select_one("main[class='skin-handler']").text metadata = {"source": self.web_path} return [Document(page_content=text, metadata=metadata)] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/college_confidential.html
2bfb79517896-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 in a readable format ready to be used.""" return f"{sender} on {date}: {text}\n\n" [docs]class WhatsAppChatLoader(BaseLoader): """Loader that loads WhatsApp messages text file.""" def __init__(self, path: str): """Initialize with path.""" self.file_path = path [docs] def load(self) -> List[Document]: """Load documents.""" p = Path(self.file_path) text_content = "" with open(p, encoding="utf8") as f: lines = f.readlines() message_line_regex = ( r"(\d{1,2}/\d{1,2}/\d{2,4}, " r"\d{1,2}:\d{1,2}[ _]?(?:AM|PM)?) - " r"(.*?): (.*)" ) for line in lines: result = re.match( message_line_regex, line.strip(), ) if result: date, sender, text = result.groups() text_content += concatenate_rows(date, sender, text) metadata = {"source": str(p)} return [Document(page_content=text_content, metadata=metadata)] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/whatsapp_chat.html
fe784d934cc2-0
Source code for langchain.document_loaders.bigquery from typing import List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class BigQueryLoader(BaseLoader): """Loads a query result from BigQuery into a list of documents. Each document represents one row of the result. The `page_content_columns` are written into the `page_content` of the document. The `metadata_columns` are written into the `metadata` of the document. By default, all columns are written into the `page_content` and none into the `metadata`. """ def __init__( self, query: str, project: Optional[str] = None, page_content_columns: Optional[List[str]] = None, metadata_columns: Optional[List[str]] = None, ): self.query = query self.project = project self.page_content_columns = page_content_columns self.metadata_columns = metadata_columns [docs] def load(self) -> List[Document]: try: from google.cloud import bigquery except ImportError as ex: raise ValueError( "Could not import google-cloud-bigquery python package. " "Please install it with `pip install google-cloud-bigquery`." ) from ex bq_client = bigquery.Client(self.project) query_result = bq_client.query(self.query).result() docs: List[Document] = [] page_content_columns = self.page_content_columns metadata_columns = self.metadata_columns if page_content_columns is None: page_content_columns = [column.name for column in query_result.schema] if metadata_columns is None: metadata_columns = [] for row in query_result:
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html
fe784d934cc2-1
metadata_columns = [] for row in query_result: page_content = "\n".join( f"{k}: {v}" for k, v in row.items() if k in page_content_columns ) metadata = {k: v for k, v in row.items() if k in metadata_columns} doc = Document(page_content=page_content, metadata=metadata) docs.append(doc) return docs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html
6c553c8e1fe3-0
Source code for langchain.document_loaders.url_selenium """Loader that uses Selenium to load a page, then uses unstructured to load the html. """ import logging from typing import TYPE_CHECKING, List, Literal, Optional, Union if TYPE_CHECKING: from selenium.webdriver import Chrome, Firefox from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader logger = logging.getLogger(__name__) [docs]class SeleniumURLLoader(BaseLoader): """Loader that uses Selenium and to load a page and unstructured to load the html. This is useful for loading pages that require javascript to render. Attributes: urls (List[str]): List of URLs to load. continue_on_failure (bool): If True, continue loading other URLs on failure. browser (str): The browser to use, either 'chrome' or 'firefox'. executable_path (Optional[str]): The path to the browser executable. headless (bool): If True, the browser will run in headless mode. """ def __init__( self, urls: List[str], continue_on_failure: bool = True, browser: Literal["chrome", "firefox"] = "chrome", executable_path: Optional[str] = None, headless: bool = True, ): """Load a list of URLs using Selenium and unstructured.""" try: import selenium # noqa:F401 except ImportError: raise ValueError( "selenium package not found, please install it with " "`pip install selenium`" ) try: import unstructured # noqa:F401 except ImportError: raise ValueError( "unstructured package not found, please install it with "
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html
6c553c8e1fe3-1
raise ValueError( "unstructured package not found, please install it with " "`pip install unstructured`" ) self.urls = urls self.continue_on_failure = continue_on_failure self.browser = browser self.executable_path = executable_path self.headless = headless def _get_driver(self) -> Union["Chrome", "Firefox"]: """Create and return a WebDriver instance based on the specified browser. Raises: ValueError: If an invalid browser is specified. Returns: Union[Chrome, Firefox]: A WebDriver instance for the specified browser. """ if self.browser.lower() == "chrome": from selenium.webdriver import Chrome from selenium.webdriver.chrome.options import Options as ChromeOptions chrome_options = ChromeOptions() if self.headless: chrome_options.add_argument("--headless") if self.executable_path is None: return Chrome(options=chrome_options) return Chrome(executable_path=self.executable_path, options=chrome_options) elif self.browser.lower() == "firefox": from selenium.webdriver import Firefox from selenium.webdriver.firefox.options import Options as FirefoxOptions firefox_options = FirefoxOptions() if self.headless: firefox_options.add_argument("--headless") if self.executable_path is None: return Firefox(options=firefox_options) return Firefox( executable_path=self.executable_path, options=firefox_options ) else: raise ValueError("Invalid browser specified. Use 'chrome' or 'firefox'.") [docs] def load(self) -> List[Document]: """Load the specified URLs using Selenium and create Document instances. Returns: List[Document]: A list of Document instances with loaded content. """
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html
6c553c8e1fe3-2
List[Document]: A list of Document instances with loaded content. """ from unstructured.partition.html import partition_html docs: List[Document] = list() driver = self._get_driver() for url in self.urls: try: driver.get(url) page_content = driver.page_source elements = partition_html(text=page_content) text = "\n\n".join([str(el) for el in elements]) metadata = {"source": url} docs.append(Document(page_content=text, metadata=metadata)) except Exception as e: if self.continue_on_failure: logger.error(f"Error fetching or processing {url}, exception: {e}") else: raise e driver.quit() return docs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html
b935c0af70d4-0
Source code for langchain.document_loaders.notebook """Loader that 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 def concatenate_cells( cell: dict, include_outputs: bool, max_output_length: int, traceback: bool ) -> str: """Combine cells information in a readable format ready to be used.""" cell_type = cell["cell_type"] source = cell["source"] output = cell["outputs"] if include_outputs and cell_type == "code" and output: if "ename" in output[0].keys(): error_name = output[0]["ename"] error_value = output[0]["evalue"] if traceback: traceback = output[0]["traceback"] return ( f"'{cell_type}' cell: '{source}'\n, gives error '{error_name}'," f" with description '{error_value}'\n" f"and traceback '{traceback}'\n\n" ) else: return ( f"'{cell_type}' cell: '{source}'\n, gives error '{error_name}'," f"with description '{error_value}'\n\n" ) elif output[0]["output_type"] == "stream": 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"
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html
b935c0af70d4-1
return f"'{cell_type}' cell: '{source}'\n\n" return "" def remove_newlines(x: Any) -> Any: """Remove recursively newlines, no matter the data structure they are stored in.""" import pandas as pd if isinstance(x, str): return x.replace("\n", "") elif isinstance(x, list): return [remove_newlines(elem) for elem in x] elif isinstance(x, pd.DataFrame): return x.applymap(remove_newlines) else: return x [docs]class NotebookLoader(BaseLoader): """Loader that loads .ipynb notebook files.""" def __init__( self, path: str, include_outputs: bool = False, max_output_length: int = 10, remove_newline: bool = False, traceback: bool = False, ): """Initialize with path.""" 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 documents.""" try: import pandas as pd except ImportError: raise ValueError( "pandas is needed for Notebook Loader, " "please install with `pip install pandas`" ) p = Path(self.file_path) with open(p, encoding="utf8") as f: d = json.load(f) data = pd.json_normalize(d["cells"]) filtered_data = data[["cell_type", "source", "outputs"]] if self.remove_newline:
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html
b935c0af70d4-2
if self.remove_newline: filtered_data = filtered_data.applymap(remove_newlines) text = filtered_data.apply( lambda x: concatenate_cells( x, self.include_outputs, self.max_output_length, self.traceback ), axis=1, ).str.cat(sep=" ") metadata = {"source": str(p)} return [Document(page_content=text, metadata=metadata)] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notebook.html
cfa1e5f1e5d5-0
Source code for langchain.document_loaders.apify_dataset """Logic for loading documents from Apify datasets.""" from typing import Any, Callable, Dict, List from pydantic import BaseModel, root_validator from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class ApifyDatasetLoader(BaseLoader, BaseModel): """Logic for loading documents from Apify datasets.""" apify_client: Any dataset_id: str """The ID of the dataset on the Apify platform.""" dataset_mapping_function: Callable[[Dict], Document] """A custom function that takes a single dictionary (an Apify dataset item) and converts it to an instance of the Document class.""" def __init__( self, dataset_id: str, dataset_mapping_function: Callable[[Dict], Document] ): """Initialize the loader with an Apify dataset ID and a mapping function. Args: dataset_id (str): The ID of the dataset on the Apify platform. dataset_mapping_function (Callable): A function that takes a single dictionary (an Apify dataset item) and converts it to an instance of the Document class. """ super().__init__( dataset_id=dataset_id, dataset_mapping_function=dataset_mapping_function ) @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate environment.""" try: from apify_client import ApifyClient values["apify_client"] = ApifyClient() except ImportError: raise ValueError( "Could not import apify-client Python package. " "Please install it with `pip install apify-client`." ) return values
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/apify_dataset.html
cfa1e5f1e5d5-1
) return values [docs] def load(self) -> List[Document]: """Load documents.""" dataset_items = self.apify_client.dataset(self.dataset_id).list_items().items return list(map(self.dataset_mapping_function, dataset_items)) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/apify_dataset.html
8bf8df6bd4df-0
Source code for langchain.document_loaders.airbyte_json """Loader that loads local airbyte json files.""" import json from typing import Any, List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader def _stringify_value(val: Any) -> str: if isinstance(val, str): return val elif isinstance(val, dict): return "\n" + _stringify_dict(val) elif isinstance(val, list): return "\n".join(_stringify_value(v) for v in val) else: return str(val) def _stringify_dict(data: dict) -> str: text = "" for key, value in data.items(): text += key + ": " + _stringify_value(data[key]) + "\n" return text [docs]class AirbyteJSONLoader(BaseLoader): """Loader that loads local airbyte json files.""" def __init__(self, file_path: str): """Initialize with file path. This should start with '/tmp/airbyte_local/'.""" self.file_path = file_path [docs] def load(self) -> List[Document]: """Load file.""" text = "" for line in open(self.file_path, "r"): data = json.loads(line)["_airbyte_data"] text += _stringify_dict(data) metadata = {"source": self.file_path} return [Document(page_content=text, metadata=metadata)] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte_json.html
33663f249618-0
Source code for langchain.document_loaders.email """Loader that loads email files.""" import os from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders.unstructured import ( UnstructuredFileLoader, satisfies_min_unstructured_version, ) [docs]class UnstructuredEmailLoader(UnstructuredFileLoader): """Loader that uses unstructured to load email files.""" def _get_elements(self) -> List: from unstructured.file_utils.filetype import FileType, detect_filetype filetype = detect_filetype(self.file_path) if filetype == FileType.EML: from unstructured.partition.email import partition_email return partition_email(filename=self.file_path, **self.unstructured_kwargs) elif satisfies_min_unstructured_version("0.5.8") and filetype == FileType.MSG: from unstructured.partition.msg import partition_msg return partition_msg(filename=self.file_path, **self.unstructured_kwargs) else: raise ValueError( f"Filetype {filetype} is not supported in UnstructuredEmailLoader." ) [docs]class OutlookMessageLoader(BaseLoader): """ Loader that loads Outlook Message files using extract_msg. https://github.com/TeamMsgExtractor/msg-extractor """ def __init__(self, file_path: str): """Initialize with file path.""" self.file_path = file_path if not os.path.isfile(self.file_path): raise ValueError("File path %s is not a valid file" % self.file_path) try: import extract_msg # noqa:F401 except ImportError: raise ImportError( "extract_msg is not installed. Please install it with " "`pip install extract_msg`"
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/email.html
33663f249618-1
"`pip install extract_msg`" ) [docs] def load(self) -> List[Document]: """Load data into document objects.""" import extract_msg msg = extract_msg.Message(self.file_path) return [ Document( page_content=msg.body, metadata={ "subject": msg.subject, "sender": msg.sender, "date": msg.date, }, ) ] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/email.html
e3d6c70150c0-0
Source code for langchain.document_loaders.srt """Loader for .srt (subtitle) files.""" from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class SRTLoader(BaseLoader): """Loader for .srt (subtitle) files.""" def __init__(self, file_path: str): """Initialize with file path.""" try: import pysrt # noqa:F401 except ImportError: raise ValueError( "package `pysrt` not found, please install it with `pysrt`" ) self.file_path = file_path [docs] def load(self) -> List[Document]: """Load using pysrt file.""" import pysrt parsed_info = pysrt.open(self.file_path) text = " ".join([t.text for t in parsed_info]) metadata = {"source": self.file_path} return [Document(page_content=text, metadata=metadata)] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/srt.html
497991f31dd4-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 unstructured to load epub files.""" def _get_elements(self) -> List: min_unstructured_version = "0.5.4" if not satisfies_min_unstructured_version(min_unstructured_version): raise ValueError( "Partitioning epub files is only supported in " f"unstructured>={min_unstructured_version}." ) from unstructured.partition.epub import partition_epub return partition_epub(filename=self.file_path, **self.unstructured_kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/epub.html
218cb57232a3-0
Source code for langchain.document_loaders.url_playwright """Loader that uses Playwright to load a page, then uses unstructured to load the html. """ import logging from typing import List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader logger = logging.getLogger(__name__) [docs]class PlaywrightURLLoader(BaseLoader): """Loader that uses Playwright and to load a page and unstructured to load the html. This is useful for loading pages that require javascript to render. Attributes: urls (List[str]): List of URLs to load. continue_on_failure (bool): If True, continue loading other URLs on failure. headless (bool): If True, the browser will run in headless mode. """ def __init__( self, urls: List[str], continue_on_failure: bool = True, headless: bool = True, remove_selectors: Optional[List[str]] = None, ): """Load a list of URLs using Playwright and unstructured.""" try: import playwright # noqa:F401 except ImportError: raise ValueError( "playwright package not found, please install it with " "`pip install playwright`" ) try: import unstructured # noqa:F401 except ImportError: raise ValueError( "unstructured package not found, please install it with " "`pip install unstructured`" ) self.urls = urls self.continue_on_failure = continue_on_failure self.headless = headless self.remove_selectors = remove_selectors [docs] def load(self) -> List[Document]:
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html
218cb57232a3-1
[docs] def load(self) -> List[Document]: """Load the specified URLs using Playwright and create Document instances. Returns: List[Document]: A list of Document instances with loaded content. """ from playwright.sync_api import sync_playwright from unstructured.partition.html import partition_html docs: List[Document] = list() with sync_playwright() as p: browser = p.chromium.launch(headless=self.headless) for url in self.urls: try: page = browser.new_page() page.goto(url) for selector in self.remove_selectors or []: elements = page.locator(selector).all() for element in elements: if element.is_visible(): element.evaluate("element => element.remove()") page_source = page.content() elements = partition_html(text=page_source) text = "\n\n".join([str(el) for el in elements]) metadata = {"source": url} docs.append(Document(page_content=text, metadata=metadata)) except Exception as e: if self.continue_on_failure: logger.error( f"Error fetching or processing {url}, exception: {e}" ) else: raise e browser.close() return docs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html
cefb97f3bb26-0
Source code for langchain.document_loaders.discord """Load from Discord chat dump""" from __future__ import annotations from typing import TYPE_CHECKING, List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader if TYPE_CHECKING: import pandas as pd [docs]class DiscordChatLoader(BaseLoader): """Load Discord chat logs.""" def __init__(self, chat_log: pd.DataFrame, user_id_col: str = "ID"): """Initialize with a Pandas DataFrame containing chat logs.""" if not isinstance(chat_log, pd.DataFrame): raise ValueError( f"Expected chat_log to be a pd.DataFrame, got {type(chat_log)}" ) self.chat_log = chat_log self.user_id_col = user_id_col [docs] def load(self) -> List[Document]: """Load all chat messages.""" result = [] for _, row in self.chat_log.iterrows(): user_id = row[self.user_id_col] metadata = row.to_dict() metadata.pop(self.user_id_col) result.append(Document(page_content=user_id, metadata=metadata)) return result By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/discord.html
042256b1b3bf-0
Source code for langchain.document_loaders.hugging_face_dataset """Loader that loads HuggingFace datasets.""" from typing import List, Mapping, Optional, Sequence, Union from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class HuggingFaceDatasetLoader(BaseLoader): """Loading logic for loading documents from the Hugging Face Hub.""" def __init__( self, path: str, page_content_column: str = "text", name: Optional[str] = None, data_dir: Optional[str] = None, data_files: Optional[ Union[str, Sequence[str], Mapping[str, Union[str, Sequence[str]]]] ] = None, cache_dir: Optional[str] = None, keep_in_memory: Optional[bool] = None, 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: Name of the dataset configuration. data_dir: Data directory of the dataset configuration. data_files: Path(s) to source data file(s). cache_dir: Directory to read/write data. keep_in_memory: Whether to copy the dataset in-memory. save_infos: Save the dataset information (checksums/size/splits/...). use_auth_token: Bearer token for remote files on the Datasets Hub. num_proc: Number of processes. """ self.path = path self.page_content_column = page_content_column self.name = name
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html
042256b1b3bf-1
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_token = use_auth_token self.num_proc = num_proc [docs] def load(self) -> List[Document]: """Load documents.""" try: from datasets import load_dataset except ImportError: raise ImportError( "Could not import datasets python package. " "Please install it with `pip install datasets`." ) dataset = load_dataset( path=self.path, name=self.name, data_dir=self.data_dir, 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, ) docs = [ Document( page_content=row.pop(self.page_content_column), metadata=row, ) for key in dataset.keys() for row in dataset[key] ] return docs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/hugging_face_dataset.html
18febc35ec48-0
Source code for langchain.document_loaders.python import tokenize from langchain.document_loaders.text import TextLoader [docs]class PythonLoader(TextLoader): """ Load Python files, respecting any non-default encoding if specified. """ def __init__(self, file_path: str): with open(file_path, "rb") as f: encoding, _ = tokenize.detect_encoding(f.readline) super().__init__(file_path=file_path, encoding=encoding) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/python.html
ec2d5a2c0ce5-0
Source code for langchain.document_loaders.bilibili import json import re import warnings from typing import List, Tuple import requests from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class BiliBiliLoader(BaseLoader): """Loader that loads bilibili transcripts.""" def __init__(self, video_urls: List[str]): """Initialize with bilibili url.""" self.video_urls = video_urls [docs] def load(self) -> List[Document]: """Load from bilibili url.""" results = [] for url in self.video_urls: transcript, video_info = self._get_bilibili_subs_and_info(url) doc = Document(page_content=transcript, metadata=video_info) results.append(doc) return results def _get_bilibili_subs_and_info(self, url: str) -> Tuple[str, dict]: try: from bilibili_api import sync, video except ImportError: raise ValueError( "requests package not found, please install it with " "`pip install bilibili-api`" ) bvid = re.search(r"BV\w+", url) if bvid is not None: v = video.Video(bvid=bvid.group()) else: aid = re.search(r"av[0-9]+", url) if aid is not None: try: v = video.Video(aid=int(aid.group()[2:])) except AttributeError: raise ValueError(f"{url} is not bilibili url.") else: raise ValueError(f"{url} is not bilibili url.") video_info = sync(v.get_info()) video_info.update({"url": url})
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bilibili.html
ec2d5a2c0ce5-1
video_info = sync(v.get_info()) video_info.update({"url": url}) # Get subtitle url subtitle = video_info.pop("subtitle") sub_list = subtitle["list"] if sub_list: sub_url = sub_list[0]["subtitle_url"] result = requests.get(sub_url) raw_sub_titles = json.loads(result.content)["body"] raw_transcript = " ".join([c["content"] for c in raw_sub_titles]) raw_transcript_with_meta_info = f""" Video Title: {video_info['title']}, description: {video_info['desc']}\n Transcript: {raw_transcript} """ return raw_transcript_with_meta_info, video_info else: raw_transcript = "" warnings.warn( f""" No subtitles found for video: {url}. Return Empty transcript. """ ) return raw_transcript, video_info By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/bilibili.html
e181a1dc8d94-0
Source code for langchain.document_loaders.blackboard """Loader that loads all documents from a blackboard course.""" import contextlib import re from pathlib import Path from typing import Any, List, Optional, Tuple from urllib.parse import unquote from langchain.docstore.document import Document from langchain.document_loaders.directory import DirectoryLoader from langchain.document_loaders.pdf import PyPDFLoader from langchain.document_loaders.web_base import WebBaseLoader [docs]class BlackboardLoader(WebBaseLoader): """Loader that loads all documents from a Blackboard course. This loader is not compatible with all Blackboard courses. It is only compatible with courses that use the new Blackboard interface. To use this loader, you must have the BbRouter cookie. You can get this cookie by logging into the course and then copying the value of the BbRouter cookie from the browser's developer tools. Example: .. code-block:: python from langchain.document_loaders import BlackboardLoader loader = BlackboardLoader( blackboard_course_url="https://blackboard.example.com/webapps/blackboard/execute/announcement?method=search&context=course_entry&course_id=_123456_1", bbrouter="expires:12345...", ) documents = loader.load() """ base_url: str folder_path: str load_all_recursively: bool def __init__( self, blackboard_course_url: str, bbrouter: str, load_all_recursively: bool = True, basic_auth: Optional[Tuple[str, str]] = None, cookies: Optional[dict] = None, ): """Initialize with blackboard course url.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
e181a1dc8d94-1
): """Initialize with blackboard course url. The BbRouter cookie is required for most blackboard courses. Args: blackboard_course_url: Blackboard course url. bbrouter: BbRouter cookie. load_all_recursively: If True, load all documents recursively. basic_auth: Basic auth credentials. cookies: Cookies. Raises: ValueError: If blackboard course url is invalid. """ super().__init__(blackboard_course_url) # Get base url try: self.base_url = blackboard_course_url.split("/webapps/blackboard")[0] except IndexError: raise ValueError( "Invalid blackboard course url. " "Please provide a url that starts with " "https://<blackboard_url>/webapps/blackboard" ) if basic_auth is not None: self.session.auth = basic_auth # Combine cookies if cookies is None: cookies = {} cookies.update({"BbRouter": bbrouter}) self.session.cookies.update(cookies) self.load_all_recursively = load_all_recursively self.check_bs4() [docs] def check_bs4(self) -> None: """Check if BeautifulSoup4 is installed. Raises: ImportError: If BeautifulSoup4 is not installed. """ try: import bs4 # noqa: F401 except ImportError: raise ImportError( "BeautifulSoup4 is required for BlackboardLoader. " "Please install it with `pip install beautifulsoup4`." ) [docs] def load(self) -> List[Document]: """Load data into document objects. Returns: List of documents.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
e181a1dc8d94-2
"""Load data into document objects. Returns: List of documents. """ if self.load_all_recursively: soup_info = self.scrape() self.folder_path = self._get_folder_path(soup_info) relative_paths = self._get_paths(soup_info) documents = [] for path in relative_paths: url = self.base_url + path print(f"Fetching documents from {url}") soup_info = self._scrape(url) with contextlib.suppress(ValueError): documents.extend(self._get_documents(soup_info)) return documents else: print(f"Fetching documents from {self.web_path}") soup_info = self.scrape() self.folder_path = self._get_folder_path(soup_info) return self._get_documents(soup_info) def _get_folder_path(self, soup: Any) -> str: """Get the folder path to save the documents in. Args: soup: BeautifulSoup4 soup object. Returns: Folder path. """ # Get the course name course_name = soup.find("span", {"id": "crumb_1"}) if course_name is None: raise ValueError("No course name found.") course_name = course_name.text.strip() # Prepare the folder path course_name_clean = ( unquote(course_name) .replace(" ", "_") .replace("/", "_") .replace(":", "_") .replace(",", "_") .replace("?", "_") .replace("'", "_") .replace("!", "_") .replace('"', "_") ) # Get the folder path folder_path = Path(".") / course_name_clean
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
e181a1dc8d94-3
) # Get the folder path folder_path = Path(".") / course_name_clean return str(folder_path) def _get_documents(self, soup: Any) -> List[Document]: """Fetch content from page and return Documents. Args: soup: BeautifulSoup4 soup object. Returns: List of documents. """ attachments = self._get_attachments(soup) self._download_attachments(attachments) documents = self._load_documents() return documents def _get_attachments(self, soup: Any) -> List[str]: """Get all attachments from a page. Args: soup: BeautifulSoup4 soup object. Returns: List of attachments. """ from bs4 import BeautifulSoup, Tag # Get content list content_list = soup.find("ul", {"class": "contentList"}) if content_list is None: raise ValueError("No content list found.") content_list: BeautifulSoup # type: ignore # Get all attachments attachments = [] for attachment in content_list.find_all("ul", {"class": "attachments"}): attachment: Tag # type: ignore for link in attachment.find_all("a"): link: Tag # type: ignore href = link.get("href") # Only add if href is not None and does not start with # if href is not None and not href.startswith("#"): attachments.append(href) return attachments def _download_attachments(self, attachments: List[str]) -> None: """Download all attachments. Args: attachments: List of attachments. """ # Make sure the folder exists Path(self.folder_path).mkdir(parents=True, exist_ok=True)
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
e181a1dc8d94-4
Path(self.folder_path).mkdir(parents=True, exist_ok=True) # Download all attachments for attachment in attachments: self.download(attachment) def _load_documents(self) -> List[Document]: """Load all documents in the folder. Returns: List of documents. """ # Create the document loader loader = DirectoryLoader( path=self.folder_path, glob="*.pdf", loader_cls=PyPDFLoader # type: ignore ) # Load the documents documents = loader.load() # Return all documents return documents def _get_paths(self, soup: Any) -> List[str]: """Get all relative paths in the navbar.""" relative_paths = [] course_menu = soup.find("ul", {"class": "courseMenu"}) if course_menu is None: raise ValueError("No course menu found.") for link in course_menu.find_all("a"): href = link.get("href") if href is not None and href.startswith("/"): relative_paths.append(href) return relative_paths [docs] def download(self, path: str) -> None: """Download a file from a url. Args: path: Path to the file. """ # Get the file content response = self.session.get(self.base_url + path, allow_redirects=True) # Get the filename filename = self.parse_filename(response.url) # Write the file to disk with open(Path(self.folder_path) / filename, "wb") as f: f.write(response.content) [docs] def parse_filename(self, url: str) -> str: """Parse the filename from a url. Args:
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
e181a1dc8d94-5
"""Parse the filename from a url. Args: url: Url to parse the filename from. Returns: The filename. """ if (url_path := Path(url)) and url_path.suffix == ".pdf": return url_path.name else: return self._parse_filename_from_url(url) def _parse_filename_from_url(self, url: str) -> str: """Parse the filename from a url. Args: url: Url to parse the filename from. Returns: The filename. Raises: ValueError: If the filename could not be parsed. """ filename_matches = re.search(r"filename%2A%3DUTF-8%27%27(.+)", url) if filename_matches: filename = filename_matches.group(1) else: raise ValueError(f"Could not parse filename from {url}") if ".pdf" not in filename: raise ValueError(f"Incorrect file type: {filename}") filename = filename.split(".pdf")[0] + ".pdf" filename = unquote(filename) filename = filename.replace("%20", " ") return filename if __name__ == "__main__": loader = BlackboardLoader( "https://<YOUR BLACKBOARD URL" " HERE>/webapps/blackboard/content/listContent.jsp?course_id=_<YOUR COURSE ID" " HERE>_1&content_id=_<YOUR CONTENT ID HERE>_1&mode=reset", "<YOUR BBROUTER COOKIE HERE>", load_all_recursively=True, ) documents = loader.load() print(f"Loaded {len(documents)} pages of PDFs from {loader.web_path}") By Harrison Chase
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
e181a1dc8d94-6
By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
a9a0fd23668f-0
Source code for langchain.document_loaders.git import os from typing import Callable, List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class GitLoader(BaseLoader): """Loads files from a Git repository into a list of documents. Repository can be local on disk available at `repo_path`, or remote at `clone_url` that will be cloned to `repo_path`. Currently supports only text files. Each document represents one file in the repository. The `path` points to the local Git repository, and the `branch` specifies the branch to load files from. By default, it loads from the `main` branch. """ def __init__( self, repo_path: str, clone_url: Optional[str] = None, branch: Optional[str] = "main", file_filter: Optional[Callable[[str], bool]] = None, ): self.repo_path = repo_path self.clone_url = clone_url self.branch = branch self.file_filter = file_filter [docs] def load(self) -> List[Document]: try: from git import Blob, Repo # type: ignore except ImportError as ex: raise ImportError( "Could not import git python package. " "Please install it with `pip install GitPython`." ) from ex if not os.path.exists(self.repo_path) and self.clone_url is None: raise ValueError(f"Path {self.repo_path} does not exist") elif self.clone_url: repo = Repo.clone_from(self.clone_url, self.repo_path) repo.git.checkout(self.branch) else: repo = Repo(self.repo_path)
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/git.html
a9a0fd23668f-1
else: repo = Repo(self.repo_path) repo.git.checkout(self.branch) docs: List[Document] = [] for item in repo.tree().traverse(): if not isinstance(item, Blob): continue file_path = os.path.join(self.repo_path, item.path) ignored_files = repo.ignored([file_path]) if len(ignored_files): continue # uses filter to skip files if self.file_filter and not self.file_filter(file_path): continue rel_file_path = os.path.relpath(file_path, self.repo_path) try: with open(file_path, "rb") as f: content = f.read() file_type = os.path.splitext(item.name)[1] # loads only text files try: text_content = content.decode("utf-8") except UnicodeDecodeError: continue metadata = { "file_path": rel_file_path, "file_name": item.name, "file_type": file_type, } doc = Document(page_content=text_content, metadata=metadata) docs.append(doc) except Exception as e: print(f"Error reading file {file_path}: {e}") return docs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/git.html
77798678f561-0
Source code for langchain.document_loaders.blockchain import os import re from enum import Enum from typing import List import requests from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader class BlockchainType(Enum): ETH_MAINNET = "eth-mainnet" ETH_GOERLI = "eth-goerli" POLYGON_MAINNET = "polygon-mainnet" POLYGON_MUMBAI = "polygon-mumbai" [docs]class BlockchainDocumentLoader(BaseLoader): """Loads elements from a blockchain smart contract into Langchain documents. The supported blockchains are: Ethereum mainnet, Ethereum Goerli testnet, Polygon mainnet, and Polygon Mumbai testnet. If no BlockchainType is specified, the default is Ethereum mainnet. The Loader uses the Alchemy API to interact with the blockchain. ALCHEMY_API_KEY environment variable must be set to use this loader. Future versions of this loader can: - Support additional Alchemy APIs (e.g. getTransactions, etc.) """ def __init__( self, contract_address: str, blockchainType: BlockchainType = BlockchainType.ETH_MAINNET, api_key: str = "docs-demo", startToken: int = 0, ): self.contract_address = contract_address self.blockchainType = blockchainType.value self.api_key = os.environ.get("ALCHEMY_API_KEY") or api_key self.startToken = startToken if not self.api_key: raise ValueError("Alchemy API key not provided.") if not re.match(r"^0x[a-fA-F0-9]{40}$", self.contract_address): raise ValueError(f"Invalid contract address {self.contract_address}")
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html
77798678f561-1
raise ValueError(f"Invalid contract address {self.contract_address}") [docs] def load(self) -> List[Document]: url = ( f"https://{self.blockchainType}.g.alchemy.com/nft/v2/" f"{self.api_key}/getNFTsForCollection?withMetadata=" f"True&contractAddress={self.contract_address}" f"&startToken={self.startToken}" ) response = requests.get(url) if response.status_code != 200: raise ValueError(f"Request failed with status code {response.status_code}") items = response.json()["nfts"] if not (items): raise ValueError( f"No NFTs found for contract address {self.contract_address}" ) result = [] for item in items: content = str(item) tokenId = item["id"]["tokenId"] metadata = {"tokenId": tokenId} result.append(Document(page_content=content, metadata=metadata)) return result By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html
b6c100d58a60-0
Source code for langchain.document_loaders.facebook_chat """Loader that loads Facebook chat json dump.""" import datetime import json from pathlib import Path from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader def concatenate_rows(row: dict) -> str: """Combine message information in a readable format ready to be used.""" sender = row["sender_name"] text = row["content"] date = datetime.datetime.fromtimestamp(row["timestamp_ms"] / 1000).strftime( "%Y-%m-%d %H:%M:%S" ) return f"{sender} on {date}: {text}\n\n" [docs]class FacebookChatLoader(BaseLoader): """Loader that loads Facebook messages json directory dump.""" def __init__(self, path: str): """Initialize with path.""" self.file_path = path [docs] def load(self) -> List[Document]: """Load documents.""" try: import pandas as pd except ImportError: raise ValueError( "pandas is needed for Facebook chat loader, " "please install with `pip install pandas`" ) p = Path(self.file_path) with open(p, encoding="utf8") as f: d = json.load(f) normalized_messages = pd.json_normalize(d["messages"]) df_normalized_messages = pd.DataFrame(normalized_messages) # Only keep plain text messages # (no services, nor links, hashtags, code, bold ...) df_filtered = df_normalized_messages[ (df_normalized_messages.content.apply(lambda x: type(x) == str)) ] df_filtered = df_filtered[["timestamp_ms", "content", "sender_name"]]
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/facebook_chat.html
b6c100d58a60-1
df_filtered = df_filtered[["timestamp_ms", "content", "sender_name"]] text = df_filtered.apply(concatenate_rows, axis=1).str.cat(sep="") metadata = {"source": str(p)} return [Document(page_content=text, metadata=metadata)] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/facebook_chat.html
8ed19df2db79-0
Source code for langchain.document_loaders.diffbot """Loader that uses Diffbot to load webpages in text format.""" import logging from typing import Any, List import requests from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader logger = logging.getLogger(__name__) [docs]class DiffbotLoader(BaseLoader): """Loader that loads Diffbot file json.""" def __init__( self, api_token: str, urls: List[str], continue_on_failure: bool = True ): """Initialize with API token, ids, and key.""" self.api_token = api_token self.urls = urls self.continue_on_failure = continue_on_failure def _diffbot_api_url(self, diffbot_api: str) -> str: return f"https://api.diffbot.com/v3/{diffbot_api}" def _get_diffbot_data(self, url: str) -> Any: """Get Diffbot file from Diffbot REST API.""" # TODO: Add support for other Diffbot APIs diffbot_url = self._diffbot_api_url("article") params = { "token": self.api_token, "url": url, } response = requests.get(diffbot_url, params=params, timeout=10) # TODO: handle non-ok errors return response.json() if response.ok else {} [docs] def load(self) -> List[Document]: """Extract text from Diffbot on all the URLs and return Document instances""" docs: List[Document] = list() for url in self.urls: try: data = self._get_diffbot_data(url) text = data["objects"][0]["text"] if "objects" in data else ""
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/diffbot.html
8ed19df2db79-1
text = data["objects"][0]["text"] if "objects" in data else "" metadata = {"source": url} docs.append(Document(page_content=text, metadata=metadata)) except Exception as e: if self.continue_on_failure: logger.error(f"Error fetching or processing {url}, exception: {e}") else: raise e return docs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/diffbot.html
6fc72cf2e093-0
Source code for langchain.document_loaders.image """Loader that loads image files.""" from typing import List from langchain.document_loaders.unstructured import UnstructuredFileLoader [docs]class UnstructuredImageLoader(UnstructuredFileLoader): """Loader that uses unstructured to load image files, such as PNGs and JPGs.""" def _get_elements(self) -> List: from unstructured.partition.image import partition_image return partition_image(filename=self.file_path, **self.unstructured_kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/image.html
444d5a8234a1-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): """Loads a query result from DuckDB into a list of documents. Each document represents one row of the result. The `page_content_columns` are written into the `page_content` of the document. The `metadata_columns` are written into the `metadata` of the document. By default, all columns are written into the `page_content` and none into the `metadata`. """ def __init__( self, query: str, database: str = ":memory:", read_only: bool = False, config: Optional[Dict[str, str]] = None, page_content_columns: Optional[List[str]] = None, metadata_columns: Optional[List[str]] = None, ): self.query = query self.database = database self.read_only = read_only self.config = config or {} self.page_content_columns = page_content_columns self.metadata_columns = metadata_columns [docs] def load(self) -> List[Document]: try: import duckdb except ImportError: raise ValueError( "Could not import duckdb python package. " "Please install it with `pip install duckdb`." ) docs = [] with duckdb.connect( database=self.database, read_only=self.read_only, config=self.config ) as con: query_result = con.execute(self.query) results = query_result.fetchall() description = cast(list, query_result.description)
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/duckdb_loader.html
444d5a8234a1-1
results = query_result.fetchall() description = cast(list, query_result.description) field_names = [c[0] for c in description] if self.page_content_columns is None: page_content_columns = field_names else: page_content_columns = self.page_content_columns if self.metadata_columns is None: metadata_columns = [] else: metadata_columns = self.metadata_columns for result in results: page_content = "\n".join( f"{column}: {result[field_names.index(column)]}" for column in page_content_columns ) metadata = { column: result[field_names.index(column)] for column in metadata_columns } doc = Document(page_content=page_content, metadata=metadata) docs.append(doc) return docs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/duckdb_loader.html
30a302883b2f-0
Source code for langchain.document_loaders.notion """Loader that 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): """Loader that loads Notion directory dump.""" def __init__(self, path: str): """Initialize with path.""" self.file_path = path [docs] def load(self) -> List[Document]: """Load documents.""" ps = list(Path(self.file_path).glob("**/*.md")) docs = [] for p in ps: with open(p) as f: text = f.read() metadata = {"source": str(p)} docs.append(Document(page_content=text, metadata=metadata)) return docs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/notion.html
d6fb54f7e23e-0
Source code for langchain.document_loaders.obsidian """Loader that loads Obsidian directory dump.""" import re from pathlib import Path from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class ObsidianLoader(BaseLoader): """Loader that loads Obsidian files from disk.""" FRONT_MATTER_REGEX = re.compile(r"^---\n(.*?)\n---\n", re.MULTILINE | re.DOTALL) def __init__( self, path: str, encoding: str = "UTF-8", collect_metadata: bool = True ): """Initialize with path.""" self.file_path = path self.encoding = encoding self.collect_metadata = collect_metadata def _parse_front_matter(self, content: str) -> dict: """Parse front matter metadata from the content and return it as a dict.""" if not self.collect_metadata: return {} match = self.FRONT_MATTER_REGEX.search(content) front_matter = {} if match: lines = match.group(1).split("\n") for line in lines: if ":" in line: key, value = line.split(":", 1) front_matter[key.strip()] = value.strip() else: # Skip lines without a colon continue return front_matter def _remove_front_matter(self, content: str) -> str: """Remove front matter metadata from the given content.""" if not self.collect_metadata: return content return self.FRONT_MATTER_REGEX.sub("", content) [docs] def load(self) -> List[Document]: """Load documents.""" ps = list(Path(self.file_path).glob("**/*.md"))
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/obsidian.html
d6fb54f7e23e-1
"""Load documents.""" ps = list(Path(self.file_path).glob("**/*.md")) docs = [] for p in ps: with open(p, encoding=self.encoding) as f: text = f.read() front_matter = self._parse_front_matter(text) text = self._remove_front_matter(text) metadata = {"source": str(p.name), "path": str(p), **front_matter} docs.append(Document(page_content=text, metadata=metadata)) return docs By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/obsidian.html
5f322d8f0334-0
Source code for langchain.document_loaders.azure_blob_storage_file """Loading logic for loading documents from an Azure Blob Storage file.""" import os import tempfile from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders.unstructured import UnstructuredFileLoader [docs]class AzureBlobStorageFileLoader(BaseLoader): """Loading logic for loading documents from Azure Blob Storage.""" def __init__(self, conn_str: str, container: str, blob_name: str): """Initialize with connection string, container and blob name.""" self.conn_str = conn_str self.container = container self.blob = blob_name [docs] def load(self) -> List[Document]: """Load documents.""" try: from azure.storage.blob import BlobClient except ImportError as exc: raise ValueError( "Could not import azure storage blob python package. " "Please install it with `pip install azure-storage-blob`." ) from exc client = BlobClient.from_connection_string( conn_str=self.conn_str, container_name=self.container, blob_name=self.blob ) with tempfile.TemporaryDirectory() as temp_dir: file_path = f"{temp_dir}/{self.container}/{self.blob}" os.makedirs(os.path.dirname(file_path), exist_ok=True) with open(f"{file_path}", "wb") as file: blob_data = client.download_blob() blob_data.readinto(file) loader = UnstructuredFileLoader(file_path) return loader.load() By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/azure_blob_storage_file.html
e62fa8f48024-0
Source code for langchain.document_loaders.twitter """Twitter document loader.""" from __future__ import annotations from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence, Union from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader if TYPE_CHECKING: import tweepy from tweepy import OAuth2BearerHandler, OAuthHandler def _dependable_tweepy_import() -> tweepy: try: import tweepy except ImportError: raise ValueError( "tweepy package not found, please install it with `pip install tweepy`" ) return tweepy [docs]class TwitterTweetLoader(BaseLoader): """Twitter tweets loader. Read tweets of user twitter handle. First you need to go to `https://developer.twitter.com/en/docs/twitter-api /getting-started/getting-access-to-the-twitter-api` to get your token. And create a v2 version of the app. """ def __init__( self, auth_handler: Union[OAuthHandler, OAuth2BearerHandler], twitter_users: Sequence[str], number_tweets: Optional[int] = 100, ): self.auth = auth_handler self.twitter_users = twitter_users self.number_tweets = number_tweets [docs] def load(self) -> List[Document]: """Load tweets.""" tweepy = _dependable_tweepy_import() api = tweepy.API(self.auth, parser=tweepy.parsers.JSONParser()) results: List[Document] = [] for username in self.twitter_users: tweets = api.user_timeline(screen_name=username, count=self.number_tweets) user = api.get_user(screen_name=username)
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html
e62fa8f48024-1
user = api.get_user(screen_name=username) docs = self._format_tweets(tweets, user) results.extend(docs) return results def _format_tweets( self, tweets: List[Dict[str, Any]], user_info: dict ) -> Iterable[Document]: """Format tweets into a string.""" for tweet in tweets: metadata = { "created_at": tweet["created_at"], "user_info": user_info, } yield Document( page_content=tweet["text"], metadata=metadata, ) [docs] @classmethod def from_bearer_token( cls, oauth2_bearer_token: str, twitter_users: Sequence[str], number_tweets: Optional[int] = 100, ) -> TwitterTweetLoader: """Create a TwitterTweetLoader from OAuth2 bearer token.""" tweepy = _dependable_tweepy_import() auth = tweepy.OAuth2BearerHandler(oauth2_bearer_token) return cls( auth_handler=auth, twitter_users=twitter_users, number_tweets=number_tweets, ) [docs] @classmethod def from_secrets( cls, access_token: str, access_token_secret: str, consumer_key: str, consumer_secret: str, twitter_users: Sequence[str], number_tweets: Optional[int] = 100, ) -> TwitterTweetLoader: """Create a TwitterTweetLoader from access tokens and secrets.""" tweepy = _dependable_tweepy_import() auth = tweepy.OAuthHandler( access_token=access_token, access_token_secret=access_token_secret,
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html
e62fa8f48024-2
access_token=access_token, access_token_secret=access_token_secret, consumer_key=consumer_key, consumer_secret=consumer_secret, ) return cls( auth_handler=auth, twitter_users=twitter_users, number_tweets=number_tweets, ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html
f7c7b3f02815-0
Source code for langchain.document_loaders.powerpoint """Loader that loads powerpoint files.""" import os from typing import List from langchain.document_loaders.unstructured import UnstructuredFileLoader [docs]class UnstructuredPowerPointLoader(UnstructuredFileLoader): """Loader that uses unstructured to load powerpoint files.""" def _get_elements(self) -> List: from unstructured.__version__ import __version__ as __unstructured_version__ 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 not installed, we'll just # check the file extension try: import magic # noqa: F401 is_ppt = detect_filetype(self.file_path) == FileType.PPT except ImportError: _, extension = os.path.splitext(self.file_path) is_ppt = extension == ".ppt" if is_ppt and unstructured_version < (0, 4, 11): raise ValueError( f"You are on unstructured version {__unstructured_version__}. " "Partitioning .ppt files is only supported in unstructured>=0.4.11. " "Please upgrade the unstructured package and try again." ) if is_ppt: from unstructured.partition.ppt import partition_ppt return partition_ppt(filename=self.file_path, **self.unstructured_kwargs) else: from unstructured.partition.pptx import partition_pptx return partition_pptx(filename=self.file_path, **self.unstructured_kwargs)
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html
f7c7b3f02815-1
return partition_pptx(filename=self.file_path, **self.unstructured_kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html
4ba1bc31e118-0
Source code for langchain.document_loaders.azlyrics """Loader that loads AZLyrics.""" from typing import List from langchain.docstore.document import Document from langchain.document_loaders.web_base import WebBaseLoader [docs]class AZLyricsLoader(WebBaseLoader): """Loader that loads AZLyrics webpages.""" [docs] def load(self) -> List[Document]: """Load webpage.""" soup = self.scrape() title = soup.title.text lyrics = soup.find_all("div", {"class": ""})[2].text text = title + lyrics metadata = {"source": self.web_path} return [Document(page_content=text, metadata=metadata)] By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Apr 25, 2023.
https://python.langchain.com/en/latest/_modules/langchain/document_loaders/azlyrics.html