import os from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse from dotenv import load_dotenv import uvicorn from models import RealEstateQuery from openai_parser import OpenAIParser from public_data_api import PublicDataAPIClient load_dotenv() app = FastAPI(title="부동산 검색 API") # CORS 설정 app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # OpenAI 파서 초기화 try: parser = OpenAIParser() except ValueError as e: print(f"Warning: {e}") parser = None # 공공데이터 API 클라이언트 초기화 public_data_client = PublicDataAPIClient() @app.get("/") async def serve_index(): """메인 페이지 제공""" return FileResponse("../frontend/index.html") @app.post("/api/search") async def search_real_estate(query: RealEstateQuery): """자연어 검색 후 실거래가 데이터 조회""" if not parser: raise HTTPException( status_code=500, detail="OpenAI API key not configured" ) try: # 1. 자연어 파싱 parsed = await parser.parse_real_estate_query(query.text) # 2. 실거래가 데이터 조회 listings = [] if parsed.region_code and parsed.property_type and parsed.transaction_type: listings = public_data_client.get_real_estate_data( property_type=parsed.property_type, transaction_type=parsed.transaction_type, region_code=parsed.region_code ) return { "parsed": parsed, "listings": listings, "count": len(listings) } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) # 정적 파일 서빙 (CSS, JS) app.mount("/static", StaticFiles(directory="../frontend"), name="static") if __name__ == "__main__": host = os.getenv("HOST", "0.0.0.0") port = int(os.getenv("PORT", 20001)) print(f"Starting server at http://localhost:{port}") uvicorn.run(app, host=host, port=port, reload=True)