|
|
|
|
|
"""
|
|
|
Hardened Trip Planner Flask app:
|
|
|
- Uses Open-Meteo for free forecasts (with robust SSL handling).
|
|
|
- Uses Gemini via ChatGoogleGenerativeAI.invoke() when a valid GOOGLE_API_KEY is available.
|
|
|
- If Gemini key is missing/invalid, falls back to a local itinerary generator (deterministic).
|
|
|
- Never exposes full tracebacks to the user (friendly messages instead).
|
|
|
"""
|
|
|
|
|
|
from flask import Flask, request, render_template_string
|
|
|
import requests
|
|
|
import os
|
|
|
from datetime import datetime
|
|
|
from dateutil import parser as date_parser
|
|
|
import certifi
|
|
|
from requests.exceptions import SSLError, RequestException
|
|
|
|
|
|
|
|
|
try:
|
|
|
from langchain_google_genai import ChatGoogleGenerativeAI
|
|
|
except Exception:
|
|
|
ChatGoogleGenerativeAI = None
|
|
|
|
|
|
app = Flask(__name__)
|
|
|
|
|
|
|
|
|
OPENWEATHER_API_KEY = os.environ.get("209688131a0268b51c101f612dca54ca", None)
|
|
|
GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY", "AIzaSyBgxuSyNFW12uRObS0XVmyaAV3gKonG_UE")
|
|
|
|
|
|
|
|
|
INDEX_HTML = """
|
|
|
<!doctype html>
|
|
|
<title>Hardened Trip Planner</title>
|
|
|
<h2>Hardened Trip Planner — Weather + Itinerary</h2>
|
|
|
<form method=post action="{{ url_for('plan') }}">
|
|
|
<label>City:</label><br>
|
|
|
<input type="text" name="city" required style="width:320px" value="{{ city|default('') }}"><br><br>
|
|
|
<label>Date (YYYY-MM-DD):</label><br>
|
|
|
<input type="date" name="date" required value="{{ date|default('') }}"><br><br>
|
|
|
<label>Trip length (days):</label><br>
|
|
|
<input type="number" name="days" min="1" max="7" value="{{ days|default(1) }}"><br><br>
|
|
|
<label>Preferences (optional):</label><br>
|
|
|
<input type="text" name="prefs" style="width:420px" value="{{ prefs|default('') }}"><br><br>
|
|
|
<input type="submit" value="Plan Trip">
|
|
|
</form>
|
|
|
<hr>
|
|
|
|
|
|
{% if notices %}
|
|
|
<div style="background:#fff3cd;border:1px solid #ffeeba;padding:10px;border-radius:6px;">
|
|
|
<strong>Notice:</strong>
|
|
|
<ul>
|
|
|
{% for n in notices %}
|
|
|
<li>{{ n }}</li>
|
|
|
{% endfor %}
|
|
|
</ul>
|
|
|
</div>
|
|
|
<hr>
|
|
|
{% endif %}
|
|
|
|
|
|
{% if weather_source %}
|
|
|
<p><strong>Weather source:</strong> {{ weather_source }}</p>
|
|
|
{% endif %}
|
|
|
|
|
|
{% if weather_summary %}
|
|
|
<h3>Weather for {{ display_date }} — {{ display_city }}</h3>
|
|
|
<pre>{{ weather_summary }}</pre>
|
|
|
<h3>Decision:
|
|
|
<span style="color: {{ 'green' if is_good else 'red' }};">
|
|
|
{{ 'Good for travel' if is_good else 'Not ideal for travel' }}
|
|
|
</span>
|
|
|
</h3>
|
|
|
{% endif %}
|
|
|
|
|
|
{% if itinerary %}
|
|
|
<h3>🧳 Suggested Itinerary</h3>
|
|
|
<pre>{{ itinerary }}</pre>
|
|
|
{% endif %}
|
|
|
|
|
|
{% if error %}
|
|
|
<div style="color:red;">{{ error }}</div>
|
|
|
{% endif %}
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
def requests_get_with_cert_retry(url, params=None, timeout=10):
|
|
|
"""
|
|
|
Try requests.get with certifi bundle first (recommended).
|
|
|
If an SSL verification error occurs, retry with verify=False (insecure) and
|
|
|
return a tuple (response_json, insecure_flag, error_message_if_any).
|
|
|
"""
|
|
|
try:
|
|
|
r = requests.get(url, params=params, timeout=timeout, verify=certifi.where())
|
|
|
r.raise_for_status()
|
|
|
return r.json(), False, None
|
|
|
except SSLError as e:
|
|
|
|
|
|
try:
|
|
|
r = requests.get(url, params=params, timeout=timeout, verify=False)
|
|
|
r.raise_for_status()
|
|
|
return r.json(), True, f"SSL verification failed with certifi; retried with verify=False. (Reason: {e})"
|
|
|
except Exception as e2:
|
|
|
return None, False, f"Open-Meteo SSL retry failed: {e2}"
|
|
|
except RequestException as e:
|
|
|
return None, False, f"Request failed: {e}"
|
|
|
|
|
|
def open_meteo_geocode(city_name):
|
|
|
url = "https://geocoding-api.open-meteo.com/v1/search"
|
|
|
params = {"name": city_name, "count": 1}
|
|
|
data, insecure, err = requests_get_with_cert_retry(url, params=params)
|
|
|
if data is None:
|
|
|
raise RuntimeError(err or "Geocoding request failed.")
|
|
|
results = data.get("results") or []
|
|
|
if not results:
|
|
|
raise ValueError("City not found (Open-Meteo geocoding).")
|
|
|
first = results[0]
|
|
|
lat, lon = first["latitude"], first["longitude"]
|
|
|
admin1 = first.get("admin1")
|
|
|
country = first.get("country", "")
|
|
|
display = f"{first.get('name')}{', ' + admin1 if admin1 else ''}, {country}"
|
|
|
return lat, lon, display, insecure, None
|
|
|
|
|
|
def open_meteo_forecast(lat, lon, start_date, end_date):
|
|
|
url = "https://api.open-meteo.com/v1/forecast"
|
|
|
params = {
|
|
|
"latitude": lat,
|
|
|
"longitude": lon,
|
|
|
"daily": "temperature_2m_max,temperature_2m_min,precipitation_probability_mean,weathercode,windspeed_10m_max",
|
|
|
"timezone": "UTC",
|
|
|
"start_date": start_date.isoformat(),
|
|
|
"end_date": end_date.isoformat()
|
|
|
}
|
|
|
data, insecure, err = requests_get_with_cert_retry(url, params=params)
|
|
|
if data is None:
|
|
|
raise RuntimeError(err or "Forecast request failed.")
|
|
|
return data, insecure, None
|
|
|
|
|
|
WEATHERCODE_MAP = {
|
|
|
0: "Clear sky", 1: "Mainly clear", 2: "Partly cloudy", 3: "Overcast",
|
|
|
45: "Fog", 48: "Rime fog", 51: "Light drizzle", 53: "Moderate drizzle",
|
|
|
55: "Dense drizzle", 61: "Light rain", 63: "Moderate rain", 65: "Heavy rain",
|
|
|
71: "Snow", 73: "Moderate snow", 75: "Heavy snow", 95: "Thunderstorm", 99: "Severe thunderstorm"
|
|
|
}
|
|
|
|
|
|
def summarize_open_meteo(daily_json):
|
|
|
|
|
|
|
|
|
try:
|
|
|
tmax = daily_json["temperature_2m_max"][0]
|
|
|
tmin = daily_json["temperature_2m_min"][0]
|
|
|
pop = daily_json.get("precipitation_probability_mean", [0])[0]
|
|
|
wcode = daily_json.get("weathercode", [None])[0]
|
|
|
wdesc = WEATHERCODE_MAP.get(wcode, f"Code {wcode}")
|
|
|
wind = daily_json.get("windspeed_10m_max", [None])[0]
|
|
|
summary = f"Temperature: {tmin}°C - {tmax}°C\nCondition: {wdesc}\nRain Probability: {pop}%\nWind (max): {wind} m/s"
|
|
|
metrics = {"temp": (tmax + tmin)/2.0, "pop": (pop or 0) / 100.0, "weather_main": wdesc, "wind": wind or 0.0}
|
|
|
return summary, metrics
|
|
|
except Exception as e:
|
|
|
raise RuntimeError(f"Failed parsing forecast data: {e}")
|
|
|
|
|
|
|
|
|
def local_itinerary(city, date_str, days, prefs):
|
|
|
"""
|
|
|
A deterministic, simple itinerary generator used when Gemini fails or key invalid.
|
|
|
This ensures user always gets a usable itinerary.
|
|
|
"""
|
|
|
|
|
|
lines = []
|
|
|
lines.append(f"Quick itinerary for {city} starting on {date_str} — {days} day(s). Preferences: {prefs or 'none'}.")
|
|
|
for d in range(days):
|
|
|
day_label = f"Day {d+1}"
|
|
|
lines.append(f"\n{day_label}:")
|
|
|
lines.append(" Morning: Visit a top-rated landmark or central park; short walk and coffee.")
|
|
|
lines.append(" Lunch: Try a popular local restaurant near the landmark.")
|
|
|
lines.append(" Afternoon: Museum / covered market / indoor experience (if raining).")
|
|
|
lines.append(" Evening: Scenic viewpoint or food street; end with a recommended cafe.")
|
|
|
lines.append(" Transport tip: Use local ride apps or short taxis for >3 km trips. Prefer walking for central areas.")
|
|
|
lines.append(" Safety tip: Keep a copy of ID, stay in well-lit areas at night.")
|
|
|
return "\n".join(lines)
|
|
|
|
|
|
|
|
|
def generate_itinerary_with_gemini(city_display, date_str, days, prefs):
|
|
|
"""
|
|
|
Tries to call Gemini via langchain_google_genai.ChatGoogleGenerativeAI.invoke().
|
|
|
If the LLM is unavailable, or API key invalid, returns None and an error message.
|
|
|
"""
|
|
|
|
|
|
if ChatGoogleGenerativeAI is None:
|
|
|
return None, "LangChain Gemini wrapper not installed or import failed."
|
|
|
|
|
|
if not GOOGLE_API_KEY or GOOGLE_API_KEY.startswith("REPLACE_WITH"):
|
|
|
return None, "Gemini API key not configured or invalid."
|
|
|
|
|
|
try:
|
|
|
llm = ChatGoogleGenerativeAI(model="gemini-2.5-pro", temperature=0.25, google_api_key=GOOGLE_API_KEY)
|
|
|
except Exception as e:
|
|
|
return None, f"Could not initialize Gemini LLM: {e}"
|
|
|
|
|
|
prompt = (
|
|
|
f"You are a practical travel planner. Create a {days}-day itinerary for {city_display} starting on {date_str}.\n"
|
|
|
f"User preferences: {prefs or 'none'}.\n"
|
|
|
"- Provide 1-line summary, then day-by-day plan with morning/afternoon/evening slots.\n"
|
|
|
"- Add 2 recommended restaurants and 1 quick transport tip per day.\n"
|
|
|
"- Keep output factual and clear; do not invent opening hours.\n"
|
|
|
"Return plain text."
|
|
|
)
|
|
|
|
|
|
try:
|
|
|
|
|
|
res = llm.invoke(prompt)
|
|
|
|
|
|
if hasattr(res, "content"):
|
|
|
|
|
|
content = res.content
|
|
|
elif isinstance(res, dict) and "output_text" in res:
|
|
|
content = res["output_text"]
|
|
|
else:
|
|
|
content = str(res)
|
|
|
return content, None
|
|
|
except Exception as e:
|
|
|
|
|
|
msg = str(e)
|
|
|
if "API key not valid" in msg or "API_KEY_INVALID" in msg or "401" in msg or "403" in msg:
|
|
|
return None, "Gemini authentication failed (invalid/expired API key)."
|
|
|
return None, f"Gemini call failed: {msg}"
|
|
|
|
|
|
|
|
|
|
|
|
@app.route("/", methods=["GET"])
|
|
|
def index():
|
|
|
return render_template_string(INDEX_HTML)
|
|
|
|
|
|
@app.route("/plan", methods=["POST"])
|
|
|
def plan():
|
|
|
city = request.form.get("city", "").strip()
|
|
|
date_str = request.form.get("date", "").strip()
|
|
|
days = int(request.form.get("days", 1))
|
|
|
prefs = request.form.get("prefs", "").strip()
|
|
|
|
|
|
if not city or not date_str:
|
|
|
return render_template_string(INDEX_HTML, error="City and date are required.", city=city, date=date_str, days=days, prefs=prefs)
|
|
|
|
|
|
|
|
|
try:
|
|
|
target_date = date_parser.parse(date_str).date()
|
|
|
except Exception:
|
|
|
return render_template_string(INDEX_HTML, error="Invalid date format (expected YYYY-MM-DD).", city=city, date=date_str, days=days, prefs=prefs)
|
|
|
|
|
|
notices = []
|
|
|
weather_summary = None
|
|
|
metrics = None
|
|
|
weather_source = None
|
|
|
insecure_flag = False
|
|
|
|
|
|
|
|
|
try:
|
|
|
lat, lon, display_city, geocode_insecure, _ = open_meteo_geocode(city)
|
|
|
|
|
|
forecast_json, forecast_insecure, _ = open_meteo_forecast(lat, lon, target_date, target_date)
|
|
|
|
|
|
insecure_flag = geocode_insecure or forecast_insecure
|
|
|
if insecure_flag:
|
|
|
notices.append("SSL certificate verification failed for Open-Meteo; requests were retried insecurely (verify=False). This is less secure — consider installing/updating system CA certs or `certifi`.")
|
|
|
|
|
|
daily = forecast_json.get("daily", {})
|
|
|
weather_summary, metrics = summarize_open_meteo(daily)
|
|
|
weather_source = "Open-Meteo (free)"
|
|
|
except Exception as e:
|
|
|
|
|
|
notices.append(f"Could not fetch weather data: {e}")
|
|
|
weather_summary = None
|
|
|
metrics = None
|
|
|
weather_source = None
|
|
|
display_city = city
|
|
|
|
|
|
|
|
|
if metrics:
|
|
|
|
|
|
is_good = True
|
|
|
if metrics.get("pop", 0) > 0.35: is_good = False
|
|
|
temp = metrics.get("temp")
|
|
|
if temp is not None and not (5 <= temp <= 35): is_good = False
|
|
|
if any(k.lower() in str(metrics.get("weather_main", "")).lower() for k in ["thunder", "storm", "snow", "heavy rain"]):
|
|
|
is_good = False
|
|
|
else:
|
|
|
is_good = True
|
|
|
|
|
|
|
|
|
itinerary = None
|
|
|
gemini_note = None
|
|
|
gemini_content, gemini_err = generate_itinerary_with_gemini(display_city, date_str, days, prefs)
|
|
|
if gemini_content:
|
|
|
itinerary = gemini_content
|
|
|
else:
|
|
|
|
|
|
gemini_note = gemini_err or "Unknown Gemini error."
|
|
|
notices.append(f"Gemini unavailable: {gemini_note} — falling back to local itinerary generator.")
|
|
|
itinerary = local_itinerary(display_city, date_str, days, prefs)
|
|
|
|
|
|
|
|
|
return render_template_string(
|
|
|
INDEX_HTML,
|
|
|
notices=notices,
|
|
|
weather_source=weather_source,
|
|
|
weather_summary=weather_summary,
|
|
|
is_good=is_good,
|
|
|
itinerary=itinerary,
|
|
|
display_date=target_date.isoformat(),
|
|
|
display_city=display_city,
|
|
|
city=city,
|
|
|
date=date_str,
|
|
|
days=days,
|
|
|
prefs=prefs
|
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
print("Starting hardened Trip Planner on http://127.0.0.1:5000")
|
|
|
print("If you see notices about SSL or Gemini key, follow printed instructions above the form.")
|
|
|
app.run(debug=False, host="127.0.0.1", port=5000)
|
|
|
|