changeset 4748:4336642b8cff

ignore JSON files in sample Python upload scripts
author Sebastien Jodogne <s.jodogne@gmail.com>
date Thu, 08 Jul 2021 14:42:20 +0200
parents 24dbf3f013d9
children 1a061bc2d6ca
files OrthancServer/Resources/Samples/ImportDicomFiles/ImportDicomFiles.py OrthancServer/Resources/Samples/ImportDicomFiles/OrthancImport.py
diffstat 2 files changed, 75 insertions(+), 23 deletions(-) [+]
line wrap: on
line diff
--- a/OrthancServer/Resources/Samples/ImportDicomFiles/ImportDicomFiles.py	Thu Jul 08 12:56:18 2021 +0200
+++ b/OrthancServer/Resources/Samples/ImportDicomFiles/ImportDicomFiles.py	Thu Jul 08 14:42:20 2021 +0200
@@ -19,11 +19,12 @@
 # along with this program. If not, see <http://www.gnu.org/licenses/>.
 
 
+import base64
+import httplib2
+import json
 import os
-import sys
 import os.path
-import httplib2
-import base64
+import sys
 
 if len(sys.argv) != 4 and len(sys.argv) != 6:
     print("""
@@ -40,23 +41,42 @@
 
 URL = 'http://%s:%d/instances' % (sys.argv[1], int(sys.argv[2]))
 
-success_count = 0
+dicom_count = 0
+json_count = 0
 total_file_count = 0
 
 
+def IsJson(content):
+    try:
+        if (sys.version_info >= (3, 0)):
+            json.loads(content.decode())
+            return True
+        else:
+            json.loads(content)
+            return True
+    except:
+        return False
+
+
 # This function will upload a single file to Orthanc through the REST API
 def UploadFile(path):
-    global success_count
+    global dicom_count
+    global json_count
     global total_file_count
 
-    f = open(path, "rb")
+    f = open(path, 'rb')
     content = f.read()
     f.close()
     total_file_count += 1
 
+    sys.stdout.write('Importing %s' % path)
+
+    if IsJson(content):
+        sys.stdout.write(' => ignored JSON file\n')
+        json_count += 1
+        return
+
     try:
-        sys.stdout.write("Importing %s" % path)
-
         h = httplib2.Http()
 
         headers = { 'content-type' : 'application/dicom' }
@@ -73,24 +93,24 @@
             # not always work)
             # http://en.wikipedia.org/wiki/Basic_access_authentication
             creds_str = username + ':' + password
-            creds_str_bytes = creds_str.encode("ascii")
+            creds_str_bytes = creds_str.encode('ascii')
             creds_str_bytes_b64 = b'Basic ' + base64.b64encode(creds_str_bytes)
-            headers['authorization'] = creds_str_bytes_b64.decode("ascii")
+            headers['authorization'] = creds_str_bytes_b64.decode('ascii')
 
         resp, content = h.request(URL, 'POST', 
                                   body = content,
                                   headers = headers)
 
         if resp.status == 200:
-            sys.stdout.write(" => success\n")
-            success_count += 1
+            sys.stdout.write(' => success\n')
+            dicom_count += 1
         else:
-            sys.stdout.write(" => failure (Is it a DICOM file? Is there a password?)\n")
+            sys.stdout.write(' => failure (Is it a DICOM file? Is there a password?)\n')
 
     except:
         type, value, traceback = sys.exc_info()
         sys.stderr.write(str(value))
-        sys.stdout.write(" => unable to connect (Is Orthanc running? Is there a password?)\n")
+        sys.stdout.write(' => unable to connect (Is Orthanc running? Is there a password?)\n')
 
 
 if os.path.isfile(sys.argv[3]):
@@ -102,7 +122,13 @@
         for f in files:
             UploadFile(os.path.join(root, f))
 
-if success_count == total_file_count:
-    print("\nSummary: all %d DICOM file(s) have been imported successfully" % success_count)
+
+if dicom_count + json_count == total_file_count:
+    print('\nSUCCESS: %d DICOM file(s) have been successfully imported' % dicom_count)
 else:
-    print("\nSummary: %d out of %d files have been imported successfully as DICOM instances" % (success_count, total_file_count))
+    print('\nWARNING: Only %d out of %d file(s) have been successfully imported as DICOM instance(s)' % (dicom_count, total_file_count - json_count))
+
+if json_count != 0:
+    print('NB: %d JSON file(s) have been ignored' % json_count)
+
+print('')
--- a/OrthancServer/Resources/Samples/ImportDicomFiles/OrthancImport.py	Thu Jul 08 12:56:18 2021 +0200
+++ b/OrthancServer/Resources/Samples/ImportDicomFiles/OrthancImport.py	Thu Jul 08 14:42:20 2021 +0200
@@ -22,6 +22,7 @@
 import argparse
 import bz2
 import gzip
+import json
 import os
 import requests
 import sys
@@ -71,12 +72,31 @@
 
 IMPORTED_STUDIES = set()
 COUNT_ERROR = 0
-COUNT_SUCCESS = 0
-        
+COUNT_DICOM = 0
+COUNT_JSON = 0
+
+
+def IsJson(content):
+    try:
+        if (sys.version_info >= (3, 0)):
+            json.loads(content.decode())
+            return True
+        else:
+            json.loads(content)
+            return True
+    except:
+        return False
+
+
 def UploadBuffer(dicom):
     global IMPORTED_STUDIES
     global COUNT_ERROR
-    global COUNT_SUCCESS
+    global COUNT_DICOM
+    global COUNT_JSON
+
+    if IsJson(dicom):
+        COUNT_JSON += 1
+        return
     
     auth = HTTPBasicAuth(args.username, args.password)
     r = requests.post('%s/instances' % args.url, auth = auth, data = dicom)
@@ -93,7 +113,7 @@
             raise
         
     info = r.json()
-    COUNT_SUCCESS += 1
+    COUNT_DICOM += 1
 
     if not info['ParentStudy'] in IMPORTED_STUDIES:
         IMPORTED_STUDIES.add(info['ParentStudy'])
@@ -219,8 +239,14 @@
         
 
 print('')
-print('Status:')
-print('  %d DICOM instances properly imported' % COUNT_SUCCESS)
+
+if COUNT_ERROR == 0:
+    print('SUCCESS:')
+else:
+    print('WARNING:')
+    
+print('  %d DICOM instances properly imported' % COUNT_DICOM)
 print('  %d DICOM studies properly imported' % len(IMPORTED_STUDIES))
+print('  %d JSON files ignored' % COUNT_JSON)
 print('  Error in %d files' % COUNT_ERROR)
 print('')