Spaces:
Build error
Build error
File size: 24,721 Bytes
d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 d521b9d d13cb20 | 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 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 | import os, io, csv, json, random
from datetime import datetime
import gradio as gr
from huggingface_hub import HfApi, hf_hub_download
# -------------------- Config --------------------
REPO_ID = os.getenv("RESULTS_REPO", "sgtlim/videoeval_results") # ์
๋ก๋ํ ๋ฆฌํฌ์ ์ผ์น
HF_TOKEN = os.getenv("HF_TOKEN")
RESULTS_FILE = "results.csv"
TOTAL_PER_PARTICIPANT = 30 # ๋ชฉํ ํ๊ฐ ๊ฐ์(์ธ์
๊ธฐ์ค)
# videos.json ์์: {"url": "...mp4", "id": "BodyWeightSquats__XXXX.mp4", "action": "BodyWeightSquats"}
with open("videos.json", "r", encoding="utf-8") as f:
V = json.load(f)
api = HfApi()
# ๊ต์๋ ์ง์นจ(๊ทธ๋๋ก, ๊ตต๊ฒ ์ฒ๋ฆฌ ํฌํจ)
INSTRUCTION_MD = """
**Task:** You will watch a series of **AI-generated videos**. For each video, your job is to rate how well the personโs action in the AI-generated video matches the action specified as "**expected action**". Some things to keep in mind:
- The generated video should **capture** the expected action **throughout the video**.
- Try to **focus only** on the expected action and do **not** judge **video quality**, **attractiveness**, **background**, **camera motion**, or **objects**.
- You will be **paid** once **all the videos are viewed and rated**.
"""
# -------------------- Helper funcs --------------------
def _load_eval_counts():
"""
Hugging Face dataset์ results.csv๋ฅผ ์ฝ์ด video_id๋ณ ํ๊ฐ ๊ฐ์(dict)๋ฅผ ๋ฐํ.
์์ผ๋ฉด 0์ผ๋ก ์ด๊ธฐํ.
"""
# ๋ชจ๋ id๋ฅผ 0์ผ๋ก ์ด๊ธฐํ
counts = {}
for v in V:
vid = _get_video_id(v)
counts[vid] = 0
b = _read_csv_bytes()
if not b:
return counts
s = io.StringIO(b.decode("utf-8", errors="ignore"))
r = csv.reader(s)
rows = list(r)
if not rows:
return counts
# ํค๋ ํ์
header = rows[0]
body = rows[1:] if header and ("video_id" in header or "overall" in header) else rows
vid_col = None
if header and "video_id" in header:
vid_col = header.index("video_id")
for row in body:
try:
vid = row[vid_col] if vid_col is not None else row[2] # ๊ธฐ๋ณธ ํฌ๋งท: ts, pid, video_id, overall, notes
if vid in counts:
counts[vid] += 1
except Exception:
continue
return counts
def _get_video_id(v: dict) -> str:
if "id" in v and v["id"]:
return v["id"]
# id๊ฐ ์์ผ๋ฉด URL ํ์ผ๋ช
์ผ๋ก ๋์ฒด
return os.path.basename(v.get("url", ""))
def _read_csv_bytes():
try:
p = hf_hub_download(
repo_id=REPO_ID, filename=RESULTS_FILE, repo_type="dataset",
token=HF_TOKEN, local_dir="/tmp", local_dir_use_symlinks=False
)
return open(p, "rb").read()
except Exception:
return None
def _append(old_bytes, row):
s = io.StringIO()
w = csv.writer(s)
if not old_bytes:
# โ
์ ํค๋
w.writerow(["ts_iso", "participant_id", "video_id", "overall", "notes"])
else:
s.write(old_bytes.decode("utf-8", errors="ignore"))
w.writerow(row)
return s.getvalue().encode("utf-8")
# def push(participant_id, action_name, score, notes=""):
# if not participant_id or not participant_id.strip():
# return gr.update(visible=True, value="โ Please enter your Participant ID before proceeding.")
# if not action_name or score is None:
# return gr.update(visible=True, value="โ Fill out all fields.")
# old = _read_csv_bytes()
# row = [
# datetime.utcnow().isoformat(),
# participant_id.strip(),
# action_name,
# float(score),
# notes or ""
# ]
# newb = _append(old, row)
# api.upload_file(
# path_or_fileobj=io.BytesIO(newb),
# path_in_repo=RESULTS_FILE,
# repo_id=REPO_ID,
# repo_type="dataset",
# token=HF_TOKEN,
# commit_message="append"
# )
# return gr.update(visible=True, value=f"โ
Saved for {action_name}.")
def push(participant_id, video_id, score, notes=""):
if not participant_id or not participant_id.strip():
return gr.update(visible=True, value="โ Please enter your Participant ID before proceeding.")
if not video_id or score is None:
return gr.update(visible=True, value="โ Fill out all fields.")
try:
old = _read_csv_bytes()
row = [
datetime.utcnow().isoformat(),
participant_id.strip(),
video_id, # โ
action ๋์ video_id ์ ์ฅ
float(score), # overall
notes or ""
]
newb = _append(old, row)
if not REPO_ID:
return gr.update(visible=True, value="โ RESULTS_REPO is not set.")
if not HF_TOKEN:
return gr.update(visible=True, value="โ HF_TOKEN is missing. Set a write token for the dataset repo.")
api.upload_file(
path_or_fileobj=io.BytesIO(newb),
path_in_repo=RESULTS_FILE,
repo_id=REPO_ID,
repo_type="dataset",
token=HF_TOKEN,
commit_message="append"
)
return gr.update(visible=True, value=f"โ
Saved for {video_id}.")
except Exception as e:
return gr.update(
visible=True,
value=f"โ Save failed: {type(e).__name__}: {e}\n"
f"- Check HF_TOKEN permission\n- Check REPO_ID\n- Create dataset repo if missing"
)
def _extract_action(v):
if "action" in v and v["action"]:
return v["action"]
raw = v.get("id", "")
return raw.split("__")[0].split(".")[0]
def pick_one():
v = random.choice(V)
return v["url"], _extract_action(v)
def _progress_html(done, total):
pct = int(100 * done / max(1, total))
return f"""
<div style="border:1px solid #ddd; height:20px; border-radius:6px; overflow:hidden; margin-top:6px;">
<div style="height:100%; width:{pct}%; background:#3b82f6;"></div>
</div>
<div style="font-size:12px; margin-top:4px;">{done} / {total}</div>
"""
def _build_order_with_anchor(total:int, anchor_idx:int, repeats:int, pool_size:int, min_gap:int=1):
"""
total: TOTAL_PER_PARTICIPANT (e.g., 30)
anchor_idx: index of the anchor video in V (0 for first item)
repeats: how many times to show anchor (e.g., 5)
pool_size: len(V)
min_gap: ์ต์ ๊ฐ๊ฒฉ(์ธ์ ๊ธ์ง => 1)
return: list of indices (length=total)
"""
assert repeats <= total, "repeats must be <= total"
assert pool_size >= 1, "videos pool must be non-empty"
# 1) ๋ค๋ฅธ ๋น๋์ค 25๊ฐ(์ค๋ณต ์์ด) ๋ฝ๊ธฐ
others_needed = total - repeats
# anchor๋ฅผ ์ ์ธํ ํ๋ณด ์ธ๋ฑ์ค
candidates = list(range(1, pool_size)) if anchor_idx == 0 else [i for i in range(pool_size) if i != anchor_idx]
if len(candidates) < others_needed:
raise ValueError("Not enough unique non-anchor videos to fill the schedule without duplication.")
others = random.sample(candidates, k=others_needed)
# 2) ๊ธฐ๋ณธ ์ํ์ค(others)๋ฅผ ๋ฌด์์๋ก ์๊ธฐ
random.shuffle(others)
# 3) ์ต์ปค๋ฅผ min_gap๋ฅผ ๋ง์กฑํ๋๋ก ์ฝ์
ํ ์์น ์ ์
# 30๊ฐ๋ฅผ 5๊ตฌ๊ฐ์ผ๋ก ๋๋ , ๊ฐ ๊ตฌ๊ฐ ๋ด์์ ์ถฉ๋ ๋ ๋๊ฒ ๋ฐฐ์น
# (๊ฐ๋จํ๊ณ ์์ ์ ์ธ ๋ฐฉ์)
seq = others[:] # ๊ธธ์ด=25
anchor_positions = []
segment = total // repeats # 30//5 = 6
for k in range(repeats):
# ๊ฐ ๊ตฌ๊ฐ [k*segment, (k+1)*segment) ์์์ ํ๋ณด ์์น๋ฅผ ๊ณ ๋ฆ
lo = k * segment
hi = (k + 1) * segment if k < repeats - 1 else total # ๋ง์ง๋ง์ ๋๊น์ง
# ๊ฒฝ๊ณ ๋ด ์์ ์คํ์
์ ํ (์ฌ์ ๋ฅผ ๋๊ณ ์ถฉ๋์ ํผํจ)
candidate_pos = random.randrange(lo, hi)
# ์ธ์ ๊ธ์ง ๋ณด์ : ์ด๋ฏธ ๋ฐฐ์ ๋ anchor ์์น๋ค๊ณผ์ ๊ฑฐ๋ฆฌ๊ฐ min_gap ์ด์ ๋๋๋ก ์กฐ์
# ํ์ ์ ์ข์ฐ๋ก ๊ทผ์ ํ ๋น ์ฌ๋กฏ ํ์
def ok(pos):
return all(abs(pos - p) >= min_gap + 1 for p in anchor_positions) # ์ฐ์๊ธ์ง => ๊ฑฐ๋ฆฌ >= 2
# ๊ทผ๋ฐฉ ํ์ ํญ
found = None
for delta in range(0, segment): # ๊ตฌ๊ฐ ํฌ๊ธฐ ๋ด์์ ํ์
# ์ข/์ฐ ๋ฒ๊ฐ์๊ฐ๋ฉฐ ํ๋ณด ์๋
for sign in (+1, -1):
pos = candidate_pos + sign * delta
if 0 <= pos < total and ok(pos):
found = pos
break
if found is not None:
break
if found is None:
# ์ตํ: 0..total-1 ๋ฒ์์์ ์๋ฌด ๋ฐ๋ ์ถฉ๋ ์๋ ๊ณณ ์ฐพ๊ธฐ
for pos in range(total):
if ok(pos):
found = pos
break
if found is None:
raise RuntimeError("Failed to place anchor without adjacency. Try different strategy or loosen min_gap.")
anchor_positions.append(found)
# 4) others๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ๊ธธ์ด total์ ๋น ์ํ์ค๋ฅผ ๋ง๋ค๊ณ anchor๋ฅผ ์ฃผ์
# ์ฐ์ ๋น ๋ฆฌ์คํธ๋ฅผ ๋ง๋ค๊ณ anchor ์์น๋ฅผ ์ฑ์ด ํ, ๋๋จธ์ง๋ฅผ others๋ก ์ฑ์
result = [None] * total
for pos in anchor_positions:
result[pos] = anchor_idx
# others ํฌ์ธํฐ
j = 0
for i in range(total):
if result[i] is None:
result[i] = others[j]
j += 1
# ์์ ์ฒดํฌ
assert len(result) == total
# ์ธ์ anchor ์๋์ง ํ์ธ
for i in range(1, total):
assert not (result[i] == anchor_idx and result[i-1] == anchor_idx), "Adjacent anchors found."
# anchor ๊ฐ์ ํ์ธ
assert sum(1 for x in result if x == anchor_idx) == repeats, "Anchor count mismatch."
return result
# -------------------- Example videos (download to local cache) --------------------
EXAMPLES = {
"BodyWeightSquats": {
"real": "examples/BodyWeightSquats_real.mp4",
"bad": "examples/BodyWeightSquats_bad.mp4",
},
"WallPushUps": {
"real": "examples/WallPushUps_real.mp4",
"bad": "examples/WallPushUps_bad.mp4",
},
}
EX_CACHE = {}
for cls, files in EXAMPLES.items():
EX_CACHE[cls] = {"real": None, "bad": None}
for kind, fname in files.items():
try:
EX_CACHE[cls][kind] = hf_hub_download(
repo_id=REPO_ID,
filename=fname,
repo_type="dataset",
token=HF_TOKEN,
local_dir="/tmp",
local_dir_use_symlinks=False,
)
except Exception as e:
print(f"[WARN] example missing: {cls} {kind} -> {fname}: {e}")
GLOBAL_CSS = """
/* ===== ๊ณตํต ๋ณ์ ํฌ๋ช
ํ (v3/v4 ๋๋ค) ===== */
:root, .gradio-container {
--body-background-fill: transparent !important;
--background-fill-primary: transparent !important;
--background-fill-secondary: transparent !important;
--block-background-fill: transparent !important;
--block-border-color: transparent !important;
--panel-background-fill: transparent !important;
--panel-border-color: transparent !important;
--section-header-background-fill: transparent !important;
--shadow-drop: 0 0 0 rgba(0,0,0,0) !important;
--shadow-spread: 0 0 0 rgba(0,0,0,0) !important;
}
/* ===== v4(Tailwind ๊ธฐ๋ฐ)์์ ์์ฃผ ์ฐ์ด๋ ๋ฐฐ๊ฒฝ/ํ
๋๋ฆฌ/๊ทธ๋ฆผ์ ์ ๊ฑฐ ===== */
.gradio-container .bg-white,
.gradio-container .bg-gray-50,
.gradio-container .bg-gray-100,
.gradio-container .bg-slate-50,
.gradio-container .bg-neutral-50,
.gradio-container .bg-secondary,
.gradio-container .border,
.gradio-container .shadow,
.gradio-container .shadow-sm,
.gradio-container .shadow-md,
.gradio-container .ring-1,
.gradio-container .ring,
.gradio-container .gr-card,
.gradio-container .prose > *:where(hr) {
background: transparent !important;
box-shadow: none !important;
border-color: transparent !important;
}
/* ===== v3 ์ปดํฌ๋ํธ ๊ณ์ด ===== */
.gradio-container .gr-panel,
.gradio-container .gr-group,
.gradio-container .gr-box,
.gradio-container .gr-row,
.gradio-container .gr-column,
.gradio-container .gr-accordion,
.gradio-container .gr-block,
.gradio-container .gr-form,
.gradio-container .gr-tabs,
.gradio-container .gr-tabitem,
.gradio-container .gr-section-header {
background: transparent !important;
box-shadow: none !important;
border: none !important;
}
/* ๊ตฌ๋ถ์ /ํค๋ ๋ฐ ์ ๊ฑฐ */
.gradio-container hr,
.gradio-container .gr-divider,
.gradio-container .gr-accordion .label {
background: transparent !important;
border: none !important;
box-shadow: none !important;
}
/* ๋ฐ๊นฅ์ชฝ ํ์ด์ง ๋ฐฐ๊ฒฝ๋ ๊ฐ์ ๋ก ํฌ๋ช
/ํฐ์์ผ๋ก */
html, body, .gradio-container { background: transparent !important; }
/* ๊ธฐ์กด CSS ์๋์ ์ถ๊ฐ */
#eval [class*="bg-"],
#eval [class*="border"],
#eval [class*="shadow"],
#eval .gr-panel, #eval .gr-group, #eval .gr-box, #eval .gr-row, #eval .gr-column,
#eval .gr-block, #eval .gr-form, #eval .gr-section-header, #eval .gr-accordion {
background: transparent !important;
border-color: transparent !important;
box-shadow: none !important;
}
#eval .gr-form, #eval .gr-panel { background: transparent !important; box-shadow:none !important; border:none !important; }
"""
# -------------------- UI --------------------
with gr.Blocks(fill_height=True, css=GLOBAL_CSS) as demo:
order_state = gr.State(value=[]) # v4์์๋ value= ๊ถ์ฅ
ptr_state = gr.State(value=0)
cur_video_id = gr.State(value="")
# ------------------ PAGE 1: Intro + Examples ------------------
page_intro = gr.Group(visible=True)
with page_intro:
gr.Markdown("## ๐ฏ Action Consistency Human Evaluation")
gr.Markdown(INSTRUCTION_MD)
# Examples: Squats
with gr.Group():
gr.Markdown("### Examples: BodyWeightSquats")
with gr.Row():
with gr.Column():
gr.Markdown("**Expected depiction of action**")
gr.Video(value=EX_CACHE["BodyWeightSquats"]["real"], height=240, autoplay=False)
with gr.Column():
gr.Markdown("**Poorly generated action**")
gr.Video(value=EX_CACHE["BodyWeightSquats"]["bad"], height=240, autoplay=False)
if not (EX_CACHE["BodyWeightSquats"]["real"] and EX_CACHE["BodyWeightSquats"]["bad"]):
gr.Markdown("> โ ๏ธ Upload `examples/BodyWeightSquats_real.mp4` and `_bad.mp4` to show both samples.")
# Examples: WallPushUps
with gr.Group():
gr.Markdown("### Examples: WallPushUps")
with gr.Row():
with gr.Column():
gr.Markdown("**Expected depiction of action**")
gr.Video(value=EX_CACHE["WallPushUps"]["real"], height=240, autoplay=False)
with gr.Column():
gr.Markdown("**Poorly generated action**")
gr.Video(value=EX_CACHE["WallPushUps"]["bad"], height=240, autoplay=False)
if not (EX_CACHE["WallPushUps"]["real"] and EX_CACHE["WallPushUps"]["bad"]):
gr.Markdown("> โ ๏ธ Upload `examples/WallPushUps_real.mp4` and `_bad.mp4` to show both samples.")
understood = gr.Checkbox(label="I have read and understand the task.", value=False)
start_btn = gr.Button("Yes, start", variant="secondary", interactive=False)
def _toggle_start(checked: bool):
return gr.update(interactive=checked, variant=("primary" if checked else "secondary"))
understood.change(_toggle_start, inputs=understood, outputs=start_btn)
# ------------------ PAGE 2: Evaluation ------------------
page_eval = gr.Group(visible=False, elem_id="eval")
with page_eval:
# PID ์
๋ ฅ
with gr.Row():
pid = gr.Textbox(label="Participant ID (required)", placeholder="e.g., Youngsun-2025/10/01")
# ์ง์นจ(์๋ฌธ) + ๋น๋์ค + ์งํ๋ฐ / ์ค๋ฅธ์ชฝ์ ์ฌ๋ผ์ด๋ + Save&Next
with gr.Row(equal_height=True):
with gr.Column(scale=1):
gr.Markdown(INSTRUCTION_MD) # ๊ต์๋ ๋ฌธ๊ตฌ ๊ทธ๋๋ก
video = gr.Video(label="Video", height=360)
progress = gr.HTML(_progress_html(0, TOTAL_PER_PARTICIPANT))
with gr.Column(scale=1):
action_tb = gr.Textbox(label="Expected action", interactive=False)
score = gr.Slider(minimum=0.0, maximum=10.0, step=0.1, value=5.0,
label="Action Consistency (0.0 (Worst) - 10.0 (Best))")
save_next = gr.Button("๐พ Save & Next โถ", variant="secondary", interactive=False)
status = gr.Markdown(visible=False)
done_state = gr.State(0)
# PID ์
๋ ฅ์ ๋ฐ๋ผ Save&Next ํ ๊ธ
def _toggle_by_pid(pid_text: str):
enabled = bool(pid_text and pid_text.strip())
return gr.update(interactive=enabled, variant=("primary" if enabled else "secondary"))
pid.change(_toggle_by_pid, inputs=pid, outputs=save_next)
# -------- ํ์ด์ง ์ ํ & ์ฒซ ๋ก๋ --------
ANCHOR_IDX = 0 # videos.json์ ๋งจ ์ฒซ ๋น๋์ค
ANCHOR_REPEATS = 5 # ์ต์ปค 5ํ
MIN_GAP = 1 # ์ต์ปค ์ฐ์ ๊ธ์ง(์ธ์ ๊ธ์ง)
def _build_order_least_first_with_anchor(total:int, anchor_idx:int, repeats:int, min_gap:int=1):
"""
- results.csv๋ฅผ ์ฝ์ด video_id๋ณ ์นด์ดํธ๋ฅผ ๊ณ์ฐ
- ์ต์ปค(์ฒซ ๋น๋์ค) 5ํ ํฌํจ, ์ฐ์ ๊ธ์ง
- ๋๋จธ์ง๋ '๊ฐ์ฅ ์ ๊ฒ ํ๊ฐ๋ ์'์ผ๋ก ์ค๋ณต ์์ด ์ฑ์
"""
assert repeats <= total
N = len(V)
assert N >= 1
# 0) id ๋งคํ
def vid_of(i): return _get_video_id(V[i])
# 1) ํ์ฌ ๋์ ์นด์ดํธ ๋ก๋
counts = _load_eval_counts()
# 2) ์ต์ปค ์ ์ธ ํ๋ณด(์ค๋ณต ์์ด) ์ ๋ ฌ: ์นด์ดํธ ์ค๋ฆ์ฐจ์, ๋๋ฅ ์ ๋๋ค ์
ํ
anchor_vid = vid_of(anchor_idx)
candidates = [i for i in range(N) if i != anchor_idx]
# ๋๋ฅ ๋๋คํ๋ฅผ ์ํด ์ผ๋จ ์
ํ
random.shuffle(candidates)
candidates.sort(key=lambda i: counts.get(vid_of(i), 0))
others_needed = total - repeats
if len(candidates) < others_needed:
raise ValueError("Not enough unique non-anchor videos to fill the schedule without duplication.")
others = candidates[:others_needed] # ์ค๋ณต ์์ด ์ ํ
# 3) others๋ฅผ ๋ฒ ์ด์ค ์ํ์ค๋ก(๋๋ค ์ด์ง ์๊ธฐ)
random.shuffle(others)
# 4) ์ต์ปค๋ฅผ ๊ตฌ๊ฐ ๋ฐฐ์น(์ฐ์ ๊ธ์ง)
seq = [None] * total
segment = total // repeats if repeats > 0 else total
anchor_positions = []
for k in range(repeats):
lo = k * segment
hi = (k + 1) * segment if k < repeats - 1 else total
cand = random.randrange(lo, hi)
def ok(pos):
return all(abs(pos - p) >= (min_gap + 1) for p in anchor_positions)
found = None
for d in range(0, max(1, segment)):
for sgn in (+1, -1):
pos = cand + sgn * d
if 0 <= pos < total and ok(pos):
found = pos
break
if found is not None:
break
if found is None:
# ๋ง์ง๋ง ์๋จ: ์ ์ฒด ํ์
for pos in range(total):
if ok(pos):
found = pos
break
if found is None:
raise RuntimeError("Failed to place anchor without adjacency.")
anchor_positions.append(found)
for pos in anchor_positions:
seq[pos] = anchor_idx
# 5) ๋น ์๋ฆฌ๋ฅผ others๋ก ์ฑ์ฐ๊ธฐ
j = 0
for i in range(total):
if seq[i] is None:
seq[i] = others[j]
j += 1
# 6) ์์ ์ฒดํฌ
assert sum(1 for x in seq if x == anchor_idx) == repeats
for i in range(1, total):
assert not (seq[i] == anchor_idx and seq[i-1] == anchor_idx), "Adjacent anchors found."
return seq
# def _start_and_load_first():
# total = TOTAL_PER_PARTICIPANT
# order = _build_order_with_anchor(
# total=total,
# anchor_idx=ANCHOR_IDX,
# repeats=ANCHOR_REPEATS,
# pool_size=len(V),
# min_gap=1 # ์ธ์ ๊ธ์ง
# )
# first_idx = order[0]
# v0 = V[first_idx]
# url0 = v0["url"]
# action0 = _extract_action(v0)
# vid0 = _get_video_id(v0) # โ
์ฌ๊ธฐ์ ์๋ณธ id
# return (
# gr.update(visible=False), # page_intro off
# gr.update(visible=True), # page_eval on
# url0, # video
# action0, # action_tb (ํ์์ฉ)
# 5.0, # score ์ด๊ธฐ๊ฐ
# gr.update(visible=False, value=""),
# 0, # done_state
# _progress_html(0, TOTAL_PER_PARTICIPANT),
# order, # order_state
# 1, # ptr_state
# vid0 # โ
cur_video_id
# )
def _start_and_load_first():
total = TOTAL_PER_PARTICIPANT
order = _build_order_least_first_with_anchor(
total=total,
anchor_idx=ANCHOR_IDX,
repeats=ANCHOR_REPEATS,
min_gap=MIN_GAP
)
first_idx = order[0]
v0 = V[first_idx]
return (
gr.update(visible=False),
gr.update(visible=True),
v0["url"],
_extract_action(v0),
5.0,
gr.update(visible=False, value=""),
0,
_progress_html(0, TOTAL_PER_PARTICIPANT),
order,
1,
_get_video_id(v0) # cur_video_id
)
start_btn.click(
_start_and_load_first,
inputs=[],
outputs=[page_intro, page_eval, video, action_tb, score, status, done_state, progress, order_state, ptr_state, cur_video_id] # โ
)
# -------- Save & Next (๋
ธํธ ์์) --------
def save_and_next(participant_id, action_name, score_val, done_cnt, order, ptr):
if not participant_id or not participant_id.strip():
# PID ์์ผ๋ฉด ๊ธฐ์กด ํ๋ฉด ์ ์ง
return (
gr.update(visible=True, value="โ Please enter your Participant ID."),
gr.update(), gr.update(), # video, action_tb ๋ณ๊ฒฝ ์์
done_cnt,
_progress_html(done_cnt, TOTAL_PER_PARTICIPANT),
5.0,
ptr,
video_id
)
status_msg = push(participant_id, action_name, score_val, "")
new_done = int(done_cnt) + 1
# ์ข
๋ฃ ์กฐ๊ฑด: ๋ชฉํ ๊ฐ์ ๋ฌ์ฑ or ์์ ์์ง
if new_done >= TOTAL_PER_PARTICIPANT or ptr >= len(order):
return (
status_msg, # status
None, # video ๋น์ฐ๊ธฐ
"", # action_tb ๋น์ฐ๊ธฐ
TOTAL_PER_PARTICIPANT, # done_state ์ต์ข
_progress_html(TOTAL_PER_PARTICIPANT, TOTAL_PER_PARTICIPANT),
5.0, # score ๋ฆฌ์
ptr,
video_id
)
# ๋ค์ ์์ ๋ก๋
next_idx = order[ptr]
v = V[next_idx]
return (
status_msg,
v["url"],
_extract_action(v),
new_done,
_progress_html(new_done, TOTAL_PER_PARTICIPANT),
5.0,
ptr + 1,
_get_video_id(v) # โ
๋ค์ cur_video_id
)
# save_next.click(
# save_and_next,
# inputs=[pid, action_tb, score, done_state, order_state, ptr_state],
# outputs=[status, video, action_tb, done_state, progress, score, ptr_state]
# )
save_next.click(
save_and_next,
# โ
cur_video_id๋ฅผ ๋ ๋ฒ์งธ ์ธ์๋ก ๋๊น
inputs=[pid, cur_video_id, score, done_state, order_state, ptr_state],
# โ
๋ง์ง๋ง์ cur_video_id๋ฅผ outputs๋ก ๋ฐ์(์ํ ๊ฐฑ์ )
outputs=[status, video, action_tb, done_state, progress, score, ptr_state, cur_video_id]
)
if __name__ == "__main__":
demo.launch()
|