You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
10 Hrs
41 Min
7 Seg

Cargar HTML y Directorio con LangChain

15/26
Resources

In this class, we explore how LangChain allows us to load and process HTML files using specialized tools called document loaders. Below, we break down the key points for taking advantage of this functionality, as well as some concepts and best practices for managing multiple files and directories.

1. Loading HTML files in LangChain

HTML files are essential for structuring and displaying content on the web. LangChain allows you to load these files and treat them as actionable documents, which means you can extract text, metadata and do analysis on the content using document loaders.

a) Document Loaders for HTML

LangChain has specific loaders for different file types, including HTML. One of the most common is Beautiful Soup, a Python library used to work with HTML files, facilitating the extraction of structured information.

  • Why use Beautiful Soup: It is a robust tool for parsing HTML and is widely used in web scraping projects. If you already have experience with Beautiful Soup, its integration with LangChain will be familiar to you.

HTML loading process:

  1. Installing Beautiful Soup: You need to install this library to work with HTML files within LangChain.
  2. Load the HTML file: Once installed, you can use Beautiful Soup's HTML loader to load the file and start extracting text and metadata, such as the page title or any other element you want to process.

b) Content and Metadata Extraction

When loading an HTML file, LangChain not only allows you to access the text of the document, but also the associated metadata, such as the file name, path, title, etc. This metadata can be useful in projects where you need to reference the source of the information or in cases of analysis of large quantities of documents.

2. Load Directories with Multiple Files

One of the most powerful features of LangChain is the ability to load entire directories containing multiple files, such as PDFs, CSVs or HTMLs. This is especially useful when working with large volumes of data distributed across different files.

a) Directory Upload

You can load the entire contents of a directory and specify which type of files you want to process (for example, HTML only or CSV only). This is done through a directory loader, which automates the loading of multiple files and allows you to process them in sequence.

  • Importance of Specific Loaders: It is important to use the right loader for each file type. For example, if in a directory you have PDFs and HTMLs, and you only need to process the HTMLs, the HTML loader will allow you to load only those files.

b) Progress Bar

When working with many files, LangChain offers an option to display a progress bar, which allows you to view the loading status of each document in real time. This is useful in large projects where the loading time may vary depending on the number of files and their size.

3. Integration with Google Drive and Google Colaboratory

If you work in Google Colab, a good practice is to use Google Drive to store and access files. LangChain allows you to easily connect your work environment with Google Drive, making it easy to upload and process files.

a) Upload files from Google Drive

  1. Connecting to Google Drive: In Google Colab, you can connect your Google Drive account and access files stored in it, such as PDFs, HTMLs or CSVs.
  2. Uploading Files and Directories: Once connected, you can access the directories in your My Drive, allowing you to easily upload files and work with them directly in Colab.

4. Best Practices for Working with Documents

  • Use Specific Loaders: Each file type (HTML, PDF, CSV) has its own loader, and it is important to use them properly to avoid formatting errors.
  • File Organization: If you work with multiple file types in the same project, it is advisable to separate them into specific folders to facilitate loading and processing with the correct loader.
  • Take advantage of Metadata: Uploaded files contain not only text, but also valuable metadata that you can use to cross-reference or identify specific documents within a large data set.

Contributions 6

Questions 1

Sort by:

Want to see more contributions, questions and answers from the community?

