Spaces:
Running
Running
File size: 9,657 Bytes
248aa67 ca921cc 248aa67 9a0f9a2 248aa67 9a0f9a2 248aa67 9a0f9a2 248aa67 9a0f9a2 248aa67 9a0f9a2 248aa67 9a0f9a2 248aa67 9a0f9a2 248aa67 9a0f9a2 248aa67 |
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 |
import json
import os
import random
import re
import sys
from datetime import datetime
from pathlib import Path
from typing import List, Optional
from uuid import uuid4
import gradio as gr
import numpy as np
import requests
from datasets import load_dataset
from huggingface_hub import (
CommitScheduler,
HfApi,
InferenceClient,
login,
snapshot_download,
)
from PIL import Image
from glob import glob
session_token = os.environ.get("SessionToken")
login(token=session_token, add_to_git_credential=True)
DEFAILT_USERNAME_MESSAGE = "You must be logged in befor starting to label images."
REPO_URL = "glitchbench/GlitchBenchReviewData"
DATASET_URL = "glitchbench/GlitchBench"
SUBMIT_MESSAGE = "✅ Submit the description"
IDUNNU_MESSAGE = "🤷 I don't know what to do with this image"
SKIP_MESSAGE = "⏭️ Skip, for now"
glitchbench_dataset = load_dataset(DATASET_URL)["validation"]
dataset_size = len(glitchbench_dataset)
# map id to index:
id_to_index = {x["id"]: i for i, x in enumerate(glitchbench_dataset)}
JSON_DATASET_DIR = Path("local_dataset")
JSON_DATASET_DATA_DIR = JSON_DATASET_DIR / "data"
JSON_DATASET_PATH = JSON_DATASET_DATA_DIR / f"labels-{uuid4()}.json"
INSTRUCTIONS = """
<div>
<section>
<h2>Introduction</h2>
<p>Welcome to the GlitchBench Dataset Labeling Tool! Your contribution is vital in helping us clean and label the dataset accurately. This tool is designed to be intuitive and user-friendly, allowing you to view images from the dataset and provide descriptions.</p>
</section>
<section>
<h2>How to Label Images</h2>
<ol>
<li><strong>Login:</strong> Use the login button at the top to login with your Hugging Face Account.</li>
<li><strong>Start Labeling:</strong> Click the 'Start Labeling' button to begin.</li>
<li><strong>View Image:</strong> An image from the GlitchBench dataset will be displayed.</li>
<li><strong>Describe the Image:</strong> Write a brief description about what is wrong or unusual about the image, focusing on the strange/unusual aspect. The description should be brief and concise.</li>
<li><strong>Submit:</strong> Click 'Submit' to save your description. You can also use 'I Don't Know' if you can't spot the bug or unusual part of the image, or 'Skip' if you don't want to provide a description for the given image.</li>
<li><strong>Continue:</strong> Move on to the next image and repeat the process.</li>
</ol>
</section>
<section>
<h2>Examples</h2>
<table style="width:100%">
<tr>
<th>Image</th>
<th>Sample Description</th>
<th>Image</th>
<th>Sample Description</th>
</tr>
<tr>
<td><img src="https://glitchbench.github.io/static/instructions/flying-horse.jpeg" alt="flying horse" style="width:100%; max-width:300px;"></td>
<td>"A horse floating in the air", or "A person riding a horse flying in the air"</td>
<td><img src="https://glitchbench.github.io/static/instructions/t-pose.jpeg" alt="t-pose" style="width:100%; max-width:300px;"></td>
<td>"A character performing a T-pose"</td>
</tr>
<tr>
<td><img src="https://glitchbench.github.io/static/instructions/a-dog-clipping-with-door.webp" alt="dog in the door" style="width:100%; max-width:300px;"></td>
<td>"A dog is clipping through the door"</td>
<td><img src="https://glitchbench.github.io/static/instructions/low-poly-face.avif" alt="low-poly face" style="width:100%; max-width:300px;"></td>
<td>"A person with a low-poly face"</td>
</tr>
<tr>
<td><img src="https://glitchbench.github.io/static/instructions/unnatural-hand-position.jpeg" alt="unnatural hands" style="width:100%; max-width:300px;"></td>
<td>"A person with unnatural hand positions."</td>
<td><img src="https://glitchbench.github.io/static/instructions/stretched_neck.jpeg" alt="unnatural neck" style="width:100%; max-width:300px;"></td>
<td>"A person with a stretched neck."</td>
</tr>
</table>
</section>
</div>
"""
if not JSON_DATASET_DIR.exists():
JSON_DATASET_DIR.mkdir()
if not JSON_DATASET_DATA_DIR.exists():
JSON_DATASET_DATA_DIR.mkdir()
print("Downloading the dataset")
print(REPO_URL)
snapshot_download(
repo_id=REPO_URL,
allow_patterns="*.json",
local_dir=JSON_DATASET_DIR,
use_auth_token=session_token,
repo_type="dataset",
)
scheduler = CommitScheduler(
repo_id=REPO_URL,
repo_type="dataset",
folder_path=JSON_DATASET_DIR,
path_in_repo="./",
every=1,
private=True,
)
def save_json(image_id: str, provided_description: str, username: str) -> None:
with scheduler.lock:
with JSON_DATASET_PATH.open("a") as f:
json.dump(
{
"username": username,
"image_id": image_id,
"user_description": provided_description,
"datetime": datetime.now().isoformat(),
},
f,
)
f.write("\n")
def set_username(profile: Optional[gr.OAuthProfile]) -> str:
if profile is None:
return DEFAILT_USERNAME_MESSAGE
return profile["preferred_username"]
def start_labeling(username_label):
if username_label == DEFAILT_USERNAME_MESSAGE:
raise gr.Error("Please login first, then click start labeling")
all_json_files = glob(str(JSON_DATASET_DATA_DIR / "*.json"))
# read json files and keep records related to the current user
all_user_records = []
for json_file in all_json_files:
with open(json_file) as f:
for line in f:
record = json.loads(line)
if record["username"] == username_label:
all_user_records.append(record["image_id"])
print(f"Found {len(all_user_records)} records for user {username_label}")
# go throught all images in the dataset and exlcude those that are already labeled by the user
remaining_indicies = set(range(dataset_size))
solved_indices = [id_to_index[x] for x in all_user_records]
remaining_indicies = remaining_indicies - set(solved_indices)
print(f"Found {len(remaining_indicies)} remaining images for user {username_label}")
return list(remaining_indicies), gr.Button(interactive=False)
def show_random_sample(username_label, remaining_batch):
rindex = random.choice(remaining_batch)
remaining_batch.remove(rindex)
# get the image
image = glitchbench_dataset[rindex]["image"]
image_id = glitchbench_dataset[rindex]["id"]
return image, image_id, "", remaining_batch
def write_user_description(username_label, image_id, user_description, skip_or_submit):
if skip_or_submit == SKIP_MESSAGE:
provided_description = "N/A"
else:
provided_description = user_description
save_json(image_id, provided_description, username_label)
with gr.Blocks() as demo:
gr.Markdown("## GlitchBench Dataset Labeling Tool")
gr.Markdown("Help us to improve our GlitchBench dataset.")
with gr.Accordion("Instructions"):
gr.HTML(INSTRUCTIONS)
with gr.Row():
username_label = gr.Text(label="Username", interactive=False)
gr.LoginButton()
gr.LogoutButton()
start_button = gr.Button("Start Labeling")
username_label.attach_load_event(set_username, None)
with gr.Row():
with gr.Column(scale=5, min_width=500):
glitch_image = gr.Image(label="Image")
glitch_image_id = gr.Textbox(label="Image ID", visible=False)
with gr.Column(scale=3, min_width=200):
user_description = gr.Textbox(lines=5, label="Description")
submit_btn = gr.Button(SUBMIT_MESSAGE)
idunnu_btn = gr.Button(IDUNNU_MESSAGE)
skip_btn = gr.Button(SKIP_MESSAGE)
remaining_batch = gr.State()
start_button.click(
start_labeling, inputs=[username_label], outputs=[remaining_batch, start_button]
).then(
show_random_sample,
inputs=[username_label, remaining_batch],
outputs=[glitch_image, glitch_image_id, user_description],
)
submit_btn.click(
write_user_description,
inputs=[username_label, glitch_image_id, user_description, submit_btn],
outputs=[],
).then(
show_random_sample,
inputs=[username_label, remaining_batch],
outputs=[glitch_image, glitch_image_id, user_description],
)
idunnu_btn.click(
write_user_description,
inputs=[username_label, glitch_image_id, user_description, idunnu_btn],
outputs=[],
).then(
show_random_sample,
inputs=[username_label, remaining_batch],
outputs=[glitch_image, glitch_image_id, user_description],
)
demo.launch()
|