Esempio n. 1
0
    def setUp(self) -> None:
        setup_server.setup_data()

        self.instance = Instance(
            a_instance.IDENTIFIER,
            Orthanc(setup_server.ORTHANC_URL)
        )
Esempio n. 2
0
    def setUp(self) -> None:
        setup_server.setup_data()

        self.study = Study(
            a_study.IDENTIFIER,
            Orthanc(setup_server.ORTHANC_URL)
        )
class TestOrthancPatientSetters(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        global orthanc_subprocess
        orthanc_subprocess = setup_server.setup_orthanc_server()

    @classmethod
    def tearDownClass(cls) -> None:
        global orthanc_subprocess
        setup_server.stop_orthanc_server_and_remove_data_directory(
            orthanc_subprocess)
        del orthanc_subprocess

    def setUp(self) -> None:
        self.orthanc = Orthanc(setup_server.ORTHANC_URL)

    def tearDown(self) -> None:
        self.orthanc = None
        setup_server.clear_data()

    def given_patient_in_orthanc_server(self):
        setup_server.setup_data()

    def test_givenOrthancWithAnUnprotectedPatient_whenSettingPatientToProtected_thenPatientIsProtected(
            self):
        self.given_patient_in_orthanc_server()

        self.orthanc.set_patient_to_protected(a_patient.IDENTIFIER)

        self.assertTrue(
            self.orthanc.get_if_patient_is_protected(a_patient.IDENTIFIER))

    def test_givenOrthancWithAnUnprotectedPatient_whenSettingPatientToNotProtected_thenPatientIsUnprotected(
            self):
        self.given_patient_in_orthanc_server()

        self.orthanc.set_patient_to_not_protected(a_patient.IDENTIFIER)

        self.assertFalse(
            self.orthanc.get_if_patient_is_protected(a_patient.IDENTIFIER))

    def test_givenOrthancWithoutPatient_whenSettingPatientToProtected_thenRaiseHTTPError(
            self):
        self.assertRaises(
            HTTPError, lambda: self.orthanc.set_patient_to_protected(
                a_patient.IDENTIFIER))

    def test_givenOrthancWithoutPatient_whenSettingPatientToNotProtected_thenRaiseHTTPError(
            self):
        self.assertRaises(
            HTTPError, lambda: self.orthanc.set_patient_to_not_protected(
                a_patient.IDENTIFIER))
class TestOrthancPatientDeleters(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        global orthanc_subprocess
        orthanc_subprocess = setup_server.setup_orthanc_server()

    @classmethod
    def tearDownClass(cls) -> None:
        global orthanc_subprocess
        setup_server.stop_orthanc_server_and_remove_data_directory(
            orthanc_subprocess)
        del orthanc_subprocess

    def setUp(self) -> None:
        self.orthanc = Orthanc(setup_server.ORTHANC_URL)

    def tearDown(self) -> None:
        self.orthanc = None
        setup_server.clear_data()

    def given_patient_in_orthanc_server(self):
        setup_server.setup_data()

    def test_givenOrthancWithPatient_whenDeletingPatientData_thenResultIsTrue(
            self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.delete_patient(a_patient.IDENTIFIER)

        self.assertTrue(result)

    def test_givenOrthancWithoutPatient_whenDeletingPatientData_thenResultIsFalse(
            self):
        result = self.orthanc.delete_patient(a_patient.IDENTIFIER)

        self.assertFalse(result)
Esempio n. 5
0
def retrieve_image(
    server: Orthanc,
    series_id: str,
    name: list = None,
    slice_idx=None,
    norm_range=True,
    convert_to_uint=None,
):

    if convert_to_uint is None:
        convert_to_uint = not norm_range
    zfile = zipfile.ZipFile(BytesIO(server.get_series_archives(series_id)))

    # return all elements if no name is given
    if name is None:
        name = zfile.namelist()

    try:
        name.remove("DICOMDIR")
    except ValueError:
        pass

    imgs = []

    for _name in name:
        with zfile.open(_name) as f:
            img = pydicom.read_file(f).pixel_array

        if norm_range:
            img = img - img.min()
            img = img / img.max()

        if convert_to_uint:
            img = ((img + 32768) / (32767 * 2 + 1)) * 255
            img = img.astype(np.uint8)

        if slice_idx is not None:
            img = img[slice_idx]
        imgs.append(img)

    if len(imgs) == 1:
        return imgs[0]
    else:
        return imgs
Esempio n. 6
0
    def setUp(self) -> None:
        setup_server.setup_data()

        self.series = Series(a_series.IDENTIFIER,
                             Orthanc(setup_server.ORTHANC_URL))
Esempio n. 7
0
        tqdm.write("Finished Patient %s" % pid)
    except Exception as e:
        return str(e)


if __name__ == "__main__":

    import sys

    base_out_dir = "/work/scratch/schock/Temp/FromOrthanc"
    valid_ids = ["0000000001"]

    series_number_mapping = {"00": "img", "01": "left", "02": "right"}
    instance_frame_mapping = {"femur": 0, "tibia": 1}

    orthanc = Orthanc("http://orthanc:8043")
    orthanc.setup_credentials(sys.argv[1], sys.argv[2])  # If needed

    patient_ids = []
    tqdm.write("Retrieve Patient IDs")
    for study_identifier in orthanc.get_studies():
        study_information = orthanc.get_study_information(study_identifier)
        study_id = study_information["MainDicomTags"]["StudyID"]
        patient_id = study_information["PatientMainDicomTags"]["PatientID"]
        if study_id in valid_ids:
            # Add Unique Patient ID and Readable (but possibly ambiguous)
            # Patient ID
            patient_ids.append(
                (study_information["ParentPatient"], patient_id))

    tqdm.write("Start Processing Patients")
Esempio n. 8
0
 def setUp(self) -> None:
     self.orthanc = Orthanc(setup_server.ORTHANC_URL)
     self.remote = RemoteModality(self.orthanc, MODALITY)
Esempio n. 9
0
class TestRemoteModality(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        global orthanc_subprocess
        global second_orthanc_subprocess
        orthanc_subprocess = setup_server.setup_orthanc_server()
        second_orthanc_subprocess = setup_server.setup_second_orthanc_server()

    @classmethod
    def tearDownClass(cls) -> None:
        global orthanc_subprocess
        global second_orthanc_subprocess
        setup_server.stop_orthanc_server_and_remove_data_directory(
            orthanc_subprocess)
        setup_server.stop_second_orthanc_server_and_remove_data_directory(
            second_orthanc_subprocess)
        del orthanc_subprocess
        del second_orthanc_subprocess

    def setUp(self) -> None:
        self.orthanc = Orthanc(setup_server.ORTHANC_URL)
        self.remote = RemoteModality(self.orthanc, MODALITY)

    def tearDown(self) -> None:
        self.orthanc = None
        self.remote = None
        setup_server.clear_data()
        setup_server.clear_data_of_second_orthanc()

    def given_patient_in_second_orthanc_server(self):
        setup_server.setup_data_for_second_orthanc()

    def test_whenDoingAnEcho_thenResultIsTrue(self):
        result = self.remote.echo()

        self.assertTrue(result)

    def test_givenDataInSecondServerAndPayload_whenQuerying_thenQueryHasExpectingContent(
            self):
        self.given_patient_in_second_orthanc_server()
        expected_query_answer_content = {
            '0008,0005': {
                'Name': 'SpecificCharacterSet',
                'Type': 'String',
                'Value': 'ISO_IR 100'
            },
            '0008,0050': {
                'Name': 'AccessionNumber',
                'Type': 'String',
                'Value': '20090926001'
            },
            '0008,0052': {
                'Name': 'QueryRetrieveLevel',
                'Type': 'String',
                'Value': 'STUDY'
            },
            '0010,0020': {
                'Name': 'PatientID',
                'Type': 'String',
                'Value': 'MP15-067'
            },
            '0020,000d': {
                'Name': 'StudyInstanceUID',
                'Type': 'String',
                'Value': '1.3.6.1.4.1.22213.2.6291.2.1'
            }
        }

        result = self.remote.query(PAYLOAD)

        self.assertIn('ID', result.keys())
        self.assertIn('Path', result.keys())
        self.assertEqual(
            expected_query_answer_content,
            self.orthanc.get_content_of_specified_query_answer(
                result['ID'], 0))

    def test_givenDataInSecondServerAndQuery_whenMoving_thenDataInSecondServerIsInFirstOrthancServer(
            self):
        self.given_patient_in_second_orthanc_server()
        cmove_data = {'TargetAet': 'FirstOrthanc'}
        expected_move_answer = {
            'Description': 'REST API',
            'LocalAet': 'FIRSTORTHANC',
            'RemoteAet': 'SECONDORTHANC'
        }

        query_result = self.remote.query(PAYLOAD)
        result = self.remote.move(query_result['ID'], cmove_data)

        try:
            del result[
                'Query']  # On some version of Orthanc, A Query field is there
        except KeyError:
            pass
        self.assertDictEqual(expected_move_answer, result)
        resulting_patient_information = self.orthanc.get_patient_information(
            self.orthanc.get_patients()[0])
        self.assertEqual(
            {
                k: v
                for k, v in PATIENT_INFORMATION.items() if k != 'LastUpdate'
            }, {
                k: v
                for k, v in resulting_patient_information.items()
                if k != 'LastUpdate'
            })
Esempio n. 10
0
 def __init__(self):
     self.orthanc = Orthanc(Config.get('pacs_adres'))
     self.orthanc.setup_credentials(Config.get('pacs_login'),
                                    Config.get('pacs_password'))
Esempio n. 11
0
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

import tkinter as tk
from tkinter import filedialog, ttk
from pathlib import Path
from distutils.dir_util import copy_tree
import subprocess, json, threading, time, datetime, zipfile, os
import concurrent.futures
from pyorthanc import Orthanc

orthanc = Orthanc('http://localhost:8042')

name = "genii"


# helper class for common gui widgets
class Elements:
    def __init__(self, master):
        self.master = master

    # method for all button processes
    def button(self, char, funct, lambdaVal, x_, y_, algn, rows):
        if lambdaVal == '':
            self.b = tk.Button(self.master, text=char, command=funct)
        else:
            self.b = tk.Button(self.master,
Esempio n. 12
0
from pyorthanc import Orthanc
orthanc = Orthanc('http://localhost:8042')

# To get patients identifier and main information
patients_identifiers = orthanc.get_patients()

for patient_identifier in patients_identifiers:
    patient = orthanc.get_patient_information(patient_identifier)
    patient_name = patient['MainDicomTags']['PatientID']
    study_identifiers = patient['Studies']


    fName = patient_name+'.zip'
    print(fName)
    bytes_content = orthanc.archive_patient(patient['ID'])
    with open(fName, 'wb') as file_handler:
        file_handler.write(bytes_content)
class TestOrthancPatientPosts(unittest.TestCase):
    @classmethod
    def setUpClass(cls) -> None:
        global orthanc_subprocess
        orthanc_subprocess = setup_server.setup_orthanc_server()

    @classmethod
    def tearDownClass(cls) -> None:
        global orthanc_subprocess
        setup_server.stop_orthanc_server_and_remove_data_directory(
            orthanc_subprocess)
        del orthanc_subprocess

    def setUp(self) -> None:
        self.orthanc = Orthanc(setup_server.ORTHANC_URL)

    def tearDown(self) -> None:
        self.orthanc = None
        setup_server.clear_data()

    def given_patient_in_orthanc_server(self):
        setup_server.setup_data()

    def test_givenOrthancWithAPatient_whenAnonymizeAPatient_thenResultIsIdentifiersOfNewAnonymousPatientAndANewAnonymousPatientIsCreated(
            self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.anonymize_patient(a_patient.IDENTIFIER)

        self.assertIsInstance(result, dict)
        self.assertIn('ID', result.keys())
        self.assertIn('Path', result.keys())
        self.assertIn('PatientID', result.keys())
        self.assertIn(result['ID'], self.orthanc.get_patients())
        self.assertEqual(
            'Anonymized1',
            self.orthanc.get_patient_information(
                result['ID'])['MainDicomTags']['PatientName'])

    def test_givenOrthancWithoutAPatient_whenAnonymizeAPatient_thenRaiseHTTPError(
            self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.anonymize_patient(a_patient.IDENTIFIER))

    def test_givenOrthancWithAPatient_whenArchivingAPatient_thenResultIsBytesOfAValidZipFile(
            self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.archive_patient(a_patient.IDENTIFIER)

        self.assertIsInstance(result, bytes)
        with open(a_patient.ZIP_FILE_PATH, 'wb') as file_handler:
            file_handler.write(result)

        a_zip_file = zipfile.ZipFile(a_patient.ZIP_FILE_PATH)
        self.assertIsNone(a_zip_file.testzip())
        os.remove(a_patient.ZIP_FILE_PATH)

    def test_givenOrthancWithoutAPatient_whenArchivingAPatient_thenRaiseHTTPError(
            self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.archive_patient(a_patient.IDENTIFIER))
Esempio n. 14
0
 def setUp(self) -> None:
     setup_server.setup_data()
     self.patient = Patient(a_patient.IDENTIFIER,
                            Orthanc(setup_server.ORTHANC_URL))
Esempio n. 15
0
class TestOrthancPatientGetters(unittest.TestCase):

    @classmethod
    def setUpClass(cls) -> None:
        global orthanc_subprocess
        orthanc_subprocess = setup_server.setup_orthanc_server()

    @classmethod
    def tearDownClass(cls) -> None:
        global orthanc_subprocess
        setup_server.stop_orthanc_server_and_remove_data_directory(orthanc_subprocess)
        del orthanc_subprocess

    def setUp(self) -> None:
        self.orthanc = Orthanc(setup_server.ORTHANC_URL)

    def tearDown(self) -> None:
        self.orthanc = None
        setup_server.clear_data()

    def given_patient_in_orthanc_server(self):
        setup_server.setup_data()

    def test_givenOrthancWithPatient_whenGettingPatients_thenResultIsANonEmptyListOfPatientIdentifier(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_patients()

        self.assertIsInstance(result, list)
        self.assertIn(a_patient.IDENTIFIER, result)

    def test_givenOrthancWithoutPatient_whenGettingPatients_thenResultIsAnEmptyList(self):
        result = self.orthanc.get_patients()

        self.assertIsInstance(result, list)
        self.assertEqual(len(result), 0)

    def test_givenOrthancWithPatient_whenGettingPatientInformation_thenResultIsADictionaryOfPatientInformation(self):
        self.given_patient_in_orthanc_server()
        keys_to_remove = ['LastUpdate']  # Removing keys that are never the same

        result = self.orthanc.get_patient_information(a_patient.IDENTIFIER)

        self.assertIsInstance(result, dict)
        result = {key: value for key, value in result.items() if key not in keys_to_remove}
        expected = {key: value for key, value in a_patient.INFORMATION.items() if key not in keys_to_remove}
        self.assertDictEqual(result, expected)

    def test_givenOrthancWithoutPatient_whenGettingPatientInformation_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_patient_information(a_patient.IDENTIFIER)
        )

    def test_givenOrthancWithPatient_whenGettingPatientZip_thenResultIsBytesOfAValidZipFile(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_patient_zip(a_patient.IDENTIFIER)

        self.assertIsInstance(result, bytes)
        with open(a_patient.ZIP_FILE_PATH, 'wb') as file_handler:
            file_handler.write(result)

        a_zip_file = zipfile.ZipFile(a_patient.ZIP_FILE_PATH)
        self.assertIsNone(a_zip_file.testzip())
        os.remove(a_patient.ZIP_FILE_PATH)

    def test_givenOrthancWithoutPatient_whenGettingPatientZip_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_patient_zip(a_patient.IDENTIFIER)
        )

    def test_givenOrthancWithPatient_whenGettingPatientInstances_thenResultIsAListOfPatientInstanceInformation(self):
        self.given_patient_in_orthanc_server()
        keys_to_remove = {'FileUuid'}  # Removing keys that are never the same

        result = self.orthanc.get_patient_instances(a_patient.IDENTIFIER)

        self.assertIsInstance(result, list)
        result = [{key: value for key, value in i.items() if key not in keys_to_remove} for i in result]
        expected = [{key: value for key, value in i.items() if key not in keys_to_remove} for i in a_patient.INSTANCES]
        self.assertCountEqual(result, expected)

    def test_givenOrthancWithoutPatient_whenGettingPatientInstances_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_patient_instances(a_patient.IDENTIFIER)
        )

    def test_givenOrthancWithPatient_whenGettingPatientInstancesTags_thenResultIsADictOfPatientInstancesTags(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_patient_instances_tags(a_patient.IDENTIFIER)

        self.assertEqual(result, a_patient.INSTANCE_TAGS)

    def test_givenOrthancWithoutPatient_whenGettingPatientInstancesTags_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_patient_instances_tags(a_patient.IDENTIFIER)
        )

    def test_givenOrthancWithPatient_whenGettingPatientInstancesTagsInSimplifiedVersion_thenResultIsADictOfPatientInstancesTagsInSimplifiedVersion(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_patient_instances_tags_in_simplified_version(a_patient.IDENTIFIER)

        self.assertEqual(result, a_patient.INSTANCE_TAGS_IN_SIMPLIFIED_VERSION)

    def test_givenOrthancWithoutPatient_whenGettingPatientInstancesTagsInSimplifiedVersion_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_patient_instances_tags_in_simplified_version(a_patient.IDENTIFIER)
        )

    def test_givenOrthancWithPatient_whenGettingPatientInstancesTagsInShorterVersion_thenResultIsADictOfPatientInstancesTagsInShorterVersion(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_patient_instances_tags_in_shorter_version(a_patient.IDENTIFIER)

        self.assertEqual(result, a_patient.INSTANCE_TAGS_IN_SHORTER_VERSION)

    def test_givenOrthancWithoutPatient_whenGettingPatientInstancesTagsInShorterVersion_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_patient_instances_tags_in_shorter_version(a_patient.IDENTIFIER)
        )

    def test_givenOrthancWithPatient_whenGettingPatientArchive_thenResultIsBytesOfAValidZipFileOfPatientArchive(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_patient_archive(a_patient.IDENTIFIER)

        with open(a_patient.ZIP_FILE_PATH, 'wb') as file_handler:
            file_handler.write(result)

        a_zip_file = zipfile.ZipFile(a_patient.ZIP_FILE_PATH)
        self.assertIsNone(a_zip_file.testzip())
        os.remove(a_patient.ZIP_FILE_PATH)

    def test_givenOrthancWithoutPatient_whenGettingPatientArchive_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_patient_archive(a_patient.IDENTIFIER)
        )

    def test_givenOrthancWithPatient_whenGettingPatientModule_thenResultIsExpectedTagInExpectedFormat(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_patient_module(a_patient.IDENTIFIER)

        self.assertEqual(result, a_patient.MODULE)

    def test_givenOrthancWithoutPatient_whenGettingPatientModule_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_patient_module(a_patient.IDENTIFIER)
        )

    def test_givenOrthancWithPatient_whenGettingPatientModuleInSimplifiedVersion_thenResultIsExpectedTagInExpectedFormat(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_patient_module_in_simplified_version(a_patient.IDENTIFIER)

        self.assertEqual(result, a_patient.MODULE_IN_SIMPLIFIED_VERSION)

    def test_givenOrthancWithoutPatient_whenGettingPatientModuleInSimplifiedVersion_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_patient_module_in_simplified_version(a_patient.IDENTIFIER)
        )

    def test_givenOrthancWithPatient_whenGettingPatientModuleInShorterVersion_thenResultIsExpectedTagInExpectedFormat(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_patient_module_in_shorter_version(a_patient.IDENTIFIER)

        self.assertEqual(result, a_patient.MODULE_IN_SHORTER_VERSION)

    def test_givenOrthancWithoutPatient_whenGettingPatientModuleInShorterVersion_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_patient_module_in_shorter_version(a_patient.IDENTIFIER)
        )

    def test_givenOrthancWithUnprotectedPatient_whenGettingIfPatientIsProtected_thenResultIsFalse(self):
        self.given_patient_in_orthanc_server()
        self.orthanc.set_patient_to_not_protected(a_patient.IDENTIFIER)

        result = self.orthanc.get_if_patient_is_protected(a_patient.IDENTIFIER)

        self.assertFalse(result)

    def test_givenOrthancWithProtectedPatient_whenGettingIfPatientIsProtected_thenResultIsTrue(self):
        self.given_patient_in_orthanc_server()
        self.orthanc.set_patient_to_protected(a_patient.IDENTIFIER)

        result = self.orthanc.get_if_patient_is_protected(a_patient.IDENTIFIER)

        self.assertTrue(result)

    def test_givenOrthancWithAPatient_whenGettingPatientSeries_thenResultIsAListOfPatientSeriesMainInformation(self):
        self.given_patient_in_orthanc_server()
        keys_to_remove = ['LastUpdate']  # Removing keys that are never the same

        result = self.orthanc.get_patient_series(a_patient.IDENTIFIER)

        self.assertIsInstance(result, list)
        result = [{key: value for key, value in i.items() if key not in keys_to_remove} for i in result]
        expected = [{key: value for key, value in i.items() if key not in keys_to_remove} for i in a_patient.SERIES]
        self.assertCountEqual(result, expected)

    def test_givenOrthancWithoutPatient_whenGettingPatientSeries_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_patient_series(a_patient.IDENTIFIER)
        )

    def test_givenOrthancWithAPatient_whenGettingPatientSharedTags_thenResultIsExpectedTagsInExpectedFormat(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_patient_shared_tags(a_patient.IDENTIFIER)

        self.assertEqual(result, a_patient.SHARED_TAGS)

    def test_givenOrthancWithoutPatient_whenGettingPatientSharedTags_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_patient_shared_tags(a_patient.IDENTIFIER)
        )

    def test_givenOrthancWithAPatient_whenGettingPatientSharedTagsInSimplifiedVersion_thenResultIsExpectedTagsInExpectedFormat(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_patient_shared_tags_in_simplified_version(a_patient.IDENTIFIER)

        self.assertEqual(result, a_patient.SHARED_TAGS_IN_SIMPLIFIED_VERSION)

    def test_givenOrthancWithoutPatient_whenGettingPatientSharedTagsInSimplifiedVersion_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_patient_shared_tags_in_simplified_version(a_patient.IDENTIFIER)
        )

    def test_givenOrthancWithAPatient_whenGettingPatientSharedTagsInShorterVersion_thenResultIsExpectedTagsInExpectedFormat(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_patient_shared_tags_in_shorter_version(a_patient.IDENTIFIER)

        self.assertEqual(result, a_patient.SHARED_TAGS_IN_SHORTER_VERSION)

    def test_givenOrthancWithoutPatient_whenGettingPatientSharedTagsInShorterVersion_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_patient_shared_tags_in_shorter_version(a_patient.IDENTIFIER)
        )

    def test_givenOrthancWithPatient_whenGettingPatientStatistics_thenResultIsExpectedPatientStatistics(self):
        self.given_patient_in_orthanc_server()
        keys_to_remove = ['DiskSize', 'UncompressedSize']  # Removing keys that are never the same

        result = self.orthanc.get_patient_statistics(a_patient.IDENTIFIER)

        self.assertIsInstance(result, dict)
        result = {key: value for key, value in result.items() if key not in keys_to_remove}
        expected = {key: value for key, value in a_patient.STATISTICS.items() if key not in keys_to_remove}
        self.assertDictEqual(result, expected)

    def test_givenOrthancWithoutPatient_whenGettingPatientStatistics_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_patient_statistics(a_patient.IDENTIFIER)
        )

    def test_givenOrthancWithPatient_whenGettingPatientStudiesInformation_thenResultIsExpectedPatientStudiesInformation(self):
        self.given_patient_in_orthanc_server()
        keys_to_remove = ['LastUpdate']  # Removing keys that are never the same

        result = self.orthanc.get_patient_studies_information(a_patient.IDENTIFIER)

        self.assertIsInstance(result, list)
        result = [self._sort_dictionary_element({key: value for key, value in i.items() if key not in keys_to_remove}) for i in result]
        expected = [self._sort_dictionary_element({key: value for key, value in i.items() if key not in keys_to_remove}) for i in a_patient.STUDIES]
        self.assertCountEqual(result, expected)

    def test_givenOrthancWithoutPatient_whenGettingPatientStudiesInformation_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_patient_studies_information(a_patient.IDENTIFIER)
        )

    def _sort_dictionary_element(self, dictionary: Dict) -> Dict:
        for key, value in dictionary.items():
            if type(value) == list:
                dictionary[key] = value.sort()

            elif type(value) == dict:
                dictionary[key] = self._sort_dictionary_element(value)

        return dictionary
class TestOrthancStudyGetters(unittest.TestCase):

    @classmethod
    def setUpClass(cls) -> None:
        global orthanc_subprocess
        orthanc_subprocess = setup_server.setup_orthanc_server()

    @classmethod
    def tearDownClass(cls) -> None:
        global orthanc_subprocess
        setup_server.stop_orthanc_server_and_remove_data_directory(orthanc_subprocess)
        del orthanc_subprocess

    def setUp(self) -> None:
        self.orthanc = Orthanc(setup_server.ORTHANC_URL)

    def tearDown(self) -> None:
        self.orthanc = None
        setup_server.clear_data()

    def given_patient_in_orthanc_server(self):
        setup_server.setup_data()

    def test_givenOrthancWithPatient_whenGettingStudies_thenResultIsANonEmptyListOfStudyIdentifiers(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_studies()

        self.assertIsInstance(result, list)
        self.assertIn(a_study.IDENTIFIER, result)

    def test_givenOrthancWithoutPatient_whenGettingStudies_thenResultIsAnEmptyList(self):
        result = self.orthanc.get_studies()

        self.assertIsInstance(result, list)
        self.assertEqual(len(result), 0)

    def test_givenOrthancWithAPatient_whenGettingStudies_thenResultIsExpectedStudyInformation(self):
        self.given_patient_in_orthanc_server()
        keys_to_exclude = {'LastUpdate'}

        result = self.orthanc.get_study_information(a_study.IDENTIFIER)

        self.assertIsInstance(result, dict)
        self.assertDictEqual(
            {key: value.sort() if type(value) == list else value for key, value in result.items() if key not in keys_to_exclude},
            {key: value.sort() if type(value) == list else value for key, value in a_study.INFORMATION.items() if key not in keys_to_exclude},
        )

    def test_givenOrthancWithoutPatient_whenGettingStudies_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_study_information(a_study.IDENTIFIER)
        )

    def test_givenOrthancWithPatient_whenGettingStudyZip_thenResultIsBytesOfAValidZipFile(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_study_zip_file(a_study.IDENTIFIER)

        self.assertIsInstance(result, bytes)
        with open(a_study.ZIP_FILE_PATH, 'wb') as file_handler:
            file_handler.write(result)

        a_zip_file = zipfile.ZipFile(a_study.ZIP_FILE_PATH)
        self.assertIsNone(a_zip_file.testzip())
        os.remove(a_study.ZIP_FILE_PATH)

    def test_givenOrthancWithoutPatient_whenGettingStudyZip_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_study_zip_file(a_study.IDENTIFIER)
        )

    def test_givenOrthancWithPatient_whenGettingStudyInstances_thenResultIsAListOfStudyInstanceInformation(self):
        self.given_patient_in_orthanc_server()
        keys_to_exclude = {'FileUuid', 'FileSize'}  # Removing keys that are never the same

        result = self.orthanc.get_study_instances(a_study.IDENTIFIER)

        self.assertIsInstance(result, list)
        result = [{key: value for key, value in i.items() if key not in keys_to_exclude} for i in result]
        expected = [{key: value for key, value in i.items() if key not in keys_to_exclude} for i in a_study.INSTANCES]
        self.assertCountEqual(result, expected)

    def test_givenOrthancWithoutPatient_whenGettingStudyInstances_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_study_instances(a_study.IDENTIFIER)
        )

    def test_givenOrthancWithPatient_whenGettingStudyInstancesTags_thenResultIsADictOfStudyInstancesTags(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_study_instances_tags(a_study.IDENTIFIER)

        self.assertEqual(result, a_study.INSTANCE_TAGS)

    def test_givenOrthancWithoutPatient_whenGettingStudyInstancesTags_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_study_instances_tags(a_study.IDENTIFIER)
        )

    def test_givenOrthancWithPatient_whenGettingStudyInstancesTagsInSimplifiedVersion_thenResultIsADictOfPatientInstancesTagsInSimplifiedVersion(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_study_instances_tags_in_simplified_version(a_study.IDENTIFIER)

        self.assertEqual(result, a_study.INSTANCE_TAGS_IN_SIMPLIFIED_VERSION)

    def test_givenOrthancWithoutPatient_whenGettingStudyInstancesTagsInSimplifiedVersion_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_study_instances_tags_in_simplified_version(
                a_study.IDENTIFIER
            )
        )

    def test_givenOrthancWithPatient_whenGettingStudyInstancesTagsInShorterVersion_thenResultIsADictOfPatientInstancesTagsInShorterVersion(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_study_instances_tags_in_shorter_version(a_study.IDENTIFIER)

        self.assertEqual(result, a_study.INSTANCE_TAGS_IN_SHORTER_VERSION)

    def test_givenOrthancWithoutPatient_whenGettingStudyInstancesTagsInShorterVersion_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_study_instances_tags_in_shorter_version(a_study.IDENTIFIER)
        )

    def test_givenOrthancWithPatient_whenGettingStudyArchive_thenResultIsBytesOfAValidZipFileOfStudyArchive(self):
        self.given_patient_in_orthanc_server()

        result = self.orthanc.get_patient_archive(a_study.IDENTIFIER)

        with open(a_study.ZIP_FILE_PATH, 'wb') as file_handler:
            file_handler.write(result)

        a_zip_file = zipfile.ZipFile(a_study.ZIP_FILE_PATH)
        self.assertIsNone(a_zip_file.testzip())
        os.remove(a_study.ZIP_FILE_PATH)

    def test_givenOrthancWithoutPatient_whenGettingStudyArchive_thenRaiseHTTPError(self):
        self.assertRaises(
            HTTPError,
            lambda: self.orthanc.get_patient_archive(a_study.IDENTIFIER)
        )
Esempio n. 17
0
 def setUp(self) -> None:
     self.orthanc = Orthanc(setup_server.ORTHANC_URL)
Esempio n. 18
0
class PACS_OrthancServerCtrl(PACS_ServerCtrl):
    def __init__(self):
        self.orthanc = Orthanc(Config.get('pacs_adres'))
        self.orthanc.setup_credentials(Config.get('pacs_login'),
                                       Config.get('pacs_password'))

    def isConnect(self) -> bool:
        return True

    def find(self):
        result = []
        patients_identifiers = self.orthanc.get_patients()
        for patient_identifier in patients_identifiers:
            patient_information = self.orthanc.get_patient_information(
                patient_identifier)
            id = patient_information['ID']
            patient_id = patient_information['MainDicomTags'].get(
                'PatientID', '---')
            patient_name = patient_information['MainDicomTags'].get(
                'PatientName', '---')
            patient_sex = patient_information['MainDicomTags'].get(
                'PatientSex', '---')

            result.append([id, patient_id, patient_name, patient_sex])

        return result

    def find_study(self, patient_id):
        result = []
        patient_information = self.orthanc.get_patient_information(patient_id)
        study_identifiers = patient_information['Studies']

        for study_identifier in study_identifiers:
            study_information = self.orthanc.get_study_information(
                study_identifier)

            id = study_information['ID']
            study_date = study_information['MainDicomTags'].get(
                'StudyDate', ' --- ')
            describe = study_information['MainDicomTags'].get(
                'StudyDescription', '---')
            institution = study_information['MainDicomTags'].get(
                'InstitutionName', '----')

            result.append([id, study_date, describe, institution])

        return result

    def find_series(self, study_id) -> list:
        result = []
        study_information = self.orthanc.get_study_information(study_id)
        series_identifiers = study_information['Series']
        for series_identifier in series_identifiers:
            series_information = self.orthanc.get_series_information(
                series_identifier)

            id = series_information['ID']
            modality = series_information['MainDicomTags'].get(
                'Modality', '---')
            protocol = series_information['MainDicomTags'].get(
                'ProtocolName', '---')
            imagesAmount = series_information['MainDicomTags'].get(
                'ImagesInAcquisition', '---')

            result.append([id, modality, protocol, imagesAmount])
        return result

    def find_instance(self, series_id: str) -> list:
        result = []
        series_information = self.orthanc.get_series_information(series_id)
        instance_identifiers = series_information['Instances']
        for instance_identifier in instance_identifiers:
            instance_information = self.orthanc.get_instance_information(
                instance_identifier)
            result.append({
                'ID':
                instance_information['ID'],
                'ParentSeries':
                instance_information['ParentSeries'],
                'IndexInSeries':
                instance_information['IndexInSeries']
            })

        return result

    def move(self, instance_id: str, path: str):
        instance = Instance(instance_id, self.orthanc)
        dicom = instance.get_dicom_file_content()

        with open(path + '.dcm', 'wb+') as file_handler:
            file_handler.write(dicom)

    def store(self):
        pass