Skip to content

Commit a88ac2f

Browse files
committed
ruffによる指摘事項修正
1 parent b90df2c commit a88ac2f

16 files changed

Lines changed: 95 additions & 264 deletions

File tree

create_env.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,7 @@
88
def create_table() -> None:
99
"""テーブルを作成する"""
1010

11-
with open(
12-
"postgres/docker-entrypoint-initdb.d/02_init.sql", encoding="UTF-8"
13-
) as init_sql:
11+
with open("postgres/docker-entrypoint-initdb.d/02_init.sql", encoding="UTF-8") as init_sql:
1412
sql = ""
1513
for line in init_sql.readlines():
1614
sql += line

library/chat_gpt.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@ def chat_gpt(message: str) -> Optional[str]:
2121
)
2222
except RateLimitError as e:
2323
if e.code == "insufficient_quota":
24-
return "栄養が足りなくて頭がうまく働かないっぽ......。このコマンドを使いたい場合は飼い主に相談してくれっぽ。"
24+
return (
25+
"栄養が足りなくて頭がうまく働かないっぽ......。このコマンドを使いたい場合は飼い主に相談してくれっぽ。"
26+
)
2527
else:
2628
raise e
2729

library/clientclass.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"""
44
clientに使うclass
55
"""
6+
67
import os
78
from abc import ABCMeta, abstractmethod
89

@@ -64,9 +65,7 @@ def post(self, message):
6465

6566
def upload(self, file, filename):
6667
"""ファイルを投稿する"""
67-
self.client.files_upload_v2(
68-
channel=self.slack_channel, file=file, filename=filename
69-
)
68+
self.client.files_upload_v2(channel=self.slack_channel, file=file, filename=filename)
7069

7170
def get_send_user(self):
7271
"""botを呼び出したユーザーを返す"""
@@ -126,9 +125,7 @@ def post(self, message):
126125

127126
def upload(self, file, filename):
128127
"""ファイルを投稿する"""
129-
self.client.loop.create_task(
130-
self.message.channel.send(file=discord.File(file, filename=filename))
131-
)
128+
self.client.loop.create_task(self.message.channel.send(file=discord.File(file, filename=filename)))
132129

133130
def get_send_user(self):
134131
"""botを呼び出したユーザーを返す"""

library/earthquake.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,7 @@ def generate_map_img(
5252
"""
5353

5454
layers: List[Layer] = [
55-
LineTrace(coords=[get_circle(lat, lng, d * 1000)], color=(100, 100, 100, 255))
56-
for d in range(10, 60, 10)
55+
LineTrace(coords=[get_circle(lat, lng, d * 1000)], color=(100, 100, 100, 255)) for d in range(10, 60, 10)
5756
]
5857
layers.append(
5958
MarkerTrace(

library/geo.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,7 @@ def get_yahoo_geo_data(place: str) -> Optional[Dict[str, str]]:
4242
else:
4343
url = "https://map.yahooapis.jp/geocode/V1/geoCoder"
4444

45-
res = requests.get(
46-
url, {"appid": conf.YAHOO_API_TOKEN, "query": place, "output": "json"}
47-
)
45+
res = requests.get(url, {"appid": conf.YAHOO_API_TOKEN, "query": place, "output": "json"})
4846

4947
if res.status_code != 200:
5048
return None
@@ -80,9 +78,7 @@ def get_gsi_geo_data(place: str) -> Optional[Dict[str, str]]:
8078
"""
8179

8280
place = unicodedata.normalize("NFKC", place)
83-
res = requests.get(
84-
"https://msearch.gsi.go.jp/address-search/AddressSearch", {"q": place}
85-
)
81+
res = requests.get("https://msearch.gsi.go.jp/address-search/AddressSearch", {"q": place})
8682

8783
if res.status_code != 200:
8884
return None
@@ -91,9 +87,7 @@ def get_gsi_geo_data(place: str) -> Optional[Dict[str, str]]:
9187
partial_match_candidates = []
9288

9389
for entry in res.json():
94-
res_place = unicodedata.normalize(
95-
"NFKC", entry.get("properties", {}).get("title", "")
96-
)
90+
res_place = unicodedata.normalize("NFKC", entry.get("properties", {}).get("title", ""))
9791
lon, lat = entry.get("geometry", {}).get("coordinates", [None, None])
9892
if lon is None or lat is None:
9993
continue

library/hatomap.py

Lines changed: 18 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -54,25 +54,13 @@ def from_geocoord(cls, geocoord: GeoCoord, zoom: int) -> WebMercatorPixelCoord:
5454
256 * (1 << zoom) * (geocoord.lng + 180) / 360,
5555
256
5656
* (1 << zoom)
57-
* (
58-
0.5
59-
- math.log(math.tan(math.pi / 4 + geocoord.lat * math.pi / 180 / 2))
60-
/ (2 * math.pi)
61-
),
57+
* (0.5 - math.log(math.tan(math.pi / 4 + geocoord.lat * math.pi / 180 / 2)) / (2 * math.pi)),
6258
zoom,
6359
)
6460

