[main] Fucking api fuck lort
All checks were successful
Build, Push, and Deploy to Nomad / docker-nomad (push) Successful in 1m1s

This commit is contained in:
2025-01-13 23:42:16 +01:00
parent 75c7a76210
commit 0129164fd5
6 changed files with 325 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
import calendar
from datetime import date, timedelta
def skriv_datoer_med_formattering(år):
start_dato = date(år, 1, 1)
slut_dato = date(år, 12, 29)
dags_differens = timedelta(days=1)
print(f"Datoer for året {år}:\n")
nuværende_dato = start_dato
while nuværende_dato <= slut_dato:
ugenummer = nuværende_dato.isocalendar()[1]
ugedag = nuværende_dato.strftime("%A")
if ugenummer % 2 != 0 and ugedag in ["Friday", "Wednesday"]:
# Tabuler outputtet længere ind
if ugedag == "Friday":
print(f"{nuværende_dato.strftime('%Y-%m-%d')} Til Porto fra København")
if ugedag == "Wednesday":
print(f"{nuværende_dato.strftime('%Y-%m-%d')} Til København fra Porto")
# else:
# print(f"{nuværende_dato.strftime('%Y-%m-%d')} ({ugedag})")
nuværende_dato += dags_differens
# Kald funktionen med det ønskede år
skriv_datoer_med_formattering(2025)

Binary file not shown.

View File

@@ -0,0 +1,177 @@
from pprint import pprint
from amadeus import Client, ResponseError
import pandas as pd
from datetime import datetime, timedelta
import json
class FlightFilter:
def __init__(self, api_key, api_secret):
self.amadeus = Client(client_id=api_key, client_secret=api_secret)
def get_flight_offers(self, request_body):
"""
Fetch flight offers using the Amadeus SDK with a JSON request body.
"""
try:
print("Fetching flight offers with the provided request body...")
response = self.amadeus.shopping.flight_offers_search.post(request_body)
return response.data
except (ResponseError, Exception) as error:
print(f"Error fetching flight offers: {error}")
return []
def filter_and_average_price(flights, morning_departure, evening_departure, morning_hours = 2, evening_hours = 2):
"""
Filters flights:
- Morning departures from OPO.
- Evening departures from CPH.
- Calculates the average price of the matched trips.
"""
morning_time = datetime.strptime( morning_departure, "%H:%M" )
evening_time = datetime.strptime( evening_departure, "%H:%M" )
morning_start = morning_time - timedelta( hours = morning_hours )
morning_end = morning_time + timedelta( hours = morning_hours )
evening_start = evening_time - timedelta( hours = evening_hours )
evening_end = evening_time + timedelta( hours = evening_hours )
morning_flights = []
evening_flights = []
for offer in flights:
for itinerary in offer.get( "itineraries", [] ):
for segment in itinerary.get( "segments", [] ):
departure_time = datetime.strptime( segment["departure"]["at"], "%Y-%m-%dT%H:%M:%S" )
origin = segment["departure"]["iataCode"]
destination = segment["arrival"]["iataCode"]
# Morning flights from OPO
if (
origin == "OPO" and destination == "CPH"
and morning_start.time() <= departure_time.time() <= morning_end.time()
):
morning_flights.append( {
"Flight ID": offer["id"],
"Price (EUR)": float( offer["price"]["total"] ),
"Departure Time": segment["departure"]["at"],
"Arrival Time": segment["arrival"]["at"],
} )
# Evening flights from CPH
elif (
origin == "CPH" and destination == "OPO"
and evening_start.time() <= departure_time.time() <= evening_end.time()
):
evening_flights.append( {
"Flight ID": offer["id"],
"Price (EUR)": float( offer["price"]["total"] ),
"Departure Time": segment["departure"]["at"],
"Arrival Time": segment["arrival"]["at"],
} )
# Calculate average prices
morning_prices = [flight["Price (EUR)"] for flight in morning_flights]
evening_prices = [flight["Price (EUR)"] for flight in evening_flights]
average_morning_price = sum( morning_prices ) / len( morning_prices ) if morning_prices else 0
average_evening_price = sum( evening_prices ) / len( evening_prices ) if evening_prices else 0
return {
"Morning Flights": morning_flights,
"Evening Flights": evening_flights,
"Average Morning Price (EUR)": average_morning_price,
"Average Evening Price (EUR)": average_evening_price,
}
return filtered_flights
def save_to_excel(self, lis_flights, cph_flights, filename):
"""Save flights from LIS and CPH into separate blocks in an Excel sheet."""
with pd.ExcelWriter( filename, engine = "openpyxl" ) as writer:
# Check for OPO → CPH flights
if lis_flights:
lis_df = pd.DataFrame( lis_flights )
lis_df.sort_values( by = "Departure Time", inplace = True )
lis_df.to_excel( writer, sheet_name = "Flights", startrow = 1, index = False )
writer.sheets["Flights"].cell( row = 1, column = 1 ).value = "Departures from OPO around 07:00"
else:
print( "No flights found from OPO to CPH." )
# Check for CPH → OPO flights
if cph_flights:
cph_df = pd.DataFrame( cph_flights )
cph_df.sort_values( by = "Departure Time", inplace = True )
cph_df.to_excel( writer, sheet_name = "Flights", startrow = len( lis_flights ) + 4, index = False )
writer.sheets["Flights"].cell( row = len( lis_flights ) + 4,
column = 1 ).value = "Departures from CPH around 18:30"
else:
print( "No flights found from CPH to OPO." )
# If no data exists, add a placeholder sheet
if not lis_flights and not cph_flights:
print( "No flight data available. Adding placeholder sheet." )
pd.DataFrame( { "Message": ["No flights found"] } ).to_excel( writer, sheet_name = "Flights",
index = False )
print( f"Filtered flights saved to: {filename}" )
# Usage example
if __name__ == "__main__":
api_key = "uxDqIh36xPAUvpXnXynwAnH86pGBdIch"
api_secret = "xTSLooNZpJWantb5"
flight_filter = FlightFilter(api_key, api_secret)
# JSON request body
request_body = {
"currencyCode": "EUR",
"originDestinations": [
{
"id": "1",
"originLocationCode": "OPO",
"destinationLocationCode": "CPH",
"departureDateTimeRange": {
"date": "2025-03-03",
"time": "06:00:00"
}
},
{
"id": "2",
"originLocationCode": "CPH",
"destinationLocationCode": "OPO",
"departureDateTimeRange": {
"date": "2025-03-06",
"time": "20:30:00"
}
}
],
"travelers": [
{"id": "1", "travelerType": "ADULT"}
],
"sources": ["GDS"],
"searchCriteria": {
"excludeAllotments": True,
"addOneWayOffers": False,
"maxFlightOffers": 10,
"allowAlternativeFareOptions": True,
}
}
# Fetch flights
flights = flight_filter.get_flight_offers(request_body)
print(f"Raw flights data: {flights}")
# Filter flights from OPO to CPH around 07:00 ± 1 hour
opo_to_cph_flights = flight_filter.filter_flights_by_time(
flights, origin_filter="OPO", destination_filter="CPH", filter_time_str="06:00", hours=2
)
# Filter flights from CPH to OPO around 18:30 ± 1 hour
cph_to_opo_flights = flight_filter.filter_flights_by_time(
flights, origin_filter="CPH", destination_filter="OPO", filter_time_str="20:30", hours=2
)
# Save to Excel
flight_filter.save_to_excel(opo_to_cph_flights, cph_to_opo_flights, "Filtered_Flights_OPO_CPH.xlsx")

