Indexify와 Mistral로 PDF 엔티티 추출하기
Indexify와 Mistral로 PDF 엔티티 추출하기 (PDF Entity Extraction with Indexify and Mistral)
Indexify와 Mistral의 LLM을 사용해 PDF 문서용 견고한 엔티티 추출 파이프라인을 구축하는 방법을 배우는 문서예요. 정보 검색, 콘텐츠 분석, 데이터 마이닝 같은 애플리케이션에 활용할 수 있습니다.
출처: 문서
본문
이 쿡북은 Indexify와 Mistral의 LLM을 사용해 PDF 문서용 견고한 엔티티 추출 파이프라인을 구축하는 방법을 보여줘요. PDF 파일에서 명명된 엔티티(named entities)를 효율적으로 추출하는 방법을 배우게 됩니다.
소개 (Introduction)
엔티티 추출, 즉 명명된 엔티티 인식(NER, named entity recognition)은 텍스트에서 명명된 엔티티를 인물, 조직, 위치, 날짜 등 미리 정의된 카테고리로 식별·분류하는 것을 말해요. 이 기법을 PDF 문서에 적용하면 비정형 텍스트에서 구조화된 정보를 자동으로 추출할 수 있어, 문서 내용을 더 쉽게 분석·활용할 수 있습니다.
사전 요구사항 (Prerequisites)
시작 전에 다음을 확인하세요:
- Python 3.9 이상으로 가상 환경 생성
python3.9 -m venv ve
source ve/bin/activate
pip(Python 패키지 관리자)- Mistral API 키
- Python과 커맨드라인 인터페이스에 대한 기본 지식
설정 (Setup)
Indexify 설치
먼저 공식 설치 스크립트로 터미널에서 Indexify를 설치해요.
curl https://getindexify.ai | sh
Indexify 서버를 시작해요.
./indexify server -d
이것은 애플리케이션에 ingestion(수집)과 retrieval(검색) API를 노출하는 장기 실행 서버를 시작해요.
필요한 추출기(Extractors) 설치
새 터미널에서 필요한 추출기를 설치해요.
pip install indexify-extractor-sdk
indexify-extractor download tensorlake/pdfextractor
indexify-extractor download tensorlake/mistral
추출기가 다운로드되면 시작할 수 있어요.
indexify-extractor join-server
추출 그래프 생성 (Creating the Extraction Graph)
추출 그래프는 엔티티 추출 파이프라인을 통한 데이터 흐름을 정의해요. 먼저 PDF에서 텍스트를 추출한 다음, 그 텍스트를 Mistral로 보내 엔티티 추출을 수행하는 그래프를 만들게요.
from indexify import IndexifyClient, ExtractionGraph
client = IndexifyClient()
extraction_graph_spec = """
name: 'pdf_entity_extractor'
extraction_policies:
- extractor: 'tensorlake/pdfextractor'
name: 'pdf_to_text'
- extractor: 'tensorlake/mistral'
name: 'text_to_entities'
input_params:
model_name: 'mistral-large-latest'
key: 'YOUR_MISTRAL_API_KEY'
system_prompt: 'Extract and categorize all named entities from the following text. Provide the results in a JSON format with categories: persons, organizations, locations, dates, and miscellaneous.'
content_source: 'pdf_to_text'
"""
extraction_graph = ExtractionGraph.from_yaml(extraction_graph_spec)
client.create_extraction_graph(extraction_graph)
'YOUR_MISTRAL_API_KEY'를 실제 Mistral API 키로 바꾸세요.
엔티티 추출 파이프라인 구현 (Implementing the Entity Extraction Pipeline)
이제 추출 그래프를 설정했으니, 파일을 업로드하고 엔티티를 검색할 수 있어요.
import json
import os
import requests
from indexify import IndexifyClient
def download_pdf(url, save_path):
response = requests.get(url)
with open(save_path, 'wb') as f:
f.write(response.content)
print(f"PDF downloaded and saved to {save_path}")
def extract_entities_from_pdf(pdf_path):
client = IndexifyClient()
# Upload the PDF file
content_id = client.upload_file("pdf_entity_extractor", pdf_path)
# Wait for the extraction to complete
client.wait_for_extraction(content_id)
# Retrieve the extracted entities
entities_content = client.get_extracted_content(
content_id=content_id,
graph_name="pdf_entity_extractor",
policy_name="text_to_entities"
)
# Parse the JSON response
entities = json.loads(entities_content[0]['content'].decode('utf-8'))
return entities
pdf_url = "https://arxiv.org/pdf/2310.06825.pdf"
pdf_path = "reference_document.pdf"
# Download the PDF
download_pdf(pdf_url, pdf_path)
extracted_entities = extract_entities_from_pdf(pdf_path)
print("Extracted Entities:")
for category, entities in extracted_entities.items():
print(f"\n{category.capitalize()}:")
for entity in entities:
print(f"- {entity}")
커스터마이즈와 고급 사용법 (Customization and Advanced Usage)
추출 그래프의 system_prompt을 수정해 엔티티 추출 과정을 커스터마이즈할 수 있어요. 예시:
특정 엔티티 유형에 집중하려면:
system_prompt: 'Extract only person names and organizations from the following text. Provide the results in a JSON format with categories: persons and organizations.'
엔티티 관계를 포함하려면:
system_prompt: 'Extract named entities and their relationships from the following text. Provide the results in a JSON format with categories: entities (including type and name) and relationships (including type and involved entities).'
또한 model_name 파라미터를 바꿔 다양한 Mistral 모델로 실험해, 특정 사용 사례에 맞는 속도와 정확도의 최상의 균형을 찾을 수 있어요.
결론 (Conclusion)
예시가 단순해 보일 수 있지만 Indexify를 사용하면 몇 가지 독특한 이점이 있어요.
- 확장 가능하고 고가용성: Indexify 서버는 클라우드에 배포해 업로드되는 수천 개의 PDF를 처리할 수 있고, 파이프라인에서 어떤 단계가 실패해도 다른 머신에서 자동으로 재시도합니다.
- 유연성: 사용 중인 문서에서 여기서 사용한 [PDF 추출 모델]이 동작하지 않으면 다른 [PDF 추출 모델]을 사용할 수 있어요.
다음 단계 (Next Steps)
- Indexify에 대해 더 알아보기: [https://docs.getindexify.ai]
- Mistral을 사용해 [대규모 요약 구축] 예시 살펴보기