Skip to content

Commit

Permalink
black formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
ryansurf committed May 24, 2024
1 parent cb6180f commit b363875
Show file tree
Hide file tree
Showing 6 changed files with 141 additions and 95 deletions.
70 changes: 43 additions & 27 deletions src/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,16 @@ def get_coordinates(args):
"""
for arg in args:
arg = str(arg)
if arg.startswith("location=") or arg.startswith("loc=") :
address = arg.split('=')[1]
if arg.startswith("location=") or arg.startswith("loc="):
address = arg.split("=")[1]
geolocator = Nominatim(user_agent="cli-surf")
location = geolocator.geocode(address)
if location is not None:
return [location.latitude, location.longitude, location]
return "No data"
return default_location()


def default_location():
"""
If no location specified in cli, find users location
Expand All @@ -36,28 +37,29 @@ def default_location():

if response.status_code == 200:
data = response.json()
location = data['loc'].split(',')
location = data["loc"].split(",")
lat = location[0]
long = location[1]
city = data['city']
city = data["city"]
return [lat, long, city]
return "No data"


def get_uv(lat, long, decimal, unit="imperial"):
"""
Get UV at coordinates
"""
# Setup the Open-Meteo API client with cache and retry on error
cache_session = requests_cache.CachedSession('.cache', expire_after = 3600)
retry_session = retry(cache_session, retries = 5, backoff_factor = 0.2)
openmeteo = openmeteo_requests.Client(session = retry_session)
cache_session = requests_cache.CachedSession(".cache", expire_after=3600)
retry_session = retry(cache_session, retries=5, backoff_factor=0.2)
openmeteo = openmeteo_requests.Client(session=retry_session)

url = "https://air-quality-api.open-meteo.com/v1/air-quality"
params = {
"latitude": lat,
"longitude": long,
"length_unit": unit,
"current": "uv_index"
"current": "uv_index",
}
try:
responses = openmeteo.weather_api(url, params=params)
Expand All @@ -72,14 +74,15 @@ def get_uv(lat, long, decimal, unit="imperial"):

return current_uv_index


def ocean_information(lat, long, decimal, unit="imperial"):
"""
Get Ocean Data at coordinates
"""
# Setup the Open-Meteo API client with cache and retry on error
cache_session = requests_cache.CachedSession('.cache', expire_after = 3600)
retry_session = retry(cache_session, retries = 5, backoff_factor = 0.2)
openmeteo = openmeteo_requests.Client(session = retry_session)
cache_session = requests_cache.CachedSession(".cache", expire_after=3600)
retry_session = retry(cache_session, retries=5, backoff_factor=0.2)
openmeteo = openmeteo_requests.Client(session=retry_session)

url = "https://marine-api.open-meteo.com/v1/marine"
params = {
Expand All @@ -88,7 +91,7 @@ def ocean_information(lat, long, decimal, unit="imperial"):
"current": ["wave_height", "wave_direction", "wave_period"],
"length_unit": unit,
"timezone": "auto",
"forecast_days": 3
"forecast_days": 3,
}
try:
responses = openmeteo.weather_api(url, params=params)
Expand All @@ -114,9 +117,9 @@ def forecast(lat, long, decimal, days=0):
Number of forecast days. Max is 7
"""
# Setup the Open-Meteo API client with cache and retry on error
cache_session = requests_cache.CachedSession('.cache', expire_after = 3600)
retry_session = retry(cache_session, retries = 5, backoff_factor = 0.2)
openmeteo = openmeteo_requests.Client(session = retry_session)
cache_session = requests_cache.CachedSession(".cache", expire_after=3600)
retry_session = retry(cache_session, retries=5, backoff_factor=0.2)
openmeteo = openmeteo_requests.Client(session=retry_session)

url = "https://marine-api.open-meteo.com/v1/marine"
params = {
Expand All @@ -125,21 +128,34 @@ def forecast(lat, long, decimal, days=0):
"daily": ["wave_height_max", "wave_direction_dominant", "wave_period_max"],
"length_unit": "imperial",
"timezone": "auto",
"forecast_days": days
"forecast_days": days,
}
responses = openmeteo.weather_api(url, params=params)

response = responses[0]

daily_height_max = round_decimal(response.Daily().Variables(0).ValuesAsNumpy(), decimal)
daily_direction_dominant = round_decimal(response.Daily().Variables(1).ValuesAsNumpy(), decimal)
daily_period_max = round_decimal(response.Daily().Variables(2).ValuesAsNumpy(), decimal)

daily_data = {"date": pd.date_range(
start = pd.to_datetime(response.Daily().Time(), unit = "s", utc = True),
end = pd.to_datetime(response.Daily().TimeEnd(), unit = "s", utc = True),
freq = pd.Timedelta(seconds = response.Daily().Interval()),
inclusive = "left"
)}
daily_height_max = round_decimal(
response.Daily().Variables(0).ValuesAsNumpy(), decimal
)
daily_direction_dominant = round_decimal(
response.Daily().Variables(1).ValuesAsNumpy(), decimal
)
daily_period_max = round_decimal(
response.Daily().Variables(2).ValuesAsNumpy(), decimal
)

daily_data = {
"date": pd.date_range(
start=pd.to_datetime(response.Daily().Time(), unit="s", utc=True),
end=pd.to_datetime(response.Daily().TimeEnd(), unit="s", utc=True),
freq=pd.Timedelta(seconds=response.Daily().Interval()),
inclusive="left",
)
}

return [daily_height_max, daily_direction_dominant, daily_period_max, daily_data['date']]
return [
daily_height_max,
daily_direction_dominant,
daily_period_max,
daily_data["date"],
]
24 changes: 16 additions & 8 deletions src/art.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
All ASCII art in this file
"""

