Skip to content

Commit 5c51626

Browse files
abrichrclaude
andcommitted
fix: resolve ruff linter and format issues across codebase
- Move warnings.warn() after imports to fix E402 errors - Remove unused imports (Any, base64, os, Service) - Remove f-string without placeholders - Apply ruff formatting to unformatted files These fixes resolve CI failures on main branch introduced in PR #10. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
1 parent 070225b commit 5c51626

File tree

7 files changed

+79
-55
lines changed

7 files changed

+79
-55
lines changed

openadapt_ml/benchmarks/azure_ops_tracker.py

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,9 @@ def start_operation(
160160
log_tail=[], # Clear stale logs
161161
started_at=self._start_time.isoformat(),
162162
elapsed_seconds=0.0,
163-
eta_seconds=TYPICAL_DURATIONS.get(operation), # Use typical duration as initial ETA
163+
eta_seconds=TYPICAL_DURATIONS.get(
164+
operation
165+
), # Use typical duration as initial ETA
164166
cost_usd=0.0,
165167
hourly_rate_usd=self.hourly_rate,
166168
vm_ip=vm_ip,
@@ -284,7 +286,9 @@ def parse_docker_build_line(self, line: str) -> dict[str, Any]:
284286
downloaded_unit = download_match.group(2)
285287
total = float(download_match.group(3))
286288
total_unit = download_match.group(4)
287-
result["download_bytes"] = int(downloaded * size_multipliers[downloaded_unit])
289+
result["download_bytes"] = int(
290+
downloaded * size_multipliers[downloaded_unit]
291+
)
288292
result["download_total_bytes"] = int(total * size_multipliers[total_unit])
289293

290294
# Extract phase from buildx output
@@ -384,7 +388,9 @@ def _update_progress(self) -> None:
384388

385389
# ETA from download speed
386390
if self._status.download_bytes > 0 and self._status.elapsed_seconds > 1:
387-
bytes_per_sec = self._status.download_bytes / self._status.elapsed_seconds
391+
bytes_per_sec = (
392+
self._status.download_bytes / self._status.elapsed_seconds
393+
)
388394
remaining_bytes = (
389395
self._status.download_total_bytes - self._status.download_bytes
390396
)
@@ -402,9 +408,15 @@ def _update_progress(self) -> None:
402408
remaining_steps = self._status.total_steps - self._status.step
403409
step_eta = time_per_step * remaining_steps
404410
# Use step ETA if we don't have download ETA or if step progress > download
405-
if eta_seconds is None or step_pct > (
406-
self._status.download_bytes / max(self._status.download_total_bytes, 1)
407-
) * 100:
411+
if (
412+
eta_seconds is None
413+
or step_pct
414+
> (
415+
self._status.download_bytes
416+
/ max(self._status.download_total_bytes, 1)
417+
)
418+
* 100
419+
):
408420
eta_seconds = step_eta
409421

410422
# 3. Fallback: Use typical duration if no progress info

openadapt_ml/benchmarks/viewer.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -38,18 +38,10 @@
3838

3939
from __future__ import annotations
4040

41-
import warnings
42-
43-
warnings.warn(
44-
"openadapt_ml.benchmarks.viewer is deprecated. "
45-
"Use openadapt_viewer instead: from openadapt_viewer import generate_benchmark_viewer",
46-
DeprecationWarning,
47-
stacklevel=2,
48-
)
49-
5041
import base64
5142
import json
5243
import logging
44+
import warnings
5345
from pathlib import Path
5446
from typing import Any
5547

@@ -58,6 +50,13 @@
5850
generate_shared_header_html as _generate_shared_header_html,
5951
)
6052

53+
warnings.warn(
54+
"openadapt_ml.benchmarks.viewer is deprecated. "
55+
"Use openadapt_viewer instead: from openadapt_viewer import generate_benchmark_viewer",
56+
DeprecationWarning,
57+
stacklevel=2,
58+
)
59+
6160
logger = logging.getLogger(__name__)
6261

6362

