Repository navigation
Expand file tree
/
Copy pathTranscriptor.swift
More file actions
184 lines (164 loc) · 7.96 KB
/
Copy pathTranscriptor.swift
File metadata and controls
184 lines (164 loc) · 7.96 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
// Ícono en la barra de menú de macOS para transcribir audios con Whisper (y opcionalmente interpretarlos con Ollama).
// Lo compila instalar.sh con: swiftc -O Transcriptor.swift -o Transcriptor
// Uso: Transcriptor <ruta de node> <ruta de interpretar.js>
// En reposo no ejecuta nada: Whisper y Ollama solo se encienden mientras se procesa un audio.
import Cocoa
import UniformTypeIdentifiers
let rutaNode = CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : "/usr/local/bin/node"
let rutaScript = CommandLine.arguments.count > 2 ? CommandLine.arguments[2] : ""
final class Transcriptor: NSObject, NSApplicationDelegate {
private var item: NSStatusItem!
private let menu = NSMenu()
private let soloTexto = NSMenuItem(title: "Transcribir audio…", action: #selector(transcribir), keyEquivalent: "t")
private let conLLM = NSMenuItem(title: "Transcribir e interpretar con IA…", action: #selector(transcribirConLLM), keyEquivalent: "i")
private let estadoItem = NSMenuItem(title: "En reposo", action: nil, keyEquivalent: "")
private let cancelarItem = NSMenuItem(title: "Cancelar", action: #selector(cancelar), keyEquivalent: "")
private var proceso: Process?
private var copiaTemporal: URL?
private var ventana: NSWindow?
func applicationDidFinishLaunching(_ notification: Notification) {
item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
ponerIcono(trabajando: false)
for opcion in [soloTexto, conLLM] {
opcion.target = self
menu.addItem(opcion)
}
menu.addItem(.separator())
estadoItem.isEnabled = false
menu.addItem(estadoItem)
cancelarItem.target = self
cancelarItem.isHidden = true
menu.addItem(cancelarItem)
menu.addItem(.separator())
let salir = NSMenuItem(title: "Quitar ícono de la barra", action: #selector(salir), keyEquivalent: "q")
salir.target = self
menu.addItem(salir)
item.menu = menu
}
private func ponerIcono(trabajando: Bool) {
guard let boton = item.button else { return }
let simbolo = trabajando ? "hourglass" : "waveform"
if let img = NSImage(systemSymbolName: simbolo, accessibilityDescription: "Transcriptor") {
img.isTemplate = true
boton.image = img
} else {
boton.title = trabajando ? "…" : "🎙"
}
boton.toolTip = trabajando ? "Procesando audio…" : "Transcribir audio"
}
@objc private func transcribir() { elegirAudio(usarLLM: false) }
@objc private func transcribirConLLM() { elegirAudio(usarLLM: true) }
private func elegirAudio(usarLLM: Bool) {
let panel = NSOpenPanel()
panel.title = usarLLM ? "Audio para transcribir e interpretar" : "Audio para transcribir"
panel.canChooseDirectories = false
panel.allowsMultipleSelection = false
panel.allowedContentTypes = [.audio, .mpeg4Audio, .mp3, .wav]
+ ["opus", "ogg", "oga", "m4a", "aac", "flac", "webm", "mp4"].compactMap { UTType(filenameExtension: $0) }
panel.directoryURL = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first
NSApp.activate(ignoringOtherApps: true)
guard panel.runModal() == .OK, let archivo = panel.url else { return }
// Se trabaja sobre una copia temporal: el archivo elegido puede estar en una carpeta
// protegida (Descargas, Escritorio) a la que node no tendría permiso de leer.
let copia = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString)
.appendingPathExtension(archivo.pathExtension)
do {
try FileManager.default.copyItem(at: archivo, to: copia)
} catch {
mostrarResultado(titulo: "Error", texto: "No se pudo leer el archivo: \(error.localizedDescription)")
return
}
copiaTemporal = copia
ejecutar(audio: copia, nombre: archivo.lastPathComponent, usarLLM: usarLLM)
}
private func ejecutar(audio: URL, nombre: String, usarLLM: Bool) {
let p = Process()
p.executableURL = URL(fileURLWithPath: rutaNode)
p.arguments = [rutaScript, audio.path] + (usarLLM ? ["--llm"] : [])
var entorno = ProcessInfo.processInfo.environment
entorno["PATH"] = "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin"
p.environment = entorno
let salida = Pipe(), errores = Pipe()
p.standardOutput = salida
p.standardError = errores
do {
try p.run()
} catch {
limpiar()
mostrarResultado(titulo: "Error", texto: "No se pudo ejecutar node (\(rutaNode)): \(error.localizedDescription)")
return
}
proceso = p
cambiarEstado(trabajando: true, texto: usarLLM ? "Transcribiendo e interpretando…" : "Transcribiendo…")
DispatchQueue.global().async {
let datos = salida.fileHandleForReading.readDataToEndOfFile()
let datosError = errores.fileHandleForReading.readDataToEndOfFile()
p.waitUntilExit()
let texto = String(decoding: datos, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
let error = String(decoding: datosError, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
DispatchQueue.main.async {
let cancelado = p.terminationReason == .uncaughtSignal || p.terminationStatus == 130
self.limpiar()
if cancelado { return }
if p.terminationStatus == 0 && !texto.isEmpty {
self.mostrarResultado(titulo: nombre, texto: texto)
} else {
self.mostrarResultado(titulo: "Error", texto: error.isEmpty ? "No se detectó voz en el audio." : error)
}
}
}
}
// Envía SIGTERM: el script detiene Whisper y apaga Ollama antes de salir.
@objc private func cancelar() { proceso?.terminate() }
private func limpiar() {
proceso = nil
if let copia = copiaTemporal { try? FileManager.default.removeItem(at: copia) }
copiaTemporal = nil
cambiarEstado(trabajando: false, texto: "En reposo")
}
private func cambiarEstado(trabajando: Bool, texto: String) {
estadoItem.title = texto
soloTexto.isEnabled = !trabajando
conLLM.isEnabled = !trabajando
cancelarItem.isHidden = !trabajando
ponerIcono(trabajando: trabajando)
}
private func mostrarResultado(titulo: String, texto: String) {
if titulo != "Error" {
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(texto, forType: .string)
}
let marco = NSRect(x: 0, y: 0, width: 560, height: 380)
let w = ventana ?? NSWindow(contentRect: marco, styleMask: [.titled, .closable, .resizable],
backing: .buffered, defer: false)
w.isReleasedWhenClosed = false
w.title = titulo == "Error" ? "Error" : "\(titulo) — copiado al portapapeles"
let scroll = NSScrollView(frame: marco)
scroll.hasVerticalScroller = true
scroll.autoresizingMask = [.width, .height]
let vista = NSTextView(frame: marco)
vista.isEditable = false
vista.isSelectable = true
vista.font = .systemFont(ofSize: 14)
vista.textContainerInset = NSSize(width: 14, height: 14)
vista.autoresizingMask = [.width]
vista.string = texto
scroll.documentView = vista
w.contentView = scroll
if ventana == nil { w.center() }
ventana = w
NSApp.activate(ignoringOtherApps: true)
w.makeKeyAndOrderFront(nil)
}
@objc private func salir() {
proceso?.terminate()
proceso?.waitUntilExit()
NSApp.terminate(nil)
}
}
let app = NSApplication.shared
let delegado = Transcriptor()
app.delegate = delegado
app.setActivationPolicy(.accessory) // sin ícono en el Dock
app.run()