6561
def to_geocoord(self) -> GeoCoord:
6662
lng = (360 * self.pixel_x) / (1 << self.zoom_level * 256) - 180
67-
lat = (
68-
math.asin(
69-
math.tanh(
70-
math.pi * (1 - 2 * self.pixel_y / (1 << self.zoom_level * 256))
71-
)
72-
)
73-
* 180
74-
/ math.pi
75-
)
63+
lat = math.asin(math.tanh(math.pi * (1 - 2 * self.pixel_y / (1 << self.zoom_level * 256)))) * 180 / math.pi
7664
return GeoCoord(lat, lng)
7765

7866
def belongs_tile(self) -> WebMercatorTilePixel:
@@ -103,12 +91,8 @@ def __post_init__(self):
10391

10492
def covered_tiles(self) -> Tuple[WebMercatorTilePixel, WebMercatorTilePixel]:
10593
return (
106-
WebMercatorPixelCoord(
107-
self.pixel_x_west, self.pixel_y_north, self.zoom
108-
).belongs_tile(),
109-
WebMercatorPixelCoord(
110-
self.pixel_x_east, self.pixel_y_south, self.zoom
111-
).belongs_tile(),
94+
WebMercatorPixelCoord(self.pixel_x_west, self.pixel_y_north, self.zoom).belongs_tile(),
95+
WebMercatorPixelCoord(self.pixel_x_east, self.pixel_y_south, self.zoom).belongs_tile(),
11296
)
11397

