id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 59 127 |
|---|---|---|
21d345307eec-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, ur... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/requests.html |
21d345307eec-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.req... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/requests.html |
f71fb3f033d5-0 | Source code for langchain.document_transformers
"""Transform documents"""
from typing import Any, Callable, List, Sequence
import numpy as np
from pydantic import BaseModel, Field
from langchain.embeddings.base import Embeddings
from langchain.math_utils import cosine_similarity
from langchain.schema import BaseDocumen... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_transformers.html |
f71fb3f033d5-1 | for first_idx, second_idx in redundant_stacked[redundant_sorted]:
if first_idx in included_idxs and second_idx in included_idxs:
# Default to dropping the second document of any highly similar pair.
included_idxs.remove(second_idx)
return list(sorted(included_idxs))
def _get_embeddin... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_transformers.html |
f71fb3f033d5-2 | """Filter down documents."""
stateful_documents = get_stateful_documents(documents)
embedded_documents = _get_embeddings_from_stateful_docs(
self.embeddings, stateful_documents
)
included_idxs = _filter_similar_embeddings(
embedded_documents, self.similarity_fn, s... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_transformers.html |
cf6e3609e60e-0 | Source code for langchain.text_splitter
"""Functionality for splitting text."""
from __future__ import annotations
import copy
import logging
import re
from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum
from typing import (
AbstractSet,
Any,
Callable,
Collection,... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-1 | """Interface for splitting text into chunks."""
def __init__(
self,
chunk_size: int = 4000,
chunk_overlap: int = 200,
length_function: Callable[[str], int] = len,
keep_separator: bool = False,
add_start_index: bool = False,
) -> None:
"""Create a new TextS... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-2 | metadata = copy.deepcopy(_metadatas[i])
if self._add_start_index:
index = text.find(chunk, index + 1)
metadata["start_index"] = index
new_doc = Document(page_content=chunk, metadata=metadata)
documents.append(new_doc)
return... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-3 | )
if len(current_doc) > 0:
doc = self._join_docs(current_doc, separator)
if doc is not None:
docs.append(doc)
# Keep on popping if:
# - we have a larger chunk than in the chunk overlap
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-4 | "Please install it with `pip install transformers`."
)
return cls(length_function=_huggingface_tokenizer_length, **kwargs)
[docs] @classmethod
def from_tiktoken_encoder(
cls: Type[TS],
encoding_name: str = "gpt2",
model_name: Optional[str] = None,
allowed_speci... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-5 | [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[Doc... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-6 | ):
"""Create a new MarkdownHeaderTextSplitter.
Args:
headers_to_split_on: Headers we want to track
return_each_line: Return each line w/ associated headers
"""
# Output line-by-line or aggregated into chunks w/ common headers
self.return_each_line = return... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-7 | # Final output
lines_with_metadata: List[LineType] = []
# Content and metadata of the chunk currently being processed
current_content: List[str] = []
current_metadata: Dict[str, str] = {}
# Keep track of the nested header structure
# header_stack: List[Dict[str, Union[int... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-8 | # Push the current header to the stack
header: HeaderType = {
"level": current_header_level,
"name": name,
"data": stripped_line[len(sep) :].strip(),
}
header_stack... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-9 | tokens_per_chunk: int
decode: Callable[[list[int]], str]
encode: Callable[[str], List[int]]
[docs]def split_text_on_tokens(*, text: str, tokenizer: Tokenizer) -> List[str]:
"""Split incoming text and return chunks."""
splits: List[str] = []
input_ids = tokenizer.encode(text)
start_idx = 0
cu... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-10 | 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]:
def _enco... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-11 | self.tokenizer = self._model.tokenizer
self._initialize_chunk_configuration(tokens_per_chunk=tokens_per_chunk)
def _initialize_chunk_configuration(
self, *, tokens_per_chunk: Optional[int]
) -> None:
self.maximum_tokens_per_chunk = cast(int, self._model.max_seq_length)
if tokens_... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-12 | truncation="do_not_truncate",
)
return token_ids_with_start_and_end_token_ids
[docs]class Language(str, Enum):
CPP = "cpp"
GO = "go"
JAVA = "java"
JS = "js"
PHP = "php"
PROTO = "proto"
PYTHON = "python"
RST = "rst"
RUBY = "ruby"
RUST = "rust"
SCALA = "scala"
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-13 | break
if re.search(_s, text):
separator = _s
new_separators = separators[i + 1 :]
break
splits = _split_text_with_regex(text, separator, self._keep_separator)
# Now go merging things, recursively splitting longer texts.
_good_splits = [... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-14 | "\nclass ",
# Split along function definitions
"\nvoid ",
"\nint ",
"\nfloat ",
"\ndouble ",
# Split along control flow statements
"\nif ",
"\nfor ",
"\nwhile ",
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-15 | "\nvar ",
"\nclass ",
# Split along control flow statements
"\nif ",
"\nfor ",
"\nwhile ",
"\nswitch ",
"\ncase ",
"\ndefault ",
# Split by the normal type of lines
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-16 | "\n",
" ",
"",
]
elif language == Language.RST:
return [
# Split along section titles
"\n=+\n",
"\n-+\n",
"\n\*+\n",
# Split along directive markers
"\n\n.. *\n... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-17 | "\nval ",
"\nvar ",
# Split along control flow statements
"\nif ",
"\nfor ",
"\nwhile ",
"\nmatch ",
"\ncase ",
# Split by the normal type of lines
"\n\n",
"\n"... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-18 | "",
]
elif language == Language.LATEX:
return [
# First, try to split along Latex sections
"\n\\\chapter{",
"\n\\\section{",
"\n\\\subsection{",
"\n\\\subsubsection{",
# Now split by environme... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-19 | # Split along compiler informations definitions
"\npragma ",
"\nusing ",
# Split along contract definitions
"\ncontract ",
"\ninterface ",
"\nlibrary ",
# Split along method definitions
"\ncon... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-20 | 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
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
cf6e3609e60e-21 | separators = self.get_separators_for_language(Language.MARKDOWN)
super().__init__(separators=separators, **kwargs)
[docs]class LatexTextSplitter(RecursiveCharacterTextSplitter):
"""Attempts to split the text along Latex-formatted layout elements."""
def __init__(self, **kwargs: Any) -> None:
"""... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/text_splitter.html |
ec2bbbd9d27d-0 | Source code for langchain.output_parsers.retry
from __future__ import annotations
from typing import TypeVar
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.prompts.base import BasePromptTemplate
from langchain.prompts.prompt import PromptTemplate
from lang... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/output_parsers/retry.html |
ec2bbbd9d27d-1 | chain = LLMChain(llm=llm, prompt=prompt)
return cls(parser=parser, retry_chain=chain)
[docs] def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T:
try:
parsed_completion = self.parser.parse(completion)
except OutputParserException:
new_completio... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/output_parsers/retry.html |
ec2bbbd9d27d-2 | ) -> RetryWithErrorOutputParser[T]:
chain = LLMChain(llm=llm, prompt=prompt)
return cls(parser=parser, retry_chain=chain)
[docs] def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T:
try:
parsed_completion = self.parser.parse(completion)
except Outp... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/output_parsers/retry.html |
c7b3c0b695d2-0 | Source code for langchain.output_parsers.list
from __future__ import annotations
from abc import abstractmethod
from typing import List
from langchain.schema import BaseOutputParser
[docs]class ListOutputParser(BaseOutputParser):
"""Class to parse the output of an LLM call to a list."""
@property
def _type(... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/output_parsers/list.html |
cd26e38429ca-0 | Source code for langchain.output_parsers.datetime
import random
from datetime import datetime, timedelta
from typing import List
from langchain.schema import BaseOutputParser, OutputParserException
from langchain.utils import comma_list
def _generate_random_datetime_strings(
pattern: str,
n: int = 3,
start_... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/output_parsers/datetime.html |
cd26e38429ca-1 | ) from e
@property
def _type(self) -> str:
return "datetime"
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/output_parsers/datetime.html |
dee55c0acbbe-0 | Source code for langchain.output_parsers.rail_parser
from __future__ import annotations
from typing import Any, Dict
from langchain.schema import BaseOutputParser
[docs]class GuardrailsOutputParser(BaseOutputParser):
guard: Any
@property
def _type(self) -> str:
return "guardrails"
[docs] @classme... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/output_parsers/rail_parser.html |
653a191b3ee3-0 | Source code for langchain.output_parsers.regex
from __future__ import annotations
import re
from typing import Dict, List, Optional
from langchain.schema import BaseOutputParser
[docs]class RegexParser(BaseOutputParser):
"""Class to parse the output into a dictionary."""
regex: str
output_keys: List[str]
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/output_parsers/regex.html |
4f6e2cdabf6e-0 | Source code for langchain.output_parsers.structured
from __future__ import annotations
from typing import Any, List
from pydantic import BaseModel
from langchain.output_parsers.format_instructions import STRUCTURED_FORMAT_INSTRUCTIONS
from langchain.output_parsers.json import parse_and_check_json_markdown
from langchai... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/output_parsers/structured.html |
d83d2f7feff4-0 | Source code for langchain.output_parsers.regex_dict
from __future__ import annotations
import re
from typing import Dict, Optional
from langchain.schema import BaseOutputParser
[docs]class RegexDictParser(BaseOutputParser):
"""Class to parse the output into a dictionary."""
regex_pattern: str = r"{}:\s?([^.'\n'... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/output_parsers/regex_dict.html |
c3e3f9bbab70-0 | Source code for langchain.output_parsers.fix
from __future__ import annotations
from typing import TypeVar
from langchain.base_language import BaseLanguageModel
from langchain.chains.llm import LLMChain
from langchain.output_parsers.prompts import NAIVE_FIX_PROMPT
from langchain.prompts.base import BasePromptTemplate
f... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/output_parsers/fix.html |
f0540bdd0577-0 | Source code for langchain.output_parsers.pydantic
import json
import re
from typing import Type, TypeVar
from pydantic import BaseModel, ValidationError
from langchain.output_parsers.format_instructions import PYDANTIC_FORMAT_INSTRUCTIONS
from langchain.schema import BaseOutputParser, OutputParserException
T = TypeVar(... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/output_parsers/pydantic.html |
f0540bdd0577-1 | @property
def _type(self) -> str:
return "pydantic"
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/output_parsers/pydantic.html |
369bc24c53df-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 UnstructuredURLLoade... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/url.html |
369bc24c53df-1 | def _validate_mode(self, mode: str) -> None:
_valid_modes = {"single", "elements"}
if mode not in _valid_modes:
raise ValueError(
f"Got {mode} for `mode`, but should be one of `{_valid_modes}`"
)
def __is_headers_available_for_html(self) -> bool:
_unst... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/url.html |
369bc24c53df-2 | 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
)
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/url.html |
cdf1588ca23c-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 com... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/hn.html |
cdf1588ca23c-1 | title = lineItem.find("span", {"class": "titleline"}).text.strip()
metadata = {
"source": self.web_path,
"title": title,
"link": link,
"ranking": ranking,
}
documents.append(
Document(
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/hn.html |
0aecaae5e02c-0 | Source code for langchain.document_loaders.csv_loader
import csv
from typing import Any, Dict, List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders.unstructured import (
UnstructuredFileLoader,
validate_unstructure... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/csv_loader.html |
0aecaae5e02c-1 | with open(self.file_path, newline="", encoding=self.encoding) as csvfile:
csv_reader = csv.DictReader(csvfile, **self.csv_args) # type: ignore
for i, row in enumerate(csv_reader):
content = "\n".join(f"{k.strip()}: {v.strip()}" for k, v in row.items())
try:
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/csv_loader.html |
e3f5ff84cb16-0 | Source code for langchain.document_loaders.youtube
"""Loader that loads YouTube transcript."""
from __future__ import annotations
import logging
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Union
from urllib.parse import parse_qs, urlparse
from pydantic import root_validator
from pyd... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
e3f5ff84cb16-1 | """Validate that either folder_id or document_ids is set, but not both."""
if not values.get("credentials_path") and not values.get(
"service_account_path"
):
raise ValueError("Must specify either channel_name or video_ids")
return values
def _load_credentials(self) -... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
e3f5ff84cb16-2 | token.write(creds.to_json())
return creds
ALLOWED_SCHEMAS = {"http", "https"}
ALLOWED_NETLOCK = {
"youtu.be",
"m.youtube.com",
"youtube.com",
"www.youtube.com",
"www.youtube-nocookie.com",
"vid.plus",
}
def _parse_video_id(url: str) -> Optional[str]:
"""Parse a youtube url and return... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
e3f5ff84cb16-3 | self.add_video_info = add_video_info
self.language = language
if isinstance(language, str):
self.language = [language]
else:
self.language = language
self.translation = translation
self.continue_on_failure = continue_on_failure
[docs] @staticmethod
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
e3f5ff84cb16-4 | except TranscriptsDisabled:
return []
try:
transcript = transcript_list.find_transcript(self.language)
except NoTranscriptFound:
en_transcript = transcript_list.find_transcript(["en"])
transcript = en_transcript.translate(self.translation)
transcri... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
e3f5ff84cb16-5 | 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/doc... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
e3f5ff84cb16-6 | "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."""
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
e3f5ff84cb16-7 | 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"]
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
e3f5ff84cb16-8 | metadata=meta_data,
)
)
except (TranscriptsDisabled, NoTranscriptFound) as e:
if self.continue_on_failure:
logger.error(
"Error fetching transscript "
+ f" {ite... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/youtube.html |
2316c0ba8cfc-0 | Source code for langchain.document_loaders.confluence
"""Load Data from a Confluence Space"""
import logging
from enum import Enum
from io import BytesIO
from typing import Any, Callable, Dict, List, Optional, Union
from tenacity import (
before_sleep_log,
retry,
stop_after_attempt,
wait_exponential,
)
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/confluence.html |
2316c0ba8cfc-1 | raw XML representation for storage. The view format is the HTML representation for
viewing with macros are rendered as though it is viewed by users. You can pass
a enum `content_format` argument to `load()` to specify the content format, this is
set to `ContentFormat.STORAGE` by default.
Hint: space_key... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/confluence.html |
2316c0ba8cfc-2 | :type max_retry_seconds: Optional[int], optional
:param confluence_kwargs: additional kwargs to initialize confluence with
:type confluence_kwargs: dict, optional
:raises ValueError: Errors while validating input
:raises ImportError: Required dependencies not installed.
"""
def __init__(
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/confluence.html |
2316c0ba8cfc-3 | )
elif token:
self.confluence = Confluence(
url=url, token=token, cloud=cloud, **confluence_kwargs
)
else:
self.confluence = Confluence(
url=url,
username=username,
password=api_key,
cloud... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/confluence.html |
2316c0ba8cfc-4 | )
if token and (api_key or username or oauth2):
errors.append(
"Cannot provide a value for `token` and a value for `api_key`, "
"`username` or `oauth2`"
)
if errors:
return errors
return None
[docs] def load(
self,
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/confluence.html |
2316c0ba8cfc-5 | defaults to False
:type include_archived_content: bool, optional
:param include_attachments: defaults to False
:type include_attachments: bool, optional
:param include_comments: defaults to False
:type include_comments: bool, optional
:param content_format: Specify conten... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/confluence.html |
2316c0ba8cfc-6 | include_attachments,
include_comments,
content_format,
ocr_languages,
)
if label:
pages = self.paginate_request(
self.confluence.get_all_pages_by_label,
label=label,
limit=limit,
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/confluence.html |
2316c0ba8cfc-7 | page = get_page(page_id=page_id, expand=content_format.value)
if not include_restricted_content and not self.is_public_page(page):
continue
doc = self.process_page(
page,
include_attachments,
include_comments... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/confluence.html |
2316c0ba8cfc-8 | are more docs based on the length of the returned list of pages, rather than
just checking for the presence of a `next` key in the response like this page
would have you do:
https://developer.atlassian.com/server/confluence/pagination-in-the-rest-api/
:param retrieval_method: Function us... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/confluence.html |
2316c0ba8cfc-9 | pages: List[dict],
include_restricted_content: bool,
include_attachments: bool,
include_comments: bool,
content_format: ContentFormat,
ocr_languages: Optional[str] = None,
) -> List[Document]:
"""Process a list of pages into a list of documents."""
docs = []
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/confluence.html |
2316c0ba8cfc-10 | BeautifulSoup(comment["body"]["view"]["value"], "lxml").get_text(
" ", strip=True
)
for comment in comments
]
text = text + "".join(comment_texts)
return Document(
page_content=text,
metadata={
"t... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/confluence.html |
2316c0ba8cfc-11 | ".wordprocessingml.document"
):
text = title + self.process_doc(absolute_url)
elif media_type == "application/vnd.ms-excel":
text = title + self.process_xls(absolute_url)
elif media_type == "image/svg+xml":
text = title + self.process_s... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/confluence.html |
2316c0ba8cfc-12 | try:
import pytesseract # noqa: F401
from PIL import Image # noqa: F401
except ImportError:
raise ImportError(
"`pytesseract` or `Pillow` package not found, "
"please run `pip install pytesseract Pillow`"
)
response = self... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/confluence.html |
2316c0ba8cfc-13 | text = ""
if (
response.status_code != 200
or response.content == b""
or response.content is None
):
return text
workbook = xlrd.open_workbook(file_contents=response.content)
for sheet in workbook.sheets():
text += f"{sheet.name... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/confluence.html |
2316c0ba8cfc-14 | img_data.seek(0)
image = Image.open(img_data)
return pytesseract.image_to_string(image, lang=ocr_languages)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/confluence.html |
2740bf7870f7-0 | Source code for langchain.document_loaders.onedrive_file
from __future__ import annotations
import tempfile
from typing import TYPE_CHECKING, List
from pydantic import BaseModel, Field
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.document_loaders... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/onedrive_file.html |
14fbe3bddd9a-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... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/conllu.html |
bf34bfd2a8eb-0 | Source code for langchain.document_loaders.psychic
"""Loader that loads documents from Psychic.dev."""
from typing import List
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class PsychicLoader(BaseLoader):
"""Loader that loads documents from Psychic.de... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/psychic.html |
e6cb6f3f1e12-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_outp... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/notebook.html |
e6cb6f3f1e12-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 [remov... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/notebook.html |
e6cb6f3f1e12-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=" ")
m... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/notebook.html |
dc8e59935034-0 | Source code for langchain.document_loaders.reddit
"""Reddit document loader."""
from __future__ import annotations
from typing import TYPE_CHECKING, Iterable, List, Optional, Sequence
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
if TYPE_CHECKING:
import pra... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/reddit.html |
dc8e59935034-1 | if self.mode == "subreddit":
for search_query in self.search_queries:
for category in self.categories:
docs = self._subreddit_posts_loader(
search_query=search_query, category=category, reddit=reddit
)
result... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/reddit.html |
dc8e59935034-2 | method = getattr(user.submissions, category)
cat_posts = method(limit=self.number_posts)
"""Format reddit posts into a string."""
for post in cat_posts:
metadata = {
"post_subreddit": post.subreddit_name_prefixed,
"post_category": category,
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/reddit.html |
84d066abc11b-0 | Source code for langchain.document_loaders.iugu
"""Loader that fetches data from IUGU"""
import json
import urllib.request
from typing import List, Optional
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
from langchain.utils import get_from_env, stringify_dict
IU... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/iugu.html |
84d066abc11b-1 | return self._get_resource()
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/iugu.html |
bbf2a9d116e5-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 powe... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/powerpoint.html |
bbf2a9d116e5-1 | return partition_pptx(filename=self.file_path, **self.unstructured_kwargs)
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/powerpoint.html |
57a30178976f-0 | Source code for langchain.document_loaders.mastodon
"""Mastodon document loader."""
from __future__ import annotations
import os
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
if TYPE... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/mastodon.html |
57a30178976f-1 | access_token = access_token or os.environ.get("MASTODON_ACCESS_TOKEN")
self.api = mastodon.Mastodon(
access_token=access_token, api_base_url=api_base_url
)
self.mastodon_accounts = mastodon_accounts
self.number_toots = number_toots
self.exclude_replies = exclude_repli... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/mastodon.html |
b317c9a823e8-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) -... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/facebook_chat.html |
3d4bd0b0a7e4-0 | Source code for langchain.document_loaders.tomarkdown
"""Loader that loads HTML to markdown using 2markdown."""
from __future__ import annotations
from typing import Iterator, List
import requests
from langchain.docstore.document import Document
from langchain.document_loaders.base import BaseLoader
[docs]class ToMarkd... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/tomarkdown.html |
7d21f0e5ecf7-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."""
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/markdown.html |
32b409ee7d1b-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.... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/image_captions.html |
32b409ee7d1b-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]:
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/image_captions.html |
a1b4b409ddaa-0 | Source code for langchain.document_loaders.html
"""Loader that uses unstructured to load HTML files."""
from typing import List
from langchain.document_loaders.unstructured import UnstructuredFileLoader
[docs]class UnstructuredHTMLLoader(UnstructuredFileLoader):
"""Loader that uses unstructured to load HTML files."... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/html.html |
db55a19f9388-0 | Source code for langchain.document_loaders.github
from abc import ABC
from datetime import datetime
from typing import Dict, Iterator, List, Literal, Optional, Union
import requests
from pydantic import BaseModel, root_validator, validator
from langchain.docstore.document import Document
from langchain.document_loaders... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/github.html |
db55a19f9388-1 | state: Optional[Literal["open", "closed", "all"]] = None
"""Filter on issue state. Can be one of: 'open', 'closed', 'all'."""
assignee: Optional[str] = None
"""Filter on assigned user. Pass 'none' for no user and '*' for any user."""
creator: Optional[str] = None
"""Filter on the user that created t... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/github.html |
db55a19f9388-2 | [docs] def lazy_load(self) -> Iterator[Document]:
"""
Get issues of a GitHub repository.
Returns:
A list of Documents with attributes:
- page_content
- metadata
- url
- title
- creator
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/github.html |
db55a19f9388-3 | """Create Document objects from a list of GitHub issues."""
metadata = {
"url": issue["html_url"],
"title": issue["title"],
"creator": issue["user"]["login"],
"created_at": issue["created_at"],
"comments": issue["comments"],
"state": issue[... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/github.html |
db55a19f9388-4 | return query_params
@property
def url(self) -> str:
return f"https://api.github.com/repos/{self.repo}/issues?{self.query_params}"
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 16, 2023. | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/github.html |
5f2b9a179cc1-0 | Source code for langchain.document_loaders.embaas
import base64
import warnings
from typing import Any, Dict, Iterator, List, Optional
import requests
from pydantic import BaseModel, root_validator, validator
from typing_extensions import NotRequired, TypedDict
from langchain.docstore.document import Document
from lang... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/embaas.html |
5f2b9a179cc1-1 | """The instruction to pass to the Embaas document extraction API."""
class EmbaasDocumentExtractionPayload(EmbaasDocumentExtractionParameters):
bytes: str
"""The base64 encoded bytes of the document to extract text from."""
class BaseEmbaasLoader(BaseModel):
embaas_api_key: Optional[str] = None
api_url:... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/embaas.html |
5f2b9a179cc1-2 | from langchain.document_loaders.embaas import EmbaasBlobLoader
loader = EmbaasBlobLoader(
params={
"should_embed": True,
"model": "e5-large-v2",
"chunk_size": 256,
"chunk_splitter": "CharacterTextSplitter"
... | rtdocs_stable/api.python.langchain.com/en/stable/_modules/langchain/document_loaders/embaas.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.