Skip to content

Commit ebe27b2

Browse files
style: format code with Autopep8 (#40)
This commit fixes the style issues introduced in 15e100d according to the output from Autopep8.
1 parent 003fcda commit ebe27b2

File tree

11 files changed

+89
-45
lines changed

11 files changed

+89
-45
lines changed

openfaas-function/llm-global-spend/handler.py

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ def __init__(self, base_url: Optional[str] = None, api_key: Optional[str] = None
3131
"accept": "application/json",
3232
"x-goog-api-key": api_key,
3333
}
34-
logger.debug(f"LiteLLMAPIClient initialized with base URL: {self.base_url}")
34+
logger.debug(
35+
f"LiteLLMAPIClient initialized with base URL: {self.base_url}")
3536

3637
def fetch_spending_logs(
3738
self, user_id=None, start_date="2024-06-01", end_date="2025-12-31"
@@ -51,20 +52,23 @@ def fetch_spending_logs(
5152
requests.exceptions.RequestException: If the API request fails
5253
"""
5354
spending_logs_endpoint = f"{self.base_url}/spend/logs"
54-
params = {"user_id": user_id, "start_date": start_date, "end_date": end_date}
55+
params = {"user_id": user_id,
56+
"start_date": start_date, "end_date": end_date}
5557

5658
logger.info(
5759
f"Fetching spend logs for user {user_id} from {start_date} to {end_date}"
5860
)
59-
logger.debug(f"API request to {spending_logs_endpoint} with params: {params}")
61+
logger.debug(
62+
f"API request to {spending_logs_endpoint} with params: {params}")
6063

6164
try:
6265
response = requests.get(
6366
spending_logs_endpoint, headers=self.headers, params=params
6467
)
6568
response.raise_for_status()
6669
data = response.json()
67-
logger.success(f"Successfully fetched {len(data)} spending log entries")
70+
logger.success(
71+
f"Successfully fetched {len(data)} spending log entries")
6872
return data
6973
except requests.exceptions.RequestException as e:
7074
logger.error(f"Failed to fetch spending logs: {str(e)}")
@@ -82,7 +86,8 @@ def __init__(self, spend_data: List[Dict]):
8286
spend_data: List of spending records
8387
"""
8488
self.spend_data = spend_data
85-
logger.debug(f"SpendAnalyzer initialized with {len(spend_data)} records")
89+
logger.debug(
90+
f"SpendAnalyzer initialized with {len(spend_data)} records")
8691

8792
def get_total_spend(self) -> float:
8893
"""Calculate the total spend across all records"""
@@ -103,20 +108,23 @@ def get_filtered_spend(
103108
Returns:
104109
float: Total spend in the specified date range
105110
"""
106-
logger.debug(f"Calculating filtered spend from {start_date} to {end_date}")
111+
logger.debug(
112+
f"Calculating filtered spend from {start_date} to {end_date}")
107113
filtered_spend = 0
108114
valid_entries = 0
109115
invalid_entries = 0
110116

111117
for entry in self.spend_data:
112118
date_string = entry.get("startTime", "")
113119
try:
114-
entry_date = datetime.datetime.strptime(date_string, "%Y-%m-%d")
120+
entry_date = datetime.datetime.strptime(
121+
date_string, "%Y-%m-%d")
115122
if start_date <= entry_date < end_date:
116123
spend_amount = entry.get("spend", 0)
117124
filtered_spend += spend_amount
118125
valid_entries += 1
119-
logger.debug(f"Added spend entry: {date_string} = {spend_amount}")
126+
logger.debug(
127+
f"Added spend entry: {date_string} = {spend_amount}")
120128
except ValueError:
121129
logger.warning(f"Invalid date format in entry: {date_string}")
122130
invalid_entries += 1
@@ -131,7 +139,8 @@ def get_current_month_spend(self) -> float:
131139
"""Calculate spend for the current month"""
132140
now = datetime.datetime.now()
133141
first_day = now.replace(day=1)
134-
next_month = (now.replace(day=28) + datetime.timedelta(days=4)).replace(day=1)
142+
next_month = (now.replace(day=28) +
143+
datetime.timedelta(days=4)).replace(day=1)
135144

136145
logger.info(
137146
f"Calculating current month spend ({first_day.strftime('%Y-%m-%d')} to {next_month.strftime('%Y-%m-%d')})"
@@ -144,7 +153,8 @@ def get_today_spend(self) -> float:
144153
today = now.replace(hour=0, minute=0, second=0, microsecond=0)
145154
tomorrow = today + datetime.timedelta(days=1)
146155

147-
logger.info(f"Calculating today's spend ({today.strftime('%Y-%m-%d')})")
156+
logger.info(
157+
f"Calculating today's spend ({today.strftime('%Y-%m-%d')})")
148158
return self.get_filtered_spend(today, tomorrow)
149159

150160

@@ -192,7 +202,8 @@ def handle(event, context):
192202
"today_spend": float(today_spend),
193203
}
194204

195-
logger.success(f"Successfully processed request, returning data: {response}")
205+
logger.success(
206+
f"Successfully processed request, returning data: {response}")
196207
return {
197208
"statusCode": 200,
198209
"body": json.dumps(response),

openfaas-function/spot-start-service/handler.py

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@
4848
ENDPOINTS_CONFIG = PORTAINER_ENDPOINTS_CONFIG.copy()
4949
except ImportError as err_msg:
5050
logger.exception(err_msg)
51-
logger.exception("Failed to import constants.py. You may need to create it.")
51+
logger.exception(
52+
"Failed to import constants.py. You may need to create it.")
5253
raise err_msg
5354

5455

@@ -121,7 +122,8 @@ def handle(event, context):
121122
# Find the service name from the referral URL
122123
service_name = service_manager.find_service_from_url(referral_url)
123124
if not service_name:
124-
logger.error(f"No service found for referral URL: {referral_url}")
125+
logger.error(
126+
f"No service found for referral URL: {referral_url}")
125127
return build_response(
126128
status_code=404,
127129
body={
@@ -133,14 +135,16 @@ def handle(event, context):
133135
# Start the service
134136
result = service_manager.start_service(service_name)
135137
status_code = 200 if result.get("success", False) else 500
136-
logger.success(f"Request processed with status {status_code}: {result}")
138+
logger.success(
139+
f"Request processed with status {status_code}: {result}")
137140
return build_response(status_code=status_code, body=result)
138141

139142
except json.JSONDecodeError as e:
140143
logger.error(f"Invalid JSON in request: {str(e)}")
141144
return build_response(
142145
status_code=400,
143-
body={"error": "Invalid JSON in request", "event": format_event(event)},
146+
body={"error": "Invalid JSON in request",
147+
"event": format_event(event)},
144148
)
145149

146150
except Exception as e:

openfaas-function/spot-start-service/handler_test.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,8 @@ def test_service_manager_find_service(self):
118118
"""Test finding service location"""
119119
# Create manager with mock client
120120
mock_client = MagicMock()
121-
manager = ServiceManager(mock_client, endpoints_config=ENDPOINTS_CONFIG)
121+
manager = ServiceManager(
122+
mock_client, endpoints_config=ENDPOINTS_CONFIG)
122123

123124
# Test finding existing service
124125
location = manager.find_service_location("service-a")

openfaas-function/spot-start-service/portainer.py

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,13 @@ def __init__(
2323
self.verify_ssl = False
2424

2525
if not self.base_url or not self.username or not self.password:
26-
logger.error("Portainer URL, username and password must be provided")
27-
raise ValueError("Portainer URL, username and password must be provided")
26+
logger.error(
27+
"Portainer URL, username and password must be provided")
28+
raise ValueError(
29+
"Portainer URL, username and password must be provided")
2830

29-
logger.debug(f"PortainerAPIClient initialized with base URL: {self.base_url}")
31+
logger.debug(
32+
f"PortainerAPIClient initialized with base URL: {self.base_url}")
3033

3134
def authenticate(self) -> str:
3235
"""
@@ -52,7 +55,8 @@ def authenticate(self) -> str:
5255

5356
if not token:
5457
logger.error("Authentication failed: No JWT token in response")
55-
raise ValueError("Authentication failed: No JWT token in response")
58+
raise ValueError(
59+
"Authentication failed: No JWT token in response")
5660

5761
self.jwt_token = token
5862
logger.success("Successfully authenticated with Portainer API")
@@ -102,7 +106,8 @@ def get_containers(self, endpoint_id: str, docker_version: str) -> List[Dict]:
102106
)
103107
response.raise_for_status()
104108
containers = response.json()
105-
logger.success(f"Successfully fetched {len(containers)} containers")
109+
logger.success(
110+
f"Successfully fetched {len(containers)} containers")
106111
return containers
107112

108113
except requests.exceptions.RequestException as e:
@@ -222,7 +227,8 @@ def find_service_location(self, service_name: str) -> Optional[Tuple[str, str]]:
222227
)
223228
return (endpoint_id, stack_id)
224229

225-
logger.warning(f"Service '{service_name}' not found in endpoints configuration")
230+
logger.warning(
231+
f"Service '{service_name}' not found in endpoints configuration")
226232
return None
227233

228234
def check_service_health(
@@ -247,7 +253,8 @@ def check_service_health(
247253
docker_version = endpoint_info.get("docker_version", "v1.24")
248254

249255
try:
250-
containers = self.api_client.get_containers(endpoint_id, docker_version)
256+
containers = self.api_client.get_containers(
257+
endpoint_id, docker_version)
251258

252259
# Filter containers belonging to this service/stack
253260
service_containers = []
@@ -259,7 +266,8 @@ def check_service_health(
259266
service_containers.append(container)
260267

261268
if not service_containers:
262-
logger.warning(f"No containers found for service '{service_name}'")
269+
logger.warning(
270+
f"No containers found for service '{service_name}'")
263271
return (False, service_location)
264272

265273
# Check if all containers are healthy
@@ -306,7 +314,8 @@ def start_service(self, service_name: str) -> Dict[str, Any]:
306314
endpoint_id, stack_id = location
307315

308316
if is_healthy:
309-
logger.info(f"Service '{service_name}' is already running and healthy")
317+
logger.info(
318+
f"Service '{service_name}' is already running and healthy")
310319
return {
311320
"success": True,
312321
"message": f"Service '{service_name}' is already running",
@@ -325,7 +334,8 @@ def start_service(self, service_name: str) -> Dict[str, Any]:
325334
self.api_client.stop_stack(stack_id, endpoint_id)
326335
time.sleep(5) # Give it some time to stop
327336
except Exception as e:
328-
logger.warning(f"Error stopping service (continuing anyway): {str(e)}")
337+
logger.warning(
338+
f"Error stopping service (continuing anyway): {str(e)}")
329339

330340
# Start the service
331341
self.api_client.start_stack(stack_id, endpoint_id)
@@ -339,7 +349,8 @@ def start_service(self, service_name: str) -> Dict[str, Any]:
339349
}
340350

341351
except Exception as e:
342-
logger.exception(f"Error starting service '{service_name}': {str(e)}")
352+
logger.exception(
353+
f"Error starting service '{service_name}': {str(e)}")
343354
return {"success": False, "message": f"Error starting service: {str(e)}"}
344355

345356
def find_service_from_url(self, referral_url: str) -> Optional[str]:
@@ -375,14 +386,16 @@ def find_service_from_url(self, referral_url: str) -> Optional[str]:
375386

376387
docker_version = endpoint_info.get("docker_version", "v1.24")
377388
try:
378-
containers = self.api_client.get_containers(endpoint_id, docker_version)
389+
containers = self.api_client.get_containers(
390+
endpoint_id, docker_version)
379391
for container in containers:
380392
labels: dict = container.get("Labels", {})
381393
domain_label: str = (
382394
labels.get("home.resolve.domain", "").lower().strip()
383395
)
384396
project_name: str = (
385-
labels.get("com.docker.compose.project", "").lower().strip()
397+
labels.get("com.docker.compose.project",
398+
"").lower().strip()
386399
)
387400

388401
# Skip if missing important labels

python/delete_old_file.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ def run(path="/path/to/downloads", exceptions=None, max_days=10):
3232
if not any(
3333
map(file_path.__contains__, exceptions)
3434
) and not file_path.endswith(".!qb"):
35-
modified_time = datetime.fromtimestamp(os.path.getmtime(file_path))
35+
modified_time = datetime.fromtimestamp(
36+
os.path.getmtime(file_path))
3637
today = datetime.today()
3738
file_age = today - modified_time
3839
if file_age.days >= max_days:
@@ -53,7 +54,8 @@ def run(path="/path/to/downloads", exceptions=None, max_days=10):
5354
except Exception as _err:
5455
logging.error("Service interrupted. %s", _err)
5556
logging.error(
56-
"Deleted %s files of %s bytes until error.", str(del_count), str(del_size)
57+
"Deleted %s files of %s bytes until error.", str(
58+
del_count), str(del_size)
5759
)
5860

5961

python/login_notification.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,8 @@ def get_key():
4444
return response.json().get("value")
4545
except requests.exceptions.Timeout:
4646
logging.warning(
47-
"[%s/%s] Timed-out so trying again.", str(count + 1), str(retries)
47+
"[%s/%s] Timed-out so trying again.", str(
48+
count + 1), str(retries)
4849
)
4950
except requests.ConnectionError as error:
5051
logging.error(

python/login_notification_ssm.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,8 @@ def get_key():
4444
return response.json().get("value")
4545
except requests.exceptions.Timeout:
4646
logging.warning(
47-
"[%s/%s] Timed-out so trying again.", str(count + 1), str(retries)
47+
"[%s/%s] Timed-out so trying again.", str(
48+
count + 1), str(retries)
4849
)
4950
except requests.ConnectionError as error:
5051
logging.error(

python/macro_keyboard_companion.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,8 @@ def turn_off_tv():
5959
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
6060
ssh.connect(ssh_host, username=ssh_uname, password=ssh_pass)
6161
# skipcq: BAN-B601
62-
ssh.exec_command(f"echo {ssh_pass} | sudo -S systemctl stop gdm3 && exit")
62+
ssh.exec_command(
63+
f"echo {ssh_pass} | sudo -S systemctl stop gdm3 && exit")
6364
ssh.close()
6465
# skipcq: PYL-W0703
6566
except Exception as error:

python/openwebui/pipe_mcts.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,8 @@ def get_chunk_content(self, chunk):
200200
if "content" in delta:
201201
yield delta["content"]
202202
except json.JSONDecodeError:
203-
logger.error('ChunkDecodeError: unable to parse "%s"', chunk_str[:100])
203+
logger.error('ChunkDecodeError: unable to parse "%s"',
204+
chunk_str[:100])
204205

205206

206207
class Node:
@@ -473,7 +474,8 @@ async def evaluate_answer(self, answer: str):
473474
score = int(re.search(r"\d+", result).group())
474475
return score
475476
except Exception as e:
476-
logger.error("Failed to parse score from result: %s - %s", result, e)
477+
logger.error(
478+
"Failed to parse score from result: %s - %s", result, e)
477479
return 0
478480

479481
async def generate_completion(self, prompt: str):
@@ -715,7 +717,8 @@ async def pipe(
715717
if match:
716718
backend, model_name = match.groups()
717719
else:
718-
logger.error("Model ID should be in the format '*.mcts/backend/model_name'")
720+
logger.error(
721+
"Model ID should be in the format '*.mcts/backend/model_name'")
719722
logger.error("Invalid model ID: %s", model_id)
720723
return ""
721724

0 commit comments

Comments
 (0)