rushankg commited on
Commit
97fde1f
·
verified ·
1 Parent(s): cb5bfd0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +303 -3
app.py CHANGED
@@ -1,3 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import pandas as pd
3
  import os
@@ -195,7 +495,7 @@ def display_first_pair():
195
  return left_image, right_image, progress
196
 
197
  def end_session():
198
- """End the session and return CSV file."""
199
  if not state["evaluations"]:
200
  return None, "No evaluations recorded."
201
 
@@ -205,7 +505,7 @@ def end_session():
205
  state["current_index"] = 0
206
  state["evaluations"] = []
207
 
208
- return filepath, f"✅ Evaluations saved as: {filename}"
209
 
210
  # Gradio interface
211
  with gr.Blocks(title="X-Ray Quality Evaluation") as demo:
@@ -266,7 +566,7 @@ with gr.Blocks(title="X-Ray Quality Evaluation") as demo:
266
  # File download
267
  download_file = gr.File(
268
  label="CSV Results",
269
- visible=False
270
  )
271
 
272
  # Event handlers
 
1
+ # import gradio as gr
2
+ # import pandas as pd
3
+ # import os
4
+ # from pathlib import Path
5
+ # from datetime import datetime
6
+ # import random
7
+ # from PIL import Image
8
+
9
+ # # Global state
10
+ # state = {
11
+ # "session_active": False,
12
+ # "image_pairs": [],
13
+ # "current_index": 0,
14
+ # "evaluations": [],
15
+ # "doctor_name": "",
16
+ # }
17
+
18
+ # # Helper functions
19
+ # def get_image_files(folder_path):
20
+ # """Get all image files from a folder."""
21
+ # valid_extensions = {'.jpg', '.jpeg', '.png', '.gif'}
22
+ # files = {}
23
+ # if os.path.exists(folder_path):
24
+ # for file in os.listdir(folder_path):
25
+ # if Path(file).suffix.lower() in valid_extensions:
26
+ # files[file] = file
27
+ # return files
28
+
29
+ # def create_image_pairs():
30
+ # """Create paired images from roentgen and pedisynth folders."""
31
+ # roentgen_files = get_image_files("roentgen")
32
+ # pedisynth_files = get_image_files("pedisynth")
33
+
34
+ # pairs = []
35
+
36
+ # # Match files by exact filename across folders
37
+ # for filename in roentgen_files:
38
+ # if filename in pedisynth_files:
39
+ # # Randomly decide which image goes left and which goes right
40
+ # is_roentgen_left = random.choice([True, False])
41
+ # # Extract condition by removing the file extension and last part (number)
42
+ # name_without_ext = Path(filename).stem
43
+ # parts = name_without_ext.rsplit(' ', 1)
44
+ # condition = parts[0] if len(parts) > 1 else name_without_ext
45
+
46
+ # pairs.append({
47
+ # 'roentgen': filename,
48
+ # 'pedisynth': filename,
49
+ # 'condition': condition,
50
+ # 'base_name': name_without_ext,
51
+ # 'roentgen_left': is_roentgen_left
52
+ # })
53
+
54
+ # # Randomize order
55
+ # random.shuffle(pairs)
56
+ # return pairs
57
+
58
+ # def load_image(folder, filename):
59
+ # """Load image from folder."""
60
+ # filepath = os.path.join(folder, filename)
61
+ # try:
62
+ # return Image.open(filepath)
63
+ # except Exception as e:
64
+ # print(f"Error loading image {filename}: {e}")
65
+ # return None
66
+
67
+ # def save_evaluations(evaluations, doctor_name):
68
+ # """Save evaluations to CSV."""
69
+ # df = pd.DataFrame(evaluations)
70
+ # timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
71
+ # filename = f"evaluations_{doctor_name}_{timestamp}.csv"
72
+
73
+ # # Save to outputs folder if it exists, otherwise current directory
74
+ # output_dir = "outputs"
75
+ # os.makedirs(output_dir, exist_ok=True)
76
+ # filepath = os.path.join(output_dir, filename)
77
+
78
+ # df.to_csv(filepath, index=False)
79
+ # return filepath, filename
80
+
81
+ # def start_session(doctor_name):
82
+ # """Start a new evaluation session."""
83
+ # if not doctor_name.strip():
84
+ # return (gr.update(visible=False), "Please enter your name to start a session.")
85
+
86
+ # state["doctor_name"] = doctor_name
87
+ # state["image_pairs"] = create_image_pairs()
88
+ # state["session_active"] = True
89
+ # state["current_index"] = 0
90
+ # state["evaluations"] = []
91
+
92
+ # if not state["image_pairs"]:
93
+ # return (gr.update(visible=False), "No image pairs found. Please ensure both roentgen/ and pedisynth/ folders have matching images.")
94
+
95
+ # return (gr.update(visible=True), "")
96
+
97
+ # def get_preference_a():
98
+ # """Handle preference for option A."""
99
+ # if not state["session_active"]:
100
+ # return None, None, "Session not active."
101
+
102
+ # current_pair = state["image_pairs"][state["current_index"]]
103
+ # preferred_source = state["current_left_source"]
104
+
105
+ # state["evaluations"].append({
106
+ # 'timestamp': datetime.now().isoformat(),
107
+ # 'condition': current_pair['condition'],
108
+ # 'base_name': current_pair['base_name'],
109
+ # 'preference': preferred_source.capitalize(),
110
+ # 'doctor': state["doctor_name"]
111
+ # })
112
+
113
+ # state["current_index"] += 1
114
+
115
+ # if state["current_index"] >= len(state["image_pairs"]):
116
+ # state["session_active"] = False
117
+ # return None, None, "✅ Evaluation complete! All images have been reviewed."
118
+
119
+ # current_pair = state["image_pairs"][state["current_index"]]
120
+
121
+ # if current_pair['roentgen_left']:
122
+ # left_image = load_image("roentgen", current_pair['roentgen'])
123
+ # right_image = load_image("pedisynth", current_pair['pedisynth'])
124
+ # state["current_left_source"] = "roentgen"
125
+ # state["current_right_source"] = "pedisynth"
126
+ # else:
127
+ # left_image = load_image("pedisynth", current_pair['pedisynth'])
128
+ # right_image = load_image("roentgen", current_pair['roentgen'])
129
+ # state["current_left_source"] = "pedisynth"
130
+ # state["current_right_source"] = "roentgen"
131
+
132
+ # progress = f"Image {state['current_index'] + 1} of {len(state['image_pairs'])} | Condition: {current_pair['condition']}"
133
+
134
+ # return left_image, right_image, progress
135
+
136
+ # def get_preference_b():
137
+ # """Handle preference for option B."""
138
+ # if not state["session_active"]:
139
+ # return None, None, "Session not active."
140
+
141
+ # current_pair = state["image_pairs"][state["current_index"]]
142
+ # preferred_source = state["current_right_source"]
143
+
144
+ # state["evaluations"].append({
145
+ # 'timestamp': datetime.now().isoformat(),
146
+ # 'condition': current_pair['condition'],
147
+ # 'base_name': current_pair['base_name'],
148
+ # 'preference': preferred_source.capitalize(),
149
+ # 'doctor': state["doctor_name"]
150
+ # })
151
+
152
+ # state["current_index"] += 1
153
+
154
+ # if state["current_index"] >= len(state["image_pairs"]):
155
+ # state["session_active"] = False
156
+ # return None, None, "✅ Evaluation complete! All images have been reviewed."
157
+
158
+ # current_pair = state["image_pairs"][state["current_index"]]
159
+
160
+ # if current_pair['roentgen_left']:
161
+ # left_image = load_image("roentgen", current_pair['roentgen'])
162
+ # right_image = load_image("pedisynth", current_pair['pedisynth'])
163
+ # state["current_left_source"] = "roentgen"
164
+ # state["current_right_source"] = "pedisynth"
165
+ # else:
166
+ # left_image = load_image("pedisynth", current_pair['pedisynth'])
167
+ # right_image = load_image("roentgen", current_pair['roentgen'])
168
+ # state["current_left_source"] = "pedisynth"
169
+ # state["current_right_source"] = "roentgen"
170
+
171
+ # progress = f"Image {state['current_index'] + 1} of {len(state['image_pairs'])} | Condition: {current_pair['condition']}"
172
+
173
+ # return left_image, right_image, progress
174
+
175
+ # def display_first_pair():
176
+ # """Display the first image pair after session starts."""
177
+ # if not state["session_active"]:
178
+ # return None, None, ""
179
+
180
+ # current_pair = state["image_pairs"][state["current_index"]]
181
+
182
+ # if current_pair['roentgen_left']:
183
+ # left_image = load_image("roentgen", current_pair['roentgen'])
184
+ # right_image = load_image("pedisynth", current_pair['pedisynth'])
185
+ # state["current_left_source"] = "roentgen"
186
+ # state["current_right_source"] = "pedisynth"
187
+ # else:
188
+ # left_image = load_image("pedisynth", current_pair['pedisynth'])
189
+ # right_image = load_image("roentgen", current_pair['roentgen'])
190
+ # state["current_left_source"] = "pedisynth"
191
+ # state["current_right_source"] = "roentgen"
192
+
193
+ # progress = f"Image {state['current_index'] + 1} of {len(state['image_pairs'])} | Condition: {current_pair['condition']}"
194
+
195
+ # return left_image, right_image, progress
196
+
197
+ # def end_session():
198
+ # """End the session and return CSV file."""
199
+ # if not state["evaluations"]:
200
+ # return None, "No evaluations recorded."
201
+
202
+ # filepath, filename = save_evaluations(state["evaluations"], state["doctor_name"])
203
+
204
+ # state["session_active"] = False
205
+ # state["current_index"] = 0
206
+ # state["evaluations"] = []
207
+
208
+ # return filepath, f"✅ Evaluations saved as: {filename}"
209
+
210
+ # # Gradio interface
211
+ # with gr.Blocks(title="X-Ray Quality Evaluation") as demo:
212
+ # gr.Markdown("# 🏥 X-Ray Quality Evaluation System")
213
+ # gr.Markdown("**Pairwise Preference Test for Synthetic X-Ray Images**")
214
+
215
+ # with gr.Row():
216
+ # with gr.Column(scale=1):
217
+ # gr.Markdown("### Start Session")
218
+ # doctor_name_input = gr.Textbox(
219
+ # label="Enter your name:",
220
+ # placeholder="Dr. Smith"
221
+ # )
222
+ # start_btn = gr.Button("Start Session", variant="primary", size="lg")
223
+
224
+ # with gr.Column(scale=1):
225
+ # gr.Markdown("### Results")
226
+ # download_btn = gr.Button("End Session & Download Results", variant="primary", size="lg")
227
+ # result_message = gr.Textbox(
228
+ # label="Status",
229
+ # interactive=False,
230
+ # show_label=True
231
+ # )
232
+
233
+ # error_section = gr.Textbox(
234
+ # label="Message",
235
+ # interactive=False,
236
+ # show_label=True,
237
+ # value=""
238
+ # )
239
+
240
+ # # Image comparison section
241
+ # with gr.Group(visible=False) as eval_section:
242
+ # gr.Markdown("### Compare Images")
243
+
244
+ # progress_text = gr.Textbox(
245
+ # label="Progress",
246
+ # interactive=False,
247
+ # show_label=True
248
+ # )
249
+
250
+ # with gr.Row():
251
+ # image_a = gr.Image(
252
+ # label="Option A",
253
+ # show_label=True,
254
+ # type="pil"
255
+ # )
256
+ # image_b = gr.Image(
257
+ # label="Option B",
258
+ # show_label=True,
259
+ # type="pil"
260
+ # )
261
+
262
+ # with gr.Row():
263
+ # pref_a = gr.Button("👈 Prefer Option A", size="lg")
264
+ # pref_b = gr.Button("👉 Prefer Option B", size="lg")
265
+
266
+ # # File download
267
+ # download_file = gr.File(
268
+ # label="CSV Results",
269
+ # visible=False
270
+ # )
271
+
272
+ # # Event handlers
273
+ # start_btn.click(
274
+ # start_session,
275
+ # inputs=doctor_name_input,
276
+ # outputs=[eval_section, error_section]
277
+ # ).then(
278
+ # display_first_pair,
279
+ # outputs=[image_a, image_b, progress_text]
280
+ # )
281
+
282
+ # pref_a.click(
283
+ # get_preference_a,
284
+ # outputs=[image_a, image_b, progress_text]
285
+ # )
286
+
287
+ # pref_b.click(
288
+ # get_preference_b,
289
+ # outputs=[image_a, image_b, progress_text]
290
+ # )
291
+
292
+ # download_btn.click(
293
+ # end_session,
294
+ # outputs=[download_file, result_message]
295
+ # )
296
+
297
+ # if __name__ == "__main__":
298
+ # demo.launch()
299
+
300
+
301
  import gradio as gr
302
  import pandas as pd
303
  import os
 
495
  return left_image, right_image, progress
496
 
497
  def end_session():
498
+ """End the session and return CSV file for download."""
499
  if not state["evaluations"]:
500
  return None, "No evaluations recorded."
501
 
 
505
  state["current_index"] = 0
506
  state["evaluations"] = []
507
 
508
+ return filepath, f"✅ Evaluations ready to download: {filename}"
509
 
510
  # Gradio interface
511
  with gr.Blocks(title="X-Ray Quality Evaluation") as demo:
 
566
  # File download
567
  download_file = gr.File(
568
  label="CSV Results",
569
+ interactive=False
570
  )
571
 
572
  # Event handlers