11498
def geocoord2pixel(self, geocoord: GeoCoord) -> Tuple[int, int]:
@@ -122,17 +106,10 @@ def geocoords2pixel_ndarray(self, geocoords: np.ndarray) -> np.ndarray:
122106
return (
123107
np.array(
124108
[
125-
256 * (1 << self.zoom) * (geocoords[..., 1] + 180) / 360
126-
- self.pixel_x_west,
109+
256 * (1 << self.zoom) * (geocoords[..., 1] + 180) / 360 - self.pixel_x_west,
127110
256
128111
* (1 << self.zoom)
129-
* (
130-
0.5
131-
- np.log(
132-
np.tan(np.pi / 4 + geocoords[..., 0] * np.pi / 180 / 2)
133-
)
134-
/ (2 * np.pi)
135-
)
112+
* (0.5 - np.log(np.tan(np.pi / 4 + geocoords[..., 0] * np.pi / 180 / 2)) / (2 * np.pi))
136113
- self.pixel_y_north,
137114
]
138115
)
@@ -175,11 +152,7 @@ class RasterTileServer:
175152
def _get_image_content(url):
176153
return cv2.imdecode(
177154
np.asarray(
178-
bytearray(
179-
requests.get(
180-
url, headers={"user-agent": f"hato-bot/{VERSION}"}
181-
).content
182-
),
155+
bytearray(requests.get(url, headers={"user-agent": f"hato-bot/{VERSION}"}).content),
183156
dtype=np.uint8,
184157
),
185158
-1,
@@ -191,22 +164,15 @@ def request(self, bbox: WebMercatorPixelBBox) -> np.ndarray:
191164
request_urls = []
192165
for x in range(tl_tilepx.tile.tile_x, rb_tilepx.tile.tile_x + 1):
193166
for y in range(tl_tilepx.tile.tile_y, rb_tilepx.tile.tile_y + 1):
194-
request_urls.append(
195-
string.Template(self.url).safe_substitute(
196-
{"x": x, "y": y, "z": bbox.zoom}
197-
)
198-
)
167+
request_urls.append(string.Template(self.url).safe_substitute({"x": x, "y": y, "z": bbox.zoom}))
199168
with Pool(16) as p:
200169
imgs = list(p.imap(self._get_image_content, request_urls))
201170

202171
tile_width_cnt = rb_tilepx.tile.tile_x + 1 - tl_tilepx.tile.tile_x
203172
tile_height_cnt = rb_tilepx.tile.tile_y + 1 - tl_tilepx.tile.tile_y
204173

205174
concated = np.concatenate(
206-
[
207-
np.concatenate(imgs[i : i + tile_height_cnt], axis=0)
208-
for i in range(0, len(imgs), tile_height_cnt)
209-
],
175+
[np.concatenate(imgs[i : i + tile_height_cnt], axis=0) for i in range(0, len(imgs), tile_height_cnt)],
210176
axis=1,
211177
)
212178

@@ -220,7 +186,6 @@ def request(self, bbox: WebMercatorPixelBBox) -> np.ndarray:
220186

221187
@dataclass
222188
class Layer(metaclass=ABCMeta):
223-
224189
@abstractmethod
225190
def get_image(self, bbox: WebMercatorPixelBBox) -> np.ndarray:
226191
pass
@@ -266,12 +231,7 @@ def get_image(self, bbox: WebMercatorPixelBBox) -> np.ndarray:
266231

267232
px_coords = bbox.geocoords2pixel_ndarray(coords)
268233

269-
symbols = {
270-
"thunder": np.array(
271-
[[1, -3], [-0, -0.5], [2, -0.5], [-1, 3], [0, 0.5], [-2, 0.5]]
272-
)
273-
/ 6
274-
}
234+
symbols = {"thunder": np.array([[1, -3], [-0, -0.5], [2, -0.5], [-1, 3], [0, 0.5], [-2, 0.5]]) / 6}
275235
if self.symbol == "circle":
276236
for c in px_coords:
277237
print(c)
@@ -316,8 +276,7 @@ def get_image(self, bbox: WebMercatorPixelBBox) -> np.ndarray:
316276
elif self.symbol in symbols.keys():
317277
symbol_coords = symbols[self.symbol]
318278
px_coords = (
319-
np.repeat(px_coords[:, np.newaxis, :], symbol_coords.shape[0], axis=1)
320-
+ symbol_coords * self.size
279+
np.repeat(px_coords[:, np.newaxis, :], symbol_coords.shape[0], axis=1) + symbol_coords * self.size
321280
)
322281
px_coords = px_coords.astype(np.int32)
323282
for c in px_coords:
@@ -364,14 +323,10 @@ def get_image(self, bbox: WebMercatorPixelBBox) -> np.ndarray:
364323
layer_img = np.array(RasterTileServer(url).request(bbox), dtype=np.float32)
365324

366325
if self.brightness != 1.0 or self.chroma != 1.0:
367-
img_hsv = np.array(
368-
cv2.cvtColor(layer_img, cv2.COLOR_BGR2HSV), dtype=np.float32
369-
)
326+
img_hsv = np.array(cv2.cvtColor(layer_img, cv2.COLOR_BGR2HSV), dtype=np.float32)
370327
img_hsv[..., 1] = img_hsv[..., 1] * self.brightness
371328
img_hsv[..., 2] = img_hsv[..., 2] * self.chroma
372-
layer_img = np.array(
373-
cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR), dtype=np.float32
374-
)
329+
layer_img = np.array(cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR), dtype=np.float32)
375330

