from fastapi import FastAPI from fastapi.responses import HTMLResponse from fastapi.staticfiles import StaticFiles import pathlib, os, uvicorn, base64 BASE = pathlib.Path(__file__).parent app = FastAPI() app.mount("/static", StaticFiles(directory=BASE), name="static") # PDF 디렉토리 설정 PDF_DIR = BASE / "pdf" if not PDF_DIR.exists(): PDF_DIR.mkdir(parents=True) # PDF 파일 목록 가져오기 def get_pdf_files(): pdf_files = [] if PDF_DIR.exists(): pdf_files = [f for f in PDF_DIR.glob("*.pdf")] return pdf_files # PDF 썸네일 생성 및 프로젝트 데이터 준비 def generate_pdf_projects(): projects_data = [] pdf_files = get_pdf_files() for pdf_file in pdf_files: projects_data.append({ "path": str(pdf_file), "name": pdf_file.stem }) return projects_data HTML = """ FlipBook Space

My FlipBook Projects

""" # API 엔드포인트: PDF 프로젝트 목록 @app.get("/api/pdf-projects") async def get_pdf_projects(): return generate_pdf_projects() # API 엔드포인트: PDF 썸네일 생성 @app.get("/api/pdf-thumbnail") async def get_pdf_thumbnail(path: str): try: import fitz # PyMuPDF # PDF 파일 열기 doc = fitz.open(path) # 첫 페이지 가져오기 if doc.page_count > 0: page = doc[0] # 썸네일용 이미지 렌더링 (해상도 조정) pix = page.get_pixmap(matrix=fitz.Matrix(0.5, 0.5)) img_data = pix.tobytes("png") # Base64 인코딩 b64_img = base64.b64encode(img_data).decode('utf-8') return {"thumbnail": f"data:image/png;base64,{b64_img}"} return {"thumbnail": None} except Exception as e: return {"error": str(e), "thumbnail": None} @app.get("/api/pdf-content") async def get_pdf_content(path: str): try: # 파일 존재 여부 확인 pdf_path = pathlib.Path(path) if not pdf_path.exists(): return {"error": f"파일을 찾을 수 없습니다: {path}"}, 404 # 파일 읽기 with open(path, "rb") as pdf_file: content = pdf_file.read() # 응답 헤더 설정 - PDF 파일임을 명시 headers = { "Content-Type": "application/pdf", "Content-Disposition": f"inline; filename={pdf_path.name}" } # 파일 콘텐츠 반환 from fastapi.responses import Response return Response(content=content, headers=headers) except Exception as e: import traceback error_details = traceback.format_exc() print(f"PDF 콘텐츠 로드 오류: {str(e)}\n{error_details}") return {"error": str(e)}, 500 @app.get("/", response_class=HTMLResponse) async def root(): return HTML if __name__ == "__main__": uvicorn.run("app:app", host="0.0.0.0", port=int(os.getenv("PORT", 7860)))