### Initialize SimpleLabel Widget Source: https://github.com/koaning/molabel/blob/main/docs/index.html Basic setup for the SimpleLabel widget requiring a list of examples and a custom render function. ```python from molabel import SimpleLabel widget = SimpleLabel(examples=list_of_examples, render=render_function) widget ``` -------------------------------- ### Install molabel with uv Source: https://github.com/koaning/molabel/blob/main/README.md Use uv pip to install the molabel package. Ensure you have uv installed. ```bash uv pip install molabel ``` -------------------------------- ### Initialize SimpleLabel Widget Source: https://context7.com/koaning/molabel/llms.txt Initialize the SimpleLabel widget with examples and a custom render function. The 'notes=True' argument enables note-taking during annotation. ```python from molabel import SimpleLabel widget = SimpleLabel( examples=examples, render=render_with_mohtml, notes=True ) ``` ```python widget_jinja = SimpleLabel( examples=examples, render=render_with_jinja, notes=True ) ``` ```python widget = SimpleLabel( examples=[ {"id": 1, "text": "First example"}, {"id": 2, "text": "Second example"}, {"id": 3, "text": "Third example"}, ], render=lambda ex: f"
{ex['text']}
", notes=True ) ``` -------------------------------- ### Basic Usage of SimpleLabel Widget Source: https://github.com/koaning/molabel/blob/main/README.md Initialize and display the SimpleLabel widget for interactive annotation. The render function defines how examples are displayed. Use get_annotations() to retrieve labeled data. ```python from molabel import SimpleLabel def render_example(example): return f"{example['text']}
" # Create annotation widget widget = SimpleLabel( examples=[{"text": "example 1"}, {"text": "example 2"}], render=render_example, notes=True ) # Display in notebook widget # Get annotations after labeling annotations = widget.get_annotations() ``` -------------------------------- ### Render with Jinja2 Template Source: https://context7.com/koaning/molabel/llms.txt Define a Jinja2 template for custom HTML rendering of annotation examples. The template can access example data using Jinja2 syntax. ```python import jinja2 template = jinja2.Template("""{{ example.text }}{{ example.sentiment }}
{example['text']}
{ex['text']}
", notes=True, shortcuts=custom_keyboard_shortcuts, gamepad_shortcuts=custom_gamepad_shortcuts ) # Available actions for shortcuts: # - "prev": Go to previous example # - "yes": Label current example as yes # - "no": Label current example as no # - "skip": Skip current example # - "focus_notes": Focus the notes input field # - "speech_notes": Start/stop speech recognition for notes # - "speech_selection": Speech recognition for selection ``` -------------------------------- ### Import HTML and Data Components Source: https://github.com/koaning/molabel/blob/main/docs/index.html Imports necessary components for HTML rendering, CSS styling, and data manipulation with Pandas. ```python from mohtml import p, tailwind_css, div, br, pre, code from mohtml.components import terminal import jinja2 import pandas as pd ``` -------------------------------- ### Configure Keyboard Shortcuts Source: https://github.com/koaning/molabel/blob/main/docs/index.html Defines default keyboard shortcuts for annotation actions. These can be customized by passing keyword arguments to the annotation tool. ```python default_shortcuts = { "Alt+1": "prev", "Alt+2": "yes", "Alt+3": "no", "Alt+4": "skip", "Alt+5": "focus_notes", "Alt+6": "speech_notes" } default_gamepad_shortcuts = { "button_0": "yes", "button_1": "no", "button_2": "skip", "button_3": "prev", "button_4": "speech_notes", "button_6": "focus_notes" } ``` -------------------------------- ### Initialize ImageLabel with NumPy Arrays Source: https://context7.com/koaning/molabel/llms.txt Create an ImageLabel widget using NumPy arrays, commonly obtained from libraries like OpenCV or Matplotlib. The array should be of uint8 type with dimensions (height, width, channels). ```python numpy_image = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8) widget_numpy = ImageLabel( images=[numpy_image], classes=["annotation"] ) ``` -------------------------------- ### Initialize ImageLabel with BytesIO Objects Source: https://context7.com/koaning/molabel/llms.txt Use ImageLabel with BytesIO objects, which are file-like objects in memory. This is useful for handling image data read from or written to memory buffers. ```python buffer = BytesIO() pil_image.save(buffer, format="PNG") buffer.seek(0) widget_buffer = ImageLabel( images=[buffer], classes=["label"] ) ``` -------------------------------- ### Integrate ImageLabel with SAM for Segmentation Source: https://context7.com/koaning/molabel/llms.txt Use ImageLabel annotations (points and boxes) as input for the Segment Anything Model (SAM) to generate segmentation masks. Requires loading the SAM model and setting the image for the predictor. ```python from molabel import ImageLabel from segment_anything import SamPredictor, sam_model_registry from PIL import Image import numpy as np import marimo as mo # Load image and SAM model image = Image.open("photo.png").convert("RGB") sam = sam_model_registry["vit_h"](checkpoint="sam_vit_h_4b8939.pth") sam.to(device="cpu") predictor = SamPredictor(sam) predictor.set_image(np.array(image)) # Create annotation widget label_widget = mo.ui.anywidget( ImageLabel( images=["photo.png"], classes=["foreground", "background"], colors=["orange", "blue"] ) ) # After user annotates, extract point coordinates annotations = label_widget.value.get_normalized_annotations()[0]["elements"] points = [a for a in annotations if a["type"] == "point"] boxes = [a for a in annotations if a["type"] == "box"] # Convert to SAM input format point_coords = [[p["points"][0]["x"], p["points"][0]["y"]] for p in points] # Generate segmentation mask if point_coords: from sklearn.preprocessing import LabelEncoder labels = LabelEncoder().fit_transform([p["label"] for p in points]) + 1 masks, scores, logits = predictor.predict( point_coords=np.array(point_coords), point_labels=labels, multimask_output=False ) # Create masked output image with transparency rgba_image = np.dstack([np.array(image), masks[0] * 255]) masked_image = Image.fromarray(rgba_image.astype(np.uint8), mode="RGBA") ``` -------------------------------- ### ImageLabel Widget for Image Annotation Source: https://context7.com/koaning/molabel/llms.txt Utilize ImageLabel for annotating images with points and bounding boxes. Supports various image sources and configurable classes with colors. Displays images within a marimo environment. ```python from molabel import ImageLabel import marimo as mo # Create image annotation widget with local files widget = ImageLabel( images=["image1.png", "image2.jpg"], # Local file paths classes=["foreground", "background", "ignore"], colors=["orange", "blue", "gray"] # Colors for each class ) # Display in marimo label_widget = mo.ui.anywidget(widget) label_widget ``` -------------------------------- ### Load Data from CSV Source: https://github.com/koaning/molabel/blob/main/docs/index.html Loads text data from a CSV file hosted on GitHub using Pandas. This is useful for preparing datasets for annotation. ```python texts = list( pd.read_csv( "https://raw.githubusercontent.com/koaning/molabel/refs/heads/main/data/subset.csv" )[ "text" ] ) return (texts,) ``` -------------------------------- ### Retrieve and Export Annotations Source: https://context7.com/koaning/molabel/llms.txt Retrieve all annotations from the widget, convert them to a pandas DataFrame for analysis, and export them to a JSON file. Supports filtering by label. ```python from molabel import SimpleLabel import pandas as pd import json # Create and use widget (after labeling session) widget = SimpleLabel( examples=[ {"id": 1, "text": "First example"}, {"id": 2, "text": "Second example"}, {"id": 3, "text": "Third example"}, ], render=lambda ex: f"{ex['text']}
", notes=True ) # Retrieve all annotations annotations = widget.get_annotations() # Example output: # [ # {"index": 0, "example": {"id": 1, "text": "First example"}, "label": "yes", "notes": "clear case", "timestamp": "2024-01-15T10:30:00Z"}, # {"index": 1, "example": {"id": 2, "text": "Second example"}, "label": "no", "notes": "", "timestamp": "2024-01-15T10:30:15Z"}, # {"index": 2, "example": {"id": 3, "text": "Third example"}, "label": "skip", "notes": "ambiguous", "timestamp": "2024-01-15T10:30:30Z"} # ] # Convert to pandas DataFrame for analysis df = pd.DataFrame(annotations) df_flat = pd.json_normalize(annotations) # Flatten nested example dict print(df_flat[["example.id", "label", "notes"]]) # Export to JSON file with open("annotations.json", "w") as f: json.dump(annotations, f, indent=2) # Filter by label yes_examples = [a for a in annotations if a["label"] == "yes"] no_examples = [a for a in annotations if a["label"] == "no"] skipped = [a for a in annotations if a["label"] == "skip"] # Calculate agreement metrics total = len(annotations) yes_rate = len(yes_examples) / total if total > 0 else 0 print(f"Yes rate: {yes_rate:.2%}") ``` -------------------------------- ### Access Raw and Normalized Annotations Source: https://context7.com/koaning/molabel/llms.txt Retrieve raw annotations with normalized 0-1 coordinates or pixel-coordinate annotations using the widget's methods. ```python raw_annotations = widget.annotations ``` ```python normalized = widget.get_normalized_annotations() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.