ctkDICOMIndexer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. /*=========================================================================
  2. Library: CTK
  3. Copyright (c) Kitware Inc.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0.txt
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. =========================================================================*/
  14. // Qt includes
  15. #include <QSqlQuery>
  16. #include <QSqlRecord>
  17. #include <QSqlError>
  18. #include <QVariant>
  19. #include <QDate>
  20. #include <QStringList>
  21. #include <QSet>
  22. #include <QFile>
  23. #include <QDirIterator>
  24. #include <QFileInfo>
  25. #include <QDebug>
  26. // ctkDICOM includes
  27. #include "ctkLogger.h"
  28. #include "ctkDICOMIndexer.h"
  29. #include "ctkDICOMIndexer_p.h"
  30. #include "ctkDICOMDatabase.h"
  31. // DCMTK includes
  32. #include <dcmtk/dcmdata/dcfilefo.h>
  33. #include <dcmtk/dcmdata/dcfilefo.h>
  34. #include <dcmtk/dcmdata/dcdeftag.h>
  35. #include <dcmtk/dcmdata/dcdatset.h>
  36. #include <dcmtk/ofstd/ofcond.h>
  37. #include <dcmtk/ofstd/ofstring.h>
  38. #include <dcmtk/ofstd/ofstd.h> /* for class OFStandard */
  39. #include <dcmtk/dcmdata/dcddirif.h> /* for class DicomDirInterface */
  40. #include <dcmtk/dcmimgle/dcmimage.h> /* for class DicomImage */
  41. #include <dcmtk/dcmimage/diregist.h> /* include support for color images */
  42. //------------------------------------------------------------------------------
  43. static ctkLogger logger("org.commontk.dicom.DICOMIndexer" );
  44. //------------------------------------------------------------------------------
  45. //------------------------------------------------------------------------------
  46. // ctkDICOMIndexerPrivate methods
  47. //------------------------------------------------------------------------------
  48. ctkDICOMIndexerPrivate::ctkDICOMIndexerPrivate(ctkDICOMIndexer& o) : q_ptr(&o), Canceled(false)
  49. {
  50. }
  51. //------------------------------------------------------------------------------
  52. ctkDICOMIndexerPrivate::~ctkDICOMIndexerPrivate()
  53. {
  54. }
  55. //------------------------------------------------------------------------------
  56. //------------------------------------------------------------------------------
  57. // ctkDICOMIndexer methods
  58. //------------------------------------------------------------------------------
  59. ctkDICOMIndexer::ctkDICOMIndexer(QObject *parent):d_ptr(new ctkDICOMIndexerPrivate(*this))
  60. {
  61. Q_UNUSED(parent);
  62. }
  63. //------------------------------------------------------------------------------
  64. ctkDICOMIndexer::~ctkDICOMIndexer()
  65. {
  66. }
  67. //------------------------------------------------------------------------------
  68. void ctkDICOMIndexer::addFile(ctkDICOMDatabase& database,
  69. const QString filePath,
  70. const QString& destinationDirectoryName)
  71. {
  72. std::cout << filePath.toStdString();
  73. if (!destinationDirectoryName.isEmpty())
  74. {
  75. logger.warn("Ignoring destinationDirectoryName parameter, just taking it as indication we should copy!");
  76. }
  77. emit indexingFilePath(filePath);
  78. database.insert(filePath, !destinationDirectoryName.isEmpty(), true);
  79. }
  80. //------------------------------------------------------------------------------
  81. void ctkDICOMIndexer::addDirectory(ctkDICOMDatabase& ctkDICOMDatabase,
  82. const QString& directoryName,
  83. const QString& destinationDirectoryName)
  84. {
  85. QStringList listOfFiles;
  86. QDir directory(directoryName);
  87. if(directory.exists("DICOMDIR"))
  88. {
  89. addDicomdir(ctkDICOMDatabase,directoryName,destinationDirectoryName);
  90. }
  91. else
  92. {
  93. QDirIterator it(directoryName,QDir::Files,QDirIterator::Subdirectories);
  94. while(it.hasNext())
  95. {
  96. listOfFiles << it.next();
  97. }
  98. emit foundFilesToIndex(listOfFiles.count());
  99. addListOfFiles(ctkDICOMDatabase,listOfFiles,destinationDirectoryName);
  100. }
  101. }
  102. //------------------------------------------------------------------------------
  103. void ctkDICOMIndexer::addListOfFiles(ctkDICOMDatabase& ctkDICOMDatabase,
  104. const QStringList& listOfFiles,
  105. const QString& destinationDirectoryName)
  106. {
  107. Q_D(ctkDICOMIndexer);
  108. QTime timeProbe;
  109. timeProbe.start();
  110. d->Canceled = false;
  111. int CurrentFileIndex = 0;
  112. int lastReportedPercent = 0;
  113. foreach(QString filePath, listOfFiles)
  114. {
  115. int percent = ( 100 * CurrentFileIndex ) / listOfFiles.size();
  116. if (lastReportedPercent / 10 < percent / 10)
  117. {
  118. // Reporting progress has a huge overhead (pending events are processed,
  119. // database is updated), therefore only report progress at every 10% increase
  120. emit this->progress(percent);
  121. lastReportedPercent = percent;
  122. }
  123. this->addFile(ctkDICOMDatabase, filePath, destinationDirectoryName);
  124. CurrentFileIndex++;
  125. if( d->Canceled )
  126. {
  127. break;
  128. }
  129. }
  130. float elapsedTimeInSeconds = timeProbe.elapsed() / 1000.0;
  131. qDebug()
  132. << QString("DICOM indexer has successfully processed %1 files [%2s]")
  133. .arg(CurrentFileIndex)
  134. .arg(QString::number(elapsedTimeInSeconds,'f', 2));
  135. emit this->indexingComplete();
  136. }
  137. //------------------------------------------------------------------------------
  138. bool ctkDICOMIndexer::addDicomdir(ctkDICOMDatabase& ctkDICOMDatabase,
  139. const QString& directoryName,
  140. const QString& destinationDirectoryName
  141. )
  142. {
  143. //Initialize dicomdir with directory path
  144. QString dcmFilePath = directoryName;
  145. dcmFilePath.append("/DICOMDIR");
  146. DcmDicomDir* dicomDir = new DcmDicomDir(dcmFilePath.toStdString().c_str());
  147. //Values to store records data at the moment only uid needed
  148. OFString patientsName, studyInstanceUID, seriesInstanceUID, sopInstanceUID, referencedFileName ;
  149. //Variables for progress operations
  150. QString instanceFilePath;
  151. QStringList listOfInstances;
  152. DcmDirectoryRecord* rootRecord = &(dicomDir->getRootRecord());
  153. DcmDirectoryRecord* patientRecord = NULL;
  154. DcmDirectoryRecord* studyRecord = NULL;
  155. DcmDirectoryRecord* seriesRecord = NULL;
  156. DcmDirectoryRecord* fileRecord = NULL;
  157. QTime timeProbe;
  158. timeProbe.start();
  159. /*Iterate over all records in dicomdir and setup path to the dataset of the filerecord
  160. then insert. the filerecord into the database.
  161. If any UID is missing the record and all of it's subelements won't be added to the database*/
  162. bool success = true;
  163. if(rootRecord != NULL)
  164. {
  165. while ((patientRecord = rootRecord->nextSub(patientRecord)) != NULL)
  166. {
  167. logger.debug( "Reading new Patient:" );
  168. if (patientRecord->findAndGetOFString(DCM_PatientName, patientsName).bad())
  169. {
  170. logger.warn( "DICOMDIR file at "+directoryName+" is invalid: patient name not found. All records belonging to this patient will be ignored.");
  171. success = false;
  172. continue;
  173. }
  174. logger.debug( "Patient's Name: " + QString(patientsName.c_str()) );
  175. while ((studyRecord = patientRecord->nextSub(studyRecord)) != NULL)
  176. {
  177. logger.debug( "Reading new Study:" );
  178. if (studyRecord->findAndGetOFString(DCM_StudyInstanceUID, studyInstanceUID).bad())
  179. {
  180. logger.warn( "DICOMDIR file at "+directoryName+" is invalid: study instance UID not found for patient "+ QString(patientsName.c_str())+". All records belonging to this study will be ignored.");
  181. success = false;
  182. continue;
  183. }
  184. logger.debug( "Study instance UID: " + QString(studyInstanceUID.c_str()) );
  185. while ((seriesRecord = studyRecord->nextSub(seriesRecord)) != NULL)
  186. {
  187. logger.debug( "Reading new Series:" );
  188. if (seriesRecord->findAndGetOFString(DCM_SeriesInstanceUID, seriesInstanceUID).bad())
  189. {
  190. logger.warn( "DICOMDIR file at "+directoryName+" is invalid: series instance UID not found for patient "+ QString(patientsName.c_str())+", study "+ QString(studyInstanceUID.c_str())+". All records belonging to this series will be ignored.");
  191. success = false;
  192. continue;
  193. }
  194. logger.debug( "Series instance UID: " + QString(seriesInstanceUID.c_str()) );
  195. while ((fileRecord = seriesRecord->nextSub(fileRecord)) != NULL)
  196. {
  197. if (fileRecord->findAndGetOFStringArray(DCM_ReferencedSOPInstanceUIDInFile, sopInstanceUID).bad()
  198. || fileRecord->findAndGetOFStringArray(DCM_ReferencedFileID,referencedFileName).bad())
  199. {
  200. logger.warn( "DICOMDIR file at "+directoryName+" is invalid: referenced SOP instance UID or file name is invalid for patient "
  201. + QString(patientsName.c_str())+", study "+ QString(studyInstanceUID.c_str())+", series "+ QString(seriesInstanceUID.c_str())+
  202. ". This file will be ignored.");
  203. success = false;
  204. continue;
  205. }
  206. //Get the filepath of the instance and insert it into a list
  207. instanceFilePath = directoryName;
  208. instanceFilePath.append("/");
  209. instanceFilePath.append(QString( referencedFileName.c_str() ));
  210. instanceFilePath.replace("\\","/");
  211. listOfInstances << instanceFilePath;
  212. }
  213. }
  214. }
  215. }
  216. float elapsedTimeInSeconds = timeProbe.elapsed() / 1000.0;
  217. qDebug()
  218. << QString("DICOM indexer has successfully processed DICOMDIR in %1 [%2s]")
  219. .arg(directoryName)
  220. .arg(QString::number(elapsedTimeInSeconds,'f', 2));
  221. emit foundFilesToIndex(listOfInstances.count());
  222. addListOfFiles(ctkDICOMDatabase,listOfInstances,destinationDirectoryName);
  223. }
  224. return success;
  225. }
  226. //------------------------------------------------------------------------------
  227. void ctkDICOMIndexer::refreshDatabase(ctkDICOMDatabase& dicomDatabase, const QString& directoryName)
  228. {
  229. Q_UNUSED(dicomDatabase);
  230. Q_UNUSED(directoryName);
  231. /*
  232. * Probably this should go to the database class as well
  233. * Or we have to extend the interface to make possible what we do here
  234. * without using SQL directly
  235. /// get all filenames from the database
  236. QSqlQuery allFilesQuery(dicomDatabase.database());
  237. QStringList databaseFileNames;
  238. QStringList filesToRemove;
  239. this->loggedExec(allFilesQuery, "SELECT Filename from Images;");
  240. while (allFilesQuery.next())
  241. {
  242. QString fileName = allFilesQuery.value(0).toString();
  243. databaseFileNames.append(fileName);
  244. if (! QFile::exists(fileName) )
  245. {
  246. filesToRemove.append(fileName);
  247. }
  248. }
  249. QSet<QString> filesytemFiles;
  250. QDirIterator dirIt(directoryName);
  251. while (dirIt.hasNext())
  252. {
  253. filesytemFiles.insert(dirIt.next());
  254. }
  255. // TODO: it looks like this function was never finished...
  256. //
  257. // I guess the next step is to remove all filesToRemove from the database
  258. // and also to add filesystemFiles into the database tables
  259. */
  260. }
  261. //------------------------------------------------------------------------------
  262. void ctkDICOMIndexer::waitForImportFinished()
  263. {
  264. // No-op - this had been used when the indexing was multi-threaded,
  265. // and has only been retained for API compatibility.
  266. }
  267. //----------------------------------------------------------------------------
  268. void ctkDICOMIndexer::cancel()
  269. {
  270. Q_D(ctkDICOMIndexer);
  271. d->Canceled = true;
  272. }