124 lines
3.6 KiB
Python
124 lines
3.6 KiB
Python
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, filter_results: bool = True):
|
|
"""자연어 검색 후 실거래가 데이터 조회"""
|
|
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
|
|
)
|
|
|
|
# 3. OpenAI로 필터링 (옵션)
|
|
if filter_results and listings:
|
|
filtered_listings = await parser.filter_listings(
|
|
user_query=query.text,
|
|
listings=listings,
|
|
top_k=10
|
|
)
|
|
return {
|
|
"parsed": parsed,
|
|
"listings": filtered_listings,
|
|
"count": len(filtered_listings),
|
|
"total_count": len(listings),
|
|
"filtered": True
|
|
}
|
|
|
|
return {
|
|
"parsed": parsed,
|
|
"listings": listings[:20], # 필터링 안 할 경우 상위 20개만
|
|
"count": min(len(listings), 20),
|
|
"total_count": len(listings),
|
|
"filtered": False
|
|
}
|
|
except Exception as e:
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
@app.post("/api/filter")
|
|
async def filter_real_estate_listings(
|
|
user_query: str,
|
|
listings: list,
|
|
top_k: int = 10
|
|
):
|
|
"""공공데이터 결과를 OpenAI로 필터링하여 최적 매물 선별"""
|
|
if not parser:
|
|
raise HTTPException(
|
|
status_code=500,
|
|
detail="OpenAI API key not configured"
|
|
)
|
|
|
|
try:
|
|
filtered = await parser.filter_listings(
|
|
user_query=user_query,
|
|
listings=listings,
|
|
top_k=top_k
|
|
)
|
|
|
|
return {
|
|
"filtered_listings": filtered,
|
|
"count": len(filtered),
|
|
"original_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) |