Spaces:
Running
Running
File size: 20,685 Bytes
97fde1f b6ae48f c697283 f443e9c c697283 f443e9c c697283 b6ae48f c697283 af5ba41 c697283 f443e9c c697283 af5ba41 c697283 f443e9c c697283 f443e9c c697283 b6ae48f c697283 af5ba41 a22def4 af5ba41 a22def4 af5ba41 a22def4 af5ba41 fa35a63 af5ba41 8657052 af5ba41 a22def4 af5ba41 b6ae48f af5ba41 b6ae48f af5ba41 b6ae48f af5ba41 c697283 b6ae48f c697283 b6ae48f af5ba41 b6ae48f af5ba41 fa35a63 af5ba41 fa35a63 af5ba41 fa35a63 af5ba41 b6ae48f af5ba41 b6ae48f af5ba41 b6ae48f 97fde1f b6ae48f 97fde1f b6ae48f c697283 b6ae48f af5ba41 b6ae48f c697283 b6ae48f c697283 c8c9007 c697283 b6ae48f 97fde1f b6ae48f af5ba41 b6ae48f af5ba41 b6ae48f d733cce af5ba41 b6ae48f d733cce af5ba41 b6ae48f af5ba41 b6ae48f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 |
# import gradio as gr
# import pandas as pd
# import os
# from pathlib import Path
# from datetime import datetime
# import random
# from PIL import Image
# # Global state
# state = {
# "session_active": False,
# "image_pairs": [],
# "current_index": 0,
# "evaluations": [],
# "doctor_name": "",
# }
# # Helper functions
# def get_image_files(folder_path):
# """Get all image files from a folder."""
# valid_extensions = {'.jpg', '.jpeg', '.png', '.gif'}
# files = {}
# if os.path.exists(folder_path):
# for file in os.listdir(folder_path):
# if Path(file).suffix.lower() in valid_extensions:
# files[file] = file
# return files
# def create_image_pairs():
# """Create paired images from roentgen and pedisynth folders."""
# roentgen_files = get_image_files("roentgen")
# pedisynth_files = get_image_files("pedisynth")
# pairs = []
# # Match files by exact filename across folders
# for filename in roentgen_files:
# if filename in pedisynth_files:
# # Randomly decide which image goes left and which goes right
# is_roentgen_left = random.choice([True, False])
# # Extract condition by removing the file extension and last part (number)
# name_without_ext = Path(filename).stem
# parts = name_without_ext.rsplit(' ', 1)
# condition = parts[0] if len(parts) > 1 else name_without_ext
# pairs.append({
# 'roentgen': filename,
# 'pedisynth': filename,
# 'condition': condition,
# 'base_name': name_without_ext,
# 'roentgen_left': is_roentgen_left
# })
# # Randomize order
# random.shuffle(pairs)
# return pairs
# def load_image(folder, filename):
# """Load image from folder."""
# filepath = os.path.join(folder, filename)
# try:
# return Image.open(filepath)
# except Exception as e:
# print(f"Error loading image {filename}: {e}")
# return None
# def save_evaluations(evaluations, doctor_name):
# """Save evaluations to CSV."""
# df = pd.DataFrame(evaluations)
# timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
# filename = f"evaluations_{doctor_name}_{timestamp}.csv"
# # Save to outputs folder if it exists, otherwise current directory
# output_dir = "outputs"
# os.makedirs(output_dir, exist_ok=True)
# filepath = os.path.join(output_dir, filename)
# df.to_csv(filepath, index=False)
# return filepath, filename
# def start_session(doctor_name):
# """Start a new evaluation session."""
# if not doctor_name.strip():
# return (gr.update(visible=False), "Please enter your name to start a session.")
# state["doctor_name"] = doctor_name
# state["image_pairs"] = create_image_pairs()
# state["session_active"] = True
# state["current_index"] = 0
# state["evaluations"] = []
# if not state["image_pairs"]:
# return (gr.update(visible=False), "No image pairs found. Please ensure both roentgen/ and pedisynth/ folders have matching images.")
# return (gr.update(visible=True), "")
# def get_preference_a():
# """Handle preference for option A."""
# if not state["session_active"]:
# return None, None, "Session not active."
# current_pair = state["image_pairs"][state["current_index"]]
# preferred_source = state["current_left_source"]
# state["evaluations"].append({
# 'timestamp': datetime.now().isoformat(),
# 'condition': current_pair['condition'],
# 'base_name': current_pair['base_name'],
# 'preference': preferred_source.capitalize(),
# 'doctor': state["doctor_name"]
# })
# state["current_index"] += 1
# if state["current_index"] >= len(state["image_pairs"]):
# state["session_active"] = False
# return None, None, "β
Evaluation complete! All images have been reviewed."
# current_pair = state["image_pairs"][state["current_index"]]
# if current_pair['roentgen_left']:
# left_image = load_image("roentgen", current_pair['roentgen'])
# right_image = load_image("pedisynth", current_pair['pedisynth'])
# state["current_left_source"] = "roentgen"
# state["current_right_source"] = "pedisynth"
# else:
# left_image = load_image("pedisynth", current_pair['pedisynth'])
# right_image = load_image("roentgen", current_pair['roentgen'])
# state["current_left_source"] = "pedisynth"
# state["current_right_source"] = "roentgen"
# progress = f"Image {state['current_index'] + 1} of {len(state['image_pairs'])} | Condition: {current_pair['condition']}"
# return left_image, right_image, progress
# def get_preference_b():
# """Handle preference for option B."""
# if not state["session_active"]:
# return None, None, "Session not active."
# current_pair = state["image_pairs"][state["current_index"]]
# preferred_source = state["current_right_source"]
# state["evaluations"].append({
# 'timestamp': datetime.now().isoformat(),
# 'condition': current_pair['condition'],
# 'base_name': current_pair['base_name'],
# 'preference': preferred_source.capitalize(),
# 'doctor': state["doctor_name"]
# })
# state["current_index"] += 1
# if state["current_index"] >= len(state["image_pairs"]):
# state["session_active"] = False
# return None, None, "β
Evaluation complete! All images have been reviewed."
# current_pair = state["image_pairs"][state["current_index"]]
# if current_pair['roentgen_left']:
# left_image = load_image("roentgen", current_pair['roentgen'])
# right_image = load_image("pedisynth", current_pair['pedisynth'])
# state["current_left_source"] = "roentgen"
# state["current_right_source"] = "pedisynth"
# else:
# left_image = load_image("pedisynth", current_pair['pedisynth'])
# right_image = load_image("roentgen", current_pair['roentgen'])
# state["current_left_source"] = "pedisynth"
# state["current_right_source"] = "roentgen"
# progress = f"Image {state['current_index'] + 1} of {len(state['image_pairs'])} | Condition: {current_pair['condition']}"
# return left_image, right_image, progress
# def display_first_pair():
# """Display the first image pair after session starts."""
# if not state["session_active"]:
# return None, None, ""
# current_pair = state["image_pairs"][state["current_index"]]
# if current_pair['roentgen_left']:
# left_image = load_image("roentgen", current_pair['roentgen'])
# right_image = load_image("pedisynth", current_pair['pedisynth'])
# state["current_left_source"] = "roentgen"
# state["current_right_source"] = "pedisynth"
# else:
# left_image = load_image("pedisynth", current_pair['pedisynth'])
# right_image = load_image("roentgen", current_pair['roentgen'])
# state["current_left_source"] = "pedisynth"
# state["current_right_source"] = "roentgen"
# progress = f"Image {state['current_index'] + 1} of {len(state['image_pairs'])} | Condition: {current_pair['condition']}"
# return left_image, right_image, progress
# def end_session():
# """End the session and return CSV file."""
# if not state["evaluations"]:
# return None, "No evaluations recorded."
# filepath, filename = save_evaluations(state["evaluations"], state["doctor_name"])
# state["session_active"] = False
# state["current_index"] = 0
# state["evaluations"] = []
# return filepath, f"β
Evaluations saved as: {filename}"
# # Gradio interface
# with gr.Blocks(title="X-Ray Quality Evaluation") as demo:
# gr.Markdown("# π₯ X-Ray Quality Evaluation System")
# gr.Markdown("**Pairwise Preference Test for Synthetic X-Ray Images**")
# with gr.Row():
# with gr.Column(scale=1):
# gr.Markdown("### Start Session")
# doctor_name_input = gr.Textbox(
# label="Enter your name:",
# placeholder="Dr. Smith"
# )
# start_btn = gr.Button("Start Session", variant="primary", size="lg")
# with gr.Column(scale=1):
# gr.Markdown("### Results")
# download_btn = gr.Button("End Session & Download Results", variant="primary", size="lg")
# result_message = gr.Textbox(
# label="Status",
# interactive=False,
# show_label=True
# )
# error_section = gr.Textbox(
# label="Message",
# interactive=False,
# show_label=True,
# value=""
# )
# # Image comparison section
# with gr.Group(visible=False) as eval_section:
# gr.Markdown("### Compare Images")
# progress_text = gr.Textbox(
# label="Progress",
# interactive=False,
# show_label=True
# )
# with gr.Row():
# image_a = gr.Image(
# label="Option A",
# show_label=True,
# type="pil"
# )
# image_b = gr.Image(
# label="Option B",
# show_label=True,
# type="pil"
# )
# with gr.Row():
# pref_a = gr.Button("π Prefer Option A", size="lg")
# pref_b = gr.Button("π Prefer Option B", size="lg")
# # File download
# download_file = gr.File(
# label="CSV Results",
# visible=False
# )
# # Event handlers
# start_btn.click(
# start_session,
# inputs=doctor_name_input,
# outputs=[eval_section, error_section]
# ).then(
# display_first_pair,
# outputs=[image_a, image_b, progress_text]
# )
# pref_a.click(
# get_preference_a,
# outputs=[image_a, image_b, progress_text]
# )
# pref_b.click(
# get_preference_b,
# outputs=[image_a, image_b, progress_text]
# )
# download_btn.click(
# end_session,
# outputs=[download_file, result_message]
# )
# if __name__ == "__main__":
# demo.launch()
import gradio as gr
import pandas as pd
import os
from pathlib import Path
from datetime import datetime
import random
from PIL import Image
# Global state
state = {
"session_active": False,
"image_pairs": [],
"current_index": 0,
"evaluations": [],
"doctor_name": "",
}
# Helper functions
def get_image_files(folder_path):
"""Get all image files from a folder."""
valid_extensions = {'.jpg', '.jpeg', '.png', '.gif'}
files = {}
if os.path.exists(folder_path):
for file in os.listdir(folder_path):
if Path(file).suffix.lower() in valid_extensions:
files[file] = file
return files
def create_image_pairs():
"""Create paired images from roentgen and pedisynth folders."""
roentgen_files = get_image_files("roentgen")
pedisynth_files = get_image_files("pedisynth")
pairs = []
# Match files by exact filename across folders
for filename in roentgen_files:
if filename in pedisynth_files:
# Randomly decide which image goes left and which goes right
is_roentgen_left = random.choice([True, False])
# Extract condition by removing the file extension and last part (number)
name_without_ext = Path(filename).stem
parts = name_without_ext.rsplit(' ', 1)
condition = parts[0] if len(parts) > 1 else name_without_ext
pairs.append({
'roentgen': filename,
'pedisynth': filename,
'condition': condition,
'base_name': name_without_ext,
'roentgen_left': is_roentgen_left
})
# Randomize order
random.shuffle(pairs)
return pairs
def load_image(folder, filename):
"""Load image from folder."""
filepath = os.path.join(folder, filename)
try:
return Image.open(filepath)
except Exception as e:
print(f"Error loading image {filename}: {e}")
return None
def save_evaluations(evaluations, doctor_name):
"""Save evaluations to CSV."""
df = pd.DataFrame(evaluations)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"evaluations_{doctor_name}_{timestamp}.csv"
# Save to outputs folder if it exists, otherwise current directory
output_dir = "outputs"
os.makedirs(output_dir, exist_ok=True)
filepath = os.path.join(output_dir, filename)
df.to_csv(filepath, index=False)
return filepath, filename
def start_session(doctor_name):
"""Start a new evaluation session."""
if not doctor_name.strip():
return (gr.update(visible=False), "Please enter your name to start a session.")
state["doctor_name"] = doctor_name
state["image_pairs"] = create_image_pairs()
state["session_active"] = True
state["current_index"] = 0
state["evaluations"] = []
if not state["image_pairs"]:
return (gr.update(visible=False), "No image pairs found. Please ensure both roentgen/ and pedisynth/ folders have matching images.")
return (gr.update(visible=True), "")
def get_preference_a():
"""Handle preference for option A."""
if not state["session_active"]:
return None, None, "Session not active."
current_pair = state["image_pairs"][state["current_index"]]
preferred_source = state["current_left_source"]
state["evaluations"].append({
'timestamp': datetime.now().isoformat(),
'condition': current_pair['condition'],
'base_name': current_pair['base_name'],
'preference': preferred_source.capitalize(),
'doctor': state["doctor_name"]
})
state["current_index"] += 1
if state["current_index"] >= len(state["image_pairs"]):
state["session_active"] = False
return None, None, "β
Evaluation complete! All images have been reviewed."
current_pair = state["image_pairs"][state["current_index"]]
if current_pair['roentgen_left']:
left_image = load_image("roentgen", current_pair['roentgen'])
right_image = load_image("pedisynth", current_pair['pedisynth'])
state["current_left_source"] = "roentgen"
state["current_right_source"] = "pedisynth"
else:
left_image = load_image("pedisynth", current_pair['pedisynth'])
right_image = load_image("roentgen", current_pair['roentgen'])
state["current_left_source"] = "pedisynth"
state["current_right_source"] = "roentgen"
progress = f"Image {state['current_index'] + 1} of {len(state['image_pairs'])} | Condition: {current_pair['condition']}"
return left_image, right_image, progress
def get_preference_b():
"""Handle preference for option B."""
if not state["session_active"]:
return None, None, "Session not active."
current_pair = state["image_pairs"][state["current_index"]]
preferred_source = state["current_right_source"]
state["evaluations"].append({
'timestamp': datetime.now().isoformat(),
'condition': current_pair['condition'],
'base_name': current_pair['base_name'],
'preference': preferred_source.capitalize(),
'doctor': state["doctor_name"]
})
state["current_index"] += 1
if state["current_index"] >= len(state["image_pairs"]):
state["session_active"] = False
return None, None, "β
Evaluation complete! All images have been reviewed."
current_pair = state["image_pairs"][state["current_index"]]
if current_pair['roentgen_left']:
left_image = load_image("roentgen", current_pair['roentgen'])
right_image = load_image("pedisynth", current_pair['pedisynth'])
state["current_left_source"] = "roentgen"
state["current_right_source"] = "pedisynth"
else:
left_image = load_image("pedisynth", current_pair['pedisynth'])
right_image = load_image("roentgen", current_pair['roentgen'])
state["current_left_source"] = "pedisynth"
state["current_right_source"] = "roentgen"
progress = f"Image {state['current_index'] + 1} of {len(state['image_pairs'])} | Condition: {current_pair['condition']}"
return left_image, right_image, progress
def display_first_pair():
"""Display the first image pair after session starts."""
if not state["session_active"]:
return None, None, ""
current_pair = state["image_pairs"][state["current_index"]]
if current_pair['roentgen_left']:
left_image = load_image("roentgen", current_pair['roentgen'])
right_image = load_image("pedisynth", current_pair['pedisynth'])
state["current_left_source"] = "roentgen"
state["current_right_source"] = "pedisynth"
else:
left_image = load_image("pedisynth", current_pair['pedisynth'])
right_image = load_image("roentgen", current_pair['roentgen'])
state["current_left_source"] = "pedisynth"
state["current_right_source"] = "roentgen"
progress = f"Image {state['current_index'] + 1} of {len(state['image_pairs'])} | Condition: {current_pair['condition']}"
return left_image, right_image, progress
def end_session():
"""End the session and return CSV file for download."""
if not state["evaluations"]:
return None, "No evaluations recorded."
filepath, filename = save_evaluations(state["evaluations"], state["doctor_name"])
state["session_active"] = False
state["current_index"] = 0
state["evaluations"] = []
return filepath, f"β
Evaluations ready to download: {filename}"
# Gradio interface
with gr.Blocks(title="X-Ray Quality Evaluation") as demo:
gr.Markdown("# π₯ X-Ray Quality Evaluation System")
gr.Markdown("**Pairwise Preference Test for Synthetic X-Ray Images**")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### Start Session")
doctor_name_input = gr.Textbox(
label="Enter your name:",
placeholder="Dr. Smith"
)
start_btn = gr.Button("Start Session", variant="primary", size="lg")
with gr.Column(scale=1):
gr.Markdown("### Results")
download_btn = gr.Button("End Session & Download Results", variant="primary", size="lg")
result_message = gr.Textbox(
label="Status",
interactive=False,
show_label=True
)
error_section = gr.Textbox(
label="Message",
interactive=False,
show_label=True,
value=""
)
# Image comparison section
with gr.Group(visible=False) as eval_section:
gr.Markdown("### Compare Images")
progress_text = gr.Textbox(
label="Progress",
interactive=False,
show_label=True
)
with gr.Row():
image_a = gr.Image(
label="Option A",
show_label=True,
type="pil"
)
image_b = gr.Image(
label="Option B",
show_label=True,
type="pil"
)
with gr.Row():
pref_a = gr.Button("π Prefer Option A", size="lg")
pref_b = gr.Button("π Prefer Option B", size="lg")
# File download
download_file = gr.File(
label="CSV Results",
interactive=False
)
# Event handlers
start_btn.click(
start_session,
inputs=doctor_name_input,
outputs=[eval_section, error_section]
).then(
display_first_pair,
outputs=[image_a, image_b, progress_text]
)
pref_a.click(
get_preference_a,
outputs=[image_a, image_b, progress_text]
)
pref_b.click(
get_preference_b,
outputs=[image_a, image_b, progress_text]
)
download_btn.click(
end_session,
outputs=[download_file, result_message]
)
if __name__ == "__main__":
demo.launch() |