Darwin Agent
fix: resolve CONFIG_ERROR - remove invalid sdk_version and static dir references
3e4e144
Raw
History Blame Contribute Delete
3.96 kB
import os
import json
from fastapi import FastAPI, UploadFile, File, HTTPException, Form
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from pathlib import Path
import shutil
import uuid
app = FastAPI(title="HanSoo Office Editor", version="1.0.0")
# CORS μ„€μ •
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# μ—…λ‘œλ“œ 디렉토리
UPLOAD_DIR = Path("/tmp/hansoo_uploads")
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
# 정적 파일 제곡 (static 디렉터리가 μ—†μœΌλ―€λ‘œ 주석 처리)
# app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/")
def read_root():
"""인덱슀 νŽ˜μ΄μ§€ 제곡"""
return FileResponse("index.html")
@app.get("/health")
def health_check():
"""ν—¬μŠ€ 체크 μ—”λ“œν¬μΈνŠΈ"""
return {"status": "healthy", "service": "HanSoo Office Editor"}
@app.post("/api/upload")
async def upload_file(file: UploadFile = File(...)):
"""파일 μ—…λ‘œλ“œ μ—”λ“œν¬μΈνŠΈ"""
try:
file_id = str(uuid.uuid4())
file_path = UPLOAD_DIR / f"{file_id}_{file.filename}"
with open(file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
return {
"success": True,
"file_id": file_id,
"filename": file.filename,
"size": file_path.stat().st_size,
"content_type": file.content_type
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/files/{file_id}")
async def get_file(file_id: str):
"""μ—…λ‘œλ“œλœ 파일 정보 쑰회"""
files = list(UPLOAD_DIR.glob(f"{file_id}_*"))
if not files:
raise HTTPException(status_code=404, detail="File not found")
file_path = files[0]
return {
"file_id": file_id,
"filename": file_path.name.replace(f"{file_id}_", ""),
"size": file_path.stat().st_size
}
@app.post("/api/process")
async def process_file(
file_id: str = Form(...),
operation: str = Form("extract")
):
"""파일 처리 μ—”λ“œν¬μΈνŠΈ (μΆ”μΆœ, λ³€ν™˜ λ“±)"""
files = list(UPLOAD_DIR.glob(f"{file_id}_*"))
if not files:
raise HTTPException(status_code=404, detail="File not found")
file_path = files[0]
try:
if operation == "extract":
# ν…μŠ€νŠΈ μΆ”μΆœ 둜직 (ν™•μž₯μžμ— 따라 처리)
content = extract_text(file_path)
return {"success": True, "content": content}
elif operation == "convert":
# λ³€ν™˜ 둜직
return {"success": True, "message": "Conversion completed"}
else:
raise HTTPException(status_code=400, detail="Unknown operation")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
def extract_text(file_path: Path) -> str:
"""νŒŒμΌμ—μ„œ ν…μŠ€νŠΈ μΆ”μΆœ"""
suffix = file_path.suffix.lower()
if suffix in [".txt", ".md", ".json", ".csv"]:
return file_path.read_text(encoding="utf-8")
elif suffix == ".pdf":
# PDF ν…μŠ€νŠΈ μΆ”μΆœ (PyPDF2 λ˜λŠ” pdfplumber ν•„μš”)
return "PDF text extraction requires additional dependencies"
elif suffix in [".docx", ".xlsx", ".pptx"]:
return "Office file extraction requires python-docx/openpyxl/python-pptx"
elif suffix in [".hwp", ".hwpx"]:
return "HWP extraction requires rhwp or pyhwp"
else:
return "Unsupported file format"
@app.on_event("shutdown")
def cleanup():
"""μ„œλ²„ μ’…λ£Œ μ‹œ μ—…λ‘œλ“œ 디렉토리 정리"""
try:
shutil.rmtree(UPLOAD_DIR)
except:
pass
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=int(os.getenv("PORT", 7860)))