-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLabelNavigationView.swift
More file actions
599 lines (524 loc) · 19.1 KB
/
Copy pathLabelNavigationView.swift
File metadata and controls
599 lines (524 loc) · 19.1 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
// LabelNavigationView.swift
// Redesigned Label tab with New/Resume/Camera options
import SwiftUI
import PhotosUI
struct LabelNavigationView: View {
@Binding var selectedTab: Int
@EnvironmentObject private var datasetManager: DatasetManager
@StateObject private var qualityManager = DataQualityManager()
@StateObject private var sessionManager = SessionManager()
// Navigation state
@State private var showImagePicker = false
@State private var showCamera = false
@State private var labelImages: [UIImage]?
@State private var activeSession: LabelingSession?
var body: some View {
NavigationStack {
ScrollView {
VStack(spacing: 24) {
// Header
headerSection
// Quick Actions
quickActionsSection
// Resume Section (if incomplete sessions exist)
if !sessionManager.incompleteSessions.isEmpty {
resumeSection
}
// Recent Sessions
if !sessionManager.recentSessions.filter({ $0.isCompleted }).isEmpty {
recentSessionsSection
}
}
.padding()
}
.background(ThemedBackground(theme: .label))
.navigationTitle("Label")
.navigationBarTitleDisplayMode(.large)
.task {
sessionManager.refresh()
}
.sheet(isPresented: $showImagePicker) {
ImageSelectorView { images in
showImagePicker = false
if let images, !images.isEmpty {
startNewSession(with: images)
}
}
}
.fullScreenCover(isPresented: $showCamera) {
CameraView { image in
showCamera = false
if let image {
startNewSession(with: [image])
}
}
}
.fullScreenCover(isPresented: Binding(
get: { labelImages != nil },
set: { if !$0 { labelImages = nil } }
)) {
if let images = labelImages {
LabelingFlowView(
images: images,
session: activeSession,
sessionManager: sessionManager,
qualityManager: qualityManager,
onComplete: {
labelImages = nil
activeSession = nil
sessionManager.completeSession()
selectedTab = 1 // Go to Dataset
Task {
await datasetManager.loadDataset()
}
},
onSaveProgress: {
labelImages = nil
activeSession = nil
ToastManager.shared.showSuccess("Session saved", message: "You can resume anytime")
}
)
}
}
}
.withToasts()
}
// MARK: - Header
private var headerSection: some View {
GradientHeaderCard(
title: "Label Objects",
subtitle: "Tap an object to teach the AI what it is",
icon: "tag.fill",
gradient: TabTheme.label.headerGradient
)
}
// MARK: - Quick Actions
private var quickActionsSection: some View {
VStack(spacing: 12) {
// Camera Button
ActionCard(
icon: "camera.fill",
title: "Take Photo",
subtitle: "Use camera to capture objects",
color: .appBlue
) {
showCamera = true
}
// Photo Library Button
ActionCard(
icon: "photo.on.rectangle.angled",
title: "Choose from Library",
subtitle: "Select multiple photos to label",
color: .appGreen
) {
showImagePicker = true
}
}
}
// MARK: - Resume Section
private var resumeSection: some View {
VStack(alignment: .leading, spacing: 12) {
HStack {
Image(systemName: "clock.arrow.circlepath")
.font(.headline)
.foregroundStyle(
LinearGradient(colors: [.appOrange, .appPink], startPoint: .leading, endPoint: .trailing)
)
Text("Continue Where You Left Off")
.font(.headline)
.foregroundColor(.primary)
}
ForEach(sessionManager.incompleteSessions) { session in
ResumeSessionCard(session: session) {
resumeSession(session)
} onDelete: {
sessionManager.deleteSession(session)
}
}
}
.padding()
.background(
RoundedRectangle(cornerRadius: 16)
.fill(Color(.systemBackground))
.overlay(
RoundedRectangle(cornerRadius: 16)
.fill(Color.appOrange.opacity(0.05))
)
.shadow(color: .black.opacity(0.06), radius: 10, y: 4)
)
}
// MARK: - Recent Sessions
private var recentSessionsSection: some View {
VStack(alignment: .leading, spacing: 12) {
HStack {
Image(systemName: "clock")
.foregroundStyle(
LinearGradient(colors: [.appPurple, .appBlue], startPoint: .leading, endPoint: .trailing)
)
Text("Recent Sessions")
.font(.headline)
}
ForEach(sessionManager.recentSessions.filter { $0.isCompleted }.prefix(3)) { session in
RecentSessionRow(session: session) {
sessionManager.deleteSession(session)
}
}
}
.padding()
.background(
RoundedRectangle(cornerRadius: 16)
.fill(Color(.systemBackground))
.overlay(
RoundedRectangle(cornerRadius: 16)
.fill(Color.appPurple.opacity(0.03))
)
.shadow(color: .black.opacity(0.06), radius: 10, y: 4)
)
}
// MARK: - Actions
private func startNewSession(with images: [UIImage]) {
let session = sessionManager.createSession(from: images)
activeSession = session
labelImages = images
}
private func resumeSession(_ session: LabelingSession) {
sessionManager.resumeSession(session)
activeSession = session
// Load images from session
var images: [UIImage] = []
for data in session.cameraImageData {
if let image = UIImage(data: data) {
images.append(image)
}
}
if images.isEmpty {
ToastManager.shared.showError("Session corrupted", message: "Could not load images")
sessionManager.deleteSession(session)
return
}
labelImages = images
}
}
// MARK: - Action Button
struct ActionButton: View {
let title: String
let subtitle: String
let icon: String
let color: Color
let action: () -> Void
var body: some View {
Button(action: action) {
HStack(spacing: 16) {
Image(systemName: icon)
.font(.title2)
.foregroundColor(.white)
.frame(width: 50, height: 50)
.background(color)
.cornerRadius(12)
VStack(alignment: .leading, spacing: 2) {
Text(title)
.font(.headline)
.foregroundColor(.primary)
Text(subtitle)
.font(.caption)
.foregroundColor(.secondary)
}
Spacer()
Image(systemName: "chevron.right")
.foregroundColor(.secondary)
}
.padding()
.background(Color(.systemBackground))
.cornerRadius(16)
.shadow(color: .black.opacity(0.05), radius: 5)
}
.buttonStyle(.plain)
}
}
// MARK: - Resume Session Card
struct ResumeSessionCard: View {
let session: LabelingSession
let onResume: () -> Void
let onDelete: () -> Void
@State private var showingDeleteConfirm = false
var body: some View {
HStack(spacing: 12) {
ZStack {
Circle()
.stroke(Color.gray.opacity(0.2), lineWidth: 4)
.frame(width: 44, height: 44)
Circle()
.trim(from: 0, to: session.progress)
.stroke(Color.orange, style: StrokeStyle(lineWidth: 4, lineCap: .round))
.frame(width: 44, height: 44)
.rotationEffect(.degrees(-90))
Text("\(Int(session.progress * 100))%")
.font(.caption2)
.fontWeight(.bold)
}
VStack(alignment: .leading, spacing: 2) {
Text(session.displayName)
.font(.subheadline)
.fontWeight(.medium)
Text("\(session.remainingImages) images remaining")
.font(.caption)
.foregroundColor(.secondary)
}
Spacer()
Button("Resume") {
onResume()
}
.buttonStyle(.borderedProminent)
.controlSize(.small)
Button {
showingDeleteConfirm = true
} label: {
Image(systemName: "trash")
.font(.subheadline)
.foregroundColor(.secondary)
.frame(width: 32, height: 32)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.accessibilityLabel("Delete session")
}
.padding()
.background(Color.orange.opacity(0.1))
.cornerRadius(12)
.confirmationDialog(
"Delete \"\(session.displayName)\"?",
isPresented: $showingDeleteConfirm,
titleVisibility: .visible
) {
Button("Delete", role: .destructive) { onDelete() }
Button("Cancel", role: .cancel) {}
} message: {
Text("This session and its progress will be removed. This can't be undone.")
}
}
}
// MARK: - Recent Session Row
struct RecentSessionRow: View {
let session: LabelingSession
let onDelete: () -> Void
@State private var showingDeleteConfirm = false
var body: some View {
HStack {
Image(systemName: "checkmark.circle.fill")
.foregroundColor(.green)
VStack(alignment: .leading, spacing: 2) {
Text(session.displayName)
.font(.subheadline)
Text("\(session.totalObjectsLabeled) objects labeled")
.font(.caption)
.foregroundColor(.secondary)
}
Spacer()
Text(session.lastModifiedAt.formatted(date: .abbreviated, time: .omitted))
.font(.caption)
.foregroundColor(.secondary)
Button {
showingDeleteConfirm = true
} label: {
Image(systemName: "trash")
.font(.subheadline)
.foregroundColor(.secondary)
.frame(width: 32, height: 32)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.accessibilityLabel("Delete session")
}
.confirmationDialog(
"Delete \"\(session.displayName)\"?",
isPresented: $showingDeleteConfirm,
titleVisibility: .visible
) {
Button("Delete", role: .destructive) { onDelete() }
Button("Cancel", role: .cancel) {}
} message: {
Text("This labeled session will be removed from your history.")
}
}
}
// MARK: - Camera View
struct CameraView: UIViewControllerRepresentable {
let onComplete: (UIImage?) -> Void
func makeUIViewController(context: Context) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.sourceType = .camera
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {}
func makeCoordinator() -> Coordinator {
Coordinator(onComplete: onComplete)
}
class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let onComplete: (UIImage?) -> Void
init(onComplete: @escaping (UIImage?) -> Void) {
self.onComplete = onComplete
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
let image = info[.originalImage] as? UIImage
onComplete(image)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
onComplete(nil)
}
}
}
// MARK: - Labeling Flow View (Sequential with progress)
struct LabelingFlowView: View {
let images: [UIImage]
let session: LabelingSession?
let sessionManager: SessionManager
let qualityManager: DataQualityManager
let onComplete: () -> Void
let onSaveProgress: () -> Void
@State private var currentIndex: Int = 0
@State private var totalLabeled: Int = 0
@State private var showingExitConfirmation = false
@State private var currentBoxes: [LabeledBox] = []
@Environment(\.dismiss) private var dismiss
var body: some View {
ZStack {
// Main labeling editor — .id forces a fresh editor (and box state)
// per image so restored/in-progress boxes never bleed across photos
LabelingEditorView(
image: images[currentIndex],
onSelectNewPhoto: { },
onBrowseDataset: { },
onClose: {
advanceToNext()
},
qualityManager: qualityManager,
autoStartSegmentation: true,
onLabeledCountChanged: { count in
totalLabeled += count
},
initialBoxes: session?.loadLabeledBoxes(forImageIndex: currentIndex) ?? [],
onBoxesChanged: { boxes in
currentBoxes = boxes
}
)
.id(currentIndex)
// Progress overlay
VStack {
progressHeader
Spacer()
}
}
.onAppear {
// Resume from saved position
if let session {
currentIndex = session.currentImageIndex
totalLabeled = session.totalObjectsLabeled
}
}
.alert("Save Progress?", isPresented: $showingExitConfirmation) {
Button("Discard", role: .destructive) {
dismiss()
}
Button("Save & Exit") {
saveAndExit()
}
Button("Cancel", role: .cancel) {}
} message: {
Text("You have \(images.count - currentIndex) images remaining. Save your progress to continue later?")
}
}
private var progressHeader: some View {
HStack {
Button {
showingExitConfirmation = true
} label: {
Image(systemName: "xmark")
.font(.headline)
.foregroundColor(.white)
.padding(8)
.background(Color.black.opacity(0.5))
.clipShape(Circle())
}
Spacer()
// Progress indicator
VStack(spacing: 2) {
Text("Image \(currentIndex + 1) of \(images.count)")
.font(.caption)
.fontWeight(.medium)
.foregroundColor(.white)
Text("\(totalLabeled) objects labeled")
.font(.caption2)
.foregroundColor(.white.opacity(0.8))
}
.padding(.horizontal, 12)
.padding(.vertical, 6)
.background(Color.black.opacity(0.5))
.cornerRadius(20)
Spacer()
HStack(spacing: 8) {
// Back button (only past first image)
if currentIndex > 0 {
Button {
currentIndex -= 1
} label: {
Image(systemName: "chevron.left")
.font(.headline.bold())
.foregroundColor(.white)
.frame(width: 36, height: 36)
.background(Color.black.opacity(0.5))
.clipShape(Circle())
}
}
// Next / Done — saves progress and advances. Renamed from "Skip"
// since it actually saves what you've labeled.
Button {
advanceToNext()
} label: {
HStack(spacing: 4) {
Text(currentIndex + 1 == images.count ? "Done" : "Next")
.font(.subheadline.bold())
if currentIndex + 1 < images.count {
Image(systemName: "chevron.right")
.font(.caption.bold())
}
}
.foregroundColor(.white)
.padding(.horizontal, 14)
.padding(.vertical, 8)
.background(Color.appBlue.opacity(0.9))
.cornerRadius(20)
}
}
}
.padding()
.padding(.top, 44) // Safe area
}
private func advanceToNext() {
// Next image starts with a clean slate
currentBoxes = []
sessionManager.saveProgress(
index: currentIndex + 1,
labeledCount: totalLabeled,
boxes: []
)
if currentIndex + 1 < images.count {
currentIndex += 1
} else {
onComplete()
}
}
private func saveAndExit() {
// Persist in-progress boxes so resume restores drawn-but-unlabeled work
sessionManager.saveProgress(
index: currentIndex,
labeledCount: totalLabeled,
boxes: currentBoxes
)
onSaveProgress()
}
}
#Preview {
LabelNavigationView(selectedTab: .constant(0))
.environmentObject(DatasetManager())
}