도커라이징
This commit is contained in:
@@ -1,66 +1,86 @@
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
import redis
|
||||
from config import OUTPUT_DIR, UPLOAD_DIR
|
||||
from fastapi import FastAPI, UploadFile
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from redis_client import redis_client
|
||||
from rq import Queue
|
||||
from worker import process_task
|
||||
|
||||
# RQ 작업 큐 생성
|
||||
task_queue = Queue("task_queue1", connection=redis_client)
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
UPLOAD_DIR = "data"
|
||||
OUTPUT_DIR = "converted"
|
||||
# CORS 설정
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"], # 모든 오리진 허용
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# 업로드 및 출력 디렉토리 생성
|
||||
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
|
||||
redis_client = redis.StrictRedis(host="localhost", port=6379, decode_responses=True)
|
||||
|
||||
|
||||
@app.post("/upload/")
|
||||
async def upload_directory(files: List[UploadFile]):
|
||||
"""사용자가 여러 개의 파일을 업로드하면 UPLOAD_DIR에 저장"""
|
||||
"""사용자가 업로드한 파일들을 UPLOAD_DIR에 저장"""
|
||||
uploaded_files = []
|
||||
|
||||
for file in files:
|
||||
file_path = Path(UPLOAD_DIR) / file.filename
|
||||
with open(file_path, "wb") as buffer:
|
||||
shutil.copyfileobj(file.file, buffer)
|
||||
uploaded_files.append(file.filename)
|
||||
|
||||
return {"message": "파일 업로드 성공", "files": uploaded_files}
|
||||
|
||||
|
||||
@app.get("/convert/")
|
||||
async def convert_files():
|
||||
"""
|
||||
업로드된 파일들을 지원하는 확장자(txt, html, docx, pdf)만 Redis 작업 큐에 태스크로 등록.
|
||||
워커에서 배치 잡으로 처리합니다.
|
||||
"""
|
||||
"""업로드된 파일을 변환 큐(RQ)에 등록하고 Job ID 반환"""
|
||||
files = os.listdir(UPLOAD_DIR)
|
||||
enqueued_tasks = []
|
||||
|
||||
for file in files:
|
||||
file_ext = file.split(".")[-1].lower()
|
||||
# 지원하는 파일 형식만 큐에 넣기
|
||||
if file_ext in ["txt", "html", "docx", "pdf"]:
|
||||
if file_ext in ["txt", "html", "docx", "pdf", "hwp"]:
|
||||
task = {
|
||||
"filename": file,
|
||||
"extension": file_ext,
|
||||
"input_path": os.path.join(UPLOAD_DIR, file),
|
||||
"output_path": os.path.join(OUTPUT_DIR, f"{Path(file).stem}.md"),
|
||||
}
|
||||
# 태스크를 JSON 문자열로 변환하여 큐에 등록
|
||||
redis_client.lpush("task_queue", json.dumps(task))
|
||||
enqueued_tasks.append(task)
|
||||
job = task_queue.enqueue(process_task, task) # RQ에 작업 등록
|
||||
enqueued_tasks.append({"task": task, "job_id": job.id})
|
||||
|
||||
return {"message": "작업이 큐에 추가되었습니다.", "tasks": enqueued_tasks}
|
||||
|
||||
|
||||
@app.get("/task/{job_id}")
|
||||
async def get_task_status(job_id: str):
|
||||
"""RQ에서 특정 Job ID의 상태 확인"""
|
||||
job = task_queue.fetch_job(job_id)
|
||||
if not job:
|
||||
return {"error": "존재하지 않는 작업입니다."}
|
||||
|
||||
return {
|
||||
"job_id": job.id,
|
||||
"status": job.get_status(),
|
||||
"result": job.result,
|
||||
"enqueued_at": str(job.enqueued_at),
|
||||
"ended_at": str(job.ended_at) if job.ended_at else None,
|
||||
}
|
||||
|
||||
|
||||
@app.get("/download/{filename}")
|
||||
async def download_file(filename: str):
|
||||
"""변환된 Markdown 파일을 다운로드할 수 있도록 제공"""
|
||||
"""변환된 Markdown 파일을 다운로드합니다."""
|
||||
file_path = Path(OUTPUT_DIR) / filename
|
||||
if not file_path.exists():
|
||||
return {"error": "파일이 존재하지 않습니다."}
|
||||
|
||||
Reference in New Issue
Block a user