376331
if self.opacity != 1.0:
377332
layer_img[layer_img[..., 3] != 0, 3] = int(round(self.opacity * 256))
@@ -409,9 +364,7 @@ class HatoMap:
409364
layers: Optional[List[Layer]] = None
410365
title: Optional[str] = None
411366

412-
def update_layout(
413-
self, mapbox: Optional[MapBox] = None, layers: Optional[List[Layer]] = None
414-
) -> None:
367+
def update_layout(self, mapbox: Optional[MapBox] = None, layers: Optional[List[Layer]] = None) -> None:
415368
if mapbox is not None:
416369
self.mapbox = mapbox
417370
if layers is not None:
@@ -475,9 +428,9 @@ def get_image(self, height: int, width: int) -> np.ndarray:
475428
if body_img.shape == none_body_img_shape:
476429
body_img = layer_img[..., :3]
477430
else:
478-
body_img = body_img[..., :3] * (
479-
1 - layer_img[..., 3:] / 255
480-
) + layer_img[..., :3] * (layer_img[..., 3:] / 255)
431+
body_img = body_img[..., :3] * (1 - layer_img[..., 3:] / 255) + layer_img[..., :3] * (
432+
layer_img[..., 3:] / 255
433+
)
481434

482435
img = np.zeros((height, width, 3), np.uint8)
483436
img.fill(255)
@@ -501,9 +454,7 @@ def get_circle(lat: float, lng: float, radius: float) -> np.ndarray:
501454
earth_e_sq = (2 * earth_f - 1) / earth_f**2
502455
c = 1 - (earth_e_sq * math.sin(lat) ** 2)
503456
meter_1deg_lat = math.pi * earth_radius * (1 - earth_e_sq) / (180 * c**1.5)
504-
meter_1deg_lng = (
505-
math.pi * earth_radius * math.cos(lat * math.pi / 180) / (180 * math.sqrt(c))
506-
)
457+
meter_1deg_lng = math.pi * earth_radius * math.cos(lat * math.pi / 180) / (180 * math.sqrt(c))
507458
lats = np.sin(np.radians(np.arange(0, 361, 1))) * radius / meter_1deg_lat + lat
508459
lngs = np.cos(np.radians(np.arange(0, 361, 1))) * radius / meter_1deg_lng + lng
509460
return np.array([lats, lngs]).T

library/jma_amedas.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,7 @@ class Place:
1515

1616
def get_jma_amedas(lat: float, lon: float) -> Optional[Dict]:
1717
nearest_place: Optional[Place] = None
18-
place_res = requests.get(
19-
"https://www.jma.go.jp/bosai/amedas/const/amedastable.json"
20-
)
18+
place_res = requests.get("https://www.jma.go.jp/bosai/amedas/const/amedastable.json")
2119

2220
if place_res.status_code != 200:
2321
return None
@@ -32,17 +30,13 @@ def get_jma_amedas(lat: float, lon: float) -> Optional[Dict]:
3230
if nearest_place is None:
3331
return None
3432

35-
latest_datetime_res = requests.get(
36-
"https://www.jma.go.jp/bosai/amedas/data/latest_time.txt"
37-
)
33+
latest_datetime_res = requests.get("https://www.jma.go.jp/bosai/amedas/data/latest_time.txt")
3834

3935
if latest_datetime_res.status_code != 200:
4036
return None
4137