Alguien dijo Web Scraping馃槒 By the way, recomiendo ampliamente el curso de 'LangChain para Manejo y Recuperaci贸n de Documentos', gran curso馃憣
Una de las funcionalidades clave de LangChain es la capacidad de cargar y procesar diversos tipos de datos, incluyendo documentos HTML y directorios completos. Esto permite crear aplicaciones de IA que pueden comprender y responder a una amplia variedad de informaci贸n. ### Cargando Archivos HTML LangChain ofrece varias opciones para cargar archivos HTML, cada una con sus propias caracter铆sticas y ventajas: * **UnstructuredHTMLLoader:** Esta clase utiliza la biblioteca Unstructured para extraer texto de archivos HTML. Es una opci贸n sencilla y efectiva para muchos casos de uso. Python`from langchain.document_loaders import` UnstructuredHTMLLoader `loader = UnstructuredHTMLLoader("example_data/fake-content.html"`) `data = loader.load() 聽 ` Usa el c贸digo [con precauci贸n](/faq#coding). * **BSHTMLLoader:** Utiliza BeautifulSoup4 para parsear el HTML y extraer el texto. Permite un mayor control sobre el proceso de extracci贸n. Python`from langchain.document_loaders import` BSHTMLLoader `loader = BSHTMLLoader("example_data/fake-content.html"`) `data = loader.load() 聽 ` Usa el c贸digo [con precauci贸n](/faq#coding). * **SpiderLoader:** Esta clase utiliza la API de Spider para cargar p谩ginas web completas y convertirlas en texto, markdown, o HTML. Es 煤til para cargar grandes cantidades de datos de la web. Python`from langchain_community.document_loaders import` SpiderLoader `loader = SpiderLoader(api_key="YOUR_API_KEY", url="https://spider.cloud") 聽 ` data = loader.load() Usa el c贸digo [con precauci贸n](/faq#coding). ### Cargando Directorios Completos Para cargar todos los archivos de un directorio, LangChain proporciona el cargador `DirectoryLoader`. Puedes especificar patrones para filtrar los archivos que deseas cargar. Python`from langchain.document_loaders import` DirectoryLoader `loader = DirectoryLoader("my_documents", glob="*.pdf") # Cargar todos los PDF` data = loader.load() Usa el c贸digo [con precauci贸n](/faq#coding). ### Procesamiento Posterior de los Datos Una vez que has cargado los documentos, puedes realizar diversas operaciones, como: * **Crear un 铆ndice:** Para realizar b煤squedas r谩pidas dentro de los documentos. * **Entrenar un modelo de lenguaje:** Para crear un modelo que pueda responder preguntas sobre los datos. * **Generar texto:** Para crear res煤menes, traducciones o nuevas piezas de contenido basadas en los documentos. Python`from langchain.vectorstores import` FAISS `# Crear un 铆ndice` vectorstore = FAISS.from\_documents(data) `# Realizar una b煤squeda` `query = "Cu谩l es la capital de Francia?"` docs = vectorstore.similarity\_search(query) Usa el c贸digo [con precauci贸n](/faq#coding). ### Consideraciones Adicionales * **Estructura de los documentos HTML:** La complejidad de la estructura HTML puede afectar la calidad de la extracci贸n de texto. * **Limpieza de datos:** Es posible que necesites realizar una limpieza adicional de los datos extra铆dos, como eliminar etiquetas HTML o normalizar el texto. * **Rendimiento:** Para grandes cantidades de datos, considera utilizar t茅cnicas de procesamiento paralelo o distribuido. ### Ejemplos de Uso * **Chatbots:** Crear un chatbot que pueda responder preguntas sobre un sitio web completo. * **Sistemas de b煤squeda:** Desarrollar un motor de b煤squeda personalizado sobre una colecci贸n de documentos. * **An谩lisis de sentimientos:** Analizar la opini贸n de los usuarios a partir de comentarios en p谩ginas web. ### Conclusi贸n LangChain ofrece una forma sencilla y flexible de cargar y procesar documentos HTML y directorios completos. Al combinar estas capacidades con los modelos de lenguaje de gran tama帽o, puedes crear aplicaciones de IA potentes y personalizadas. **驴Tienes alguna pregunta espec铆fica sobre la carga de HTML y directorios con LangChain?** Por ejemplo, podemos explorar: * **C贸mo manejar diferentes formatos de archivos:** PDF, DOCX, etc. * **C贸mo personalizar la extracci贸n de texto:** Utilizando expresiones regulares o XPath. * **C贸mo optimizar el rendimiento para grandes conjuntos de datos.**
from langchain.document\_loaders import PyPDFLoader
Para cargar un archivo HTML en Google Colab, debes seguir estos pasos: 1. **Guardar el archivo en Google Drive**: Crea una carpeta en tu Google Drive y sube el archivo HTML all铆. 2. **Conectar Google Colab a Google Drive**: Usa el siguiente c贸digo en una celda de Colab para montar tu Google Drive: ```python from google.colab import drive drive.mount('/content/drive') ``` 3. **Acceder al archivo**: Despu茅s de montar, puedes acceder a tu archivo HTML usando la ruta correspondiente, por ejemplo: ```python file_path = '/content/drive/My Drive/tu_carpeta/tu_archivo.html' ``` Luego, puedes utilizar el cargador de HTML en LangChain para procesarlo.
Para cargar un sitio web externo en LangChain utilizando una URI, puedes utilizar `requests` para obtener el contenido HTML y luego procesarlo con `Beautiful Soup`. Aqu铆 tienes un ejemplo b谩sico: ```python import requests from bs4 import BeautifulSoup from langchain.document_loaders import BeautifulSoupLoader # Cargar HTML desde una URI url = "https://ejemplo.com" response = requests.get(url) soup = BeautifulSoup(response.content, 'html.parser') # Crear un documento con Beautiful Soup loader = BeautifulSoupLoader(soup.prettify()) document = loader.load() print(document) ``` Aseg煤rate de tener instaladas las librer铆as necesarias y ajustar el c贸digo seg煤n tus necesidades.
Reto completado en base a la ruta de cada archivo se usa un loader o otro ```js from langchain_community.document_loaders import DirectoryLoader !pid install langchain_community !pip install unstructured !pip install unstructured[pdf] !pip install unstructured[docx] !pip install unstructured[excel] from langchain.document_loaders import PyPDFLoader, CSVLoader, BSHTMLLoader, TextLoader import os # Directorio que contiene los archivos directory_path = "/content/documents" files = [os.path.join(directory_path, f) for f in os.listdir(directory_path)] for file_path in files: if file_path.endswith(".pdf"): print(f"Procesando PDF: {file_path}") loader = PyPDFLoader(file_path) docs = loader.load() for doc in docs: print(f"Contenido (primeros 100 caracteres): {doc.page_content[:100]}...\n") elif file_path.endswith(".csv"): print(f"Procesando CSV: {file_path}") loader = CSVLoader(file_path=file_path) data = loader.load() for record in data[:4]: print(record) elif file_path.endswith(".html"): print(f"Procesando HTML: {file_path}") loader = BSHTMLLoader(file_path) data = loader.load() for doc in data: print(f"Contenido (primeros 100 caracteres): {doc.page_content[:100]}...\n") elif file_path.endswith(".md"): print(f"Procesando Markdown: {file_path}") loader = TextLoader(file_path) docs = loader.load() for doc in docs: print(f"Contenido (primeros 100 caracteres): {doc.page_content[:100]}...\n") else: print(f"Archivo no soportado: {file_path}") ```