File size: 13,952 Bytes
b8958a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# app.py
"""

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  # used to provide a trusted CA bundle for requests
from requests.exceptions import SSLError, RequestException

# LangChain Gemini wrapper
try:
    from langchain_google_genai import ChatGoogleGenerativeAI
except Exception:
    ChatGoogleGenerativeAI = None  # handled later

app = Flask(__name__)

# ---------------- CONFIG (set your keys here or use env vars) ----------------
OPENWEATHER_API_KEY = os.environ.get("209688131a0268b51c101f612dca54ca", None)  # optional, not used here
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 %}

"""

# ---------------- Utilities: Open-Meteo (robust SSL) ----------------

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:
        # Retry insecurely but return a notice that we did that
        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):
    # daily_json is forecast["daily"]
    # We expect single-day request; index 0 corresponds to requested date
    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}")

# -------------- Local deterministic itinerary fallback --------------
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.

    """
    # Minimal static content to avoid hallucination
    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)

# -------------- Gemini (LangChain) wrapper with graceful fallback --------------
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 wrapper not available
    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:
        # use invoke() per LangChain's new API
        res = llm.invoke(prompt)
        # The object returned by invoke may vary. Safely extract string content:
        if hasattr(res, "content"):
            # often a ChatResult with content attribute
            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:
        # Inspect message to decide if it's an auth error
        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}"

# -------------------- Flask routes --------------------

@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)

    # parse date
    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 Open-Meteo geocode + forecast with robust handling
    try:
        lat, lon, display_city, geocode_insecure, _ = open_meteo_geocode(city)
        # request daily forecast for the same date
        forecast_json, forecast_insecure, _ = open_meteo_forecast(lat, lon, target_date, target_date)
        # combine insecure flags
        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`.")
        # parse daily
        daily = forecast_json.get("daily", {})
        weather_summary, metrics = summarize_open_meteo(daily)
        weather_source = "Open-Meteo (free)"
    except Exception as e:
        # parsing or request failed: show a friendly notice and continue to itinerary fallback
        notices.append(f"Could not fetch weather data: {e}")
        weather_summary = None
        metrics = None
        weather_source = None
        display_city = city  # fallback label

    # Decide good/bad if metrics present; if absent, per your request always produce itinerary
    if metrics:
        # heuristics
        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  # user requested itinerary even if weather couldn't be fetched

    # Try Gemini; if fails due to missing/invalid key or runtime error, fallback to local itinerary
    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:
        # record a friendly note and generate local deterministic itinerary
        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)

    # Final render (no raw exceptions)
    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)