AI 실거래가 추천 10개 프로토타입
This commit is contained in:
1 parent
cb5dd5f25f
commit
b1f8061811
8 files changed
+243
-18
No files matched your search
+48
-3
@@ -39,7 +39,7 @@ async def serve_index():
|
||||
return FileResponse("../frontend/index.html")
|
||||
|
||||
@app.post("/api/search")
|
||||
async def search_real_estate(query: RealEstateQuery):
|
||||
async def search_real_estate(query: RealEstateQuery, filter_results: bool = True):
|
||||
"""자연어 검색 후 실거래가 데이터 조회"""
|
||||
if not parser:
|
||||
raise HTTPException(
|
||||
@@ -60,10 +60,55 @@ async def search_real_estate(query: RealEstateQuery):
|
||||
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,
|
||||
"count": len(listings)
|
||||
"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))
|
||||
|
||||
@@ -136,4 +136,97 @@ class OpenAIParser:
|
||||
property_type=None,
|
||||
region_code=None,
|
||||
region_name=None
|
||||
)
|
||||
)
|
||||
|
||||
async def filter_listings(self, user_query: str, listings: list, top_k: int = 10) -> list:
|
||||
"""
|
||||
OpenAI를 사용하여 실거래가 목록에서 사용자 요구사항과 가장 일치하는 매물 선별
|
||||
|
||||
Args:
|
||||
user_query: 사용자의 원본 검색 쿼리
|
||||
listings: 공공데이터 API에서 받은 실거래가 목록
|
||||
top_k: 선별할 매물 개수 (기본값: 10)
|
||||
|
||||
Returns:
|
||||
필터링된 매물 목록
|
||||
"""
|
||||
|
||||
if not listings:
|
||||
return []
|
||||
|
||||
# 매물 정보를 간략하게 정리
|
||||
simplified_listings = []
|
||||
for idx, item in enumerate(listings[:50]): # 최대 50개만 처리 (토큰 제한)
|
||||
simplified = {
|
||||
"index": idx,
|
||||
"거래유형": item.get("거래유형", ""),
|
||||
"매물형태": item.get("매물형태", ""),
|
||||
"거래금액": item.get("거래금액", ""),
|
||||
"보증금액": item.get("보증금액", ""),
|
||||
"월세금액": item.get("월세금액", ""),
|
||||
"전용면적": item.get("전용면적", ""),
|
||||
"층": item.get("층", ""),
|
||||
"건축년도": item.get("건축년도", ""),
|
||||
"법정동": item.get("법정동", ""),
|
||||
"거래일": f"{item.get('년', '')}.{item.get('월', '')}.{item.get('일', '')}"
|
||||
}
|
||||
# 빈 값 제거
|
||||
simplified = {k: v for k, v in simplified.items() if v}
|
||||
simplified_listings.append(simplified)
|
||||
|
||||
system_prompt = """
|
||||
당신은 부동산 전문가입니다.
|
||||
사용자의 요구사항과 실거래가 데이터를 비교하여 가장 적합한 매물을 선별해주세요.
|
||||
|
||||
평가 기준:
|
||||
1. 가격 조건 일치도 (사용자가 언급한 가격 범위)
|
||||
2. 면적 조건 일치도 (평수, 방 개수 등)
|
||||
3. 층수 선호도
|
||||
4. 건축년도 (신축/구축 선호도)
|
||||
5. 위치 적합성
|
||||
|
||||
JSON 형식으로 응답하세요:
|
||||
{
|
||||
"selected_indices": [가장 적합한 매물의 index 10개],
|
||||
"reason": "선별 이유 간단 설명"
|
||||
}
|
||||
"""
|
||||
|
||||
user_prompt = f"""
|
||||
사용자 요구사항: {user_query}
|
||||
|
||||
실거래가 데이터:
|
||||
{json.dumps(simplified_listings, ensure_ascii=False, indent=2)}
|
||||
|
||||
위 데이터에서 사용자 요구사항과 가장 잘 맞는 매물 {top_k}개를 선별해주세요.
|
||||
"""
|
||||
|
||||
try:
|
||||
response = self.client.chat.completions.create(
|
||||
model="gpt-3.5-turbo",
|
||||
messages=[
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_prompt}
|
||||
],
|
||||
temperature=0.1,
|
||||
response_format={"type": "json_object"}
|
||||
)
|
||||
|
||||
result = json.loads(response.choices[0].message.content)
|
||||
selected_indices = result.get("selected_indices", [])
|
||||
|
||||
# 선별된 매물 반환
|
||||
filtered_listings = []
|
||||
for idx in selected_indices:
|
||||
if 0 <= idx < len(listings):
|
||||
listing = listings[idx].copy()
|
||||
listing["match_reason"] = result.get("reason", "")
|
||||
listing["rank"] = len(filtered_listings) + 1
|
||||
filtered_listings.append(listing)
|
||||
|
||||
return filtered_listings[:top_k]
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error filtering listings: {e}")
|
||||
# 에러 시 원본 데이터의 상위 10개 반환
|
||||
return listings[:top_k]
|
||||
Reference in new issue
Block a user