11import os
22import shutil
33import tempfile
4+ from io import BytesIO
5+ from typing import List
46
57import pydicom
68import requests
79from dotenv import load_dotenv
810from flask import Flask , g , jsonify , render_template , request
911from flask_cors import CORS
12+ from pydicom .dataset import Dataset
1013
1114from BDD .MesuresSQLite import MesuresDB
12- from mock import simulate_modele_transform , simulate_rtstruct_generation
15+ from mock import simulate_rtstruct_generation2
1316
1417load_dotenv ()
1518
@@ -133,78 +136,39 @@ def segmentation(study_instance_uid):
133136 return jsonify ({"error" : "StudyInstanceUID not found" }), 404
134137
135138 try :
136- # Utiliser l'ID Orthanc pour récupérer les instances DICOM pour l'étude spécifiée
137- response = requests .get (f"{ ORTHANC_URL } /studies/{ orthanc_study_id } /instances" )
138- if response .status_code == 200 :
139- dicom_instances = response .json ()
140- print ("DICOM Instances for StudyInstanceUID" , study_instance_uid , ":" , dicom_instances )
141-
142- # Ici, ajouter logique de traitement des images DICOM récupérées
143- # Pour le moment, on simule la génération du RTStruct
144- rtstruct_path = simulate_rtstruct_generation () # mock
145-
146- return upload_rtstruct_mocked (rtstruct_path )
147- else :
148- return jsonify ({"error" : "Failed to retrieve DICOM instances" }), response .status_code
149- except requests .exceptions .RequestException as e :
150- print (f"Erreur lors du traitement du fichier DICOM : { e } " )
151- return jsonify ({"error" : "Server error" }), 500
152-
153-
154-
155- @app .route ('/seuillage/<study_instance_uid>' , methods = ['POST' ])
156- def apply_seuillage_to_study (study_instance_uid ):
157- orthanc_study_id = find_orthanc_study_id_by_study_instance_uid (study_instance_uid )
158- if not orthanc_study_id :
159- return jsonify ({"error" : "StudyInstanceUID not found" }), 404
160-
161- try :
139+ # Récupérer les métadonnées des instances DICOM pour l'étude spécifiée
162140 response = requests .get (f"{ ORTHANC_URL } /studies/{ orthanc_study_id } /instances" )
163141 if response .status_code != 200 :
164142 return jsonify ({"error" : "Failed to retrieve DICOM instances" }), response .status_code
165-
166- dicom_instances = response .json ()
167- temp_dir = tempfile .mkdtemp ()
168143
169- file_paths = []
170- for instance in dicom_instances :
144+ # Extraire les identifiants des instances DICOM à partir de la réponse JSON
145+ instances = response .json ()
146+ dicom_data = []
147+
148+ # Télécharger chaque fichier DICOM en utilisant son identifiant
149+ for instance in instances :
171150 instance_id = instance ['ID' ]
172- dicom_file = requests .get (f"{ ORTHANC_URL } /instances/{ instance_id } /file" , stream = True )
173- temp_file_path = os .path .join (temp_dir , f"{ instance_id } .dcm" )
174- with open (temp_file_path , 'wb' ) as f :
175- for chunk in dicom_file :
176- f .write (chunk )
177- file_paths .append (temp_file_path )
151+ dicom_response = requests .get (f"{ ORTHANC_URL } /instances/{ instance_id } /file" , stream = True )
178152
179- # Apply the seuillage transformation
180- modified_dicoms = simulate_modele_transform (file_paths )
181- print ("test" )
182- # Optionally upload modified DICOMs back to Orthanc
153+ if dicom_response .status_code == 200 :
154+ # Vous pouvez ici charger les données DICOM directement dans pydicom si nécessaire
155+ dicom_file = pydicom .dcmread (BytesIO (dicom_response .content ))
156+ dicom_data .append (dicom_file )
157+ else :
158+ print (f"Failed to download DICOM file for instance ID { instance_id } " )
183159
184- delete_dicom_instance (study_instance_uid )
185-
186- """
187- for modified_dicom in modified_dicoms:
188- print("Uploading")
189- temp_file_path = os.path.join(temp_dir, modified_dicom.filename)
190- modified_dicom.save_as(temp_file_path)
191- with open(temp_file_path, 'rb') as f:
192- files = {'file': (os.path.basename(temp_file_path), f, 'application/dicom')}
193- upload_response = requests.post(f"{ORTHANC_URL}/instances", files=files)
194- print("Upload response:", upload_response.status_code)
195- if upload_response.status_code not in [200, 202]:
196- print("Failed to upload modified DICOM file to Orthanc:", upload_response.status_code)
197- """
198- shutil .rmtree (temp_dir ) # Clean up temporary files
160+ print ("DICOM files retrieved and processed successfully." )
161+ #print(dicom_data[0])
162+ rtstruct = simulate_rtstruct_generation2 (dicom_data ) # mock
163+ print ("mon rtstruct c'est cela" )
164+ print (rtstruct )
165+ upload_rtstruct (rtstruct )
199166
167+ return jsonify ({"success" : "DICOM files retrieved and processed successfully." }), 200
200168 except requests .exceptions .RequestException as e :
201- return jsonify ({"error" : str (e )}), 500
202-
203- return jsonify ({"success" : "Seuillage applied and DICOMs uploaded." }), 200
169+ return jsonify ({"error" : f"Server error: { str (e )} " }), 500
204170
205171
206-
207-
208172def find_orthanc_study_id_by_study_instance_uid (study_instance_uid ):
209173 studies_response = requests .get (f"{ ORTHANC_URL } /studies" )
210174
@@ -228,7 +192,8 @@ def find_orthanc_study_id_by_study_instance_uid(study_instance_uid):
228192
229193 return None
230194
231- def upload_rtstruct_mocked (rtstruct_path ):
195+ """
196+ def upload_rtstruct(rtstruct_path):
232197 try:
233198 print(f"Uploading RTStruct from {rtstruct_path}")
234199
@@ -244,6 +209,45 @@ def upload_rtstruct_mocked(rtstruct_path):
244209 except Exception as e:
245210 print(e)
246211 return jsonify({"error": "Server error"}), 500
212+ """
213+
214+ def upload_rtstruct (rtstruct ):
215+ buffer = rtstruct .save_to_memory () # Récupère le buffer en mémoire contenant le RTStruct
216+ print ("Uploading RTStruct..." )
217+ print (buffer )
218+ try :
219+ files = {'file' : ('rtstruct.dcm' , buffer , 'application/dicom' )}
220+ response = requests .post (f"{ ORTHANC_URL } /instances" , files = files )
221+
222+ if response .status_code in [200 , 202 ]:
223+ orthanc_response = response .json () if response .content else "No JSON content in response"
224+ return jsonify ({"success" : "RTStruct uploaded successfully" , "OrthancResponse" : orthanc_response }), response .status_code
225+ else :
226+ return jsonify ({"error" : "Failed to upload RTStruct to Orthanc" , "OrthancResponse" : response .text }), response .status_code
227+ except Exception as e :
228+ print (e )
229+ return jsonify ({"error" : "Server error" }), 500
230+
231+
232+ def load_dicom_datasets (dicom_folder_path : str ) -> List [Dataset ]:
233+ """
234+ Charge tous les fichiers DICOM d'un dossier donné en datasets pydicom.
235+ """
236+ dicom_datasets = []
237+ for filename in os .listdir (dicom_folder_path ):
238+ if filename .endswith ('.dcm' ):
239+ file_path = os .path .join (dicom_folder_path , filename )
240+ try :
241+ ds = pydicom .dcmread (file_path )
242+ dicom_datasets .append (ds )
243+ except Exception as e :
244+ print (f"Erreur lors de la lecture du fichier DICOM { filename } : { e } " )
245+ continue # ou lever une exception selon les besoins de votre application
246+
247+ if not dicom_datasets :
248+ raise Exception ("Aucun fichier DICOM valide trouvé dans le dossier spécifié." )
249+
250+ return dicom_datasets
247251
248252def get_db ():
249253 db = getattr (g , '_database' , None )
0 commit comments