Пример #1
0
def study(request, study_iuid):
    # Patient Name
    response = {}
    study_iuid_tag = gdcm.Tag(0x20, 0xD)
    study_iuid_element = gdcm.DataElement(study_iuid_tag)
    study_descr_tag = gdcm.Tag(0x8, 0x1030)
    study_descr_element = gdcm.DataElement(study_descr_tag)
    study_iuid_element.SetByteValue(str(study_iuid), gdcm.VL(len(study_iuid)))
    ds = gdcm.DataSet()
    ds.Insert(study_iuid_element)
    ds.Insert(study_descr_element)
    cnf = gdcm.CompositeNetworkFunctions()
    theQuery = cnf.ConstructQuery(gdcm.eStudyRootType, gdcm.eStudy, ds)

    # prepare the variable for output
    ret = gdcm.DataSetArrayType()
    # Execute the C-FIND query
    cnf.CFind(settings.SC_DICOM_SERVER, settings.SC_DICOM_PORT, theQuery, ret,
              'GDCM_PYTHON', settings.AET)

    response["description"] = str(
        ret[0].GetDataElement(study_descr_tag).GetValue())

    ds = gdcm.DataSet()

    series_descr_tag = gdcm.Tag(0x8, 0x103E)
    series_descr_element = gdcm.DataElement(series_descr_tag)
    series_iuid_tag = gdcm.Tag(0x20, 0xE)
    series_iuid_element = gdcm.DataElement(series_iuid_tag)
    series_number_tag = gdcm.Tag(0x20, 0x11)
    series_number_element = gdcm.DataElement(series_number_tag)

    ds.Insert(study_iuid_element)
    ds.Insert(series_descr_element)
    ds.Insert(series_iuid_element)
    ds.Insert(series_number_element)

    series_query = cnf.ConstructQuery(gdcm.eStudyRootType, gdcm.eSeries, ds)
    ret = gdcm.DataSetArrayType()
    cnf.CFind(settings.SC_DICOM_SERVER, settings.SC_DICOM_PORT, series_query,
              ret, 'GDCM_PYTHON', settings.AET)

    sorted_ret = sorted(
        ret,
        key=lambda x: int(str(x.GetDataElement(series_number_tag).GetValue())))

    response["series"] = [{
        "description":
        str(x.GetDataElement(series_descr_tag).GetValue()),
        "uid":
        str(x.GetDataElement(series_iuid_tag).GetValue())
    } for x in sorted_ret]

    json_response = json.dumps(response)

    if request.GET.has_key('callback'):
        json_response = "(function(){%s(%s);})();" % (request.GET['callback'],
                                                      json_response)

    return HttpResponse(json_response, content_type="application/json")
Пример #2
0
    def listPatients(self):  # root query

        self.d = DicomDataset()
        self.queryTag = self.tag_PatientID
        self.d.add(self.queryTag)
        for tag in self.tag_Patient:
            self.d.add(tag)

        self.cnf = gdcm.CompositeNetworkFunctions()
        self.theQuery = self.cnf.ConstructQuery(gdcm.eStudyRootType,
                                                gdcm.eStudy, self.d.get())
        self.ret_query = gdcm.DataSetArrayType()

        self.cnf.CFind(self.server, self.remoteport, self.theQuery,
                       self.ret_query, self.aetitle, self.caller)
        UIDs = []
        desc = []
        timestamps = []
        for i in range(0, self.ret_query.size()):
            x = str(self.ret_query[i].GetDataElement(self.queryTag).GetValue())
            if x in UIDs: continue
            UIDs.append(
                str(self.ret_query[i].GetDataElement(
                    self.queryTag).GetValue()))
            desc.append(
                str(self.ret_query[i].GetDataElement(
                    self.tag_PatientName).GetValue()))
            timestamps.append(0)

        return UIDs, desc, timestamps
