Django (Python)와 React로 AI 기반 문서 인사이트 도구 만들기
I’m happy to translate the article for you, but I’ll need the text you’d like translated. Could you please paste the content (excluding the source line you already provided) so I can translate it into Korean while preserving the formatting and code blocks?
개요
계약서, 협정서 또는 기타 비즈니스 문서를 관리하는 일은 시간도 많이 걸리고 오류가 발생하기 쉽습니다. AI를 활용해 PDF에서 당사자, 중요한 날짜, 조항 등 핵심 정보를 자동으로 추출할 수 있다면 어떨까요?
이번 튜토리얼에서는 다음을 사용해 Document Insights 도구를 만드는 방법을 보여드립니다:
- Backend: Django + Django REST Framework
- Frontend: React + Axios
- Database: SQLite
- AI: OpenAI GPT API
- PDF Parsing: PyPDF2
백엔드
단계 1 – 의존성 설치
pip install django djangorestframework PyPDF2 openai
단계 2 – 문서용 Django 모델
api/models.py
from django.db import models
class Document(models.Model):
file = models.FileField(upload_to='documents/')
uploaded_at = models.DateTimeField(auto_now_add=True)
extracted_text = models.TextField(blank=True, null=True)
insights = models.JSONField(blank=True, null=True)
마이그레이션 실행:
python manage.py makemigrations
python manage.py migrate
단계 3 – Serializer
api/serializers.py
from rest_framework import serializers
from .models import Document
class DocumentSerializer(serializers.ModelSerializer):
class Meta:
model = Document
fields = ['id', 'file', 'uploaded_at', 'extracted_text', 'insights']
단계 4 – OpenAI GPT를 활용한 Django API 뷰
api/views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Document
from .serializers import DocumentSerializer
from PyPDF2 import PdfReader
from openai import OpenAI
# Initialize OpenAI client
client = OpenAI(api_key="YOUR_OPENAI_API_KEY")
class UploadDocument(APIView):
def post(self, request):
file = request.FILES['file']
doc = Document.objects.create(file=file)
# Extract text from PDF
reader = PdfReader(file)
text = ""
for page in reader.pages:
text += page.extract_text() or ""
doc.extracted_text = text
# Prepare AI prompt
prompt = f"""
You are an AI assistant that extracts structured information from documents.
For the following document text, provide:
1. Parties involved
2. Important dates
3. Key clauses
4. Any missing or inconsistent information
Return as JSON.
Document:
{text}
"""
# Call OpenAI API
response = client.chat.completions.create(
model="gpt-5-nano", # use gpt-3.5-turbo or gpt-4 if you have access
messages=[{"role": "user", "content": prompt}]
)
# Save AI insights
doc.insights = response.choices[0].message.content
doc.save()
serializer = DocumentSerializer(doc)
return Response(serializer.data)
단계 5 – URL 설정
api/urls.py
from django.urls import path
from .views import UploadDocument
urlpatterns = [
path('upload-document/', UploadDocument.as_view(), name='upload-document'),
]
프로젝트에 앱의 URL을 추가:
project/urls.py
from django.urls import path, include
urlpatterns = [
path('api/', include('api.urls')),
]
Source: …
프론트엔드 (React)
Axios 설치
npm install axios
DocumentInsights 컴포넌트
src/pages/DocumentInsights.jsx
import React, { useState } from 'react';
import axios from 'axios';
export default function DocumentInsights() {
const [file, setFile] = useState(null);
const [insights, setInsights] = useState(null);
const handleUpload = async () => {
const formData = new FormData();
formData.append('file', file);
try {
const { data } = await axios.post(
'http://127.0.0.1:8000/api/upload-document/',
formData
);
setInsights(JSON.parse(data.insights));
} catch (error) {
console.error(error);
}
};
return (
<div>
<h1>AI 문서 인사이트</h1>
<input type="file" onChange={e => setFile(e.target.files[0])} />
<button onClick={handleUpload}>업로드</button>
{insights && (
<div>
<h2>당사자:</h2>
{insights.parties?.join(', ')}
<h2>날짜:</h2>
{insights.dates?.join(', ')}
<h2>핵심 조항:</h2>
{insights.key_clauses?.join(', ')}
<h2>누락된 정보:</h2>
{insights.missing_info?.join(', ')}
</div>
)}
</div>
);
}
앱 진입점
src/App.js
import DocumentInsights from "./pages/DocumentInsights";
import "./App.css";
function App() {
return (
<div className="App">
<DocumentInsights />
</div>
);
}
export default App;
🎉 준비 완료!
Django 서버(python manage.py runserver)와 React 개발 서버(npm start)를 실행하세요. UI를 통해 PDF를 업로드하면 백엔드가 AI‑생성 인사이트를 반환하고 프론트엔드에 표시됩니다. 즐거운 코딩 되세요!
Django에서 CORS 활성화
백엔드가 CORS를 허용하도록 설정하세요:
pip install django-cors-headers
**settings.py**에 다음을 추가합니다:
INSTALLED_APPS = [
# …
'corsheaders',
]
MIDDLEWARE = [
# …
'corsheaders.middleware.CorsMiddleware',
]
CORS_ALLOW_ALL_ORIGINS = True
Step 7: 테스트하기
Django 실행
python manage.py runserver
React 실행
npm run dev
검증
브라우저를 열고 PDF를 업로드하면 AI 기반 구조화된 인사이트를 확인할 수 있습니다.