4238
latest_datetime = datetime.datetime.fromisoformat(latest_datetime_res.text)
43-
amedas_url = latest_datetime.strftime(
44-
"https://www.jma.go.jp/bosai/amedas/data/map/%Y%m%d%H%M%S.json"
45-
)
39+
amedas_url = latest_datetime.strftime("https://www.jma.go.jp/bosai/amedas/data/map/%Y%m%d%H%M%S.json")
4640
amedas_res = requests.get(amedas_url)
4741

4842
if amedas_res.status_code != 200:

library/jma_amesh.py

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
"""
44
jma_amesh
55
"""
6+
67
import datetime
78
import json
89
from dataclasses import dataclass
@@ -60,13 +61,7 @@ def get_latest_timestamps() -> dict:
6061
[
6162
(
6263
e,
63-
max(
64-
[
65-
i.basetime
66-
for i in timejson
67-
if i.basetime == i.validtime and e in i.elements
68-
]
69-
),
64+
max([i.basetime for i in timejson if i.basetime == i.validtime and e in i.elements]),
7065
)
7166
for e in elements
7267
]
@@ -90,7 +85,9 @@ def get_jma_image_server(timestamp: str) -> str:
9085

9186
def get_liden(timestamp: str) -> List[Tuple[float, float, int]]:
9287
"""気象庁落雷JSONを取得する"""
93-
liden_json_url = f"https://www.jma.go.jp/bosai/jmatile/data/nowc/{timestamp}/none/{timestamp}/surf/liden/data.geojson" # noqa: E501
88+
liden_json_url = (
89+
f"https://www.jma.go.jp/bosai/jmatile/data/nowc/{timestamp}/none/{timestamp}/surf/liden/data.geojson" # noqa: E501
90+
)
9491
response = requests.get(liden_json_url)
9592

9693
if response.status_code == 200:
@@ -105,23 +102,16 @@ def get_liden(timestamp: str) -> List[Tuple[float, float, int]]:
105102
return [(0.0, 0.0, 0)]
106103

107104

108-
def jma_amesh(
109-
lat: float, lng: float, zoom: int, around_tiles: int
110-
) -> Optional[Image.Image]:
105+
def jma_amesh(lat: float, lng: float, zoom: int, around_tiles: int) -> Optional[Image.Image]:
111106
"""
112107
気象庁雨雲レーダーとOpenStreetMap画像を取得して結合する
113108
Usage: jma_amesh(lat=37, lng=139, zoom=8, around_tiles=2).save('res2.png')
114109
"""
115110

116111
jma_timestamp = get_latest_timestamps()
117-
layers: List[Layer] = [
118-
RasterLayer(
119-
url=get_jma_image_server(jma_timestamp["hrpns_nd"]), opacity=128 / 256
120-
)
121-
]
112+
layers: List[Layer] = [RasterLayer(url=get_jma_image_server(jma_timestamp["hrpns_nd"]), opacity=128 / 256)]
122113
layers += [
123-
LineTrace(coords=[get_circle(lat, lng, d * 1000)], color=(100, 100, 100, 255))
124-
for d in range(10, 60, 10)
114+
LineTrace(coords=[get_circle(lat, lng, d * 1000)], color=(100, 100, 100, 255)) for d in range(10, 60, 10)
125115
]
126116
layers.append(
127117
MarkerTrace(
@@ -134,7 +124,7 @@ def jma_amesh(
134124
)
135125
h = HatoMap(
136126
basemap="open-street-map-dim",
137-
title=f'雨雲:{timestamp2jst(jma_timestamp["hrpns_nd"])} 雷:{timestamp2jst(jma_timestamp["liden"])}',
127+
title=f"雨雲:{timestamp2jst(jma_timestamp['hrpns_nd'])} 雷:{timestamp2jst(jma_timestamp['liden'])}",
138128
mapbox=MapBox(center=GeoCoord(lat, lng), zoom=zoom),
139129
layers=layers,
140130
)

0 commit comments

Comments
 (0)