Пример #3
0
    def find_patients(patientID: str = None):
        print('Getting actie archive and user...')
        klient = db.get_active_user()
        archive = db.get_active_archive()
        # klucze(filtrowanie lub określenie, które dane są potrzebne)
        klucze = gdcm.KeyValuePairArrayType()
        tag = gdcm.Tag(0x0010, 0x0010)  # 10, 10 == PATIENT_NAME
        if patientID is None:
            p_id_key = gdcm.KeyValuePairType(tag, "*")  # * == dowolne imię
        else:
            p_id_key = gdcm.KeyValuePairType(tag,
                                             patientID)  # * == dowolne imię

        p_name_kay = gdcm.KeyValuePairType(gdcm.Tag(0x0010, 0x0020), "")
        p_birth_key = gdcm.KeyValuePairType(gdcm.Tag(0x0010, 0x0030), "")
        study_id = gdcm.KeyValuePairType(gdcm.Tag(0x0020, 0x0010), "")

        klucze.append(p_id_key)
        klucze.append(p_name_kay)
        #klucze.append(gdcm.KeyValuePairType(gdcm.Tag(0x0010, 0x0020), ""))
        print('Keys - READY! \n Makeing query....')
        # zwrotnie oczekujemy wypełnionego 10, 20 czyli PATIENT_ID

        # skonstruuj zapytanie gdcm.BaseRootQuery
        zapytanie = gdcm.CompositeNetworkFunctions.ConstructQuery(
            gdcm.ePatientRootType, gdcm.ePatient, klucze)
        print('Query - READY! \n Finding....')
        # sprawdź, czy zapytanie spełnia kryteria
        if not zapytanie.ValidateQuery():
            print("FIND błędne zapytanie!")
            return []

        # kontener na wyniki
        wynik = gdcm.DataSetArrayType()

        # wykonaj zapytanie
        stan = gdcm.CompositeNetworkFunctions.CFind(str(klient[2]),
                                                    int(archive[3]), zapytanie,
                                                    wynik, str(klient[1]),
                                                    str(archive[1]))

        # sprawdź stan
        if (not stan):
            print("Program isn't able to find any patients")
            return []
        if patientID is None:
            print("All patients are found")
        else:
            print("{} patient is found".format(patientID))
        response = []

        # pokaż wyniki
        for x in wynik:
            response.append([
                str(x.GetDataElement(gdcm.Tag(0x0010, 0x0020)).GetValue()),
                str(x.GetDataElement(gdcm.Tag(0x0010, 0x0010)).GetValue())
            ])
        return response
Пример #4
0
    def cfind(self, dic_keys):
        # Esta funcion hay que reimplementarla completamente
        # Solo funciona para las consulta hechas dede la interfaz grafica
        # no es para todo tipo de consulta
        datasets_study_resut = gdcm.DataSetArrayType()
        datasets_series_resut = gdcm.DataSetArrayType()
        #        datasets_image_resut = gdcm.DataSetArrayType()

        keys_in_level = self.get_keys_in_level(dic_keys)

        cochinaa = False
        for key in keys_in_level['study']:
            if keys_in_level['study'][key]:
                cochinaa = True
                break

        if cochinaa:
            query_dataset = self.construct_dataset(keys_in_level['study'])
            datasets_study_resut = self.find(gdcm.eStudy, query_dataset)
            #            while datasets_study_resut.size():
            #                print datasets_study_resut.pop()
            while datasets_study_resut.size():
                dataset = datasets_study_resut.pop()
                if keys_in_level['series']:

                    query_dataset = self.construct_dataset(
                        keys_in_level['series'], dataset)
                    self._service_manager.InitializeConnection()
                    datasets_vector_result = self.find(gdcm.eSeries,
                                                       query_dataset)
                    while datasets_vector_result.size():
                        datasets_series_resut.append(
                            datasets_vector_result.pop())
            if datasets_series_resut.size():
                #OJOO con esta modificacion --> return datasets_series_result era lo que estaba
                return (keys_in_level, datasets_series_resut)
            else:
                return None
        else:
            query_dataset = self.construct_dataset(keys_in_level['all_key'])
            datasets_result = self.find(gdcm.eSeries, query_dataset)
            return (keys_in_level, datasets_result)
