Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ruff #45

Merged
merged 7 commits into from
Feb 9, 2024
Merged

Ruff #45

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
8 changes: 8 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,11 @@ repos:
rev: 22.10.0
hooks:
- id: black
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.2.1
hooks:
# Run the linter.
- id: ruff
args: [ --fix , --ignore , "F403" ]
exclude: "__init__"
31 changes: 16 additions & 15 deletions example_tool/brainmask_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,12 @@
import argparse

import pydicom
from pdf2dcm import Pdf2EncapsDCM, Pdf2RgbSC
from pdf2dcm import Pdf2EncapsDCM
from subprocess import run
from pipeline_functions import *
from pipeline_functions import dicom_inference_and_conversion, brainmask_inference
from pdf_report import generate_report
from pydicom import dcmread
from pathlib import Path
from enum import Enum, auto



description = "author: Michal Brzus\nBrainmask Tool\n"
Expand Down Expand Up @@ -51,7 +49,7 @@
output_path = Path(args.output_dir)


try :
try:
nifti_path = dicom_inference_and_conversion(
session_dir=session_path.as_posix(),
output_dir=output_path.as_posix(),
Expand Down Expand Up @@ -101,7 +99,9 @@
mask_path = list(Path(brainmask_output_dir).glob("*.nii.gz"))[0]
stage_name = "report_generation"
try:
pdf_fn = generate_report(im_path.as_posix(), mask_path.as_posix(), report_output_dir)
pdf_fn = generate_report(
im_path.as_posix(), mask_path.as_posix(), report_output_dir
)
print(f"Report created: {pdf_fn}")
except Exception as e:
print(f"Error in stage: {stage_name}")
Expand All @@ -114,22 +114,23 @@

try:
converter = Pdf2EncapsDCM()
converted_dcm = converter.run(path_pdf=pdf_fn, path_template_dcm=template_dcm.as_posix(), suffix =".dcm")[0]
converted_dcm = converter.run(
path_pdf=pdf_fn, path_template_dcm=template_dcm.as_posix(), suffix=".dcm"
)[0]
del report_output_dir, brainmask_output_dir, nifti_path

print(f"Report created: {converted_dcm}")

# Adding needed metadata to the report
""""""
pdf_dcm = dcmread(converted_dcm,stop_before_pixels=True)

pdf_dcm = dcmread(converted_dcm, stop_before_pixels=True)

extra_metadata = [
(
"SeriesDescription",
"0008,103e",
f"This is a rough brainmask",
),
(
"SeriesDescription",
"0008,103e",
"This is a rough brainmask",
),
]
for info in extra_metadata:
title = info[0]
Expand All @@ -148,4 +149,4 @@
print(f"Successfully finished stage: {stage_name}")


# [ 'tests/test_data/test_file.dcm' ]
# [ 'tests/test_data/test_file.dcm' ]
4 changes: 2 additions & 2 deletions example_tool/cnn_transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,8 @@ def __call__(self, data):
return d


unsqueze_lambda = lambda x: x.squeeze(dim=0)
shape_lambda = lambda x: x.shape
# unsqueze_lambda = lambda x: x.squeeze(dim=0)
# shape_lambda = lambda x: x.shape


class ResampleMaskToOgd(object):
Expand Down
5 changes: 1 addition & 4 deletions example_tool/pdf_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@
import numpy as np
from io import BytesIO
import base64
import subprocess
import platform


# CSS Content
Expand Down Expand Up @@ -102,8 +100,7 @@ def generate_image(im_path, mask_path):
return image_base64


def generate_pdf(brain_volume, image_base64, file_path
):
def generate_pdf(brain_volume, image_base64, file_path):
# HTML Content
html_string = f"""
<!DOCTYPE html>
Expand Down
41 changes: 24 additions & 17 deletions example_tool/pipeline_functions.py
Original file line number Diff line number Diff line change
@@ -1,30 +1,34 @@
from cnn_transforms import *
from cnn_transforms import (
LoadITKImaged,
ResampleStartRegionBrainMaskd,
ITKImageToNumpyd,
AddChanneld,
ToITKImaged,
ResampleMaskToOgd,
SaveITKImaged,
)
import pytorch_lightning as pl
from monai.data import CacheDataset

from monai.networks.layers import Norm
from monai.networks.nets import UNet
from monai.transforms import (
Compose,
ScaleIntensityRangePercentilesd,
ToTensord,
CopyItemsd,
KeepLargestConnectedComponentd,
FillHolesd
)
from torchmetrics.classification import Dice
import torch
from monai.losses.dice import GeneralizedDiceFocalLoss

itk.MultiThreaderBase.SetGlobalDefaultNumberOfThreads(1)

from pathlib import Path
from dcm_classifier.study_processing import ProcessOneDicomStudyToVolumesMappingBase
from dcm_classifier.image_type_inference import ImageTypeClassifierBase
from dcm_classifier.namic_dicom_typing import itk_read_from_dicomfn_list
import re
from pydicom import dcmread
from subprocess import run
import itk


itk.MultiThreaderBase.SetGlobalDefaultNumberOfThreads(1)


def validate_subject_id(subject_id: str) -> str:
Expand Down Expand Up @@ -82,9 +86,13 @@ def dicom_inference_and_conversion(
fname = f"{validate_subject_id(sub)}_{validate_session_id(ses)}_acq-{plane}_{modality}"
series_vol_list = series.get_volume_list()
if len(series_vol_list) > 1:
print(f"Series {series_number} not supported. More than one volume in series.")
print(
f"Series {series_number} not supported. More than one volume in series."
)
else:
itk_im = itk_read_from_dicomfn_list(series_vol_list[0].get_one_volume_dcm_filenames())
itk_im = itk_read_from_dicomfn_list(
series_vol_list[0].get_one_volume_dcm_filenames()
)
itk.imwrite(itk_im, f"{sub_ses_dir}/{fname}.nii.gz")

return sub_ses_dir
Expand All @@ -108,7 +116,9 @@ def forward(self, x):
return self.model(x)


def brainmask_inference(data: list, model_file: str, out_dir: str, postfix='brainmask') -> None:
def brainmask_inference(
data: list, model_file: str, out_dir: str, postfix="brainmask"
) -> None:
print("\nDATA: ", data)
model = BrainmaskModel.load_from_checkpoint(
checkpoint_path=model_file,
Expand Down Expand Up @@ -155,12 +165,10 @@ def brainmask_inference(data: list, model_file: str, out_dir: str, postfix='brai
with torch.no_grad(): # perform the inference
test_output = model.model(item["image"].unsqueeze(dim=0).to(device))
# convert from one hot encoding
out_im = (
torch.argmax(test_output, dim=1).detach().cpu()
)
out_im = torch.argmax(test_output, dim=1).detach().cpu()

print(out_im.shape)
item["inferred_label"] = out_im #.squeeze(dim=0)
item["inferred_label"] = out_im # .squeeze(dim=0)
item["inferred_label_meta_dict"] = item["image_meta_dict"]
item["inferred_label_meta_dict"]["filename"] = item["image_meta_dict"][
"filename"
Expand All @@ -176,4 +184,3 @@ def brainmask_inference(data: list, model_file: str, out_dir: str, postfix='brai
]
)
out_transforms(item)

2 changes: 1 addition & 1 deletion job-monitoring-app/backend/app/models/api_key.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime, func
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime
from sqlalchemy.orm import relationship

from .base import Base, DateMixin
Expand Down
2 changes: 1 addition & 1 deletion job-monitoring-app/backend/app/models/event.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from sqlalchemy import Column, ForeignKey
from sqlalchemy.sql.sqltypes import String, Integer, Enum, JSON
from sqlalchemy.sql.sqltypes import String, Integer, Enum
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import relationship

Expand Down
2 changes: 1 addition & 1 deletion job-monitoring-app/backend/app/models/job.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from sqlalchemy import Column, ForeignKey, UniqueConstraint
from sqlalchemy.sql.sqltypes import String, Integer
from sqlalchemy.orm import relationship, backref
from sqlalchemy.orm import relationship

from .base import Base, DateMixin

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from sqlalchemy import Column, Enum, ForeignKey, UniqueConstraint
from sqlalchemy import Column, Enum, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql.sqltypes import Integer, String

Expand Down
3 changes: 1 addition & 2 deletions job-monitoring-app/backend/app/routers/api_keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@
get_db,
get_user_from_api_key,
API_KEY_HEADER_NAME,
get_current_user_from_token,
get_current_provider,
)
from app import schemas, services
from fastapi import APIRouter, Depends, Query
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

router = APIRouter()
Expand Down
2 changes: 1 addition & 1 deletion job-monitoring-app/backend/app/routers/events.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from app import schemas, services
from app.dependencies import get_db, get_user_from_api_key
from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

router = APIRouter()
Expand Down
4 changes: 2 additions & 2 deletions job-monitoring-app/backend/app/routers/job_configurations.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def get_job_configuration_by_id(
if job_configuration is None:
raise HTTPException(status_code=404, detail="Job not found")

if not (provider.id in [job_configuration.provider_id]):
if provider.id not in [job_configuration.provider_id]:
raise HTTPException(status_code=403, detail="Not allowed")

return job_configuration
Expand All @@ -53,7 +53,7 @@ def get_job_configurations_by_tag_and_version(
):
# case 1: get specific configuration if both tag and version are provided
should_get_specific_version_of_tag = tag and (
type(version) is str and version != "latest"
isinstance(version, str) and version != "latest"
)

if should_get_specific_version_of_tag:
Expand Down
4 changes: 2 additions & 2 deletions job-monitoring-app/backend/app/routers/jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def get_job(
if job is None:
raise HTTPException(status_code=404, detail="Job not found")

if not (user.id in [job.customer_id, job.provider_id]):
if user.id not in [job.customer_id, job.provider_id]:
# TODO: add job.provider_id to the list of allowed users that can
# access this once we have api key based access? See above comment
raise HTTPException(status_code=403, detail="Not allowed")
Expand All @@ -62,7 +62,7 @@ def get_job_events(
if job is None:
raise HTTPException(status_code=404, detail="Job not found")

if not (user.id in [job.customer_id, job.provider_id]):
if user.id not in [job.customer_id, job.provider_id]:
raise HTTPException(status_code=403, detail="Not allowed")

return job.events
5 changes: 2 additions & 3 deletions job-monitoring-app/backend/app/routers/reporting.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
from datetime import datetime, timedelta

from app import schemas, services
from app import services
from app.dependencies import get_db, get_current_provider
from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
import io
import pandas as pd
Expand Down
2 changes: 1 addition & 1 deletion job-monitoring-app/backend/app/schemas/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from enum import Enum
from typing import Dict, Optional, Union

from pydantic import BaseModel, Json
from pydantic import BaseModel

from .step_configuration import StepConfiguration

Expand Down
2 changes: 1 addition & 1 deletion job-monitoring-app/backend/app/schemas/job.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from datetime import datetime
from typing import List

from pydantic import BaseModel, StrictStr
from pydantic import BaseModel

from . import Event
from .job_configuration import JobConfiguration
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from datetime import datetime
from typing import List, Optional

from pydantic import StrictInt, StrictStr, conlist
from pydantic import StrictInt, StrictStr

from .metadata_configuration import MetadataConfiguration, MetadataConfigurationCreate
from .unique_tag import UniqueTagModel
Expand Down
1 change: 0 additions & 1 deletion job-monitoring-app/backend/app/services/api_keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

from datetime import datetime

from .users import get_user

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

Expand Down
1 change: 0 additions & 1 deletion job-monitoring-app/backend/app/services/events.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from app import models, schemas
from sqlalchemy import cast
from sqlalchemy.orm import Session

from .job_configuration import get_step_configuration_by_composite_key
Expand Down
2 changes: 1 addition & 1 deletion job-monitoring-app/backend/app/services/reporting.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import json
from datetime import datetime, timedelta
from datetime import datetime

from pydantic import BaseModel
from sqlalchemy.orm import Session
Expand Down
3 changes: 0 additions & 3 deletions job-monitoring-app/backend/conftest.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
import os
import random

import pytest
from app import schemas, services, models
from app.models.base import truncate_all_tables
Expand Down
Loading
Loading