import os import json import re import sys import datetime import re fhome=os.path.expanduser('~') sys.path.insert(1,fhome+'/software/src/labkeyInterface') import labkeyInterface import labkeyDatabaseBrowser fconfig=os.path.join(fhome,'.labkey','network.json') net=labkeyInterface.labkeyInterface() net.init(fconfig) db=labkeyDatabaseBrowser.labkeyDB(net) i=0 projectOrthanc='Orthanc/Database' inputDataset='Imaging' projectStudy='iPNUMMretro/Study' outputDataset='Imaging1' ds=db.selectRows(projectOrthanc,'study',inputDataset,[]) #single entry for the patientId/dicomStudy pair selectVars=['PatientId','dicomStudy'] dates=[datetime.datetime.strptime(row['studyDate'],'%Y/%m/%d %H:%M:%S') for row in ds['rows']] idx=sorted(range(len(dates)),key=lambda k:dates[k]) for j in range(len(dates)): #row in ds['rows']: row=ds['rows'][idx[j]] #skip series which don't match selected filters outvar='NONE' sd=row['seriesDescription'] if sd=='PET WB': outvar='PETWB' if sd.find('CT WB')==0: if sd.find('fov')<0: outvar='CT' if outvar=='NONE': continue filters=[] for v in selectVars: filters.append({'variable':v,'value':row[v],'oper':'eq'}) ds2=db.selectRows(projectStudy,'study',outputDataset, [{'variable':'PatientId','value':row['PatientId'],'oper':'eq'}]) ds1=db.selectRows(projectStudy,'study',outputDataset,filters) if len(ds1['rows'])>1: print('ERROR: too many matches for {}/{}'.format(row['PatientId'],row['dicomStudy'])) continue mode='update' outRow={} if len(ds1['rows'])==0: mode='insert' outRow['PatientId']=row['PatientId'] outRow['SequenceNum']=len(ds2['rows']) outRow['dicomStudy']=row['dicomStudy'] else: outRow=ds1['rows'][0] outRow[outvar]=row['orthancSeries'] outRow['studyDate']=row['studyDate'] status=db.modifyRows(mode,projectStudy,'study',outputDataset,[outRow]) print('{}'.format(status)) if j==50: break print("Done")