HeshamAI commited on
Commit
6fcfcd3
·
verified ·
1 Parent(s): 8723257

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -38
app.py CHANGED
@@ -139,9 +139,6 @@ class DicomAnalyzer:
139
  print(f"Handling key press: {key}")
140
  pan_amount = int(5 * self.zoom_factor)
141
 
142
- original_pan_x = self.pan_x
143
- original_pan_y = self.pan_y
144
-
145
  if key == 'ArrowLeft':
146
  self.pan_x = max(0, self.pan_x - pan_amount)
147
  elif key == 'ArrowRight':
@@ -155,7 +152,6 @@ class DicomAnalyzer:
155
  except Exception as e:
156
  print(f"Error handling keyboard input: {str(e)}")
157
  return self.display_image
158
-
159
  def analyze_roi(self, evt: gr.SelectData):
160
  try:
161
  if self.current_image is None:
@@ -174,7 +170,6 @@ class DicomAnalyzer:
174
  y = int(round(y))
175
 
176
  height, width = self.original_image.shape[:2]
177
-
178
  Y, X = np.ogrid[:height, :width]
179
  radius = self.circle_diameter / 2.0
180
  r_squared = radius * radius
@@ -224,6 +219,7 @@ class DicomAnalyzer:
224
  except Exception as e:
225
  print(f"Error analyzing ROI: {str(e)}")
226
  return self.display_image, f"Error analyzing ROI: {str(e)}"
 
227
  def update_display(self):
228
  try:
229
  if self.original_display is None:
@@ -279,22 +275,55 @@ class DicomAnalyzer:
279
  print(f"Error updating display: {str(e)}")
280
  return self.original_display
281
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
  def add_formulas_to_template(self, ws, row_pair, col_group, red_font):
283
- """Add formulas for each row pair and column group"""
284
  try:
285
- base_col = col_group[1] # Mean column
286
- std_col = col_group[2] # StdDev column
287
 
288
  row1, row2 = row_pair
289
 
290
- # Formula for first row: =Mean/StdDev
291
  formula1 = f"={base_col}{row1}/{std_col}{row1}"
292
  formula_col = get_column_letter(column_index_from_string(col_group[-1]) + 1)
293
  cell1 = ws[f"{formula_col}{row1}"]
294
  cell1.value = formula1
295
  cell1.font = red_font
296
 
297
- # Formula for second row: =(Mean1-Mean2)/StdDev2
298
  formula2 = f"=({base_col}{row1}-{base_col}{row2})/{std_col}{row2}"
299
  cell2 = ws[f"{formula_col}{row2}"]
300
  cell2.value = formula2
@@ -311,40 +340,26 @@ class DicomAnalyzer:
311
 
312
  wb = openpyxl.Workbook()
313
  ws = wb.active
314
-
315
  red_font = openpyxl.styles.Font(color="FF0000")
316
 
317
  column_groups = [
318
- ('B', 'C', 'D', 'E', 'F'), # First group
319
- ('H', 'I', 'J', 'K', 'L'), # Second group
320
- ('N', 'O', 'P', 'Q', 'R'), # Third group
321
- ('T', 'U', 'V', 'W', 'X'), # Fourth group
322
- ('Z', 'AA', 'AB', 'AC', 'AD'), # Fifth group
323
- ('AF', 'AG', 'AH', 'AI', 'AJ'), # Sixth group
324
- ('AL', 'AM', 'AN', 'AO', 'AP'), # Seventh group
325
- ('AR', 'AS', 'AT', 'AU', 'AV'), # Eighth group
326
- ('AX', 'AY', 'AZ', 'BA', 'BB'), # Ninth group
327
- ('BD', 'BE', 'BF', 'BG', 'BH'), # Tenth group
328
- ('BJ', 'BK', 'BL', 'BM', 'BN'), # Eleventh group
329
- ('BP', 'BQ', 'BR', 'BS', 'BT'), # Twelfth group
330
- ('BV', 'BW', 'BX', 'BY', 'BZ') # Thirteenth group
331
  ]
332
 
333
  row_pairs = [
334
- (2, 3), # 7mm
335
- (5, 6), # 6.5mm
336
- (8, 9), # 6mm
337
- (11, 12), # 5.5mm
338
- (14, 15), # 5mm
339
- (17, 18), # 4.5mm
340
- (20, 21), # 4mm
341
- (23, 24), # 3.5mm
342
- (26, 27), # 3mm
343
- (29, 30) # 2.5mm
344
  ]
