id
stringlengths
14
16
text
stringlengths
4
1.28k
source
stringlengths
54
121
4db1aa5fc4dc-4
metadata = self._get_metadata() if hasattr(element, "metadata"): metadata.update(element.metadata.to_dict()) page_number = metadata.get("page_number", 1) # Check if this page_number already exists in docs_dict if page_number not in text...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html
4db1aa5fc4dc-5
] 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]c...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html
4db1aa5fc4dc-6
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} def get_elements_from_api( file_path: Union[str, List[str], None] = None, file: Union[IO, Sequence[IO], N...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html
4db1aa5fc4dc-7
files=file, api_key=api_key, api_url=api_url, **unstructured_kwargs, ) elements = [] for _elements in _doc_elements: elements.extend(_elements) return elements else: from unstructured.partition.api import partition_via_api ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html
4db1aa5fc4dc-8
api_key: str = "", **unstructured_kwargs: Any, ): """Initialize with file path.""" if isinstance(file_path, str): validate_unstructured_version(min_unstructured_version="0.6.2") else: validate_unstructured_version(min_unstructured_version="0.6.3") self...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html
4db1aa5fc4dc-9
"""Loader that uses unstructured to load file IO objects.""" def __init__( self, file: Union[IO, Sequence[IO]], mode: str = "single", **unstructured_kwargs: Any, ): """Initialize with file path.""" self.file = file super().__init__(mode=mode, **unstructure...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html
4db1aa5fc4dc-10
mode: str = "single", url: str = "https://api.unstructured.io/general/v0/general", api_key: str = "", **unstructured_kwargs: Any, ): """Initialize with file path.""" if isinstance(file, collections.abc.Sequence): validate_unstructured_version(min_unstructured_vers...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/unstructured.html
928a54c6e8b6-0
Source code for langchain.document_loaders.word_document """Loader that loads word documents.""" import os import tempfile from abc import ABC from typing import List from urllib.parse import urlparse import requests from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html
928a54c6e8b6-1
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...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html
928a54c6e8b6-2
if hasattr(self, "temp_file"): self.temp_file.close() [docs] def load(self) -> List[Document]: """Load given path as single page.""" import docx2txt return [ Document( page_content=docx2txt.process(self.file_path), metadata={"source": se...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html
928a54c6e8b6-3
from unstructured.file_utils.filetype import FileType, detect_filetype unstructured_version = tuple( [int(x) for x in __unstructured_version__.split(".")] ) # NOTE(MthwRobinson) - magic will raise an import error if the libmagic # system dependency isn't installed. If it's no...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html
928a54c6e8b6-4
"Partitioning .doc files is only supported in unstructured>=0.4.11. " "Please upgrade the unstructured package and try again." ) if is_doc: from unstructured.partition.doc import partition_doc return partition_doc(filename=self.file_path, **self.unstructured_k...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/word_document.html
45008f3f51cc-0
Source code for langchain.document_loaders.blockchain import os import re import time from enum import Enum from typing import List, Optional import requests from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader class BlockchainType(Enum): """Enumerator of the suppo...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html
45008f3f51cc-1
The Loader uses the Alchemy API to interact with the blockchain. ALCHEMY_API_KEY environment variable must be set to use this loader. The API returns 100 NFTs per request and can be paginated using the startToken parameter. If get_all_tokens is set to True, the loader will get all tokens on the cont...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html
45008f3f51cc-2
""" def __init__( self, contract_address: str, blockchainType: BlockchainType = BlockchainType.ETH_MAINNET, api_key: str = "docs-demo", startToken: str = "", get_all_tokens: bool = False, max_execution_time: Optional[int] = None, ): self.contract_a...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html
45008f3f51cc-3
[docs] def load(self) -> List[Document]: result = [] current_start_token = self.startToken start_time = time.time() while True: url = ( f"https://{self.blockchainType}.g.alchemy.com/nft/v2/" f"{self.api_key}/getNFTsForCollection?withMetadata...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html
45008f3f51cc-4
metadata = { "source": self.contract_address, "blockchain": self.blockchainType, "tokenId": tokenId, } result.append(Document(page_content=content, metadata=metadata)) # exit after the first API call if get_all_token...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html
45008f3f51cc-5
) return result # add one to the tokenId, ensuring the correct tokenId format is used def _get_next_tokenId(self, tokenId: str) -> str: value_type = self._detect_value_type(tokenId) if value_type == "hex_0x": value_int = int(tokenId, 16) elif value_type == "hex_0xbf":...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html
45008f3f51cc-6
return "0xbf" + format(result, "0" + str(len(tokenId) - 4) + "x") else: return str(result) # A smart contract can use different formats for the tokenId @staticmethod def _detect_value_type(tokenId: str) -> str: if isinstance(tokenId, int): return "int" elif to...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blockchain.html
e075db98eb6e-0
Source code for langchain.document_loaders.evernote """Load documents from Evernote. https://gist.github.com/foxmask/7b29c43a161e001ff04afdb2f181e31c """ import hashlib import logging from base64 import b64decode from time import strptime from typing import Any, Dict, Iterator, List, Optional from langchain.docstore.do...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
e075db98eb6e-1
of the Document, any non content metadata (e.g. 'author', 'created', 'updated' etc. but not 'content-raw' or 'resource') tags on the note will be extracted and stored as metadata on the Document. Args: file_path (str): The path to the notebook export with a .enex extension load_single_docume...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
e075db98eb6e-2
self.load_single_document = load_single_document [docs] def load(self) -> List[Document]: """Load documents from EverNote export file.""" documents = [ Document( page_content=note["content"], metadata={ **{ key: v...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
e075db98eb6e-3
) ] @staticmethod def _parse_content(content: str) -> str: try: import html2text return html2text.html2text(content).strip() except ImportError as e: logging.error( "Could not import `html2text`. Although it is not a required package " ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
e075db98eb6e-4
# Sometimes elem.text is None rsc_dict[elem.tag] = b64decode(elem.text) if elem.text else b"" rsc_dict["hash"] = hashlib.md5(rsc_dict[elem.tag]).hexdigest() else: rsc_dict[elem.tag] = elem.text return rsc_dict @staticmethod def _parse_note(note...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
e075db98eb6e-5
# A copy of original content note_dict["content-raw"] = elem.text elif elem.tag == "resource": resources.append(EverNoteLoader._parse_resource(elem)) elif elem.tag == "created" or elem.tag == "updated": note_dict[elem.tag] = strptime(elem.text, "%Y...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
e075db98eb6e-6
@staticmethod def _parse_note_xml(xml_file: str) -> Iterator[Dict[str, Any]]: """Parse Evernote xml.""" # Without huge_tree set to True, parser may complain about huge text node # Try to recover, because there may be " ", which will cause # "XMLSyntaxError: Entity 'nbsp' not def...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
e075db98eb6e-7
) for action, elem in context: if elem.tag == "note": yield EverNoteLoader._parse_note(elem)
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
3f5946ba1aa8-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, fil...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/srt.html
3f5946ba1aa8-1
text = " ".join([t.text for t in parsed_info]) metadata = {"source": self.file_path} return [Document(page_content=text, metadata=metadata)]
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/srt.html
be5efb3be8d7-0
Source code for langchain.document_loaders.gutenberg """Loader that loads .txt web files.""" from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class GutenbergLoader(BaseLoader): """Loader that uses urllib to load .txt web files.""" ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gutenberg.html
be5efb3be8d7-1
elements = urlopen(self.file_path) text = "\n\n".join([str(el.decode("utf-8-sig")) for el in elements]) metadata = {"source": self.file_path} return [Document(page_content=text, metadata=metadata)]
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/gutenberg.html
c15b07699442-0
Source code for langchain.document_loaders.sitemap """Loader that fetches a sitemap and loads those URLs.""" import itertools import re from typing import Any, Callable, Generator, Iterable, List, Optional from langchain.document_loaders.web_base import WebBaseLoader from langchain.schema import Document def _default_p...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html
c15b07699442-1
def __init__( self, web_path: str, filter_urls: Optional[List[str]] = None, parsing_function: Optional[Callable] = None, blocksize: Optional[int] = None, blocknum: int = 0, meta_function: Optional[Callable] = None, is_local: bool = False, ): ""...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html
c15b07699442-2
meta_function: Function to parse bs4.Soup output for metadata remember when setting this method to also copy metadata["loc"] to metadata["source"] if you are using this field is_local: whether the sitemap is a local file """ if blocksize is not None and blocks...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html
c15b07699442-3
self.meta_function = meta_function or _default_meta_function self.blocksize = blocksize self.blocknum = blocknum self.is_local = is_local [docs] def parse_sitemap(self, soup: Any) -> List[dict]: """Parse sitemap xml and load into a list of dicts.""" els = [] for url in...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html
c15b07699442-4
if (prop := url.find(tag)) } ) for sitemap in soup.find_all("sitemap"): loc = sitemap.find("loc") if not loc: continue soup_child = self.scrape_all([loc.text], "xml")[0] els.extend(self.parse_sitemap(soup_child)) ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html
c15b07699442-5
soup = self.scrape("xml") els = self.parse_sitemap(soup) if self.blocksize is not None: elblocks = list(_batch_block(els, self.blocksize)) blockcount = len(elblocks) if blockcount - 1 < self.blocknum: raise ValueError( "Selected sit...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/sitemap.html
39fe2db54e03-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, ) ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-1
raise ValueError("unknown content format") [docs]class ConfluenceLoader(BaseLoader): """ Load Confluence pages. Port of https://llamahub.ai/l/confluence This currently supports username/api_key, Oauth2 login or personal access token authentication. Specify a list page_ids and/or space_key to load in...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-2
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...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-3
:param url: _description_ :type url: str :param api_key: _description_, defaults to None :type api_key: str, optional :param username: _description_, defaults to None :type username: str, optional :param oauth2: _description_, defaults to {} :type oauth2: dict, optional :param token: _de...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-4
: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__( ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-5
errors = ConfluenceLoader.validate_init_args( url, api_key, username, oauth2, token ) if errors: raise ValueError(f"Error(s) while validating input: {errors}") self.base_url = url self.number_of_retries = number_of_retries self.min_retry_seconds = min_retr...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-6
self.confluence = Confluence( url=url, token=token, cloud=cloud, **confluence_kwargs ) else: self.confluence = Confluence( url=url, username=username, password=api_key, cloud=cloud, **confluen...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-7
if (api_key and not username) or (username and not api_key): errors.append( "If one of `api_key` or `username` is provided, " "the other must be as well." ) if (api_key or username) and oauth2: errors.append( "Cannot provide a v...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-8
"`['access_token', 'access_token_secret', 'consumer_key', 'key_cert']`" ) 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...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-9
limit: Optional[int] = 50, max_pages: Optional[int] = 1000, ocr_languages: Optional[str] = None, ) -> List[Document]: """ :param space_key: Space key retrieved from a confluence URL, defaults to None :type space_key: Optional[str], optional :param page_ids: List of sp...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-10
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...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-11
:raises ValueError: _description_ :raises ImportError: _description_ :return: _description_ :rtype: List[Document] """ if not space_key and not page_ids and not label and not cql: raise ValueError( "Must specify at least one among `space_key`, `page_id...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-12
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, ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-13
docs += self.process_pages( pages, include_restricted_content, include_attachments, include_comments, content_format, ocr_languages, ) if page_ids: for page_id in page_ids: get...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-14
if not include_restricted_content and not self.is_public_page(page): continue doc = self.process_page( page, include_attachments, include_comments, content_format, ocr_languages, ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-15
return response.get("results", []) [docs] def paginate_request(self, retrieval_method: Callable, **kwargs: Any) -> List: """Paginate the various methods to retrieve groups of pages. Unfortunately, due to page size, sometimes the Confluence API doesn't match the limit value. If `limit` is >10...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-16
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 used to retrieve docs :type retrieval_method: callable :return: List of...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-17
), before_sleep=before_sleep_log(logger, logging.WARNING), )(retrieval_method) batch = get_pages(**kwargs, start=len(docs)) if not batch: break docs.extend(batch) return docs[:max_pages] [docs] def is_public_page(self, page: dict...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-18
include_comments: bool, content_format: ContentFormat, ocr_languages: Optional[str] = None, ) -> List[Document]: """Process a list of pages into a list of documents.""" docs = [] for page in pages: if not include_restricted_content and not self.is_public_page(page...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-19
) -> Document: try: from bs4 import BeautifulSoup # type: ignore except ImportError: raise ImportError( "`beautifulsoup4` package not found, please run " "`pip install beautifulsoup4`" ) if include_attachments: atta...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-20
" ", strip=True ) for comment in comments ] text = text + "".join(comment_texts) return Document( page_content=text, metadata={ "title": page["title"], "id": page["id"], "source": self...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-21
# poppler and tesseract attachments = self.confluence.get_attachments_from_content(page_id)["results"] texts = [] for attachment in attachments: media_type = attachment["metadata"]["mediaType"] absolute_url = self.base_url + attachment["_links"]["download"] ti...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-22
elif media_type == "application/vnd.ms-excel": text = title + self.process_xls(absolute_url) elif media_type == "image/svg+xml": text = title + self.process_svg(absolute_url, ocr_languages) else: continue texts.append(text) retu...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-23
) response = self.confluence.request(path=link, absolute=True) text = "" if ( response.status_code != 200 or response.content == b"" or response.content is None ): return text try: images = convert_from_bytes(response.co...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-24
except ImportError: raise ImportError( "`pytesseract` or `Pillow` package not found, " "please run `pip install pytesseract Pillow`" ) response = self.confluence.request(path=link, absolute=True) text = "" if ( response.status_c...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-25
except ImportError: raise ImportError( "`docx2txt` package not found, please run `pip install docx2txt`" ) response = self.confluence.request(path=link, absolute=True) text = "" if ( response.status_code != 200 or response.content =...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-26
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...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-27
from reportlab.graphics import renderPM # noqa: F401 from svglib.svglib import svg2rlg # noqa: F401 except ImportError: raise ImportError( "`pytesseract`, `Pillow`, `reportlab` or `svglib` package not found, " "please run `pip install pytesseract Pillow ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
39fe2db54e03-28
image = Image.open(img_data) return pytesseract.image_to_string(image, lang=ocr_languages)
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
1d2a5ac4608a-0
Source code for langchain.document_loaders.text import logging from typing import List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders.helpers import detect_file_encodings logger = logging.getLogger(__name__) [docs]class T...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/text.html
1d2a5ac4608a-1
"""Initialize with file path.""" self.file_path = file_path self.encoding = encoding self.autodetect_encoding = autodetect_encoding [docs] def load(self) -> List[Document]: """Load from file path.""" text = "" try: with open(self.file_path, encoding=self.en...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/text.html
1d2a5ac4608a-2
except Exception as e: raise RuntimeError(f"Error loading {self.file_path}") from e metadata = {"source": self.file_path} return [Document(page_content=text, metadata=metadata)]
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/text.html
cd3f4336ba73-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] ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/azlyrics.html
ad7486d31ad1-0
Source code for langchain.document_loaders.weather """Simple reader that reads weather data from OpenWeatherMap API""" from __future__ import annotations from datetime import datetime from typing import Iterator, List, Optional, Sequence from langchain.docstore.document import Document from langchain.document_loaders.b...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/weather.html
ad7486d31ad1-1
self.client = client self.places = places [docs] @classmethod def from_params( cls, places: Sequence[str], *, openweathermap_api_key: Optional[str] = None ) -> WeatherDataLoader: client = OpenWeatherMapAPIWrapper(openweathermap_api_key=openweathermap_api_key) return cls(client...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/weather.html
d89ee163bbfd-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_...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/email.html
d89ee163bbfd-1
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(BaseLo...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/email.html
d89ee163bbfd-2
"`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={ ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/email.html
e596df7fd730-0
Source code for langchain.document_loaders.odt """Loader that loads Open Office ODT files.""" from typing import Any, List from langchain.document_loaders.unstructured import ( UnstructuredFileLoader, validate_unstructured_version, ) [docs]class UnstructuredODTLoader(UnstructuredFileLoader): """Loader that ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/odt.html
1d4b6e2d55a2-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.docume...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
1d4b6e2d55a2-1
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=...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
1d4b6e2d55a2-2
): """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. ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
1d4b6e2d55a2-3
) 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...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
1d4b6e2d55a2-4
"""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 = [] ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
1d4b6e2d55a2-5
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 cou...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
1d4b6e2d55a2-6
) # 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: ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
1d4b6e2d55a2-7
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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
1d4b6e2d55a2-8
# 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 = Director...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
1d4b6e2d55a2-9
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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
1d4b6e2d55a2-10
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. ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
1d4b6e2d55a2-11
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://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/blackboard.html
1811f4804ea2-0
Source code for langchain.document_loaders.telegram """Loader that loads Telegram chat json dump.""" from __future__ import annotations import asyncio import json from pathlib import Path from typing import TYPE_CHECKING, Dict, List, Optional, Union from langchain.docstore.document import Document from langchain.docume...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
1811f4804ea2-1
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) with open(p, encoding="utf8") as f: d = json.load(f) text = "".join( concate...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
1811f4804ea2-2
# Take a single string as one page text = [text] page_docs = [Document(page_content=page) for page in text] # Add page numbers as metadata for i, doc in enumerate(page_docs): doc.metadata["page"] = i + 1 # Split pages into chunks doc_chunks = [] for doc in page_docs: text...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
1811f4804ea2-3
) # Add sources a metadata doc.metadata["source"] = f"{doc.metadata['page']}-{doc.metadata['chunk']}" doc_chunks.append(doc) return doc_chunks [docs]class TelegramChatApiLoader(BaseLoader): """Loader that loads Telegram chat json directory dump.""" def __init__( s...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
1811f4804ea2-4
self.file_path = file_path [docs] async def fetch_data_from_telegram(self) -> None: """Fetch data from Telegram API and save it as a JSON file.""" from telethon.sync import TelegramClient data = [] async with TelegramClient(self.username, self.api_id, self.api_hash) as client: ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
1811f4804ea2-5
} ) with open(self.file_path, "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=4) def _get_message_threads(self, data: pd.DataFrame) -> dict: """Create a dictionary of message threads from the given data. Args: data (pd.DataFr...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
1811f4804ea2-6
""" Recursively find all replies to a given parent message ID. Args: parent_id (int): The parent message ID. reply_data (pd.DataFrame): A DataFrame containing reply messages. Returns: list: A list of message IDs that are replies to the ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
1811f4804ea2-7
# Filter out reply messages and drop rows with NaN in 'reply_to_id' reply_messages = data[data["is_reply"]].dropna(subset=["reply_to_id"]) # Convert 'reply_to_id' to integer reply_messages["reply_to_id"] = reply_messages["reply_to_id"].astype(int) # Create a dictionary of message threads...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
1811f4804ea2-8
on the list of message threads. Args: message_threads (dict): A dictionary where the key is the parent message \ ID and the value is a list of message IDs in ascending order. data (pd.DataFrame): A DataFrame containing the conversation data: - message.send...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
1811f4804ea2-9
.tolist() ) message_texts = [str(elem) for elem in message_texts] # Combine the message texts combined_text += " ".join(message_texts) + ".\n" return combined_text.strip() [docs] def load(self) -> List[Document]: """Load documents.""" if self.ch...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
1811f4804ea2-10
except ImportError: raise ImportError( """`pandas` package not found. please install with `pip install pandas` """ ) normalized_messages = pd.json_normalize(d) df = pd.DataFrame(normalized_messages) message_threads = self._...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
93d6d48400eb-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...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/embaas.html