id
stringlengths
14
15
text
stringlengths
49
2.47k
source
stringlengths
61
166
8329be7fba50-0
Source code for langchain.memory.chat_message_histories.file import json import logging from pathlib import Path from typing import List from langchain.schema import ( BaseChatMessageHistory, ) from langchain.schema.messages import BaseMessage, messages_from_dict, messages_to_dict logger = logging.getLogger(__name_...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/file.html
0049f2258d9d-0
Source code for langchain.memory.chat_message_histories.postgres import json import logging from typing import List from langchain.schema import ( BaseChatMessageHistory, ) from langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict logger = logging.getLogger(__name__) DEFAULT_CONNECTION...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html
0049f2258d9d-1
items = [record["message"] for record in self.cursor.fetchall()] messages = messages_from_dict(items) return messages [docs] def add_message(self, message: BaseMessage) -> None: """Append the message to the record in PostgreSQL""" from psycopg import sql query = sql.SQL("INSER...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/postgres.html
dde66c42395f-0
Source code for langchain.memory.chat_message_histories.mongodb import json import logging from typing import List from langchain.schema import ( BaseChatMessageHistory, ) from langchain.schema.messages import BaseMessage, _message_to_dict, messages_from_dict logger = logging.getLogger(__name__) DEFAULT_DBNAME = "c...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html
dde66c42395f-1
except errors.OperationFailure as error: logger.error(error) if cursor: items = [json.loads(document["History"]) for document in cursor] else: items = [] messages = messages_from_dict(items) return messages [docs] def add_message(self, message: Base...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/mongodb.html
076a75875f80-0
Source code for langchain.memory.chat_message_histories.rocksetdb from datetime import datetime from time import sleep from typing import Any, Callable, List, Union from uuid import uuid4 from langchain.schema import BaseChatMessageHistory from langchain.schema.messages import BaseMessage, _message_to_dict, messages_fr...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html
076a75875f80-1
if (curr - start).total_seconds() * 1000 > timeout: raise TimeoutError(f"{method} timed out at {timeout} ms") sleep(RocksetChatMessageHistory.SLEEP_INTERVAL_MS / 1000) def _query(self, query: str, **query_params: Any) -> List[Any]: """Executes an SQL statement and returns the res...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html
076a75875f80-2
"""Sleeps until the collection for this message history is ready to be queried """ self._wait_until( lambda: self._collection_is_ready(), RocksetChatMessageHistory.CREATE_TIMEOUT_MS, ) def _wait_until_message_added(self, message_id: str) -> None: """Sl...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html
076a75875f80-3
"""Constructs a new RocksetChatMessageHistory. Args: - session_id: The ID of the chat session - client: The RocksetClient object to use to query - collection: The name of the collection to use to store chat messages. If a collection with the given na...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html
076a75875f80-4
self.location = f'"{self.workspace}"."{self.collection}"' self.rockset = rockset self.messages_key = messages_key self.message_uuid_method = message_uuid_method self.sync = sync if not self._collection_exists(): self._create_collection() self._wait_until_c...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html
076a75875f80-5
], ) ], ) if self.sync: self._wait_until_message_added(message.additional_kwargs["id"]) [docs] def clear(self) -> None: """Removes all messages from the chat history""" self._create_empty_doc() if self.sync: self._wait_until(...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/rocksetdb.html
8b7dce9024a9-0
Source code for langchain.memory.chat_message_histories.streamlit from typing import List from langchain.schema import ( BaseChatMessageHistory, ) from langchain.schema.messages import BaseMessage [docs]class StreamlitChatMessageHistory(BaseChatMessageHistory): """ Chat message history that stores messages ...
https://api.python.langchain.com/en/latest/_modules/langchain/memory/chat_message_histories/streamlit.html
eac0fc9e46f9-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
eac0fc9e46f9-1
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
a48a0e042aec-0
Source code for langchain.document_loaders.rtf """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 unstruct...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rtf.html
a48a0e042aec-1
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) ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rtf.html
c89c9655e346-0
Source code for langchain.document_loaders.youtube """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 pydantic.datacl...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html
c89c9655e346-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) -...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html
c89c9655e346-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...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html
c89c9655e346-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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html
c89c9655e346-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...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html
c89c9655e346-5
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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html
c89c9655e346-6
[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"): raise ValueError("...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html
c89c9655e346-7
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 def _get_document_for_channel(s...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html
c89c9655e346-8
metadata=meta_data, ) ) except (TranscriptsDisabled, NoTranscriptFound) as e: if self.continue_on_failure: logger.error( "Error fetching transscript " + f" {ite...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/youtube.html
12567918a8ae-0
Source code for langchain.document_loaders.psychic """Loads documents from Psychic.dev.""" from typing import List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class PsychicLoader(BaseLoader): """Loads documents from Psychic.dev.""" [docs] ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/psychic.html
2c8989a57408-0
Source code for langchain.document_loaders.recursive_url_loader import asyncio import re from typing import Callable, Iterator, List, Optional, Set, Union from urllib.parse import urljoin, urlparse import requests from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [d...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html
2c8989a57408-1
self.max_depth = max_depth if max_depth is not None else 2 self.timeout = timeout if timeout is not None else 10 self.prevent_outside = prevent_outside if prevent_outside is not None else True def _get_sub_links(self, raw_html: str, base_url: str) -> List[str]: """This function extracts all ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html
2c8989a57408-2
if link.startswith("/") and not link.startswith("//"): absolute_paths.append(urljoin(base_url, link)) continue # Some may have omitted the protocol like //to/path if link.startswith("//"): absolute_paths.append(f"{urlparse(base_url).scheme}:{link}"...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html
2c8989a57408-3
Args: url: The URL to crawl. visited: A set of visited URLs. """ if depth > self.max_depth: return [] # Add a trailing slash if not present if not url.endswith("/"): url += "/" # Exclude the root and parent from a list visit...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html
2c8989a57408-4
) -> List[Document]: """Recursively get all child links starting with the path of the input URL. Args: url: The URL to crawl. visited: A set of visited URLs. depth: To reach the current url, how many pages have been visited. """ try: import...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html
2c8989a57408-5
return [] absolute_paths = self._get_sub_links(text, url) # Worker will be only called within the current function # Worker function will process the link # then recursively call get_child_links_recursive to process the children async def worker(link: str) -> ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html
2c8989a57408-6
sub_tasks = [] for link in absolute_paths: sub_tasks.append( self._async_get_child_links_recursive(link, visited, depth + 1) ) # sub_tasks returns coroutines of list, # so we need to flatten the list await asyncio.gather(*sub_tasks)...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/recursive_url_loader.html
1394ec5ba77a-0
Source code for langchain.document_loaders.s3_file """Loading logic for loading documents from an AWS S3 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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/s3_file.html
e66f101762a1-0
Source code for langchain.document_loaders.toml import json from pathlib import Path from typing import Iterator, List, Union from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class TomlLoader(BaseLoader): """ A TOML document loader that inherits from ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/toml.html
3ce4dfcece68-0
Source code for langchain.document_loaders.chatgpt """Load conversations from ChatGPT data export""" import datetime import json from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]def concatenate_rows(message: dict, title: str) -> str: ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/chatgpt.html
3ce4dfcece68-1
documents = [] for d in data: title = d["title"] messages = d["mapping"] text = "".join( [ concatenate_rows(messages[key]["message"], title) for idx, key in enumerate(messages) if not ( ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/chatgpt.html
e3aa77c39e4d-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
e3aa77c39e4d-1
Confluence API supports difference format of page content. The storage format is the 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 c...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
e3aa77c39e4d-2
:type min_retry_seconds: Optional[int], optional :param max_retry_seconds: defaults to 10 :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 in...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
e3aa77c39e4d-3
) if oauth2: self.confluence = Confluence( url=url, oauth2=oauth2, cloud=cloud, **confluence_kwargs ) elif token: self.confluence = Confluence( url=url, token=token, cloud=cloud, **confluence_kwargs ) else: ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
e3aa77c39e4d-4
errors.append( "You have either omitted require keys or added extra " "keys to the oauth2 dictionary. key values should be " "`['access_token', 'access_token_secret', 'consumer_key', 'key_cert']`" ) if token and (api_key or username or oauth2): ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
e3aa77c39e4d-5
:param cql: CQL Expression, defaults to None :type cql: Optional[str], optional :param include_restricted_content: defaults to False :type include_restricted_content: bool, optional :param include_archived_content: Whether to include archived content, ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
e3aa77c39e4d-6
docs = [] if space_key: pages = self.paginate_request( self.confluence.get_all_pages_from_space, space=space_key, limit=limit, max_pages=max_pages, status="any" if include_archived_content else "current", ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
e3aa77c39e4d-7
self.number_of_retries # type: ignore[arg-type] ), wait=wait_exponential( multiplier=1, # type: ignore[arg-type] min=self.min_retry_seconds, # type: ignore[arg-type] max=self.max_retry_seconds, # type: ig...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
e3aa77c39e4d-8
seems to cap the response to 100. Also, due to the Atlassian Python package, we don't get the "next" values from the "_links" key because they only return the value from the result key. So here, the pagination starts from 0 and goes until the max_pages, getting the `limit` number of page...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
e3aa77c39e4d-9
"""Check if a page is publicly accessible.""" restrictions = self.confluence.get_all_restrictions_for_content(page["id"]) return ( page["status"] == "current" and not restrictions["read"]["restrictions"]["user"]["results"] and not restrictions["read"]["restrictions"][...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
e3aa77c39e4d-10
"`pip install markdownify`" ) else: try: from bs4 import BeautifulSoup # type: ignore except ImportError: raise ImportError( "`beautifulsoup4` package not found, please run " "`pip install beautifuls...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
e3aa77c39e4d-11
) -> List[str]: try: from PIL import Image # noqa: F401 except ImportError: raise ImportError( "`Pillow` package not found, " "please run `pip install Pillow`" ) # depending on setup you may also need to set the correct path for # popp...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
e3aa77c39e4d-12
try: import pytesseract # noqa: F401 from pdf2image import convert_from_bytes # noqa: F401 except ImportError: raise ImportError( "`pytesseract` or `pdf2image` package not found, " "please run `pip install pytesseract pdf2image`" ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
e3aa77c39e4d-13
image = Image.open(BytesIO(response.content)) except OSError: return text return pytesseract.image_to_string(image, lang=ocr_languages) [docs] def process_doc(self, link: str) -> str: try: import docx2txt # noqa: F401 except ImportError: raise Impo...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
e3aa77c39e4d-14
file_extension = os.path.splitext(filename)[1] if file_extension.startswith( ".csv" ): # if the extension found in the url is ".csv" content_string = response.content.decode("utf-8") df = pd.read_csv(io.StringIO(content_string)) text += df.to_string(index...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
e3aa77c39e4d-15
): return text drawing = svg2rlg(BytesIO(response.content)) img_data = BytesIO() renderPM.drawToFile(drawing, img_data, fmt="PNG") img_data.seek(0) 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
f173fbeb6f6b-0
Source code for langchain.document_loaders.powerpoint """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...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html
f173fbeb6f6b-1
try: import magic # noqa: F401 is_ppt = detect_filetype(self.file_path) == FileType.PPT except ImportError: _, extension = os.path.splitext(str(self.file_path)) is_ppt = extension == ".ppt" if is_ppt and unstructured_version < (0, 4, 11): rais...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html
b0de701ffa6a-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
b0de701ffa6a-1
"""Initialize with file path.""" self.file_path = file_path 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"], ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
b0de701ffa6a-2
if elem.tag == "data": # 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 ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
b0de701ffa6a-3
@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 "&nbsp;", which will cause # "XMLSyntaxError: Entity 'nbsp' not def...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
ccc0283c2e38-0
Source code for langchain.document_loaders.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 AzureBlobSto...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/azure_blob_storage_file.html
ce2c0ad5ea75-0
Source code for langchain.document_loaders.xorbits from typing import Any, Iterator, List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class XorbitsLoader(BaseLoader): """Load Xorbits DataFrame.""" [docs] def __init__(self, data_frame: Any, page_co...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/xorbits.html
502e08f63d6f-0
Source code for langchain.document_loaders.obsidian """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): """Loads Obsidian files ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obsidian.html
502e08f63d6f-1
"""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")) do...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obsidian.html
8d5df2fd4ac1-0
Source code for langchain.document_loaders.rss """Loader that uses unstructured to load HTML files.""" import logging from typing import Any, Iterator, List, Optional, Sequence from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders.news im...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rss.html
8d5df2fd4ac1-1
Finally, newspaper is used to process each article: https://newspaper.readthedocs.io/en/latest/ """ # noqa: E501 [docs] def __init__( self, urls: Optional[Sequence[str]] = None, opml: Optional[str] = None, continue_on_failure: bool = True, show_progress_bar: bool = Fa...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rss.html
8d5df2fd4ac1-2
"Package listparser must be installed if the opml arg is used. " "Please install with 'pip install listparser' or use the " "urls arg instead." ) from e rss = listparser.parse(self.opml) return [feed.url for feed in rss.feeds] [docs] def lazy_load(self) -> ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/rss.html
a50dbbea5e10-0
Source code for langchain.document_loaders.hn """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."...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hn.html
a50dbbea5e10-1
title = lineItem.find("span", {"class": "titleline"}).text.strip() metadata = { "source": self.web_path, "title": title, "link": link, "ranking": ranking, } documents.append( Document( ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/hn.html
4f4047bbfecd-0
Source code for langchain.document_loaders.telegram """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.document_loaders.b...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
4f4047bbfecd-1
if isinstance(text, str): # 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 = [] ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
4f4047bbfecd-2
file_path: The file path to save the data to. Defaults to "telegram_data.json". """ self.chat_entity = chat_entity self.api_id = api_id self.api_hash = api_hash self.username = username self.file_path = file_path [docs] async def fetch_data_from_telegr...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
4f4047bbfecd-3
the value is a list of message IDs in ascending order. """ def find_replies(parent_id: int, reply_data: pd.DataFrame) -> List[int]: """ Recursively find all replies to a given parent message ID. Args: parent_id (int): The parent message ID. ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
4f4047bbfecd-4
) -> str: """ Combine the message texts for each parent message ID based \ 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. ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
4f4047bbfecd-5
d = json.load(f) try: import pandas as pd except ImportError: raise ImportError( """`pandas` package not found. please install with `pip install pandas` """ ) normalized_messages = pd.json_normalize(d) d...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/telegram.html
c0735c81ab72-0
Source code for langchain.document_loaders.arxiv from typing import List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.utilities.arxiv import ArxivAPIWrapper [docs]class ArxivLoader(BaseLoader): """Loads a query result from arxiv.org...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/arxiv.html
7757c6036a66-0
Source code for langchain.document_loaders.obs_file # coding:utf-8 import os import tempfile from typing import Any, List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders.unstructured import UnstructuredFileLoader [docs]cla...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obs_file.html
7757c6036a66-1
- "get_token_from_ecs" (bool, optional): Whether to retrieve the security token from ECS. Defaults to False if not provided. If set to True, `ak`, `sk`, and `token` will be ignored. Raises: ValueError: If the `esdk-obs-python` package is not installed. TypeError: If the provided `client`...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obs_file.html
7757c6036a66-2
from obs import ObsClient except ImportError: raise ImportError( "Could not import esdk-obs-python python package. " "Please install it with `pip install esdk-obs-python`." ) if not client: if not endpoint: raise ValueEr...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/obs_file.html
70e3630851c4-0
Source code for langchain.document_loaders.pdf """Loads PDF files.""" import json import logging import os import tempfile import time from abc import ABC from io import StringIO from pathlib import Path from typing import Any, Iterator, List, Mapping, Optional, Sequence, Union from urllib.parse import urlparse import ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
70e3630851c4-1
""" def _get_elements(self) -> List: from unstructured.partition.pdf import partition_pdf return partition_pdf(filename=self.file_path, **self.unstructured_kwargs) [docs]class BasePDFLoader(BaseLoader, ABC): """Base loader class for PDF files. Defaults to check for local file, but if the fil...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
70e3630851c4-2
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_dir"): self.temp_dir.cleanup() @staticmethod def _is_valid_url(url: str) -> bool: """Check if the ur...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
70e3630851c4-3
except ImportError: raise ImportError( "pypdf package not found, please install it with " "`pip install pypdf`" ) self.parser = PyPDFParser(password=password) super().__init__(file_path) [docs] def load(self) -> List[Document]: """Load given path as pag...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
70e3630851c4-4
load_hidden: bool = False, recursive: bool = False, ): self.path = path self.glob = glob self.load_hidden = load_hidden self.recursive = recursive self.silent_errors = silent_errors @staticmethod def _is_visible(path: Path) -> bool: return not any(part...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
70e3630851c4-5
[docs] def load(self) -> List[Document]: """Eagerly load the content.""" return list(self.lazy_load()) [docs] def lazy_load( self, ) -> Iterator[Document]: """Lazily load documents.""" blob = Blob.from_path(self.file_path) yield from self.parser.parse(blob) [doc...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
70e3630851c4-6
[docs] def __init__(self, file_path: str) -> None: """Initialize with a file path.""" try: import fitz # noqa:F401 except ImportError: raise ImportError( "`PyMuPDF` package not found, please install it with " "`pip install pymupdf`" ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
70e3630851c4-7
""" super().__init__(file_path) self.mathpix_api_key = get_from_dict_or_env( kwargs, "mathpix_api_key", "MATHPIX_API_KEY" ) self.mathpix_api_id = get_from_dict_or_env( kwargs, "mathpix_api_id", "MATHPIX_API_ID" ) self.processed_file_format = proces...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
70e3630851c4-8
Returns: None """ url = self.url + "/" + pdf_id for _ in range(0, self.max_wait_time_seconds, 5): response = requests.get(url, headers=self.headers) response_data = response.json() status = response_data.get("status", None) if status == "completed"...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
70e3630851c4-9
pdf_id = self.send_pdf() contents = self.get_processed_pdf(pdf_id) if self.should_clean_pdf: contents = self.clean_pdf(contents) metadata = {"source": self.source, "file_path": self.source} return [Document(page_content=contents, metadata=metadata)] [docs]class PDFPlumberLoad...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
70e3630851c4-10
access the Amazon Textract service. Example: .. code-block:: python from langchain.document_loaders import AmazonTextractPDFLoader loader = AmazonTextractPDFLoader( file_path="s3://pdfs/myfile.pdf" ) document = loader.load() """ [docs] d...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
70e3630851c4-11
else: features = [] if credentials_profile_name or region_name or endpoint_url: try: import boto3 if credentials_profile_name is not None: session = boto3.Session(profile_name=credentials_profile_name) else: ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
70e3630851c4-12
else: blob = Blob.from_path(self.file_path) if AmazonTextractPDFLoader._get_number_of_pages(blob) > 1: raise ValueError( f"the file {blob.path} is a multi-page document, \ but not stored on S3. \ Textract requires multi-...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/pdf.html
9eb948990088-0
Source code for langchain.document_loaders.stripe """Loader that fetches data from Stripe""" 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_dic...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/stripe.html
9eb948990088-1
return [Document(page_content=text, metadata=metadata)] def _get_resource(self) -> List[Document]: endpoint = STRIPE_ENDPOINTS.get(self.resource) if endpoint is None: return [] return self._make_request(endpoint) [docs] def load(self) -> List[Document]: return self._ge...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/stripe.html
8eca11891056-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...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html
8eca11891056-1
from unstructured.__version__ import __version__ as __unstructured_version__ self.__version = __unstructured_version__ except ImportError: raise ImportError( "unstructured package not found, please install it with " "`pip install unstructured`" ...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html
8eca11891056-2
_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...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html
8eca11891056-3
except Exception as e: if self.continue_on_failure: logger.error(f"Error fetching or processing {url}, exception: {e}") continue else: raise e if self.mode == "single": text = "\n\n".join([str(el) for...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/url.html
afdabd1a374a-0
Source code for langchain.document_loaders.facebook_chat """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 [docs]def concatenate_rows(row: dict) -> str:...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/facebook_chat.html
f6a2f9298684-0
Source code for langchain.document_loaders.bigquery from __future__ import annotations from typing import TYPE_CHECKING, List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader if TYPE_CHECKING: from google.auth.credentials import Credentials [docs]clas...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html
f6a2f9298684-1
""" self.query = query self.project = project self.page_content_columns = page_content_columns self.metadata_columns = metadata_columns self.credentials = credentials [docs] def load(self) -> List[Document]: try: from google.cloud import bigquery ex...
https://api.python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html