#ASCII text colors
# ASCII text colors
colors = {
"end": "\033[0m",
"default": "\033[39m",
Expand All @@ -12,26 +12,32 @@
"blue": "\033[0;34m",
"purple": "\033[0;35m",
"teal": "\033[0;36m",
"light_blue": "\033[0;34m"
"light_blue": "\033[0;34m",
}


def print_wave(show_wave, show_large_wave, color):
"""
Prints Wave
"""
if color is not None and color.lower() not in colors:
print("Not a valid color")
color = 'blue'
color = "blue"
if int(show_wave) == 1:


print(colors[color] + """
print(
colors[color]
+ """
.-``'.
.` .`
_.-' '._
""" + colors['end'])
"""
+ colors["end"]
)
if int(show_large_wave) == 1:
print(colors[color] + """
print(
colors[color]
+ """
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⣴⣶⠾⠿⠿⠯⣷⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣼⣾⠛⠁⠀⠀⠀⠀⠀⠀⠈⢻⣦⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⣾⠿⠁⠀⠀⠀⢀⣤⣾⣟⣛⣛⣶⣬⣿⣆⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
Expand All @@ -41,4 +47,6 @@ def print_wave(show_wave, show_large_wave, color):
⠀⠀⠀⠀⠀⣠⣼⡏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠙⠷⣤⣤⣠⣤⣤⡤⡶⣶⢿⠟⠹⠿⠄⣿⣿⠏⠀⣀⣤⡦⠀⠀⠀⠀⣀⡄
⢀⣄⣠⣶⣿⠏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠉⠓⠚⠋⠉⠀⠀⠀⠀⠀⠀⠈⠛⡛⡻⠿⠿⠙⠓⢒⣺⡿⠋⠁
⠉⠉⠉⠛⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠉⠁⠀
""" + colors['end'])
"""
+ colors["end"]
)
42 changes: 25 additions & 17 deletions src/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
General helper functions
"""


def seperate_args(args):
"""
Args are seperated by commas in input. Sereperat them and return list
Expand All @@ -11,20 +12,22 @@ def seperate_args(args):
return new_args
return []


def get_forecast_days(args):
"""
Checks to see if forecast in cli args. Defaults to 0
"""
for arg in args:
arg = str(arg)
if arg.startswith("forecast=") or arg.startswith("fc="):
forecast = int(arg.split('=')[1])
forecast = int(arg.split("=")[1])
if forecast < 0 or forecast > 7:
print("Must choose a non-negative number >= 7 in forecast!")
break
return forecast
return 0