Пример #5
0
    def listStudies(self, patientID=None):  # root query

        self.d = DicomDataset()
        self.queryTag = self.tag_StudyUID
        self.d.add(self.queryTag)
        for tag in self.tag_Study:
            self.d.add(tag)
        if patientID != None:
            self.d.add(self.tag_PatientID, patientID)

        self.cnf = gdcm.CompositeNetworkFunctions()
        self.theQuery = self.cnf.ConstructQuery(gdcm.eStudyRootType,
                                                gdcm.eStudy, self.d.get())
        self.ret_query = gdcm.DataSetArrayType()

        self.cnf.CFind(self.server, self.remoteport, self.theQuery,
                       self.ret_query, self.aetitle, self.caller)
        UIDs = []
        desc = []
        timestamp = []
        for i in range(0, self.ret_query.size()):
            x = str(self.ret_query[i].GetDataElement(self.queryTag).GetValue())
            if x in UIDs: continue
            UIDs.append(
                str(self.ret_query[i].GetDataElement(
                    self.queryTag).GetValue()))
            desc.append(
                str(self.ret_query[i].GetDataElement(
                    self.tag_StudyDescription).GetValue()))

            datestring = (self.ret_query[i].GetDataElement(
                self.tag_StudyDate).GetValue())
            timestring = (self.ret_query[i].GetDataElement(
                self.tag_StudyTime).GetValue())

            if datestring != None and timestring != None:
                datestring = str(datestring)
                timestring = str(timestring)
                d = datetime.datetime(year=int(datestring[0:4]),
                                      month=int(datestring[4:6]),
                                      day=int(datestring[6:]),
                                      hour=int(timestring[0:2]),
                                      minute=int(timestring[2:4]),
                                      second=int(timestring[4:]),
                                      microsecond=0)
                timestamp.append(time.mktime(d.timetuple()))
            else:
                timestamp.append(0)

        return UIDs, desc, timestamp
Пример #6
0
    def findPatients():
        klient = db.get_active_user()
        archive = db.get_active_archive()

        # klucze(filtrowanie lub określenie, które dane są potrzebne)
        klucze = gdcm.KeyValuePairArrayType()

        tag = gdcm.Tag(0x0010, 0x0010)  # 10, 10 == PATIENT_NAME
        klucz1 = gdcm.KeyValuePairType(tag, "*")  # * == dowolne imię
        klucze.append(klucz1)
        klucze.append(gdcm.KeyValuePairType(gdcm.Tag(0x0010, 0x0020), ""))
        print('Keys - READY! \n Makeing query....')
        # zwrotnie oczekujemy wypełnionego 10, 20 czyli PATIENT_ID

        # skonstruuj zapytanie gdcm.BaseRootQuery
        zapytanie = gdcm.CompositeNetworkFunctions.ConstructQuery(
            gdcm.ePatientRootType, gdcm.ePatient, klucze)
        print('Query - READY! \n Finding....')
        # sprawdź, czy zapytanie spełnia kryteria
        if not zapytanie.ValidateQuery():
            print("FIND błędne zapytanie!")
            return

        # kontener na wyniki
        wynik = gdcm.DataSetArrayType()

        # wykonaj zapytanie
        stan = gdcm.CompositeNetworkFunctions.CFind(str(klient[2]),
                                                    int(archive[3]), zapytanie,
                                                    wynik, str(klient[1]),
                                                    str(archive[1]))
        print('Finding - READY!')
        print(wynik)
        # sprawdź stan
        if (not stan):
            print("Program isn't able to find any patients")
            return None
        print("All patients are found")
        response = []
        print(wynik)
        # pokaż wyniki
        for x in wynik:
            print(str(x))  # cała odpowiedź jako wielolinijkowy napis
            response.append([
                str(x.GetDataElement(gdcm.Tag(0x0010, 0x0020)).GetValue()),
                str(x.GetDataElement(gdcm.Tag(0x0010, 0x0010)).GetValue())
            ])
        return response