345
 
346
  phantom_sizes = ['(7mm)', '(6.5mm)', '(6mm)', '(5.5mm)', '(5mm)',
347
  '(4.5mm)', '(4mm)', '(3.5mm)', '(3mm)', '(2.5mm)']
 
348
  for i, size in enumerate(phantom_sizes):
349
  header_cell = ws.cell(row=row_pairs[i][0]-1, column=1, value=size)
350
  header_cell.font = red_font
@@ -385,7 +400,6 @@ class DicomAnalyzer:
385
  return None, f"Error saving results: {str(e)}"
386
 
387
  def _write_result_to_cells(self, ws, result, cols, row):
388
- """Helper method to write a single result to worksheet cells"""
389
  ws[f"{cols[0]}{row}"] = float(result['Area (mm²)'])
390
  ws[f"{cols[1]}{row}"] = float(result['Mean'])
391
  ws[f"{cols[2]}{row}"] = float(result['StdDev'])
@@ -401,7 +415,6 @@ class DicomAnalyzer:
401
  return df.to_string(index=False)
402
 
403
  def add_blank_row(self, image):
404
- """Add a blank row to the results"""
405
  self.results.append({
406
  'Area (mm²)': '',
407
  'Mean': '',
@@ -413,7 +426,6 @@ class DicomAnalyzer:
413
  return image, self.format_results()
414
 
415
  def add_zero_row(self, image):
416
- """Add a row of zeros to the results"""
417
  self.results.append({
418
  'Area (mm²)': '0.000',
419
  'Mean': '0.000',
@@ -425,12 +437,13 @@ class DicomAnalyzer:
425
  return image, self.format_results()
426
 
427
  def undo_last(self, image):
428
- """Remove the last measurement"""
429
  if self.results:
430
  self.results.pop()
431
  if self.marks:
432
  self.marks.pop()
433
  return self.update_display(), self.format_results()
 
 
434
  def create_interface():
435
  print("Creating interface...")
436
  analyzer = DicomAnalyzer()
 
139
  print(f"Handling key press: {key}")
140
  pan_amount = int(5 * self.zoom_factor)
141
 
 
 
 
142
  if key == 'ArrowLeft':
143
  self.pan_x = max(0, self.pan_x - pan_amount)
144
  elif key == 'ArrowRight':
 
152
  except Exception as e:
153
  print(f"Error handling keyboard input: {str(e)}")
154
  return self.display_image
 
155
  def analyze_roi(self, evt: gr.SelectData):
156
  try:
157
  if self.current_image is None:
 
170
  y = int(round(y))
171
 
172
  height, width = self.original_image.shape[:2]
 
173
  Y, X = np.ogrid[:height, :width]
174
  radius = self.circle_diameter / 2.0
175
  r_squared = radius * radius
 
219
  except Exception as e:
220
  print(f"Error analyzing ROI: {str(e)}")
221
  return self.display_image, f"Error analyzing ROI: {str(e)}"
222
+
223
  def update_display(self):
224
  try:
225
  if self.original_display is None:
 
275
  print(f"Error updating display: {str(e)}")
276
  return self.original_display
277
 
278
+ def save_results(self):
279
+ """
280
+ Basic save function for raw results with improved error handling and logging
281
+ """
282
+ try:
283
+ if not self.results:
284
+ logger.warning("Attempted to save with no results")
285
+ return None, "No results to save"
286
+
287
+ df = pd.DataFrame(self.results)
288
+ columns_order = ['Area (mm²)', 'Mean', 'StdDev', 'Min', 'Max', 'Point']
289
+ df = df[columns_order]
290
+
291
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
292
+ output_file = f"analysis_results_{timestamp}.xlsx"
293
+
294
+ with pd.ExcelWriter(output_file, engine='openpyxl') as writer:
295
+ df.to_excel(writer, index=False, sheet_name='Results')
296
+
297
+ worksheet = writer.sheets['Results']
298
+ for idx, col in enumerate(df.columns):
299
+ max_length = max(
300
+ df[col].astype(str).apply(len).max(),
301
+ len(str(col))
302
+ ) + 2
303
+ worksheet.column_dimensions[get_column_letter(idx + 1)].width = max_length
304
+
305
+ logger.info(f"Results saved successfully to {output_file}")
306
+ return output_file, f"Results saved successfully to {output_file}"
307
+
308
+ except Exception as e:
309
+ error_msg = f"Error saving results: {str(e)}"
310
+ logger.error(error_msg)
311
+ logger.error(traceback.format_exc())
312
+ return None, error_msg
313
+
314
  def add_formulas_to_template(self, ws, row_pair, col_group, red_font):
 
315
  try:
316
+ base_col = col_group[1]
317
+ std_col = col_group[2]
318
 
319
  row1, row2 = row_pair
320
 
 
321
  formula1 = f"={base_col}{row1}/{std_col}{row1}"
322
  formula_col = get_column_letter(column_index_from_string(col_group[-1]) + 1)
323
  cell1 = ws[f"{formula_col}{row1}"]
324
  cell1.value = formula1
325
  cell1.font = red_font
326
 
 
327
  formula2 = f"=({base_col}{row1}-{base_col}{row2})/{std_col}{row2}"
328
  cell2 = ws[f"{formula_col}{row2}"]
329
  cell2.value = formula2
 
340
 
341
  wb = openpyxl.Workbook()
342
  ws = wb.active
 
343
  red_font = openpyxl.styles.Font(color="FF0000")
344
 
345
  column_groups = [
346
+ ('B', 'C', 'D', 'E', 'F'), ('H', 'I', 'J', 'K', 'L'),
347
+ ('N', 'O', 'P', 'Q', 'R'), ('T', 'U', 'V', 'W', 'X'),
348
+ ('Z', 'AA', 'AB', 'AC', 'AD'), ('AF', 'AG', 'AH', 'AI', 'AJ'),
349
+ ('AL', 'AM', 'AN', 'AO', 'AP'), ('AR', 'AS', 'AT', 'AU', 'AV'),
350
+ ('AX', 'AY', 'AZ', 'BA', 'BB'), ('BD', 'BE', 'BF', 'BG', 'BH'),
351
+ ('BJ', 'BK', 'BL', 'BM', 'BN'), ('BP', 'BQ', 'BR', 'BS', 'BT'),
352
+ ('BV', 'BW', 'BX', 'BY', 'BZ')
 
 
 
 
 
 
353
  ]
354
 
355
  row_pairs = [
356
+ (2, 3), (5, 6), (8, 9), (11, 12), (14, 15),
357
+ (17, 18), (20, 21), (23, 24), (26, 27), (29, 30)
 
 
 
 
 
 
 
 
358
  ]
359
 
360
  phantom_sizes = ['(7mm)', '(6.5mm)', '(6mm)', '(5.5mm)', '(5mm)',
361
  '(4.5mm)', '(4mm)', '(3.5mm)', '(3mm)', '(2.5mm)']
362
+
363
  for i, size in enumerate(phantom_sizes):
364
  header_cell = ws.cell(row=row_pairs[i][0]-1, column=1, value=size)
365
  header_cell.font = red_font
 
400
  return None, f"Error saving results: {str(e)}"
401
 
402
  def _write_result_to_cells(self, ws, result, cols, row):
 
403
  ws[f"{cols[0]}{row}"] = float(result['Area (mm²)'])
404
  ws[f"{cols[1]}{row}"] = float(result['Mean'])
405
  ws[f"{cols[2]}{row}"] = float(result['StdDev'])
 
415
  return df.to_string(index=False)
416
 
417
  def add_blank_row(self, image):
 
418
  self.results.append({
419
  'Area (mm²)': '',
420
  'Mean': '',
 
426
  return image, self.format_results()
427
 
428
  def add_zero_row(self, image):
 
429
  self.results.append({
430
  'Area (mm²)': '0.000',
431
  'Mean': '0.000',
 
437
  return image, self.format_results()
438
 
439
  def undo_last(self, image):
 
440
  if self.results:
441
  self.results.pop()
442
  if self.marks:
443
  self.marks.pop()
444
  return self.update_display(), self.format_results()
445
+
446
+ # Interface creation and main execution will be in the next part...
447
  def create_interface():
448
  print("Creating interface...")
449
  analyzer = DicomAnalyzer()