Skip to content

Commit 0456f32

Browse files
authored
Merge pull request #192 from andrewm4894/precommit-improve
Precommit improve
2 parents 5718065 + af67b58 commit 0456f32

File tree

105 files changed

+2382
-2371
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

105 files changed

+2382
-2371
lines changed

.pre-commit-config.yaml

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,20 +14,10 @@ repos:
1414
# args: ["--branch", "main"]
1515
- id: trailing-whitespace
1616
args: ["--markdown-linebreak-ext=md"]
17-
- repo: https://github.com/pycqa/isort
18-
rev: 5.12.0
19-
hooks:
20-
- id: isort
21-
args:
22-
- "--profile"
23-
- "black"
24-
- repo: https://github.com/charliermarsh/ruff-pre-commit
25-
rev: v0.0.241
17+
# isort removed - ruff handles import sorting now
18+
- repo: https://github.com/astral-sh/ruff-pre-commit
19+
rev: v0.8.4
2620
hooks:
2721
- id: ruff
28-
args:
29-
- "--fix"
30-
- "--exclude"
31-
- "metrics/defaults/python/prompt.py"
32-
- "--exclude"
33-
- "anomstack/llm/completion.py"
22+
args: ["--fix"]
23+
- id: ruff-format

anomstack/alerts/asciiart.py

