SPB Git

Repository Public License

ActionsView.swift 16.6 KB 300 lines swift

1//2//  ORIX Audio3//  File: ORIXAudio/Features/Actions/ActionsView.swift4//  Description: ORIX Actions: workflow list, visual step builder with editable parameters, batch runner with progress, cancellation and results.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//9import ORIXAudioCore10import SwiftData11import SwiftUI1213enum StepText {14    static func title(_ step: ActionStep) -> String {15        switch step {16        case .analyze: String(localized: "Analyze")17        case .transcribe: String(localized: "Transcribe")18        case .summarize: String(localized: "Summarize")19        case .removeSilence: String(localized: "Remove silence")20        case .normalize: String(localized: "Normalize")21        case .enhance: String(localized: "Enhance")22        case .convert: String(localized: "Convert")23        case .exportTranscript: String(localized: "Export transcript")24        case .exportReport: String(localized: "Export analysis report")25        }26    }27    static func detail(_ step: ActionStep) -> String {28        switch step {29        case .analyze: String(localized: "Levels, loudness, spectrum, speech activity")30        case .transcribe(let id): String(localized: "On-device · \(Locale.current.localizedString(forIdentifier: id) ?? id)")31        case .summarize: String(localized: "Notes from the transcript, on-device")32        case .removeSilence(let s): String(localized: "Cuts silences longer than \(s.formatted()) s")33        case .normalize(let t): String(localized: "Peak to \(t.formatted()) dBFS")34        case .enhance(let n, let v, let hp):35            [n > 0 ? String(localized: "noise reduction \(Int(n * 100)) %") : nil, v ? String(localized: "voice chain") : (hp > 0 ? String(localized: "high-pass \(Int(hp)) Hz") : nil)]36                .compactMap { $0 }.joined(separator: " · ")37        case .convert(let f): f.displayName38        case .exportTranscript(let f): f.displayName39        case .exportReport: "PDF"40        }41    }42    static func symbol(_ step: ActionStep) -> String {43        switch step {44        case .analyze: "chart.xyaxis.line"45        case .transcribe: "text.quote"46        case .summarize: "sparkles"47        case .removeSilence: "scissors"48        case .normalize: "arrow.up.and.down.righttriangle.up.righttriangle.down"49        case .enhance: "wand.and.stars"50        case .convert: "arrow.triangle.2.circlepath"51        case .exportTranscript: "doc.text"52        case .exportReport: "doc.richtext"53        }54    }55}5657struct ActionsView: View {58    @Environment(AppModel.self) private var model59    @Environment(\.modelContext) private var context60    @Query(sort: \Workflow.createdAt) private var workflows: [Workflow]61    @State private var editing: Workflow?62    @State private var running: Workflow?6364    var body: some View {65        List {66            if model.actions.isRunning || !model.actions.log.isEmpty {67                Section("Last run") { NavigationLink { ActionRunView() } label: { ActionRunSummary() } }68            }69            Section {70                ForEach(workflows) { workflow in71                    Button { editing = workflow } label: {72                        HStack(spacing: 12) {73                            Image(systemName: workflow.symbol).font(.title3).foregroundStyle(ORIX.brandGradient).frame(width: 32)74                            VStack(alignment: .leading, spacing: 3) {75                                Text(workflow.name).font(.body.weight(.medium)).foregroundStyle(ORIX.Palette.text)76                                Text(workflow.steps.map(StepText.title).joined(separator: " → ")).font(.caption).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(2)77                                if workflow.trigger != .manual {78                                    Chip(text: workflow.trigger == .afterRecording ? String(localized: "Runs after each recording") : String(localized: "Runs after each import"), symbol: "bolt.badge.automatic", tint: ORIX.Palette.violet)79                                }80                            }81                            Spacer()82                            Button { running = workflow } label: { Image(systemName: "play.circle.fill").font(.title2) }83                                .buttonStyle(.borderless).accessibilityLabel(Text("Run \(workflow.name)")).disabled(model.actions.isRunning)84                        }85                    }86                    .swipeActions { Button("Delete", systemImage: "trash", role: .destructive) { context.delete(workflow) } }87                }88            } header: { Text("Workflows") } footer: {89                Text("A workflow runs its steps in order on each recording you choose. Steps that change the audio produce a new recording; the original is never altered.")90            }91        }92        .listStyle(.insetGrouped).scrollContentBackground(.hidden).orixScreenBackground()93        .navigationTitle("Actions")94        .toolbar {95            ToolbarItem(placement: .topBarTrailing) {96                Button("New workflow", systemImage: "plus") {97                    let w = Workflow(name: String(localized: "New workflow"), steps: [.analyze])98                    context.insert(w); editing = w99                }100            }101        }102        .sheet(item: $editing) { WorkflowEditor(workflow: $0) }103        .sheet(item: $running) { RecordingPickerSheet(workflow: $0) }104    }105}106107struct ActionRunSummary: View {108    @Environment(AppModel.self) private var model109    var body: some View {110        let runner = model.actions111        VStack(alignment: .leading, spacing: 6) {112            HStack {113                Text(runner.workflowName).font(.body.weight(.medium))114                Spacer()115                if runner.isRunning { ProgressView().controlSize(.small) }116            }117            ProgressView(value: runner.progress).tint(ORIX.Palette.cyan)118            let failed = runner.log.filter { if case .failed = $0.outcome { true } else { false } }.count119            Text(runner.isRunning ? "Running…" : (failed == 0 ? "Finished" : "Finished with \(failed) failed steps"))120                .font(.caption).foregroundStyle(failed == 0 ? ORIX.Palette.textSecondary : ORIX.Palette.record)121        }122    }123}124125struct ActionRunView: View {126    @Environment(AppModel.self) private var model127    @State private var share: SharePayload?128    var body: some View {129        let runner = model.actions130        List {131            Section {132                ActionRunSummary()133                if runner.isRunning { Button("Cancel", role: .destructive) { runner.cancel() } }134                if !runner.outputs.isEmpty { Button("Share \(runner.outputs.count) exported files", systemImage: "square.and.arrow.up") { share = SharePayload(urls: runner.outputs) } }135                if !runner.createdRecordings.isEmpty { Label("\(runner.createdRecordings.count) new recordings added to the library", systemImage: "plus.rectangle.on.folder") }136            }137            Section("Steps") {138                ForEach(runner.log) { entry in139                    HStack(alignment: .top, spacing: 10) {140                        Group {141                            switch entry.outcome {142                            case .running: ProgressView().controlSize(.small)143                            case .done: Image(systemName: "checkmark.circle.fill").foregroundStyle(ORIX.Palette.good)144                            case .failed: Image(systemName: "xmark.octagon.fill").foregroundStyle(ORIX.Palette.record)145                            case .skipped: Image(systemName: "minus.circle").foregroundStyle(ORIX.Palette.warning)146                            }147                        }.frame(width: 22)148                        VStack(alignment: .leading, spacing: 2) {149                            Text(StepText.title(entry.step)).font(.subheadline.weight(.medium))150                            Text(entry.recordingTitle).font(.caption).foregroundStyle(ORIX.Palette.textSecondary)151                            switch entry.outcome {152                            case .failed(let m): Text(m).font(.caption).foregroundStyle(ORIX.Palette.record)153                            case .skipped(let m): Text(m).font(.caption).foregroundStyle(ORIX.Palette.warning)154                            default: EmptyView()155                            }156                        }157                    }158                }159            }160        }161        .navigationTitle("Run").navigationBarTitleDisplayMode(.inline)162        .shareSheet($share)163    }164}165166/// Choose which recordings a workflow runs on.167struct RecordingPickerSheet: View {168    @Environment(AppModel.self) private var model169    @Environment(\.dismiss) private var dismiss170    @Query(filter: #Predicate<Recording> { $0.deletedAt == nil }, sort: \Recording.createdAt, order: .reverse) private var recordings: [Recording]171    let workflow: Workflow172    @State private var selection: Set<UUID> = []173    var body: some View {174        NavigationStack {175            List(recordings, selection: $selection) { r in176                VStack(alignment: .leading) {177                    Text(r.title).lineLimit(1)178                    Text("\(Formatters.duration(r.duration)) · \(r.formatLine)").font(.caption).foregroundStyle(ORIX.Palette.textSecondary)179                }.tag(r.id)180            }181            .environment(\.editMode, .constant(.active))182            .navigationTitle(workflow.name).navigationBarTitleDisplayMode(.inline)183            .toolbar {184                ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }185                ToolbarItem(placement: .confirmationAction) {186                    Button("Run on \(selection.count)") { model.actions.start(workflow, on: recordings.filter { selection.contains($0.id) }); dismiss() }.disabled(selection.isEmpty)187                }188            }189        }190    }191}192193/// Choose which workflow runs on recordings already selected in the library.194struct WorkflowPickerSheet: View {195    @Environment(AppModel.self) private var model196    @Environment(\.dismiss) private var dismiss197    @Query(sort: \Workflow.createdAt) private var workflows: [Workflow]198    let recordings: [Recording]199    var onStart: () -> Void = {}200    var body: some View {201        NavigationStack {202            List(workflows) { workflow in203                Button { model.actions.start(workflow, on: recordings); onStart(); dismiss() } label: {204                    Label { VStack(alignment: .leading) { Text(workflow.name); Text(workflow.steps.map(StepText.title).joined(separator: " → ")).font(.caption).foregroundStyle(ORIX.Palette.textSecondary) } }205                        icon: { Image(systemName: workflow.symbol) }206                }207            }208            .navigationTitle("Run on \(recordings.count) recordings").navigationBarTitleDisplayMode(.inline)209            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } }210        }211        .presentationDetents([.medium, .large])212    }213}214215struct WorkflowEditor: View {216    @Environment(AppSettings.self) private var settings217    @Environment(\.dismiss) private var dismiss218    @Bindable var workflow: Workflow219    @State private var steps: [ActionStep] = []220    @State private var locales: [Locale] = []221222    var body: some View {223        NavigationStack {224            Form {225                Section("Workflow") {226                    TextField("Name", text: $workflow.name)227                    Picker("Runs", selection: Binding(get: { workflow.trigger }, set: { workflow.trigger = $0 })) {228                        Text("When I start it").tag(WorkflowTrigger.manual)229                        Text("After each recording").tag(WorkflowTrigger.afterRecording)230                        Text("After each import").tag(WorkflowTrigger.afterImport)231                    }232                }233                Section {234                    ForEach(Array(steps.enumerated()), id: \.offset) { index, step in235                        VStack(alignment: .leading, spacing: 8) {236                            HStack(spacing: 10) {237                                Text("\(index + 1)").font(.caption.weight(.bold)).frame(width: 22, height: 22).background(ORIX.Palette.cyan.opacity(0.2), in: Circle())238                                Image(systemName: StepText.symbol(step)).foregroundStyle(ORIX.Palette.cyan)239                                VStack(alignment: .leading) {240                                    Text(StepText.title(step)).font(.body.weight(.medium))241                                    Text(StepText.detail(step)).font(.caption).foregroundStyle(ORIX.Palette.textSecondary)242                                }243                            }244                            parameters(index: index, step: step)245                        }246                        .padding(.vertical, 2)247                    }248                    .onDelete { steps.remove(atOffsets: $0) }249                    .onMove { steps.move(fromOffsets: $0, toOffset: $1) }250                    Menu {251                        Button("Analyze", systemImage: "chart.xyaxis.line") { steps.append(.analyze) }252                        Button("Transcribe", systemImage: "text.quote") { steps.append(.transcribe(localeIdentifier: settings.transcriptionLocaleIdentifier)) }253                        Button("Summarize", systemImage: "sparkles") { steps.append(.summarize) }254                        Divider()255                        Button("Remove silence", systemImage: "scissors") { steps.append(.removeSilence(minimumSeconds: 1.5)) }256                        Button("Enhance", systemImage: "wand.and.stars") { steps.append(.enhance(noiseReduction: 0.5, voice: true, highPassHz: 80)) }257                        Button("Normalize", systemImage: "arrow.up.and.down") { steps.append(.normalize(targetPeakDBFS: -1)) }258                        Button("Convert", systemImage: "arrow.triangle.2.circlepath") { steps.append(.convert(format: .aac)) }259                        Divider()260                        Button("Export transcript", systemImage: "doc.text") { steps.append(.exportTranscript(format: .markdown)) }261                        Button("Export analysis report", systemImage: "doc.richtext") { steps.append(.exportReport) }262                    } label: { Label("Add step", systemImage: "plus.circle.fill") }263                } header: { Text("Steps") } footer: {264                    Text("Summarize needs a transcript, so put Transcribe before it. Audio steps are applied together when the next non-audio step (or the end) is reached.")265                }266            }267            .environment(\.editMode, .constant(.active))268            .navigationTitle("Edit workflow").navigationBarTitleDisplayMode(.inline)269            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { workflow.steps = steps; dismiss() } } }270            .task { steps = workflow.steps; locales = await TranscriptionEngine.supportedLocales() }271            .onDisappear { workflow.steps = steps }272        }273    }274275    @ViewBuilder private func parameters(index: Int, step: ActionStep) -> some View {276        switch step {277        case .transcribe(let id):278            Picker("Language", selection: Binding(get: { id }, set: { steps[index] = .transcribe(localeIdentifier: $0) })) {279                if !locales.contains(where: { $0.identifier(.bcp47) == id }) { Text(id).tag(id) }280                ForEach(locales, id: \.identifier) { Text(Locale.current.localizedString(forIdentifier: $0.identifier) ?? $0.identifier).tag($0.identifier(.bcp47)) }281            }282        case .removeSilence(let seconds):283            Stepper("Longer than \(seconds.formatted()) s", value: Binding(get: { seconds }, set: { steps[index] = .removeSilence(minimumSeconds: $0) }), in: 0.5...10, step: 0.5)284        case .normalize(let target):285            Stepper("Peak \(target.formatted()) dBFS", value: Binding(get: { target }, set: { steps[index] = .normalize(targetPeakDBFS: $0) }), in: -12...0, step: 0.5)286        case .enhance(let noise, let voice, let highPass):287            VStack(alignment: .leading) {288                Text("Noise reduction \(Int(noise * 100)) %").font(.caption)289                Slider(value: Binding(get: { noise }, set: { steps[index] = .enhance(noiseReduction: $0, voice: voice, highPassHz: highPass) }), in: 0...1)290                Toggle("Voice chain (high-pass, presence, compression)", isOn: Binding(get: { voice }, set: { steps[index] = .enhance(noiseReduction: noise, voice: $0, highPassHz: highPass) }))291            }292        case .convert(let format):293            Picker("Format", selection: Binding(get: { format }, set: { steps[index] = .convert(format: $0) })) { ForEach(AudioExportFormat.allCases) { Text($0.displayName).tag($0) } }294        case .exportTranscript(let format):295            Picker("Format", selection: Binding(get: { format }, set: { steps[index] = .exportTranscript(format: $0) })) { ForEach(TranscriptFileFormat.allCases) { Text($0.displayName).tag($0) } }296        default: EmptyView()297        }298    }299}300
Files main
Menu

Theme