Skip to content
Merged

Ruff #143

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ jobs:
pip install -r requirements.txt -r requirements-test.txt
pip install git+https://github.com/huggingface/diffusers
- name: Format check
run: black --check dw dw_mcp tests
run: ruff format --check dw dw_mcp tests
- name: Lint
run: ruff check dw dw_mcp tests
- name: Tests
run: pytest -q

Expand Down
30 changes: 19 additions & 11 deletions docs/SECURITY_QUICKREF.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,16 @@ and [REMOTE.md](REMOTE.md).

```python
from dw.security import (
validate_path, validate_workflow_path, validate_output_path,
validate_url, validate_variable_name, validate_string_input,
sanitize_command_args, SecurityError, PathTraversalError, InvalidInputError
validate_path,
validate_workflow_path,
validate_output_path,
validate_url,
validate_variable_name,
validate_string_input,
sanitize_command_args,
SecurityError,
PathTraversalError,
InvalidInputError,
)
```

Expand All @@ -28,11 +35,11 @@ anything a workflow names:

```python
from dw.locations import (
validate_media_path, # confined to the workflow dir / assets / outputs
validate_media_glob, # the same, on a pattern's fixed prefix
contained_matches, # each match re-checked on its real path
validate_media_url, # no loopback / link-local / private host
validate_model_name, # a Hub repo id, or a contained path
validate_media_path, # confined to the workflow dir / assets / outputs
validate_media_glob, # the same, on a pattern's fixed prefix
contained_matches, # each match re-checked on its real path
validate_media_url, # no loopback / link-local / private host
validate_model_name, # a Hub repo id, or a contained path
)
```

Expand All @@ -49,13 +56,14 @@ workflow_path = validate_workflow_path("workflow.json")
output_path = validate_output_path(user_path, base_output_dir)

# User input
var_name = validate_variable_name("prompt") # OK
var_name = validate_variable_name("bad;name") # raises InvalidInputError
var_name = validate_variable_name("prompt") # OK
var_name = validate_variable_name("bad;name") # raises InvalidInputError
value = validate_string_input(user_input, max_length=1000)
url = validate_url(user_url) # http/https only
url = validate_url(user_url) # http/https only

# Subprocess (dw/ doesn't currently shell out anywhere - pattern for if/when it does)
import subprocess

cmd = sanitize_command_args(["python", "-m", "dw.run", validated_path])
subprocess.Popen(cmd, shell=False)
```
Expand Down
106 changes: 57 additions & 49 deletions docs/superpowers/plans/2026-03-26-ecosystem-utilities.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,9 @@ class TestSegmentImage:
torch.zeros(1, 1, 480, 640)
]
# Set the mask area to 1
mock_sam_proc_instance.post_process_masks.return_value[0][0, 0, 100:300, 100:300] = 1.0
mock_sam_proc_instance.post_process_masks.return_value[0][
0, 0, 100:300, 100:300
] = 1.0

image = _make_test_image()
result = segment_image(image, "dog")
Expand Down Expand Up @@ -787,9 +789,7 @@ def interpolate_frames(video, device="cpu", **kwargs):
)

if len(video) < 2:
raise ValueError(
f"Need at least 2 frames to interpolate, got {len(video)}"
)
raise ValueError(f"Need at least 2 frames to interpolate, got {len(video)}")

logger.info(
f"Interpolating {len(video)} frames with {multiplier}x multiplier on {device}"
Expand Down Expand Up @@ -836,7 +836,9 @@ def _load_rife_model(device, model_name=None):
)

if model_name is None:
model_name = "skytnt/anime-seg" # Placeholder — replace with actual RIFE HF repo
model_name = (
"skytnt/anime-seg" # Placeholder — replace with actual RIFE HF repo
)

logger.info(f"Loading RIFE model from {model_name} to {device}")

Expand Down Expand Up @@ -1026,14 +1028,20 @@ class TestMetadataEmbedding:
def test_png_metadata_embedded(self):
"""When embed_metadata is true, PNG should contain parameters text chunk."""
with tempfile.TemporaryDirectory() as temp_dir:
result_def = {"content_type": "image/png", "save": True, "embed_metadata": True}
result_def = {
"content_type": "image/png",
"save": True,
"embed_metadata": True,
}
result = Result(result_def)
result.set_metadata({
"workflow_id": "test_workflow",
"step_name": "generate",
"model_name": "test/model",
"arguments": {"prompt": "a cat", "num_inference_steps": 25},
})
result.set_metadata(
{
"workflow_id": "test_workflow",
"step_name": "generate",
"model_name": "test/model",
"arguments": {"prompt": "a cat", "num_inference_steps": 25},
}
)

# Add a real PIL image
img = Image.new("RGB", (64, 64), color=(128, 64, 32))
Expand Down Expand Up @@ -1163,45 +1171,45 @@ Replace it with metadata-aware saving:
Add the `_save_image_with_metadata` method to the Result class (after `save_artifact`):

```python
def _save_image_with_metadata(self, image, output_path, content_type):
"""Save an image with embedded generation metadata.
def _save_image_with_metadata(self, image, output_path, content_type):
"""Save an image with embedded generation metadata.

