Spaces:
Sleeping
Sleeping
This is almost good
Browse filesFiles changed (5)
- .gitignoreAdded+6
- app.py+171-92
- dataset.py+2
- documentation.pyAdded+217
- packager.pyAdded+109
123456.py[cod]__pycache__/.mypy_cache/.pytest_cache/.ruff_cache/.pdm-python3 unmodified lines45678910111213141516171819209 unmodified lines303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381 unmodified line1401411421431441451461471481491501511521531541551561571581593 unmodified linesfrom dataset import ImageDatasetfrom labelizer import get_task_responsedef auto_label(image):text = get_task_response("<MORE_DETAILED_CAPTION>", image)return image, textdef auto_label_and_update(dataset, im, image_id):"""Generate label and return updated dataset."""text = get_task_response("<MORE_DETAILED_CAPTION>", im)return dataset.update_label(image_id, text)def uploaded(files, current_dataset):9 unmodified lines# Generate actual labelslabels_dict = {}for imdata in progress.tqdm(dataset.images):text = get_task_response("<MORE_DETAILED_CAPTION>", Image.open(imdata["path"]))print(text)labels_dict[imdata["id"]] = textreturn dataset.update_all_labels(labels_dict), labeldef update_buttons_states(dataset):count = len(dataset.images)return (gr.update(interactive=count > 0), # remove allgr.update(interactive=count > 0), # label all)CSS = """.label_image_box {border-radius: 1rem;background: var(--panel-background-fill);.image-frame img {height: 300px;max-height: 300px;}}"""with gr.Blocks(title="Labelizer") as demo:dataset = gr.State()with gr.Sidebar():gr.Markdown("# πΌοΈ Image Labeling Tool")gr.Markdown("Upload images and add labels to build your dataset.")upload_button = gr.UploadButton("Upload images", file_count="multiple")label_all = gr.Button("Labelize all images", interactive=False)is_labeling_in_progress = gr.State(False)progressbar = gr.Label("", visible=False, label="Preparing...")remove_all = gr.Button("Remove all", interactive=False)@gr.render(inputs=[dataset, is_labeling_in_progress])def render_grid(dataset, is_labeling_in_progress):if dataset is None:returncols = 6rows = len(dataset.images) // colsif len(dataset.images) > cols * rows:rows += 1current = 0for _ in range(rows):with gr.Row(equal_height=True):for _ in range(cols):with gr.Column(variant="compact", elem_classes=["label_image_box"]):if current >= len(dataset.images):breakimage = gr.Image(dataset.images[current]["path"],type="pil",container=False,sources=None,buttons=["fullscreen"],)label = gr.Text(dataset.images[current]["label"],placeholder="Description...",lines=5,container=False,interactive=not is_labeling_in_progress,)with gr.Row():button = gr.Button("Generate label",interactive=not is_labeling_in_progress,)button.click(auto_label,inputs=[image],outputs=[image, label],)current += 1remove_all.click(lambda: ImageDataset(), inputs=None, outputs=dataset).then(update_buttons_states, inputs=dataset, outputs=[remove_all, label_all])upload_button.upload(uploaded, inputs=[upload_button, dataset], outputs=dataset).then(update_buttons_states,inputs=dataset,outputs=[remove_all, label_all],)label_all.click(fn=lambda: (gr.update(interactive=False),gr.update(interactive=False),gr.update(visible=True),True,),inputs=None,outputs=[upload_button,label_all,progressbar,is_labeling_in_progress,],).then(1 unmodified lineinputs=[dataset, progressbar],outputs=[dataset, progressbar],).then(fn=lambda: (gr.update(interactive=True),gr.update(interactive=True),gr.update(visible=False),False,),inputs=None,outputs=[upload_button,label_all,progressbar,is_labeling_in_progress,],)if __name__ == "__main__":demo.launch(css=CSS)3 unmodified lines45678910111213141516171819202122232425269 unmodified lines363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871 unmodified line1891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372383 unmodified linesfrom dataset import ImageDatasetfrom labelizer import get_task_responsefrom packager import create_dataset_zipfrom documentation import DOC_CONTENTdef auto_label(image, imid, dataset):text = get_task_response("<MORE_DETAILED_CAPTION>", image)ds = dataset.update_label(imid, text)return text, dsdef label_changed(label, imid, dataset):return dataset.update_label(imid, label)def update_single_label(dataset, label_text, image_id):"""Update single image label in dataset."""return dataset.update_label(image_id, label_text)def uploaded(files, current_dataset):9 unmodified lines# Generate actual labelslabels_dict = {}for imdata in progress.tqdm(dataset.images):text = get_task_response("<MORE_DETAILED_CAPTION>", Image.open(imdata["path"])) # type: ignorelabels_dict[imdata["id"]] = text # type: ignorereturn dataset.update_all_labels(labels_dict), labeldef download_dataset(dataset, organize_in_folders):"""Create and return zip file for download."""zip_path = create_dataset_zip(dataset, organize_in_folders)return zip_pathdef update_buttons_states(dataset, labeling_in_progress=False):"""Update all button states based on dataset and labeling progress."""count = len(dataset.images)return (gr.update(interactive=count == 0 and not labeling_in_progress), # uploadgr.update(interactive=count > 0 and not labeling_in_progress), # label allgr.update(visible=labeling_in_progress), # progressbargr.update(interactive=count > 0 and not labeling_in_progress), # remove allgr.update(interactive=count > 0 and not labeling_in_progress), # downloadlabeling_in_progress, # is_labeling_in_progress)def start_labeling(dataset):"""Start labeling process - disable buttons and show progress."""return update_buttons_states(dataset, labeling_in_progress=True)def finish_labeling(dataset):"""Finish labeling process - enable buttons and hide progress."""return update_buttons_states(dataset, labeling_in_progress=False)with gr.Blocks(title="Labelizer", fill_width=True) as demo:dataset = gr.State()with gr.Sidebar():gr.Markdown("# πΌοΈ Image Labeling Tool")with gr.Group():gr.Markdown("Upload images and add labels to build your dataset.")upload_button = gr.UploadButton("π Upload images", file_count="multiple")label_all = gr.Button("π·οΈ Labelize all images", interactive=False)is_labeling_in_progress = gr.State(False)progressbar = gr.Label("", visible=False, label="Preparing...")remove_all = gr.Button("ποΈ Remove all", interactive=False)with gr.Group():download_button = gr.DownloadButton("πΎ Download dataset", interactive=False, size="lg")organize_files = gr.Checkbox(label="π Organize in folders", value=False)@gr.render(inputs=[dataset, is_labeling_in_progress])def render_grid(ds, is_labeling_in_progress):if not ds or len(ds.images) == 0:gr.Markdown(DOC_CONTENT)return# Hidden component to trigger label refreshgr.Number(value=0, visible=False)with gr.Row(equal_height=True):for im in ds.images:with (gr.Column(elem_classes="label-image-box",preserved_by_key=[f"image_{im['id']}",f"text_{im['id']}",f"button_{im['id']}",f"button_clicked_{im['id']}",f"label_changed_{im['id']}",],),):image = gr.Image(im["path"],type="pil",container=False,sources=None,buttons=["fullscreen"],height=300,key=f"image_{im['id']}",)label = gr.Text(placeholder="Description...",lines=5,container=False,interactive=not is_labeling_in_progress,key=f"text_{im['id']}",)# Hidden component to store current image IDcurrent_image_id = gr.State(value=im["id"])button = gr.Button("β¨ Generate label",interactive=not is_labeling_in_progress,key=f"button_{im['id']}",)button.click(auto_label,inputs=[image, current_image_id, dataset],outputs=[label, dataset],key=f"button_clicked_{im['id']}",)# Update dataset when label is changedlabel.change(label_changed,inputs=[label, current_image_id, dataset],outputs=[dataset],key=f"label_changed_{im['id']}",)# Remove everythingremove_all.click(lambda: ImageDataset(),inputs=None,outputs=dataset,).then(update_buttons_states,inputs=[dataset, is_labeling_in_progress],outputs=[upload_button,label_all,progressbar,remove_all,download_button,is_labeling_in_progress,],)# Label all imageslabel_all.click(fn=start_labeling,inputs=[dataset],outputs=[upload_button,label_all,progressbar,remove_all,download_button,is_labeling_in_progress,],).then(1 unmodified lineinputs=[dataset, progressbar],outputs=[dataset, progressbar],).then(fn=finish_labeling,inputs=[dataset],outputs=[upload_button,label_all,progressbar,remove_all,download_button,is_labeling_in_progress,],)# Upload imagesupload_button.upload(uploaded,inputs=[upload_button, dataset],outputs=dataset,).then(update_buttons_states,inputs=[dataset, is_labeling_in_progress],outputs=[upload_button,label_all,progressbar,remove_all,download_button,is_labeling_in_progress,],)# Download zip filedownload_button.click(download_dataset,inputs=[dataset, organize_files],outputs=[download_button],)if __name__ == "__main__":CSS = """.gr-group {padding: .2rem;}.label-image-box {}"""demo.queue().launch(css=CSS)
4 unmodified lines56789104 unmodified linesdef add_images(self, files):"""Return new instance with added images."""new_images = self.images.copy()for _, file in enumerate(files):new_images.append({4 unmodified lines567891011124 unmodified linesdef add_images(self, files):"""Return new instance with added images."""new_images = self.images.copy()if files is None:return selffor _, file in enumerate(files):new_images.append({
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217DOC_CONTENT = """# πΌοΈ Image Labeling Tool - User Guide
## π Overview
This tool helps you create labeled image datasets quickly and efficiently using AI-powered automatic labeling. Perfect for machine learning projects, computer vision tasks, and dataset preparation.
---
## π Getting Started
### Step 1: Upload Images- Click **π Upload images** button- Select multiple image files from your computer- Supported formats: JPG, PNG, GIF, and other common image formats- Images will appear in a grid layout
### Step 2: Generate LabelsYou have two options for labeling:
#### Option A: Individual Labeling- Click **β¨ Generate label** below any image- AI will analyze the image and create a detailed description- Edit the generated text if needed
#### Option B: Batch Labeling- Click **π·οΈ Labelize all images** button- AI will process all images automatically- Progress bar shows labeling status- All images get labeled simultaneously
### Step 3: Review and Edit- Labels appear as text boxes below each image- Click on any text box to edit the description- Make changes as needed for your specific use case
### Step 4: Download Dataset- Configure download options in the **π¦ Download Options** section- Choose folder organization preference: - β
**Organized**: Images in `images/` folder, labels in `labels/` folder - β **Flat**: All files in root directory- Click **πΎ Download dataset** to get your labeled dataset
---
## π― Features
### π€ AI-Powered Labeling- Uses advanced Florence-2 model for accurate image descriptions- Generates detailed, contextual descriptions- Supports multiple description styles
### π Dataset Management- Add/remove images easily- Edit labels manually- Real-time progress tracking- Efficient batch processing
### π¦ Flexible Export Options- **Organized mode**: Perfect for ML frameworks expecting separate folders- **Flat mode**: Ideal for simple file organization- Automatic text file generation with matching names
### π¨ User-Friendly Interface- Clean, intuitive design- Visual progress indicators- Responsive layout- Emoji-enhanced navigation
---
## π‘ Tips & Best Practices
### For Better Labels- Use high-quality, clear images- Ensure good lighting and focus- Avoid blurry or low-resolution images- Consider image diversity for training datasets
### For Efficient Workflow- Start with a small batch to test label quality- Use batch processing for large datasets- Review and edit labels for consistency- Download frequently to save progress
### For Dataset Quality- Ensure consistent labeling style- Add specific details relevant to your use case- Remove irrelevant or poor-quality images- Test your dataset with your target application
---
## π§ Technical Details
### Supported Image Formats- JPEG (.jpg, .jpeg)- PNG (.png)- GIF (.gif)- BMP (.bmp)- TIFF (.tiff, .tif)- WebP (.webp)
### Label Format- Plain text files (.txt)- UTF-8 encoding- Same basename as corresponding image- Example: `photo1.jpg` β `photo1.txt`
### File Organization
#### Organized Mode```dataset.zipβββ images/β βββ photo1.jpgβ βββ photo2.pngβ βββ ...βββ labels/ βββ photo1.txt βββ photo2.txt βββ ...```
#### Flat Mode```dataset.zipβββ photo1.jpgβββ photo1.txtβββ photo2.pngβββ photo2.txtβββ ...```
---
## π― Use Cases
### Machine Learning- **Image Classification**: Create labeled datasets for training classifiers- **Object Detection**: Generate descriptions for object detection tasks- **Image Retrieval**: Build searchable image databases- **Data Augmentation**: Create consistent label sets for augmented data
### Content Management- **Photo Archives**: Organize personal or professional image collections- **E-commerce**: Generate product descriptions automatically- **Social Media**: Create alt-text and captions for images- **Digital Asset Management**: Tag and organize visual content
### Research & Education- **Academic Projects**: Prepare datasets for computer vision research- **Teaching Materials**: Create labeled examples for students- **Accessibility**: Generate descriptions for visually impaired users- **Documentation**: Auto-generate figure descriptions
---
## β οΈ Important Notes
### Performance- Processing time depends on image count and size- Batch processing is more efficient than individual labeling- Large datasets may take several minutes to process
### Privacy- Images are processed locally on your machine- No data is sent to external servers during processing- Downloaded datasets contain only your images and labels
### Limitations- Very large images (>10MB) may take longer to process- Complex images with multiple objects may need manual refinement- AI accuracy varies with image quality and complexity
---
## π Troubleshooting
### Common Issues
**Images not uploading?**- Check file format compatibility- Ensure files aren't corrupted- Try smaller batches first
**Labels seem inaccurate?**- Improve image quality and lighting- Edit labels manually after generation- Use consistent image style for better results
**Download not working?**- Ensure you have labeled images first- Check available disk space- Try both folder organization options
**Performance slow?**- Close other applications- Use smaller image batches- Consider image size optimization
### Getting Help- Check image formats and sizes- Ensure stable internet connection for model loading- Restart the application if issues persist
---
## π Ready to Start!
1. **Upload** your images using the π button2. **Generate** labels individually or in batch3. **Review** and edit as needed4. **Download** your labeled dataset
Happy labeling! π"""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109import tempfileimport zipfilefrom typing import Optionalfrom pathlib import Path
from dataset import ImageDataset
def create_dataset_zip( dataset: ImageDataset, organize_in_folders: bool = True) -> Optional[str]: """Create a zip file containing images and their text labels.
Args: dataset: ImageDataset containing images with labels organize_in_folders: If True, puts images in 'images/' folder and texts in 'labels/' folder. If False, puts all files in the root folder.
Returns: str: Path to the created zip file, or None if dataset is empty """ if not dataset.images: return None
# Create a temporary file temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".zip") temp_path = temp_file.name temp_file.close()
try: with zipfile.ZipFile(temp_path, "w", zipfile.ZIP_DEFLATED) as zip_file: for image_data in dataset.images: image_path = image_data["path"] label = image_data["label"]
try: # Determine file paths based on organization option image_filename = Path(image_path).name base_name = Path(image_path).stem text_filename = f"{base_name}.txt"
if organize_in_folders: image_zip_path = f"images/{image_filename}" text_zip_path = f"labels/{text_filename}" else: image_zip_path = image_filename text_zip_path = text_filename
# Add the image file to zip with open(image_path, "rb") as img_file: zip_file.writestr(image_zip_path, img_file.read())
# Create and add the text file zip_file.writestr(text_zip_path, label.encode("utf-8"))
except FileNotFoundError: # Skip if image file doesn't exist continue except Exception as e: # Log error but continue with other files print(f"Error processing {image_path}: {e}") continue
return temp_path
except Exception as e: # Clean up temp file if creation failed Path(temp_path).unlink(missing_ok=True) print(f"Error creating zip file: {e}") return None
# Create a temporary file temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".zip") temp_path = temp_file.name temp_file.close()
try: with zipfile.ZipFile(temp_path, "w", zipfile.ZIP_DEFLATED) as zip_file: for image_data in dataset.images: image_path = image_data["path"] label = image_data["label"]
try: # Add the image file to zip with open(image_path, "rb") as img_file: zip_file.writestr( f"images/{Path(image_path).name}", img_file.read() )
# Create and add the text file with the same base name base_name = Path(image_path).stem text_filename = f"labels/{base_name}.txt" zip_file.writestr(text_filename, label.encode("utf-8"))
except FileNotFoundError: # Skip if image file doesn't exist continue except Exception as e: # Log error but continue with other files print(f"Error processing {image_path}: {e}") continue
return temp_path
except Exception as e: # Clean up temp file if creation failed Path(temp_path).unlink(missing_ok=True) print(f"Error creating zip file: {e}") return None.gitignoreAdded+6
app.py+171-92
dataset.py+2
documentation.pyAdded+217
packager.pyAdded+109