openadapt_ml/benchmarks/vm_monitor.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1014,7 +1014,9 @@ def detect_vm_activity(
10141014
return VMActivity(
10151015
is_active=is_running,
10161016
activity_type="benchmark_running" if is_running else "idle",
1017-
description="WAA benchmark running" if is_running else "WAA ready - idle",
1017+
description="WAA benchmark running"
1018+
if is_running
1019+
else "WAA ready - idle",
10181020
benchmark_progress=probe_data,
10191021
)
10201022
except json.JSONDecodeError:

openadapt_ml/benchmarks/waa_deploy/api_agent.py

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@
4343
import os
4444
import re
4545
from io import BytesIO
46-
from typing import Any, Dict, List
46+
from typing import Dict, List
4747

4848
from PIL import Image
4949

@@ -210,6 +210,7 @@ def __init__(
210210
)
211211
try:
212212
from anthropic import Anthropic
213+
213214
self._client = Anthropic(api_key=self.api_key)
214215
except ImportError:
215216
raise RuntimeError(
@@ -225,6 +226,7 @@ def __init__(
225226
)
226227
try:
227228
from openai import OpenAI
229+
228230
self._client = OpenAI(api_key=self.api_key)
229231
except ImportError:
230232
raise RuntimeError(
@@ -240,9 +242,13 @@ def __init__(
240242
self.memory_block_text = "# empty memory block"
241243
self.step_counter = 0
242244

243-
logger.info(f"ApiAgent initialized with provider={provider}, model={self.model}")
245+
logger.info(
246+
f"ApiAgent initialized with provider={provider}, model={self.model}"
247+
)
244248
if self.demo:
245-
logger.info(f"Demo trajectory provided ({len(self.demo)} chars) - will persist across all steps")
249+
logger.info(
250+
f"Demo trajectory provided ({len(self.demo)} chars) - will persist across all steps"
251+
)
246252

247253
def predict(self, instruction: str, obs: Dict) -> tuple:
248254
"""Predict the next action based on observation.
@@ -325,10 +331,9 @@ def predict(self, instruction: str, obs: Dict) -> tuple:
325331
# Add action history if enabled (enhanced: includes reasoning, not just raw actions)
326332
if self.use_history and self.history:
327333
# Use rich history with reasoning (like PC Agent-E)
328-
history_entries = self.history[-self.history_cutoff:]
334+
history_entries = self.history[-self.history_cutoff :]
329335
history_str = "\n\n".join(
330-
f"[Step {i+1}] {entry}"
331-
for i, entry in enumerate(history_entries)
336+
f"[Step {i + 1}] {entry}" for i, entry in enumerate(history_entries)
332337
)
333338
content_parts.append(f"History of previous steps:\n{history_str}")
334339
logs["history_entries"] = len(history_entries)
@@ -381,14 +386,18 @@ def predict(self, instruction: str, obs: Dict) -> tuple:
381386
actions = [code_text]
382387
self.prev_actions.append(code_text)
383388
# Store rich history with reasoning (memory + action)
384-
self._add_to_history(f"Thought: {self.memory_block_text}\nAction: {code_text}")
389+
self._add_to_history(
390+
f"Thought: {self.memory_block_text}\nAction: {code_text}"
391+
)
385392
else:
386393
# Try to extract action from response text
387394
action = self._parse_action_from_text(response_text, w, h)
388395
if action:
389396
actions = [action]
390397
self.prev_actions.append(action)
391-
self._add_to_history(f"Thought: {self.memory_block_text}\nAction: {action}")
398+
self._add_to_history(
399+
f"Thought: {self.memory_block_text}\nAction: {action}"
400+
)
392401
else:
393402
logger.warning("Could not extract action from response")
394403
actions = ["# Could not parse action"]
@@ -483,33 +492,25 @@ def _parse_action_from_text(self, text: str, width: int, height: int) -> str | N
483492
Python code string or None if parsing failed.
484493
"""
485494
# Try to find click coordinates
486-
click_match = re.search(
487-
r"click.*?(\d+)\s*,\s*(\d+)", text, re.IGNORECASE
488-
)
495+
click_match = re.search(r"click.*?(\d+)\s*,\s*(\d+)", text, re.IGNORECASE)
489496
if click_match:
490497
x, y = int(click_match.group(1)), int(click_match.group(2))
491498
return f"computer.click({x}, {y})"
492499

493500
# Try to find type text
494-
type_match = re.search(
495-
r'type[:\s]+["\'](.+?)["\']', text, re.IGNORECASE
496-
)
501+
type_match = re.search(r'type[:\s]+["\'](.+?)["\']', text, re.IGNORECASE)
497502
if type_match:
498503
text_to_type = type_match.group(1)
499504
return f'computer.type("{text_to_type}")'
500505

501506
# Try to find key press
502-
key_match = re.search(
503-
r"press[:\s]+(\w+)", text, re.IGNORECASE
504-
)
507+
key_match = re.search(r"press[:\s]+(\w+)", text, re.IGNORECASE)
505508
if key_match:
506509
key = key_match.group(1).lower()
507510
return f'computer.press("{key}")'
508511

509512
# Try to find hotkey
510-
hotkey_match = re.search(
511-
r"hotkey[:\s]+(\w+)\s*\+\s*(\w+)", text, re.IGNORECASE
512-
)
513+
hotkey_match = re.search(r"hotkey[:\s]+(\w+)\s*\+\s*(\w+)", text, re.IGNORECASE)
513514
if hotkey_match:
514515
key1, key2 = hotkey_match.group(1).lower(), hotkey_match.group(2).lower()
515516
return f'computer.hotkey("{key1}", "{key2}")'

openadapt_ml/cloud/local.py

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1078,11 +1078,17 @@ def do_GET(self):
10781078
status["session_id"] = session.get("session_id")
10791079
status["session_is_active"] = session.get("is_active", False)
10801080
# Include accumulated time from previous sessions for hybrid display
1081-
status["accumulated_seconds"] = session.get("accumulated_seconds", 0.0)
1081+
status["accumulated_seconds"] = session.get(
1082+
"accumulated_seconds", 0.0
1083+
)
10821084
# Calculate current session time (total - accumulated)
1083-
current_session_seconds = max(0, status["elapsed_seconds"] - status["accumulated_seconds"])
1085+
current_session_seconds = max(
1086+
0, status["elapsed_seconds"] - status["accumulated_seconds"]
1087+
)
10841088
status["current_session_seconds"] = current_session_seconds
1085-
status["current_session_cost_usd"] = (current_session_seconds / 3600) * session.get("hourly_rate_usd", 0.422)
1089+
status["current_session_cost_usd"] = (
1090+
current_session_seconds / 3600
1091+
) * session.get("hourly_rate_usd", 0.422)
10861092

10871093
try:
10881094
tunnel_mgr = get_tunnel_manager()
@@ -3212,12 +3218,18 @@ def compute_server_side_values(status: dict) -> dict:
32123218
status["session_id"] = session.get("session_id")
32133219
status["session_is_active"] = session.get("is_active", False)
32143220
# Include accumulated time from previous sessions for hybrid display
3215-
status["accumulated_seconds"] = session.get("accumulated_seconds", 0.0)
3221+
status["accumulated_seconds"] = session.get(
3222+
"accumulated_seconds", 0.0
3223+
)
32163224
# Calculate current session time (total - accumulated)
3217-
current_session_seconds = max(0, status["elapsed_seconds"] - status["accumulated_seconds"])
3225+
current_session_seconds = max(
3226+
0, status["elapsed_seconds"] - status["accumulated_seconds"]
3227+
)
32183228
status["current_session_seconds"] = current_session_seconds
32193229
hourly_rate = session.get("hourly_rate_usd", 0.422)
3220-
status["current_session_cost_usd"] = (current_session_seconds / 3600) * hourly_rate
3230+
status["current_session_cost_usd"] = (
3231+
current_session_seconds / 3600
3232+
) * hourly_rate
32213233

32223234
try:
32233235
tunnel_mgr = get_tunnel_manager()

openadapt_ml/scripts/capture_screenshots.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,7 @@
3535
from __future__ import annotations
3636

3737
import argparse
38-
import base64
3938
import datetime
40-
import os
4139
import re
4240
import subprocess
4341
import sys
@@ -108,7 +106,6 @@ def capture_web_page_selenium(url: str, output_path: Path) -> bool:
108106
try:
109107
from selenium import webdriver
110108
from selenium.webdriver.chrome.options import Options
111-
from selenium.webdriver.chrome.service import Service
112109

113110
options = Options()
114111
options.add_argument("--headless")
@@ -358,7 +355,9 @@ def capture_vm_screenshot_from_vm(output_path: Path) -> bool:
358355
)
359356

360357
if result.returncode != 0:
361-
print(f" VM screenshot failed: {result.stderr[:200] if result.stderr else 'Unknown error'}")
358+
print(
359+
f" VM screenshot failed: {result.stderr[:200] if result.stderr else 'Unknown error'}"
360+
)
362361
return False
363362

364363
# The CLI saves to training_output/current/vm_screenshot.png
@@ -499,7 +498,7 @@ def main():
499498
print(f" OK: {output_path.name} ({size_kb:.1f} KB)")
500499
results[target] = str(output_path)
501500
else:
502-
print(f" SKIP: Not available or capture failed")
501+
print(" SKIP: Not available or capture failed")
503502
results[target] = None
504503
except Exception as e:
505504
print(f" ERROR: {e}")

openadapt_ml/training/viewer.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,14 @@
1313

1414
from __future__ import annotations
1515

16+
import json
1617
import warnings
18+
from pathlib import Path
19+
20+
from openadapt_ml.training.shared_ui import (
21+
get_shared_header_css as _get_shared_header_css,
22+
generate_shared_header_html as _generate_shared_header_html,
23+
)
1724

1825
warnings.warn(
1926
"openadapt_ml.training.viewer is deprecated. "
@@ -22,14 +29,6 @@
2229
stacklevel=2,
2330
)
2431

25-
import json
26-
from pathlib import Path
27-
28-
from openadapt_ml.training.shared_ui import (
29-
get_shared_header_css as _get_shared_header_css,
30-
generate_shared_header_html as _generate_shared_header_html,
31-
)
32-
3332

3433
def _copy_transcript_and_audio(capture_path: Path | None, output_dir: Path) -> None:
3534
"""Copy transcript.json and convert audio to mp3 for viewer playback.

0 commit comments

Comments
 (0)