from __future__ import annotations import os import gradio as gr import json import random from datetime import datetime from typing import Dict, List, Tuple import hashlib from datasets import load_dataset from huggingface_hub import HfApi from huggingface_hub import Repository import shutil import threading from collections.abc import Iterable from gradio.themes.base import Base from gradio.themes.utils import colors, fonts, sizes HF_TOKEN = os.environ.get("HF_TOKEN") os.environ['HF_AUTH'] = HF_TOKEN HfApi(token=HF_TOKEN) USER_IDS = set(json.loads(os.environ.get("USER_IDS"))) class Soft(Base): def __init__( self, *, primary_hue: colors.Color | str = colors.indigo, secondary_hue: colors.Color | str = colors.indigo, neutral_hue: colors.Color | str = colors.gray, spacing_size: sizes.Size | str = sizes.spacing_md, radius_size: sizes.Size | str = sizes.radius_md, text_size: sizes.Size | str = sizes.text_md, font: fonts.Font | str | Iterable[fonts.Font | str] = ( "ui-sans-serif", "system-ui", "sans-serif", ), font_mono: fonts.Font | str | Iterable[fonts.Font | str] = ( "ui-monospace", "Consolas", "monospace", ), ): super().__init__( primary_hue=primary_hue, secondary_hue=secondary_hue, neutral_hue=neutral_hue, spacing_size=spacing_size, radius_size=radius_size, text_size=text_size, font=font, font_mono=font_mono, ) self.name = "soft" super().set( # Colors background_fill_primary="*neutral_50", slider_color="*primary_500", slider_color_dark="*primary_600", # Shadows shadow_drop="0 1px 4px 0 rgb(0 0 0 / 0.1)", shadow_drop_lg="0 2px 5px 0 rgb(0 0 0 / 0.2)", # Block Labels block_background_fill="white", block_label_padding="*spacing_sm *spacing_md", block_label_background_fill="*primary_100", block_label_background_fill_dark="*primary_600", block_label_radius="*radius_md", block_label_text_size="*text_md", block_label_text_weight="600", block_label_text_color="*primary_500", block_label_text_color_dark="white", block_title_radius="*block_label_radius", block_title_padding="*block_label_padding", block_title_background_fill="*block_label_background_fill", block_title_text_weight="600", block_title_text_color="*primary_500", block_title_text_color_dark="white", block_label_margin="*spacing_md", # Inputs input_background_fill="white", input_border_color="*neutral_100", input_shadow="*shadow_drop", input_shadow_focus="*shadow_drop_lg", checkbox_shadow="none", # Buttons shadow_spread="6px", button_primary_shadow="*shadow_drop_lg", button_primary_shadow_hover="*shadow_drop_lg", button_primary_shadow_active="*shadow_inset", button_secondary_shadow="*shadow_drop_lg", button_secondary_shadow_hover="*shadow_drop_lg", button_secondary_shadow_active="*shadow_inset", checkbox_label_shadow="*shadow_drop_lg", button_primary_background_fill="*primary_500", button_primary_background_fill_hover="*primary_400", button_primary_background_fill_hover_dark="*primary_500", button_primary_text_color="white", button_secondary_background_fill="white", button_secondary_background_fill_hover="*neutral_100", button_secondary_background_fill_hover_dark="*primary_500", button_secondary_text_color="*neutral_800", button_cancel_background_fill="*button_secondary_background_fill", button_cancel_background_fill_hover="*button_secondary_background_fill_hover", button_cancel_background_fill_hover_dark="*button_secondary_background_fill_hover", button_cancel_text_color="*button_secondary_text_color", checkbox_label_background_fill_selected="*primary_500", checkbox_label_background_fill_selected_dark="*primary_600", checkbox_border_width="1px", checkbox_border_color="*neutral_100", checkbox_border_color_dark="*neutral_600", checkbox_background_color_selected="*primary_600", checkbox_background_color_selected_dark="*primary_700", checkbox_border_color_focus="*primary_500", checkbox_border_color_focus_dark="*primary_600", checkbox_border_color_selected="*primary_600", checkbox_border_color_selected_dark="*primary_700", checkbox_label_text_color_selected="white", # Borders block_border_width="0px", panel_border_width="0px", ) # Configuration for the output dataset ANNOTATIONS_REPO = "ltg/svg-qa-annotations" DATA_DIR = "annotation_data" ANNOTATIONS_FILE = os.path.join(DATA_DIR, "train.jsonl") PROMPT_TEXT = "Which of the four captions best describes the following SVG image?" # Initialize repository def init_repository(): """Initialize or clone the repository""" try: repo = Repository( local_dir=DATA_DIR, clone_from=ANNOTATIONS_REPO, use_auth_token=HF_TOKEN, repo_type="dataset" ) repo.git_pull() return repo except Exception as e: print(f"Error initializing repository: {e}") os.makedirs(DATA_DIR, exist_ok=True) return None # Initialize on startup annotation_repo = init_repository() def load_existing_annotations(): """Load existing annotations from the jsonl file""" annotations = {} if os.path.exists(ANNOTATIONS_FILE): try: with open(ANNOTATIONS_FILE, "r") as f: for line in f: if line.strip(): ann = json.loads(line) user_id = ann.get("user_id") if user_id: if user_id not in annotations: annotations[user_id] = [] annotations[user_id].append(ann) print(f"Loaded {sum(len(v) for v in annotations.values())} existing annotations") except Exception as e: print(f"Error loading annotations: {e}") return annotations def save_annotation_to_file(annotation_data): """Save a single annotation to the jsonl file and push to hub""" global annotation_repo try: if annotation_repo: annotation_repo.git_pull() with open(ANNOTATIONS_FILE, "a") as f: line = json.dumps(annotation_data, ensure_ascii=False) f.write(f"{line}\n") if annotation_repo: annotation_repo.push_to_hub(blocking=False) except Exception as e: print(f"Error saving annotation: {e}") try: shutil.rmtree(DATA_DIR) annotation_repo = init_repository() with open(ANNOTATIONS_FILE, "a") as f: line = json.dumps(annotation_data, ensure_ascii=False) f.write(f"{line}\n") if annotation_repo: annotation_repo.push_to_hub(blocking=False) except Exception as e2: print(f"Failed to save annotation after retry: {e2}") def load_dataset_samples(): """Load and prepare dataset samples for SVG caption QA""" try: dataset = load_dataset("ltg/svg-qa", split="train", token=HF_TOKEN) samples = [] for item in dataset: sample_id = item["index"] svg_content = item["image"] annotations = item["annotations"] # Skip samples with null annotations if annotations is None: continue # Each annotation becomes a separate sample for ann_idx, annotation in enumerate(annotations): if annotation is None: continue correct_caption = annotation["correct"] incorrect_captions = annotation["incorrect"] # list of 3 # Use a unique id combining sample index and annotation index unique_id = f"{sample_id}_{ann_idx}" if len(annotations) > 1 else str(sample_id) samples.append({ "id": unique_id, "original_index": sample_id, "annotation_index": ann_idx, "filename": item["filename"], "svg": svg_content, "correct": correct_caption, "incorrect": incorrect_captions, }) print(f"Loaded {len(samples)} SVG QA samples (from {len(dataset)} images)") return samples except Exception as e: print(f"Error loading dataset: {e}") print("Using dummy data for testing...") return [ { "id": "0", "original_index": 0, "annotation_index": 0, "filename": "dummy.svg", "svg": '', "correct": "a red circle", "incorrect": [ "a blue square", "a green triangle", "a yellow star" ], } ] # Load dataset on startup DATASET_SAMPLES = load_dataset_samples() def get_shuffled_options(sample): """Given a sample, return shuffled (options, correct_index) pair. Seeded on the SVG image content so order is consistent across all users.""" options = [sample["correct"]] + sample["incorrect"] random.seed(sample["svg"]) random.shuffle(options) correct_index = options.index(sample["correct"]) return options, correct_index class AnnotationManager: def __init__(self): self.annotations = load_existing_annotations() self.user_states = {} for user_id, user_annotations in self.annotations.items(): annotated_ids = [ann["sample_id"] for ann in user_annotations] self.user_states[user_id] = { "annotations": annotated_ids } def get_user_seed(self, user_id: str) -> int: """Generate consistent seed for user""" return int(hashlib.md5(user_id.encode()).hexdigest(), 16) def get_user_samples(self, user_id: str) -> List[Dict]: """Get shuffled samples for user based on their ID""" seed = self.get_user_seed(user_id) samples = DATASET_SAMPLES.copy() random.Random(seed).shuffle(samples) return samples def get_next_sample(self, user_id: str) -> Tuple[Dict, int, int]: """Get next unannotated sample for user""" if user_id not in self.user_states: if user_id in self.annotations: annotated_ids = [ann["sample_id"] for ann in self.annotations[user_id]] self.user_states[user_id] = { "annotations": annotated_ids } else: self.user_states[user_id] = { "annotations": [] } samples = self.get_user_samples(user_id) state = self.user_states[user_id] total_annotated = len(state["annotations"]) for idx, sample in enumerate(samples): if not self.is_annotated(user_id, sample["id"]): return sample, total_annotated + 1, len(samples) return None, len(samples), len(samples) def is_annotated(self, user_id: str, sample_id) -> bool: """Check if user has annotated this sample""" if user_id not in self.annotations: return False return any(ann["sample_id"] == sample_id for ann in self.annotations[user_id]) def save_annotation(self, user_id: str, sample_id, choice_index: int, chosen_caption: str, correct_caption: str, options: List[str], correct_index: int, filename: str = None): """Save user's annotation and persist to file""" if user_id not in self.annotations: self.annotations[user_id] = [] annotation = { "user_id": user_id, "sample_id": sample_id, "filename": filename, "chosen_index": choice_index, "chosen_caption": chosen_caption, "correct_caption": correct_caption, "correct_index": correct_index, "is_correct": chosen_caption == correct_caption, "options": options, "timestamp": datetime.now().isoformat() } self.annotations[user_id].append(annotation) if user_id in self.user_states: self.user_states[user_id]["annotations"].append(sample_id) else: self.user_states[user_id] = { "annotations": [sample_id] } threading.Thread( target=save_annotation_to_file, args=(annotation,) ).start() print(f"Saved annotation: user={user_id}, sample={sample_id}, correct={annotation['is_correct']}") def get_user_progress(self, user_id: str) -> Dict: """Get user's annotation progress""" if user_id not in self.annotations: return {"completed": 0, "total": len(DATASET_SAMPLES)} completed = len(self.annotations[user_id]) return {"completed": completed, "total": len(DATASET_SAMPLES)} # Initialize manager manager = AnnotationManager() def render_svg_html(svg_content: str) -> str: """Wrap SVG content in HTML for display, centered and scaled.""" return f"""