Пример #7
0
    def find(self, query_level, keys_dataset):
        """
           1- Aqui tengo que crear la lista de contextos de presentacion
           2- Asociarme (
           3- comprobar cuales fueron los contextos aceptados en la asociacion
           4- construir el query segun los contextos aceptados.
           5- enviar el query
        """
        # Building Presentation Contexts List
        pre_contexts = self._get_presentation_contexts('find')
        print '-------', len(pre_contexts)

        self._service_manager.SetPresentationContexts(pre_contexts)
        if not self._service_manager.StartAssociation():
            raise Exception("Start Association for CFind Failed.")

        pcinfo_accepted = self.prescontexts_accepted(pre_contexts)
        pcontexts_accepted = pcinfo_accepted[0]
        abs_list = pcinfo_accepted[1]

        if not len(pcontexts_accepted):
            raise Exception(
                "Dicom Server not permit QueryRetrieve operations.")

        model = self.get_model('find', query_level, abs_list)
        if model < 0 or model > 1:
            raise Exception("El modelo QR en el DCMSERVER no soporta " + \
                            "busqueda a ese nivel.")

        dataset_vector = gdcm.DataSetArrayType()
        query = self.construct_query(model, query_level, keys_dataset)
        status_cfind = self._service_manager.SendFind(query, dataset_vector)

        if not status_cfind:
            raise Exception("Internal error in SendFind function.")
        else:
            l = dataset_vector.size()
            #            while dataset_vector.size():
            #                print dataset_vector.pop()
            #
            print "ALLLLLL : ", l
            return dataset_vector

        if not self._service_manager.StopAssociation():
            raise Exception("Stop Association Failed.")
Пример #8
0
    def listSeries(self, studyUID, patientID=None):  # root query
        self.d = DicomDataset()
        self.queryTag = self.tag_SeriesUID

        self.d.add(self.queryTag)
        self.d.add(self.tag_StudyUID, studyUID)
        self.d.add(self.tag_infmodel, "SERIES")

        for tag in self.tag_Study:
            self.d.add(tag)
        for tag in self.tag_Series:
            self.d.add(tag)
        if patientID != None:
            self.d.add(self.tag_PatientID, patientID)

        self.cnf = gdcm.CompositeNetworkFunctions()
        self.theQuery = self.cnf.ConstructQuery(gdcm.eStudyRootType,
                                                gdcm.eSeries, self.d.get())
        self.ret_query = gdcm.DataSetArrayType()

        self.cnf.CFind(self.server, self.remoteport, self.theQuery,
                       self.ret_query, self.aetitle, self.caller)
        UIDs = []
        desc = []
        modality = []
        for i in range(0, self.ret_query.size()):
            x = str(self.ret_query[i].GetDataElement(self.queryTag).GetValue())
            if x in UIDs: continue
            UIDs.append(
                str(self.ret_query[i].GetDataElement(
                    self.queryTag).GetValue()))
            desc.append(
                str(self.ret_query[i].GetDataElement(
                    self.tag_SeriesDescription).GetValue()))
            modality.append(
                str(self.ret_query[i].GetDataElement(
                    self.tag_SeriesModality).GetValue()))

        return UIDs, desc, modality
Пример #9
0
def series(request, series_iuid):

    series_iuid_tag = gdcm.Tag(0x20, 0xE)
    series_iuid_element = gdcm.DataElement(series_iuid_tag)
    series_iuid_element.SetByteValue(str(series_iuid),
                                     gdcm.VL(len(series_iuid)))
    instance_uid_tag = gdcm.Tag(0x8, 0x18)
    instance_uid_element = gdcm.DataElement(instance_uid_tag)
    instance_number_tag = gdcm.Tag(0x20, 0x13)
    instance_number_element = gdcm.DataElement(instance_number_tag)

    ds = gdcm.DataSet()
    ds.Insert(series_iuid_element)
    ds.Insert(instance_uid_element)
    ds.Insert(instance_number_element)

    cnf = gdcm.CompositeNetworkFunctions()

    instance_query = cnf.ConstructQuery(gdcm.eStudyRootType, gdcm.eImage, ds)
    ret = gdcm.DataSetArrayType()
    cnf.CFind(settings.SC_DICOM_SERVER, settings.SC_DICOM_PORT, instance_query,
              ret, 'GDCM_PYTHON', settings.AET)

    sorted_ret = sorted(
        ret,
        key=lambda x: int(str(
            x.GetDataElement(instance_number_tag).GetValue())))
    response = [
        str(x.GetDataElement(instance_uid_tag).GetValue()) for x in sorted_ret
    ]

    json_response = json.dumps(response)

    if request.GET.has_key('callback'):
        json_response = "(function(){%s(%s);})();" % (request.GET['callback'],
                                                      json_response)

    return HttpResponse(json_response, content_type="application/json")
