Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -169,189 +169,3 @@ else:
|
|
| 169 |
|
| 170 |
st.divider()
|
| 171 |
st.caption("Labels are saved & committed as `labels.csv` to this Space (see the Files tab).")
|
| 172 |
-
|
| 173 |
-
'''
|
| 174 |
-
import os
|
| 175 |
-
import glob
|
| 176 |
-
from pathlib import Path
|
| 177 |
-
from datetime import datetime, timezone
|
| 178 |
-
|
| 179 |
-
import streamlit as st
|
| 180 |
-
import pandas as pd
|
| 181 |
-
from PIL import Image
|
| 182 |
-
from filelock import FileLock
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
from pathlib import Path
|
| 186 |
-
BASE_DIR = Path(__file__).parent.resolve() # <- absolute path to the repo folder
|
| 187 |
-
|
| 188 |
-
# ---------------- Config ----------------
|
| 189 |
-
IMAGE_DIR = os.getenv("IMAGE_DIR", str(BASE_DIR / "images"))
|
| 190 |
-
LABELS_CSV = os.getenv("LABELS_CSV", str(BASE_DIR / "labels.csv"))
|
| 191 |
-
#LABELS_CSV = os.getenv("LABELS_CSV", str(Path(__file__).parent / "labels.csv"))
|
| 192 |
-
LABEL_LEFT = os.getenv("LABEL_A", "Class A")
|
| 193 |
-
LABEL_RIGHT = os.getenv("LABEL_B", "Class B")
|
| 194 |
-
SHOW_ALREADY_LABELED = os.getenv("SHOW_ALREADY_LABELED", "0") == "1"
|
| 195 |
-
SUPPORTED_EXTS = (".png", ".jpg", ".jpeg", ".bmp", ".gif", ".tif", ".tiff", ".webp")
|
| 196 |
-
|
| 197 |
-
# ---------------- Config ----------------
|
| 198 |
-
#IMAGE_DIR = os.getenv("IMAGE_DIR", "images")
|
| 199 |
-
#LABELS_CSV = os.getenv("LABELS_CSV", "labels.csv")
|
| 200 |
-
#LABEL_LEFT = os.getenv("LABEL_A", "Class A")
|
| 201 |
-
#LABEL_RIGHT = os.getenv("LABEL_B", "Class B")
|
| 202 |
-
#SHOW_ALREADY_LABELED = os.getenv("SHOW_ALREADY_LABELED", "0") == "1"
|
| 203 |
-
#SUPPORTED_EXTS = (".png", ".jpg", ".jpeg", ".bmp", ".gif", ".tif", ".tiff", ".webp")
|
| 204 |
-
|
| 205 |
-
st.set_page_config(page_title="Two-Button Image Labeler", layout="centered")
|
| 206 |
-
|
| 207 |
-
# Optional: create empty CSV so it’s visible even before the first click
|
| 208 |
-
labels_path = Path(LABELS_CSV)
|
| 209 |
-
if not labels_path.exists():
|
| 210 |
-
labels_path.write_text("image,label,annotator,timestamp\n", encoding="utf-8")
|
| 211 |
-
|
| 212 |
-
# --------------- Helpers ----------------
|
| 213 |
-
def list_images():
|
| 214 |
-
paths = []
|
| 215 |
-
for p in glob.glob(os.path.join(IMAGE_DIR, "**", "*"), recursive=True):
|
| 216 |
-
if p.lower().endswith(SUPPORTED_EXTS):
|
| 217 |
-
paths.append(p)
|
| 218 |
-
return sorted(paths)
|
| 219 |
-
|
| 220 |
-
def read_labels():
|
| 221 |
-
if os.path.exists(LABELS_CSV):
|
| 222 |
-
try:
|
| 223 |
-
return pd.read_csv(LABELS_CSV)
|
| 224 |
-
except Exception:
|
| 225 |
-
return pd.DataFrame(columns=["image", "label", "annotator", "timestamp"])
|
| 226 |
-
return pd.DataFrame(columns=["image", "label", "annotator", "timestamp"])
|
| 227 |
-
|
| 228 |
-
def rel_to_image_dir(p: str):
|
| 229 |
-
try:
|
| 230 |
-
return str(Path(p).resolve().relative_to(Path(IMAGE_DIR).resolve()))
|
| 231 |
-
except Exception:
|
| 232 |
-
return Path(p).name # fall back to filename
|
| 233 |
-
|
| 234 |
-
#def rel_to_image_dir(p: str):
|
| 235 |
-
# try:
|
| 236 |
-
# return str(Path(p).resolve().relative_to(Path(IMAGE_DIR).resolve()))
|
| 237 |
-
# except Exception:
|
| 238 |
-
# return p
|
| 239 |
-
|
| 240 |
-
def write_label(image_path: str, label: str, annotator: str):
|
| 241 |
-
os.makedirs(os.path.dirname(LABELS_CSV) or ".", exist_ok=True)
|
| 242 |
-
record = {
|
| 243 |
-
"image": rel_to_image_dir(image_path),
|
| 244 |
-
"label": label,
|
| 245 |
-
"annotator": annotator,
|
| 246 |
-
"timestamp": datetime.now(timezone.utc).isoformat()
|
| 247 |
-
}
|
| 248 |
-
with FileLock(LABELS_CSV + ".lock", timeout=10):
|
| 249 |
-
exists = os.path.exists(LABELS_CSV)
|
| 250 |
-
df = pd.DataFrame([record])
|
| 251 |
-
df.to_csv(LABELS_CSV, mode="a", header=not exists, index=False)
|
| 252 |
-
|
| 253 |
-
# --- NEW: copy labels.csv into repo folder so it's visible in Files tab ---
|
| 254 |
-
try:
|
| 255 |
-
import shutil
|
| 256 |
-
dst = Path(__file__).parent / "labels.csv"
|
| 257 |
-
shutil.copy(LABELS_CSV, dst)
|
| 258 |
-
except Exception as e:
|
| 259 |
-
print(f"Warning: could not copy labels.csv into app/: {e}")
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
#def write_label(image_path: str, label: str, annotator: str):
|
| 263 |
-
# os.makedirs(os.path.dirname(LABELS_CSV) or ".", exist_ok=True)
|
| 264 |
-
# record = {
|
| 265 |
-
# "image": rel_to_image_dir(image_path),
|
| 266 |
-
# "label": label,
|
| 267 |
-
# "annotator": annotator,
|
| 268 |
-
# "timestamp": datetime.now(timezone.utc).isoformat()
|
| 269 |
-
# }
|
| 270 |
-
# with FileLock(LABELS_CSV + ".lock", timeout=10):
|
| 271 |
-
# exists = os.path.exists(LABELS_CSV)
|
| 272 |
-
# df = pd.DataFrame([record])
|
| 273 |
-
# df.to_csv(LABELS_CSV, mode="a", header=not exists, index=False)
|
| 274 |
-
|
| 275 |
-
# --------------- UI ---------------------
|
| 276 |
-
st.title("🏷️ Two-Button Image Labeler")
|
| 277 |
-
st.write("Enter your name, click **Start**, then label each image using the big buttons. Use **Skip** to bypass an image.")
|
| 278 |
-
|
| 279 |
-
with st.sidebar:
|
| 280 |
-
annotator = st.text_input("Your name*", value="")
|
| 281 |
-
start = st.button("Start", type="primary")
|
| 282 |
-
|
| 283 |
-
# session state
|
| 284 |
-
if "order" not in st.session_state:
|
| 285 |
-
st.session_state.order = []
|
| 286 |
-
if "idx" not in st.session_state:
|
| 287 |
-
st.session_state.idx = 0
|
| 288 |
-
if "total" not in st.session_state:
|
| 289 |
-
st.session_state.total = 0
|
| 290 |
-
if "started" not in st.session_state:
|
| 291 |
-
st.session_state.started = False
|
| 292 |
-
|
| 293 |
-
# start
|
| 294 |
-
if start:
|
| 295 |
-
if not annotator.strip():
|
| 296 |
-
st.sidebar.error("Please enter your name.")
|
| 297 |
-
else:
|
| 298 |
-
imgs = list_images()
|
| 299 |
-
labels_df = read_labels()
|
| 300 |
-
if not SHOW_ALREADY_LABELED and len(labels_df) > 0:
|
| 301 |
-
labeled = set(labels_df["image"].astype(str).tolist())
|
| 302 |
-
rel_imgs = [rel_to_image_dir(p) for p in imgs]
|
| 303 |
-
imgs = [p for p, r in zip(imgs, rel_imgs) if r not in labeled]
|
| 304 |
-
|
| 305 |
-
if not imgs:
|
| 306 |
-
st.warning("No images found (or all labeled). Upload PNG/JPG/etc. to the `images/` folder.")
|
| 307 |
-
else:
|
| 308 |
-
# Simple deterministic order; you can randomize with: random.shuffle(imgs)
|
| 309 |
-
st.session_state.order = imgs
|
| 310 |
-
st.session_state.idx = 0
|
| 311 |
-
st.session_state.total = len(imgs)
|
| 312 |
-
st.session_state.started = True
|
| 313 |
-
|
| 314 |
-
# main panel
|
| 315 |
-
if not st.session_state.started:
|
| 316 |
-
st.info("Fill your name on the left and press **Start**.")
|
| 317 |
-
else:
|
| 318 |
-
idx = st.session_state.idx
|
| 319 |
-
total = st.session_state.total
|
| 320 |
-
if idx >= total:
|
| 321 |
-
st.success("All done 🎉 Thank you!")
|
| 322 |
-
else:
|
| 323 |
-
current_image = st.session_state.order[idx]
|
| 324 |
-
st.caption(f"{idx} / {total}")
|
| 325 |
-
try:
|
| 326 |
-
img = Image.open(current_image)
|
| 327 |
-
# If multipage TIFF, show first page
|
| 328 |
-
if getattr(img, "n_frames", 1) > 1:
|
| 329 |
-
img.seek(0)
|
| 330 |
-
# Convert to RGB for browsers
|
| 331 |
-
if img.mode not in ("RGB", "RGBA"):
|
| 332 |
-
img = img.convert("RGB")
|
| 333 |
-
st.image(img, use_column_width=True)
|
| 334 |
-
except Exception as e:
|
| 335 |
-
st.warning(f"Could not display image: {current_image}\n{e}")
|
| 336 |
-
|
| 337 |
-
col1, col2, col3 = st.columns([1,1,1])
|
| 338 |
-
with col1:
|
| 339 |
-
if st.button(f"⬅️ {LABEL_LEFT}", use_container_width=True):
|
| 340 |
-
write_label(current_image, LABEL_LEFT, annotator.strip())
|
| 341 |
-
st.session_state.idx += 1
|
| 342 |
-
st.rerun()
|
| 343 |
-
with col2:
|
| 344 |
-
if st.button("Skip", use_container_width=True):
|
| 345 |
-
write_label(current_image, "Skip", annotator.strip())
|
| 346 |
-
st.session_state.idx += 1
|
| 347 |
-
st.rerun()
|
| 348 |
-
with col3:
|
| 349 |
-
if st.button(f"{LABEL_RIGHT} ➡️", use_container_width=True):
|
| 350 |
-
write_label(current_image, LABEL_RIGHT, annotator.strip())
|
| 351 |
-
st.session_state.idx += 1
|
| 352 |
-
st.rerun()
|
| 353 |
-
|
| 354 |
-
# Footer / admin
|
| 355 |
-
st.divider()
|
| 356 |
-
st.caption("Labels are saved to `labels.csv` in this Space. You can download it from the Files tab.")
|
| 357 |
-
'''
|
|
|
|
| 169 |
|
| 170 |
st.divider()
|
| 171 |
st.caption("Labels are saved & committed as `labels.csv` to this Space (see the Files tab).")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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