Args:
image: PIL Image to save
output_path: File path to save to
content_type: MIME type (determines embedding method)
"""
metadata_json = json.dumps(self.metadata, default=str)

if content_type == "image/png":
from PIL.PngImagePlugin import PngInfo

png_info = PngInfo()
png_info.add_text("parameters", metadata_json)
image.save(output_path, pnginfo=png_info)
logger.debug(f"Embedded PNG metadata in {output_path}")
elif content_type in ("image/jpeg", "image/webp"):
try:
import piexif

exif_dict = {"0th": {}, "Exif": {}, "GPS": {}, "1st": {}}
if hasattr(image, "info") and "exif" in image.info:
exif_dict = piexif.load(image.info["exif"])
exif_dict["Exif"][
piexif.ExifIFD.UserComment
] = piexif.helper.UserComment.dump(metadata_json)
exif_bytes = piexif.dump(exif_dict)
image.save(output_path, exif=exif_bytes)
logger.debug(f"Embedded EXIF metadata in {output_path}")
except ImportError:
logger.warning(
"piexif not installed - saving without metadata. "
"Install with: pip install piexif"
)
image.save(output_path)
else:
# Unsupported image format for metadata - save normally
Args:
image: PIL Image to save
output_path: File path to save to
content_type: MIME type (determines embedding method)
"""
metadata_json = json.dumps(self.metadata, default=str)

if content_type == "image/png":
from PIL.PngImagePlugin import PngInfo

png_info = PngInfo()
png_info.add_text("parameters", metadata_json)
image.save(output_path, pnginfo=png_info)
logger.debug(f"Embedded PNG metadata in {output_path}")
elif content_type in ("image/jpeg", "image/webp"):
try:
import piexif

exif_dict = {"0th": {}, "Exif": {}, "GPS": {}, "1st": {}}
if hasattr(image, "info") and "exif" in image.info:
exif_dict = piexif.load(image.info["exif"])
exif_dict["Exif"][piexif.ExifIFD.UserComment] = (
piexif.helper.UserComment.dump(metadata_json)
)
exif_bytes = piexif.dump(exif_dict)
image.save(output_path, exif=exif_bytes)
logger.debug(f"Embedded EXIF metadata in {output_path}")
except ImportError:
logger.warning(
"piexif not installed - saving without metadata. "
"Install with: pip install piexif"
)
image.save(output_path)
else:
# Unsupported image format for metadata - save normally
image.save(output_path)
```

- [ ] **Step 3: Run metadata tests**
Expand Down
4 changes: 3 additions & 1 deletion docs/superpowers/plans/2026-09-01-desktop-installers.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,9 @@ def settings_dir():
runs dw/__init__.py and pulls in torch, which this pure HTTP client has
no use for (test_mcp_server.py::TestStartupWeight guards the boundary).
"""
return Path(os.environ.get("DIFFUSERS_HELPER_ROOT") or "~/.diffusers_helper/").expanduser()
return Path(
os.environ.get("DIFFUSERS_HELPER_ROOT") or "~/.diffusers_helper/"
).expanduser()


def _base_url_from_server_file():
Expand Down
Loading
Loading