115 lines
3.4 KiB
Python
115 lines
3.4 KiB
Python
import os
|
|
from typing import Optional
|
|
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, ParsedRealEstate
|
|
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/parse", response_model=ParsedRealEstate)
|
|
async def parse_real_estate(query: RealEstateQuery):
|
|
"""자연어 입력을 파싱하여 부동산 정보 추출"""
|
|
if not parser:
|
|
raise HTTPException(
|
|
status_code=500,
|
|
detail="OpenAI API key not configured. Please set OPENAI_API_KEY in .env file"
|
|
)
|
|
|
|
try:
|
|
result = await parser.parse_real_estate_query(query.text)
|
|
return result
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
@app.get("/api/real-estate-data")
|
|
async def get_real_estate_listings(
|
|
property_type: str = "아파트",
|
|
transaction_type: str = "매매",
|
|
region_code: str = "11680",
|
|
deal_ymd: Optional[str] = None
|
|
):
|
|
"""공공데이터 API를 통한 실거래가 조회"""
|
|
try:
|
|
data = public_data_client.get_real_estate_data(
|
|
property_type=property_type,
|
|
transaction_type=transaction_type,
|
|
region_code=region_code,
|
|
deal_ymd=deal_ymd
|
|
)
|
|
return {"data": data, "count": len(data)}
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
@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
|
|
)
|
|
print(listings)
|
|
|
|
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) |