# app.py (FlightAI) — Gradio 6.6 compatible for Hugging Face Spaces # Groq chat + professional UI + prices for (almost) all cities via Amadeus (optional) import os import json import sqlite3 import tempfile import re from typing import List, Dict, Tuple, Optional import requests from dotenv import load_dotenv import gradio as gr from groq import Groq from PIL import Image, ImageDraw, ImageFont # ========================= # Config # ========================= load_dotenv(override=True) GROQ_API_KEY = os.getenv("GROQ_API_KEY", "").strip() if not GROQ_API_KEY: raise RuntimeError( "Missing GROQ_API_KEY. On Hugging Face Spaces go to: " "Settings → Variables and secrets → add GROQ_API_KEY (as a Secret)." ) MODEL = os.getenv("GROQ_MODEL", "llama-3.1-8b-instant") # HF Spaces persistent storage (if enabled) is /data DB = os.getenv("FLIGHTAI_DB_PATH", "/data/prices.db" if os.path.isdir("/data") else "prices.db") APP_TITLE = "FlightAI" APP_SUBTITLE = "Live flight quotes (optional) • Destination poster • Spoken replies" client = Groq(api_key=GROQ_API_KEY) SYSTEM_MESSAGE = """ You are FlightAI, a professional airline assistant. Your goals: - Provide accurate ticket pricing and booking guidance. - Keep responses concise and professional (max 2 short sentences). - If pricing is requested, gather missing details politely: origin, destination, dates, passengers, cabin. - Never invent prices. If live pricing is unavailable, say so and offer alternatives (demo DB prices). Tool policy: - You have access to pricing tools only. - Use tools when the user asks for prices or comparisons. - If the tool returns no data, say you don’t have live pricing for that request. """.strip() # ========================= # Database (demo fallback) # ========================= db_dir = os.path.dirname(DB) if db_dir and not os.path.exists(db_dir): os.makedirs(db_dir, exist_ok=True) with sqlite3.connect(DB) as conn: cur = conn.cursor() cur.execute("CREATE TABLE IF NOT EXISTS prices (city TEXT PRIMARY KEY, price REAL)") conn.commit() def set_ticket_price(city: str, price: float) -> None: with sqlite3.connect(DB) as conn: cur = conn.cursor() cur.execute( "INSERT INTO prices (city, price) VALUES (?, ?) " "ON CONFLICT(city) DO UPDATE SET price = ?", (city.lower(), price, price), ) conn.commit() def get_ticket_price(city: str) -> str: city = (city or "").strip() with sqlite3.connect(DB) as conn: cur = conn.cursor() cur.execute("SELECT price FROM prices WHERE city = ?", (city.lower(),)) row = cur.fetchone() return f"DEMO_DB: Ticket price to {city} is ${row[0]}" if row else "DEMO_DB: No price data available for this city" for c, p in {"london": 799, "paris": 899, "tokyo": 1420, "sydney": 2999}.items(): set_ticket_price(c, p) # ========================= # Live pricing via Amadeus (optional) # ========================= CITY_TO_IATA = { "london": "LON", "paris": "PAR", "tokyo": "TYO", "sydney": "SYD", "cairo": "CAI", "new york": "NYC", "dubai": "DXB", "rome": "ROM", "madrid": "MAD", "berlin": "BER", } def normalize_place_to_iata(place: str) -> Optional[str]: if not place: return None if re.fullmatch(r"[A-Za-z]{3}", place.strip()): return place.strip().upper() return CITY_TO_IATA.get(place.strip().lower()) def amadeus_get_token() -> Optional[str]: key = os.getenv("AMADEUS_API_KEY", "").strip() secret = os.getenv("AMADEUS_API_SECRET", "").strip() if not key or not secret: return None url = "https://test.api.amadeus.com/v1/security/oauth2/token" data = {"grant_type": "client_credentials", "client_id": key, "client_secret": secret} r = requests.post(url, data=data, timeout=30) if r.status_code != 200: return None return r.json().get("access_token") def get_flight_quote_live( origin: str, destination: str, depart_date: str, return_date: Optional[str] = None, adults: int = 1, travel_class: str = "ECONOMY", ) -> str: token = amadeus_get_token() if not token: return "LIVE_API: Live pricing is not configured (missing/invalid Amadeus keys)." origin_iata = normalize_place_to_iata(origin) dest_iata = normalize_place_to_iata(destination) if not origin_iata or not dest_iata: return ( "LIVE_API: Please provide origin/destination as IATA airport codes (e.g., CAI, LON), " "or use a supported city name from the demo list." ) url = "https://test.api.amadeus.com/v2/shopping/flight-offers" headers = {"Authorization": f"Bearer {token}"} params = { "originLocationCode": origin_iata, "destinationLocationCode": dest_iata, "departureDate": depart_date, "adults": max(1, int(adults)), "travelClass": travel_class.upper(), "max": 10, "currencyCode": "USD", } if return_date: params["returnDate"] = return_date r = requests.get(url, headers=headers, params=params, timeout=45) if r.status_code != 200: return f"LIVE_API: No live offers returned (status {r.status_code})." data = r.json() offers = data.get("data", []) if not offers: return "LIVE_API: No live offers found for that route/date." cheapest_price = None cheapest = None for off in offers: price = off.get("price", {}).get("grandTotal") if not price: continue try: val = float(price) except Exception: continue if cheapest_price is None or val < cheapest_price: cheapest_price = val cheapest = off if cheapest_price is None: return "LIVE_API: Offers found, but couldn’t read prices." itineraries = (cheapest or {}).get("itineraries", []) stops = [] for it in itineraries: segs = it.get("segments", []) stops.append(max(0, len(segs) - 1)) trip_type = "Round-trip" if return_date else "One-way" return ( f"LIVE_API: {trip_type} {origin_iata}→{dest_iata} from ${cheapest_price:.2f} USD " f"({travel_class.upper()}, adults={adults}, stops={stops})." ) # ========================= # Tools for Groq function-calling # ========================= tools = [ { "type": "function", "function": { "name": "get_ticket_price", "description": "Get a demo return-ticket price by destination city (SQLite demo data).", "parameters": { "type": "object", "properties": {"destination_city": {"type": "string"}}, "required": ["destination_city"], "additionalProperties": False, }, }, }, { "type": "function", "function": { "name": "get_flight_quote", "description": "Get a live flight quote (if configured) using origin, destination, dates, passengers, and cabin.", "parameters": { "type": "object", "properties": { "origin": {"type": "string", "description": "Origin city or IATA code"}, "destination": {"type": "string", "description": "Destination city or IATA code"}, "depart_date": {"type": "string", "description": "YYYY-MM-DD"}, "return_date": {"type": "string", "description": "YYYY-MM-DD (optional)"}, "adults": {"type": "integer", "description": "Number of adult passengers"}, "travel_class": {"type": "string", "description": "ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST"}, }, "required": ["origin", "destination", "depart_date"], "additionalProperties": False, }, }, }, ] def handle_tool_calls(assistant_msg) -> List[Dict]: responses = [] for tc in (assistant_msg.tool_calls or []): name = tc.function.name args = json.loads(tc.function.arguments or "{}") if name == "get_ticket_price": city = args.get("destination_city", "") result = get_ticket_price(city) responses.append({"role": "tool", "content": result, "tool_call_id": tc.id}) elif name == "get_flight_quote": result = get_flight_quote_live( origin=args.get("origin", ""), destination=args.get("destination", ""), depart_date=args.get("depart_date", ""), return_date=(args.get("return_date") or None), adults=int(args.get("adults", 1) or 1), travel_class=args.get("travel_class", "ECONOMY") or "ECONOMY", ) responses.append({"role": "tool", "content": result, "tool_call_id": tc.id}) else: responses.append({"role": "tool", "content": "Unknown tool call.", "tool_call_id": tc.id}) return responses # ========================= # Poster template # ========================= def _try_font(name: str, size: int): try: return ImageFont.truetype(name, size) except Exception: return ImageFont.load_default() def poster_template(city: str) -> Image.Image: city_t = city.title() if city else "Your Destination" w, h = 1024, 1024 img = Image.new("RGB", (w, h), (10, 18, 32)) draw = ImageDraw.Draw(img) for y in range(h): r = 10 + int(20 * (y / h)) g = 18 + int(30 * (y / h)) b = 32 + int(50 * (y / h)) draw.line([(0, y), (w, y)], fill=(r, g, b)) draw.rounded_rectangle((60, 70, w - 60, 280), radius=26, fill=(255, 255, 255)) draw.rounded_rectangle((60, 70, w - 60, 280), radius=26, outline=(0, 0, 0), width=3) font_big = _try_font("arial.ttf", 72) font_med = _try_font("arial.ttf", 38) font_small = _try_font("arial.ttf", 26) draw.text((95, 100), f"Vacation in {city_t}", fill=(0, 0, 0), font=font_big) draw.text((97, 190), "FlightAI Specials", fill=(40, 40, 40), font=font_med) base_y = 800 x = 80 import random random.seed(hash(city_t) % 10_000) while x < w - 80: bw = random.randint(40, 110) bh = random.randint(90, 280) draw.rectangle([x, base_y - bh, x + bw, base_y], fill=(0, 0, 0)) x += bw + random.randint(12, 22) draw.text((60, 930), "FlightAI • Smart quotes • Better trips", fill=(230, 230, 230), font=font_small) return img # ========================= # TTS (optional) # ========================= async def _edge_tts_async(text: str, out_path: str) -> None: import edge_tts communicate = edge_tts.Communicate(text, voice="en-US-JennyNeural") await communicate.save(out_path) def tts_to_wav(text: str) -> Tuple[Optional[str], str]: text = (text or "").strip() if not text: return None, "No speech." try: import asyncio fd, out_path = tempfile.mkstemp(suffix=".wav", prefix="flightai_tts_") os.close(fd) asyncio.run(_edge_tts_async(text, out_path)) if os.path.exists(out_path) and os.path.getsize(out_path) > 1000: return out_path, "✅ Audio ready (edge-tts)." return None, "⚠️ edge-tts ran, but no WAV was produced." except Exception: return None, "Audio not available (install edge-tts: python -m pip install edge-tts)." # ========================= # Turn runner # ========================= def run_turn(user_text: str, api_messages: List[Dict]) -> Tuple[str, Optional[str], Image.Image, str, str, List[Dict]]: api_messages = api_messages + [{"role": "user", "content": user_text}] max_loops = 6 seen = set() last_city_for_poster: Optional[str] = None for _ in range(max_loops): resp = client.chat.completions.create( model=MODEL, messages=api_messages, tools=tools, tool_choice="auto", ) choice = resp.choices[0] msg = choice.message if choice.finish_reason != "tool_calls": text = (msg.content or "").strip() parts = re.split(r"(?<=[.!?])\s+", text) text = " ".join(parts[:2]).strip() api_messages = api_messages + [{"role": "assistant", "content": text}] audio_path, audio_status = tts_to_wav(text) poster = poster_template(last_city_for_poster or "your trip") img_status = "Poster generated (template)." return text, audio_path, poster, audio_status, img_status, api_messages signature = tuple((tc.function.name, tc.function.arguments) for tc in (msg.tool_calls or [])) if signature in seen: fallback = "Sorry—I’m having trouble retrieving pricing right now." api_messages = api_messages + [{"role": "assistant", "content": fallback}] audio_path, audio_status = tts_to_wav(fallback) return fallback, audio_path, poster_template("your trip"), audio_status, "Poster generated.", api_messages seen.add(signature) for tc in (msg.tool_calls or []): if tc.function.name in ("get_ticket_price", "get_flight_quote"): try: args = json.loads(tc.function.arguments or "{}") if "destination_city" in args: last_city_for_poster = args.get("destination_city") if "destination" in args: last_city_for_poster = args.get("destination") except Exception: pass api_messages = api_messages + [ { "role": "assistant", "content": msg.content, "tool_calls": [ { "id": tc.id, "type": tc.type, "function": {"name": tc.function.name, "arguments": tc.function.arguments}, } for tc in (msg.tool_calls or []) ], } ] api_messages = api_messages + handle_tool_calls(msg) fallback = "Sorry—I couldn’t complete that request." api_messages = api_messages + [{"role": "assistant", "content": fallback}] audio_path, audio_status = tts_to_wav(fallback) return fallback, audio_path, poster_template("your trip"), audio_status, "Poster generated.", api_messages # ========================= # UI (Gradio 6) # ========================= CSS = """ .gradio-container { max-width: 1250px !important; } #header { border: 1px solid rgba(255,255,255,.10); border-radius: 16px; padding: 16px 18px; background: linear-gradient(135deg, #0b1220, #0f172a); } #brand { font-size: 22px; font-weight: 800; margin: 0; letter-spacing: .2px; } #tag { opacity: .8; margin-top: 6px; } #panel { border: 1px solid rgba(255,255,255,.10); border-radius: 16px; padding: 12px; } .small { font-size: 12px; opacity: .75; } """ EXAMPLES = [ "Give me a quote from CAI to LON on 2026-03-10 for 1 adult economy.", "How much is a return ticket to London? (demo)", "Compare prices to Paris and Tokyo (demo).", ] def init_api_state(): return [{"role": "system", "content": SYSTEM_MESSAGE}] def build_quote_message(origin, destination, depart, ret, adults, cabin): origin = (origin or "").strip() destination = (destination or "").strip() depart = (depart or "").strip() ret = (ret or "").strip() adults = int(adults or 1) cabin = (cabin or "ECONOMY").strip().upper() if ret: return f"Get me a live flight quote from {origin} to {destination} departing {depart} returning {ret} for {adults} adult(s) in {cabin}." return f"Get me a live flight quote from {origin} to {destination} departing {depart} for {adults} adult(s) in {cabin}." # Chat display is list[tuple(user, assistant)] def on_user_submit(user_text: str, chat_display, api_state): user_text = (user_text or "").strip() if not user_text: return "", chat_display, api_state chat_display = (chat_display or []) + [(user_text, "")] return "", chat_display, api_state def on_user_submit(user_text: str, chat_display, api_state): user_text = (user_text or "").strip() if not user_text: return "", chat_display, api_state chat_display = (chat_display or []) chat_display = chat_display + [{"role": "user", "content": user_text}] return "", chat_display, api_state def on_get_quote(origin, destination, depart, ret, adults, cabin, chat_display, api_state): msg = build_quote_message(origin, destination, depart, ret, adults, cabin) chat_display = (chat_display or []) chat_display = chat_display + [{"role": "user", "content": msg}] return chat_display, api_state def on_assistant(chat_display, api_state): chat_display = (chat_display or []) # find last user message last_user = None for m in reversed(chat_display): if m.get("role") == "user": last_user = m.get("content") break if not last_user: return chat_display, gr.update(value=None), gr.update(value=None), "No message.", "No image.", api_state assistant_text, audio_path, poster, audio_status, img_status, api_state = run_turn(last_user, api_state) chat_display = chat_display + [{"role": "assistant", "content": assistant_text}] aud_update = gr.update(value=audio_path) if audio_path else gr.update(value=None) img_update = gr.update(value=poster) if poster is not None else gr.update(value=None) return chat_display, aud_update, img_update, audio_status, img_status, api_state def on_clear(): return [], None, None, "", "", init_api_state() with gr.Blocks() as demo: api_state = gr.State(init_api_state()) with gr.Column(elem_id="header"): gr.Markdown(f"