kec ocr 추가

This commit is contained in:
2025-06-12 12:33:07 +09:00
parent 5510529a36
commit 921a275e93
5 changed files with 168 additions and 51 deletions

View File

@@ -3,7 +3,7 @@
import asyncio
import json # JSON 파싱을 위해 추가
from fastapi import APIRouter, FastAPI, File, HTTPException, UploadFile
from fastapi import APIRouter, FastAPI, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from routers import google_docai
from utils.config import (
@@ -11,6 +11,8 @@ from utils.config import (
CORS_ALLOW_HEADERS,
CORS_ALLOW_METHODS,
CORS_ALLOW_ORIGINS,
DOCAI_LOCATION,
DOCAI_PROJECT_ID,
UPLOAD_DOCS_DIR,
)
@@ -47,10 +49,10 @@ doc_ai_router = APIRouter(
tags=["DocumentAI"],
)
# Document AI 관련 설정값 (프로덕션에서는 환경 변수나 설정 파일에서 로드 권장)
DOCAI_PROJECT_ID = "drawingpdfocr-461103"
DOCAI_LOCATION = "us"
DOCAI_PROCESSOR_ID = "b838676d4e3b4758" # 실제 사용자의 프로세서 ID
# DOCAI_PROCESSOR_ID = "b838676d4e3b4758" # 실제 사용자의 프로세서 ID
# KEC_DOCAI_PROCESSOR_ID = "94de4322c20d276f"
async def run_sync_in_threadpool(func, *args, **kwargs):
@@ -62,71 +64,57 @@ async def run_sync_in_threadpool(func, *args, **kwargs):
return await loop.run_in_executor(None, lambda: func(*args, **kwargs))
@doc_ai_router.post("/process-document/")
async def process_uploaded_document(file: UploadFile = File(...)):
@doc_ai_router.post("/available-processors", summary="도면 OCR API")
async def handle_docai_upload(file: UploadFile, processor_id: str):
"""
업로드된 파일을 Document AI로 처리하고, 추출된 엔티티 정보를 JSON으로 반환합니다.
국토교통부 = "b838676d4e3b4758"\n
도로공사 = "94de4322c20d276f"
"""
if not file.content_type:
raise HTTPException(status_code=400, detail="File content type is missing.")
# 지원되는 MIME 타입 (예시, 필요에 따라 확장)
allowed_mime_types = ["application/pdf", "image/jpeg", "image/png", "image/tiff"]
if file.content_type not in allowed_mime_types:
raise HTTPException(
status_code=400,
detail=f"Unsupported file type: '{file.content_type}'. Supported: {', '.join(allowed_mime_types)}",
)
print(f"Received audio file for async processing: {file.filename}")
print(f"Received file: {file.filename}")
file_id = str(create_key())
# 파일 저장 (유틸리티 함수 사용)
try:
file_path, file_content = save_uploaded_file(file, UPLOAD_DOCS_DIR, file_id)
except HTTPException as e:
raise e
except Exception as e:
raise HTTPException(
status_code=500, detail=f"파일 저장 준비 중 오류 발생: {str(e)}"
)
raise HTTPException(status_code=500, detail=f"파일 저장 실패: {str(e)}")
try:
# Document AI 처리 (동기 함수를 비동기적으로 호출)
document_result = await run_sync_in_threadpool(
google_docai.process_document_from_content, # 수정된 함수 사용
google_docai.process_document_from_content,
project_id=DOCAI_PROJECT_ID,
location=DOCAI_LOCATION,
processor_id=DOCAI_PROCESSOR_ID,
processor_id=processor_id,
file_content=file_content,
mime_type=file.content_type,
field_mask="text,entities", # 필요한 필드 마스크
field_mask="text,entities",
)
print(document_result)
if not document_result:
# 이 경우는 process_document_from_content 함수 내부에서 예외가 발생하지 않고
# None이나 빈 Document 객체를 반환했을 때를 대비 (일반적으론 예외 발생)
raise HTTPException(
status_code=500,
detail="Failed to process document: No result from Document AI.",
)
raise HTTPException(status_code=500, detail="Document AI 처리 결과 없음.")
json_output_string = google_docai.extract_and_convert_to_json(document_result)
return json.loads(json_output_string)
except HTTPException as http_exc:
# 이미 HTTPException으로 처리된 예외는 그대로 다시 발생시킴
raise http_exc
except Exception as e:
# 기타 예외 처리 (로깅 권장)
# import traceback
# print(f"Error processing file: {e}\n{traceback.format_exc()}")
raise HTTPException(
status_code=500,
detail=f"An error occurred during document processing: {str(e)}",
detail=f"Document AI 처리 중 오류 발생: {str(e)}",
)
finally:
await file.close() # 업로드된 파일 객체를 닫아 리소스 정리
await file.close()
# app에 라우터 등록