View File

@@ -0,0 +1,111 @@
from amadeus import Client, ResponseError
import pandas as pd
class FlightFilter:
def __init__(self, api_key, api_secret):
self.amadeus = Client(client_id=api_key, client_secret=api_secret)
def get_flight_offers(self, request_body):
try:
print("Fetching flight offers with the provided request body...")
response = self.amadeus.shopping.flight_offers_search.post(request_body)
return response.data
except ResponseError as error:
print(f"Error fetching flight offers: {error}")
print("Response Details:", error.response.body) # Add this line for detailed error logging
return []
def filter_flights(self, flights, origin, destination):
"""
Filters flights by origin and destination.
"""
filtered_flights = []
for offer in flights:
for itinerary in offer.get("itineraries", []):
for segment in itinerary.get("segments", []):
segment_origin = segment["departure"]["iataCode"]
segment_destination = segment["arrival"]["iataCode"]
# Check if the flight matches the filters
if segment_origin == origin and segment_destination == destination:
filtered_flights.append({
"Flight ID": offer["id"],
"Price (EUR)": float(offer["price"]["total"]),
"Departure Time": segment["departure"]["at"],
"Arrival Time": segment["arrival"]["at"],
})
return filtered_flights
def calculate_average_price(self, flights):
"""
Calculate the average price of a list of flights.
"""
prices = [flight["Price (EUR)"] for flight in flights]
return sum(prices) / len(prices) if prices else 0
def save_to_excel(self, filtered_flights, filename):
"""
Save filtered flights to an Excel file.
"""
with pd.ExcelWriter(filename, engine="openpyxl") as writer:
if filtered_flights:
flights_df = pd.DataFrame(filtered_flights)
flights_df.to_excel(writer, sheet_name="Flights", index=False)
print(f"Filtered flights saved to {filename}")
else:
print("No flights found.")
# Usage Example
if __name__ == "__main__":
# Replace these with your Amadeus API credentials
api_key = "uxDqIh36xPAUvpXnXynwAnH86pGBdIch"
api_secret = "xTSLooNZpJWantb5"
# Initialize the FlightFilter
flight_filter = FlightFilter(api_key, api_secret)
# Request body for the API call
request_body = {
"currencyCode": "EUR",
"originDestinations": [
{
"id": "1",
"originLocationCode": "OPO",
"destinationLocationCode": "CPH",
"departureDateTimeRange": {"date": "2025-03-03", "time": "06:00:00"},
},
{
"id": "2",
"originLocationCode": "CPH",
"destinationLocationCode": "OPO",
"departureDateTimeRange": {"date": "2025-03-06", "time": "20:30:00"},
},
],
"travelers": [{"id": "1", "travelerType": "ADULT"}],
"sources": ["GDS"],
}
# Fetch flight offers
flights = flight_filter.get_flight_offers(request_body)
print(flights)
# Filter flights by origin and destination
opo_to_cph_flights = flight_filter.filter_flights(flights, "OPO", "CPH")
cph_to_opo_flights = flight_filter.filter_flights(flights, "CPH", "OPO")
# Calculate average prices
avg_opo_to_cph_price = flight_filter.calculate_average_price(opo_to_cph_flights)
avg_cph_to_opo_price = flight_filter.calculate_average_price(cph_to_opo_flights)
# Output results
print("Flights (OPO → CPH):", opo_to_cph_flights)
print("Flights (CPH → OPO):", cph_to_opo_flights)
print(f"Average OPO → CPH Price: {avg_opo_to_cph_price} EUR")
print(f"Average CPH → OPO Price: {avg_cph_to_opo_price} EUR")
# Save to Excel
all_flights = opo_to_cph_flights + cph_to_opo_flights
flight_filter.save_to_excel(all_flights, "Filtered_Flights.xlsx")