-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2085 lines (1707 loc) · 74.9 KB
/
app.py
File metadata and controls
2085 lines (1707 loc) · 74.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
LabelMate - AI-Powered Data Labeling Assistant
Main Streamlit Application
A production-ready tool for data teams to accelerate annotation workflows.
Run: streamlit run app.py
Author: @swamy18
Repository: https://github.com/swamy18/labelmate
"""
import streamlit as st
import pandas as pd
import os
import json
import time
from pathlib import Path
from PIL import Image
from typing import Dict, List, Optional
import plotly.express as px
import plotly.graph_objects as go
# Import our custom modules
from utils.text_helper import (
load_text_csv, suggest_text_label, save_text_csv,
get_labeling_stats
)
from utils.image_helper import (
suggest_image_labels, process_uploaded_images, export_image_labels
)
from utils.charts import (
display_progress_metrics, animated_progress_bar,
label_distribution_chart, ai_vs_human_comparison,
export_analytics_summary
)
# =============================================================================
# PAGE CONFIGURATION AND STYLING
# =============================================================================
st.set_page_config(
page_title="LabelMate - AI Data Labeling",
page_icon="🏷️",
layout="wide",
initial_sidebar_state="expanded",
menu_items={
'Get Help': 'https://github.com/swamy18/labelmate/wiki',
'Report a bug': 'https://github.com/swamy18/labelmate/issues',
'About': 'LabelMate v1.0 - AI-Powered Data Labeling Assistant'
}
)
# Custom CSS for professional styling
st.markdown("""
<style>
/* Main header styling */
.main-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 2rem;
border-radius: 15px;
margin-bottom: 2rem;
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}
.main-header h1 {
color: white;
margin: 0;
text-align: center;
font-size: 2.5rem;
font-weight: 700;
}
.subtitle {
color: #666;
text-align: center;
font-size: 1.2rem;
margin-bottom: 2rem;
font-style: italic;
}
/* Status indicators */
.success-box {
background: linear-gradient(90deg, #d4edda 0%, #c3e6cb 100%);
border: 1px solid #28a745;
border-radius: 8px;
padding: 1rem;
margin: 1rem 0;
}
.warning-box {
background: linear-gradient(90deg, #fff3cd 0%, #ffeaa7 100%);
border: 1px solid #ffc107;
border-radius: 8px;
padding: 1rem;
margin: 1rem 0;
}
.error-box {
background: linear-gradient(90deg, #f8d7da 0%, #f5c6cb 100%);
border: 1px solid #dc3545;
border-radius: 8px;
padding: 1rem;
margin: 1rem 0;
}
/* Cards and containers */
.metric-card {
background: white;
padding: 1.5rem;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
border: 1px solid #e1e8ed;
margin: 0.5rem 0;
}
.labeling-container {
background: #f8f9fa;
padding: 1.5rem;
border-radius: 10px;
margin: 1rem 0;
border: 1px solid #dee2e6;
}
/* Progress indicators */
.progress-container {
background: white;
padding: 1rem;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
margin: 1rem 0;
}
/* Button enhancements */
.stButton > button {
border-radius: 8px;
font-weight: 600;
transition: all 0.3s ease;
}
.stButton > button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
/* Responsive design */
@media (max-width: 768px) {
.main-header h1 {
font-size: 2rem;
}
.main-header {
padding: 1rem;
}
}
/* Animation for loading states */
@keyframes pulse {
0% { opacity: 1; }
50% { opacity: 0.5; }
100% { opacity: 1; }
}
.loading {
animation: pulse 2s infinite;
}
</style>
""", unsafe_allow_html=True)
# =============================================================================
# UTILITY FUNCTIONS
# =============================================================================
def create_directories():
"""Ensure required directories exist"""
for dir_name in ["data", "data/temp_images", "exports"]:
Path(dir_name).mkdir(parents=True, exist_ok=True)
def display_api_status():
"""Display API configuration status in sidebar"""
st.sidebar.markdown("### 🔑 API Configuration")
gemini_key = os.getenv("GOOGLE_API_KEY")
openai_key = os.getenv("OPENAI_API_KEY")
if gemini_key:
st.sidebar.success("✅ Gemini API configured")
st.sidebar.caption("🤖 Text + Image labeling available")
elif openai_key:
st.sidebar.success("✅ OpenAI API configured")
st.sidebar.caption("📝 Text labeling only")
else:
st.sidebar.error("❌ No API key configured")
st.sidebar.info("💡 Add GOOGLE_API_KEY or OPENAI_API_KEY to your .env file")
with st.sidebar.expander("🔧 Setup Instructions"):
st.markdown("""
1. Get a free API key:
- [Gemini AI](https://makersuite.google.com/app/apikey) (Recommended)
- [OpenAI](https://platform.openai.com/api-keys)
2. Create a `.env` file in the project root:
```
GOOGLE_API_KEY=your_key_here
```
3. Restart the application
""")
def show_welcome_message():
"""Display welcome message for new users"""
if "welcome_shown" not in st.session_state:
st.info("""
👋 **Welcome to LabelMate!**
This AI-powered tool helps you label text and images efficiently:
- Upload your data (CSV for text, images for vision tasks)
- Get AI suggestions instantly
- Review and correct labels easily
- Export high-quality labeled datasets
Choose a mode from the sidebar to get started!
""")
st.session_state.welcome_shown = True
def initialize_session_state():
"""Initialize all session state variables"""
if "text_df" not in st.session_state:
st.session_state.text_df = pd.DataFrame()
if "processed_images" not in st.session_state:
st.session_state.processed_images = {}
if "labeling_task" not in st.session_state:
st.session_state.labeling_task = "sentiment"
if "current_page" not in st.session_state:
st.session_state.current_page = 0
if "auto_save" not in st.session_state:
st.session_state.auto_save = True
# =============================================================================
# MAIN APPLICATION HEADER
# =============================================================================
def render_header():
"""Render the main application header"""
st.markdown("""
<div class="main-header">
<h1>🏷️ LabelMate</h1>
<p style="color: white; text-align: center; margin: 0; font-size: 1.1rem;">
AI-Powered Data Labeling Assistant
</p>
</div>
""", unsafe_allow_html=True)
st.markdown("""
<p class="subtitle">
Accelerate your data annotation workflow with intelligent AI assistance
</p>
""", unsafe_allow_html=True)
# =============================================================================
# SIDEBAR NAVIGATION
# =============================================================================
def render_sidebar():
"""Render sidebar navigation and controls"""
st.sidebar.title("🎛️ Control Panel")
st.sidebar.markdown("---")
# Mode selection
mode = st.sidebar.selectbox(
"📋 Select Mode",
["📄 Text Labeling", "🖼️ Image Labeling", "📊 Analytics Dashboard"],
help="Choose the type of data labeling task"
)
st.sidebar.markdown("---")
# API status
display_api_status()
st.sidebar.markdown("---")
# Settings section
with st.sidebar.expander("⚙️ Settings"):
auto_save = st.checkbox(
"Auto-save progress",
value=st.session_state.get("auto_save", True),
help="Automatically save your progress"
)
st.session_state.auto_save = auto_save
show_advanced = st.checkbox(
"Show advanced options",
value=False,
help="Display advanced configuration options"
)
# Quick stats
if not st.session_state.text_df.empty or st.session_state.processed_images:
st.sidebar.markdown("---")
st.sidebar.markdown("### 📈 Quick Stats")
if not st.session_state.text_df.empty:
text_stats = get_labeling_stats(st.session_state.text_df)
st.sidebar.metric("Text Items", text_stats["total"])
st.sidebar.metric("Text Progress", f"{text_stats['progress']:.1f}%")
if st.session_state.processed_images:
img_total = len(st.session_state.processed_images)
img_labeled = sum(1 for data in st.session_state.processed_images.values()
if data["selected_label"] != "unknown")
img_progress = (img_labeled / max(img_total, 1)) * 100
st.sidebar.metric("Image Items", img_total)
st.sidebar.metric("Image Progress", f"{img_progress:.1f}%")
# Help section
st.sidebar.markdown("---")
with st.sidebar.expander("📚 Quick Help"):
st.markdown("""
**Text Labeling:**
- Upload CSV with 'text' column
- Choose sentiment or topic task
- Review AI suggestions
- Export labeled results
**Image Labeling:**
- Upload JPG/PNG files
- Get AI label suggestions
- Select or customize labels
- Export filename-label mapping
**Analytics:**
- View progress metrics
- Analyze AI performance
- Export comprehensive reports
""")
return mode
# =============================================================================
# TEXT LABELING MODE
# =============================================================================
def render_text_labeling_mode():
"""Render the complete text labeling interface"""
st.header("📄 Text Data Labeling")
# Configuration section
col1, col2, col3 = st.columns([2, 2, 1])
with col1:
task = st.selectbox(
"🎯 Labeling Task",
["sentiment", "topic"],
index=0 if st.session_state.labeling_task == "sentiment" else 1,
help="Choose the type of text classification"
)
st.session_state.labeling_task = task
with col2:
batch_size = st.number_input(
"🔢 Batch Size",
min_value=1, max_value=100, value=10,
help="Number of items to process at once"
)
with col3:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("🔄 Reset Data", help="Clear all data and start over"):
st.session_state.text_df = pd.DataFrame()
st.success("✅ Data reset successfully!")
st.rerun()
# File upload section
st.subheader("📤 Upload Your Data")
uploaded_file = st.file_uploader(
"Choose a CSV file",
type=["csv"],
help="Your CSV file must contain a 'text' column with the data to label"
)
# Sample data option
col1, col2 = st.columns([1, 1])
with col1:
if st.button("🧪 Load Sample Data", help="Try with sample text data"):
sample_texts = [
"I absolutely love this product! It's amazing!",
"Terrible experience. Would not recommend.",
"It's okay, nothing special but does the job.",
"Best purchase I've made this year!",
"Could be better, but it's acceptable.",
"Waste of money. Very disappointed.",
"Pretty good overall, happy with it.",
"Not great, not terrible. Average quality.",
"Excellent quality and fast shipping!",
"Poor customer service experience.",
"The new update broke everything!",
"Works perfectly as described.",
"Overpriced for what you get.",
"Great value for money!",
"Customer support was very helpful.",
"Delivery was delayed twice.",
"Exactly what I was looking for.",
"Quality could be much better.",
"Impressed with the quick response.",
"Would definitely buy again!"
]
sample_df = pd.DataFrame({
"text": sample_texts,
"label": [""] * len(sample_texts),
"ai_suggested": [""] * len(sample_texts),
"human_changed": [False] * len(sample_texts)
})
st.session_state.text_df = sample_df
st.success("✅ Sample data loaded! 20 texts ready for labeling.")
st.rerun()
# Process uploaded file
if uploaded_file is not None:
try:
with st.spinner("📖 Loading and validating your data..."):
df = load_text_csv(uploaded_file)
st.session_state.text_df = df.copy()
st.success(f"✅ Successfully loaded {len(df)} text samples!")
except Exception as e:
st.error(f"❌ Error loading file: {str(e)}")
return
# Main interface - only show if we have data
if not st.session_state.text_df.empty:
df = st.session_state.text_df
# Data preview section
with st.expander("👀 Data Preview & Statistics", expanded=True):
col1, col2 = st.columns([2, 1])
with col1:
st.dataframe(
df.head(10)[["text", "label", "ai_suggested", "human_changed"]],
use_container_width=True,
height=300
)
with col2:
stats = get_labeling_stats(df)
st.metric("Total Texts", stats["total"])
st.metric("Labeled", f"{stats['labeled']} ({stats['progress']:.1f}%)")
st.metric("AI Generated", stats["ai_generated"])
st.metric("Human Edited", stats["human_changed"])
if stats["ai_generated"] > 0:
accuracy = stats["accuracy"]
st.metric("AI Accuracy", f"{accuracy:.1f}%")
# AI batch labeling section
st.subheader("🤖 AI Batch Labeling")
unlabeled_count = (df["label"] == "").sum()
if unlabeled_count > 0:
col1, col2, col3, col4 = st.columns([2, 1, 1, 1])
with col1:
st.info(f"📝 {unlabeled_count} items need labeling")
with col2:
if st.button("🚀 Label All", type="primary"):
label_all_texts(df, task)
with col3:
sample_size = min(5, unlabeled_count)
if st.button(f"🧪 Label {sample_size}"):
label_sample_texts(df, task, sample_size)
with col4:
if st.button("⚡ Label Batch"):
label_batch_texts(df, task, batch_size)
else:
st.success("🎉 All texts have been labeled!")
# Progress visualization
st.subheader("📊 Progress Dashboard")
stats = get_labeling_stats(df)
display_progress_metrics(stats)
animated_progress_bar(stats["labeled"], stats["total"], "Labeling Progress")
# Interactive labeling section
st.subheader("✏️ Review & Correct Labels")
render_text_review_interface(df, task)
# Visualization section
col1, col2 = st.columns([1, 1])
with col1:
label_distribution_chart(df, "label", "Current Label Distribution")
with col2:
ai_vs_human_comparison(df)
# Export section
render_text_export_section(df, task)
def label_all_texts(df, task):
"""Label all unlabeled texts with AI"""
progress_placeholder = st.empty()
status_placeholder = st.empty()
unlabeled_mask = df["label"] == ""
unlabeled_indices = df[unlabeled_mask].index.tolist()
if not unlabeled_indices:
st.warning("No unlabeled texts found!")
return
progress_bar = progress_placeholder.progress(0)
for i, idx in enumerate(unlabeled_indices):
# Update progress
progress = (i + 1) / len(unlabeled_indices)
progress_bar.progress(progress)
# Show current item
current_text = df.at[idx, "text"]
status_placeholder.text(f"Processing {i+1}/{len(unlabeled_indices)}: {current_text[:50]}...")
# Get AI suggestion
suggestion = suggest_text_label(current_text, task)
df.at[idx, "ai_suggested"] = suggestion
df.at[idx, "label"] = suggestion
# Auto-save progress periodically
if st.session_state.auto_save and (i + 1) % 10 == 0:
st.session_state.text_df = df.copy()
st.session_state.text_df = df.copy()
progress_placeholder.empty()
status_placeholder.empty()
st.success(f"🎉 Successfully labeled {len(unlabeled_indices)} texts!")
st.rerun()
def label_sample_texts(df, task, sample_size):
"""Label a small sample of texts"""
with st.spinner(f"🤖 Labeling {sample_size} samples..."):
unlabeled_mask = df["label"] == ""
sample_indices = df[unlabeled_mask].head(sample_size).index
for idx in sample_indices:
suggestion = suggest_text_label(df.at[idx, "text"], task)
df.at[idx, "ai_suggested"] = suggestion
df.at[idx, "label"] = suggestion
st.session_state.text_df = df.copy()
st.success(f"✅ Labeled {len(sample_indices)} samples!")
st.rerun()
def label_batch_texts(df, task, batch_size):
"""Label a specific batch of texts"""
unlabeled_mask = df["label"] == ""
batch_indices = df[unlabeled_mask].head(batch_size).index
if len(batch_indices) == 0:
st.warning("No unlabeled texts found!")
return
progress_placeholder = st.empty()
progress_bar = progress_placeholder.progress(0)
for i, idx in enumerate(batch_indices):
progress = (i + 1) / len(batch_indices)
progress_bar.progress(progress)
suggestion = suggest_text_label(df.at[idx, "text"], task)
df.at[idx, "ai_suggested"] = suggestion
df.at[idx, "label"] = suggestion
st.session_state.text_df = df.copy()
progress_placeholder.empty()
st.success(f"✅ Processed batch of {len(batch_indices)} texts!")
st.rerun()
def render_text_review_interface(df, task):
"""Render the text review and correction interface"""
# Filter and pagination controls
col1, col2, col3 = st.columns([2, 1, 1])
with col1:
filter_option = st.selectbox(
"🔍 Filter items:",
["All items", "Unlabeled only", "AI labeled only", "Human modified only", "Need review"]
)
with col2:
items_per_page = st.selectbox("📄 Items per page:", [5, 10, 20, 50], index=1)
with col3:
sort_option = st.selectbox("📊 Sort by:", ["Original order", "Text length", "Confidence"])
# Apply filters
filtered_df = apply_text_filters(df, filter_option)
if filtered_df.empty:
st.info(f"🔍 No items match the filter: {filter_option}")
return
# Apply sorting
if sort_option == "Text length":
filtered_df = filtered_df.copy()
filtered_df["text_length"] = filtered_df["text"].str.len()
filtered_df = filtered_df.sort_values("text_length", ascending=False)
# Pagination
total_items = len(filtered_df)
total_pages = (total_items + items_per_page - 1) // items_per_page
if total_pages > 1:
page = st.selectbox(f"📖 Page (1-{total_pages}):", range(1, total_pages + 1)) - 1
st.session_state.current_page = page
else:
page = 0
start_idx = page * items_per_page
end_idx = min(start_idx + items_per_page, total_items)
page_df = filtered_df.iloc[start_idx:end_idx]
# Review interface
st.markdown(f"**Showing items {start_idx + 1}-{end_idx} of {total_items}**")
for i, (idx, row) in enumerate(page_df.iterrows()):
render_single_text_review(idx, row, task, i + start_idx)
# Navigation buttons for pagination
if total_pages > 1:
col1, col2, col3 = st.columns([1, 2, 1])
with col1:
if page > 0 and st.button("⬅️ Previous Page"):
st.session_state.current_page = page - 1
st.rerun()
with col3:
if page < total_pages - 1 and st.button("➡️ Next Page"):
st.session_state.current_page = page + 1
st.rerun()
def apply_text_filters(df, filter_option):
"""Apply selected filter to the dataframe"""
if filter_option == "Unlabeled only":
return df[df["label"] == ""]
elif filter_option == "AI labeled only":
return df[(df["ai_suggested"] != "") & (~df["human_changed"])]
elif filter_option == "Human modified only":
return df[df["human_changed"]]
elif filter_option == "Need review":
# Items where AI suggestion differs significantly or low confidence
return df[(df["ai_suggested"] != "") & (df["label"] == "")]
else:
return df
def render_single_text_review(idx, row, task, display_idx):
"""Render a single text item for review"""
with st.container():
# Create a bordered container
st.markdown(f"""
<div class="labeling-container" style="margin: 1rem 0;">
</div>
""", unsafe_allow_html=True)
col1, col2, col3 = st.columns([3, 1, 1])
with col1:
# Display text with character limit
text_preview = row["text"]
if len(text_preview) > 200:
text_preview = text_preview[:200] + "..."
st.markdown(f"**Text #{display_idx + 1}:**")
st.write(text_preview)
# Show AI suggestion if available
if row["ai_suggested"]:
confidence_emoji = "🎯" if not row["human_changed"] else "✏️"
st.caption(f"{confidence_emoji} AI suggested: **{row['ai_suggested']}**")
# Show modification status
if row["human_changed"]:
st.caption("✏️ *Human modified*")
with col2:
# Label selection
if task == "sentiment":
label_options = ["", "Positive", "Negative", "Neutral"]
else: # topic
label_options = ["", "Technology", "Business", "Politics", "Sports",
"Entertainment", "Health", "Education", "Other"]
current_label = row["label"]
if current_label not in label_options:
label_options.append(current_label)
new_label = st.selectbox(
"Label:",
label_options,
index=label_options.index(current_label) if current_label in label_options else 0,
key=f"label_{idx}_{display_idx}"
)
# Update dataframe if label changed
if new_label != current_label:
df = st.session_state.text_df
df.at[idx, "label"] = new_label
# Mark as human changed if different from AI suggestion
if row["ai_suggested"] and new_label != row["ai_suggested"]:
df.at[idx, "human_changed"] = True
st.session_state.text_df = df.copy()
# Auto-save if enabled
if st.session_state.auto_save:
save_text_csv(df, f"auto_save_{task}.csv")
with col3:
# Action buttons
if st.button("👁️ Full Text", key=f"view_{idx}_{display_idx}"):
st.info(f"**Complete Text:**\n\n{row['text']}")
# Quick label buttons for common cases
if task == "sentiment" and not row["label"]:
quick_col1, quick_col2 = st.columns(2)
with quick_col1:
if st.button("👍", key=f"pos_{idx}_{display_idx}", help="Mark as Positive"):
update_text_label(idx, "Positive", row)
with quick_col2:
if st.button("👎", key=f"neg_{idx}_{display_idx}", help="Mark as Negative"):
update_text_label(idx, "Negative", row)
st.markdown("---")
def update_text_label(idx, new_label, row):
"""Update a text label and handle change tracking"""
df = st.session_state.text_df
df.at[idx, "label"] = new_label
if row["ai_suggested"] and new_label != row["ai_suggested"]:
df.at[idx, "human_changed"] = True
st.session_state.text_df = df.copy()
st.rerun()
def render_text_export_section(df, task):
"""Render the export section for text labeling"""
st.subheader("📥 Export Results")
# Export statistics
stats = get_labeling_stats(df)
col1, col2, col3, col4 = st.columns([1, 1, 1, 1])
with col1:
if st.button("💾 Save Progress", type="primary"):
filepath = save_text_csv(df, f"labeled_text_{task}.csv")
st.success(f"✅ Saved to {filepath}")
with col2:
# Download CSV
csv_data = df.to_csv(index=False)
st.download_button(
label="⬇️ Download CSV",
data=csv_data,
file_name=f"labeled_text_{task}_{pd.Timestamp.now().strftime('%Y%m%d_%H%M%S')}.csv",
mime="text/csv"
)
with col3:
# Download only labeled items
labeled_df = df[df["label"] != ""]
if not labeled_df.empty:
labeled_csv = labeled_df.to_csv(index=False)
st.download_button(
label="📋 Labeled Only",
data=labeled_csv,
file_name=f"completed_labels_{task}.csv",
mime="text/csv"
)
else:
st.button("📋 Labeled Only", disabled=True, help="No labeled items yet")
with col4:
if st.button("📈 Export Analytics"):
analytics_path = export_analytics_summary(df, stats)
st.success(f"✅ Analytics saved to {analytics_path}")
# Export summary
if stats["labeled"] > 0:
with st.expander("📊 Export Summary"):
st.write(f"**Ready to export:**")
st.write(f"- Total items: {stats['total']}")
st.write(f"- Labeled items: {stats['labeled']} ({stats['progress']:.1f}%)")
st.write(f"- AI generated: {stats['ai_generated']}")
st.write(f"- Human modified: {stats['human_changed']}")
if stats['ai_generated'] > 0:
st.write(f"- AI accuracy: {stats['accuracy']:.1f}%")
# Label distribution
label_counts = df["label"].value_counts()
if not label_counts.empty:
st.write("**Label distribution:**")
for label, count in label_counts.items():
if label: # Skip empty labels
st.write(f" - {label}: {count} ({count/stats['labeled']*100:.1f}%)")
# =============================================================================
# IMAGE LABELING MODE
# =============================================================================
def render_image_labeling_mode():
"""Render the complete image labeling interface"""
st.header("🖼️ Image Data Labeling")
# Configuration section
col1, col2, col3 = st.columns([2, 2, 1])
with col1:
num_suggestions = st.slider(
"🎯 AI suggestions per image",
min_value=1, max_value=5, value=3,
help="Number of label suggestions from AI"
)
with col2:
display_mode = st.selectbox(
"👁️ Display Mode",
["Grid View", "List View", "Single Image"],
help="Choose how to display images for labeling"
)
with col3:
st.markdown("<br>", unsafe_allow_html=True)
if st.button("🔄 Reset Images", help="Clear all image data"):
st.session_state.processed_images = {}
# Clean up temp directory
import shutil
temp_dir = Path("data/temp_images")
if temp_dir.exists():
shutil.rmtree(temp_dir)
temp_dir.mkdir(parents=True, exist_ok=True)
st.success("✅ Image data reset!")
st.rerun()
# File upload section
st.subheader("📤 Upload Your Images")
uploaded_files = st.file_uploader(
"Choose image files",
type=["png", "jpg", "jpeg", "webp", "bmp"],
accept_multiple_files=True,
help="Upload one or more images to label"
)
# Sample images option
if st.button("🧪 Use Sample Images", help="Try with sample images"):
st.info("📝 For demo purposes, upload your own images or use the sample data folder")
# Process uploaded images
if uploaded_files:
# Check if we need to reprocess images
current_file_names = {f.name for f in uploaded_files}
stored_file_names = set(st.session_state.processed_images.keys())
if current_file_names != stored_file_names:
with st.spinner("🖼️ Processing images..."):
st.session_state.processed_images = process_uploaded_images(uploaded_files)
processed_images = st.session_state.processed_images
if processed_images:
st.success(f"✅ Processed {len(processed_images)} images")
# Progress tracking
total_images = len(processed_images)
labeled_images = sum(1 for data in processed_images.values()
if data["selected_label"] != "unknown")
# Progress metrics
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("📷 Total Images", total_images)
with col2:
st.metric("✅ Labeled", labeled_images)
with col3:
progress_pct = (labeled_images / max(total_images, 1)) * 100
st.metric("📊 Progress", f"{progress_pct:.1f}%")
with col4:
human_modified = sum(1 for data in processed_images.values()
if data.get("human_changed", False))
st.metric("✏️ Modified", human_modified)
animated_progress_bar(labeled_images, total_images, "Image Labeling Progress")
# Render the appropriate display mode
if display_mode == "Grid View":
render_grid_view(processed_images, num_suggestions)
elif display_mode == "List View":
render_list_view(processed_images, num_suggestions)
else: # Single Image
render_single_image_view(processed_images, num_suggestions)
# Label distribution chart
render_image_analytics(processed_images)
# Export section
render_image_export_section(processed_images)
def render_grid_view(processed_images, num_suggestions):
"""Render images in a grid layout"""
st.subheader("🔲 Grid View - Quick Labeling")
# Create grid layout
cols_per_row = 3
image_items = list(processed_images.items())
for i in range(0, len(image_items), cols_per_row):
cols = st.columns(cols_per_row)
for j, (img_name, img_data) in enumerate(image_items[i:i+cols_per_row]):
with cols[j]:
# Display image
st.image(img_data["image"], caption=img_name, width=200)
# Current selection status
current_label = img_data["selected_label"]
if current_label != "unknown":
status_color = "🟢" if not img_data.get("human_changed", False) else "🟡"
st.caption(f"{status_color} **{current_label}**")
else:
st.caption("🔴 **Unlabeled**")
# Label selection
suggestions = img_data["suggested_labels"]
label_options = suggestions + ["Custom"]
try:
default_index = suggestions.index(current_label) if current_label in suggestions else 0
except ValueError:
default_index = len(suggestions) # Custom option
selected_label = st.selectbox(
f"Label for {img_name}:",
label_options,
index=default_index,
key=f"grid_{img_name}_{i}_{j}"
)
# Handle custom label
if selected_label == "Custom":
custom_label = st.text_input(
"Custom label:",
value=current_label if current_label not in suggestions else "",
key=f"custom_grid_{img_name}_{i}_{j}",
placeholder="Enter custom label"
)
if custom_label:
selected_label = custom_label
# Update if changed
if selected_label != current_label and selected_label != "Custom":
processed_images[img_name]["selected_label"] = selected_label
processed_images[img_name]["human_changed"] = selected_label != suggestions[0]
st.session_state.processed_images = processed_images
# Auto-save if enabled
if st.session_state.auto_save:
export_image_labels(processed_images, "auto_save_images.csv")
def render_list_view(processed_images, num_suggestions):
"""Render images in a detailed list view"""
st.subheader("📋 List View - Detailed Review")
for img_name, img_data in processed_images.items():
with st.expander(f"📷 {img_name}", expanded=False):
col1, col2 = st.columns([1, 2])
with col1:
st.image(img_data["image"], width=300)
# Image info
img = img_data["image"]