Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

Update CLI to use typer

Punit Aranib5a33804b055
diff --git a/fli/cli.py b/fli/cli.py
index 638a14e..31984dc 100644
--- a/fli/cli.py
+++ b/fli/cli.py
@@ -1,27 +1,70 @@
#!/usr/bin/env python3
-import argparse
from datetime import datetime
-from typing import List, Tuple
+from typing import List, Optional
+
+import typer
+from click import Context, Parameter
+from rich import box
+from rich.console import Console, Group
+from rich.panel import Panel
+from rich.table import Table
+from rich.text import Text
+from typing_extensions import Annotated
from fli.models import Airline, Airport, MaxStops, PassengerInfo, SeatType, SortBy
from fli.search import Search, SearchFilters
+app = typer.Typer(
+ help="Search for flights using Google Flights data",
+ add_completion=True,
+)
+console = Console()
+
+
+def format_airport(airport: Airport) -> str:
+ """Format airport code and name (first two words)."""
+ name_parts = airport.value.split()[:3] # Get first three words
+ name = " ".join(name_parts)
+ return f"{airport.name} ({name})"
+
+
+def validate_time_range(
+ ctx: Context, param: Parameter, value: Optional[str]
+) -> Optional[tuple[int, int]]:
+ """Validate and parse time range in format 'start-end' (24h format)."""
+ if not value:
+ return None
-def parse_time_range(time_range: str) -> Tuple[int, int]:
- """Parse time range in format 'start-end' (24h format)."""
try:
- start, end = map(int, time_range.split("-"))
+ start, end = map(int, value.split("-"))
if not (0 <= start <= 23 and 0 <= end <= 23):
raise ValueError
return start, end
except ValueError:
- raise ValueError("Time range must be in format 'start-end' (e.g., '6-20')")
+ raise typer.BadParameter("Time range must be in format 'start-end' (e.g., 6-20)")
+
+
+def validate_date(ctx: Context, param: Parameter, value: str) -> str:
+ """Validate date format."""
+ try:
+ datetime.strptime(value, "%Y-%m-%d")
+ return value
+ except ValueError:
+ raise typer.BadParameter("Date must be in YYYY-MM-DD format")
-def parse_airlines(airlines: List[str]) -> List[Airline]:
+def parse_airlines(airlines: Optional[List[str]]) -> Optional[List[Airline]]:
"""Parse airlines from list of airline codes."""
- return [getattr(Airline, airline.strip().upper()) for airline in airlines if airline.strip()]
+ if not airlines:
+ return None
+
+ try:
+ return [
+ getattr(Airline, airline.strip().upper()) for airline in airlines if airline.strip()
+ ]
+ except AttributeError as e:
+ raise typer.BadParameter(f"Invalid airline code: {str(e)}")
def filter_flights_by_time(flights: list, start_hour: int, end_hour: int) -> list:
@@ -38,109 +81,166 @@ def filter_flights_by_airlines(flights: list, airlines: List[Airline]) -> list:
return [flight for flight in flights if any(leg.airline in airlines for leg in flight.legs)]
-def main():
- parser = argparse.ArgumentParser(
- description="Search for flights using simple parameters",
- formatter_class=argparse.RawDescriptionHelpFormatter,
- epilog="""
-Examples:
- fli JFK LHR 2025-10-25 --time 6-20 --airlines BA KL
- fli SFO NYC 2025-11-01 --time 9-17 --stops NON_STOP --sort DURATION
- fli LAX MIA 2025-12-25 --seat BUSINESS
- """,
- )
-
- # Required arguments
- parser.add_argument("from_airport", help="Departure airport code (e.g., JFK)")
- parser.add_argument("to_airport", help="Arrival airport code (e.g., LON)")
- parser.add_argument("date", help="Travel date (YYYY-MM-DD)")
-
- # Optional arguments
- parser.add_argument("--time", help="Time range in 24h format (e.g., 6-20)")
- parser.add_argument("--airlines", nargs="+", help="List of airline codes (e.g., BA KL)")
- parser.add_argument(
- "--seat",
- choices=["ECONOMY", "PREMIUM_ECONOMY", "BUSINESS", "FIRST"],
- default="ECONOMY",
- help="Seat type (default: ECONOMY)",
- )
- parser.add_argument(
- "--stops",
- choices=["ANY", "NON_STOP", "ONE_STOP", "TWO_PLUS_STOPS"],
- default="ANY",
- help="Maximum number of stops (default: ANY)",
- )
- parser.add_argument(
- "--sort",
- choices=["CHEAPEST", "DURATION", "DEPARTURE_TIME", "ARRIVAL_TIME"],
- default="CHEAPEST",
- help="Sort results by (default: CHEAPEST)",
- )
-
- args = parser.parse_args()
-
- try:
- # Parse parameters
- departure_airport = getattr(Airport, args.from_airport.upper())
- arrival_airport = getattr(Airport, args.to_airport.upper())
- seat_type = getattr(SeatType, args.seat)
- stops = getattr(MaxStops, args.stops)
- sort_by = getattr(SortBy, args.sort)
-
- # Validate date format
- try:
- datetime.strptime(args.date, "%Y-%m-%d")
- except ValueError:
- raise ValueError("Date must be in YYYY-MM-DD format")
-
- # Create search filters
- filters = SearchFilters(
- departure_airport=departure_airport,
- arrival_airport=arrival_airport,
- departure_date=args.date,
- passenger_info=PassengerInfo(adults=1),
- seat_type=seat_type,
- stops=stops,
- sort_by=sort_by,
+def format_duration(minutes: int) -> str:
+ """Format duration in minutes to hours and minutes."""
+ hours = minutes // 60
+ mins = minutes % 60
+ return f"{hours}h {mins}m"
+
+
+def display_flight_results(flights: list):
+ """Display flight results in a beautiful format."""
+ if not flights:
+ console.print(Panel("No flights found matching your criteria", style="red"))
+ return
+
+ for i, flight in enumerate(flights, 1):
+ # Create main flight info table
+ table = Table(show_header=False, box=box.SIMPLE)
+ table.add_column("Label", style="blue")
+ table.add_column("Value", style="green")
+
+ table.add_row("Price", f"${flight.price:,.2f}")
+ table.add_row("Duration", format_duration(flight.duration))
+ table.add_row("Stops", str(flight.stops))
+
+ # Create segments table
+ segments = Table(title="Flight Segments", box=box.ROUNDED)
+ segments.add_column("Airline", style="cyan")
+ segments.add_column("Flight", style="magenta")
+ segments.add_column("From", style="yellow", width=30)
+ segments.add_column("Departure", style="green")
+ segments.add_column("To", style="yellow", width=30)
+ segments.add_column("Arrival", style="green")
+
+ for leg in flight.legs:
+ segments.add_row(
+ leg.airline.value,
+ leg.flight_number,
+ format_airport(leg.departure_airport),
+ leg.departure_datetime.strftime("%H:%M %d-%b"),
+ format_airport(leg.arrival_airport),
+ leg.arrival_datetime.strftime("%H:%M %d-%b"),
+ )
+
+ # Display in a panel
+ console.print(
+ Panel(
+ Group(
+ Text(f"Flight Option {i}", style="bold blue"),
+ Text(""),
+ table,
+ Text(""),
+ segments,
+ ),
+ title=f"[bold]Flight {i} of {len(flights)}[/bold]",
+ border_style="blue",
+ box=box.ROUNDED,
+ )
)
-
- # Perform search
- search = Search()
- flights = search.search(filters)
-
- if not flights:
- print("No flights found.")
- return
-
- # Apply time filter if specified
- if args.time:
- start_hour, end_hour = parse_time_range(args.time)
- flights = filter_flights_by_time(flights, start_hour, end_hour)
-
- # Apply airline filter if specified
- if args.airlines:
- airlines = parse_airlines(args.airlines)
- flights = filter_flights_by_airlines(flights, airlines)
-
- if not flights:
- print("No flights found matching the specified filters.")
- return
-
- # Display results
- for i, flight in enumerate(flights, 1):
- print(f"\nFlight Option {i}:")
- print(f"Price: ${flight.price}")
- print(f"Duration: {flight.duration} minutes")
- print(f"Stops: {flight.stops}")
-
- for leg in flight.legs:
- print(f"\n Flight: {leg.airline.value} {leg.flight_number}")
- print(f" From: {leg.departure_airport.value} at {leg.departure_datetime}")
- print(f" To: {leg.arrival_airport.value} at {leg.arrival_datetime}")
-
- except (AttributeError, ValueError) as e:
- parser.error(str(e))
+ console.print()
+
+
+def search(
+ from_airport: Annotated[str, typer.Argument(help="Departure airport code (e.g., JFK)")],
+ to_airport: Annotated[str, typer.Argument(help="Arrival airport code (e.g., LHR)")],
+ date: Annotated[str, typer.Argument(help="Travel date (YYYY-MM-DD)", callback=validate_date)],
+ time: Annotated[
+ Optional[str],
+ typer.Option(
+ "--time",
+ "-t",
+ help="Time range in 24h format (e.g., 6-20)",
+ callback=validate_time_range,
+ ),
+ ] = None,
+ airlines: Annotated[
+ Optional[List[str]],
+ typer.Option(
+ "--airlines",
+ "-a",
+ help="List of airline codes (e.g., BA KL)",
+ ),
+ ] = None,
+ seat: Annotated[
+ str,
+ typer.Option(
+ "--seat",
+ "-s",
+ help="Seat type (ECONOMY, PREMIUM_ECONOMY, BUSINESS, FIRST)",
+ ),
+ ] = "ECONOMY",
+ stops: Annotated[
+ str,
+ typer.Option(
+ "--stops",
+ "-x",
+ help="Maximum number of stops (ANY, NON_STOP, ONE_STOP, TWO_PLUS_STOPS)",
+ ),
+ ] = "ANY",
+ sort: Annotated[
+ str,
+ typer.Option(
+ "--sort",
+ "-o",
+ help="Sort results by (CHEAPEST, DURATION, DEPARTURE_TIME, ARRIVAL_TIME)",
+ ),
+ ] = "CHEAPEST",
+):
+ """
+ Search for flights with flexible filtering options.
+
+ Examples:
+ fli search JFK LHR 2025-10-25 --time 6-20 --airlines BA KL
+ fli search SFO NYC 2025-11-01 -t 9-17 --stops NON_STOP --sort DURATION
+ fli search LAX MIA 2025-12-25 --seat BUSINESS
+ """
+ with console.status("[bold green]Searching for flights...") as status:
+ try:
+ # Parse parameters
+ departure_airport = getattr(Airport, from_airport.upper())
+ arrival_airport = getattr(Airport, to_airport.upper())
+ seat_type = getattr(SeatType, seat.upper())
+ max_stops = getattr(MaxStops, stops.upper())
+ sort_by = getattr(SortBy, sort.upper())
+
+ # Create search filters
+ filters = SearchFilters(
+ departure_airport=departure_airport,
+ arrival_airport=arrival_airport,
+ departure_date=date,
+ passenger_info=PassengerInfo(adults=1),
+ seat_type=seat_type,
+ stops=max_stops,
+ sort_by=sort_by,
+ )
+
+ # Perform search
+ search_client = Search()
+ flights = search_client.search(filters)
+
+ if not flights:
+ console.print(Panel("No flights found.", style="red"))
+ raise typer.Exit(1)
+
+ # Apply time filter if specified
+ if time:
+ start_hour, end_hour = time
+ flights = filter_flights_by_time(flights, start_hour, end_hour)
+
+ # Apply airline filter if specified
+ airline_list = parse_airlines(airlines)
+ if airline_list:
+ flights = filter_flights_by_airlines(flights, airline_list)
+
+ # Display results
+ display_flight_results(flights)
+
+ except (AttributeError, ValueError) as e:
+ console.print(f"[red]Error:[/red] {str(e)}")
+ raise typer.Exit(1)
if __name__ == "__main__":
- main()
+ app()
diff --git a/poetry.lock b/poetry.lock
index 7ee4f75..3c518a1 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -222,6 +222,20 @@ files = [
{file = "charset_normalizer-3.4.1.tar.gz", hash = "sha256:44251f18cd68a75b56585dd00dae26183e102cd5e0f9f1466e6df5da2ed64ea3"},
]
+[[package]]
+name = "click"
+version = "8.1.8"
+description = "Composable command line interface toolkit"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "click-8.1.8-py3-none-any.whl", hash = "sha256:63c132bbbed01578a06712a2d1f497bb62d9c1c0d329b7903a866228027263b2"},
+ {file = "click-8.1.8.tar.gz", hash = "sha256:ed53c9d8990d83c2a27deae68e4ee337473f6330c040a31d4225c9574d16096a"},
+]
+
+[package.dependencies]
+colorama = {version = "*", markers = "platform_system == \"Windows\""}
+
[[package]]
name = "colorama"
version = "0.4.6"
@@ -525,6 +539,41 @@ html5 = ["html5lib"]
htmlsoup = ["BeautifulSoup4"]
source = ["Cython (>=3.0.11)"]
+[[package]]
+name = "markdown-it-py"
+version = "3.0.0"
+description = "Python port of markdown-it. Markdown parsing, done right!"
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "markdown-it-py-3.0.0.tar.gz", hash = "sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb"},
+ {file = "markdown_it_py-3.0.0-py3-none-any.whl", hash = "sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1"},
+]
+
+[package.dependencies]
+mdurl = ">=0.1,<1.0"
+
+[package.extras]
+benchmarking = ["psutil", "pytest", "pytest-benchmark"]
+code-style = ["pre-commit (>=3.0,<4.0)"]
+compare = ["commonmark (>=0.9,<1.0)", "markdown (>=3.4,<4.0)", "mistletoe (>=1.0,<2.0)", "mistune (>=2.0,<3.0)", "panflute (>=2.3,<3.0)"]
+linkify = ["linkify-it-py (>=1,<3)"]
+plugins = ["mdit-py-plugins"]
+profiling = ["gprof2dot"]
+rtd = ["jupyter_sphinx", "mdit-py-plugins", "myst-parser", "pyyaml", "sphinx", "sphinx-copybutton", "sphinx-design", "sphinx_book_theme"]
+testing = ["coverage", "pytest", "pytest-cov", "pytest-regressions"]
+
+[[package]]
+name = "mdurl"
+version = "0.1.2"
+description = "Markdown URL utilities"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8"},
+ {file = "mdurl-0.1.2.tar.gz", hash = "sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba"},
+]
+
[[package]]
name = "packaging"
version = "24.2"
@@ -694,6 +743,20 @@ files = [
[package.dependencies]
typing-extensions = ">=4.6.0,<4.7.0 || >4.7.0"
+[[package]]
+name = "pygments"
+version = "2.19.0"
+description = "Pygments is a syntax highlighting package written in Python."
+optional = false
+python-versions = ">=3.8"
+files = [
+ {file = "pygments-2.19.0-py3-none-any.whl", hash = "sha256:4755e6e64d22161d5b61432c0600c923c5927214e7c956e31c23923c89251a9b"},
+ {file = "pygments-2.19.0.tar.gz", hash = "sha256:afc4146269910d4bdfabcd27c24923137a74d562a23a320a41a55ad303e19783"},
+]
+
+[package.extras]
+windows-terminal = ["colorama (>=0.4.6)"]
+
[[package]]
name = "pytest"
version = "8.3.4"
@@ -765,6 +828,24 @@ urllib3 = ">=1.21.1,<3"
socks = ["PySocks (>=1.5.6,!=1.5.7)"]
use-chardet-on-py3 = ["chardet (>=3.0.2,<6)"]
+[[package]]
+name = "rich"
+version = "13.9.4"
+description = "Render rich text, tables, progress bars, syntax highlighting, markdown and more to the terminal"
+optional = false
+python-versions = ">=3.8.0"
+files = [
+ {file = "rich-13.9.4-py3-none-any.whl", hash = "sha256:6049d5e6ec054bf2779ab3358186963bac2ea89175919d699e378b99738c2a90"},
+ {file = "rich-13.9.4.tar.gz", hash = "sha256:439594978a49a09530cff7ebc4b5c7103ef57baf48d5ea3184f21d9a2befa098"},
+]
+
+[package.dependencies]
+markdown-it-py = ">=2.2.0"
+pygments = ">=2.13.0,<3.0.0"
+
+[package.extras]
+jupyter = ["ipywidgets (>=7.5.1,<9)"]
+
[[package]]
name = "ruff"
version = "0.8.6"
@@ -792,6 +873,17 @@ files = [
{file = "ruff-0.8.6.tar.gz", hash = "sha256:dcad24b81b62650b0eb8814f576fc65cfee8674772a6e24c9b747911801eeaa5"},
]
+[[package]]
+name = "shellingham"
+version = "1.5.4"
+description = "Tool to Detect Surrounding Shell"
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686"},
+ {file = "shellingham-1.5.4.tar.gz", hash = "sha256:8dbca0739d487e5bd35ab3ca4b36e11c4078f3a234bfce294b0a0291363404de"},
+]
+
[[package]]
name = "sniffio"
version = "1.3.1"
@@ -818,6 +910,23 @@ files = [
doc = ["reno", "sphinx"]
test = ["pytest", "tornado (>=4.5)", "typeguard"]
+[[package]]
+name = "typer"
+version = "0.15.1"
+description = "Typer, build great CLIs. Easy to code. Based on Python type hints."
+optional = false
+python-versions = ">=3.7"
+files = [
+ {file = "typer-0.15.1-py3-none-any.whl", hash = "sha256:7994fb7b8155b64d3402518560648446072864beefd44aa2dc36972a5972e847"},
+ {file = "typer-0.15.1.tar.gz", hash = "sha256:a0588c0a7fa68a1978a069818657778f86abe6ff5ea6abf472f940a08bfe4f0a"},
+]
+
+[package.dependencies]
+click = ">=8.0.0"
+rich = ">=10.11.0"
+shellingham = ">=1.3.0"
+typing-extensions = ">=3.7.4.3"
+
[[package]]
name = "typing-extensions"
version = "4.12.2"
@@ -849,4 +958,4 @@ zstd = ["zstandard (>=0.18.0)"]
[metadata]
lock-version = "2.0"
python-versions = "^3.13"
-content-hash = "011fe30f59c081b3d9fb77737220806b22d288fc713668c43b02ee4e37c87cd5"
+content-hash = "ae5aca23bf470b2036de0bb446c04e82fbd59e92be1441c1e9e82ca95ab19757"
diff --git a/pyproject.toml b/pyproject.toml
index fcb75fa..3fb3caa 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -14,9 +14,10 @@ pydantic = "^2.10.4"
ratelimit = "^2.2.1"
requests = "^2.32.3"
tenacity = "^9.0.0"
+typer = "^0.15.1"
[tool.poetry.scripts]
-fli = "fli.cli:main"
+fli = "fli.cli:app"
[tool.poetry.group.dev.dependencies]
pytest = "^8.3.4"