File size: 9,529 Bytes
be4f592
 
 
5937e2e
 
be4f592
293fd6c
5937e2e
 
c206733
 
5937e2e
 
c206733
5937e2e
 
 
 
 
be4f592
5937e2e
c206733
 
be4f592
c206733
5937e2e
 
 
c206733
5937e2e
c206733
5937e2e
 
 
c206733
 
 
 
 
 
 
 
 
 
 
5937e2e
 
 
 
c206733
5937e2e
 
c206733
 
 
 
 
79f9cf5
5937e2e
c206733
5937e2e
 
 
c206733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5937e2e
be4f592
c206733
 
 
 
5937e2e
c206733
 
 
 
5937e2e
c206733
 
 
 
5937e2e
 
 
 
 
c206733
5937e2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c206733
5937e2e
 
 
 
be4f592
5937e2e
c206733
 
 
 
 
 
5937e2e
c206733
 
 
5937e2e
c206733
 
 
5937e2e
c206733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5937e2e
c206733
 
5937e2e
c206733
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
import os
from dotenv import load_dotenv
import datetime

load_dotenv()
print(os.environ.get("FLIGHTLABS_API_TOKEN"), "apitoken")
def get_travel_listing(originSkyId, destinationSkyId, originEntityId, destinationEntityId, date, adults, access_key=None):
    try:
        # Use API token from environment or passed as an argument
        access_key = access_key or os.environ.get("FLIGHTLABS_API_TOKEN")
        if not access_key:
            raise ValueError("Access key is required.")
        
        if not originSkyId or not destinationSkyId or not originEntityId or not destinationEntityId:
            raise ValueError("All IDs (Sky and Entity) are required.")

        # Construct API URL
        api_url = f"https://app.goflightlabs.com/retrieveFlights?access_key={access_key}&originSkyId={originSkyId}&destinationSkyId={destinationSkyId}&originEntityId={originEntityId}&destinationEntityId={destinationEntityId}&date={date}&adults={adults}"
        response = requests.get(api_url)
        response.raise_for_status()

        # Parse response JSON
        data = response.json()

        if 'error' in data:
            raise ValueError(f"API Error: {data['error']}")

        # Process the response data
        extracted_data = []
        seen_flights = set()

        for itinerary in data.get("itineraries", []):
            for leg in itinerary.get("legs", []):
                # Safely access nested keys
                origin = leg.get("origin", {}).get("name", "N/A")
                destination = leg.get("destination", {}).get("name", "N/A")
                duration_in_minutes = leg.get("durationInMinutes", 0)
                carriers = leg.get("carriers", {}).get("marketing", [{}])

                unique_key = (
                    leg.get("origin", {}).get("displayCode", "N/A"),
                    leg.get("destination", {}).get("displayCode", "N/A"),
                    leg.get("departure", "N/A")
                )
                if unique_key in seen_flights:
                    continue
                seen_flights.add(unique_key)

                # Format duration safely
                hours = duration_in_minutes // 60
                minutes = duration_in_minutes % 60
                duration_formatted = f"{hours} hours and {minutes} minutes" if duration_in_minutes else "N/A"

                # Safely get airline details
                airline_code = carriers[0].get("alternateId", "N/A")
                airline_name = carriers[0].get("name", "N/A")

                # Build stops information
                stop_locations = [leg.get("origin", {}).get("displayCode", "N/A")]
                stop_details = []
                segments = leg.get("segments", [])
                for i, segment in enumerate(segments[:-1]):
                    stop_code = segment.get("destination", {}).get("displayCode", "N/A")
                    stop_arrival = segment.get("arrival", None)
                    next_departure = segments[i + 1].get("departure", None)
                    if stop_arrival and next_departure:
                        stop_duration_minutes = int(
                            (datetime.datetime.fromisoformat(next_departure) -
                             datetime.datetime.fromisoformat(stop_arrival)).total_seconds() / 60
                        )
                        stop_hours = stop_duration_minutes // 60
                        stop_minutes = stop_duration_minutes % 60
                        stop_time_formatted = (
                            f"{stop_hours} hours" if stop_minutes == 0 else
                            f"{stop_hours} hours and {stop_minutes} minutes" if stop_hours > 0 else
                            f"{stop_minutes} minutes"
                        )
                        stop_details.append(f"{stop_code} ({stop_time_formatted})")
                    stop_locations.append(stop_code)

                stop_locations.append(leg.get("destination", {}).get("displayCode", "N/A"))
                stops_route = " --> ".join(stop_locations)

                # Safely extract flight price
                price = itinerary.get("price", {}).get("formatted", "N/A")

                # Add extracted data to the list
                extracted_data.append({
                    "origin": origin,
                    "destination": destination,
                    "airline_code": airline_code,
                    "airline_name": airline_name,
                    "duration": duration_formatted,
                    "price": price,
                    "departure": leg.get("departure", "N/A"),
                    "arrival": leg.get("arrival", "N/A"),
                    "flight_number": ", ".join(segment.get("flightNumber", "N/A") for segment in segments),
                    "stop_count": leg.get("stopCount", 0),
                    "stops_route": stops_route,
                    "stops_details": stop_details
                })

        # Display the extracted flight data in a structured format
        for flight in extracted_data:
            print("\nFlight Details:")
            print(f"Origin: {flight['origin']}")
            print(f"Destination: {flight['destination']}")
            print(f"Airline Code: {flight['airline_code']}")
            print(f"Airline Name: {flight['airline_name']}")
            print(f"Duration: {flight['duration']}")
            print(f"Price: {flight['price']}")
            print(f"Departure: {flight['departure']}")
            print(f"Arrival: {flight['arrival']}")
            print(f"Flight Number(s): {flight['flight_number']}")
            print(f"Number of Stops: {flight['stop_count']}")
            print(f"Route: {flight['stops_route']}")
            if flight['stop_count'] > 0:
                print(f"Stop Details: {', '.join(flight['stops_details'])}")
            else:
                print("Stop Details: No stops on the trip")

        return extracted_data

    except Exception as e:
        print(f"Error occurred: {e}")
        return False

