Skip to main content

Natural language flight search parser — extract structured flight data from freeform text

Project description

flights-nlp ✈️

A robust, Django-friendly natural language flight search query parser for English and Japanese. It translates freeform text queries into structured parameters ready for flight search APIs (like Amadeus, Sabre, or Skyscanner).

Features

  • 🧠 Hybrid Route Extraction: Combines spaCy NLP models (en_core_web_sm/ja_core_news_sm) with geographic database lookups to reliably extract origin and destination cities/airports, resolving sequence ambiguities.
  • 🇯🇵 Spaceless Japanese Support: Fully parses spaceless Japanese query layouts (e.g., 東京から札幌明日片道).
  • 📍 Multi-Airport Cities (MAC): Resolves city and airport names (e.g., 羽田, 成田) to their IATA codes and ties them back to parent metropolitan codes (e.g., TYO).
  • 🔍 Airport Disambiguation: Extracts parenthesized hints like 大阪(伊丹) to target specific airports (e.g., ITM) instead of whole metropolitan areas.
  • 📅 Relative Dates & Durations: Parses relative terms (today, tomorrow, next week, 来週の月曜日), relative offsets (3日後, 2週間後), and trip durations (for a week, 1週間, 3日間).
  • 👥 Passenger Parsing: Normalizes numbers and counts for adults, children, and infants (e.g., 大人二人, 2 adults 1 infant).
  • 🛡️ Django Ready: Fully optimized for web frameworks with startup model pre-loading (preload_models), custom exception classes, and standard Python logging hooks.

Installation

Requires Python 3.9+. Install via pip or uv:

pip install flights-nlp

SpaCy language pipelines (en_core_web_sm / ja_core_news_sm) are downloaded automatically on first parse (or when you call preload_models). You can also install them manually:

python -m spacy download en_core_web_sm
python -m spacy download ja_core_news_sm

Quick Start (Python API)

Basic Parsing

from datetime import date
from flights_nlp import parse

# Parse a query relative to a reference date
result = parse("Tokyo to Sapporo next week 3 adults", reference_date=date(2026, 7, 12))

print(result.origin)               # "Tokyo"
print(result.origin_iata)          # ["NRT", "HND"]
print(result.origin_city_code)     # "TYO"
print(result.destination)          # "Sapporo"
print(result.destination_iata)     # ["CTS", "OKD"]
print(result.departure_date)       # 2026-07-20
print(result.adults)               # 3
print(result.trip_type)            # "round_trip"

Serializing to JSON

print(result.to_json(indent=2))

Django Startup Warmup (Model Pre-loading)

To prevent the initial web request from experiencing a ~2 second model loading latency, call preload_models inside your Django app's startup hook:

# myapp/apps.py
from django.apps import AppConfig
from flights_nlp import preload_models

class MyAppConfig(AppConfig):
    name = "myapp"
    
    def ready(self):
        # Preload English and Japanese models
        preload_models(["en", "ja"])

Custom Exception Handling

The library raises structured subclasses of FlightsNLPError (which inherits from ValueError):

  • RouteExtractionError: Raised when origin/destination cannot be resolved.
  • DateResolutionError: Raised when date formats are invalid.
  • PassengerParsingError: Raised when passenger parameters are faulty.

Command Line Interface (CLI)

The package installs a CLI tool flights-nlp to parse queries directly from the terminal.

JSON Output (Default)

flights-nlp "Tokyo to Sapporo next week 3 adults"

Table Output

flights-nlp "東京から札幌明日片道" --format table

Output:

┌────────────────┬─────────────────────────┐
│     Field      │          Value          │
├────────────────┼─────────────────────────┤
│ Origin         │ Tokyo [TYO] (NRT,HND)   │
│ Destination    │ Sapporo [SPK] (CTS,OKD) │
│ Departure Date │ 2026-07-13              │
│ Return Date    │ —                       │
│ Trip Type      │ one_way                 │
│ Adults         │ 1                       │
│ Children       │ 0                       │
│ Infants        │ 0                       │
└────────────────┴─────────────────────────┘

Interactive Playground (Streamlit)

For developer testing, run the Streamlit visual debugger locally:

uv run streamlit run app.py

This starts a dashboard where you can type queries, inspect spaCy tokenization / entity tags, check JSON representations, and test various reference dates reactively.


Running Tests

To run the full unit test suite:

pytest tests/

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

flights_nlp-0.1.3.tar.gz (18.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

flights_nlp-0.1.3-py3-none-any.whl (21.4 kB view details)

Uploaded Python 3

File details

Details for the file flights_nlp-0.1.3.tar.gz.

File metadata

  • Download URL: flights_nlp-0.1.3.tar.gz
  • Upload date:
  • Size: 18.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.29 {"installer":{"name":"uv","version":"0.11.29","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for flights_nlp-0.1.3.tar.gz
Algorithm Hash digest
SHA256 903936fbd9b1cec17e937137218fa04b92d71c283bc118e70d7c3aca1eed3b3f
MD5 2791d01362500399e54a0ad53a0d6898
BLAKE2b-256 87fc2d6f096616c5949ce4438cc6d2f489a5da6cf84e40b5c37b56d1dd37487e

See more details on using hashes here.

File details

Details for the file flights_nlp-0.1.3-py3-none-any.whl.

File metadata

  • Download URL: flights_nlp-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 21.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.29 {"installer":{"name":"uv","version":"0.11.29","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for flights_nlp-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 109573b4a18d4e7faac34f37232f54597de6504d6a30b96a01a868279a8d59a6
MD5 a33beb14c78fdfc25c12288e54b1e7b1
BLAKE2b-256 0c0c00c597b57c8f41f27863d5ba6fbe3f8a19131e818f537265b52088c207ab

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page