def print_location(city, show_city):
"""
Prints location
Expand All @@ -33,36 +36,39 @@ def print_location(city, show_city):
print("Location: ", city)
print("\n")


# def print_output(uv_index, ocean_data, show_uv, show_height, show_direction, show_period):
def print_output(ocean_data_dict):
"""
Prints output
"""
if int(ocean_data_dict['show_uv']) == 1:
print("UV index: ", ocean_data_dict['uv_index'])
if int(ocean_data_dict['show_height']) == 1:
print("Wave Height: ", ocean_data_dict['ocean_data'][0])
if int(ocean_data_dict['show_direction']) == 1:
print("Wave Direction: ", ocean_data_dict['ocean_data'][1])
if int(ocean_data_dict['show_period']) == 1:
print("Wave Period: ", ocean_data_dict['ocean_data'][2])
if int(ocean_data_dict["show_uv"]) == 1:
print("UV index: ", ocean_data_dict["uv_index"])
if int(ocean_data_dict["show_height"]) == 1:
print("Wave Height: ", ocean_data_dict["ocean_data"][0])
if int(ocean_data_dict["show_direction"]) == 1:
print("Wave Direction: ", ocean_data_dict["ocean_data"][1])
if int(ocean_data_dict["show_period"]) == 1:
print("Wave Period: ", ocean_data_dict["ocean_data"][2])


def print_forecast(ocean, forecast):
"""
Takes in list of forecast data and prints
"""
transposed = list(zip(*forecast))
for day in transposed:
if ocean['show_date'] == 1:
if ocean["show_date"] == 1:
print("Date: ", day[3])
if int(ocean['show_height']) == 1:
if int(ocean["show_height"]) == 1:
print("Wave Height: ", day[0])
if int(ocean['show_direction']) == 1:
if int(ocean["show_direction"]) == 1:
print("Wave Direction: ", day[1])
if int(ocean['show_period']) == 1:
if int(ocean["show_period"]) == 1:
print("Wave Period: ", day[2])
print("\n")


def extract_decimal(args):
"""
Function to extract decimal value from command-line arguments
Expand All @@ -71,22 +77,24 @@ def extract_decimal(args):
for arg in args:
if arg.startswith("decimal=") or arg.startswith("dec="):
try:
decimal_value = int(arg.split('=')[1])
decimal_value = int(arg.split("=")[1])
return decimal_value
except (ValueError, IndexError):
print("Invalid value for decimal. Please provide an integer.")
return 1


def get_color(args):
"""
Gets the color in the cli args
"""
for arg in args:
arg = str(arg)
if arg.startswith("color=") or arg.startswith("c=") :
color_name = arg.split('=')[1]
if arg.startswith("color=") or arg.startswith("c="):
color_name = arg.split("=")[1]
return color_name
return 'blue'
return "blue"


def round_decimal(round_list, decimal):
"""
Expand Down
40 changes: 21 additions & 19 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
import art

args = helper.seperate_args(sys.argv)
#sys cli inputs
#Defaults. 1 == Show, anything else == hide
# sys cli inputs
# Defaults. 1 == Show, anything else == hide
coordinates = api.get_coordinates(args)
lat = coordinates[0]
long = coordinates[1]
Expand All @@ -31,35 +31,36 @@
"unit": "imperial",
"decimal": helper.extract_decimal(args),
"forecast_days": helper.get_forecast_days(args),
"color": helper.get_color(args)
"color": helper.get_color(args),
}

# Check if specific options are present in args and update ocean dictionary accordingly
if "hide_wave" in args or "hw" in args:
ocean['show_wave'] = 0
ocean["show_wave"] = 0
if "show_large_wave" in args or "slw" in args:
ocean['show_large_wave'] = 1
ocean["show_large_wave"] = 1
if "hide_uv" in args or "huv" in args:
ocean['show_uv'] = 0
ocean["show_uv"] = 0
if "hide_height" in args or "hh" in args:
ocean['show_height'] = 0
ocean["show_height"] = 0
if "hide_direction" in args or "hdir" in args:
ocean['show_direction'] = 0
ocean["show_direction"] = 0
if "hide_period" in args or "hp" in args:
ocean['show_period'] = 0
ocean["show_period"] = 0
if "hide_location" in args or "hl" in args:
ocean['show_city'] = 0
ocean["show_city"] = 0
if "hide_date" in args or "hdate" in args:
ocean['show_date'] = 0
ocean["show_date"] = 0
if "metric" in args or "m" in args:
ocean['unit'] = "metric"
ocean["unit"] = "metric"

# Calls APIs though python files
ocean_data = api.ocean_information(lat, long, ocean['decimal'], ocean['unit'])
uv_index = api.get_uv(lat, long, ocean['decimal'], ocean['unit'])
ocean_data = api.ocean_information(lat, long, ocean["decimal"], ocean["unit"])
uv_index = api.get_uv(lat, long, ocean["decimal"], ocean["unit"])

ocean["ocean_data"] = ocean_data
ocean["uv_index"] = uv_index

ocean['ocean_data'] = ocean_data
ocean['uv_index'] = uv_index

def main():
"""
Expand All @@ -72,11 +73,12 @@ def main():
print(coordinates)
print("No ocean data at this location.")
else:
helper.print_location(ocean['city'], ocean['show_city'])
art.print_wave(ocean['show_wave'], ocean['show_large_wave'], ocean['color'])
helper.print_location(ocean["city"], ocean["show_city"])
art.print_wave(ocean["show_wave"], ocean["show_large_wave"], ocean["color"])
helper.print_output(ocean)
print("\n")
forecast = api.forecast(lat, long, ocean['decimal'], ocean['forecast_days'])
forecast = api.forecast(lat, long, ocean["decimal"], ocean["forecast_days"])
helper.print_forecast(ocean, forecast)


main()
Loading

0 comments on commit b363875

Please sign in to comment.