orthancDatabaseBrowser.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import orthancInterface
  2. import json
  3. import chardet
  4. import io
  5. def extractJSON(data):
  6. encoding=chardet.detect(data)["encoding"]
  7. #try with a set of encodings to maximize probability of success
  8. encodings=[encoding,'utf_8']
  9. for x in encodings:
  10. try:
  11. return json.loads(data.decode(x))
  12. except UnicodeDecodeError:
  13. print(f'Failed to decode with [{x}]: {data}')
  14. return None
  15. class orthancDB:
  16. def __init__(self,net):
  17. self.net=net
  18. def getList(self,category):
  19. url=self.net.getCoreURL()
  20. url+='/'+category
  21. response=self.net.get(url)
  22. return extractJSON(response.data)
  23. def getPatients(self):
  24. return self.getList('patients')
  25. def getStudies(self):
  26. return self.getList('studies')
  27. def getPatientData(self, orthancId):
  28. return self.getData('patients',orthancId)
  29. def getStudyData(self, studyOrthancId):
  30. return self.getData('studies',studyOrthancId)
  31. def getSeriesData(self, seriesOrthancId):
  32. return self.getData('series',seriesOrthancId)
  33. def getNumpy(self,level,orthancId):
  34. url=self.net.getCoreURL()
  35. url+='/'+level+'/'+orthancId+'/numpy'
  36. response=self.net.get(url,binary=True)
  37. return io.BytesIO(response.data)
  38. def getData(self, level, orthancId):
  39. url=self.net.getCoreURL()
  40. url+='/'+level+'/'+orthancId
  41. response=self.net.get(url)
  42. return extractJSON(response.data)
  43. def getDicomField(self,orthancInstanceId,dicomField):
  44. url=self.net.getCoreURL()
  45. url+='/instances/'+orthancInstanceId+'/content/'+dicomField
  46. response=self.net.get(url)
  47. try:
  48. encoding=chardet.detect(response.data)["encoding"]
  49. return response.data.decode(encoding)
  50. except TypeError:
  51. return ''
  52. def selectRows(self, qfilter):
  53. obj={}
  54. obj["Level"]="Instance"
  55. obj["Query"]=qfilter
  56. jsonData=json.dumps(obj)
  57. url=self.net.getCoreURL()
  58. url+='/tools/find'
  59. response=self.net.post(url,'json',jsonData)
  60. encoding=chardet.detect(response.data)["encoding"]
  61. return json.loads(response.data.decode(encoding))
  62. def upload(self, f) :
  63. url=self.net.getCoreURL()
  64. url+='/instances'
  65. fobj=open (f, 'rb')
  66. response=self.net.post(url,'octet-stream',fobj.read())
  67. try:
  68. encoding=chardet.detect(response.data)["encoding"]
  69. except AttributeError:
  70. print(response)
  71. return json.loads('{"status":"BAD"}')
  72. return json.loads(response.data.decode(encoding))
  73. def remove(self,level,orthancId):
  74. url=self.net.getCoreURL()
  75. url+='/'+level+'/'+orthancId
  76. response=self.net.delete(url)
  77. print(response.data)