Skip to content

Commit 7b34f7a

Browse files
committed
some code cleanup
1 parent 9ae59ab commit 7b34f7a

12 files changed

+77
-102
lines changed

src/Models.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
# Models for All weather data data
2-
import time
3-
42

53
class CurrentWeather:
64
total_instances = 0

src/__init__.py

Whitespace-only changes.

src/backendAirPollution.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def current_air_pollution(latitude: float, longitude: float, **kwargs):
2121
except requests.exceptions.RequestException as e:
2222
print(f"Error: {e}")
2323

24-
def _get_current_air_pollution(self,lat,lon):
24+
def _get_current_air_pollution(self, lat, lon):
2525
current_args = [
2626
"european_aqi",
2727
"us_aqi",

src/backendWeather.py

Lines changed: 48 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,48 +1,48 @@
1-
from typing import List
21
import requests
32
import datetime
43

54
from gi.repository import Gio
65

76

8-
97
base_url = "https://api.open-meteo.com/v1/forecast"
108

11-
class Weather():
9+
10+
class Weather:
1211
"""
1312
See Documentation at: https://open-meteo.com/en/docs
1413
"""
14+
1515
def __init__(self) -> None:
16-
global settings,measurement_type,temperature_unit,wind_speed_unit
16+
global settings, measurement_type, temperature_unit, wind_speed_unit
1717
settings = Gio.Settings(schema_id="io.github.amit9838.weather")
18-
measurement_type = settings.get_string('measure-type')
18+
measurement_type = settings.get_string("measure-type")
1919
if measurement_type == "imperial":
2020
temperature_unit = "fahrenheit"
2121
wind_speed_unit = "mph"
22+
2223
# Current Weather =============================================
2324
@staticmethod
2425
def current_weather(latitude: float, longitude: float, **kwargs):
25-
2626
url = base_url + f"?latitude={latitude}&longitude={longitude}"
2727

2828
# Check for kwargs keyword parameters
29-
if 'current' in kwargs:
30-
current_fields = ",".join(kwargs.get('current'))
31-
url = url+f"&current={current_fields}"
32-
29+
if "current" in kwargs:
30+
current_fields = ",".join(kwargs.get("current"))
31+
url = url + f"&current={current_fields}"
32+
3333
if measurement_type == "imperial":
3434
url += f"&temperature_unit={temperature_unit}&wind_speed_unit={wind_speed_unit}"
3535

3636
try:
37-
url = url+f"&timeformat=unixtime"
37+
url = url + f"&timeformat=unixtime"
3838
response = requests.get(url)
3939
response.raise_for_status() # Raise an exception if the request was unsuccessful
4040
data = response.json()
4141
return data
4242
except requests.exceptions.RequestException as e:
4343
print(f"Error: {e}")
4444

45-
def _get_current_weather(self,lat,lon):
45+
def _get_current_weather(self, lat, lon):
4646
current_args = [
4747
"temperature_2m",
4848
"relativehumidity_2m",
@@ -53,85 +53,83 @@ def _get_current_weather(self,lat,lon):
5353
"weathercode",
5454
"surface_pressure",
5555
"windspeed_10m",
56-
"winddirection_10m"
56+
"winddirection_10m",
5757
]
58-
return self.current_weather(lat,lon,current = current_args)
59-
58+
return self.current_weather(lat, lon, current=current_args)
6059

6160
# Hourly Forecast ==============================================
6261
@staticmethod
6362
def forecast_hourly(latitude: float, longitude: float, **kwargs):
64-
6563
url = base_url + f"?latitude={latitude}&longitude={longitude}"
6664

6765
# Check for kwargs keyword parameters
68-
if 'hourly' in kwargs:
69-
hourly_fields = ",".join(kwargs.get('hourly'))
70-
url = url+f"&hourly={hourly_fields}"
71-
66+
if "hourly" in kwargs:
67+
hourly_fields = ",".join(kwargs.get("hourly"))
68+
url = url + f"&hourly={hourly_fields}"
69+
7270
if measurement_type == "imperial":
7371
url += f"&temperature_unit={temperature_unit}&wind_speed_unit={wind_speed_unit}"
7472

7573
try:
76-
url = url+f"&timeformat=unixtime"
74+
url = url + f"&timeformat=unixtime"
7775
response = requests.get(url)
7876
response.raise_for_status() # Raise an exception if the request was unsuccessful
7977
data = response.json()
8078
return data
8179
except requests.exceptions.RequestException as e:
8280
print(f"Error: {e}")
8381

84-
85-
def _get_hourly_forecast(self,lat,lon):
82+
def _get_hourly_forecast(self, lat, lon):
8683
hourly_args = [
87-
'temperature_2m',
88-
'relativehumidity_2m',
89-
'dewpoint_2m',
90-
'apparent_temperature',
91-
'weathercode',
92-
'precipitation',
93-
'surface_pressure',
94-
'visibility',
95-
'windspeed_10m',
96-
'wind_direction_10m',
97-
'uv_index',
98-
'is_day'
84+
"temperature_2m",
85+
"relativehumidity_2m",
86+
"dewpoint_2m",
87+
"apparent_temperature",
88+
"weathercode",
89+
"precipitation",
90+
"surface_pressure",
91+
"visibility",
92+
"windspeed_10m",
93+
"wind_direction_10m",
94+
"uv_index",
95+
"is_day",
9996
]
10097

10198
today = datetime.datetime.today().date()
102-
tomorrow = today+datetime.timedelta(days=1)
103-
return self.forecast_hourly(lat, lon,hourly=hourly_args,start_date=today,end_date=tomorrow)
104-
99+
tomorrow = today + datetime.timedelta(days=1)
100+
return self.forecast_hourly(
101+
lat, lon, hourly=hourly_args, start_date=today, end_date=tomorrow
102+
)
105103

106104
# Forecast daily ====================================================
107105
@staticmethod
108106
def forecast_daily(latitude: float, longitude: float, **kwargs):
109107
url = base_url + f"?latitude={latitude}&longitude={longitude}"
110-
if 'daily' in kwargs:
111-
hourly_fields = ",".join(kwargs.get('daily'))
112-
url = url+f"&daily={hourly_fields}"
108+
if "daily" in kwargs:
109+
hourly_fields = ",".join(kwargs.get("daily"))
110+
url = url + f"&daily={hourly_fields}"
113111

114-
if 'timezone' in kwargs:
115-
url = url+f"&timezone={kwargs.get('timezone')}"
116-
if 'start_date' in kwargs:
117-
url = url+f"&start_date={kwargs.get('start_date')}"
112+
if "timezone" in kwargs:
113+
url = url + f"&timezone={kwargs.get('timezone')}"
114+
if "start_date" in kwargs:
115+
url = url + f"&start_date={kwargs.get('start_date')}"
118116

119-
if 'end_date' in kwargs:
120-
url = url+f"&end_date={kwargs.get('end_date')}"
117+
if "end_date" in kwargs:
118+
url = url + f"&end_date={kwargs.get('end_date')}"
121119

122120
if measurement_type == "imperial":
123121
url += f"&temperature_unit={temperature_unit}&wind_speed_unit={wind_speed_unit}"
124122

125123
try:
126-
url = url+f"&timeformat=unixtime"
124+
url = url + f"&timeformat=unixtime"
127125
response = requests.get(url)
128126
response.raise_for_status() # Raise an exception if the request was unsuccessful
129127
data = response.json()
130128
return data
131129
except requests.exceptions.RequestException as e:
132130
print(f"Error: {e}")
133131

134-
def _get_daily_forecast(self,lat,lon):
132+
def _get_daily_forecast(self, lat, lon):
135133
daily_args = [
136134
"weathercode",
137135
"temperature_2m_max",
@@ -143,4 +141,4 @@ def _get_daily_forecast(self,lat,lon):
143141
"windspeed_10m_max",
144142
]
145143

146-
return self.forecast_daily(lat,lon,daily=daily_args,timezone="GMT")
144+
return self.forecast_daily(lat, lon, daily=daily_args, timezone="GMT")

src/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# main.py
22
#
3-
# Copyright 2023 Amit
3+
# Copyright 2024 Amit
44
#
55
# This program is free software: you can redistribute it and/or modify
66
# it under the terms of the GNU General Public License as published by

src/meson.build

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ configure_file(
2828

2929

3030
weather_sources = [
31-
'__init__.py',
3231
'main.py',
3332
'weather.py',
3433
'weatherData.py',

src/units.py

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,3 @@
33
def get_measurement_type():
44
settings = Gio.Settings.new("io.github.amit9838.weather")
55
return settings.get_string("measure-type")
6-
7-
# Units and measurements
8-
measurements = {
9-
"metric":{"temp_unit":"°C",
10-
"speed_unit":'km/h',"speed_mul":3.6, # convert speed from m/s to km/h
11-
"dist_unit":'km',"dist_mul":0.001
12-
},
13-
"imperial":{"temp_unit":"°F",
14-
"speed_unit":'mph',"speed_mul":1, #speed miles/hr
15-
"dist_unit":'miles',"dist_mul":0.0006213712,
16-
}
17-
}

src/utils.py

Lines changed: 22 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,12 @@
22
import socket
33
import json
44
from datetime import datetime, timedelta, timezone
5-
from gi.repository import Adw,Gio
5+
from gi.repository import Adw, Gio
66

77
current_weather_data = None
88
air_pollution_data = None
99
forecast_weather_data = None
1010

11-
def get_weather_data():
12-
return current_weather_data,air_pollution_data,forecast_weather_data
13-
14-
def set_weather_data(current,air_pollution,forecast):
15-
global current_weather_data, air_pollution_data,forecast_weather_data
16-
current_weather_data = current
17-
air_pollution_data = air_pollution
18-
forecast_weather_data = forecast
1911

2012
def check_internet_connection():
2113
has_active_internet = False
@@ -26,21 +18,26 @@ def check_internet_connection():
2618
except OSError:
2719
return has_active_internet
2820

21+
2922
def get_selected_city_coords():
3023
settings = Gio.Settings.new("io.github.amit9838.weather")
31-
selected_city = int(str(settings.get_value('selected-city')))
32-
added_cities = list(settings.get_value('added-cities'))
33-
city_loc = added_cities[selected_city].split(',')
34-
return city_loc[-2],city_loc[-1] #latitude,longitude
24+
selected_city = int(str(settings.get_value("selected-city")))
25+
added_cities = list(settings.get_value("added-cities"))
26+
city_loc = added_cities[selected_city].split(",")
27+
return city_loc[-2], city_loc[-1] # latitude,longitude
28+
3529

36-
def create_toast(text,priority=0):
30+
def create_toast(text, priority=0):
3731
toast = Adw.Toast.new(text)
3832
toast.set_priority(Adw.ToastPriority(priority))
3933
return toast
4034

35+
4136
def convert_to_local_time(timestamp, timezone_stamp):
42-
hour_offset_from_utc = (timezone_stamp)/3600
43-
return datetime.fromtimestamp(timestamp,tz=timezone.utc) + timedelta(hours=hour_offset_from_utc)
37+
hour_offset_from_utc = (timezone_stamp) / 3600
38+
return datetime.fromtimestamp(timestamp, tz=timezone.utc) + timedelta(
39+
hours=hour_offset_from_utc
40+
)
4441

4542

4643
def get_cords():
@@ -60,28 +57,28 @@ def get_my_tz_offset_from_utc():
6057
return f"Error: {str(e)}"
6158

6259

63-
def get_tz_offset_by_cord(lat,lon):
60+
def get_tz_offset_by_cord(lat, lon):
6461
url = f"https://api.geotimezone.com/public/timezone?latitude={lat}&longitude={lon}"
6562

6663
res = requests.get(url)
6764
if res.status_code != 200:
6865
return 0
69-
66+
7067
res = json.loads(res.text)
7168
if res.get("offset") is None:
7269
return 0
73-
70+
7471
offset_arr = res.get("offset")[3:].split(":")
7572
offset_arr = [int(x) for x in offset_arr]
76-
epoch_hr = abs(offset_arr[0])*3600
73+
epoch_hr = abs(offset_arr[0]) * 3600
7774
epoch_s = 0
78-
75+
7976
if len(offset_arr) > 1:
80-
epoch_s = offset_arr[1]*60
81-
82-
epoch_offset = epoch_hr+epoch_s
77+
epoch_s = offset_arr[1] * 60
78+
79+
epoch_offset = epoch_hr + epoch_s
8380

8481
if offset_arr[0] < 0:
8582
epoch_offset *= -1
86-
83+
8784
return epoch_offset

src/weather.in

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
# weather.in
44
#
5-
# Copyright 2023 Amit
5+
# Copyright 2024 Amit
66
#
77
# This program is free software: you can redistribute it and/or modify
88
# it under the terms of the GNU General Public License as published by

src/weather.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
gi.require_version("Gtk", "4.0")
66
gi.require_version("Adw", "1")
7-
from gi.repository import Gtk, Adw, Gio, GLib
7+
from gi.repository import Gtk, Adw, Gio
88

99
# module import
1010
from .utils import create_toast,check_internet_connection
@@ -123,8 +123,6 @@ def show_loader(self):
123123
container_loader.append(loader_label)
124124

125125
loader.start()
126-
# loader = Gtk.Label(label=f"Loading…")
127-
# loader.set_css_classes(["text-1", "bold-2"])
128126
loader.set_hexpand(True)
129127
loader.set_vexpand(True)
130128
self.main_stack.add_named(container_loader, "loader")
@@ -211,8 +209,6 @@ def get_weather(self,reload_type=None,title = ""):
211209
self.settings.reset('added-cities')
212210
self.settings.reset('selected-city')
213211

214-
215-
216212
child = self.main_stack.get_child_by_name('main_grid')
217213
if child is not None:
218214
self.main_stack.remove(child)
@@ -317,7 +313,6 @@ def _refresh_weather(self,widget):
317313
thread.start()
318314

319315

320-
321316
# ============= Menu buttom methods ==============
322317
def _on_about_clicked(self, *args, **kwargs ):
323318
AboutWindow(application)

src/windowAbout.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
def AboutWindow(parent,*args):
77
dialog = Adw.AboutWindow.new()
8-
dialog.set_application_name(_("Weather"))
8+
dialog.set_application_name("Weather")
99
dialog.set_application_icon("io.github.amit9838.weather")
1010
dialog.set_version("1.0.1")
1111
dialog.set_developer_name("Amit Chaudhary")
@@ -14,7 +14,7 @@ def AboutWindow(parent,*args):
1414
dialog.set_website("https://amit9838.github.io/weather/")
1515
dialog.set_issue_url("https://github.com/amit9838/weather/issues")
1616
# dialog.add_credit_section("Contributors", ["name url"])
17-
dialog.set_copyright(_("Copyright © 2023 Weather Developers"))
17+
dialog.set_copyright(_("Copyright © 2024 Weather Developers"))
1818
dialog.set_developers(["Amit Chaudhary"])
1919
# Translators: Please enter your credits here. (format: "Name https://example.com" or "Name <email@example.com>", no quotes)
2020
dialog.set_translator_credits(_("translator_credits"))

0 commit comments

Comments
 (0)