LangChain: Document Loaders로 문서 읽어들이기

파일로 된 문서를 가지고 LLM으로 작업하기 위해서는 먼저 문서의 내용을 읽어들여야겠죠. 파이썬에서 직접 문서의 내용을 텍스트로 읽어서 LLM에 전달하는 것도 가능합니다. 하지만 LangChain에서 제공하는 Document loader를 이용하면 편리하게 다양한 문서를 통일된 방식으로 읽어들일 수 있습니다.

LangChain에는 PDF, HTML, Text, Markdown, Json, CSV 파일 외에도 다양한 종류의 로컬 파일들과 클라우드 드라이브의 파일들을 읽을 수 있는 Document loader들이 있습니다. Document loader를 이용해 문서를 읽으면 Document 객체의 리스트를 반환합니다. 분할 여부에 따라 하나의 객체만 있는 리스트가 반환될 수도 있고, 페이지마다 하나씩 객체가 생성되어 여러 개의 원소를 가진 리스트가 반환될 수도 있습니다. 문서의 내용은 Document 객체의 page_content 속성에 들어가고, 원본 파일, 문서 제목, 페이지 번호 등의 정보는 metadata 속성에 저장됩니다. 예제를 살펴보겠습니다.

HTML 문서 읽기

import requests

url = "https://www.gutenberg.org/cache/epub/2680/pg2680-images.html"

response = requests.get(url)

with open("Meditations_pg.html",'wb') as fh:
    fh.write(response.content)

연습을 위해 프로젝트 구텐베르크 사이트에서 페이지를 하나 다운받아 Meditations_pg.html 파일로 저장했습니다. 마르쿠스 아우렐리우스의 명상록입니다. 이 html 파일을 읽어보겠습니다. BSHTMLLoader를 이용할텐데, 이를 위해서는 BeautifulSoup4 패키지를 먼저 설치해야 합니다.

# 설치: pip install beautifulsoup4

from langchain.document_loaders import BSHTMLLoader

loader = BSHTMLLoader("Meditations_pg.html")
data = loader.load()

위의 data는 Document 객체가 하나 들어있는 리스트입니다. 메타데이터를 확인해보겠습니다.

data[0].metadata
## 출력
{'source': 'Meditations_pg.html',
 'title': 'The Project Gutenberg eBook of Meditations, by Marcus Aurelius'}

이번엔 내용을 일부만 확인해보겠습니다.

data[0].page_content[:1000]
## 출력
'\n\nThe Project Gutenberg eBook of Meditations, by Marcus Aurelius\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nThe Project Gutenberg eBook of Meditations\nThis ebook is for the use of anyone anywhere in the United States and\nmost other parts of the world at no cost and with almost no restrictions\nwhatsoever. You may copy it, give it away or re-use it under the terms\nof the Project Gutenberg License included with this ebook or online\nat www.gutenberg.org. If you are not located in the United States,\nyou will have to check the laws of the country where you are located\nbefore using this eBook.\nTitle: Meditations\n\nAuthor: Emperor of Rome Marcus Aurelius\n\nRelease date: June 1, 2001 [eBook #2680]\n                Most recently updated: March 9, 2021\nLanguage: English\n\n*** START OF THE PROJECT GUTENBERG EBOOK MEDITATIONS ***\n\n\n      MEDITATIONS\n    \n\n      By Marcus Aurelius\n    \n\n      MARCUS AURELIUS ANTONINUS THE ROMAN EMPEROR\n    \n\n \n\n\n\n      BOOKS\n    \n\n INTRODUCTION \n\n\n\n\n\nHIS FIRST BOOK\n\n\nTHE SECOND BOOK\n\n\nTHE THI'

전체 길이를 확인해보죠.

len(data[0].page_content)
## 출력
487994

공백 포함 48만자가 넘네요. 이 내용을 LLM에 전달하면 token 제한에 걸리겠죠? LLM에 전달할 때는 내용을 chunk로 분할해서 전달하게 됩니다.

PDF 문서 읽기

이번에는 위 웹 페이지를 pdf로 출력한 파일을 읽어보겠습니다. 이를 위해서는 pypdf 패키지를 미리 설치해야 합니다.

# 설치: pip install pypdf

from langchain.document_loaders import PyPDFLoader

loader = PyPDFLoader("Meditations.pdf")
pages = loader.load_and_split()
len(pages)
## 출력
151

load_and_split 명령으로 pdf 파일을 읽으면서 분할했습니다. 그랬더니 길이가 151인 리스트가 나왔습니다. 실제 pdf 파일의 페이지 수가 151입니다.

pages[0].metadata  ## {'source': 'Meditations.pdf', 'page': 0}
pages[150].metadata  ## {'source': 'Meditations.pdf', 'page': 150}

Metadata에 들어있는 항목이 html 파일의 경우와 달라졌죠? 문서에 따라 metadata의 내용이 달라진다는 것을 알 수 있습니다.

pages[0]
## 출력
Document(page_content='10/6/23, 10:40 PM The Project Gutenberg eBook of Meditations, by Marcus Aurelius\nhttps://www.gutenberg.org/cache/epub/2680/pg2680-images.html 1/151The Project Gutenberg eBook of Meditations\nThis ebook is for the use of anyone anywhere in the United\nStates and most other parts of the world at no cost and with\nalmost no restrictions whatsoever . You may copy it, give it\naway or re-use it under the terms of the Project Gutenber g\nLicense included with this ebook or online at\nwww .gutenber g.org. If you are not located in the United\nStates, you will have to check the laws of the country where\nyou are located before using this eBook.\nTitle: Meditations\nAuthor : Emperor of Rome Marcus Aurelius\nRelease date : June 1, 2001 [eBook #2680]\nMost recently updated: March 9, 2021\nLanguage : English\n*** ST ART OF THE PROJECT  GUTENBERG EBOOK\nMEDIT ATIONS ***\nMEDIT A TIONS\nBy Mar cus Aurelius\nMARCUS AURELIUS ANTONINUS\nTHE ROMAN EMPEROR\nBOOKS\nINTRODUCTION\nHIS FIRST  BOOK\nTHE SECOND BOOK\nTHE THIRD BOOK\nTHE FOUR TH BOOK\nTHE FIFTH BOOK\nTHE SIXTH BOOK\nTHE SEVENTH BOOK\nTHE EIGHTH BOOK\nTHE NINTH BOOK', metadata={'source': 'Meditations.pdf', 'page': 0})

리스트의 첫 번째 원소를 확인해보니 Document 객체가 들어있고, 페이지 내용은 page_content 속성에, 추가 정보는 metadata 속성에 들어가 있는 것을 확인할 수 있습니다.

이렇게 LangChain의 Document loader를 이용하면 다양한 유형의 파일들을 편리하게 읽어들일 수 있습니다.

댓글 남기기