File size: 4,733 Bytes
723cf28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import requests
import pandas as pd
from datetime import datetime
from dotenv import load_dotenv
import os
import time
from dotenv import load_dotenv

OPENSKY_URL = "https://opensky-network.org/api/states/all"
OPENSKY_URL_DEPARTURES = "https://opensky-network.org/api/flights/departure"

def fetch_opensky_snapshot() -> pd.DataFrame:
    """
    Fetches a snapshot of current flights from the OpenSky API.
    Returns a pandas DataFrame of flight state vectors.
    """
    r = requests.get(OPENSKY_URL, timeout=20)
    if r.status_code != 200:
        raise RuntimeError(f"Failed to fetch OpenSky data: {r.status_code} {r.reason} -> {r.text[:200]}")   


    data = r.json()
    states = data.get("states", [])
    timestamp = data.get("time", datetime.utcnow().timestamp())

    cols = [
        "icao24", "callsign", "origin_country", "time_position", "last_contact",
        "longitude", "latitude", "baro_altitude", "on_ground", "velocity",
        "true_track", "vertical_rate", "sensors", "geo_altitude", "squawk",
        "spi", "position_source"
    ]
    df = pd.DataFrame(states, columns=cols)
    df["last_contact"] = pd.to_datetime(df["last_contact"], unit="s")
    df.attrs["timestamp"] = datetime.utcfromtimestamp(timestamp)
    return df

def fetch_aviation_API_airlines_endpoint():
    """
    Fetches airline data from the AviationStack API airlines endpoint.
    
    Parameters:
    - None
    
    Returns:
    - dict: The JSON response from the AviationStack API containing the airline data.
    """
    #api_key = os.environ.get("AVIATION_KEY") # Retrieve the API key (when running on HuggingFace)
    # Comment the line above and uncomment the two lines below if you are running the app locally (not on HuggingFace) and have a .env file with the AviationStack API key
    load_dotenv()
    api_key = os.getenv("AVIATION_KEY") # Retrieve the API key
    url = f"https://api.aviationstack.com/v1/airlines?access_key={api_key}"
    response = requests.get(url)
    return response.json()

def fetch_rdu_departures(hours=6) -> pd.DataFrame:
    """
    Fetch recent departures from RDU (KRDU) within the last n hours (default is 6).
    Returns a pandas DataFrame.
    """
    end = int(time.time())
    begin = end - hours * 3600
    params = {
        "airport": "KRDU",
        "begin": begin,
        "end": end
    }

    response = requests.get(OPENSKY_URL_DEPARTURES, params=params, timeout=20)
    if response.status_code != 200:
        raise RuntimeError(f"Failed to fetch data, {response.headers}")
    
    data = response.json()
    columns = [
        "icao24", "firstSeen", "estDepartureAirport", "lastSeen", "estArrivalAirport", "callsign",
        "estDepartureAirportHorizDistance", "estDepartureAirportVertDistance", "estArrivalAirportHorizDistance",
        "estArrivalAirportVertDistance", "departureAirportCandidatesCount", "arrivalAirportCandidatesCount"
    ]
    data_df = pd.DataFrame(data, columns=columns)

    flights = []
    for _, flight in data_df.iterrows():
        flights.append({
            "icao24": flight["icao24"],
            "callsign": flight["callsign"],
            "departure": flight["estDepartureAirport"],
            "arrival": flight["estArrivalAirport"]
        })
    return pd.DataFrame(flights)

def fetch_aviation_API_airlines_endpoint():
    """
    Fetches airline data from the AviationStack API airlines endpoint.
    
    Parameters:
    - None
    
    Returns:
    - dict: The JSON response from the AviationStack API containing the airline data.
    """
    #api_key = os.environ.get("AVIATION_KEY") # Retrieve the API key (when running on HuggingFace)
    # Comment the line above and uncomment the two lines below if you are running the app locally (not on HuggingFace) and have a .env file with the AviationStack API key
    load_dotenv()
    api_key = os.getenv("AVIATION_KEY") # Retrieve the API key
    url = f"https://api.aviationstack.com/v1/airlines?access_key={api_key}"
    response = requests.get(url)
    return response.json()


if __name__ == "__main__":
    print("Fetching live flight data from OpenSky…")
    try:
        df = fetch_opensky_snapshot()
        print(f"Fetched {len(df)} flights at {df.attrs['timestamp']}")
        print(df.head())

        df_2 = fetch_rdu_departures(hours=6)
        print(f"Fetched {len(df)} flights at {df.attrs['timestamp']}")
        print(df.head())
    except Exception as e:
        print("Error:", e)

    print("Fetching airline data from AviationStack…")
    try:
        airline_data = fetch_aviation_API_airlines_endpoint()
        print(f"Fetched {len(airline_data.get('data', []))} airlines")
        print(airline_data)
    except Exception as e:
        print("Error:", e)