Lines changed: 19 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -91,9 +91,7 @@ def __init__(
9191
else:
9292
self.graphsymbol = graphsymbol
9393
if self._len_noansi(self.graphsymbol) != 1:
94-
raise Exception(
95-
"Bad graphsymbol length, must be 1", self._len_noansi(self.graphsymbol)
96-
)
94+
raise Exception("Bad graphsymbol length, must be 1", self._len_noansi(self.graphsymbol))
9795
self.multivalue = multivalue
9896
self.hsymbols = [
9997
self._u(""),
@@ -181,9 +179,7 @@ def _get_thresholds(self, data):
181179
if self.multivalue:
182180
totalvalue_len += len("," + self._trans_hr(ivalue))
183181
else:
184-
totalvalue_len = max(
185-
totalvalue_len, len(self._trans_hr(ivalue))
186-
)
182+
totalvalue_len = max(totalvalue_len, len(self._trans_hr(ivalue)))
187183

188184
if self.multivalue:
189185
# remove one comma if multivalues
@@ -214,17 +210,13 @@ def _gen_graph_string(
214210
):
215211
"""Generate the bar + its paddings (left and right)"""
216212

217-
def _gen_graph_string_part(
218-
value, max_value, min_neg_value, graph_length, color
219-
):
213+
def _gen_graph_string_part(value, max_value, min_neg_value, graph_length, color):
220214
all_width = max_value + abs(min_neg_value)
221215

222216
if all_width == 0:
223217
bar_width = 0
224218
else:
225-
bar_width = int(
226-
abs(float(value)) * float(graph_length) / float(all_width)
227-
)
219+
bar_width = int(abs(float(value)) * float(graph_length) / float(all_width))
228220

229221
return (
230222
Pyasciigraph._color_string(self.graphsymbol * bar_width, color),
@@ -236,9 +228,7 @@ def _gen_graph_string_part(
236228
if all_width == 0:
237229
neg_width = 0
238230
else:
239-
neg_width = int(
240-
abs(float(min_neg_value)) * float(graph_length) / float(all_width)
241-
)
231+
neg_width = int(abs(float(min_neg_value)) * float(graph_length) / float(all_width))
242232
int(abs(max_value) * graph_length / all_width)
243233

244234
if isinstance(value, Iterable):
@@ -264,9 +254,7 @@ def _gen_graph_string_part(
264254
accuvalue += scaled_value
265255

266256
# left padding
267-
totalstring = (
268-
Pyasciigraph._u(" ") * (neg_width - abs(totalsquares)) + totalstring
269-
)
257+
totalstring = Pyasciigraph._u(" ") * (neg_width - abs(totalsquares)) + totalstring
270258

271259
# reset some counters
272260
accuvalue = 0
@@ -285,9 +273,7 @@ def _gen_graph_string_part(
285273
accuvalue += scaled_value
286274

287275
# right padding
288-
totalstring += Pyasciigraph._u(" ") * (
289-
start_value_pos - neg_width - abs(totalsquares)
290-
)
276+
totalstring += Pyasciigraph._u(" ") * (start_value_pos - neg_width - abs(totalsquares))
291277
return totalstring
292278
else:
293279
# handling for single value item
@@ -312,9 +298,7 @@ def _gen_info_string(self, info, start_info_pos, line_length):
312298
number_of_space = line_length - start_info_pos - self._len_noansi(info)
313299
return info + Pyasciigraph._u(" ") * number_of_space
314300

315-
def _gen_value_string(
316-
self, value, min_neg_value, color, start_value_pos, start_info_pos
317-
):
301+
def _gen_value_string(self, value, min_neg_value, color, start_value_pos, start_info_pos):
318302
"""Generate the value string + padding"""
319303
icount = 0
320304
if isinstance(value, Iterable) and self.multivalue:
@@ -324,14 +308,10 @@ def _gen_value_string(
324308
# with the len() function even when they are not printed to
325309
# the screen.
326310
totalvalue_len = len(self._trans_hr(ivalue))
327-
totalvalue = Pyasciigraph._color_string(
328-
self._trans_hr(ivalue), icolor
329-
)
311+
totalvalue = Pyasciigraph._color_string(self._trans_hr(ivalue), icolor)
330312
else:
331313
totalvalue_len += len("," + self._trans_hr(ivalue))
332-
totalvalue += "," + Pyasciigraph._color_string(
333-
self._trans_hr(ivalue), icolor
334-
)
314+
totalvalue += "," + Pyasciigraph._color_string(self._trans_hr(ivalue), icolor)
335315
icount += 1
336316
elif isinstance(value, Iterable):
337317
max_value = min_neg_value
@@ -347,9 +327,7 @@ def _gen_value_string(
347327
totalvalue_len = len(self._trans_hr(value))
348328
totalvalue = Pyasciigraph._color_string(self._trans_hr(value), color)
349329

350-
number_space = (
351-
start_info_pos - start_value_pos - totalvalue_len - self.separator_length
352-
)
330+
number_space = start_info_pos - start_value_pos - totalvalue_len - self.separator_length
353331

354332
# This must not be negitive, this happens when the string length is
355333
# larger than the separator length
@@ -457,18 +435,14 @@ def graph(self, label=None, data=[]):
457435
# calcul of where to start info
458436
start_info_pos = self.line_length - all_thre["info_max_length"]
459437
# calcul of where to start value
460-
start_value_pos = (
461-
start_info_pos - self.separator_length - all_thre["value_max_length"]
462-
)
438+
start_value_pos = start_info_pos - self.separator_length - all_thre["value_max_length"]
463439
# calcul of where to end graph
464440
graph_length = start_value_pos - self.separator_length
465441
else:
466442
# calcul of where to start value
467443
start_value_pos = self.min_graph_length + self.separator_length
468444
# calcul of where to start info
469-
start_info_pos = (
470-
start_value_pos + all_thre["value_max_length"] + self.separator_length
471-
)
445+
start_info_pos = start_value_pos + all_thre["value_max_length"] + self.separator_length
472446
# calcul of where to end graph
473447
graph_length = start_value_pos - self.separator_length
474448
# calcul of the real line length
@@ -514,32 +488,18 @@ def make_alert_message(
514488
score_col="metric_score_smooth",
515489
ascii_graph=False,
516490
):
517-
df_alert_metric = df_alert_metric.sort_values(
518-
by="metric_timestamp", ascending=False
519-
).dropna()
520-
df_alert_metric["metric_timestamp"] = pd.to_datetime(
521-
df_alert_metric["metric_timestamp"]
522-
)
491+
df_alert_metric = df_alert_metric.sort_values(by="metric_timestamp", ascending=False).dropna()
492+
df_alert_metric["metric_timestamp"] = pd.to_datetime(df_alert_metric["metric_timestamp"])
523493
x = df_alert_metric["metric_value"].round(2).values.tolist()
524494
metric_name = df_alert_metric["metric_name"].unique()[0]
525-
metric_timestamp_from = (
526-
df_alert_metric["metric_timestamp"].min().strftime("%Y-%m-%d %H:%M")
527-
)
528-
metric_timestamp_to = (
529-
df_alert_metric["metric_timestamp"].max().strftime("%Y-%m-%d %H:%M")
530-
)
495+
metric_timestamp_from = df_alert_metric["metric_timestamp"].min().strftime("%Y-%m-%d %H:%M")
496+
metric_timestamp_to = df_alert_metric["metric_timestamp"].max().strftime("%Y-%m-%d %H:%M")
531497
graph_title = f"{metric_name} ({metric_timestamp_from} to {metric_timestamp_to})"
532498
message = ""
533499
if ascii_graph:
534500
labels = (
535-
np.where(
536-
df_alert_metric["metric_alert"] == 1,
537-
anomaly_symbol,
538-
normal_symbol
539-
)
540-
+ (df_alert_metric[score_col].round(2) * 100)
541-
.astype("int")
542-
.astype("str")
501+
np.where(df_alert_metric["metric_alert"] == 1, anomaly_symbol, normal_symbol)
502+
+ (df_alert_metric[score_col].round(2) * 100).astype("int").astype("str")
543503
+ "% "
544504
)
545505
data = zip(labels, x)

anomstack/alerts/email.py

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@
22
Helper functions for sending alerts via email.
33
"""
44

5-
import os
6-
import smtplib
7-
import ssl
8-
import tempfile
95
from email import encoders
106
from email.mime.base import MIMEBase
117
from email.mime.multipart import MIMEMultipart
128
from email.mime.text import MIMEText
9+
import os
10+
import smtplib
11+
import ssl
12+
import tempfile
1313

1414
from dagster import get_dagster_logger
1515

@@ -55,12 +55,8 @@ def send_email_with_plot(
5555
host = os.getenv("ANOMSTACK_ALERT_EMAIL_SMTP_HOST")
5656
port = os.getenv("ANOMSTACK_ALERT_EMAIL_SMTP_PORT")
5757

58-
with tempfile.NamedTemporaryFile(
59-
prefix=attachment_name, suffix=".png", delete=False
60-
) as temp:
61-
fig = make_alert_plot(
62-
df, metric_name, threshold, score_col, score_title, tags=tags
63-
)
58+
with tempfile.NamedTemporaryFile(prefix=attachment_name, suffix=".png", delete=False) as temp:
59+
fig = make_alert_plot(df, metric_name, threshold, score_col, score_title, tags=tags)
6460
fig.savefig(temp.name)
6561

6662
msg = MIMEMultipart()
@@ -70,14 +66,10 @@ def send_email_with_plot(
7066

7167
msg.attach(MIMEText(body, "html"))
7268
binary_file = open(temp.name, "rb")
73-
payload = MIMEBase(
74-
"application", "octate-stream", Name=f"{attachment_name}.png"
75-
)
69+
payload = MIMEBase("application", "octate-stream", Name=f"{attachment_name}.png")
7670
payload.set_payload((binary_file).read())
7771
encoders.encode_base64(payload)
78-
payload.add_header(
79-
"Content-Decomposition", "attachment", filename=f"{attachment_name}.png"
80-
)
72+
payload.add_header("Content-Decomposition", "attachment", filename=f"{attachment_name}.png")
8173
msg.attach(payload)
8274

8375
context = ssl.create_default_context()
@@ -126,7 +118,7 @@ def send_email(
126118
with smtplib.SMTP(host, port) as server:
127119
server.connect(host, port)
128120
server.starttls(context=context)
129-
server.login(sender, password) # type: ignore
121+
server.login(sender, password) # type: ignore
130122
text = msg.as_string()
131123
server.sendmail(sender, to, text)
132124
server.quit()

anomstack/alerts/send.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22
Helper functions to send alerts.
33
"""
44

5-
import pandas as pd
65
from dagster import get_dagster_logger
6+
import pandas as pd
77

88
from anomstack.alerts.asciiart import make_alert_message
99
from anomstack.alerts.email import send_email, send_email_with_plot
@@ -46,9 +46,7 @@ def send_alert(
4646
"""
4747
logger = get_dagster_logger()
4848
logger.debug(f"alerts to send: \n{df}")
49-
message = make_alert_message(
50-
df, description=description, tags=tags, score_col=score_col
51-
)
49+
message = make_alert_message(df, description=description, tags=tags, score_col=score_col)
5250
if "slack" in alert_methods:
5351
send_alert_slack_with_plot(
5452
df=df,

anomstack/alerts/slack.py

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,8 @@
4141
import os
4242
import tempfile
4343

44-
import matplotlib.pyplot as plt
4544
from dagster import get_dagster_logger
45+
import matplotlib.pyplot as plt
4646
from slack_sdk import WebClient
4747
from slack_sdk.errors import SlackApiError
4848

@@ -73,10 +73,7 @@ def send_alert_slack(
7373
slack_token = os.environ.get("ANOMSTACK_SLACK_BOT_TOKEN")
7474
if not slack_token:
7575
raise ValueError(
76-
(
77-
"Slack bot token not found in environment variable "
78-
"ANOMSTACK_SLACK_BOT_TOKEN"
79-
)
76+
("Slack bot token not found in environment variable " "ANOMSTACK_SLACK_BOT_TOKEN")
8077
)
8178

8279
client = WebClient(token=slack_token)
@@ -119,9 +116,7 @@ def send_alert_slack(
119116
filename=os.path.basename(image_file_path),
120117
)
121118
else:
122-
response = client.chat_postMessage(
123-
channel=channel_id, text=f"*{title}*\n{message}"
124-
)
119+
response = client.chat_postMessage(channel=channel_id, text=f"*{title}*\n{message}")
125120
except SlackApiError as e:
126121
logger.error(f"Error sending message to Slack channel {channel_name, channel_id}: {e}")
127122

@@ -146,13 +141,9 @@ def send_alert_slack_with_plot(
146141
channel_name = os.environ.get("ANOMSTACK_SLACK_CHANNEL")
147142

148143
with tempfile.NamedTemporaryFile(
149-
prefix=f"{metric_name}_{metric_timestamp}_",
150-
suffix=".png",
151-
delete=False
144+
prefix=f"{metric_name}_{metric_timestamp}_", suffix=".png", delete=False
152145
) as temp:
153-
fig = make_alert_plot(
154-
df, metric_name, threshold, score_col, score_title, tags=tags
155-
)
146+
fig = make_alert_plot(df, metric_name, threshold, score_col, score_title, tags=tags)
156147
fig.savefig(temp.name)
157148
plt.close(fig)
158149

0 commit comments

Comments
 (0)