Skip to content

Commit 75ca0b8

Browse files
committed
Ruff: manual fixes
1 parent 5e1549a commit 75ca0b8

38 files changed

+157
-127
lines changed

ai_diffusion/client.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from abc import ABC, abstractmethod
66
from collections import deque
77
from collections.abc import AsyncGenerator, Callable, Iterable
8+
from dataclasses import dataclass, field
89
from enum import Enum
910
from typing import Any, Generic, NamedTuple, TypeVar
1011

@@ -23,6 +24,10 @@
2324
from .util import ensure
2425

2526

27+
class ServerError(Exception):
28+
pass
29+
30+
2631
class ClientEvent(Enum):
2732
progress = 0
2833
finished = 1
@@ -245,7 +250,7 @@ def resource(
245250
id = ResourceId(kind, arch, identifier)
246251
model = self.find(id)
247252
if model is None:
248-
raise Exception(f"{id.name} not found")
253+
raise KeyError(f"{id.name} not found")
249254
return model
250255

251256
def find(self, id: ResourceId):
@@ -389,10 +394,11 @@ def from_list(data: list):
389394
return [TranslationPackage.from_dict(item) for item in data]
390395

391396

392-
class ClientFeatures(NamedTuple):
397+
@dataclass(frozen=True)
398+
class ClientFeatures:
393399
ip_adapter: bool = True
394400
translation: bool = True
395-
languages: list[TranslationPackage] = []
401+
languages: list[TranslationPackage] = field(default_factory=list)
396402
max_upload_size: int = 0
397403
max_control_layers: int = 1000
398404
gguf: bool = False

ai_diffusion/cloud_client.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from collections.abc import Iterable
99
from copy import copy
1010
from dataclasses import dataclass, field
11-
from datetime import datetime
11+
from datetime import datetime, timezone
1212
from enum import Enum
1313
from typing import Any
1414

@@ -23,6 +23,7 @@
2323
ClientModels,
2424
DeviceInfo,
2525
News,
26+
ServerError,
2627
TranslationPackage,
2728
User,
2829
loras_to_upload,
@@ -122,9 +123,9 @@ async def sign_in(self):
122123
yield sign_in_url
123124

124125
auth_confirm = await self._post("auth/confirm", {"client_id": client_id})
125-
time = datetime.now()
126+
time = datetime.now(timezone.utc)
126127
while auth_confirm["status"] == "not-found":
127-
if (datetime.now() - time).seconds > 300:
128+
if (datetime.now(timezone.utc) - time).seconds > 300:
128129
raise TimeoutError(_("Sign-in attempt timed out after 5 minutes"))
129130
await asyncio.sleep(2)
130131
auth_confirm = await self._post("auth/confirm", {"client_id": client_id})
@@ -403,9 +404,11 @@ async def _upload_lora(self, lora: File):
403404
yield sent / max(total, 1)
404405
except NetworkError as e:
405406
log.error(f"LoRA model upload failed [{e.status}]: {e.message}")
406-
raise Exception(_("Connection error during upload of LoRA model") + f" {lora.name}")
407+
raise ServerError(
408+
_("Connection error during upload of LoRA model") + f" {lora.name}"
409+
) from e
407410
except Exception as e:
408-
raise Exception(_("Error during upload of LoRA model") + f" {lora.name}") from e
411+
raise ServerError(_("Error during upload of LoRA model") + f" {lora.name}") from e
409412

410413
async def receive_images(self, images: dict):
411414
offsets = images.get("offsets")

ai_diffusion/comfy_client.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
MissingResources,
2727
OutputBatchMode,
2828
Quantization,
29+
ServerError,
2930
SharedWorkflow,
3031
TextOutput,
3132
TranslationPackage,
@@ -174,7 +175,7 @@ async def connect(url=default_url, access_token=""):
174175
pass
175176
except Exception as e:
176177
msg = _("Could not establish websocket connection at") + f" {wsurl}: {e!s}"
177-
raise Exception(msg)
178+
raise ServerError(msg)
178179

179180
# Check custom nodes
180181
log.info("Checking for required custom nodes...")
@@ -615,7 +616,7 @@ async def upload_loras(self, work: WorkflowInput, local_job_id: str):
615616

616617
await self.refresh()
617618
except Exception as e:
618-
raise Exception(_("Error during upload of LoRA model") + f" {file.path}: {e!s}")
619+
raise ServerError(_("Error during upload of LoRA model") + f" {file.path}: {e!s}")
619620

620621
async def _get_active_job(self, job_id: str):
621622
if self._active_job and self._active_job.id == job_id:
@@ -859,7 +860,7 @@ def _ensure_supported_style(client: Client):
859860
if checkpoint is None:
860861
log.warning("No checkpoints found for any of the supported workloads!")
861862
if len(client.models.checkpoints) == 0:
862-
raise Exception(_("No diffusion model checkpoints found"))
863+
raise RuntimeError(_("No diffusion model checkpoints found"))
863864
return
864865
log.info(f"No supported styles found, creating default style with checkpoint {checkpoint}")
865866
default = next((s for s in Styles.list() if s.filename == "default.json"), None)

ai_diffusion/comfy_workflow.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -346,7 +346,7 @@ def sampler_custom_advanced(
346346
start_at_step=0,
347347
cfg=7.0,
348348
seed=-1,
349-
extent=Extent(1024, 1024),
349+
extent: Extent | None = None,
350350
):
351351
self.sample_count += steps - start_at_step
352352

@@ -373,7 +373,12 @@ def sampler_custom_advanced(
373373
)[1]
374374

375375
def scheduler_sigmas(
376-
self, model: Output, scheduler="normal", steps=20, arch=Arch.sdxl, extent=Extent(1024, 1024)
376+
self,
377+
model: Output,
378+
scheduler="normal",
379+
steps=20,
380+
arch=Arch.sdxl,
381+
extent: Extent | None = None,
377382
):
378383
if scheduler in ("align_your_steps", "ays"):
379384
assert arch is Arch.sd15 or arch.is_sdxl_like
@@ -418,6 +423,7 @@ def scheduler_sigmas(
418423
beta=0.5,
419424
)
420425
elif scheduler == "flux2":
426+
extent = extent or Extent(1024, 1024)
421427
return self.add(
422428
"Flux2Scheduler",
423429
output_count=1,

ai_diffusion/custom_workflow.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ def _process_file(self, file: Path):
124124
graph = json.load(f)
125125
self._process_workflow(file.stem, WorkflowSource.local, graph, file)
126126

127-
def rowCount(self, parent=QModelIndex()):
127+
def rowCount(self, parent: QModelIndex | None = None):
128128
return len(self._workflows)
129129

130130
def data(self, index: QModelIndex, role: int = 0):

ai_diffusion/document.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -332,10 +332,9 @@ def _selection_is_entire_document(selection: krita.Selection, extent: Extent):
332332

333333

334334
class PoseLayers:
335-
_layers: dict[str, Pose] = {}
336-
_timer = QTimer()
337-
338335
def __init__(self):
336+
self._layers: dict[str, Pose] = {}
337+
self._timer = QTimer()
339338
self._timer.setInterval(500)
340339
self._timer.timeout.connect(self.update)
341340
self._timer.start()

ai_diffusion/eventloop.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,13 @@ def schedule():
3838

3939

4040
def stop():
41-
global _timer, _loop
41+
global _timer
4242
try:
4343
_timer.stop()
4444
_timer = None
4545
_loop.stop()
4646
_loop.close()
47-
except Exception:
47+
except Exception: # noqa
4848
pass
4949

5050

ai_diffusion/extension.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,10 @@
1616

1717

1818
class AIToolsExtension(Extension):
19-
_actions: dict[str, QAction] = {}
20-
_settings_dialog: SettingsDialog
21-
2219
def __init__(self, parent):
2320
super().__init__(parent)
21+
self._actions: dict[str, QAction] = {}
22+
2423
log.info(f"Extension initialized, Version: {__version__}, Python: {sys.version}")
2524

2625
extension_dir = Path(__file__).parent

ai_diffusion/files.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ def __init__(self, database: Path | None = None, parent=None):
9999
self._files: list[File] = []
100100
self.load()
101101

102-
def rowCount(self, parent=QModelIndex()):
102+
def rowCount(self, parent: QModelIndex | None = None):
103103
return len(self._files)
104104

105105
def data(self, index: QModelIndex, role: int = 0):

ai_diffusion/image.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -378,7 +378,7 @@ def from_bytes(data: QBuffer | QByteArray | memoryview | bytes, format: str | No
378378
if loader.read(img):
379379
return Image(img)
380380
else:
381-
raise Exception(f"Failed to load image from buffer: {loader.errorString()}")
381+
raise RuntimeError(f"Failed to load image from buffer: {loader.errorString()}")
382382

383383
@staticmethod
384384
def from_pil(pil_image):
@@ -561,7 +561,7 @@ def write(
561561
global _qt_supports_webp
562562
_qt_supports_webp = False
563563
self.write(buffer, format.no_webp_fallback)
564-
raise Exception(f"Failed to write image to buffer: {writer.errorString()} {info}")
564+
raise RuntimeError(f"Failed to write image to buffer: {writer.errorString()} {info}")
565565

566566
def to_bytes(self, format=ImageFileFormat.png):
567567
byte_array = QByteArray()
@@ -604,7 +604,7 @@ def save(
604604
fmt = format or ImageFileFormat.from_extension(filepath)
605605
file = QFile(str(filepath))
606606
if not file.open(QFile.OpenModeFlag.WriteOnly):
607-
raise Exception(f"Failed to open {filepath} for writing: {file.errorString()}")
607+
raise RuntimeError(f"Failed to open {filepath} for writing: {file.errorString()}")
608608
try:
609609
self.write(file, fmt, quality)
610610
finally:

0 commit comments

Comments
 (0)