Best Python code snippet using tempest_python
Series.py
Source:Series.py
1import logging2import os3import zipfile4import json5import sys6import pydicom as dicom7import SimpleITK as sitk8import numpy as np9from classes.Volume import Volume10from pydicom.dataset import Dataset, FileDataset11class Series(object):12 series_id = None13 study_id = None14 metrics = None # ?15 image = None16 series_info = None17 loaded = None18 def __init__(self):19 super().__init__()20 self.series_info = dict([21 ('PatientID', 0),22 ('PatientName', 0),23 ('PatientSex', 0),24 ('PatientAge', 0),25 ('PatientBirthDate', 0),26 ('ContentDate', 0),27 ('ContrastBolusAgent', 0),28 ('ContrastBolusRoute', 0),29 ('Manufacturer', 0),30 ('ManufacturerModelName', 0)31 ])32 self.loaded = False33 self.miniature = None34 self.list_volumes = []35 self.path_to_series = ''36 def download_series(self, folder):37 if folder.type == 'pacs':38 self.parse_dataset(folder)39 elif folder.type == 'folder':40 self.from_folder(folder)41 def parse_dataset(self, dt):42 if type(dt) is Dataset:43 try:44 self.image = None45 except Exception as e:46 print(e)47 else:48 print('It not need type')49 def from_folder(self, path_to_series):50 current_path = os.getcwd()51 try:52 self.path_to_series = path_to_series53 series_reader = sitk.ImageSeriesReader()54 os.chdir(path_to_series)55 dicom_files_name = series_reader.GetGDCMSeriesFileNames('./')56 series_reader.SetFileNames(dicom_files_name)57 image = series_reader.Execute()58 os.chdir(current_path)59 meta_info = dicom.read_file('%s/%s' % (path_to_series, dicom_files_name[0]))60 self.meta_load(meta_info)61 self.image = np.array(sitk.GetArrayFromImage(image)[::-1], dtype=np.int16)62 self.series_info.update({'ImagesNumber': len(self.image),63 'ImageShape': self.image.shape[1:]})64 self.miniature = self.image[len(self.image) // 2] // 10 + 10065 self.loaded = True66 if 'series_info.json' in os.listdir(path_to_series):67 self.json_decode()68 except Exception as e:69 os.chdir(current_path)70 print(path_to_series, self.loaded)71 print(e)72 def meta_load(self, meta_data):73 try:74 if type(meta_data) is FileDataset:75 for key, _ in self.series_info.items():76 value = getattr(meta_data, key, '')77 if type(value) not in (str, int, float):78 value = str(value)79 if key == 'ContentDate' or key == 'PatientBirthDate':80 value = '.'.join([value[6:], value[4:6], value[:4]])81 self.series_info.update({key: value})82 x, y = getattr(meta_data, 'PixelSpacing', [1, 1])83 z_t = float(getattr(meta_data, 'SliceThickness', 2))84 z_s = float(getattr(meta_data, 'spacingBetweenSlices', 0))85 self.metrics = np.array([z_t + z_s, float(y), float(x)])86 self.series_info.update({'SliceThickness': z_t})87 self.series_id = getattr(meta_data, 'SeriesInstanceUID', -1)88 self.study_id = getattr(meta_data, 'StudyInstanceUID', -1)89 except Exception as e:90 print(e)91 def add_value(self, coordinate, size=None, type_volume=None, probability=None, is_doctor=False, is_confirmed=False):92 if coordinate is not None:93 try:94 self.list_volumes.append(Volume(coordinate, size, type_volume, probability, is_doctor, is_confirmed))95 except Exception as e:96 print('add_value', e)97 def get_series_info(self):98 return self.series_info99 def get_metric(self):100 return self.metrics101 def get_image(self):102 return self.image103 def get_study_id(self):104 return self.study_id105 def get_series_id(self):106 return self.series_id107 def get_status(self):108 return self.loaded109 def get_miniature(self):110 return self.miniature111 def get_list_contour_from_doctor(self):112 return [volume.get_coordinate() for volume in self.list_volumes if volume.is_doctor]113 def get_volume_size(self, coordinate):114 try:115 point_number = len(np.argwhere(self.image[coordinate[0, 0]:coordinate[1, 0],116 coordinate[0, 1]:coordinate[1, 1],117 coordinate[0, 2]:coordinate[1, 2]] > -150))118 point_number *= self.metrics.prod()119 return int(point_number)120 except Exception as e:121 print(e, 'get_volume_size')122 def get_volume_from_point(self, z, x, y):123 for volume in self.list_volumes:124 if volume.is_point_in_coordinate(z, x, y):125 return volume.json_code()126 def delete_volume_from_point(self, z, x, y):127 for volume, i in zip(self.list_volumes, range(len(self.list_volumes))):128 if volume.is_point_in_coordinate(z, x, y):129 self.list_volumes.pop(i)130 def save_series(self):131 try:132 if self.path_to_series != '':133 jsonfile = open(self.path_to_series + '/series_info.json', 'w')134 json.dump(self.json_code(), jsonfile)135 return True136 else:137 return False138 except Exception as e:139 print(e, 'save_series')140 return False141 def series_to_send_zip(self):142 current_dir = os.getcwd()143 try:144 zipf = zipfile.ZipFile('tmp/%s.zip' % self.series_id, 'w', zipfile.ZIP_DEFLATED)145 self.save_series()146 os.chdir(self.path_to_series)147 for file in os.listdir(self.path_to_series):148 if '.dcm' in file or '.json' in file:149 zipf.write(file)150 zipf.close()151 os.chdir(current_dir)152 return 'tmp/%s.zip' % self.series_id153 except Exception as e:154 os.chdir(current_dir)155 print(e, 'series_to_send_zip')156 def json_code(self):157 try:158 list_volumes = [volume.json_code() for volume in self.list_volumes]159 file = {160 'Type': 'series',161 'SeriesID': self.series_id,162 'StudyID': self.study_id,163 'Information': self.series_info,164 'Metrics': self.metrics.tolist(),165 'Volumes': list_volumes166 }167 return file168 except Exception as e:169 print(e, 'json_code')170 return None171 def json_decode(self):172 try:173 file_name = '%s/series_info.json' % self.path_to_series174 with open(file_name, 'r') as json_file:175 file = json.load(json_file)176 self.series_from_dict(file)177 except Exception as e:178 print(e, 'json_decode')179 def series_from_dict(self, file):180 try:181 # self.series_id = file['SeriesID']182 # self.study_id = file['StudyID']183 # self.series_info = file['Information']184 self.metrics = np.array(file['Metrics'])185 list_volume = file['Volumes']186 for volume in list_volume:187 try:188 self.add_value(volume['coordinate'], volume['volume_size'], volume['volume_type'],189 volume['probability'], volume['is_doctor'], volume['is_confirmed'])190 if volume['information'] != dict([]):191 self.list_volumes[-1].set_information(volume['information'])192 except Exception as e:193 print(e, 'series_from_dict, for')194 except Exception as e:...
Launcher.py
Source:Launcher.py
1import os2import sys3import docker4from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QListWidget, QFileDialog, \5 QMainWindow, QWidget, QListWidgetItem, QApplication6from PyQt5.QtCore import Qt7class Launcher(QMainWindow):8 def __init__(self):9 super().__init__()10 self.setWindowTitle("dti_launcher")11 self.main_layout = MainLayout(self)12 self.setCentralWidget(self.main_layout)13 self.setGeometry(100, 100, 500, 500)14 self.show()15class MainLayout(QWidget):16 def __init__(self, parent):17 super().__init__(parent)18 self.volumes = dict()19 layout = QVBoxLayout(self)20 # X Server IP21 lbl_ip = QLabel(self)22 lbl_ip.setText("X-Server IP address")23 layout.addWidget(lbl_ip)24 ip_layout = QHBoxLayout(self)25 self.txt_ip_1 = self.add_text_ip("172", 3)26 ip_layout.addWidget(self.txt_ip_1)27 ip_layout.addWidget(QLabel(".", self))28 self.txt_ip_2 = self.add_text_ip("20", 3)29 ip_layout.addWidget(self.txt_ip_2)30 ip_layout.addWidget(QLabel(".", self))31 self.txt_ip_3 = self.add_text_ip("140", 3)32 ip_layout.addWidget(self.txt_ip_3)33 ip_layout.addWidget(QLabel(".", self))34 self.txt_ip_4 = self.add_text_ip("113", 3)35 ip_layout.addWidget(self.txt_ip_4)36 ip_layout.addWidget(QLabel(":", self))37 self.txt_ip_5 = self.add_text_ip("0", 4)38 ip_layout.addWidget(self.txt_ip_5)39 ip_layout.addWidget(QLabel(".", self))40 self.txt_ip_6 = self.add_text_ip("0", 4)41 ip_layout.addWidget(self.txt_ip_6)42 ip_layout.addStretch()43 layout.addLayout(ip_layout)44 # volume mapping45 layout.addStretch()46 layout.addWidget(QLabel("Volume mapping", self))47 host_layout = QHBoxLayout(self)48 host_layout.addWidget(QLabel("Host: ", self))49 self.txt_host = QLineEdit("", self)50 self.txt_host.setReadOnly(True)51 host_layout.addWidget(self.txt_host)52 self.btn_get_folder = QPushButton(self)53 self.btn_get_folder.setText("Get")54 self.btn_get_folder.clicked.connect(self.get_folder)55 host_layout.addWidget(self.btn_get_folder)56 layout.addLayout(host_layout)57 docker_layout = QHBoxLayout(self)58 docker_layout.addWidget(QLabel("Docker: ", self))59 self.txt_docker = QLineEdit("/mnt/data", self)60 self.txt_docker.setReadOnly(True)61 docker_layout.addWidget(self.txt_docker)62 layout.addLayout(docker_layout)63 self.btn_add = QPushButton(self)64 self.btn_add.setText("Add")65 self.btn_add.clicked.connect(self.add_folder)66 layout.addWidget(self.btn_add)67 self.btn_rem = QPushButton(self)68 self.btn_rem.setText("Remove")69 self.btn_rem.clicked.connect(self.rem_folder)70 layout.addWidget(self.btn_rem)71 self.list_volumes = QListWidget(self)72 layout.addWidget(self.list_volumes)73 lbl_list = QLabel("data folder on host computer || data folder in the docker container")74 lbl_list.setAlignment(Qt.AlignCenter)75 layout.addWidget(lbl_list)76 # Launch Button77 self.btn_launch = QPushButton(self)78 self.btn_launch.setText("Launch")79 self.btn_launch.clicked.connect(self.launch)80 layout.addStretch()81 layout.addWidget(self.btn_launch)82 self.setLayout(layout)83 def add_text_ip(self, string, max_length):84 txt_ip = QLineEdit(string, self)85 txt_ip.setMaxLength(max_length)86 txt_ip.setFixedWidth(40)87 txt_ip.setAlignment(Qt.AlignCenter)88 return txt_ip89 def get_folder(self):90 dlg = QFileDialog(self)91 dlg.setFileMode(QFileDialog.Directory)92 dlg.setWindowTitle("Select data directory")93 if dlg.exec_():94 files = dlg.selectedFiles()95 if self.validate_host_dir(files[0]):96 self.txt_host.setText(files[0])97 @staticmethod98 def validate_host_dir(directory):99 if os.path.isdir(directory):100 return True101 else:102 return False103 def add_folder(self):104 if self.validate_host_dir(self.txt_host.text()):105 item = QListWidgetItem()106 item.setTextAlignment(Qt.AlignCenter)107 if self.txt_docker.text()[0] != "/":108 self.txt_docker.setText("/" + self.txt_docker.text())109 item.setText(self.txt_host.text() + " || " + self.txt_docker.text())110 self.list_volumes.addItem(item)111 self.txt_host.setText("")112 self.txt_host.setReadOnly(False)113 self.txt_docker.setText("")114 self.txt_docker.setReadOnly(False)115 def rem_folder(self):116 for item in self.list_volumes.selectedItems():117 self.list_volumes.takeItem(self.list_volumes.row(item))118 if self.list_volumes.count() == 0:119 self.txt_docker.setText("/mnt/data")120 self.txt_docker.setReadOnly(True)121 def launch(self):122 display_env = ["DISPLAY=" + self.txt_ip_1.text() + "."123 + self.txt_ip_2.text() + "." + self.txt_ip_3.text() + "."124 + self.txt_ip_4.text() + ":"125 + self.txt_ip_5.text() + "." + self.txt_ip_6.text(), 'USER=neuro']126 volumes = dict()127 for count in range(self.list_volumes.count()):128 str_split = self.list_volumes.item(count).text().split(" || ")129 volumes[str_split[0]] = {'bind': str_split[1], 'mode': 'rw'}130 # add Scripts folder131 curr_path = os.path.abspath(__file__)132 volumes[os.path.split(curr_path)[0]] = {'bind': '/mnt/scripts/', 'mode': 'rw'}133 # docker client134 client = docker.from_env()135 ctnr = client.containers.run(image='sachslab/dti_base:0.3f', environment=display_env,136 command='python /mnt/scripts/Main/Main.py', detach=True, tty=True,137 volumes=volumes, remove=True)138 # Closing launcher window139 self.parent().close()140if __name__ == '__main__':141 qapp = QApplication(sys.argv) # application object / sys.argv are command line arguments.142 aw = Launcher() # basic widget creation, if no parent: widget == window...
test_list_task_output.py
Source:test_list_task_output.py
1import mock2import unittest3import kojihub4class TestListTaskOutput(unittest.TestCase):5 @mock.patch('os.path.isdir')6 @mock.patch('os.walk')7 def test_empty(self, walk, isdir):8 isdir.return_value = True9 walk.return_value = []10 result = kojihub.list_task_output(1)11 self.assertEqual(result, [])12 @mock.patch('os.path.isdir')13 @mock.patch('os.walk')14 def test_simple(self, walk, isdir):15 isdir.return_value = True16 walk.return_value = (('dir', [], ['file']),)17 result = kojihub.list_task_output(1)18 self.assertEqual(result, ['file'])19 @mock.patch('os.stat')20 @mock.patch('os.path.isdir')21 @mock.patch('os.walk')22 def test_simple_stat(self, walk, isdir, stat):23 isdir.return_value = True24 walk.return_value = (('dir', [], ['file']),)25 st_mock = mock.MagicMock()26 st_mock.st_size = 12327 st_mock.st_atime = 34528 st_mock.st_mtime = 67829 st_mock.st_ctime = 90130 stat.return_value = st_mock31 result = kojihub.list_task_output(1, stat=True)32 self.assertEqual(result, {33 'file': {34 'st_size': '123',35 'st_atime': 345,36 'st_mtime': 678,37 'st_ctime': 901,38 }39 })40 @mock.patch('kojihub.list_volumes')41 @mock.patch('os.stat')42 @mock.patch('os.path.isdir')43 @mock.patch('os.walk')44 def test_volumes(self, walk, isdir, stat, list_volumes):45 isdir.return_value = True46 walk.return_value = (('dir', [], ['file']),)47 st_mock = mock.MagicMock()48 st_mock.st_size = 12349 st_mock.st_atime = 34550 st_mock.st_mtime = 67851 st_mock.st_ctime = 90152 stat.return_value = st_mock53 list_volumes.return_value = [{'name': 'DEFAULT'}]54 result = kojihub.list_task_output(1, all_volumes=True)55 self.assertEqual(result, {'file': ['DEFAULT']})56 @mock.patch('kojihub.list_volumes')57 @mock.patch('os.stat')58 @mock.patch('os.path.isdir')59 @mock.patch('os.walk')60 def test_volumes_stat(self, walk, isdir, stat, list_volumes):61 isdir.return_value = True62 walk.return_value = (('dir', [], ['file']),)63 st_mock = mock.MagicMock()64 st_mock.st_size = 12365 st_mock.st_atime = 34566 st_mock.st_mtime = 67867 st_mock.st_ctime = 90168 stat.return_value = st_mock69 list_volumes.return_value = [{'name': 'DEFAULT'}]70 result = kojihub.list_task_output(1, stat=True, all_volumes=True)71 self.assertEqual(result, {72 'file': {73 'DEFAULT': {74 'st_size': '123',75 'st_atime': 345,76 'st_mtime': 678,77 'st_ctime': 901,78 }79 }...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!