Spaces:
Sleeping
Sleeping
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}¤cy=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}¤cy=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 | |