Пример #10
0
    def RunCFind(self):

        tags = [(0x0010, 0x0010), (0x0010, 0x1010), (0x0010,0x0040), (0x0008,0x1030),\
                (0x0008,0x0060), (0x0008,0x0022), (0x0008,0x0080), (0x0010,0x0030),\
                (0x0008,0x0050), (0x0008,0x0090), (0x0008,0x103E), (0x0008,0x0033),\
                (0x0008,0x0032), (0x0020,0x000d)]

        ds = gdcm.DataSet()

        for tag in tags:

            tg = gdcm.Tag(tag[0], tag[1])

            de = gdcm.DataElement(tg)

            if self.search_type == 'patient' and tag == (0x0010, 0x0010):

                bit_size = len(self.search_word) + 1
                de.SetByteValue(str(self.search_word + '*'), gdcm.VL(bit_size))
            else:
                de.SetByteValue('*', gdcm.VL(1))

            ds.Insert(de)

        cnf = gdcm.CompositeNetworkFunctions()
        theQuery = cnf.ConstructQuery(gdcm.ePatientRootType,
                                      gdcm.eImageOrFrame, ds)
        ret = gdcm.DataSetArrayType()

        cnf.CFind(self.address, int(self.port), theQuery, ret, self.aetitle,\
                  self.aetitle_call)

        patients = {}

        exist_images = False
        c = 0
        for i in range(0, ret.size()):
            patient_id = str(ret[i].GetDataElement(gdcm.Tag(
                0x0010, 0x0020)).GetValue())
            serie_id = str(ret[i].GetDataElement(gdcm.Tag(0x0020,
                                                          0x000e)).GetValue())

            if not (patient_id in patients.keys()):
                patients[patient_id] = {}

            if not (serie_id in patients[patient_id]):

                rt = ret[i]

                name = self.GetValueFromDICOM(rt, (0x0010, 0x0010))
                age = self.GetValueFromDICOM(rt, (0x0010, 0x1010))
                gender = self.GetValueFromDICOM(rt, (0x0010, 0x0040))
                study_description = self.GetValueFromDICOM(
                    rt, (0x0008, 0x1030))
                modality = self.GetValueFromDICOM(rt, (0x0008, 0x0060))
                institution = self.GetValueFromDICOM(rt, (0x0008, 0x0080))
                date_of_birth = utils.format_date(
                    self.GetValueFromDICOM(rt, (0x0010, 0x0030)))
                acession_number = self.GetValueFromDICOM(rt, (0x0008, 0x0050))
                ref_physician = self.GetValueFromDICOM(rt, (0x0008, 0x0090))
                serie_description = self.GetValueFromDICOM(
                    rt, (0x0008, 0x103E))
                acquisition_time = utils.format_time(
                    self.GetValueFromDICOM(rt, (0x0008, 0x0032)))
                acquisition_date = utils.format_date(
                    self.GetValueFromDICOM(rt, (0x0008, 0x0022)))

                teste = self.GetValueFromDICOM(rt, (0x0020, 0x000d))

                patients[patient_id][serie_id] = {'name':name, 'age':age, 'gender':gender,\
                                                  'study_description':study_description,\
                                                  'modality':modality, \
                                                  'acquisition_time':acquisition_time,\
                                                  'acquisition_date':acquisition_date,\
                                                  'institution':institution,\
                                                  'date_of_birth':date_of_birth,\
                                                  'acession_number':acession_number,\
                                                  'ref_physician':ref_physician,\
                                                  'serie_description':serie_description}

                patients[patient_id][serie_id]['n_images'] = 1
            else:
                patients[patient_id][serie_id]['n_images'] += 1

        return patients
Пример #11
0
 python FindAllPatientName.py

"""

import gdcm

# Patient Name
tag = gdcm.Tag(0x10, 0x10)
de = gdcm.DataElement(tag)

# Search all patient name where string match 'F*'
de.SetByteValue('F*', gdcm.VL(2))

ds = gdcm.DataSet()
ds.Insert(de)

cnf = gdcm.CompositeNetworkFunctions()
theQuery = cnf.ConstructQuery(gdcm.ePatientRootType, gdcm.ePatient, ds)

#print theQuery.ValidateQuery()

# prepare the variable for output
ret = gdcm.DataSetArrayType()

# Execute the C-FIND query
cnf.CFind('dicom.example.com', 11112, theQuery, ret, 'GDCM_PYTHON', 'ANY-SCP')

for i in range(0, ret.size()):
    print "Patient #", i
    print ret[i]