Spaces:
Sleeping
Sleeping
Download app.py from davda54/svg-annotation: direct link, hf CLI and curl.
- Browser
- Download file 23.9 kB
-
https://huggingface.co/spaces/davda54/svg-annotation/resolve/main/app.py
- Command line
-
hf download hf://spaces/davda54/svg-annotation/app.py
-
curl -L -o app.py https://huggingface.co/spaces/davda54/svg-annotation/resolve/main/app.py
23.9 kB
| 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": '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><circle cx="100" cy="100" r="80" fill="red"/></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""" | |
| <div style="display: flex; justify-content: center; align-items: center; padding: 20px; background: white; border-radius: 8px;"> | |
| <div style="max-width: 500px; max-height: 500px; width: 100%;"> | |
| {svg_content} | |
| </div> | |
| </div> | |
| """ | |
| def get_sample_display_data(sample): | |
| """Get the display data for a sample, including shuffled options.""" | |
| options, correct_index = get_shuffled_options(sample) | |
| svg_html = render_svg_html(sample["svg"]) | |
| return svg_html, options, correct_index | |
| def login(user_id: str) -> Tuple: | |
| """Handle user login""" | |
| if not user_id or user_id.strip() == "" or user_id.strip() not in USER_IDS: | |
| return ( | |
| gr.update(visible=True), # login_interface | |
| gr.update(visible=False), # annotation_interface | |
| "", # user_state | |
| gr.update(value="Please enter a valid ID"), # login_status | |
| gr.update(), # svg_display | |
| gr.update(), # btn_1 | |
| gr.update(), # btn_2 | |
| gr.update(), # btn_3 | |
| gr.update(), # btn_4 | |
| gr.update(), # progress | |
| [], # current_options state | |
| -1, # correct_index state | |
| ) | |
| user_id = user_id.strip() | |
| sample, current, total = manager.get_next_sample(user_id) | |
| if sample is None: | |
| return ( | |
| gr.update(visible=True), | |
| gr.update(visible=False), | |
| user_id, | |
| gr.update(value=f"All {total} samples completed for user: {user_id}! ๐"), | |
| gr.update(), | |
| gr.update(), | |
| gr.update(), | |
| gr.update(), | |
| gr.update(), | |
| gr.update(), | |
| [], | |
| -1, | |
| ) | |
| svg_html, options, correct_index = get_sample_display_data(sample) | |
| return ( | |
| gr.update(visible=False), # login_interface | |
| gr.update(visible=True), # annotation_interface | |
| user_id, # user_state | |
| gr.update(value=""), # login_status | |
| gr.update(value=svg_html), # svg_display | |
| gr.update(value=f"A: {options[0]}"), # btn_1 | |
| gr.update(value=f"B: {options[1]}"), # btn_2 | |
| gr.update(value=f"C: {options[2]}"), # btn_3 | |
| gr.update(value=f"D: {options[3]}"), # btn_4 | |
| gr.update(value=f"Progress: {current}/{total}"), # progress | |
| options, # current_options state | |
| correct_index, # correct_index state | |
| ) | |
| def annotate(choice_index: int, user_id: str, current_options: list, correct_index: int) -> Tuple: | |
| """Handle annotation submission""" | |
| if not user_id: | |
| return ( | |
| gr.update(), # svg_display | |
| gr.update(), # btn_1 | |
| gr.update(), # btn_2 | |
| gr.update(), # btn_3 | |
| gr.update(), # btn_4 | |
| gr.update(), # progress | |
| gr.update(value="Error: No user logged in", visible=True), # status | |
| [], # current_options | |
| -1, # correct_index | |
| ) | |
| # Get current sample to save annotation | |
| sample, _, _ = manager.get_next_sample(user_id) | |
| if sample: | |
| chosen_caption = current_options[choice_index] | |
| manager.save_annotation( | |
| user_id=user_id, | |
| sample_id=sample["id"], | |
| choice_index=choice_index, | |
| chosen_caption=chosen_caption, | |
| correct_caption=sample["correct"], | |
| options=current_options, | |
| correct_index=correct_index, | |
| filename=sample.get("filename"), | |
| ) | |
| # Get next sample | |
| next_sample, current, total = manager.get_next_sample(user_id) | |
| if next_sample is None: | |
| return ( | |
| gr.update(value="<h2 style='text-align:center;padding:40px;'>All samples completed! Thank you for your annotations. ๐</h2>"), | |
| gr.update(value="A: โ", interactive=False), | |
| gr.update(value="B: โ", interactive=False), | |
| gr.update(value="C: โ", interactive=False), | |
| gr.update(value="D: โ", interactive=False), | |
| gr.update(value=f"Progress: {total}/{total} โ Complete!"), | |
| gr.update(value="All annotations complete!", visible=True), | |
| [], | |
| -1, | |
| ) | |
| svg_html, options, new_correct_index = get_sample_display_data(next_sample) | |
| return ( | |
| gr.update(value=svg_html), # svg_display | |
| gr.update(value=f"A: {options[0]}"), # btn_1 | |
| gr.update(value=f"B: {options[1]}"), # btn_2 | |
| gr.update(value=f"C: {options[2]}"), # btn_3 | |
| gr.update(value=f"D: {options[3]}"), # btn_4 | |
| gr.update(value=f"Progress: {current}/{total}"), # progress | |
| gr.update(value="Annotation saved!", visible=True), # status | |
| options, # current_options | |
| new_correct_index, # correct_index | |
| ) | |
| def logout() -> Tuple: | |
| """Handle user logout""" | |
| return ( | |
| gr.update(visible=True), | |
| gr.update(visible=False), | |
| "", | |
| gr.update(value=""), | |
| gr.update(value=""), | |
| gr.update(value="A:"), | |
| gr.update(value="B:"), | |
| gr.update(value="C:"), | |
| gr.update(value="D:"), | |
| gr.update(value=""), | |
| [], | |
| -1, | |
| ) | |
| # Custom CSS | |
| custom_css = """ | |
| #login-group { | |
| background-color: white !important; | |
| } | |
| #login-group > * { | |
| background-color: white !important; | |
| } | |
| #login-group .gr-group { | |
| background-color: white !important; | |
| } | |
| #login-group .gr-form { | |
| background-color: white !important; | |
| } | |
| .light-shadow { | |
| box-shadow: 0 1px 4px 0 rgb(0 0 0 / 0.1) !important; | |
| } | |
| .narrow-center { | |
| max-width: 33.33%; | |
| min-width: 320px; | |
| margin-left: auto !important; | |
| margin-right: auto !important; | |
| } | |
| .svg-container { | |
| display: flex; | |
| justify-content: center; | |
| background: white; | |
| border-radius: 8px; | |
| padding: 10px; | |
| } | |
| .svg-container svg { | |
| max-width: 100%; | |
| height: auto; | |
| } | |
| .caption-btn { | |
| text-align: left !important; | |
| white-space: normal !important; | |
| min-height: 50px !important; | |
| padding: 12px 16px !important; | |
| } | |
| """ | |
| # Create Gradio interface | |
| with gr.Blocks( | |
| theme=Soft(font=[gr.themes.GoogleFont("Source Sans Pro"), "Arial"]), | |
| title="SVG Caption Annotation Tool", | |
| css=custom_css | |
| ) as app: | |
| gr.Markdown("# SVG Caption Annotation") | |
| user_state = gr.State("") | |
| current_options_state = gr.State([]) | |
| correct_index_state = gr.State(-1) | |
| # Login Interface | |
| with gr.Column(visible=True) as login_interface: | |
| with gr.Column(variant="panel", elem_id="login-group", elem_classes="light-shadow"): | |
| gr.Markdown("## Log in", padding=True) | |
| user_id_input = gr.Textbox( | |
| label="Enter your unique annotator ID to begin", | |
| placeholder="Annotator ID" | |
| ) | |
| with gr.Row(): | |
| login_btn = gr.Button("Login", variant="primary", scale=0.2, min_width=100) | |
| gr.HTML("") | |
| login_status = gr.Markdown("", padding=True) | |
| # Annotation Interface | |
| with gr.Column(visible=False, elem_id="annotation-group") as annotation_interface: | |
| with gr.Column(elem_classes="narrow-center"): | |
| progress_label = gr.Markdown("") | |
| gr.Markdown(f"**{PROMPT_TEXT}**") | |
| # SVG display | |
| with gr.Row(elem_classes="light-shadow"): | |
| svg_display = gr.HTML(value="", label="SVG Image") | |
| # Caption choice buttons | |
| gr.Markdown("### Choose the best caption:") | |
| btn_1 = gr.Button("A:", variant="primary", elem_classes="caption-btn") | |
| btn_2 = gr.Button("B:", variant="primary", elem_classes="caption-btn") | |
| btn_3 = gr.Button("C:", variant="primary", elem_classes="caption-btn") | |
| btn_4 = gr.Button("D:", variant="primary", elem_classes="caption-btn") | |
| status_message = gr.Markdown("", visible=False) | |
| with gr.Row(visible=False): | |
| logout_btn = gr.Button("Logout", variant="stop", size="sm") | |
| # --- Event handlers --- | |
| login_outputs = [ | |
| login_interface, | |
| annotation_interface, | |
| user_state, | |
| login_status, | |
| svg_display, | |
| btn_1, btn_2, btn_3, btn_4, | |
| progress_label, | |
| current_options_state, | |
| correct_index_state, | |
| ] | |
| login_btn.click( | |
| fn=login, | |
| inputs=[user_id_input], | |
| outputs=login_outputs | |
| ) | |
| user_id_input.submit( | |
| fn=login, | |
| inputs=[user_id_input], | |
| outputs=login_outputs | |
| ) | |
| annotate_outputs = [ | |
| svg_display, | |
| btn_1, btn_2, btn_3, btn_4, | |
| progress_label, | |
| status_message, | |
| current_options_state, | |
| correct_index_state, | |
| ] | |
| btn_1.click( | |
| fn=lambda uid, opts, ci: annotate(0, uid, opts, ci), | |
| inputs=[user_state, current_options_state, correct_index_state], | |
| outputs=annotate_outputs | |
| ) | |
| btn_2.click( | |
| fn=lambda uid, opts, ci: annotate(1, uid, opts, ci), | |
| inputs=[user_state, current_options_state, correct_index_state], | |
| outputs=annotate_outputs | |
| ) | |
| btn_3.click( | |
| fn=lambda uid, opts, ci: annotate(2, uid, opts, ci), | |
| inputs=[user_state, current_options_state, correct_index_state], | |
| outputs=annotate_outputs | |
| ) | |
| btn_4.click( | |
| fn=lambda uid, opts, ci: annotate(3, uid, opts, ci), | |
| inputs=[user_state, current_options_state, correct_index_state], | |
| outputs=annotate_outputs | |
| ) | |
| logout_btn.click( | |
| fn=logout, | |
| inputs=[], | |
| outputs=login_outputs | |
| ) | |
| if __name__ == "__main__": | |
| app.launch() |