Files
ai-hotel-recommender/app.py
T

70 lines
2.7 KiB
Python

from flask import Flask, render_template, request, jsonify
import random
import math
app = Flask(__name__)
# 模拟酒店数据(实际可接入真实API)
HOTELS = [
{"id": 1, "name": "海景大酒店", "lat": 31.2304, "lng": 121.4737, "price": 800, "rating": 4.8, "tags": ["海景", "免费早餐", "健身房"]},
{"id": 2, "name": "城市商务酒店", "lat": 31.2350, "lng": 121.4800, "price": 500, "rating": 4.5, "tags": ["商务中心", "会议室", "24小时前台"]},
{"id": 3, "name": "温馨民宿", "lat": 31.2250, "lng": 121.4650, "price": 300, "rating": 4.7, "tags": ["家庭房", "厨房", "免费停车"]},
{"id": 4, "name": "豪华度假村", "lat": 31.2400, "lng": 121.4900, "price": 1500, "rating": 4.9, "tags": ["泳池", "SPA", "私人海滩"]},
{"id": 5, "name": "经济快捷酒店", "lat": 31.2200, "lng": 121.4600, "price": 200, "rating": 4.2, "tags": ["免费WiFi", "空调", "电视"]},
]
def haversine(lat1, lon1, lat2, lon2):
"""计算两点间距离(公里)"""
R = 6371
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = math.sin(dlat/2)**2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon/2)**2
c = 2 * math.asin(math.sqrt(a))
return R * c
def ai_recommend(destination, budget, preferences, user_lat, user_lng):
"""简单AI推荐:根据预算、偏好、距离评分"""
scored = []
for h in HOTELS:
score = 0
# 预算匹配
if budget and h["price"] <= budget:
score += 30
elif budget:
score -= 10
# 偏好匹配
for pref in preferences:
if pref in h["tags"]:
score += 20
# 评分
score += h["rating"] * 5
# 距离(越近越高)
dist = haversine(user_lat, user_lng, h["lat"], h["lng"])
score += max(0, 30 - dist * 2)
h_copy = h.copy()
h_copy["distance"] = round(dist, 2)
h_copy["score"] = round(score, 1)
scored.append(h_copy)
scored.sort(key=lambda x: x["score"], reverse=True)
return scored
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/recommend', methods=['POST'])
def recommend():
data = request.json
destination = data.get('destination', '上海')
budget = data.get('budget')
preferences = data.get('preferences', [])
user_lat = data.get('lat', 31.2304)
user_lng = data.get('lng', 121.4737)
if budget:
budget = float(budget)
results = ai_recommend(destination, budget, preferences, user_lat, user_lng)
return jsonify({"hotels": results})
if __name__ == '__main__':
app.run(debug=True)