api 구축

This commit is contained in:
2025-06-04 15:25:36 +09:00
parent 04536eabd6
commit 5510529a36
7 changed files with 698 additions and 0 deletions

16
workspace/utils/config.py Normal file
View File

@@ -0,0 +1,16 @@
# config.py
import os
from pathlib import Path
# 디렉토리 설정
UPLOAD_DOCS_DIR = Path(os.getenv("AUDIO_DIR", "./data/UPLOAD_DOCS"))
RESULT_DIR = Path(os.getenv("RESULT_DIR", "./data/results"))
# 허용 파일 확장자
ALLOWED_EXTENSIONS = {".pdf"}
# CORS 설정
CORS_ALLOW_ORIGINS = os.getenv("CORS_ALLOW_ORIGINS", "*").split(",")
CORS_ALLOW_CREDENTIALS = os.getenv("CORS_ALLOW_CREDENTIALS", "true").lower() == "true"
CORS_ALLOW_METHODS = os.getenv("CORS_ALLOW_METHODS", "*").split(",")
CORS_ALLOW_HEADERS = os.getenv("CORS_ALLOW_HEADERS", "*").split(",")

View File

@@ -0,0 +1,58 @@
# utils/file_utils.py
from pathlib import Path
from fastapi import HTTPException, UploadFile
from snowflake import SnowflakeGenerator
from utils.config import ALLOWED_EXTENSIONS, RESULT_DIR, UPLOAD_DOCS_DIR
def create_essential_directories():
"""애플리케이션 시작 시 필요한 디렉토리를 생성합니다."""
UPLOAD_DOCS_DIR.mkdir(exist_ok=True)
RESULT_DIR.mkdir(exist_ok=True)
def create_key(node=1):
generator = SnowflakeGenerator(node)
key_value = next(generator)
return str(key_value)
def save_uploaded_file(
upload_file: UploadFile, save_dir: Path, file_prefix: str
) -> tuple[str, bytes]:
"""
업로드된 파일을 지정된 디렉토리에 저장하고, 파일 내용을 바이트로 반환합니다.
Returns:
저장된 파일 경로 (str), 파일 내용 (bytes)
"""
file_extension = Path(upload_file.filename).suffix.lower()
if file_extension not in ALLOWED_EXTENSIONS:
raise HTTPException(
status_code=400,
detail=f"지원하지 않는 파일 형식이에요. 지원 형식: {', '.join(ALLOWED_EXTENSIONS)} 😢",
)
new_filename = f"{file_prefix}{file_extension}"
file_path = save_dir / new_filename
try:
upload_file.file.seek(0)
file_content = upload_file.file.read() # 내용을 읽음
with open(file_path, "wb") as buffer:
buffer.write(file_content) # 내용을 저장
print(f"File saved: {file_path}")
return str(file_path), file_content
except IOError as e:
print(f"File saving error for {file_prefix}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"파일 저장 중 오류 발생: {str(e)}")
except Exception as e:
print(f"Unexpected file saving error for {file_prefix}: {e}", exc_info=True)
raise HTTPException(
status_code=500, detail=f"파일 처리 중 예상치 못한 오류 발생: {str(e)}"
)