if __name__ == "__main__":
    try:
        # Gather user inputs
        originSkyId = input("Enter the origin SkyId: ").strip()
        if not originSkyId:
            raise ValueError("Origin SkyId is required.")
        
        destinationSkyId = input("Enter the destination SkyId: ").strip()
        if not destinationSkyId:
            raise ValueError("Destination SkyId is required.")
        
        originEntityId = input("Enter the origin EntityId: ").strip()
        if not originEntityId:
            raise ValueError("Origin EntityId is required.")
        
        destinationEntityId = input("Enter the destination EntityId: ").strip()
        if not destinationEntityId:
            raise ValueError("Destination EntityId is required.")
        
        date_input = input("Enter the travel date (YYYY-MM-DD): ").strip()
        if not date_input:
            raise ValueError("Travel date is required.")
        
        adults = input("Enter the number of adults (optional): ").strip()

        # Validate the date input
        try:
            date = datetime.datetime.strptime(date_input, "%Y-%m-%d").date()
        except ValueError:
            raise ValueError("Invalid date format. Please use YYYY-MM-DD.")

        # Call the get_travel_listing function
        print("\nFetching travel listings...")
        travel_listings = get_travel_listing(
            originSkyId=originSkyId,
            destinationSkyId=destinationSkyId,
            originEntityId=originEntityId,
            destinationEntityId=destinationEntityId,
            date=str(date),
            adults=adults or 1  
        )

        if not travel_listings:
            print("No travel listings found or an error occurred.")
    except Exception as e:
        print(f"Error occurred: {e}")

# code1: 

# import requests
# import os
# import pandas as pd

# from dotenv import load_dotenv
# load_dotenv()

# def get_travel_listing (origin_iata, destination_iata, depart_date, return_date ):
#      try:
#         api_token = os.environ["TRAVEL_PAYOUT_API_TOKEN"]
#         api_url = f"https://api.travelpayouts.com/v1/prices/cheap?origin={origin_iata}&destination={destination_iata}&depart_date={depart_date}&return_date={return_date or ''}&token={api_token}&currency=usd"
#       # FOR CALENDAR
#       #   api_url = f"https://api.travelpayouts.com/v1/prices/calendar?origin={origin_iata}&destination={destination_iata}&depart_date={depart_date}&return_date={return_date or ''}&token={api_token}&currency=usd"
#         print(api_url)
#         response = requests.get(api_url)
#         data = response.json()
#         print(data)
        
#         airlines_data = []
#         airlines = pd.read_json('data/airlines.json')
        
#         for k in data['data'].keys():
#             # find PK in airlines[]{code = PK}
#             # FOR CALENDER
#             # data['data'][k]['airline_name'] = airlines[airlines['code'] == data['data'][k]['airline']]['name'].values[0]
            
#             # FOR CHEAP FLIGHTS
#             airline = {}
#             airline_complete = airlines[airlines['code'] == data['data'][k][list(data['data'][k].keys())[0]]['airline']]['name'].values[0]
            
#             airline = data['data'][k][list(data['data'][k].keys())[0]]
#             airline['airline_name'] = airline_complete

#             airlines_data.append(airline)

#         return airlines_data

#      except Exception as e:
#         print(e)
#         print("ERR")
#         return False