📌 LangChain을 활용하면 다양한 문서(PDF, Word, PPT, Python 파일)를 쉽게 로드하고, AI 검색 및 LLM 모델과 연결할 수 있습니다.
💡 이번 글에서는 LangChain에서 제공하는 문서 로더를 활용하여 여러 파일을 처리하는 방법을 완벽하게 정리했습니다.
📌 1️⃣ LangChain에서 다양한 문서 파일을 로드해야 하는 이유?
AI 검색 엔진이나 LLM(RAG, Retrieval-Augmented Generation) 모델을 개발할 때, 텍스트 데이터가 여러 파일 포맷으로 존재할 가능성이 높습니다.
예를 들어:
- PDF 문서 → 연구 논문, 보고서
- Word 파일 → 회의록, 계약서
- PPT 파일 → 프레젠테이션
- Python 코드 → 코드 기반 문서
LangChain에서는 파일 형식에 따라 최적화된 DocumentLoader를 제공하여, 개발자가 원하는 문서를 쉽게 불러올 수 있도록 지원합니다. 🚀
📌 2️⃣ LangChain 파일 로더 종류 (파일별 최적 로더)
LangChain에서는 파일 포맷별로 적절한 DocumentLoader를 사용해야 합니다.
아래 표는 각 파일별 적절한 로더를 정리한 것입니다.
파일 포맷 | 로더 클래스 | 필요 라이브러리 |
PyPDFLoader | pypdf | |
Word (.docx) | Docx2txtLoader | python-docx, docx2txt |
PPT (.pptx) | UnstructuredPPTXLoader | unstructured |
Python (.py) | TextLoader | 기본 제공 |
📌 3️⃣ 파일별 LangChain 로더 사용법
이제 각 파일 형식별로 LangChain에서 문서를 로드하는 방법을 알아보겠습니다.
✅ PDF 파일 로드 (PyPDFLoader)
python
복사편집
from langchain_community.document_loaders import PyPDFLoader
# PDF 파일 로드
loader = PyPDFLoader("./sample.pdf")
pages = loader.load_and_split()
# 첫 페이지 내용 출력
print(pages[0].page_content)
✔ **PyPDFLoader**는 pypdf 기반으로 PDF를 불러오며, load_and_split()을 사용하면 페이지 단위로 나눌 수도 있습니다.
✅ Word 파일 로드 (Docx2txtLoader)
python
복사편집
from langchain_community.document_loaders import Docx2txtLoader
# Word 파일 로드
loader = Docx2txtLoader("./sample.docx")
docs = loader.load()
# 문서 내용 출력
print(docs[0].page_content)
✔ Docx2txtLoader는 .docx 파일을 텍스트로 변환하여 로드합니다.
✅ PPT 파일 로드 (UnstructuredPPTXLoader)
python
복사편집
from langchain_community.document_loaders import UnstructuredPPTXLoader
# PPT 파일 로드
loader = UnstructuredPPTXLoader("./sample.pptx")
docs = loader.load()
# 슬라이드 내용 출력
print(docs[0].page_content)
✔ UnstructuredPPTXLoader는 PPT 슬라이드 내용을 추출하는 데 사용됩니다.
✅ Python 파일 로드 (TextLoader)
python
복사편집
from langchain_community.document_loaders import TextLoader
# Python 파일 로드
loader = TextLoader("./sample.py")
docs = loader.load()
# 코드 내용 출력
print(docs[0].page_content)
✔ TextLoader는 .py, .txt 같은 일반적인 텍스트 기반 파일을 로드할 수 있습니다.
📌 4️⃣ 여러 파일을 한 번에 처리하는 방법
파일별로 로더를 따로 만들 필요 없이, 자동으로 적절한 로더를 선택하는 방법도 있습니다.
✅ 여러 파일을 한 번에 로드 (자동 선택)
python
복사편집
from langchain_community.document_loaders import PyPDFLoader, Docx2txtLoader, UnstructuredPPTXLoader, TextLoader
# 파일별 로더 매핑
file_loaders = {
"pdf": PyPDFLoader,
"docx": Docx2txtLoader,
"pptx": UnstructuredPPTXLoader,
"py": TextLoader
}
# 여러 파일 로드 함수
def load_file(file_path):
ext = file_path.split(".")[-1] # 파일 확장자 추출
loader_class = file_loaders.get(ext) # 확장자에 맞는 로더 선택
if loader_class:
loader = loader_class(file_path)
return loader.load()
else:
raise ValueError(f"지원되지 않는 파일 형식: {ext}")
# 파일 리스트
file_list = ["sample.pdf", "sample.docx", "sample.pptx", "sample.py"]
# 모든 파일 로드
all_docs = []
for file in file_list:
docs = load_file(file)
all_docs.extend(docs)
# 첫 번째 문서 출력
print(all_docs[0].page_content)
✅ 파일 확장자별로 자동으로 적절한 로더를 선택하여 로드 가능!
✅ 새로운 파일 포맷을 추가할 때 file_loaders에 로더만 추가하면 됨.
📌 5️⃣ LangChain 파일 로더 활용 사례
LangChain의 DocumentLoader를 활용하면, 다양한 AI 검색 시스템을 구축할 수 있습니다.
✔ AI 기반 문서 검색 엔진
✔ LLM 기반 RAG 시스템
✔ 대량 문서 자동 분석 및 요약
💡 실제 적용 사례
예를 들어, FAISS나 Pinecone 같은 벡터 검색 엔진을 활용하면,
LangChain으로 로드한 문서를 벡터화하여 "가장 유사한 문서 찾기" 기능을 구현할 수 있습니다. 🚀
📌 6️⃣ 관련 참고 링크
📌 LangChain 공식 문서
🔗 https://python.langchain.com/docs/
📌 LangChain 파일 로더 문서
🔗 PyPDFLoader (PDF 파일 로드)
https://python.langchain.com/docs/modules/data_connection/document_loaders/pypdf
🔗 Docx2txtLoader (Word 문서 로드)
https://python.langchain.com/docs/modules/data_connection/document_loaders/docx2txt
🔗 UnstructuredPPTXLoader (PPT 파일 로드)
https://python.langchain.com/docs/modules/data_connection/document_loaders/unstructured_pptx
🔗 TextLoader (Python 파일 로드)
https://python.langchain.com/docs/modules/data_connection/document_loaders/text
🚀 결론: LangChain 파일 로딩으로 AI 검색 시스템을 확장하자!
🔹 LangChain을 활용하면 PDF, Word, PPT, Python 파일을 손쉽게 로드할 수 있습니다.
🔹 파일 형식별로 적절한 DocumentLoader를 활용하면 AI 검색 엔진 구축이 더욱 쉬워집니다.
🔹 한 번에 여러 파일을 로드하는 자동화 방법을 활용하면 대규모 문서 처리도 가능합니다.
👉 LangChain을 활용한 AI 문서 검색 시스템을 직접 만들어보고 싶다면, 위 코드를 참고해보세요! 🚀
'생성형 AI 활용법' 카테고리의 다른 글
🚀 AI 업계의 핫이슈! OpenAI vs. 딥시크 – o3-mini의 성능 분석 (2) | 2025.02.01 |
---|---|
LLM Search Engine: Elasticsearch, Pinecone, FAISS, Milvus 비교 및 샘플 코드 (0) | 2025.01.31 |
LLM API 사용 시 Function Call (0) | 2025.01.29 |
ChatGPT 완벽 활용법: AI 성능을 극대화하는 프롬프트 엔지니어링 Top 7 (1) | 2025.01.28 |