diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index f0df43b5051..7b06d42b70b 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -2789,6 +2789,59 @@ text_track = "Text" video = "Video" zoom = "Zoom" +[editor.transcript] +cleanup = "Aufräumen" +cleanup_tooltip = "Füllwörter entfernen und Pausen kürzen" +delete_matches = "Alle löschen" +delete_matches_tooltip = "Jeden Treffer aus dem Video schneiden" +empty_description = "Transkribieren Sie diese Aufnahme auf diesem Computer und bearbeiten Sie dann das Video über seinen Text." +empty_title = "Noch kein Transkript" +hint = "Klicken Sie auf ein Wort, um dorthin zu springen. Wählen Sie Wörter aus und drücken Sie die Löschtaste, um sie aus dem Video zu schneiden." +next_match = "Nächster Treffer" +no_audio = "Diese Aufnahme hat keinen Ton zum Transkribieren." +previous_match = "Vorheriger Treffer" +restore_blocked = "Dieser Teil wurde in der Zeitleiste geschnitten. Nutzen Sie Rückgängig oder ziehen Sie den Clip-Rand, um ihn zurückzuholen." +restore_hint = { one = "Klicken, um {count} Wort wiederherzustellen", other = "Klicken, um {count} Wörter wiederherzustellen" } +restore_transition = "Entfernen Sie den Übergang neben diesem Schnitt, um ihn wiederherzustellen." +search = "Suchen" +search_count = "{current} von {total}" +search_none = "Keine Treffer" +search_placeholder = "Im Transkript suchen" +seconds = "{value} s" +selection = { one = "{count} Wort ausgewählt, {seconds} s", other = "{count} Wörter ausgewählt, {seconds} s" } +selection_cut = { one = "{count} geschnittenes Wort ausgewählt. Drücken Sie die Löschtaste, um es wiederherzustellen.", other = "{count} geschnittene Wörter ausgewählt. Drücken Sie die Löschtaste, um sie wiederherzustellen." } +skipped_hold = { one = "{count} Schnitt wurde übersprungen, weil eine Vollbild-Texttafel dieses Bild hält", other = "{count} Schnitte wurden übersprungen, weil Vollbild-Texttafeln diese Bilder halten" } +skipped_last_clip = "Der letzte Clip kann nicht weggeschnitten werden." +skipped_transition = { one = "{count} Schnitt wurde übersprungen, weil er einen Übergang berührt", other = "{count} Schnitte wurden übersprungen, weil sie Übergänge berühren" } +title = "Transkript" +transcribe = "Transkribieren" +transcribing = "Wird transkribiert…" +words = { one = "{count} Wort", other = "{count} Wörter" } + +[editor.transcript.fillers] +discourse = "Füllphrasen" +discourse_hint = "like, you know, so" +false_start = "Fehlstarts" +false_start_hint = "we should, we need" +hesitation = "Zögerlaute" +hesitation_hint = "um, uh, hmm" +keep = "Dieses behalten" +listen = "Anhören" +none = "Keine Füllwörter in diesen Kategorien übrig" +remove = "Dieses entfernen" +remove_all = { one = "{count} entfernen", other = "{count} entfernen" } +repetition = "Wiederholte Wörter" +repetition_hint = "the the, I I" +title = "Füllwörter" + +[editor.transcript.pauses] +apply = "Kürzen" +keep = "Kürzen auf" +longer_than = "Pausen länger als" +none = "Keine so langen Pausen" +summary = { one = "{count} Pause, spart {seconds} s", other = "{count} Pausen, sparen {seconds} s" } +title = "Pausen" + [editor.window] audio_filter = "Audio" audio_segment_changed = "Dieses Audiosegment hat sich geändert. Wählen Sie es aus und wählen Sie erneut einen Ersatz." @@ -2891,11 +2944,12 @@ window_title_placeholder = "Fenstertitel" windows_description = "Titelleiste mit Fenstersteuerung" [editor.window.header] -captions = "Untertitel" delete_recording = "Aufnahme löschen" export = "Exportieren" open_bundle = "Aufnahmepaket öffnen" presets = "Vorlagen" +transcript = "Transkript" +transcript_tooltip = "Per Transkript bearbeiten" [editor.window.image] changed = "Dieses Bild hat sich bei der Auswahl eines Ersatzes geändert. Wählen Sie es aus und versuchen Sie es erneut." diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index 606f9323e6d..a3cb0262512 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -2791,6 +2791,59 @@ text_track = "Text" video = { text = "Video", context = "Timeline gutter label of the recording's video track." } zoom = "Zoom" +[editor.transcript] +cleanup = "Clean up" +cleanup_tooltip = "Remove filler words and shorten pauses" +delete_matches = "Delete all" +delete_matches_tooltip = "Cut every match from the video" +empty_description = "Transcribe this recording on this computer, then edit the video by editing its text." +empty_title = "No transcript yet" +hint = "Click a word to jump to it. Select words and press Delete to cut them from the video." +next_match = "Next match" +no_audio = "This recording has no audio to transcribe." +previous_match = "Previous match" +restore_blocked = "This part was cut on the timeline. Use Undo or drag the clip edge to bring it back." +restore_hint = { one = "Click to restore {count} word", other = "Click to restore {count} words" } +restore_transition = "Remove the transition next to this cut to restore it." +search = "Find" +search_count = { text = "{current} of {total}", context = "Search results: {current} is the highlighted match, {total} how many there are." } +search_none = "No matches" +search_placeholder = "Find in transcript" +seconds = { text = "{value} s", context = "{value} is a number of seconds such as 1.5." } +selection = { one = "{count} word selected, {seconds} s", other = "{count} words selected, {seconds} s", context = "{seconds} is how long the selected words take to say, such as 2.4." } +selection_cut = { one = "{count} cut word selected. Press Delete to restore it.", other = "{count} cut words selected. Press Delete to restore them." } +skipped_hold = { one = "{count} cut was skipped because a fullscreen text card holds that frame", other = "{count} cuts were skipped because fullscreen text cards hold those frames" } +skipped_last_clip = "The last clip cannot be cut away." +skipped_transition = { one = "{count} cut was skipped because it touches a transition", other = "{count} cuts were skipped because they touch transitions" } +title = "Transcript" +transcribe = "Transcribe" +transcribing = "Transcribing…" +words = { one = "{count} word", other = "{count} words" } + +[editor.transcript.fillers] +discourse = "Filler phrases" +discourse_hint = { text = "like, you know, so", context = "English examples of the fillers this category finds. Detection is English only, so keep them in English." } +false_start = "False starts" +false_start_hint = { text = "we should, we need", context = "An English example of a restarted sentence. Keep it in English." } +hesitation = "Hesitations" +hesitation_hint = { text = "um, uh, hmm", context = "English hesitation sounds. Keep them in English." } +keep = "Keep this one" +listen = "Listen" +none = "No filler words left in these categories" +remove = "Remove this one" +remove_all = { one = "Remove {count}", other = "Remove {count}" } +repetition = "Repeated words" +repetition_hint = { text = "the the, I I", context = "English examples of a repeated word. Keep them in English." } +title = "Filler words" + +[editor.transcript.pauses] +apply = "Shorten" +keep = "Shorten to" +longer_than = "Pauses longer than" +none = "No pauses that long" +summary = { one = "{count} pause, saves {seconds} s", other = "{count} pauses, saves {seconds} s", context = "{seconds} is how much shorter the video gets, such as 12.5." } +title = "Pauses" + [editor.window] audio_filter = { text = "Audio", context = "File type filter name in the audio file picker." } audio_segment_changed = "This audio segment changed. Select it and choose a replacement again." @@ -2893,11 +2946,12 @@ window_title_placeholder = "Window title" windows_description = "Title bar with window controls" [editor.window.header] -captions = "Captions" delete_recording = "Delete recording" export = "Export" open_bundle = "Open recording bundle" presets = "Presets" +transcript = "Transcript" +transcript_tooltip = "Edit by transcript" [editor.window.image] changed = "This image changed while choosing a replacement. Select it and try again." diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index 96233f8ded6..fba3707fc65 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -2789,6 +2789,59 @@ text_track = "Texto" video = "Vídeo" zoom = "Zoom" +[editor.transcript] +cleanup = "Limpiar" +cleanup_tooltip = "Quitar muletillas y acortar pausas" +delete_matches = "Eliminar todo" +delete_matches_tooltip = "Cortar del vídeo cada coincidencia" +empty_description = "Transcribe esta grabación en este ordenador y luego edita el vídeo editando su texto." +empty_title = "Aún no hay transcripción" +hint = "Haz clic en una palabra para ir a ella. Selecciona palabras y pulsa la tecla de borrar para cortarlas del vídeo." +next_match = "Siguiente coincidencia" +no_audio = "Esta grabación no tiene audio que transcribir." +previous_match = "Coincidencia anterior" +restore_blocked = "Esta parte se cortó en la línea de tiempo. Usa Deshacer o arrastra el borde del clip para recuperarla." +restore_hint = { one = "Haz clic para restaurar {count} palabra", many = "Haz clic para restaurar {count} de palabras", other = "Haz clic para restaurar {count} palabras" } +restore_transition = "Quita la transición junto a este corte para restaurarlo." +search = "Buscar" +search_count = "{current} de {total}" +search_none = "Sin coincidencias" +search_placeholder = "Buscar en la transcripción" +seconds = "{value} s" +selection = { one = "{count} palabra seleccionada, {seconds} s", many = "{count} de palabras seleccionadas, {seconds} s", other = "{count} palabras seleccionadas, {seconds} s" } +selection_cut = { one = "{count} palabra cortada seleccionada. Pulsa la tecla de borrar para restaurarla.", many = "{count} de palabras cortadas seleccionadas. Pulsa la tecla de borrar para restaurarlas.", other = "{count} palabras cortadas seleccionadas. Pulsa la tecla de borrar para restaurarlas." } +skipped_hold = { one = "Se omitió {count} corte porque una tarjeta de texto a pantalla completa retiene ese fotograma", many = "Se omitieron {count} de cortes porque tarjetas de texto a pantalla completa retienen esos fotogramas", other = "Se omitieron {count} cortes porque tarjetas de texto a pantalla completa retienen esos fotogramas" } +skipped_last_clip = "No se puede cortar el último clip." +skipped_transition = { one = "Se omitió {count} corte porque toca una transición", many = "Se omitieron {count} de cortes porque tocan transiciones", other = "Se omitieron {count} cortes porque tocan transiciones" } +title = "Transcripción" +transcribe = "Transcribir" +transcribing = "Transcribiendo…" +words = { one = "{count} palabra", many = "{count} de palabras", other = "{count} palabras" } + +[editor.transcript.fillers] +discourse = "Frases de relleno" +discourse_hint = "like, you know, so" +false_start = "Comienzos en falso" +false_start_hint = "we should, we need" +hesitation = "Titubeos" +hesitation_hint = "um, uh, hmm" +keep = "Conservar esta" +listen = "Escuchar" +none = "No quedan muletillas en estas categorías" +remove = "Quitar esta" +remove_all = { one = "Quitar {count}", many = "Quitar {count}", other = "Quitar {count}" } +repetition = "Palabras repetidas" +repetition_hint = "the the, I I" +title = "Muletillas" + +[editor.transcript.pauses] +apply = "Acortar" +keep = "Acortar a" +longer_than = "Pausas de más de" +none = "No hay pausas tan largas" +summary = { one = "{count} pausa, ahorra {seconds} s", many = "{count} de pausas, ahorran {seconds} s", other = "{count} pausas, ahorran {seconds} s" } +title = "Pausas" + [editor.window] audio_filter = "Audio" audio_segment_changed = "Este segmento de audio cambió. Selecciónalo y vuelve a elegir un reemplazo." @@ -2891,11 +2944,12 @@ window_title_placeholder = "Título de la ventana" windows_description = "Barra de título con controles de ventana" [editor.window.header] -captions = "Subtítulos" delete_recording = "Eliminar grabación" export = "Exportar" open_bundle = "Abrir paquete de la grabación" presets = "Preajustes" +transcript = "Transcripción" +transcript_tooltip = "Editar con la transcripción" [editor.window.image] changed = "Esta imagen cambió mientras elegías un reemplazo. Selecciónala e inténtalo de nuevo." diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index 7163a23f76d..8b281eafbf7 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -2789,6 +2789,59 @@ text_track = "Texte" video = "Vidéo" zoom = "Zoom" +[editor.transcript] +cleanup = "Nettoyer" +cleanup_tooltip = "Supprimer les mots de remplissage et raccourcir les pauses" +delete_matches = "Tout supprimer" +delete_matches_tooltip = "Couper chaque résultat de la vidéo" +empty_description = "Transcrivez cet enregistrement sur cet ordinateur, puis modifiez la vidéo en modifiant son texte." +empty_title = "Pas encore de transcription" +hint = "Cliquez sur un mot pour y aller. Sélectionnez des mots et appuyez sur la touche Supprimer pour les couper de la vidéo." +next_match = "Résultat suivant" +no_audio = "Cet enregistrement n'a pas d'audio à transcrire." +previous_match = "Résultat précédent" +restore_blocked = "Cette partie a été coupée dans la timeline. Utilisez Annuler ou faites glisser le bord du clip pour la récupérer." +restore_hint = { one = "Cliquez pour restaurer {count} mot", many = "Cliquez pour restaurer {count} de mots", other = "Cliquez pour restaurer {count} mots" } +restore_transition = "Supprimez la transition à côté de cette coupe pour la restaurer." +search = "Rechercher" +search_count = "{current} sur {total}" +search_none = "Aucun résultat" +search_placeholder = "Rechercher dans la transcription" +seconds = "{value} s" +selection = { one = "{count} mot sélectionné, {seconds} s", many = "{count} de mots sélectionnés, {seconds} s", other = "{count} mots sélectionnés, {seconds} s" } +selection_cut = { one = "{count} mot coupé sélectionné. Appuyez sur la touche Supprimer pour le restaurer.", many = "{count} de mots coupés sélectionnés. Appuyez sur la touche Supprimer pour les restaurer.", other = "{count} mots coupés sélectionnés. Appuyez sur la touche Supprimer pour les restaurer." } +skipped_hold = { one = "{count} coupe ignorée, car une carte de texte plein écran fige cette image", many = "{count} de coupes ignorées, car des cartes de texte plein écran figent ces images", other = "{count} coupes ignorées, car des cartes de texte plein écran figent ces images" } +skipped_last_clip = "Le dernier clip ne peut pas être coupé." +skipped_transition = { one = "{count} coupe ignorée, car elle touche une transition", many = "{count} de coupes ignorées, car elles touchent des transitions", other = "{count} coupes ignorées, car elles touchent des transitions" } +title = "Transcription" +transcribe = "Transcrire" +transcribing = "Transcription…" +words = { one = "{count} mot", many = "{count} de mots", other = "{count} mots" } + +[editor.transcript.fillers] +discourse = "Expressions de remplissage" +discourse_hint = "like, you know, so" +false_start = "Faux départs" +false_start_hint = "we should, we need" +hesitation = "Hésitations" +hesitation_hint = "um, uh, hmm" +keep = "Garder celui-ci" +listen = "Écouter" +none = "Plus de mots de remplissage dans ces catégories" +remove = "Supprimer celui-ci" +remove_all = { one = "Supprimer {count}", many = "Supprimer {count}", other = "Supprimer {count}" } +repetition = "Mots répétés" +repetition_hint = "the the, I I" +title = "Mots de remplissage" + +[editor.transcript.pauses] +apply = "Raccourcir" +keep = "Raccourcir à" +longer_than = "Pauses de plus de" +none = "Aucune pause aussi longue" +summary = { one = "{count} pause, gagne {seconds} s", many = "{count} de pauses, gagnent {seconds} s", other = "{count} pauses, gagnent {seconds} s" } +title = "Pauses" + [editor.window] audio_filter = "Audio" audio_segment_changed = "Ce segment audio a changé. Sélectionnez-le et choisissez de nouveau un remplacement." @@ -2891,11 +2944,12 @@ window_title_placeholder = "Titre de la fenêtre" windows_description = "Barre de titre avec boutons de fenêtre" [editor.window.header] -captions = "Sous-titres" delete_recording = "Supprimer l'enregistrement" export = "Exporter" open_bundle = "Ouvrir le dossier de l'enregistrement" presets = "Préréglages" +transcript = "Transcription" +transcript_tooltip = "Modifier via la transcription" [editor.window.image] changed = "Cette image a changé pendant le choix d'un remplacement. Sélectionnez-la et réessayez." diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index 99ebd8f31a3..b33e86bc267 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -2789,6 +2789,59 @@ text_track = "टेक्स्ट" video = "वीडियो" zoom = "ज़ूम" +[editor.transcript] +cleanup = "साफ़ करें" +cleanup_tooltip = "फ़िलर शब्द हटाएँ और ठहराव छोटे करें" +delete_matches = "सभी हटाएँ" +delete_matches_tooltip = "हर मिलान को वीडियो से काटें" +empty_description = "इस कंप्यूटर पर इस रिकॉर्डिंग को ट्रांसक्राइब करें, फिर उसका टेक्स्ट बदलकर वीडियो एडिट करें।" +empty_title = "अभी कोई ट्रांसक्रिप्ट नहीं" +hint = "किसी शब्द पर जाने के लिए उस पर क्लिक करें। शब्द चुनें और डिलीट कुंजी दबाएँ, वे वीडियो से कट जाएँगे।" +next_match = "अगला मिलान" +no_audio = "इस रिकॉर्डिंग में ट्रांसक्राइब करने के लिए कोई ऑडियो नहीं है।" +previous_match = "पिछला मिलान" +restore_blocked = "यह हिस्सा टाइमलाइन में काटा गया था। इसे वापस लाने के लिए पूर्ववत करें या क्लिप का किनारा खींचें।" +restore_hint = { one = "{count} शब्द वापस लाने के लिए क्लिक करें", other = "{count} शब्द वापस लाने के लिए क्लिक करें" } +restore_transition = "इसे वापस लाने के लिए इस कट के पास का ट्रांज़िशन हटाएँ।" +search = "खोजें" +search_count = "{total} में से {current}" +search_none = "कोई मिलान नहीं" +search_placeholder = "ट्रांसक्रिप्ट में खोजें" +seconds = "{value} सेकंड" +selection = { one = "{count} शब्द चुना गया, {seconds} सेकंड", other = "{count} शब्द चुने गए, {seconds} सेकंड" } +selection_cut = { one = "{count} कटा हुआ शब्द चुना गया। वापस लाने के लिए डिलीट कुंजी दबाएँ।", other = "{count} कटे हुए शब्द चुने गए। वापस लाने के लिए डिलीट कुंजी दबाएँ।" } +skipped_hold = { one = "{count} कट छोड़ा गया क्योंकि फ़ुलस्क्रीन टेक्स्ट कार्ड उस फ़्रेम को रोके हुए है", other = "{count} कट छोड़े गए क्योंकि फ़ुलस्क्रीन टेक्स्ट कार्ड उन फ़्रेम को रोके हुए हैं" } +skipped_last_clip = "आखिरी क्लिप को काटा नहीं जा सकता।" +skipped_transition = { one = "{count} कट छोड़ा गया क्योंकि वह ट्रांज़िशन को छूता है", other = "{count} कट छोड़े गए क्योंकि वे ट्रांज़िशन को छूते हैं" } +title = "ट्रांसक्रिप्ट" +transcribe = "ट्रांसक्राइब करें" +transcribing = "ट्रांसक्राइब हो रहा है…" +words = { one = "{count} शब्द", other = "{count} शब्द" } + +[editor.transcript.fillers] +discourse = "फ़िलर वाक्यांश" +discourse_hint = "like, you know, so" +false_start = "अधूरी शुरुआत" +false_start_hint = "we should, we need" +hesitation = "हिचक" +hesitation_hint = "um, uh, hmm" +keep = "इसे रखें" +listen = "सुनें" +none = "इन श्रेणियों में कोई फ़िलर शब्द नहीं बचा" +remove = "इसे हटाएँ" +remove_all = { one = "{count} हटाएँ", other = "{count} हटाएँ" } +repetition = "दोहराए गए शब्द" +repetition_hint = "the the, I I" +title = "फ़िलर शब्द" + +[editor.transcript.pauses] +apply = "छोटा करें" +keep = "इतना करें" +longer_than = "इससे लंबे ठहराव" +none = "इतने लंबे ठहराव नहीं हैं" +summary = { one = "{count} ठहराव, {seconds} सेकंड बचेंगे", other = "{count} ठहराव, {seconds} सेकंड बचेंगे" } +title = "ठहराव" + [editor.window] audio_filter = "ऑडियो" audio_segment_changed = "यह ऑडियो सेगमेंट बदल गया है। इसे चुनें और फिर से बदलने के लिए फ़ाइल चुनें।" @@ -2891,11 +2944,12 @@ window_title_placeholder = "विंडो टाइटल" windows_description = "विंडो कंट्रोल के साथ टाइटल बार" [editor.window.header] -captions = "कैप्शन" delete_recording = "रिकॉर्डिंग हटाएँ" export = "एक्सपोर्ट" open_bundle = "रिकॉर्डिंग बंडल खोलें" presets = "प्रीसेट" +transcript = "ट्रांसक्रिप्ट" +transcript_tooltip = "ट्रांसक्रिप्ट से एडिट करें" [editor.window.image] changed = "बदलने के लिए चुनते समय यह इमेज बदल गई। इसे चुनें और फिर से कोशिश करें।" diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index 170cc1bdc9d..643614f856f 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -2789,6 +2789,59 @@ text_track = "テキスト" video = "動画" zoom = "ズーム" +[editor.transcript] +cleanup = "クリーンアップ" +cleanup_tooltip = "フィラーを削除し、間を短くします" +delete_matches = "すべて削除" +delete_matches_tooltip = "一致した箇所をすべて動画からカットします" +empty_description = "このコンピュータで録画を文字起こしすると、テキストを編集して動画を編集できます。" +empty_title = "文字起こしはまだありません" +hint = "単語をクリックするとその位置に移動します。単語を選択して削除キーを押すと、動画からカットされます。" +next_match = "次の一致" +no_audio = "この録画には文字起こしできる音声がありません。" +previous_match = "前の一致" +restore_blocked = "この部分はタイムラインでカットされています。取り消すか、クリップの端をドラッグして戻してください。" +restore_hint = { other = "クリックして{count}語を復元" } +restore_transition = "復元するには、このカットの隣のトランジションを削除してください。" +search = "検索" +search_count = "{current}/{total}" +search_none = "一致なし" +search_placeholder = "文字起こしを検索" +seconds = "{value}秒" +selection = { other = "{count}語を選択中、{seconds}秒" } +selection_cut = { other = "カット済みの{count}語を選択中。削除キーを押すと復元します。" } +skipped_hold = { other = "全画面テキストがフレームを保持しているため、{count}件のカットをスキップしました" } +skipped_last_clip = "最後のクリップはカットできません。" +skipped_transition = { other = "トランジションに重なるため、{count}件のカットをスキップしました" } +title = "文字起こし" +transcribe = "文字起こし" +transcribing = "文字起こし中…" +words = { other = "{count}語" } + +[editor.transcript.fillers] +discourse = "つなぎ言葉" +discourse_hint = "like, you know, so" +false_start = "言い直し" +false_start_hint = "we should, we need" +hesitation = "言いよどみ" +hesitation_hint = "um, uh, hmm" +keep = "残す" +listen = "聞く" +none = "このカテゴリにフィラーはありません" +remove = "削除" +remove_all = { other = "{count}件を削除" } +repetition = "繰り返し" +repetition_hint = "the the, I I" +title = "フィラー" + +[editor.transcript.pauses] +apply = "短くする" +keep = "短縮後" +longer_than = "次より長い間" +none = "その長さの間はありません" +summary = { other = "{count}か所、{seconds}秒短縮" } +title = "間" + [editor.window] audio_filter = "音声" audio_segment_changed = "この音声セグメントは変更されました。選択して、もう一度置き換えるファイルを選んでください。" @@ -2891,11 +2944,12 @@ window_title_placeholder = "ウィンドウタイトル" windows_description = "ウィンドウボタン付きのタイトルバー" [editor.window.header] -captions = "字幕" delete_recording = "録画を削除" export = "書き出し" open_bundle = "録画バンドルを開く" presets = "プリセット" +transcript = "文字起こし" +transcript_tooltip = "文字起こしで編集" [editor.window.image] changed = "置き換えを選んでいる間にこの画像が変更されました。選択してもう一度お試しください。" diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index 5149552f6cc..ef96d27f1eb 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -2789,6 +2789,59 @@ text_track = "文字" video = "视频" zoom = "缩放" +[editor.transcript] +cleanup = "清理" +cleanup_tooltip = "移除填充词并缩短停顿" +delete_matches = "全部删除" +delete_matches_tooltip = "从视频中剪掉所有匹配项" +empty_description = "在这台电脑上转写此录制内容,然后通过编辑文字来编辑视频。" +empty_title = "还没有转写内容" +hint = "点击单词即可跳转。选中单词后按删除键,即可从视频中剪掉。" +next_match = "下一个匹配项" +no_audio = "此录制内容没有可转写的音频。" +previous_match = "上一个匹配项" +restore_blocked = "这部分已在时间线上剪掉。请使用撤销,或拖动片段边缘将其恢复。" +restore_hint = { other = "点击恢复 {count} 个词" } +restore_transition = "请先移除此剪切旁的转场,再进行恢复。" +search = "查找" +search_count = "{current}/{total}" +search_none = "无匹配项" +search_placeholder = "在转写中查找" +seconds = "{value} 秒" +selection = { other = "已选中 {count} 个词,{seconds} 秒" } +selection_cut = { other = "已选中 {count} 个已剪掉的词。按删除键可恢复。" } +skipped_hold = { other = "已跳过 {count} 处剪切,因为全屏文字卡定格了这些画面" } +skipped_last_clip = "无法剪掉最后一个片段。" +skipped_transition = { other = "已跳过 {count} 处剪切,因为它们与转场重叠" } +title = "转写" +transcribe = "转写" +transcribing = "正在转写…" +words = { other = "{count} 个词" } + +[editor.transcript.fillers] +discourse = "填充短语" +discourse_hint = "like, you know, so" +false_start = "说错重来" +false_start_hint = "we should, we need" +hesitation = "迟疑词" +hesitation_hint = "um, uh, hmm" +keep = "保留此项" +listen = "试听" +none = "这些类别中没有填充词" +remove = "移除此项" +remove_all = { other = "移除 {count} 个" } +repetition = "重复词" +repetition_hint = "the the, I I" +title = "填充词" + +[editor.transcript.pauses] +apply = "缩短" +keep = "缩短到" +longer_than = "停顿长于" +none = "没有这么长的停顿" +summary = { other = "{count} 处停顿,节省 {seconds} 秒" } +title = "停顿" + [editor.window] audio_filter = "音频" audio_segment_changed = "此音频分段已更改。请选中它并重新选择替换文件。" @@ -2891,11 +2944,12 @@ window_title_placeholder = "窗口标题" windows_description = "带窗口控制按钮的标题栏" [editor.window.header] -captions = "字幕" delete_recording = "删除录制" export = "导出" open_bundle = "打开录制包" presets = "预设" +transcript = "转写" +transcript_tooltip = "通过转写编辑" [editor.window.image] changed = "选择替换图片时此图片已更改。请选中它后重试。" diff --git a/apps/desktop-gpui/src/app_windows.rs b/apps/desktop-gpui/src/app_windows.rs index 02acce84992..be7f9bc4bd1 100644 --- a/apps/desktop-gpui/src/app_windows.rs +++ b/apps/desktop-gpui/src/app_windows.rs @@ -5884,6 +5884,7 @@ fn load_editor_project_candidate( drive_auto_sidebar(handle, cx).await; drive_auto_playback(path, handle, cx).await; crate::editor_bench::run(handle, cx).await; + crate::transcript::automation::run(handle, cx).await; drive_auto_export(handle, cx).await; crate::editor_hover_bench::run(handle, cx).await; }) diff --git a/apps/desktop-gpui/src/editor_clips.rs b/apps/desktop-gpui/src/editor_clips.rs index 610ef609bcb..ec2e4caf80c 100644 --- a/apps/desktop-gpui/src/editor_clips.rs +++ b/apps/desktop-gpui/src/editor_clips.rs @@ -568,6 +568,7 @@ impl EditorWindow { self.close_clips(window, cx); } else { self.clips.open = true; + self.transcript.open = false; } cx.notify(); } diff --git a/apps/desktop-gpui/src/editor_edits.rs b/apps/desktop-gpui/src/editor_edits.rs index 56762e0e019..edf9c1c356c 100644 --- a/apps/desktop-gpui/src/editor_edits.rs +++ b/apps/desktop-gpui/src/editor_edits.rs @@ -206,6 +206,30 @@ impl ProjectHistory { } } + pub fn removed_takes( + &self, + timeline: &cap_project::TimelineConfiguration, + ) -> Vec { + let mut seen: std::collections::HashSet = timeline + .segments + .iter() + .map(|segment| segment.recording_clip) + .collect(); + let mut found = Vec::new(); + let current = self.entries.len() - self.count; + for entry in self.entries[..current].iter().rev() { + let Some(past) = entry.timeline.as_ref() else { + continue; + }; + for segment in &past.segments { + if seen.insert(segment.recording_clip) { + found.push(segment.clone()); + } + } + } + found + } + /// `canUndo = list.length - count > 1`. pub fn can_undo(&self) -> bool { self.entries.len() - self.count > 1 @@ -1584,6 +1608,167 @@ fn ripple_delete_output_tracks( ripple_delete_audio_track(&mut timeline.audio_segments, cut_start, cut_end, shift); } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RangeCut { + Applied, + Empty, + Transition, + Hold, + LastClip, +} + +/// A clip piece shorter than one 60 fps frame is not worth keeping: a cut that +/// would leave one takes it too, so playback never seeks into a sliver. +pub const MIN_CLIP_PIECE: f64 = 1.0 / 60.0; + +pub fn cut_clip_range( + timeline: &mut TimelineConfiguration, + index: usize, + local_start: f64, + local_end: f64, +) -> RangeCut { + let Some(segment) = timeline.segments.get(index) else { + return RangeCut::Empty; + }; + let duration = segment.duration(); + if !(local_start.is_finite() && local_end.is_finite() && duration.is_finite()) { + return RangeCut::Empty; + } + let mut local_start = local_start.clamp(0.0, duration); + let mut local_end = local_end.clamp(0.0, duration); + if local_end - local_start < 1e-4 { + return RangeCut::Empty; + } + if local_start < MIN_CLIP_PIECE { + local_start = 0.0; + } + if duration - local_end < MIN_CLIP_PIECE { + local_end = duration; + } + let incoming = timeline + .effective_transition(index) + .map_or(0.0, |transition| transition.duration); + let outgoing = timeline + .effective_transition(index + 1) + .map_or(0.0, |transition| transition.duration); + if (incoming > 0.0 && local_start < incoming * 2.0) + || (outgoing > 0.0 && duration - local_end < outgoing * 2.0) + { + return RangeCut::Transition; + } + let whole = local_start == 0.0 && local_end == duration; + if whole && timeline.segments.len() < 2 { + return RangeCut::LastClip; + } + + let clip_start = editor_timeline::clip_timeline_offsets(timeline) + .get(index) + .copied() + .unwrap_or(0.0); + let holds = timeline.hold_windows(); + let output_start = effective_to_output_end(&holds, clip_start + local_start); + let output_end = effective_to_output(&holds, clip_start + local_end).max(output_start); + if holds + .iter() + .any(|(start, end)| *start < output_end - 1e-9 && *end > output_start + 1e-9) + { + return RangeCut::Hold; + } + + let duration_before = clip_timeline_duration(timeline); + let segment = &mut timeline.segments[index]; + let source_start = segment.start + local_start * segment.timescale; + let source_end = segment.start + local_end * segment.timescale; + if whole { + timeline.segments.remove(index); + timeline.transitions.retain(|transition| { + let at = transition.segment_index as usize; + at != index && at != index + 1 + }); + for transition in timeline.transitions.iter_mut() { + if transition.segment_index as usize > index { + transition.segment_index -= 1; + } + } + } else if local_start == 0.0 { + segment.start = source_end; + } else if local_end == duration { + segment.end = source_start; + } else { + let mut tail = segment.clone(); + tail.start = source_end; + segment.end = source_start; + timeline.segments.insert(index + 1, tail); + for transition in timeline.transitions.iter_mut() { + if transition.segment_index as usize > index { + transition.segment_index += 1; + } + } + } + let shift = (duration_before - clip_timeline_duration(timeline)).max(0.0); + ripple_delete_output_tracks(timeline, output_start, output_end, shift); + RangeCut::Applied +} + +pub fn ripple_insert_output_tracks( + timeline: &mut TimelineConfiguration, + boundary: f64, + shift: f64, +) { + use crate::editor_clips::{ripple_keyboard_track, ripple_track}; + ripple_track(&mut timeline.style_segments, boundary, shift); + ripple_track(&mut timeline.image_segments, boundary, shift); + ripple_track(&mut timeline.zoom_segments, boundary, shift); + ripple_track(&mut timeline.scene_segments, boundary, shift); + ripple_track(&mut timeline.text_segments, boundary, shift); + ripple_track(&mut timeline.caption_segments, boundary, shift); + ripple_keyboard_track(&mut timeline.keyboard_segments, boundary, shift); + ripple_track(&mut timeline.audio_segments, boundary, shift); + for segment in &mut timeline.mask_segments { + if segment.start >= boundary { + segment.start += shift; + segment.end += shift; + } else if segment.end > boundary { + let local = boundary - segment.start; + for time in segment + .keyframes + .position + .iter_mut() + .map(|key| &mut key.time) + .chain(segment.keyframes.size.iter_mut().map(|key| &mut key.time)) + .chain( + segment + .keyframes + .intensity + .iter_mut() + .map(|key| &mut key.time), + ) + { + if *time >= local { + *time += shift; + } + } + segment.end += shift; + } + } + for segment in &mut timeline.camera3d_segments { + if segment.start >= boundary { + segment.start += shift; + segment.end += shift; + } else if segment.end > boundary { + let local = boundary - segment.start; + for track in segment.tracks.all_tracks_mut() { + for keyframe in track.iter_mut() { + if keyframe.time >= local { + keyframe.time += shift; + } + } + } + segment.end += shift; + } + } +} + /// The seven plain splits. 3D is **not** among them: `splitCamera3DSegment` /// rebuilds both halves' pose tracks around the pose the segment held at the /// cut (`ED/context.ts:640-676`), which needs the keyframe evaluator; see the diff --git a/apps/desktop-gpui/src/editor_tabs.rs b/apps/desktop-gpui/src/editor_tabs.rs index d0eac8334f5..cd2ed2b09dc 100644 --- a/apps/desktop-gpui/src/editor_tabs.rs +++ b/apps/desktop-gpui/src/editor_tabs.rs @@ -2903,7 +2903,7 @@ impl EditorWindow { .full_width() .disabled(generating || any_deleting) .on_click(cx.listener(|this, _, window, cx| { - this.generate_captions_clicked(window, cx); + this.generate_transcript(true, window, cx); })), ); } @@ -3501,7 +3501,7 @@ impl EditorWindow { /// -- reattach the progress poller. Deferred out of render because it /// mutates the sidebar state, and keyed by entity so it runs once per /// window. - fn ensure_captions_init(&self, cx: &mut Context) { + pub(crate) fn ensure_captions_init(&self, cx: &mut Context) { static INITIALISED: LazyLock>> = LazyLock::new(|| Mutex::new(HashSet::new())); if !INITIALISED @@ -3572,11 +3572,14 @@ impl EditorWindow { /// tab reads the download, so only the sidebar is rebuilt. pub(crate) fn repaint_caption_download(&mut self, cx: &mut Context) { self.invalidate_sidebar(cx); + if self.transcript.open { + self.invalidate_transcript(cx); + } } /// `downloadModel` (`CaptionsTab.tsx:643-690`). The download runs on the /// tokio runtime and survives this window; the poll task repaints. - fn start_caption_model_download(&mut self, cx: &mut Context) { + pub(crate) fn start_caption_model_download(&mut self, cx: &mut Context) { let model = self.selected_caption_model().name; if !transcription::begin_download(model) { return; @@ -3604,8 +3607,15 @@ impl EditorWindow { /// `generateCaptions` (`CaptionsTab.tsx:715-757`): transcribe on the /// tokio blocking pool, then apply the result through one `edit_project` - /// write so a regenerate is a single undo entry. - fn generate_captions_clicked(&mut self, window: &mut Window, cx: &mut Context) { + /// write so a regenerate is a single undo entry. The transcript panel + /// passes `show_captions: false`: transcribing to edit by text must not + /// switch subtitles on. + pub(crate) fn generate_transcript( + &mut self, + show_captions: bool, + window: &mut Window, + cx: &mut Context, + ) { let Some(summary) = self.summary() else { return; }; @@ -3661,6 +3671,7 @@ impl EditorWindow { segments, &recording_durations, recording_duration, + show_captions, window, cx, ); @@ -3697,11 +3708,16 @@ impl EditorWindow { segments: Vec, recording_durations: &[f64], recording_duration: f64, + show_captions: bool, window: &mut Window, cx: &mut Context, ) { let recording_durations = recording_durations.to_vec(); self.edit_project("caption-generate", window, cx, move |project| { + let shown = project + .captions + .as_ref() + .is_some_and(|captions| captions.settings.enabled); crate::style_presets::seed_default_captions(project); transcription::apply_caption_result( project, @@ -3709,10 +3725,15 @@ impl EditorWindow { &recording_durations, recording_duration, ); + if !show_captions && let Some(captions) = project.captions.as_mut() { + captions.settings.enabled = shown; + } true }); - // `setEditorState("timeline", "tracks", "caption", true)`. - self.tracks.caption = true; + if show_captions { + // `setEditorState("timeline", "tracks", "caption", true)`. + self.tracks.caption = true; + } cx.notify(); } diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs index cf7862f2005..bf66e6aaac0 100644 --- a/apps/desktop-gpui/src/editor_window.rs +++ b/apps/desktop-gpui/src/editor_window.rs @@ -246,6 +246,12 @@ fn editor_player_width(viewport_width: f32) -> f32 { (viewport_width - SIDEBAR_WIDTH - 8. - 16. - 2.).max(0.) } +const TRANSCRIPT_GRIP_WIDTH: f32 = 12.; + +fn transcript_row_width(viewport_width: f32) -> f32 { + (viewport_width - 16. - TRANSCRIPT_GRIP_WIDTH).max(0.) +} + // --------------------------------------------------------------------------- // Timeline metrics -- all of them now live in [`crate::editor_timeline`], // which owns the strip itself (`routes/editor/Timeline/index.tsx:62-68`). @@ -743,6 +749,7 @@ enum EditorSection { Transport, Sidebar, Timeline, + Transcript, } struct EditorSectionView { @@ -797,6 +804,7 @@ impl Render for EditorSectionView { editor.render_preparing_sidebar(false), ) } + EditorSection::Transcript => editor.render_transcript(window, cx), EditorSection::Timeline => { let viewport_width: f32 = window.viewport_size().width.into(); let viewport_height: f32 = window.viewport_size().height.into(); @@ -1493,7 +1501,7 @@ pub struct EditorWindow { clip_anim_generation: u64, /// `editorInstance.recordings.segments[i].display.duration`, which the clip /// trim clamps read (`TL/ClipTrack.tsx:1160-1162`). - clip_display_durations: Vec, + pub(crate) clip_display_durations: Vec, /// `editorInstance.recordingDuration` = `recordings.duration()`. recording_duration: f64, /// `meta().hasCamera` and "more than one recording clip", the two facts @@ -1622,6 +1630,8 @@ pub struct EditorWindow { /// The Clips layout mode (`ClipsSidebar.tsx`): while open, the config /// sidebar's column draws the clips sidebar instead. pub(crate) clips: crate::editor_clips::ClipsState, + pub(crate) transcript: crate::transcript::TranscriptState, + transcript_view: Entity, } struct PresetsMenu { @@ -2072,6 +2082,10 @@ impl EditorWindow { let editor = editor.clone(); move |cx| EditorSectionView::new(&editor, EditorSection::Sidebar, cx) }); + let transcript_view = cx.new({ + let editor = editor.clone(); + move |cx| EditorSectionView::new(&editor, EditorSection::Transcript, cx) + }); let timeline_view = cx.new(move |cx| EditorSectionView::new(&editor, EditorSection::Timeline, cx)); @@ -2209,12 +2223,22 @@ impl EditorWindow { caption_sync_signature: None, export: None, clips: crate::editor_clips::ClipsState::default(), + transcript: crate::transcript::TranscriptState::new(cx.focus_handle()), + transcript_view, } } /// `frameNumberToRender`'s time: `previewTime ?? playbackTime` /// (`Editor.tsx:515-519`), floored at zero. /// Where the playhead stands, for the panels that mark the pose on it. + fn player_width(&self, viewport_width: f32) -> f32 { + if self.transcript.open { + transcript_row_width(viewport_width) * self.transcript.player_share + } else { + editor_player_width(viewport_width) + } + } + pub(crate) fn playhead_time(&self) -> f64 { self.playhead } @@ -2309,6 +2333,7 @@ impl EditorWindow { self.canvas_selection = None; self.project = config; self.synchronize_caption_track(true); + self.transcript.dirty = true; self.history = ProjectHistory::new(self.project.clone()); self.tracks = TrackLanes::from_project(&self.project, self.has_camera); self.rebuild_timeline(); @@ -2526,7 +2551,7 @@ impl EditorWindow { ) } - fn edit_timeline_project( + pub(crate) fn edit_timeline_project( &mut self, change: impl FnOnce(&mut ProjectConfiguration) -> bool, window: &mut Window, @@ -2547,7 +2572,7 @@ impl EditorWindow { /// `note_transform` exists: a drag's arithmetic is only checkable end to /// end if the numbers come out of the running app. Intermediate drag /// frames log at `debug`; the line below is the settled one. - fn note_edit(&self, reason: &'static str, track: Option) { + pub(crate) fn note_edit(&self, reason: &'static str, track: Option) { let timeline = self.project.timeline.as_ref(); // The affected track's boxes, four decimals, so a scripted drag's // predicted seconds can be checked against what actually landed. @@ -2623,6 +2648,7 @@ impl EditorWindow { } self.synchronize_caption_track(false); self.history.record(&self.project); + self.transcript.dirty = true; self.style_presets.close_menu(); if rebuild_timeline { self.rebuild_timeline(); @@ -2641,6 +2667,7 @@ impl EditorWindow { } self.synchronize_caption_track(false); self.history.record(&self.project); + self.transcript.dirty = true; self.publish_project(); cx.notify(); } @@ -2739,7 +2766,7 @@ impl EditorWindow { /// `projectHistory.undo()` -- reconcile the previous snapshot back over the /// store. The playhead is not moved and the selection is not restored; /// neither is in the snapshot (`editorState` is a separate store). - fn undo(&mut self, window: &mut Window, cx: &mut Context) { + pub(crate) fn undo(&mut self, window: &mut Window, cx: &mut Context) { self.close_frame_controls(window, cx); self.end_field_edit(cx); self.close_color_picker(cx); @@ -2751,7 +2778,7 @@ impl EditorWindow { self.note_edit("undo", None); } - fn redo(&mut self, window: &mut Window, cx: &mut Context) { + pub(crate) fn redo(&mut self, window: &mut Window, cx: &mut Context) { self.close_frame_controls(window, cx); self.end_field_edit(cx); self.close_color_picker(cx); @@ -2793,6 +2820,9 @@ impl EditorWindow { != crate::editor_sidebar::is_none_background(&config); self.project = config; self.synchronize_caption_track(false); + self.transcript.dirty = true; + self.transcript.selection = None; + self.transcript.hovered_cut = None; self.rebuild_timeline(); if self.animated_gradient_config().is_some() { self.sidebar.source_tab = crate::editor_sidebar::initial_source_tab(&self.project); @@ -3240,6 +3270,7 @@ impl EditorWindow { self.last_playhead_redraw = Instant::now(); self.invalidate_playback_chrome(window, cx); + self.transcript_sync_active(true, cx); } /// The pause half of `handlePlayPauseClick`, also used by the end-of-media @@ -3426,10 +3457,20 @@ impl EditorWindow { /// picture for one decode instead of paying a warmup per tick. pub fn seek_to_time(&mut self, time: f64, cx: &mut Context) { if self.apply_seek(time) { + self.transcript_sync_active(true, cx); cx.notify(); } } + pub(crate) fn play_range(&mut self, from: f64, until: f64, cx: &mut Context) { + if self.playing { + self.stop_playback(cx); + } + self.start_playback(from.max(0.0), cx); + self.play_until = Some(until); + cx.notify(); + } + /// One pointer move of a ruler scrub. While paused, the playhead is read /// by the timeline, the transport clock and what the window itself renders /// (the canvas overlay, the clip popover), so this invalidates those the @@ -3442,6 +3483,7 @@ impl EditorWindow { if !self.apply_seek(time) { return; } + self.transcript_sync_active(true, cx); if self.playing || self.ordinary_handoff_frame.is_some() { cx.notify(); return; @@ -4191,6 +4233,10 @@ impl EditorWindow { self.sidebar_view.update(cx, |_, cx| cx.notify()); } + pub(crate) fn invalidate_transcript(&mut self, cx: &mut Context) { + self.transcript_view.update(cx, |_, cx| cx.notify()); + } + fn set_hovered_track( &mut self, track: Option, @@ -10071,16 +10117,10 @@ impl EditorWindow { fn render_header(&self, window: &Window, cx: &mut Context) -> impl IntoElement { let theme = self.theme; let name_focused = self.name_input.read(cx).focus_handle().is_focused(window); - let has_captions = self.project.captions.as_ref().is_some_and(|captions| { - captions - .segments - .iter() - .any(|segment| !segment.words.is_empty()) - }); let compact = compact_header_controls( f32::from(window.viewport_size().width), cfg!(target_os = "windows"), - has_captions, + true, ); let drag_area = |area: gpui::Div| { @@ -10215,15 +10255,7 @@ impl EditorWindow { })), ) .child(self.render_clips_pill(compact, cx)) - // ``: the button only exists - // once a transcript with words does. - .children(has_captions.then(|| { - self.header_pill( - "icons/captions.svg", - tr::editor::window::header::captions(), - compact, - ) - })) + .child(self.render_transcript_pill(compact, cx)) .child(div().w(px(6.)).flex_none()) .when(self.sharing.is_some(), |group| { group.child(self.render_reupload_button(cx)) @@ -10262,20 +10294,53 @@ impl EditorWindow { .bg(Hsla::from(self.theme.editor.line_strong)) } - /// The Captions toggle. Inert -- the transcript layout mode does not exist - /// yet. Clips has its own live button (`crate::editor_clips`). - fn header_pill( - &self, - icon: &'static str, - label: &'static str, - compact: bool, - ) -> impl IntoElement { + fn render_transcript_pill(&self, compact: bool, cx: &mut Context) -> impl IntoElement { let theme = self.theme; - ui::EditorButton::plain(&theme, "editor-captions-pill") - .left_icon(icon) - .when(!compact, |button| button.label(label)) - .tooltip(&theme, label) - .disabled(true) + ui::EditorButton::plain(&theme, "editor-transcript-pill") + .left_icon("icons/scan-text.svg") + .when(!compact, |button| { + button.label(tr::editor::window::header::transcript()) + }) + .tooltip(&theme, tr::editor::window::header::transcript_tooltip()) + .pressed(self.transcript.open) + .disabled(!self.project_ready()) + .on_click(cx.listener(|this, _, window, cx| this.toggle_transcript(window, cx))) + } + + fn render_transcript_grip(&self, cx: &mut Context) -> impl IntoElement { + let theme = self.theme; + div() + .id("transcript-resize-handle") + .group("transcript-grip") + .flex_none() + .w(px(TRANSCRIPT_GRIP_WIDTH)) + .h_full() + .flex() + .items_center() + .justify_center() + .cursor(gpui::CursorStyle::ResizeLeftRight) + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, event: &MouseDownEvent, _window, cx| { + this.transcript.resize = + Some((f32::from(event.position.x), this.transcript.player_share)); + cx.notify(); + }), + ) + .child( + div() + .w(px(4.)) + .h(px(40.)) + .rounded(px(2.)) + .bg(if self.transcript.resize.is_some() { + Hsla::from(theme.editor.text_3) + } else { + Hsla::from(theme.editor.line_strong) + }) + .group_hover("transcript-grip", |this| { + this.bg(Hsla::from(theme.editor.text_3)) + }), + ) } /// The Export button: the one primary control in the editor, a vertical @@ -10474,7 +10539,7 @@ impl EditorWindow { /// preview-resolution control on the right. fn render_player_toolbar(&self, window: &Window, cx: &mut Context) -> impl IntoElement { let theme = self.theme; - let narrow = editor_player_width(f32::from(window.viewport_size().width)) < 560.; + let narrow = self.player_width(f32::from(window.viewport_size().width)) < 560.; div() .w_full() .h_full() @@ -10787,7 +10852,7 @@ impl EditorWindow { fn render_transport(&self, window: &Window, cx: &mut Context) -> impl IntoElement { let theme = self.theme; let editor = theme.editor; - let player_width = editor_player_width(f32::from(window.viewport_size().width)); + let player_width = self.player_width(f32::from(window.viewport_size().width)); let compact = player_width < 760.; let narrow = player_width < 620.; let total = self.total_duration(); @@ -12305,7 +12370,14 @@ impl Render for EditorWindow { div() .flex() .flex_col() - .flex_1() + .when(!self.transcript.open, |card| card.flex_1()) + .when(self.transcript.open, |card| { + card.flex_none().w(px(transcript_row_width( + viewport_width, + ) * self + .transcript + .player_share)) + }) .min_w_0() .min_h_0() .rounded(px(12.)) @@ -12319,15 +12391,26 @@ impl Render for EditorWindow { // The 8px gutter is the wrapper's, not the // sidebar view's: a margin inside a cached // element is not honoured. - .child( - div().flex_none().h_full().pl(px(8.)).child( - self.sidebar_view.clone().cached( - StyleRefinement::default() - .w(px(SIDEBAR_WIDTH)) - .h_full(), + .when(!self.transcript.open, |row| { + row.child( + div().flex_none().h_full().pl(px(8.)).child( + self.sidebar_view.clone().cached( + StyleRefinement::default() + .w(px(SIDEBAR_WIDTH)) + .h_full(), + ), ), - ), - ), + ) + }) + .when(self.transcript.open, |row| { + row.child(self.render_transcript_grip(cx)).child( + div().flex_1().min_w_0().h_full().child( + self.transcript_view + .clone() + .cached(StyleRefinement::default().size_full()), + ), + ) + }), ) // The timeline card: the wrapper is owned here so // `render_timeline` keeps laying out inside a plain @@ -12437,6 +12520,19 @@ impl Render for EditorWindow { ) .cursor(gpui::CursorStyle::ResizeRow) })) + .children(self.transcript.resize.is_some().then(|| { + ui::Slider::drag_layer( + "transcript-split-drag", + cx.listener(|this, event: &MouseMoveEvent, window, cx| { + let row = transcript_row_width(f32::from(window.viewport_size().width)); + this.transcript_resize_move(f32::from(event.position.x), row, cx); + }), + cx.listener(|this, _: &MouseUpEvent, _window, cx| { + this.transcript_resize_end(cx); + }), + ) + .cursor(gpui::CursorStyle::ResizeLeftRight) + })) .children(self.zoom_slider_drag.then(|| { ui::Slider::drag_layer( "timeline-zoom-drag", diff --git a/apps/desktop-gpui/src/i18n/editor_shell_surface_tests.rs b/apps/desktop-gpui/src/i18n/editor_shell_surface_tests.rs index 30f0a643746..02c454bd608 100644 --- a/apps/desktop-gpui/src/i18n/editor_shell_surface_tests.rs +++ b/apps/desktop-gpui/src/i18n/editor_shell_surface_tests.rs @@ -10,6 +10,7 @@ pub(super) fn is_editor_shell_surface_key(key: &str) -> bool { "editor.preparing.", "editor.tabs.", "editor.timeline.", + "editor.transcript.", "editor.window.", "ui.", ] @@ -18,6 +19,16 @@ pub(super) fn is_editor_shell_surface_key(key: &str) -> bool { } const FORMATTED: &[&str] = &[ + "editor.transcript.fillers.remove_all", + "editor.transcript.pauses.summary", + "editor.transcript.restore_hint", + "editor.transcript.search_count", + "editor.transcript.seconds", + "editor.transcript.selection", + "editor.transcript.selection_cut", + "editor.transcript.skipped_hold", + "editor.transcript.skipped_transition", + "editor.transcript.words", "editor.window.clip_menu.transition_seconds", "editor.markers.button", "editor.markers.default_name", @@ -1025,7 +1036,6 @@ fn editor_shell_surfaces_match_the_literals_they_replaced() { tr::editor::window::frame::windows_description(), "Title bar with window controls", ), - (tr::editor::window::header::captions(), "Captions"), ( tr::editor::window::header::delete_recording(), "Delete recording", @@ -1036,6 +1046,105 @@ fn editor_shell_surfaces_match_the_literals_they_replaced() { "Open recording bundle", ), (tr::editor::window::header::presets(), "Presets"), + (tr::editor::transcript::cleanup(), "Clean up"), + ( + tr::editor::transcript::cleanup_tooltip(), + "Remove filler words and shorten pauses", + ), + (tr::editor::transcript::delete_matches(), "Delete all"), + ( + tr::editor::transcript::delete_matches_tooltip(), + "Cut every match from the video", + ), + ( + tr::editor::transcript::empty_description(), + "Transcribe this recording on this computer, then edit the video by editing its text.", + ), + (tr::editor::transcript::empty_title(), "No transcript yet"), + ( + tr::editor::transcript::fillers::discourse(), + "Filler phrases", + ), + ( + tr::editor::transcript::fillers::discourse_hint(), + "like, you know, so", + ), + ( + tr::editor::transcript::fillers::false_start(), + "False starts", + ), + ( + tr::editor::transcript::fillers::false_start_hint(), + "we should, we need", + ), + (tr::editor::transcript::fillers::hesitation(), "Hesitations"), + ( + tr::editor::transcript::fillers::hesitation_hint(), + "um, uh, hmm", + ), + (tr::editor::transcript::fillers::keep(), "Keep this one"), + (tr::editor::transcript::fillers::listen(), "Listen"), + ( + tr::editor::transcript::fillers::none(), + "No filler words left in these categories", + ), + (tr::editor::transcript::fillers::remove(), "Remove this one"), + ( + tr::editor::transcript::fillers::repetition(), + "Repeated words", + ), + ( + tr::editor::transcript::fillers::repetition_hint(), + "the the, I I", + ), + (tr::editor::transcript::fillers::title(), "Filler words"), + ( + tr::editor::transcript::hint(), + "Click a word to jump to it. Select words and press Delete to cut them from the video.", + ), + (tr::editor::transcript::next_match(), "Next match"), + ( + tr::editor::transcript::no_audio(), + "This recording has no audio to transcribe.", + ), + (tr::editor::transcript::pauses::apply(), "Shorten"), + (tr::editor::transcript::pauses::keep(), "Shorten to"), + ( + tr::editor::transcript::pauses::longer_than(), + "Pauses longer than", + ), + ( + tr::editor::transcript::pauses::none(), + "No pauses that long", + ), + (tr::editor::transcript::pauses::title(), "Pauses"), + (tr::editor::transcript::previous_match(), "Previous match"), + ( + tr::editor::transcript::restore_blocked(), + "This part was cut on the timeline. Use Undo or drag the clip edge to bring it back.", + ), + ( + tr::editor::transcript::restore_transition(), + "Remove the transition next to this cut to restore it.", + ), + (tr::editor::transcript::search(), "Find"), + (tr::editor::transcript::search_none(), "No matches"), + ( + tr::editor::transcript::search_placeholder(), + "Find in transcript", + ), + ( + tr::editor::transcript::skipped_last_clip(), + "The last clip cannot be cut away.", + ), + (tr::editor::transcript::title(), "Transcript"), + (tr::editor::transcript::transcribe(), "Transcribe"), + (tr::editor::transcript::transcribing(), "Transcribing…"), + (tr::editor::window::header::transcript(), "Transcript"), + ( + tr::editor::window::header::transcript_tooltip(), + "Edit by transcript", + ), ( tr::editor::window::image::changed(), "This image changed while choosing a replacement. Select it and try again.", diff --git a/apps/desktop-gpui/src/main.rs b/apps/desktop-gpui/src/main.rs index c87a59cab7e..507f301b65d 100644 --- a/apps/desktop-gpui/src/main.rs +++ b/apps/desktop-gpui/src/main.rs @@ -99,6 +99,7 @@ mod target_overlay; mod target_thumbnails; mod teleprompter_window; mod theme; +mod transcript; mod transcription; mod tray; mod ui; diff --git a/apps/desktop-gpui/src/transcript.rs b/apps/desktop-gpui/src/transcript.rs new file mode 100644 index 00000000000..613aa7d12bc --- /dev/null +++ b/apps/desktop-gpui/src/transcript.rs @@ -0,0 +1,323 @@ +//! Text-based editing: the transcript panel beside the player, where deleting +//! words cuts them out of the video. +//! +//! The source of truth never changes shape. Caption words stay in source time +//! in `project.captions`, the clip list in `project.timeline` says what plays, +//! and a word is shown as cut when less than half of it plays. Deleting words +//! therefore only edits clips (with the same all-track ripple the timeline's +//! own delete uses), a cut made on the timeline shows up struck through here, +//! and restoring a word grows the clips back over it. + +pub(crate) mod automation; +pub(crate) mod cuts; +pub(crate) mod energy; +pub(crate) mod model; +#[cfg(test)] +mod tests; +mod view; + +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; +use std::ops::Range; +use std::rc::Rc; +use std::sync::Arc; +use std::time::Instant; + +use cap_project::disfluency::DisfluencyKind; +use gpui::{FocusHandle, ListAlignment, ListState, TextLayout, px}; + +use self::energy::EnergyEnvelope; +use self::model::{TranscriptDoc, TranscriptEdl}; + +pub(crate) const STORE_SECTION: &str = "editorTranscript"; +const SPLIT_KEY: &str = "playerShare"; +const PAUSE_LONGER_KEY: &str = "pauseLongerThan"; +const PAUSE_KEEP_KEY: &str = "pauseKeep"; + +pub(crate) const MIN_PLAYER_SHARE: f32 = 0.3; +pub(crate) const MAX_PLAYER_SHARE: f32 = 0.75; +const DEFAULT_PLAYER_SHARE: f32 = 0.55; + +pub(crate) const DEFAULT_PAUSE_LONGER_THAN: f64 = 1.0; +pub(crate) const DEFAULT_PAUSE_KEEP: f64 = 0.5; +pub(crate) const PAUSE_LONGER_RANGE: (f64, f64) = (0.3, 5.0); +pub(crate) const PAUSE_KEEP_RANGE: (f64, f64) = (0.1, 2.0); + +/// After the user scrolls the transcript by hand, playback stops pulling it +/// along for this long. +pub(crate) const FOLLOW_PAUSE: std::time::Duration = std::time::Duration::from_secs(4); + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct WordSelection { + pub anchor: usize, + pub focus: usize, +} + +impl WordSelection { + pub fn single(word: usize) -> Self { + Self { + anchor: word, + focus: word, + } + } + + pub fn range(self) -> Range { + self.anchor.min(self.focus)..self.anchor.max(self.focus) + 1 + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum DragUnit { + Word, + Sentence, + Paragraph, +} + +#[derive(Clone, Copy, Debug)] +pub(crate) struct WordDrag { + pub unit: DragUnit, + pub origin: (usize, usize), +} + +pub(crate) struct SearchState { + pub input: gpui::Entity, + pub matches: Arc>>, + pub current: usize, + pub query: String, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum CleanupTab { + Fillers, + Pauses, +} + +pub(crate) struct CleanupState { + pub open: bool, + pub tab: CleanupTab, + pub categories: [bool; 4], + pub ignored: HashSet, + pub pause_longer_than: f64, + pub pause_keep: f64, + pub filler_rows: gpui::UniformListScrollHandle, + pub pause_rows: gpui::UniformListScrollHandle, +} + +impl CleanupState { + fn new() -> Self { + let section = crate::store::store_section(STORE_SECTION); + let read = |key: &str, default: f64, (min, max): (f64, f64)| { + section + .get(key) + .and_then(serde_json::Value::as_f64) + .filter(|value| value.is_finite()) + .map_or(default, |value| value.clamp(min, max)) + }; + Self { + open: false, + tab: CleanupTab::Fillers, + categories: [true, true, true, false], + ignored: HashSet::new(), + pause_longer_than: read( + PAUSE_LONGER_KEY, + DEFAULT_PAUSE_LONGER_THAN, + PAUSE_LONGER_RANGE, + ), + pause_keep: read(PAUSE_KEEP_KEY, DEFAULT_PAUSE_KEEP, PAUSE_KEEP_RANGE), + filler_rows: gpui::UniformListScrollHandle::new(), + pause_rows: gpui::UniformListScrollHandle::new(), + } + } + + pub fn category_enabled(&self, kind: DisfluencyKind) -> bool { + self.categories[category_index(kind)] + } + + pub fn persist_pauses(&self) { + crate::store::set_store_setting( + STORE_SECTION, + PAUSE_LONGER_KEY, + serde_json::json!(self.pause_longer_than), + ); + crate::store::set_store_setting( + STORE_SECTION, + PAUSE_KEEP_KEY, + serde_json::json!(self.pause_keep), + ); + } +} + +pub(crate) fn category_index(kind: DisfluencyKind) -> usize { + match kind { + DisfluencyKind::Hesitation => 0, + DisfluencyKind::Repetition => 1, + DisfluencyKind::FalseStart => 2, + DisfluencyKind::Discourse => 3, + } +} + +pub(crate) struct TranscriptState { + pub open: bool, + pub player_share: f32, + pub doc: Option>, + pub edl: Option>, + /// Set by every project change; the models are only re-derived while the + /// panel is open, so the feature costs nothing when it is closed. + pub dirty: bool, + edl_key: u64, + pub list: ListState, + pub selection: Option, + pub caret: Option, + pub drag: Option, + pub active: Option, + pub hovered_cut: Option, + pub user_scrolled: Option, + pub search: Option, + pub cleanup: CleanupState, + pub focus: FocusHandle, + pub layouts: Rc>>, + pub resize: Option<(f32, f32)>, + pub energy: Option>, + pub energy_loading: bool, + pub energy_offsets: Vec<(f64, f64)>, +} + +impl TranscriptState { + pub fn new(focus: FocusHandle) -> Self { + let player_share = crate::store::store_section(STORE_SECTION) + .get(SPLIT_KEY) + .and_then(serde_json::Value::as_f64) + .filter(|value| value.is_finite()) + .map_or(DEFAULT_PLAYER_SHARE, |value| { + (value as f32).clamp(MIN_PLAYER_SHARE, MAX_PLAYER_SHARE) + }); + Self { + open: false, + player_share, + doc: None, + edl: None, + dirty: true, + edl_key: 0, + list: ListState::new(0, ListAlignment::Top, px(600.)), + selection: None, + caret: None, + drag: None, + active: None, + hovered_cut: None, + user_scrolled: None, + search: None, + cleanup: CleanupState::new(), + focus, + layouts: Rc::new(RefCell::new(HashMap::new())), + resize: None, + energy: None, + energy_loading: false, + energy_offsets: Vec::new(), + } + } + + pub fn persist_split(&self) { + crate::store::set_store_setting( + STORE_SECTION, + SPLIT_KEY, + serde_json::json!(self.player_share), + ); + } + + pub fn refresh( + &mut self, + project: &cap_project::ProjectConfiguration, + recording_durations: &[f64], + ) -> bool { + if !self.dirty && self.doc.is_some() == has_words(project) { + return false; + } + self.dirty = false; + let Some(captions) = project.captions.as_ref().filter(|_| has_words(project)) else { + let changed = self.doc.is_some(); + self.doc = None; + self.edl = None; + self.list.reset(0); + self.selection = None; + self.caret = None; + self.active = None; + return changed; + }; + let mut changed = false; + let signature = model::captions_signature(Some(captions)); + if self + .doc + .as_ref() + .is_none_or(|doc| doc.signature != signature) + { + let doc = TranscriptDoc::build(captions); + self.list.reset(doc.paragraphs.len()); + self.layouts.borrow_mut().clear(); + self.selection = None; + self.caret = None; + self.active = None; + self.hovered_cut = None; + self.cleanup.ignored.clear(); + self.doc = Some(Arc::new(doc)); + self.edl_key = 0; + changed = true; + } + let key = timeline_key(project.timeline.as_ref(), recording_durations); + if changed || key != self.edl_key || self.edl.is_none() { + self.edl_key = key; + let doc = self.doc.as_ref().expect("document was just built"); + self.edl = project + .timeline + .as_ref() + .map(|timeline| Arc::new(TranscriptEdl::build(doc, timeline, recording_durations))); + self.hovered_cut = None; + changed = true; + } + if let (Some(search), Some(doc)) = (self.search.as_mut(), self.doc.as_ref()) + && changed + { + search.matches = Arc::new(view::find_matches(doc, &search.query)); + search.current = search.current.min(search.matches.len().saturating_sub(1)); + } + changed + } +} + +pub(crate) fn has_words(project: &cap_project::ProjectConfiguration) -> bool { + project.captions.as_ref().is_some_and(|captions| { + captions + .segments + .iter() + .any(|segment| !segment.words.is_empty()) + }) +} + +fn timeline_key( + timeline: Option<&cap_project::TimelineConfiguration>, + recording_durations: &[f64], +) -> u64 { + use std::hash::{Hash, Hasher}; + let mut hasher = std::hash::DefaultHasher::new(); + for duration in recording_durations { + duration.to_bits().hash(&mut hasher); + } + if let Some(timeline) = timeline { + for segment in &timeline.segments { + segment.recording_clip.hash(&mut hasher); + segment.start.to_bits().hash(&mut hasher); + segment.end.to_bits().hash(&mut hasher); + segment.timescale.to_bits().hash(&mut hasher); + } + for transition in &timeline.transitions { + transition.segment_index.hash(&mut hasher); + transition.duration.to_bits().hash(&mut hasher); + } + for (start, end) in timeline.hold_windows() { + start.to_bits().hash(&mut hasher); + end.to_bits().hash(&mut hasher); + } + } else { + 1u8.hash(&mut hasher); + } + hasher.finish() +} diff --git a/apps/desktop-gpui/src/transcript/automation.rs b/apps/desktop-gpui/src/transcript/automation.rs new file mode 100644 index 00000000000..74dd2d2d630 --- /dev/null +++ b/apps/desktop-gpui/src/transcript/automation.rs @@ -0,0 +1,378 @@ +//! `CAP_GPUI_AUTO_TRANSCRIPT=,...` drives the transcript panel for +//! screenshots, perf runs and export checks. Actions: `open`, `seed:`, +//! `transcribe`, `select:-`, `delete`, `cleanup[:pauses]`, `fillers`, +//! `pauses`, `cuts:`, `search:`, `seek:`, `play`, `stop`, +//! `wait:`, `scroll:`, `follow:`, `undo`, `redo`, +//! `hover-cut`, `restore`, `dump:`. + +use std::time::{Duration, Instant}; + +use gpui::{AsyncApp, WindowHandle, px}; + +use super::WordSelection; +use crate::editor_window::EditorWindow; + +const READY_TIMEOUT: Duration = Duration::from_secs(60); +const TRANSCRIBE_TIMEOUT: Duration = Duration::from_secs(1800); +const FRAME: Duration = Duration::from_millis(16); + +fn ms(duration: Duration) -> f64 { + duration.as_secs_f64() * 1000.0 +} + +async fn sleep(cx: &AsyncApp, duration: Duration) { + cx.background_executor().timer(duration).await; +} + +fn draw(handle: WindowHandle, cx: &mut AsyncApp) -> f64 { + cx.update(|cx| crate::draw_bench::timed_draw(handle.into(), cx)) + .map_or(f64::NAN, ms) +} + +fn seeded_captions(words: usize, duration: f64) -> cap_project::CaptionsData { + const VOCABULARY: &[&str] = &[ + "today", "we", "are", "going", "to", "look", "at", "how", "the", "export", "settings", + "work", "and", "why", "this", "timeline", "makes", "editing", "faster", "for", "everyone", + "on", "team", "when", "you", "record", "a", "quick", "update", + ]; + let step = ((duration - 1.0) / words.max(1) as f64).max(0.05); + let mut out = Vec::with_capacity(words); + let mut time = 0.5; + for index in 0..words { + let mut text = if index % 40 == 20 { + "um,".to_string() + } else { + VOCABULARY[(index * 7 + index / 13) % VOCABULARY.len()].to_string() + }; + if index % 13 == 12 { + text.push('.'); + } + let pause = if index % 13 == 12 { step * 0.6 } else { 0.0 }; + out.push(cap_project::CaptionWord { + text, + start: time as f32, + end: (time + step * 0.7) as f32, + }); + time += step + pause; + if time > duration - 0.5 { + break; + } + } + cap_project::CaptionsData { + segments: out + .chunks(6) + .enumerate() + .map(|(index, chunk)| cap_project::CaptionSegment { + id: format!("segment-{index}"), + start: chunk[0].start, + end: chunk[chunk.len() - 1].end, + text: chunk + .iter() + .map(|word| word.text.as_str()) + .collect::>() + .join(" "), + words: chunk.to_vec(), + }) + .collect(), + settings: Default::default(), + source_timed: true, + } +} + +pub(crate) async fn run(handle: WindowHandle, cx: &mut AsyncApp) { + let Ok(spec) = std::env::var("CAP_GPUI_AUTO_TRANSCRIPT") else { + return; + }; + let started = Instant::now(); + while !handle + .update(cx, |view, _, _| { + view.latest_frame.is_some() && view.project_ready() + }) + .unwrap_or(false) + { + if started.elapsed() > READY_TIMEOUT { + eprintln!("transcript-auto: the editor never became ready"); + return; + } + sleep(cx, Duration::from_millis(50)).await; + } + sleep(cx, Duration::from_millis(500)).await; + + for action in spec.split(',').map(str::trim).filter(|a| !a.is_empty()) { + let (name, argument) = action.split_once(':').unwrap_or((action, "")); + let started = Instant::now(); + let detail = handle.update(cx, |view, window, cx| -> String { + match name { + "open" => { + if !view.transcript.open { + view.toggle_transcript(window, cx); + } + format!( + "{} words, {} paragraphs", + view.transcript + .doc + .as_ref() + .map_or(0, |doc| doc.words.len()), + view.transcript + .doc + .as_ref() + .map_or(0, |doc| doc.paragraphs.len()) + ) + } + "seed" => { + let words = argument.parse().unwrap_or(20_000); + let duration = view.total_duration(); + let captions = seeded_captions(words, duration); + let count: usize = captions.segments.iter().map(|s| s.words.len()).sum(); + view.edit_timeline_project( + |project| { + project.captions = Some(captions); + true + }, + window, + cx, + ); + format!("{count} words over {duration:.1}s") + } + "transcribe" => { + view.generate_transcript(false, window, cx); + String::new() + } + "select" => { + let (a, b) = argument.split_once('-').unwrap_or((argument, argument)); + let (a, b) = (a.parse().unwrap_or(0), b.parse().unwrap_or(0)); + view.transcript.selection = Some(WordSelection { + anchor: a, + focus: b, + }); + view.transcript_reveal(a, false); + view.invalidate_transcript(cx); + format!("{a}-{b}") + } + "delete" => { + view.transcript_delete_selection(window, cx); + view.timeline_summary() + } + "cleanup" => { + view.transcript.cleanup.open = true; + view.transcript.cleanup.tab = if argument == "pauses" { + super::CleanupTab::Pauses + } else { + super::CleanupTab::Fillers + }; + view.invalidate_transcript(cx); + String::new() + } + "fillers" => { + view.transcript_remove_fillers(window, cx); + view.timeline_summary() + } + "pauses" => { + view.transcript_shorten_pauses(window, cx); + view.timeline_summary() + } + "cuts" => { + let count = argument.parse().unwrap_or(500); + view.transcript_spread_cuts(count, window, cx); + view.timeline_summary() + } + "search" => { + view.transcript_open_search(window, cx); + if let Some(search) = &view.transcript.search { + let query = argument.to_string(); + search + .input + .update(cx, |input, cx| input.set_text(query.clone(), cx)); + } + view.transcript_search_changed(argument.to_string(), cx); + String::new() + } + "seek" => { + view.seek_to_time(argument.parse().unwrap_or(0.0), cx); + String::new() + } + "play" => { + if !view.playing { + view.toggle_play(window, cx); + } + String::new() + } + "stop" => { + view.stop_for_measurement(cx); + String::new() + } + "undo" => { + view.undo(window, cx); + view.timeline_summary() + } + "redo" => { + view.redo(window, cx); + view.timeline_summary() + } + "hover-cut" => { + view.transcript.hovered_cut = view + .transcript + .edl + .as_ref() + .filter(|edl| !edl.cut_runs.is_empty()) + .map(|_| 0); + view.invalidate_transcript(cx); + String::new() + } + "restore" => { + let run = view + .transcript + .edl + .as_ref() + .and_then(|edl| edl.cut_runs.first().cloned()); + if let Some(run) = run { + view.transcript_restore(run, window, cx); + } + view.timeline_summary() + } + "dump" => view.transcript_dump(argument), + _ => String::new(), + } + }); + let action_ms = ms(started.elapsed()); + let Ok(detail) = detail else { + return; + }; + match name { + "wait" => { + sleep(cx, Duration::from_millis(argument.parse().unwrap_or(500))).await; + } + "transcribe" => { + let started = Instant::now(); + while handle + .update(cx, |view, _, _| { + crate::transcription::ui_snapshot(&view.project_path).generating + }) + .unwrap_or(false) + { + if started.elapsed() > TRANSCRIBE_TIMEOUT { + break; + } + sleep(cx, Duration::from_millis(200)).await; + } + println!( + "transcript-auto: transcribe finished in {:.1}s", + started.elapsed().as_secs_f64() + ); + } + "scroll" => { + let frames: usize = argument.parse().unwrap_or(240); + let mut samples = Vec::with_capacity(frames); + for frame in 0..frames { + sleep(cx, FRAME).await; + handle + .update(cx, |view, _, cx| { + let delta = if (frame / 120) % 2 == 0 { 60. } else { -60. }; + view.transcript.list.scroll_by(px(delta)); + view.invalidate_transcript(cx); + }) + .ok(); + samples.push(draw(handle, cx) * 1000.0); + } + crate::draw_bench::report("transcript-auto", "scroll draw", &mut samples); + continue; + } + "follow" => { + let seconds: f64 = argument.parse().unwrap_or(10.0); + let frames = (seconds * 60.0) as usize; + let mut samples = Vec::with_capacity(frames); + for _ in 0..frames { + sleep(cx, FRAME).await; + samples.push(draw(handle, cx) * 1000.0); + } + crate::draw_bench::report( + "transcript-auto", + "playback draw (transcript open)", + &mut samples, + ); + continue; + } + _ => {} + } + let draw_ms = draw(handle, cx); + println!("transcript-auto: {action} {action_ms:.2}ms + draw {draw_ms:.2}ms {detail}"); + } +} + +impl EditorWindow { + fn transcript_spread_cuts( + &mut self, + count: usize, + window: &mut gpui::Window, + cx: &mut gpui::Context, + ) { + let (Some(doc), Some(edl)) = (self.transcript.doc.clone(), self.transcript.edl.clone()) + else { + return; + }; + let kept: Vec = (0..doc.words.len()) + .filter(|word| edl.is_kept(*word)) + .collect(); + if kept.len() < 3 || count == 0 { + return; + } + let stride = (kept.len() / (count + 1)).max(2); + let runs: Vec<_> = kept + .iter() + .skip(stride / 2) + .step_by(stride) + .take(count) + .map(|word| *word..*word + 1) + .collect(); + self.transcript_cut_runs(&runs, "transcript-spread-cuts", window, cx); + } + + fn timeline_summary(&self) -> String { + let clips = self + .project + .timeline + .as_ref() + .map_or(0, |timeline| timeline.segments.len()); + let kept = self.transcript.edl.as_ref().map_or(0, |edl| edl.kept_count); + format!( + "-> {clips} clips, {kept} words kept, {:.2}s", + self.total_duration() + ) + } + + fn transcript_dump(&self, path: &str) -> String { + let (Some(doc), Some(edl)) = (&self.transcript.doc, &self.transcript.edl) else { + return "no transcript".into(); + }; + let words: Vec<_> = doc + .words + .iter() + .enumerate() + .map(|(index, word)| { + serde_json::json!({ + "text": word.text, + "start": word.start, + "end": word.end, + "kept": edl.is_kept(index), + "output_start": edl.source_to_output(word.start), + "output_end": edl.source_to_output(word.end), + }) + }) + .collect(); + let body = serde_json::json!({ + "duration": self.total_duration(), + "clips": self.project.timeline.as_ref().map(|timeline| { + timeline + .segments + .iter() + .map(|segment| (segment.recording_clip, segment.start, segment.end)) + .collect::>() + }), + "words": words, + }); + match std::fs::write(path, serde_json::to_vec_pretty(&body).unwrap_or_default()) { + Ok(()) => format!("wrote {path}"), + Err(error) => format!("failed to write {path}: {error}"), + } + } +} diff --git a/apps/desktop-gpui/src/transcript/cuts.rs b/apps/desktop-gpui/src/transcript/cuts.rs new file mode 100644 index 00000000000..fb38fe1150b --- /dev/null +++ b/apps/desktop-gpui/src/transcript/cuts.rs @@ -0,0 +1,427 @@ +use std::ops::Range; + +use cap_project::TimelineConfiguration; + +use super::energy::{EnergyEnvelope, HOP_SECONDS}; +use super::model::{TranscriptDoc, TranscriptEdl, build_mappings, merge_ranges, recording_offsets}; +use crate::editor_edits::{self, RangeCut}; + +/// Speech decays after the recognizer's word end, so a cut keeps at least this +/// much of the silence after a kept word when the gap allows it... +pub const TAIL_GUARD: f64 = 0.04; +/// ...and this much before a kept word's onset. +pub const ONSET_GUARD: f64 = 0.02; +/// Where a word has no neighbour (the first or last word), the cut reaches +/// this far into the silence beyond it. A first word this close to the start +/// takes the lead-in with it, so cutting an opening "um" starts the video on +/// the next word instead of leaving a sliver of silence. +pub const EDGE_REACH: f64 = 0.6; +const TOUCHING_SEARCH: f64 = 0.04; +const EDGE_PENALTY_DB: f32 = 6.0; +const MAX_SEARCH_STEPS: usize = 4_000; +const MIN_PAUSE_CUT: f64 = 0.05; + +pub fn quietest_point(energy: Option<&EnergyEnvelope>, lo: f64, hi: f64) -> f64 { + let (lo, hi) = if lo <= hi { (lo, hi) } else { (hi, lo) }; + let centre = (lo + hi) / 2.0; + let Some(energy) = energy else { + return centre; + }; + let half = (hi - lo) / 2.0; + if half < HOP_SECONDS / 2.0 { + return centre; + } + let step = (HOP_SECONDS).max((hi - lo) / MAX_SEARCH_STEPS as f64); + let steps = ((hi - lo) / step).floor() as usize; + let mut best: Option<(f32, f64)> = None; + for index in 0..=steps { + let time = (lo + index as f64 * step).min(hi); + let Some(db) = energy.smoothed_db(time) else { + continue; + }; + let score = db + EDGE_PENALTY_DB * ((time - centre).abs() / half) as f32; + if best.is_none_or(|(best_score, _)| score < best_score) { + best = Some((score, time)); + } + } + best.map_or(centre, |(_, time)| time) +} + +/// The cut point between word `index - 1` and word `index` (`index` may be 0 +/// or `words.len()` for the edges). Deterministic per gap, so cutting two +/// neighbouring words one at a time lands on exactly the same boundary as +/// cutting them together. +pub fn gap_cut(doc: &TranscriptDoc, energy: Option<&EnergyEnvelope>, index: usize) -> f64 { + let previous = index.checked_sub(1).and_then(|at| doc.words.get(at)); + let next = doc.words.get(index); + let (previous_end, next_start) = match (previous, next) { + (Some(previous), Some(next)) => (previous.end, next.start), + (None, Some(next)) if next.start <= EDGE_REACH * 2.0 => return 0.0, + (None, Some(next)) => ((next.start - EDGE_REACH).max(0.0), next.start), + (Some(previous), None) => (previous.end, previous.end + EDGE_REACH), + (None, None) => return 0.0, + }; + let gap = next_start - previous_end; + let (lo, hi) = if gap > 0.0 { + ( + previous_end + TAIL_GUARD.min(gap * 0.3), + next_start - ONSET_GUARD.min(gap * 0.2), + ) + } else { + let centre = (previous_end + next_start) / 2.0; + let floor = previous.map_or(f64::NEG_INFINITY, |word| (word.start + word.end) / 2.0); + let ceiling = next.map_or(f64::INFINITY, |word| (word.start + word.end) / 2.0); + ( + (centre - TOUCHING_SEARCH).max(floor).min(centre), + (centre + TOUCHING_SEARCH).min(ceiling).max(centre), + ) + }; + quietest_point(energy, lo, hi) +} + +pub fn plan_word_cuts( + doc: &TranscriptDoc, + energy: Option<&EnergyEnvelope>, + runs: &[Range], +) -> Vec> { + merge_ranges( + runs.iter() + .filter(|run| run.start < run.end && run.end <= doc.words.len()) + .map(|run| gap_cut(doc, energy, run.start)..gap_cut(doc, energy, run.end)) + .collect(), + ) +} + +#[derive(Clone, Debug, PartialEq)] +pub struct PauseCut { + pub after_word: usize, + pub length: f64, + pub saves: f64, + pub cut: Range, +} + +pub fn plan_pause_cuts( + doc: &TranscriptDoc, + edl: &TranscriptEdl, + energy: Option<&EnergyEnvelope>, + longer_than: f64, + keep: f64, +) -> Vec { + let keep = keep.max(0.0); + let floor = longer_than.max(keep + MIN_PAUSE_CUT); + let slowest = edl + .mappings + .iter() + .map(|mapping| mapping.timescale) + .fold(f64::INFINITY, f64::min); + let mut pauses = Vec::new(); + for index in 1..doc.words.len() { + if !edl.is_kept(index - 1) || !edl.is_kept(index) { + continue; + } + let previous_end = doc.words[index - 1].end; + let next_start = doc.words[index].start; + if slowest > 0.0 && (next_start - previous_end) / slowest <= floor { + continue; + } + let Some(timescale) = edl.timescale_over(previous_end..next_start) else { + continue; + }; + let length = (next_start - previous_end) / timescale; + if length <= longer_than || length <= keep + MIN_PAUSE_CUT { + continue; + } + let lead = keep * 0.45 * timescale; + let trail = keep * timescale - lead; + let lo_limit = previous_end + TAIL_GUARD.min(lead); + let hi_limit = next_start - ONSET_GUARD.min(trail); + let start_target = previous_end + lead; + let end_target = next_start - trail; + let start = quietest_point( + energy, + (start_target - 0.06).max(lo_limit), + (start_target + 0.06).min(end_target), + ); + let end = quietest_point( + energy, + (end_target - 0.06).max(start), + (end_target + 0.06).min(hi_limit), + ); + let saves = (end - start) / timescale; + if saves < MIN_PAUSE_CUT { + continue; + } + pauses.push(PauseCut { + after_word: index - 1, + length, + saves, + cut: start..end, + }); + } + pauses +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct CutReport { + pub applied: usize, + pub transition: usize, + pub hold: usize, + pub last_clip: usize, +} + +impl CutReport { + pub fn skipped(&self) -> usize { + self.transition + self.hold + self.last_clip + } +} + +/// Removes every source range from the timeline, wherever and however many +/// times it plays. Pieces are cut from the end backwards so each cut's clip +/// index and local times stay valid while the ones after it are applied. +pub fn apply_source_cuts( + timeline: &mut TimelineConfiguration, + recording_durations: &[f64], + cuts: &[Range], +) -> CutReport { + let cuts = merge_ranges(cuts.to_vec()); + let mappings = build_mappings(timeline, recording_durations); + let mut pieces: Vec<(usize, f64, f64)> = Vec::new(); + for mapping in &mappings { + let first = cuts.partition_point(|cut| cut.end <= mapping.source_start); + for cut in cuts[first..] + .iter() + .take_while(|cut| cut.start < mapping.source_end) + { + let start = cut.start.max(mapping.source_start); + let end = cut.end.min(mapping.source_end); + if end > start { + pieces.push(( + mapping.segment, + (start - mapping.source_start) / mapping.timescale, + (end - mapping.source_start) / mapping.timescale, + )); + } + } + } + pieces.sort_by(|a, b| b.0.cmp(&a.0).then(b.1.total_cmp(&a.1))); + + let mut report = CutReport::default(); + for (segment, start, end) in pieces { + match editor_edits::cut_clip_range(timeline, segment, start, end) { + RangeCut::Applied => report.applied += 1, + RangeCut::Empty => {} + RangeCut::Transition => report.transition += 1, + RangeCut::Hold => report.hold += 1, + RangeCut::LastClip => report.last_clip += 1, + } + } + report +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum RestoreBlocker { + NotAdjacent, + Transition, +} + +const TOUCH_EPSILON: f64 = 1e-6; + +pub fn restore_hole( + timeline: &mut TimelineConfiguration, + recording_durations: &[f64], + removed_takes: &[cap_project::TimelineSegment], + hole: Range, + must_cover: f64, +) -> Result<(), RestoreBlocker> { + let offsets = recording_offsets(recording_durations); + let clip_bounds = |clip: u32| { + let start = offsets.get(clip as usize).copied().unwrap_or(0.0); + let duration = recording_durations + .get(clip as usize) + .copied() + .unwrap_or(f64::INFINITY); + (start, start + duration) + }; + let mut next = timeline.clone(); + let mappings = build_mappings(&next, recording_durations); + let left = mappings + .iter() + .find(|mapping| (mapping.source_end - hole.start).abs() < TOUCH_EPSILON) + .copied(); + let right = mappings + .iter() + .find(|mapping| (mapping.source_start - hole.end).abs() < TOUCH_EPSILON) + .copied(); + match (left, right) { + (Some(left), Some(right)) if right.segment != left.segment + 1 => { + return Err(RestoreBlocker::NotAdjacent); + } + (None, None) => return Err(RestoreBlocker::NotAdjacent), + _ => {} + } + if let Some(left) = left + && next.effective_transition(left.segment + 1).is_some() + { + return Err(RestoreBlocker::Transition); + } + if let Some(right) = right + && next.effective_transition(right.segment).is_some() + { + return Err(RestoreBlocker::Transition); + } + + let mut restored_to = hole.start; + if let Some(left) = left { + let (clip_start, clip_end) = clip_bounds(left.recording_clip); + let target = hole.end.min(clip_end); + let grow = target - left.source_end; + if grow > 0.0 { + let holds = next.hold_windows(); + let boundary = editor_edits::effective_to_output(&holds, left.effective_end()); + next.segments[left.segment].end = target - clip_start; + editor_edits::ripple_insert_output_tracks(&mut next, boundary, grow / left.timescale); + restored_to = target; + } + } + if let Some(right) = right { + let (clip_start, _) = clip_bounds(right.recording_clip); + let target = restored_to.max(hole.start).max(clip_start); + let grow = right.source_start - target; + if grow > 0.0 { + let effective_start = build_mappings(&next, recording_durations) + .get(right.segment) + .map_or(right.effective_start, |mapping| mapping.effective_start); + let holds = next.hold_windows(); + let boundary = editor_edits::effective_to_output(&holds, effective_start); + next.segments[right.segment].start = target - clip_start; + editor_edits::ripple_insert_output_tracks(&mut next, boundary, grow / right.timescale); + } + } + + let first_missing = left.map_or(0, |left| left.recording_clip + 1); + let last_missing = right.map_or(recording_durations.len() as u32, |right| { + right.recording_clip + }); + let mut index = match (left, right) { + (Some(left), _) => left.segment + 1, + (None, Some(right)) => right.segment, + (None, None) => 0, + }; + for clip in first_missing..last_missing { + let (start, end) = clip_bounds(clip); + let duration = end - start; + if !(duration.is_finite() && duration > 0.0) + || start < hole.start - TOUCH_EPSILON + || end > hole.end + TOUCH_EPSILON + { + continue; + } + let effective = crate::editor_timeline::clip_timeline_offsets(&next) + .get(index) + .copied() + .unwrap_or_else(|| editor_edits::clip_timeline_duration(&next)); + let holds = next.hold_windows(); + let boundary = editor_edits::effective_to_output(&holds, effective); + let removed = removed_takes + .iter() + .find(|segment| segment.recording_clip == clip); + let template = removed + .or_else(|| { + left.or(right) + .and_then(|mapping| timeline.segments.get(mapping.segment)) + }) + .cloned() + .unwrap_or(cap_project::TimelineSegment { + timescale: 1.0, + ..Default::default() + }); + next.segments.insert( + index, + cap_project::TimelineSegment { + recording_clip: clip, + start: 0.0, + end: duration, + name: removed.and(template.name.clone()), + ..template + }, + ); + for transition in next.transitions.iter_mut() { + if transition.segment_index as usize >= index { + transition.segment_index += 1; + } + } + let played = next.segments[index].duration(); + editor_edits::ripple_insert_output_tracks(&mut next, boundary, played); + index += 1; + } + + let covered = build_mappings(&next, recording_durations) + .iter() + .any(|mapping| mapping.source_start <= must_cover && must_cover < mapping.source_end); + if !covered { + return Err(RestoreBlocker::NotAdjacent); + } + + if let (Some(left), Some(_)) = (left, right) { + let mergeable = { + let (a, b) = ( + &next.segments[left.segment], + &next.segments[left.segment + 1], + ); + a.recording_clip == b.recording_clip + && (a.end - b.start).abs() < TOUCH_EPSILON + && a.timescale == b.timescale + && a.volume == b.volume + && a.speed_audio_mode == b.speed_audio_mode + && a.hide_cursor == b.hide_cursor + && (b.name.is_none() || a.name == b.name) + }; + if mergeable { + editor_edits::merge_clip_segments( + &mut next, + left.segment, + editor_edits::ClipMergeDirection::Next, + ); + } + } + *timeline = next; + Ok(()) +} + +/// Brings back every cut word in `words`, one cut stretch at a time, and +/// returns how many stretches that took. All or nothing: if any stretch +/// cannot be restored, the timeline is left exactly as it was. +pub fn restore_words( + timeline: &mut TimelineConfiguration, + recording_durations: &[f64], + removed_takes: &[cap_project::TimelineSegment], + doc: &TranscriptDoc, + words: Range, +) -> Result { + let mut next = timeline.clone(); + let mut restored = 0; + for _ in 0..=words.len() { + let edl = TranscriptEdl::build(doc, &next, recording_durations); + let Some(index) = words.clone().find(|word| !edl.is_kept(*word)) else { + break; + }; + let word = &doc.words[index]; + let first = edl + .kept_ranges + .partition_point(|range| range.end <= word.start); + let uncovered = match edl.kept_ranges.get(first) { + Some(range) if range.start <= word.start => range.end, + _ => word.start, + }; + let point = if uncovered < word.end { + uncovered + } else { + word.start + }; + let hole = edl.hole_around(point).ok_or(RestoreBlocker::NotAdjacent)?; + restore_hole(&mut next, recording_durations, removed_takes, hole, point)?; + restored += 1; + } + *timeline = next; + Ok(restored) +} diff --git a/apps/desktop-gpui/src/transcript/energy.rs b/apps/desktop-gpui/src/transcript/energy.rs new file mode 100644 index 00000000000..7879dbeead1 --- /dev/null +++ b/apps/desktop-gpui/src/transcript/energy.rs @@ -0,0 +1,110 @@ +use std::sync::Arc; + +/// 5 ms hops: fine enough to land a cut between two syllables, coarse enough +/// that a two hour recording costs under 6 MB. +pub const HOP_SECONDS: f64 = 0.005; +const SAMPLE_RATE: f64 = 48_000.0; + +#[derive(Debug, Default)] +pub struct EnergyEnvelope { + clips: Vec>, + clip_offsets: Vec, +} + +pub struct EnvelopeTrack<'a> { + pub slices: Vec<&'a [f32]>, + pub channels: u16, + pub offset_seconds: f64, +} + +pub fn clip_envelope(tracks: &[EnvelopeTrack<'_>], duration: f64) -> Vec { + let hop = (HOP_SECONDS * SAMPLE_RATE).round() as i64; + let hops = ((duration.max(0.0) * SAMPLE_RATE).ceil() as i64 + hop - 1) / hop; + let mut sums = vec![0.0f64; hops.max(0) as usize]; + let mut counts = vec![0u32; sums.len()]; + for track in tracks { + let channels = usize::from(track.channels.max(1)); + let offset = (track.offset_seconds * SAMPLE_RATE).round() as i64; + let mut frame: i64 = 0; + let mut channel = 0usize; + let mut mixed = 0.0f64; + 'slices: for slice in &track.slices { + for sample in *slice { + mixed += f64::from(*sample); + channel += 1; + if channel < channels { + continue; + } + let source = frame - offset; + frame += 1; + channel = 0; + let mono = mixed / channels as f64; + mixed = 0.0; + if source < 0 { + continue; + } + let index = (source / hop) as usize; + if index >= sums.len() { + break 'slices; + } + sums[index] += mono * mono; + counts[index] += 1; + } + } + } + let per_track = tracks.len().max(1) as f64; + sums.iter() + .zip(&counts) + .map(|(sum, count)| { + if *count == 0 { + 0.0 + } else { + (sum / f64::from(*count) * per_track) as f32 + } + }) + .collect() +} + +impl EnergyEnvelope { + pub fn new(clips: Vec>, recording_durations: &[f64]) -> Self { + Self { + clip_offsets: super::model::recording_offsets(recording_durations), + clips: clips.into_iter().map(Arc::from).collect(), + } + } + + pub fn is_empty(&self) -> bool { + self.clips.iter().all(|clip| clip.is_empty()) + } + + fn locate(&self, source: f64) -> Option<(usize, f64)> { + let clip = self + .clip_offsets + .partition_point(|offset| *offset <= source) + .checked_sub(1)?; + Some((clip, source - self.clip_offsets[clip])) + } + + pub fn energy_at(&self, source: f64) -> Option { + let (clip, local) = self.locate(source)?; + if local < 0.0 { + return None; + } + self.clips + .get(clip)? + .get((local / HOP_SECONDS) as usize) + .copied() + } + + pub fn smoothed_db(&self, source: f64) -> Option { + let mut total = 0.0; + let mut count = 0; + for step in [-1.0, 0.0, 1.0] { + if let Some(energy) = self.energy_at(source + step * HOP_SECONDS) { + total += energy; + count += 1; + } + } + (count > 0).then(|| 10.0 * (total / count as f32 + 1e-10).log10()) + } +} diff --git a/apps/desktop-gpui/src/transcript/model.rs b/apps/desktop-gpui/src/transcript/model.rs new file mode 100644 index 00000000000..c385d2f8530 --- /dev/null +++ b/apps/desktop-gpui/src/transcript/model.rs @@ -0,0 +1,499 @@ +use std::ops::Range; + +use cap_project::disfluency::{Disfluency, DisfluencyToken, detect_disfluencies}; +use cap_project::{CaptionsData, TimelineConfiguration}; +use gpui::SharedString; + +use crate::editor_edits; +use crate::editor_timeline; + +const PARAGRAPH_PAUSE: f64 = 1.6; +const SENTENCE_PARAGRAPH_PAUSE: f64 = 0.7; +const SOFT_PARAGRAPH_WORDS: usize = 70; +const HARD_PARAGRAPH_WORDS: usize = 140; +const ACTIVE_WORD_LINGER: f64 = 0.25; + +#[derive(Clone, Debug, PartialEq)] +pub struct Word { + pub text: String, + pub start: f64, + pub end: f64, +} + +#[derive(Clone, Debug)] +pub struct Paragraph { + pub words: Range, + pub text: SharedString, + pub spans: Vec>, +} + +impl Paragraph { + pub fn word_at_byte(&self, byte: usize) -> usize { + let local = self + .spans + .partition_point(|span| span.end < byte) + .min(self.spans.len().saturating_sub(1)); + self.words.start + local + } + + pub fn span(&self, word: usize) -> Option> { + self.spans.get(word.checked_sub(self.words.start)?).cloned() + } +} + +pub struct TranscriptDoc { + pub words: Vec, + pub paragraphs: Vec, + pub paragraph_of: Vec, + pub fillers: Vec, + pub filler_of: Vec, + pub signature: u64, +} + +pub const NO_FILLER: u32 = u32::MAX; + +fn attaches_to_previous(text: &str) -> bool { + text.chars().next().is_some_and(|first| { + matches!( + first, + ',' | '.' + | '!' + | '?' + | ';' + | ':' + | '%' + | ')' + | ']' + | '}' + | '\'' + | '’' + | '、' + | '。' + | '!' + | '?' + | ';' + | ':' + | ',' + ) + }) +} + +fn ends_sentence(text: &str) -> bool { + let trimmed = text.trim_end_matches(['"', '\'', '”', '’', ')']); + trimmed.ends_with(['.', '!', '?', '。', '!', '?', '…']) +} + +fn ends_clause(text: &str) -> bool { + ends_sentence(text) || text.ends_with([',', ';', ':', '—', '-', ',']) +} + +pub fn captions_signature(captions: Option<&CaptionsData>) -> u64 { + use std::hash::{Hash, Hasher}; + let mut hasher = std::hash::DefaultHasher::new(); + if let Some(captions) = captions { + captions.source_timed.hash(&mut hasher); + captions.segments.len().hash(&mut hasher); + for segment in &captions.segments { + segment.words.len().hash(&mut hasher); + for word in &segment.words { + word.text.hash(&mut hasher); + word.start.to_bits().hash(&mut hasher); + word.end.to_bits().hash(&mut hasher); + } + } + } + hasher.finish() +} + +pub fn flatten_words(captions: &CaptionsData) -> Vec { + let mut words: Vec = Vec::new(); + let mut raw: Vec<(&str, f64, f64)> = captions + .segments + .iter() + .flat_map(|segment| segment.words.iter()) + .filter_map(|word| { + let text = word.text.trim(); + let (start, end) = (f64::from(word.start), f64::from(word.end)); + (!text.is_empty() && start.is_finite() && end.is_finite()).then_some(( + text, + start, + end.max(start), + )) + }) + .collect(); + raw.sort_by(|a, b| a.1.total_cmp(&b.1)); + for (text, start, end) in raw { + let spoken = !cap_project::disfluency::normalize_word(text).is_empty(); + match words.last_mut() { + Some(previous) if !spoken || attaches_to_previous(text) => { + previous.text.push_str(text); + if spoken { + previous.end = previous.end.max(end); + } + } + _ if !spoken => {} + _ => words.push(Word { + text: text.to_string(), + start, + end, + }), + } + } + words +} + +fn build_paragraphs(words: &[Word]) -> Vec> { + let mut paragraphs = Vec::new(); + let mut start = 0; + for index in 1..words.len() { + let previous = &words[index - 1]; + let gap = words[index].start - previous.end; + let length = index - start; + let sentence = ends_sentence(&previous.text); + let breaks = gap >= PARAGRAPH_PAUSE + || (sentence && gap >= SENTENCE_PARAGRAPH_PAUSE) + || (sentence && length >= SOFT_PARAGRAPH_WORDS) + || (length >= HARD_PARAGRAPH_WORDS && (ends_clause(&previous.text) || gap >= 0.3)) + || length >= HARD_PARAGRAPH_WORDS * 2; + if breaks { + paragraphs.push(start..index); + start = index; + } + } + if start < words.len() { + paragraphs.push(start..words.len()); + } + paragraphs +} + +impl TranscriptDoc { + pub fn build(captions: &CaptionsData) -> Self { + let words = flatten_words(captions); + let tokens: Vec = words + .iter() + .map(|word| DisfluencyToken { + text: &word.text, + start: word.start, + end: word.end, + }) + .collect(); + let fillers = detect_disfluencies(&tokens); + let mut filler_of = vec![NO_FILLER; words.len()]; + for (index, filler) in fillers.iter().enumerate() { + for slot in &mut filler_of[filler.words.clone()] { + *slot = index as u32; + } + } + + let ranges = build_paragraphs(&words); + let mut paragraph_of = vec![0u32; words.len()]; + let paragraphs = ranges + .into_iter() + .enumerate() + .map(|(index, range)| { + let mut text = String::new(); + let mut spans = Vec::with_capacity(range.len()); + for word in &words[range.clone()] { + if !text.is_empty() { + text.push(' '); + } + let start = text.len(); + text.push_str(&word.text); + spans.push(start..text.len()); + } + for slot in &mut paragraph_of[range.clone()] { + *slot = index as u32; + } + Paragraph { + words: range, + text: text.into(), + spans, + } + }) + .collect(); + + Self { + words, + paragraphs, + paragraph_of, + fillers, + filler_of, + signature: captions_signature(Some(captions)), + } + } + + pub fn is_empty(&self) -> bool { + self.words.is_empty() + } + + pub fn paragraph_of(&self, word: usize) -> usize { + self.paragraph_of.get(word).copied().unwrap_or(0) as usize + } + + pub fn word_at_source(&self, source: f64) -> Option { + let index = self + .words + .partition_point(|word| word.start <= source) + .checked_sub(1)?; + let word = &self.words[index]; + (source <= word.end.max(word.start) + ACTIVE_WORD_LINGER).then_some(index) + } + + pub fn filler(&self, word: usize) -> Option<&Disfluency> { + let index = *self.filler_of.get(word)?; + (index != NO_FILLER).then(|| &self.fillers[index as usize]) + } + + pub fn text_of(&self, words: Range) -> String { + let mut text = String::new(); + for word in &self.words[words] { + if !text.is_empty() { + text.push(' '); + } + text.push_str(&word.text); + } + text + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Mapping { + pub segment: usize, + pub recording_clip: u32, + pub source_start: f64, + pub source_end: f64, + pub effective_start: f64, + pub timescale: f64, +} + +impl Mapping { + pub fn effective_end(&self) -> f64 { + self.effective_start + (self.source_end - self.source_start) / self.timescale + } + + pub fn effective_at(&self, source: f64) -> f64 { + self.effective_start + (source - self.source_start) / self.timescale + } +} + +pub fn recording_offsets(recording_durations: &[f64]) -> Vec { + let mut offsets = Vec::with_capacity(recording_durations.len()); + let mut total = 0.0; + for duration in recording_durations { + offsets.push(total); + total += duration; + } + offsets +} + +pub fn build_mappings( + timeline: &TimelineConfiguration, + recording_durations: &[f64], +) -> Vec { + let offsets = recording_offsets(recording_durations); + editor_timeline::clip_timeline_offsets(timeline) + .into_iter() + .zip(&timeline.segments) + .enumerate() + .map(|(segment_index, (effective_start, segment))| { + let offset = offsets + .get(segment.recording_clip as usize) + .copied() + .unwrap_or(0.0); + Mapping { + segment: segment_index, + recording_clip: segment.recording_clip, + source_start: offset + segment.start, + source_end: offset + segment.end, + effective_start, + timescale: segment.timescale, + } + }) + .collect() +} + +/// Which words survive the current edit list. A word counts as kept when at +/// least half of it plays, which is what makes a cut placed in the silence +/// beside a word never hide it, while a word trimmed down to a sliver reads as +/// cut. +pub struct TranscriptEdl { + pub kept: Vec, + pub mappings: Vec, + pub holds: Vec<(f64, f64)>, + pub kept_ranges: Vec>, + pub cut_runs: Vec>, + pub kept_count: usize, +} + +pub fn merge_ranges(mut ranges: Vec>) -> Vec> { + ranges.retain(|range| range.end > range.start); + ranges.sort_by(|a, b| a.start.total_cmp(&b.start)); + let mut merged: Vec> = Vec::with_capacity(ranges.len()); + for range in ranges { + match merged.last_mut() { + Some(last) if range.start <= last.end + 1e-9 => last.end = last.end.max(range.end), + _ => merged.push(range), + } + } + merged +} + +impl TranscriptEdl { + pub fn build( + doc: &TranscriptDoc, + timeline: &TimelineConfiguration, + recording_durations: &[f64], + ) -> Self { + let mappings = build_mappings(timeline, recording_durations); + let kept_ranges = merge_ranges( + mappings + .iter() + .map(|mapping| mapping.source_start..mapping.source_end) + .collect(), + ); + let mut kept = Vec::with_capacity(doc.words.len()); + let mut cursor = 0; + for word in &doc.words { + while kept_ranges + .get(cursor) + .is_some_and(|range| range.end <= word.start) + { + cursor += 1; + } + let duration = word.end - word.start; + let is_kept = if duration <= 1e-6 { + kept_ranges + .get(cursor) + .is_some_and(|range| range.start <= word.start && word.start < range.end) + } else { + let covered: f64 = kept_ranges[cursor.min(kept_ranges.len())..] + .iter() + .take_while(|range| range.start < word.end) + .map(|range| (range.end.min(word.end) - range.start.max(word.start)).max(0.0)) + .sum(); + covered >= duration * 0.5 + }; + kept.push(is_kept); + } + + let mut cut_runs = Vec::new(); + let mut run_start = None; + for (index, is_kept) in kept.iter().enumerate() { + match (run_start, is_kept) { + (None, false) => run_start = Some(index), + (Some(start), true) => { + cut_runs.push(start..index); + run_start = None; + } + _ => {} + } + } + if let Some(start) = run_start { + cut_runs.push(start..kept.len()); + } + + Self { + kept_count: kept.iter().filter(|kept| **kept).count(), + kept, + mappings, + holds: timeline.hold_windows(), + kept_ranges, + cut_runs, + } + } + + pub fn is_kept(&self, word: usize) -> bool { + self.kept.get(word).copied().unwrap_or(false) + } + + pub fn cut_run_of(&self, word: usize) -> Option { + let index = self.cut_runs.partition_point(|run| run.end <= word); + self.cut_runs + .get(index) + .filter(|run| run.contains(&word)) + .map(|_| index) + } + + pub fn source_to_output(&self, source: f64) -> Option { + let mapping = self + .mappings + .iter() + .find(|mapping| mapping.source_start <= source && source < mapping.source_end) + .or_else(|| { + self.mappings + .iter() + .find(|mapping| (mapping.source_end - source).abs() < 1e-9) + })?; + Some(editor_edits::effective_to_output( + &self.holds, + mapping.effective_at(source), + )) + } + + pub fn output_start_of(&self, word: &Word) -> Option { + self.source_to_output(word.start).or_else(|| { + let index = self + .kept_ranges + .partition_point(|range| range.end <= word.start); + let range = self.kept_ranges.get(index)?; + if range.start >= word.end { + return None; + } + self.source_to_output(range.start.max(word.start)) + }) + } + + pub fn output_end_of(&self, word: &Word) -> Option { + self.source_to_output(word.end).or_else(|| { + let index = self + .kept_ranges + .partition_point(|range| range.start < word.end) + .checked_sub(1)?; + let range = &self.kept_ranges[index]; + if range.end <= word.start { + return None; + } + self.source_to_output(range.end.min(word.end)) + }) + } + + /// The speed `range` plays at when one clip plays all of it; `None` when it + /// is cut, or crosses into another clip where the speed may differ. + pub fn timescale_over(&self, range: Range) -> Option { + self.mappings + .iter() + .find(|mapping| { + mapping.source_start <= range.start + 1e-9 && range.end <= mapping.source_end + 1e-9 + }) + .map(|mapping| mapping.timescale) + } + + pub fn output_to_source(&self, output: f64) -> Option { + let effective = output - editor_edits::held_time_before(&self.holds, output); + let index = self + .mappings + .partition_point(|mapping| mapping.effective_start <= effective) + .checked_sub(1)?; + let mapping = &self.mappings[index]; + (effective <= mapping.effective_end() + 1e-9).then_some( + mapping.source_start + (effective - mapping.effective_start) * mapping.timescale, + ) + } + + pub fn hole_around(&self, source: f64) -> Option> { + let after = self + .kept_ranges + .partition_point(|range| range.start <= source); + if after > 0 && self.kept_ranges[after - 1].end > source { + return None; + } + let start = after + .checked_sub(1) + .map_or(f64::NEG_INFINITY, |before| self.kept_ranges[before].end); + let end = self + .kept_ranges + .get(after) + .map_or(f64::INFINITY, |range| range.start); + Some(start..end) + } +} diff --git a/apps/desktop-gpui/src/transcript/tests.rs b/apps/desktop-gpui/src/transcript/tests.rs new file mode 100644 index 00000000000..6253213814f --- /dev/null +++ b/apps/desktop-gpui/src/transcript/tests.rs @@ -0,0 +1,1009 @@ +use std::ops::Range; + +use cap_project::{ + CaptionSegment, CaptionWord, CaptionsData, ClipTransition, ClipTransitionType, + ProjectConfiguration, TextLayout, TimelineConfiguration, +}; + +use super::cuts::{ + self, CutReport, ONSET_GUARD, RestoreBlocker, TAIL_GUARD, apply_source_cuts, gap_cut, + plan_pause_cuts, plan_word_cuts, quietest_point, restore_words, +}; +use super::energy::{EnergyEnvelope, EnvelopeTrack, HOP_SECONDS, clip_envelope}; +use super::model::{TranscriptDoc, TranscriptEdl, flatten_words}; +use crate::editor_edits; + +/// Collapses a sorted, possibly overlapping list of word indices into runs. +fn runs_of(words: impl IntoIterator) -> Vec> { + let mut sorted: Vec = words.into_iter().collect(); + sorted.sort_unstable(); + sorted.dedup(); + let mut runs: Vec> = Vec::new(); + for word in sorted { + match runs.last_mut() { + Some(run) if run.end == word => run.end += 1, + _ => runs.push(word..word + 1), + } + } + runs +} + +fn captions(words: &[(&str, f64, f64)]) -> CaptionsData { + let segments = words + .chunks(6) + .enumerate() + .map(|(index, chunk)| CaptionSegment { + id: format!("segment-{index}"), + start: chunk[0].1 as f32, + end: chunk[chunk.len() - 1].2 as f32, + text: chunk + .iter() + .map(|(text, ..)| *text) + .collect::>() + .join(" "), + words: chunk + .iter() + .map(|(text, start, end)| CaptionWord { + text: (*text).to_string(), + start: *start as f32, + end: *end as f32, + }) + .collect(), + }) + .collect(); + CaptionsData { + segments, + settings: Default::default(), + source_timed: true, + } +} + +/// `count` words, each 0.3 s long with 0.2 s of silence after it. +fn spoken(texts: &[&str]) -> Vec<(String, f64, f64)> { + texts + .iter() + .enumerate() + .map(|(index, text)| { + let start = 1.0 + index as f64 * 0.5; + ((*text).to_string(), start, start + 0.3) + }) + .collect() +} + +fn borrowed(words: &[(String, f64, f64)]) -> Vec<(&str, f64, f64)> { + words + .iter() + .map(|(text, start, end)| (text.as_str(), *start, *end)) + .collect() +} + +fn project(words: &[(&str, f64, f64)], durations: &[f64]) -> ProjectConfiguration { + let mut project = ProjectConfiguration::default(); + assert!(editor_edits::ensure_timeline(&mut project, durations)); + project.captions = Some(captions(words)); + project +} + +fn timeline(project: &ProjectConfiguration) -> &TimelineConfiguration { + project.timeline.as_ref().unwrap() +} + +fn timeline_mut(project: &mut ProjectConfiguration) -> &mut TimelineConfiguration { + project.timeline.as_mut().unwrap() +} + +fn model(project: &ProjectConfiguration, durations: &[f64]) -> (TranscriptDoc, TranscriptEdl) { + let doc = TranscriptDoc::build(project.captions.as_ref().unwrap()); + let edl = TranscriptEdl::build(&doc, timeline(project), durations); + (doc, edl) +} + +fn cut_words( + project: &mut ProjectConfiguration, + durations: &[f64], + runs: &[(usize, usize)], +) -> CutReport { + let doc = TranscriptDoc::build(project.captions.as_ref().unwrap()); + let runs: Vec> = runs.iter().map(|(start, end)| *start..*end).collect(); + let cuts = plan_word_cuts(&doc, None, &runs); + apply_source_cuts(timeline_mut(project), durations, &cuts) +} + +fn kept(project: &ProjectConfiguration, durations: &[f64]) -> Vec { + model(project, durations).1.kept +} + +fn bounds(project: &ProjectConfiguration) -> Vec<(f64, f64)> { + timeline(project) + .segments + .iter() + .map(|segment| (segment.start, segment.end)) + .collect() +} + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-6 +} + +#[test] +fn flattening_folds_punctuation_and_sorts() { + let data = captions(&[ + ("world", 0.6, 0.9), + ("hello", 0.1, 0.5), + (",", 0.5, 0.5), + ("", 1.0, 1.1), + ("again", 1.2, 1.5), + (".", 1.5, 1.5), + ("it", 2.0, 2.1), + ("'s", 2.1, 2.2), + ]); + let words = flatten_words(&data); + let texts: Vec<_> = words.iter().map(|word| word.text.as_str()).collect(); + assert_eq!(texts, ["hello,", "world", "again.", "it's"]); + assert!(close(words[3].end, 2.2)); +} + +#[test] +fn paragraphs_break_at_long_pauses_and_sentence_ends() { + let data = captions(&[ + ("One", 0.0, 0.2), + ("two.", 0.3, 0.5), + ("Three", 1.4, 1.6), + ("four", 1.7, 1.9), + ("five", 4.0, 4.2), + ]); + let doc = TranscriptDoc::build(&data); + let ranges: Vec<_> = doc.paragraphs.iter().map(|p| p.words.clone()).collect(); + assert_eq!(ranges, [0..2, 2..4, 4..5]); + assert_eq!(doc.paragraphs[0].text.as_ref(), "One two."); + assert_eq!(doc.paragraphs[0].spans, [0..3, 4..8]); + assert_eq!(doc.paragraphs[0].word_at_byte(3), 0); + assert_eq!(doc.paragraphs[0].word_at_byte(4), 1); + assert_eq!(doc.paragraphs[0].word_at_byte(99), 1); +} + +#[test] +fn long_runs_without_punctuation_still_break() { + let words: Vec<_> = (0..400) + .map(|index| { + ( + "word".to_string(), + index as f64 * 0.3, + index as f64 * 0.3 + 0.25, + ) + }) + .collect(); + let doc = TranscriptDoc::build(&captions(&borrowed(&words))); + assert!(doc.paragraphs.len() >= 2); + assert!(doc.paragraphs.iter().all(|p| p.words.len() <= 280)); + assert_eq!( + doc.paragraphs.iter().map(|p| p.words.len()).sum::(), + 400 + ); +} + +#[test] +fn deleting_a_word_cuts_inside_the_silences_around_it() { + let words = spoken(&["so", "um", "the", "export", "works"]); + let durations = [5.0]; + let mut project = project(&borrowed(&words), &durations); + let report = cut_words(&mut project, &durations, &[(1, 2)]); + assert_eq!(report.applied, 1); + assert_eq!(kept(&project, &durations), [true, false, true, true, true]); + + let segments = bounds(&project); + assert_eq!(segments.len(), 2); + let (doc, _) = model(&project, &durations); + let before = &doc.words[0]; + let removed = &doc.words[1]; + let after = &doc.words[2]; + assert!(segments[0].1 >= before.end + TAIL_GUARD - 1e-9); + assert!(segments[0].1 <= removed.start); + assert!(segments[1].0 >= removed.end); + assert!(segments[1].0 <= after.start - ONSET_GUARD + 1e-9); + assert!(close( + editor_edits::clip_timeline_duration(timeline(&project)), + 5.0 - (segments[1].0 - segments[0].1) + )); +} + +#[test] +fn cutting_neighbours_one_at_a_time_matches_cutting_them_together() { + let words = spoken(&["a", "b", "c", "d", "e"]); + let durations = [5.0]; + let mut together = project(&borrowed(&words), &durations); + cut_words(&mut together, &durations, &[(1, 3)]); + let mut apart = project(&borrowed(&words), &durations); + cut_words(&mut apart, &durations, &[(1, 2)]); + cut_words(&mut apart, &durations, &[(2, 3)]); + let total = + |project: &ProjectConfiguration| editor_edits::clip_timeline_duration(timeline(project)); + assert!(close(total(&together), total(&apart))); + assert_eq!(kept(&together, &durations), kept(&apart, &durations)); + let played: f64 = bounds(&apart).iter().map(|(s, e)| e - s).sum(); + assert!(close(played, total(&together))); +} + +#[test] +fn other_tracks_ripple_with_the_cut() { + let words = spoken(&["one", "two", "three", "four"]); + let durations = [4.0]; + let mut project = project(&borrowed(&words), &durations); + timeline_mut(&mut project) + .text_segments + .push(editor_edits::default_text_segment(3.0, 3.5, 0)); + let before = editor_edits::clip_timeline_duration(timeline(&project)); + cut_words(&mut project, &durations, &[(1, 2)]); + let removed = before - editor_edits::clip_timeline_duration(timeline(&project)); + let text = &timeline(&project).text_segments[0]; + assert!(close(text.start, 3.0 - removed)); + assert!(close(text.end, 3.5 - removed)); +} + +#[test] +fn restoring_undoes_the_cut_exactly() { + let words = spoken(&["so", "um", "the", "export", "works"]); + let durations = [5.0]; + let original = project(&borrowed(&words), &durations); + let mut project = original.clone(); + timeline_mut(&mut project) + .text_segments + .push(editor_edits::default_text_segment(3.0, 3.5, 0)); + let with_text = project.clone(); + cut_words(&mut project, &durations, &[(1, 2)]); + let doc = TranscriptDoc::build(project.captions.as_ref().unwrap()); + let restored = restore_words(timeline_mut(&mut project), &durations, &[], &doc, 1..2).unwrap(); + assert_eq!(restored, 1); + assert_eq!(bounds(&project), bounds(&original)); + let text = &timeline(&project).text_segments[0]; + let expected = &timeline(&with_text).text_segments[0]; + assert!(close(text.start, expected.start) && close(text.end, expected.end)); + assert_eq!(kept(&project, &durations), [true; 5]); +} + +#[test] +fn restore_reaches_a_cut_at_the_start_and_end() { + let words = spoken(&["um", "hello", "there", "uh"]); + let durations = [4.0]; + let mut project = project(&borrowed(&words), &durations); + cut_words(&mut project, &durations, &[(0, 1), (3, 4)]); + assert_eq!(kept(&project, &durations), [false, true, true, false]); + assert!(close(timeline(&project).segments[0].start, 1.41)); + let doc = TranscriptDoc::build(project.captions.as_ref().unwrap()); + restore_words(timeline_mut(&mut project), &durations, &[], &doc, 0..1).unwrap(); + restore_words(timeline_mut(&mut project), &durations, &[], &doc, 3..4).unwrap(); + assert_eq!(kept(&project, &durations), [true; 4]); + assert_eq!(bounds(&project), [(0.0, 4.0)]); +} + +#[test] +fn restore_refuses_a_cut_between_reordered_clips() { + let words = spoken(&["a", "b", "c", "d"]); + let durations = [4.0]; + let mut project = project(&borrowed(&words), &durations); + cut_words(&mut project, &durations, &[(1, 2)]); + timeline_mut(&mut project).segments.swap(0, 1); + let before = bounds(&project); + let doc = TranscriptDoc::build(project.captions.as_ref().unwrap()); + let result = restore_words(timeline_mut(&mut project), &durations, &[], &doc, 1..2); + assert_eq!(result, Err(RestoreBlocker::NotAdjacent)); + assert_eq!(bounds(&project), before); +} + +#[test] +fn a_timeline_cut_shows_up_as_cut_words() { + let words = spoken(&["a", "b", "c", "d", "e"]); + let durations = [5.0]; + let mut project = project(&borrowed(&words), &durations); + let timeline = timeline_mut(&mut project); + assert!(editor_edits::split_clip_segment(timeline, 1.9, None)); + assert!(editor_edits::split_clip_segment(timeline, 2.9, None)); + assert!(editor_edits::delete_clip_segments(timeline, &[1])); + assert_eq!(kept(&project, &durations), [true, true, false, false, true]); +} + +#[test] +fn words_in_later_recordings_map_through_the_recording_offsets() { + let durations = [3.0, 3.0]; + let words = [ + ("first", 1.0, 1.4), + ("take", 1.6, 2.0), + ("second", 4.0, 4.4), + ("take", 4.6, 5.0), + ]; + let mut project = project(&words, &durations); + assert_eq!(timeline(&project).segments.len(), 2); + let (_, edl) = model(&project, &durations); + assert!(close(edl.source_to_output(4.0).unwrap(), 4.0)); + assert!(close(edl.output_to_source(4.2).unwrap(), 4.2)); + cut_words(&mut project, &durations, &[(2, 3)]); + assert_eq!(kept(&project, &durations), [true, true, false, true]); + let segments = &timeline(&project).segments; + assert_eq!(segments.len(), 2); + assert_eq!(segments[1].recording_clip, 1); + assert!(segments[1].start > 1.4 && segments[1].start < 1.6); +} + +#[test] +fn fast_clips_cut_in_playback_time() { + let words = spoken(&["a", "b", "c", "d"]); + let durations = [4.0]; + let mut project = project(&borrowed(&words), &durations); + timeline_mut(&mut project).segments[0].timescale = 2.0; + let (_, edl) = model(&project, &durations); + assert!(close(edl.source_to_output(2.0).unwrap(), 1.0)); + cut_words(&mut project, &durations, &[(1, 2)]); + assert_eq!(kept(&project, &durations), [true, false, true, true]); + let played: f64 = bounds(&project).iter().map(|(s, e)| e - s).sum(); + assert!(close( + editor_edits::clip_timeline_duration(timeline(&project)), + played / 2.0 + )); +} + +#[test] +fn cuts_next_to_a_transition_are_skipped_and_reported() { + let words = spoken(&["a", "b", "c", "d", "e", "f", "g", "h"]); + let durations = [5.0]; + let mut project = project(&borrowed(&words), &durations); + let timeline = timeline_mut(&mut project); + assert!(editor_edits::split_clip_segment(timeline, 2.85, None)); + timeline.transitions.push(ClipTransition { + segment_index: 1, + kind: ClipTransitionType::CrossFade, + duration: 0.5, + }); + let before = bounds(&project); + let report = cut_words(&mut project, &durations, &[(3, 4)]); + assert_eq!(report.applied, 0); + assert!(report.transition >= 1); + assert_eq!(bounds(&project), before); +} + +#[test] +fn cuts_under_a_fullscreen_text_hold_are_skipped() { + let words = spoken(&["a", "b", "c", "d"]); + let durations = [4.0]; + let mut project = project(&borrowed(&words), &durations); + let mut hold = editor_edits::default_text_segment(1.6, 1.9, 0); + hold.layout = TextLayout::Fullscreen; + timeline_mut(&mut project).text_segments.push(hold); + let report = cut_words(&mut project, &durations, &[(1, 2)]); + assert_eq!(report.hold, 1); + assert_eq!(report.applied, 0); +} + +#[test] +fn the_last_clip_is_never_cut_away() { + let words = spoken(&["a", "b"]); + let durations = [2.0]; + let mut project = project(&borrowed(&words), &durations); + let report = apply_source_cuts(timeline_mut(&mut project), &durations, &[0.0..2.0]); + assert_eq!(report.last_clip, 1); + assert_eq!(bounds(&project), [(0.0, 2.0)]); +} + +#[test] +fn slivers_at_clip_edges_are_absorbed() { + let durations = [4.0]; + let mut project = project(&[("a", 1.0, 1.3)], &durations); + let report = apply_source_cuts(timeline_mut(&mut project), &durations, &[0.005..1.0]); + assert_eq!(report.applied, 1); + assert_eq!(bounds(&project), [(1.0, 4.0)]); +} + +#[test] +fn touching_words_cut_at_their_shared_boundary() { + let data = captions(&[("one", 0.0, 0.5), ("two", 0.5, 1.0), ("three", 1.0, 1.5)]); + let doc = TranscriptDoc::build(&data); + let point = gap_cut(&doc, None, 1); + assert!(close(point, 0.5)); +} + +#[test] +fn cut_points_snap_to_the_quietest_moment_in_the_gap() { + let duration = 3.0; + let mut samples = Vec::new(); + for index in 0..(duration * 48_000.0) as usize { + let time = index as f64 / 48_000.0; + let quiet = (1.42..1.46).contains(&time); + let amplitude = if quiet { 0.0005 } else { 0.05 }; + samples.push((amplitude * (time * 440.0 * std::f64::consts::TAU).sin()) as f32); + } + let envelope = EnergyEnvelope::new( + vec![clip_envelope( + &[EnvelopeTrack { + slices: vec![&samples], + channels: 1, + offset_seconds: 0.0, + }], + duration, + )], + &[duration], + ); + let point = quietest_point(Some(&envelope), 1.3, 1.7); + assert!((1.42..=1.46).contains(&point), "{point}"); + assert!(close(quietest_point(None, 1.3, 1.7), 1.5)); + + let flat = vec![0.01f32; (duration * 48_000.0) as usize]; + let envelope = EnergyEnvelope::new( + vec![clip_envelope( + &[EnvelopeTrack { + slices: vec![&flat], + channels: 1, + offset_seconds: 0.0, + }], + duration, + )], + &[duration], + ); + let point = quietest_point(Some(&envelope), 1.0, 2.0); + assert!((point - 1.5).abs() <= HOP_SECONDS, "{point}"); +} + +#[test] +fn the_envelope_honours_track_offsets_and_split_slices() { + let mut samples = vec![0.0f32; 96_000]; + for sample in &mut samples[48_000..48_480] { + *sample = 0.5; + } + let (head, tail) = samples.split_at(1_001); + let envelope = clip_envelope( + &[EnvelopeTrack { + slices: vec![head, tail], + channels: 2, + offset_seconds: 0.25, + }], + 1.0, + ); + let loud: Vec<_> = envelope + .iter() + .enumerate() + .filter(|(_, energy)| **energy > 0.0) + .map(|(index, _)| index) + .collect(); + assert_eq!(loud, [(0.25 / HOP_SECONDS).round() as usize]); +} + +#[test] +fn shortening_pauses_leaves_the_target_silence() { + let words = [ + ("before", 1.0, 1.4), + ("after", 4.0, 4.4), + ("close", 4.6, 5.0), + ]; + let durations = [6.0]; + let mut project = project(&words, &durations); + let (doc, edl) = model(&project, &durations); + let pauses = plan_pause_cuts(&doc, &edl, None, 1.0, 0.5); + assert_eq!(pauses.len(), 1); + assert_eq!(pauses[0].after_word, 0); + let cuts: Vec<_> = pauses.iter().map(|pause| pause.cut.clone()).collect(); + apply_source_cuts(timeline_mut(&mut project), &durations, &cuts); + let (_, edl) = model(&project, &durations); + let gap = edl.source_to_output(4.0).unwrap() - edl.source_to_output(1.4).unwrap(); + assert!((gap - 0.5).abs() < 1e-6, "{gap}"); + assert_eq!(edl.kept, [true, true, true]); + assert!(plan_pause_cuts(&doc, &edl, None, 1.0, 0.5).is_empty()); +} + +#[test] +fn runs_collapse_neighbouring_words() { + assert_eq!(runs_of([5, 1, 2, 3, 7, 6, 2]), [1..4, 5..8]); + assert!(runs_of([]).is_empty()); +} + +#[test] +fn hostile_transcripts_do_not_panic() { + let durations = [10.0]; + let mut project = project( + &[ + ("zero", 1.0, 1.0), + ("backwards", 3.0, 2.0), + ("normal", 4.0, 4.5), + ("zero", 4.5, 4.5), + ], + &durations, + ); + let (doc, edl) = model(&project, &durations); + assert_eq!(doc.words.len(), 4); + assert!(edl.kept.iter().all(|kept| *kept)); + cut_words(&mut project, &durations, &[(0, 2), (3, 4)]); + let mut empty = ProjectConfiguration::default(); + assert!(editor_edits::ensure_timeline(&mut empty, &durations)); + empty.captions = Some(captions(&[])); + let doc = TranscriptDoc::build(empty.captions.as_ref().unwrap()); + assert!(doc.is_empty()); + assert!(plan_word_cuts(&doc, None, std::slice::from_ref(&(0..3))).is_empty()); +} + +#[test] +fn two_hour_timestamps_keep_their_precision() { + let base = 7_100.0; + let words: Vec<(String, f64, f64)> = (0..10) + .map(|index| { + let start = base + index as f64 * 0.5; + (format!("w{index}"), start, start + 0.3) + }) + .collect(); + let durations = [7_200.0]; + let mut project = project(&borrowed(&words), &durations); + cut_words(&mut project, &durations, &[(4, 5)]); + let (doc, edl) = model(&project, &durations); + assert_eq!( + edl.kept, + [true, true, true, true, false, true, true, true, true, true] + ); + let after = edl.source_to_output(doc.words[5].start).unwrap(); + let before = edl.source_to_output(doc.words[3].end).unwrap(); + assert!( + after - before > 0.15 && after - before < 0.5, + "{}", + after - before + ); +} + +#[test] +fn removing_hundreds_of_fillers_from_twenty_thousand_words_is_fast() { + let mut words = Vec::with_capacity(20_000); + let mut time = 0.5; + for index in 0..20_000 { + let text = if index % 40 == 20 { + "um,".to_string() + } else { + format!("w{index}") + }; + words.push((text, time, time + 0.25)); + time += if index % 400 == 399 { 1.96 } else { 0.36 }; + } + let durations = [time + 1.0]; + let mut project = project(&borrowed(&words), &durations); + + let started = std::time::Instant::now(); + let doc = TranscriptDoc::build(project.captions.as_ref().unwrap()); + let build = started.elapsed(); + let runs: Vec<_> = doc + .fillers + .iter() + .map(|filler| filler.words.clone()) + .collect(); + assert_eq!(runs.len(), 500); + + let started = std::time::Instant::now(); + let cuts = plan_word_cuts(&doc, None, &runs); + let report = apply_source_cuts(timeline_mut(&mut project), &durations, &cuts); + let apply = started.elapsed(); + assert_eq!(report.applied, 500); + assert_eq!(timeline(&project).segments.len(), 501); + + let started = std::time::Instant::now(); + let edl = TranscriptEdl::build(&doc, timeline(&project), &durations); + let rebuild = started.elapsed(); + let cut: Vec<_> = (0..doc.words.len()) + .filter(|word| !edl.kept[*word]) + .collect(); + assert_eq!(cut.len(), 500); + assert!(cut.iter().all(|word| doc.words[*word].text == "um,")); + + let started = std::time::Instant::now(); + let pauses = plan_pause_cuts(&doc, &edl, None, 1.0, 0.5); + let pause_plan = started.elapsed(); + assert_eq!(pauses.len(), 49); + assert!(pauses.iter().all(|pause| pause.after_word % 400 == 399)); + + let limit = |release_ms: u64| { + std::time::Duration::from_millis(if cfg!(debug_assertions) { + release_ms * 15 + } else { + release_ms + }) + }; + println!( + "20k words: doc {build:?}, 500 cuts {apply:?}, edl {rebuild:?}, pauses {pause_plan:?}" + ); + assert!(build < limit(80), "{build:?}"); + assert!(apply < limit(16), "{apply:?}"); + assert!(rebuild < limit(8), "{rebuild:?}"); + assert!(pause_plan < limit(2), "{pause_plan:?}"); +} + +#[test] +fn output_and_source_times_round_trip_through_a_transition() { + let durations = [10.0]; + let mut project = project(&[("a", 1.0, 1.2)], &durations); + let timeline = timeline_mut(&mut project); + assert!(editor_edits::split_clip_segment(timeline, 5.0, None)); + timeline.segments[1].start = 6.0; + timeline.transitions.push(ClipTransition { + segment_index: 1, + kind: ClipTransitionType::CrossFade, + duration: 1.0, + }); + let (_, edl) = model(&project, &durations); + assert!(close(edl.output_to_source(2.0).unwrap(), 2.0)); + assert!(close(edl.output_to_source(4.5).unwrap(), 6.5)); + assert!(close(edl.source_to_output(7.0).unwrap(), 5.0)); +} + +#[test] +fn search_matches_phrases_and_prefixes() { + let data = captions(&[ + ("You", 0.0, 0.1), + ("know,", 0.2, 0.3), + ("I", 0.4, 0.5), + ("know", 0.6, 0.7), + ("you", 0.8, 0.9), + ("knowingly", 1.0, 1.1), + ]); + let doc = TranscriptDoc::build(&data); + assert_eq!(super::view::find_matches(&doc, "you know"), [0..2, 4..6]); + assert_eq!(super::view::find_matches(&doc, "KNOW"), [1..2, 3..4, 5..6]); + assert!(super::view::find_matches(&doc, " ").is_empty()); +} + +#[test] +fn cuts_unknown_to_the_planner_are_no_ops() { + let durations = [2.0]; + let mut project = project(&[("a", 0.5, 0.8)], &durations); + let report = cuts::apply_source_cuts(timeline_mut(&mut project), &durations, &[5.0..6.0]); + assert_eq!(report, CutReport::default()); +} + +#[test] +fn restoring_brings_back_mask_keyframes_with_the_material() { + let words = spoken(&["one", "two", "three", "four"]); + let durations = [4.0]; + let mut project = project(&borrowed(&words), &durations); + let mut mask = editor_edits::default_mask_segment(0.0, 4.0, 0); + mask.keyframes.intensity = vec![ + cap_project::MaskScalarKeyframe { + time: 1.0, + value: 0.2, + }, + cap_project::MaskScalarKeyframe { + time: 3.0, + value: 0.8, + }, + ]; + timeline_mut(&mut project).mask_segments.push(mask); + cut_words(&mut project, &durations, &[(1, 2)]); + let doc = TranscriptDoc::build(project.captions.as_ref().unwrap()); + restore_words(timeline_mut(&mut project), &durations, &[], &doc, 1..2).unwrap(); + let mask = &timeline(&project).mask_segments[0]; + assert!(close(mask.end, 4.0)); + let times: Vec = mask + .keyframes + .intensity + .iter() + .map(|key| key.time) + .collect(); + assert!(close(times[0], 1.0) && close(times[1], 3.0), "{times:?}"); +} + +#[test] +fn restoring_puts_back_a_whole_take_that_was_cut() { + let durations = [2.0, 2.0, 2.0]; + let words = [ + ("first", 0.5, 0.9), + ("middle", 2.5, 2.9), + ("last", 4.5, 4.9), + ]; + let mut project = project(&words, &durations); + assert!(editor_edits::delete_clip_segments( + timeline_mut(&mut project), + &[1] + )); + assert_eq!(kept(&project, &durations), [true, false, true]); + let doc = TranscriptDoc::build(project.captions.as_ref().unwrap()); + restore_words(timeline_mut(&mut project), &durations, &[], &doc, 1..2).unwrap(); + assert_eq!(kept(&project, &durations), [true, true, true]); + let clips: Vec = timeline(&project) + .segments + .iter() + .map(|segment| segment.recording_clip) + .collect(); + assert_eq!(clips, [0, 1, 2]); + assert!(close( + editor_edits::clip_timeline_duration(timeline(&project)), + 6.0 + )); +} + +#[test] +fn a_restored_take_keeps_the_speed_of_its_neighbours() { + let durations = [2.0, 2.0, 2.0]; + let words = [ + ("first", 0.5, 0.9), + ("middle", 2.5, 2.9), + ("last", 4.5, 4.9), + ]; + let mut project = project(&words, &durations); + for segment in &mut timeline_mut(&mut project).segments { + segment.timescale = 2.0; + } + assert!(editor_edits::delete_clip_segments( + timeline_mut(&mut project), + &[1] + )); + let doc = TranscriptDoc::build(project.captions.as_ref().unwrap()); + restore_words(timeline_mut(&mut project), &durations, &[], &doc, 1..2).unwrap(); + assert!( + timeline(&project) + .segments + .iter() + .all(|segment| segment.timescale == 2.0) + ); + assert!(close( + editor_edits::clip_timeline_duration(timeline(&project)), + 3.0 + )); +} + +#[test] +fn pauses_across_a_clip_boundary_are_left_alone() { + let words = [("before", 1.0, 1.4), ("after", 5.0, 5.4)]; + let durations = [6.0]; + let mut project = project(&words, &durations); + assert!(editor_edits::split_clip_segment( + timeline_mut(&mut project), + 3.0, + None + )); + timeline_mut(&mut project).segments[1].timescale = 2.0; + let (doc, edl) = model(&project, &durations); + assert!(plan_pause_cuts(&doc, &edl, None, 1.0, 0.5).is_empty()); +} + +#[test] +fn pauses_are_measured_and_kept_in_playback_time() { + let words = [("before", 1.0, 1.4), ("after", 5.0, 5.4)]; + let durations = [6.0]; + let mut project = project(&words, &durations); + timeline_mut(&mut project).segments[0].timescale = 2.0; + let (doc, edl) = model(&project, &durations); + assert!(plan_pause_cuts(&doc, &edl, None, 2.0, 0.5).is_empty()); + let pauses = plan_pause_cuts(&doc, &edl, None, 1.5, 0.5); + assert_eq!(pauses.len(), 1); + assert!(close(pauses[0].length, 1.8)); + let cuts: Vec<_> = pauses.iter().map(|pause| pause.cut.clone()).collect(); + apply_source_cuts(timeline_mut(&mut project), &durations, &cuts); + let (_, edl) = model(&project, &durations); + let gap = edl.source_to_output(5.0).unwrap() - edl.source_to_output(1.4).unwrap(); + assert!((gap - 0.5).abs() < 1e-6, "{gap}"); +} + +#[cfg(target_os = "linux")] +mod keyboard { + use gpui::{ + AppContext, Context, Entity, InteractiveElement, IntoElement, Render, Styled, Window, div, + }; + + use crate::editor_window::EditorWindow; + use crate::transcript::WordSelection; + + struct KeyView { + editor: Entity, + _project: tempfile::TempDir, + } + + impl Render for KeyView { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + self.editor.update(cx, |editor, cx| { + div() + .size_full() + .track_focus(&editor.transcript.focus) + .on_key_down(cx.listener(EditorWindow::transcript_key_down)) + }) + } + } + + fn fixture( + cx: &mut gpui::TestAppContext, + ) -> (Entity, &mut gpui::VisualTestContext) { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().to_path_buf(); + let (view, cx) = cx.add_window_view(move |window, cx| { + let editor = cx.new(|cx| EditorWindow::new(path, window, cx)); + editor.update(cx, |editor, cx| { + let words = super::spoken(&["One", "two.", "Three", "four", "five"]); + editor.project = super::project(&super::borrowed(&words), &[5.0]); + editor.clip_display_durations = vec![5.0]; + editor.transcript.open = true; + editor.transcript.dirty = true; + editor.transcript_refresh(); + window.focus(&editor.transcript.focus, cx); + }); + KeyView { + editor, + _project: directory, + } + }); + (view.read_with(cx, |view, _| view.editor.clone()), cx) + } + + fn selection( + editor: &Entity, + cx: &mut gpui::VisualTestContext, + ) -> Option { + editor.read_with(cx, |editor, _| editor.transcript.selection) + } + + #[gpui::test] + fn arrows_extend_and_collapse_the_word_selection(cx: &mut gpui::TestAppContext) { + let (editor, cx) = fixture(cx); + cx.simulate_keystrokes("right"); + assert_eq!(selection(&editor, cx), Some(WordSelection::single(0))); + cx.simulate_keystrokes("right right"); + assert_eq!(selection(&editor, cx), Some(WordSelection::single(2))); + cx.simulate_keystrokes("shift-right shift-right"); + assert_eq!( + selection(&editor, cx), + Some(WordSelection { + anchor: 2, + focus: 4 + }) + ); + cx.simulate_keystrokes("shift-left shift-left shift-left"); + assert_eq!( + selection(&editor, cx), + Some(WordSelection { + anchor: 2, + focus: 1 + }) + ); + cx.simulate_keystrokes("escape"); + assert_eq!(selection(&editor, cx), None); + cx.simulate_keystrokes("ctrl-a"); + assert_eq!(selection(&editor, cx).map(WordSelection::range), Some(0..5)); + cx.simulate_keystrokes("home"); + assert_eq!(selection(&editor, cx), Some(WordSelection::single(0))); + cx.simulate_keystrokes("end"); + assert_eq!(selection(&editor, cx), Some(WordSelection::single(4))); + } + + #[gpui::test] + fn copy_puts_the_selected_words_on_the_clipboard(cx: &mut gpui::TestAppContext) { + let (editor, cx) = fixture(cx); + editor.update(cx, |editor, _| { + editor.transcript.selection = Some(WordSelection { + anchor: 1, + focus: 3, + }); + }); + cx.simulate_keystrokes("ctrl-c"); + let copied = cx.read_from_clipboard().and_then(|item| item.text()); + assert_eq!(copied.as_deref(), Some("two. Three four")); + } + + #[gpui::test] + fn a_loudness_envelope_loaded_with_old_audio_offsets_is_dropped(cx: &mut gpui::TestAppContext) { + let (editor, cx) = fixture(cx); + editor.update(cx, |editor, cx| { + editor.transcript.energy_loading = true; + editor.transcript.dirty = false; + let envelope = super::EnergyEnvelope::new(vec![vec![0.01; 200]], &[1.0]); + let installed = editor.transcript_energy_loaded( + vec![(0.0, 0.0)], + Some(vec![(0.25, 0.0)]), + envelope, + cx, + ); + assert!(!installed); + assert!(editor.transcript.energy.is_none()); + assert!(editor.transcript.dirty); + assert!(!editor.transcript.energy_loading); + + let envelope = super::EnergyEnvelope::new(vec![vec![0.01; 200]], &[1.0]); + let installed = editor.transcript_energy_loaded( + vec![(0.25, 0.0)], + Some(vec![(0.25, 0.0)]), + envelope, + cx, + ); + assert!(installed); + assert!(editor.transcript.energy.is_some()); + }); + } +} + +#[test] +fn a_restore_that_fails_part_way_changes_nothing() { + let words = spoken(&["a", "b", "c", "d", "e", "f", "g", "h"]); + let durations = [5.0]; + let mut project = project(&borrowed(&words), &durations); + cut_words(&mut project, &durations, &[(3, 4)]); + let timeline = timeline_mut(&mut project); + assert!(editor_edits::split_clip_segment(timeline, 2.55, None)); + assert!(editor_edits::split_clip_segment(timeline, 2.85, None)); + assert!(editor_edits::delete_clip_segments(timeline, &[2])); + timeline.transitions.push(ClipTransition { + segment_index: 2, + kind: ClipTransitionType::CrossFade, + duration: 0.06, + }); + assert!(timeline.effective_transition(2).is_some()); + let before = bounds(&project); + assert_eq!(kept(&project, &durations)[3..5], [false, false]); + let doc = TranscriptDoc::build(project.captions.as_ref().unwrap()); + let result = restore_words(timeline_mut(&mut project), &durations, &[], &doc, 3..5); + assert_eq!(result, Err(RestoreBlocker::Transition)); + assert_eq!(bounds(&project), before); +} + +#[test] +fn partly_trimmed_words_map_to_their_surviving_part() { + let words = [ + ("first", 0.5, 1.0), + ("middle", 1.2, 1.7), + ("last", 1.9, 2.4), + ]; + let durations = [3.0]; + let mut project = project(&words, &durations); + let segment = &mut timeline_mut(&mut project).segments[0]; + segment.start = 0.65; + segment.end = 2.2; + let (doc, edl) = model(&project, &durations); + assert!(edl.is_kept(0) && edl.is_kept(2)); + assert_eq!(edl.source_to_output(doc.words[0].start), None); + assert_eq!(edl.source_to_output(doc.words[2].end), None); + + let start = edl.output_start_of(&doc.words[0]).unwrap(); + assert!(close(start, 0.0), "{start}"); + let end = edl.output_end_of(&doc.words[2]).unwrap(); + assert!(close(end, 2.2 - 0.65), "{end}"); + let middle = edl.output_start_of(&doc.words[1]).unwrap(); + assert!(close(middle, 1.2 - 0.65), "{middle}"); +} + +#[test] +fn a_restored_take_comes_back_with_its_own_settings() { + let durations = [2.0, 2.0, 2.0]; + let words = [ + ("first", 0.5, 0.9), + ("middle", 2.5, 2.9), + ("last", 4.5, 4.9), + ]; + let mut project = project(&words, &durations); + let middle = &mut timeline_mut(&mut project).segments[1]; + middle.timescale = 2.0; + middle.volume = Some(0.5); + middle.speed_audio_mode = Some(cap_project::ClipSpeedAudioMode::MaintainPitch); + middle.hide_cursor = Some(true); + middle.name = Some("Second take".into()); + let original = middle.clone(); + let mut history = editor_edits::ProjectHistory::new(project.clone()); + + let report = apply_source_cuts(timeline_mut(&mut project), &durations, &[2.0..4.0]); + assert_eq!(report.applied, 1); + assert_eq!(timeline(&project).segments.len(), 2); + history.record(&project); + assert_eq!(kept(&project, &durations), [true, false, true]); + + let settings = |segment: &cap_project::TimelineSegment| { + ( + segment.recording_clip, + segment.timescale, + segment.start, + segment.end, + segment.name.clone(), + segment.speed_audio_mode, + segment.volume, + segment.hide_cursor, + ) + }; + let removed = history.removed_takes(timeline(&project)); + assert_eq!(removed.len(), 1); + assert_eq!(settings(&removed[0]), settings(&original)); + let doc = TranscriptDoc::build(project.captions.as_ref().unwrap()); + restore_words(timeline_mut(&mut project), &durations, &removed, &doc, 1..2).unwrap(); + assert_eq!(kept(&project, &durations), [true, true, true]); + let segments = &timeline(&project).segments; + assert_eq!(segments.len(), 3); + assert_eq!(settings(&segments[1]), settings(&original)); + assert!(segments[0].timescale == 1.0 && segments[2].timescale == 1.0); + assert!(segments[0].volume.is_none() && segments[2].hide_cursor.is_none()); + assert!(close( + editor_edits::clip_timeline_duration(timeline(&project)), + 2.0 + 1.0 + 2.0 + )); +} diff --git a/apps/desktop-gpui/src/transcript/view.rs b/apps/desktop-gpui/src/transcript/view.rs new file mode 100644 index 00000000000..89d27dc43ae --- /dev/null +++ b/apps/desktop-gpui/src/transcript/view.rs @@ -0,0 +1,2407 @@ +use std::cell::RefCell; +use std::collections::{HashMap, HashSet}; +use std::ops::Range; +use std::rc::Rc; +use std::sync::Arc; +use std::time::Instant; + +use cap_project::disfluency::{Disfluency, DisfluencyKind, normalize_word}; +use gpui::{ + AnyElement, AppContext, ClipboardItem, Context, FontWeight, HighlightStyle, Hsla, + InteractiveElement, IntoElement, KeyDownEvent, ListOffset, MouseButton, MouseDownEvent, + MouseMoveEvent, ParentElement, Pixels, Point, SharedString, StatefulInteractiveElement, + StrikethroughStyle, Styled, StyledText, TextLayout, UnderlineStyle, WeakEntity, Window, div, + prelude::FluentBuilder, px, svg, +}; + +use super::cuts::{self, CutReport, RestoreBlocker}; +use super::model::{TranscriptDoc, TranscriptEdl}; +use super::{ + CleanupTab, DragUnit, FOLLOW_PAUSE, MAX_PLAYER_SHARE, MIN_PLAYER_SHARE, PAUSE_KEEP_RANGE, + PAUSE_LONGER_RANGE, SearchState, WordDrag, WordSelection, category_index, +}; +use crate::editor_window::EditorWindow; +use crate::i18n::tr; +use crate::theme::Theme; +use crate::ui; + +const TEXT_SIZE: f32 = 15.; +const LINE_HEIGHT: f32 = 25.; +const STAMP_WIDTH: f32 = 46.; +const FOLLOW_MARGIN: f32 = 48.; +const FOLLOW_ANCHOR: f32 = 0.32; +const LISTEN_BEFORE: f64 = 1.5; +const LISTEN_AFTER: f64 = 1.0; + +pub(super) fn find_matches(doc: &TranscriptDoc, query: &str) -> Vec> { + let needle: Vec = query + .split_whitespace() + .map(normalize_word) + .filter(|word| !word.is_empty()) + .collect(); + if needle.is_empty() { + return Vec::new(); + } + let normalized: Vec = doc + .words + .iter() + .map(|word| normalize_word(&word.text)) + .collect(); + let mut matches = Vec::new(); + let mut index = 0; + while index + needle.len() <= normalized.len() { + let last = needle.len() - 1; + let hit = needle.iter().enumerate().all(|(offset, word)| { + let candidate = &normalized[index + offset]; + if offset == last { + candidate.starts_with(word.as_str()) + } else { + candidate == word + } + }); + if hit { + matches.push(index..index + needle.len()); + index += needle.len(); + } else { + index += 1; + } + } + matches +} + +fn sentence_bounds(doc: &TranscriptDoc, word: usize) -> (usize, usize) { + let ends = |index: usize| { + doc.words[index] + .text + .trim_end_matches(['"', '\'', '”', '’', ')']) + .ends_with(['.', '!', '?', '…']) + }; + let paragraph = &doc.paragraphs[doc.paragraph_of(word)].words; + let mut start = word; + while start > paragraph.start && !ends(start - 1) { + start -= 1; + } + let mut end = word; + while end + 1 < paragraph.end && !ends(end) { + end += 1; + } + (start, end) +} + +fn unit_bounds(doc: &TranscriptDoc, word: usize, unit: DragUnit) -> (usize, usize) { + match unit { + DragUnit::Word => (word, word), + DragUnit::Sentence => sentence_bounds(doc, word), + DragUnit::Paragraph => { + let range = &doc.paragraphs[doc.paragraph_of(word)].words; + (range.start, range.end - 1) + } + } +} + +fn kind_label(kind: DisfluencyKind) -> &'static str { + match kind { + DisfluencyKind::Hesitation => tr::editor::transcript::fillers::hesitation(), + DisfluencyKind::Repetition => tr::editor::transcript::fillers::repetition(), + DisfluencyKind::FalseStart => tr::editor::transcript::fillers::false_start(), + DisfluencyKind::Discourse => tr::editor::transcript::fillers::discourse(), + } +} + +fn kind_hint(kind: DisfluencyKind) -> &'static str { + match kind { + DisfluencyKind::Hesitation => tr::editor::transcript::fillers::hesitation_hint(), + DisfluencyKind::Repetition => tr::editor::transcript::fillers::repetition_hint(), + DisfluencyKind::FalseStart => tr::editor::transcript::fillers::false_start_hint(), + DisfluencyKind::Discourse => tr::editor::transcript::fillers::discourse_hint(), + } +} + +fn seconds_label(value: f64) -> String { + tr::editor::transcript::seconds(crate::i18n::decimal(format!("{value:.1}"))).to_string() +} + +#[derive(Clone, Copy)] +struct Palette { + text_1: Hsla, + text_2: Hsla, + text_3: Hsla, + accent: Hsla, + selection: Hsla, + active_bg: Hsla, + filler_bg: Hsla, + filler_text: Hsla, + filler_line: Hsla, + match_bg: Hsla, + current_match_bg: Hsla, + restore_bg: Hsla, +} + +impl Palette { + fn new(theme: &Theme) -> Self { + let editor = theme.editor; + let accent = Hsla::from(editor.accent); + Self { + text_1: Hsla::from(editor.text_1), + text_2: Hsla::from(editor.text_2), + text_3: Hsla::from(editor.text_3), + accent, + selection: accent.opacity(0.24), + active_bg: accent.opacity(0.12), + filler_bg: Hsla::from(theme.amber_3), + filler_text: Hsla::from(theme.amber_11), + filler_line: Hsla::from(theme.amber_11).opacity(0.7), + match_bg: Hsla::from(theme.amber_6).opacity(0.55), + current_match_bg: Hsla::from(theme.amber_6), + restore_bg: accent.opacity(0.14), + } + } +} + +struct ParagraphPainter { + doc: Arc, + edl: Option>, + selection: Option>, + active: Option, + hovered_cut: Option>, + matches: Arc>>, + current_match: Option>, + ignored: Arc>, + palette: Palette, + editor: WeakEntity, + layouts: Rc>>, +} + +impl ParagraphPainter { + fn is_kept(&self, word: usize) -> bool { + self.edl.as_ref().is_none_or(|edl| edl.is_kept(word)) + } + + fn in_match(&self, word: usize) -> Option { + let index = self.matches.partition_point(|range| range.end <= word); + let range = self + .matches + .get(index) + .filter(|range| range.contains(&word))?; + Some(self.current_match.as_ref() == Some(range)) + } + + fn word_style(&self, word: usize) -> HighlightStyle { + let palette = &self.palette; + let mut style = HighlightStyle::default(); + let kept = self.is_kept(word); + if !kept { + style.color = Some(palette.text_3); + style.strikethrough = Some(StrikethroughStyle { + thickness: px(1.), + color: Some(palette.text_3), + }); + if self + .hovered_cut + .as_ref() + .is_some_and(|run| run.contains(&word)) + { + style.background_color = Some(palette.restore_bg); + style.color = Some(palette.text_2); + } + } else if let Some(filler) = self.doc.filler(word) + && !self.ignored.contains(&filler.words.start) + { + if filler.kind == DisfluencyKind::Discourse { + style.underline = Some(UnderlineStyle { + thickness: px(1.5), + color: Some(palette.filler_line), + wavy: false, + }); + } else { + style.background_color = Some(palette.filler_bg); + style.color = Some(palette.filler_text); + } + } + if kept && self.active == Some(word) { + style.color = Some(palette.accent); + style.background_color = Some(palette.active_bg); + } + if let Some(current) = self.in_match(word) { + style.background_color = Some(if current { + palette.current_match_bg + } else { + palette.match_bg + }); + } + if self + .selection + .as_ref() + .is_some_and(|range| range.contains(&word)) + { + style.background_color = Some(palette.selection); + } + style + } + + fn paragraph(&self, index: usize) -> AnyElement { + let Some(paragraph) = self.doc.paragraphs.get(index) else { + return div().into_any_element(); + }; + let mut highlights: Vec<(Range, HighlightStyle)> = Vec::new(); + for (offset, span) in paragraph.spans.iter().enumerate() { + let style = self.word_style(paragraph.words.start + offset); + if style == HighlightStyle::default() { + continue; + } + match highlights.last_mut() { + Some((range, previous)) + if *previous == style + && offset > 0 + && range.end == paragraph.spans[offset - 1].end => + { + range.end = span.end; + } + _ => highlights.push((span.clone(), style)), + } + } + let text = StyledText::new(paragraph.text.clone()).with_highlights(highlights); + let layout = text.layout().clone(); + + let first_kept = paragraph.words.clone().find(|word| self.is_kept(*word)); + let stamp = first_kept + .and_then(|word| self.edl.as_ref()?.output_start_of(&self.doc.words[word])) + .map(crate::editor_timeline::format_time); + let hovering_cut_here = self + .hovered_cut + .as_ref() + .is_some_and(|run| run.start < paragraph.words.end && paragraph.words.start < run.end); + + let editor = self.editor.clone(); + let down_layout = layout.clone(); + let move_editor = self.editor.clone(); + let move_layout = layout.clone(); + let stamp_editor = self.editor.clone(); + let layouts = self.layouts.clone(); + let paint_layout = layout.clone(); + div() + .id(("transcript-paragraph", index)) + .w_full() + .flex() + .flex_row() + .items_start() + .pb(px(14.)) + .child( + div() + .id(("transcript-stamp", index)) + .flex_none() + .w(px(STAMP_WIDTH)) + .pt(px(3.)) + .text_size(px(11.)) + .line_height(px(LINE_HEIGHT - 4.)) + .text_color(self.palette.text_3) + .cursor_pointer() + .hover(|style| style.text_color(self.palette.text_2)) + .children(stamp) + .on_mouse_down(MouseButton::Left, move |_, window, cx| { + stamp_editor + .update(cx, |this, cx| { + this.transcript_select_paragraph(index, window, cx); + }) + .ok(); + }), + ) + .child( + div() + .relative() + .flex_1() + .min_w_0() + .when(hovering_cut_here, |this| this.cursor_pointer()) + .child(text) + .child( + gpui::canvas( + move |_, _, _| { + layouts.borrow_mut().insert(index, paint_layout); + }, + |_, _, _, _| {}, + ) + .absolute() + .size_0(), + ) + .on_mouse_down(MouseButton::Left, move |event, window, cx| { + let byte = byte_at(&down_layout, event.position); + editor + .update(cx, |this, cx| { + this.transcript_mouse_down(index, byte, event, window, cx); + }) + .ok(); + }) + .on_mouse_move(move |event, window, cx| { + let byte = byte_at(&move_layout, event.position); + move_editor + .update(cx, |this, cx| { + this.transcript_mouse_move(index, byte, event, window, cx); + }) + .ok(); + }), + ) + .into_any_element() + } +} + +const ROW_HEIGHT: f32 = 30.; +const MAX_VISIBLE_ROWS: usize = 8; + +fn snippet_around(doc: &TranscriptDoc, words: Range) -> (String, Range) { + let paragraph = &doc.paragraphs[doc.paragraph_of(words.start)].words; + let before_start = paragraph.start.max(words.start.saturating_sub(4)); + let after_end = doc.paragraphs[doc.paragraph_of(words.end - 1)] + .words + .end + .min(words.end + 4); + let phrase = doc.text_of(words.clone()); + let mut snippet = String::new(); + if before_start < words.start { + snippet.push_str("… "); + snippet.push_str(&doc.text_of(before_start..words.start)); + snippet.push(' '); + } + let highlight = snippet.len()..snippet.len() + phrase.len(); + snippet.push_str(&phrase); + if words.end < after_end { + snippet.push(' '); + snippet.push_str(&doc.text_of(words.end..after_end)); + snippet.push_str(" …"); + } + (snippet, highlight) +} + +fn row_stamp(palette: Palette, stamp: String) -> impl IntoElement { + div() + .flex_none() + .w(px(38.)) + .text_size(px(11.)) + .text_color(palette.text_3) + .child(stamp) +} + +#[allow(clippy::too_many_arguments)] +fn filler_row( + theme: &Theme, + palette: Palette, + doc: &TranscriptDoc, + edl: &TranscriptEdl, + index: usize, + words: Range, + selected: bool, + editor: WeakEntity, +) -> AnyElement { + let (snippet, highlight) = snippet_around(doc, words.clone()); + let text = StyledText::new(snippet).with_highlights([( + highlight, + HighlightStyle { + background_color: Some(palette.filler_bg), + color: Some(palette.filler_text), + ..Default::default() + }, + )]); + let stamp = edl + .output_start_of(&doc.words[words.start]) + .map(crate::editor_timeline::format_time) + .unwrap_or_default(); + let on_row = { + let editor = editor.clone(); + let words = words.clone(); + move |_: &gpui::ClickEvent, window: &mut Window, cx: &mut gpui::App| { + editor + .update(cx, |this, cx| { + window.focus(&this.transcript.focus, cx); + this.transcript_focus_filler(words.clone(), false, cx); + }) + .ok(); + } + }; + let on_listen = { + let editor = editor.clone(); + let words = words.clone(); + move |_: &gpui::ClickEvent, _: &mut Window, cx: &mut gpui::App| { + editor + .update(cx, |this, cx| { + this.transcript_focus_filler(words.clone(), true, cx); + }) + .ok(); + } + }; + let on_keep = { + let editor = editor.clone(); + let start = words.start; + move |_: &gpui::ClickEvent, _: &mut Window, cx: &mut gpui::App| { + editor + .update(cx, |this, cx| { + this.transcript.cleanup.ignored.insert(start); + this.invalidate_transcript(cx); + }) + .ok(); + } + }; + let on_remove = move |_: &gpui::ClickEvent, window: &mut Window, cx: &mut gpui::App| { + editor + .update(cx, |this, cx| { + this.transcript_remove_filler(words.clone(), window, cx); + }) + .ok(); + }; + div() + .id(("transcript-filler", index)) + .w_full() + .flex() + .flex_row() + .items_center() + .gap(px(4.)) + .h(px(ROW_HEIGHT)) + .px(px(6.)) + .rounded(px(6.)) + .when(selected, |this| this.bg(palette.selection.opacity(0.6))) + .hover(|style| style.bg(Hsla::from(theme.editor.ctl))) + .cursor_pointer() + .on_click(on_row) + .child(row_stamp(palette, stamp)) + .child( + div() + .flex_1() + .min_w_0() + .text_size(px(13.)) + .text_color(palette.text_2) + .truncate() + .child(text), + ) + .child( + ui::EditorButton::plain(theme, ("transcript-filler-listen", index)) + .left_icon("icons/play.svg") + .tooltip(theme, tr::editor::transcript::fillers::listen()) + .on_click(on_listen), + ) + .child( + ui::EditorButton::plain(theme, ("transcript-filler-keep", index)) + .left_icon("icons/check.svg") + .tooltip(theme, tr::editor::transcript::fillers::keep()) + .on_click(on_keep), + ) + .child( + ui::EditorButton::plain(theme, ("transcript-filler-remove", index)) + .left_icon("icons/x.svg") + .tooltip(theme, tr::editor::transcript::fillers::remove()) + .on_click(on_remove), + ) + .into_any_element() +} + +fn pause_row( + theme: &Theme, + palette: Palette, + doc: &TranscriptDoc, + edl: &TranscriptEdl, + pause: &cuts::PauseCut, + keep: f64, + editor: WeakEntity, +) -> AnyElement { + let word = pause.after_word; + let stamp = edl + .output_end_of(&doc.words[word]) + .map(crate::editor_timeline::format_time) + .unwrap_or_default(); + let before = doc.text_of(word.saturating_sub(3)..word + 1); + let after = doc.text_of(word + 1..(word + 4).min(doc.words.len())); + let text = format!( + "{before} {} → {} {after}", + seconds_label(pause.length), + seconds_label(keep) + ); + div() + .id(("transcript-pause", word)) + .w_full() + .flex() + .flex_row() + .items_center() + .gap(px(4.)) + .h(px(ROW_HEIGHT)) + .px(px(6.)) + .rounded(px(6.)) + .hover(|style| style.bg(Hsla::from(theme.editor.ctl))) + .cursor_pointer() + .on_click(move |_, window, cx| { + editor + .update(cx, |this, cx| { + window.focus(&this.transcript.focus, cx); + this.transcript_focus_filler(word..word + 2, true, cx); + }) + .ok(); + }) + .child(row_stamp(palette, stamp)) + .child( + div() + .flex_1() + .min_w_0() + .text_size(px(13.)) + .text_color(palette.text_2) + .truncate() + .child(text), + ) + .into_any_element() +} + +fn byte_at(layout: &TextLayout, position: Point) -> usize { + match layout.index_for_position(position) { + Ok(index) | Err(index) => index, + } +} + +impl EditorWindow { + pub(crate) fn toggle_transcript(&mut self, window: &mut Window, cx: &mut Context) { + if !self.project_ready() { + return; + } + if self.transcript.open { + self.transcript.open = false; + self.transcript.drag = None; + self.transcript.resize = None; + self.focus_root(window, cx); + } else { + if self.clips.open { + self.close_clips(window, cx); + } + self.transcript.open = true; + self.transcript.dirty = true; + let started = Instant::now(); + self.transcript_refresh(); + tracing::info!( + elapsed_ms = started.elapsed().as_secs_f64() * 1000.0, + words = self + .transcript + .doc + .as_ref() + .map_or(0, |doc| doc.words.len()), + paragraphs = self + .transcript + .doc + .as_ref() + .map_or(0, |doc| doc.paragraphs.len()), + "transcript opened" + ); + self.transcript_sync_active(false, cx); + if let Some(active) = self.transcript.active { + self.transcript_reveal(active, true); + } + window.focus(&self.transcript.focus, cx); + self.transcript_load_energy(cx); + } + cx.notify(); + } + + pub(crate) fn transcript_refresh(&mut self) -> bool { + if !self.transcript.open { + return false; + } + let durations = self.clip_display_durations.clone(); + self.transcript.refresh(&self.project, &durations) + } + + pub(crate) fn transcript_sync_active(&mut self, follow: bool, cx: &mut Context) { + if !self.transcript.open { + return; + } + let (Some(doc), Some(edl)) = (&self.transcript.doc, &self.transcript.edl) else { + return; + }; + let active = edl + .output_to_source(self.playhead_time()) + .and_then(|source| doc.word_at_source(source)) + .filter(|word| edl.is_kept(*word)); + if active == self.transcript.active { + return; + } + self.transcript.active = active; + if follow + && let Some(active) = active + && self + .transcript + .user_scrolled + .is_none_or(|at| at.elapsed() > FOLLOW_PAUSE) + && self.transcript.drag.is_none() + { + self.transcript_reveal(active, true); + } + self.invalidate_transcript(cx); + } + + pub(crate) fn transcript_reveal(&mut self, word: usize, follow: bool) { + let Some(doc) = self.transcript.doc.clone() else { + return; + }; + let paragraph = doc.paragraph_of(word); + let viewport = self.transcript.list.viewport_bounds(); + let height = viewport.size.height; + if height <= px(0.) { + self.transcript.list.scroll_to(ListOffset { + item_ix: paragraph, + offset_in_item: px(0.), + }); + return; + } + let position = self + .transcript + .layouts + .borrow() + .get(¶graph) + .zip(doc.paragraphs[paragraph].span(word)) + .and_then(|(layout, span)| layout.position_for_index(span.start)); + let visible_paragraph = + self.transcript + .list + .bounds_for_item(paragraph) + .is_some_and(|bounds| { + bounds.bottom() > viewport.top() && bounds.top() < viewport.bottom() + }); + match position.filter(|_| visible_paragraph) { + Some(position) => { + let top = viewport.top() + px(FOLLOW_MARGIN); + let bottom = viewport.bottom() - px(FOLLOW_MARGIN + LINE_HEIGHT); + if position.y >= top && position.y <= bottom { + return; + } + let target = if follow { + viewport.top() + height * FOLLOW_ANCHOR + } else if position.y < top { + top + } else { + bottom + }; + self.transcript.list.scroll_by(position.y - target); + } + None => { + self.transcript.list.scroll_to(ListOffset { + item_ix: paragraph, + offset_in_item: px(0.), + }); + if follow { + self.transcript.list.scroll_by(-(height * FOLLOW_ANCHOR)); + } + } + } + } + + fn transcript_doc(&self) -> Option<(Arc, Arc)> { + Some((self.transcript.doc.clone()?, self.transcript.edl.clone()?)) + } + + fn transcript_seek_word(&mut self, word: usize, cx: &mut Context) { + let Some((doc, edl)) = self.transcript_doc() else { + return; + }; + let Some(output) = doc + .words + .get(word) + .and_then(|word| edl.output_start_of(word)) + else { + return; + }; + self.transcript.user_scrolled = None; + self.seek_to_time(output, cx); + self.transcript.active = edl.is_kept(word).then_some(word); + } + + pub(crate) fn transcript_mouse_down( + &mut self, + paragraph: usize, + byte: usize, + event: &MouseDownEvent, + window: &mut Window, + cx: &mut Context, + ) { + let Some((doc, edl)) = self.transcript_doc() else { + return; + }; + let Some(word) = doc.paragraphs.get(paragraph).map(|p| p.word_at_byte(byte)) else { + return; + }; + window.focus(&self.transcript.focus, cx); + cx.stop_propagation(); + self.set_selection(None, cx); + + if !edl.is_kept(word) && !event.modifiers.shift && event.click_count == 1 { + if let Some(run) = edl.cut_run_of(word) { + let words = edl.cut_runs[run].clone(); + self.transcript_restore(words, window, cx); + } + return; + } + + let unit = match event.click_count { + 2 => DragUnit::Sentence, + count if count >= 3 => DragUnit::Paragraph, + _ => DragUnit::Word, + }; + let origin = unit_bounds(&doc, word, unit); + if event.modifiers.shift + && let Some(selection) = self + .transcript + .selection + .or(self.transcript.caret.map(WordSelection::single)) + { + self.transcript.selection = Some(WordSelection { + anchor: selection.anchor, + focus: word, + }); + self.transcript.drag = Some(WordDrag { + unit: DragUnit::Word, + origin: (selection.anchor, selection.anchor), + }); + } else { + self.transcript.selection = Some(WordSelection { + anchor: origin.0, + focus: origin.1, + }); + self.transcript.drag = Some(WordDrag { unit, origin }); + self.transcript_seek_word(origin.0, cx); + } + self.transcript.caret = None; + self.invalidate_transcript(cx); + } + + pub(crate) fn transcript_mouse_move( + &mut self, + paragraph: usize, + byte: usize, + event: &MouseMoveEvent, + _window: &mut Window, + cx: &mut Context, + ) { + let Some((doc, edl)) = self.transcript_doc() else { + return; + }; + let Some(word) = doc.paragraphs.get(paragraph).map(|p| p.word_at_byte(byte)) else { + return; + }; + if let Some(drag) = self.transcript.drag { + if !event.dragging() { + self.transcript.drag = None; + return; + } + let (low, high) = unit_bounds(&doc, word, drag.unit); + let selection = if word < drag.origin.0 { + WordSelection { + anchor: drag.origin.1, + focus: low, + } + } else { + WordSelection { + anchor: drag.origin.0, + focus: high.max(drag.origin.1), + } + }; + if self.transcript.selection != Some(selection) { + self.transcript.selection = Some(selection); + self.invalidate_transcript(cx); + } + return; + } + let hovered = (!edl.is_kept(word)).then(|| edl.cut_run_of(word)).flatten(); + if hovered != self.transcript.hovered_cut { + self.transcript.hovered_cut = hovered; + self.invalidate_transcript(cx); + } + } + + fn transcript_select_paragraph( + &mut self, + paragraph: usize, + window: &mut Window, + cx: &mut Context, + ) { + let Some(doc) = self.transcript.doc.clone() else { + return; + }; + let Some(range) = doc.paragraphs.get(paragraph).map(|p| p.words.clone()) else { + return; + }; + window.focus(&self.transcript.focus, cx); + cx.stop_propagation(); + self.transcript.selection = Some(WordSelection { + anchor: range.start, + focus: range.end - 1, + }); + self.transcript_seek_word(range.start, cx); + self.invalidate_transcript(cx); + } + + fn transcript_end_drag(&mut self, cx: &mut Context) { + if self.transcript.drag.take().is_some() { + self.invalidate_transcript(cx); + } + } + + pub(crate) fn transcript_key_down( + &mut self, + event: &KeyDownEvent, + window: &mut Window, + cx: &mut Context, + ) { + if ui::text_input_has_focus(window, cx) { + return; + } + let Some((doc, edl)) = self.transcript_doc() else { + return; + }; + if doc.words.is_empty() { + return; + } + let keystroke = &event.keystroke; + let modifiers = keystroke.modifiers; + let command = modifiers.secondary(); + let last = doc.words.len() - 1; + let handled = match keystroke.key.as_str() { + "f" if command => { + self.transcript_open_search(window, cx); + true + } + "a" if command && !modifiers.shift => { + self.transcript.selection = Some(WordSelection { + anchor: 0, + focus: last, + }); + true + } + "c" if command && !modifiers.shift => { + self.transcript_copy(cx); + true + } + "backspace" | "delete" if !command && !modifiers.alt => { + if self.transcript.selection.is_some() { + self.transcript_delete_selection(window, cx); + true + } else { + false + } + } + "enter" if !command => { + self.transcript_play_selection(cx); + true + } + "escape" => { + if self.transcript.search.is_some() { + self.transcript_close_search(window, cx); + true + } else if self.transcript.selection.take().is_some() { + true + } else if self.transcript.cleanup.open { + self.transcript.cleanup.open = false; + true + } else { + false + } + } + "left" | "right" | "up" | "down" | "home" | "end" if !modifiers.alt => { + let from = self + .transcript + .selection + .map(|selection| selection.focus) + .or(self.transcript.caret) + .or(self.transcript.active) + .unwrap_or(0); + let target = match keystroke.key.as_str() { + "left" if command => doc.paragraphs[doc.paragraph_of(from)].words.start, + "right" if command => doc.paragraphs[doc.paragraph_of(from)].words.end - 1, + "left" => from.saturating_sub(1), + "right" => (from + 1).min(last), + "up" if command => 0, + "down" if command => last, + "home" => 0, + "end" => last, + "up" => self.transcript_vertical(&doc, from, -1), + _ => self.transcript_vertical(&doc, from, 1), + }; + let had_selection = self.transcript.selection.is_some(); + if modifiers.shift { + let anchor = self + .transcript + .selection + .map_or(from, |selection| selection.anchor); + self.transcript.selection = Some(WordSelection { + anchor, + focus: target, + }); + } else { + let target = if had_selection + || self.transcript.caret.is_some() + || self.transcript.active.is_some() + { + target + } else { + 0 + }; + self.transcript.selection = Some(WordSelection::single(target)); + if edl.is_kept(target) { + self.transcript_seek_word(target, cx); + } + } + self.transcript.caret = None; + self.transcript_reveal(target, false); + true + } + _ => false, + }; + if handled { + cx.stop_propagation(); + window.prevent_default(); + self.invalidate_transcript(cx); + } + } + + fn transcript_vertical(&self, doc: &TranscriptDoc, from: usize, direction: i32) -> usize { + let paragraph = doc.paragraph_of(from); + let layouts = self.transcript.layouts.borrow(); + let fallback = || { + if direction < 0 { + paragraph + .checked_sub(1) + .map_or(0, |previous| doc.paragraphs[previous].words.end - 1) + } else { + doc.paragraphs + .get(paragraph + 1) + .map_or(doc.words.len() - 1, |next| next.words.start) + } + }; + let Some(position) = layouts + .get(¶graph) + .zip(doc.paragraphs[paragraph].span(from)) + .and_then(|(layout, span)| layout.position_for_index(span.start)) + else { + return fallback(); + }; + let line = px(LINE_HEIGHT); + let target = Point { + x: position.x + px(2.), + y: position.y + line * 0.5 + line * direction as f32, + }; + for (index, layout) in layouts.iter() { + let bounds = layout.bounds(); + if target.y >= bounds.top() && target.y <= bounds.bottom() { + let probe = Point { + x: target.x.max(bounds.left()), + y: target.y, + }; + return doc.paragraphs[*index].word_at_byte(byte_at(layout, probe)); + } + } + fallback() + } + + fn transcript_copy(&mut self, cx: &mut Context) { + let (Some((doc, edl)), Some(selection)) = + (self.transcript_doc(), self.transcript.selection) + else { + return; + }; + let text = selection + .range() + .filter(|word| edl.is_kept(*word)) + .map(|word| doc.words[word].text.as_str()) + .collect::>() + .join(" "); + if !text.is_empty() { + cx.write_to_clipboard(ClipboardItem::new_string(text)); + } + } + + fn transcript_play_selection(&mut self, cx: &mut Context) { + let (Some((doc, edl)), Some(selection)) = + (self.transcript_doc(), self.transcript.selection) + else { + return; + }; + let mut kept = selection.range().filter(|word| edl.is_kept(*word)); + let Some(first) = kept.next() else { + return; + }; + let last = kept.next_back().unwrap_or(first); + let (Some(from), Some(until)) = ( + edl.output_start_of(&doc.words[first]), + edl.output_end_of(&doc.words[last]), + ) else { + return; + }; + self.play_range(from, until + 0.15, cx); + } + + pub(super) fn transcript_cut_runs( + &mut self, + runs: &[Range], + reason: &'static str, + window: &mut Window, + cx: &mut Context, + ) -> CutReport { + let Some(doc) = self.transcript.doc.clone() else { + return CutReport::default(); + }; + let energy = self.transcript.energy.clone(); + let cuts = cuts::plan_word_cuts(&doc, energy.as_deref(), runs); + self.transcript_apply_cuts(&cuts, reason, window, cx) + } + + fn transcript_apply_cuts( + &mut self, + cuts: &[Range], + reason: &'static str, + window: &mut Window, + cx: &mut Context, + ) -> CutReport { + if cuts.is_empty() { + return CutReport::default(); + } + let started = Instant::now(); + let durations = self.clip_display_durations.clone(); + let mut report = CutReport::default(); + self.edit_timeline_project( + |project| { + if !crate::editor_edits::ensure_timeline(project, &durations) { + return false; + } + let Some(timeline) = project.timeline.as_mut() else { + return false; + }; + report = cuts::apply_source_cuts(timeline, &durations, cuts); + report.applied > 0 + }, + window, + cx, + ); + self.transcript.dirty = true; + self.transcript_refresh(); + tracing::info!( + reason, + cuts = cuts.len(), + applied = report.applied, + skipped = report.skipped(), + elapsed_ms = started.elapsed().as_secs_f64() * 1000.0, + "transcript cut" + ); + if report.applied > 0 { + self.note_edit(reason, Some(crate::editor_timeline::TrackKind::Clip)); + } + if report.transition > 0 { + self.show_notice( + tr::editor::transcript::skipped_transition(report.transition), + window, + cx, + ); + } else if report.hold > 0 { + self.show_notice( + tr::editor::transcript::skipped_hold(report.hold), + window, + cx, + ); + } else if report.last_clip > 0 { + self.show_notice(tr::editor::transcript::skipped_last_clip(), window, cx); + } + self.transcript_sync_active(false, cx); + report + } + + pub(super) fn transcript_delete_selection( + &mut self, + window: &mut Window, + cx: &mut Context, + ) { + let (Some((doc, edl)), Some(selection)) = + (self.transcript_doc(), self.transcript.selection) + else { + return; + }; + let range = selection.range(); + if range.clone().all(|word| !edl.is_kept(word)) { + self.transcript_restore(range, window, cx); + return; + } + let first_kept = range.clone().find(|word| edl.is_kept(*word)); + let report = self.transcript_cut_runs( + std::slice::from_ref(&range), + "transcript-delete", + window, + cx, + ); + if report.applied == 0 { + return; + } + self.transcript.selection = None; + self.transcript.caret = Some(range.end.min(doc.words.len() - 1)); + if !self.playing + && let (Some(first), Some(edl)) = (first_kept, self.transcript.edl.clone()) + { + let join = (first..doc.words.len()) + .find(|word| edl.is_kept(*word)) + .and_then(|word| edl.output_start_of(&doc.words[word])); + if let Some(join) = join { + self.seek_to_time(join, cx); + self.transcript_sync_active(false, cx); + } + } + } + + pub(super) fn transcript_restore( + &mut self, + words: Range, + window: &mut Window, + cx: &mut Context, + ) { + let Some(doc) = self.transcript.doc.clone() else { + return; + }; + let durations = self.clip_display_durations.clone(); + let removed_takes = self + .project + .timeline + .as_ref() + .map(|timeline| self.history.removed_takes(timeline)) + .unwrap_or_default(); + let mut outcome = Ok(0); + self.edit_timeline_project( + |project| { + let Some(timeline) = project.timeline.as_mut() else { + return false; + }; + outcome = + cuts::restore_words(timeline, &durations, &removed_takes, &doc, words.clone()); + matches!(outcome, Ok(count) if count > 0) + }, + window, + cx, + ); + self.transcript.dirty = true; + self.transcript_refresh(); + self.transcript.hovered_cut = None; + match outcome { + Ok(count) if count > 0 => { + self.note_edit( + "transcript-restore", + Some(crate::editor_timeline::TrackKind::Clip), + ); + self.transcript.selection = Some(WordSelection { + anchor: words.start, + focus: words.end - 1, + }); + } + Ok(_) => {} + Err(RestoreBlocker::Transition) => { + self.show_notice(tr::editor::transcript::restore_transition(), window, cx); + } + Err(RestoreBlocker::NotAdjacent) => { + self.show_notice(tr::editor::transcript::restore_blocked(), window, cx); + } + } + self.invalidate_transcript(cx); + } + + pub(super) fn transcript_open_search(&mut self, window: &mut Window, cx: &mut Context) { + if let Some(search) = &self.transcript.search { + let input = search.input.clone(); + input.update(cx, |input, cx| input.focus_and_select_all(window, cx)); + return; + } + let input = cx.new(|cx| { + let mut input = ui::TextInputState::single_line(window, cx); + input.set_placeholder(tr::editor::transcript::search_placeholder()); + input + }); + let subscription = cx.subscribe_in( + &input, + window, + |this: &mut Self, input, event: &ui::TextInputEvent, window, cx| match event { + ui::TextInputEvent::Changed => { + let query = input.read(cx).text().to_string(); + this.transcript_search_changed(query, cx); + } + ui::TextInputEvent::Confirmed => { + let back = window.modifiers().shift; + this.transcript_step_match(if back { -1 } else { 1 }, cx); + } + ui::TextInputEvent::Cancelled => this.transcript_close_search(window, cx), + ui::TextInputEvent::Blurred => {} + }, + ); + self.push_text_subscription(subscription); + input.update(cx, |input, cx| input.focus_and_select_all(window, cx)); + self.transcript.search = Some(SearchState { + input, + matches: Arc::new(Vec::new()), + current: 0, + query: String::new(), + }); + if let Some(selection) = self.transcript.selection + && let Some(doc) = self.transcript.doc.clone() + && selection.range().len() <= 6 + { + let text = doc.text_of(selection.range()); + if let Some(search) = &self.transcript.search { + search + .input + .update(cx, |input, cx| input.set_text(text.clone(), cx)); + } + self.transcript_search_changed(text, cx); + } + self.invalidate_transcript(cx); + } + + fn transcript_close_search(&mut self, window: &mut Window, cx: &mut Context) { + self.transcript.search = None; + window.focus(&self.transcript.focus, cx); + self.invalidate_transcript(cx); + } + + pub(super) fn transcript_search_changed(&mut self, query: String, cx: &mut Context) { + let Some(doc) = self.transcript.doc.clone() else { + return; + }; + let matches = find_matches(&doc, &query); + let playhead_word = self.transcript.active.unwrap_or(0); + let Some(search) = self.transcript.search.as_mut() else { + return; + }; + search.query = query; + search.current = matches + .iter() + .position(|range| range.start >= playhead_word) + .unwrap_or(0); + search.matches = Arc::new(matches); + let first = search.matches.get(search.current).map(|range| range.start); + if let Some(first) = first { + self.transcript_reveal(first, false); + } + self.invalidate_transcript(cx); + } + + fn transcript_step_match(&mut self, step: i32, cx: &mut Context) { + let Some(search) = self.transcript.search.as_mut() else { + return; + }; + let count = search.matches.len(); + if count == 0 { + return; + } + search.current = + (search.current as i64 + i64::from(step)).rem_euclid(count as i64) as usize; + let range = search.matches[search.current].clone(); + self.transcript.selection = Some(WordSelection { + anchor: range.start, + focus: range.end - 1, + }); + self.transcript_seek_word(range.start, cx); + self.transcript_reveal(range.start, false); + self.invalidate_transcript(cx); + } + + fn transcript_delete_matches(&mut self, window: &mut Window, cx: &mut Context) { + let Some(search) = &self.transcript.search else { + return; + }; + let Some(edl) = self.transcript.edl.clone() else { + return; + }; + let runs: Vec> = search + .matches + .iter() + .filter(|range| (*range).clone().any(|word| edl.is_kept(word))) + .cloned() + .collect(); + self.transcript.selection = None; + self.transcript_cut_runs(&runs, "transcript-delete-matches", window, cx); + self.invalidate_transcript(cx); + } + + fn transcript_live_fillers(&self) -> Vec<(usize, Disfluency)> { + let (Some(doc), Some(edl)) = (&self.transcript.doc, &self.transcript.edl) else { + return Vec::new(); + }; + doc.fillers + .iter() + .enumerate() + .filter(|(_, filler)| { + !self + .transcript + .cleanup + .ignored + .contains(&filler.words.start) + && filler.words.clone().all(|word| edl.is_kept(word)) + }) + .map(|(index, filler)| (index, filler.clone())) + .collect() + } + + pub(super) fn transcript_remove_fillers( + &mut self, + window: &mut Window, + cx: &mut Context, + ) { + let categories = self.transcript.cleanup.categories; + let runs: Vec> = self + .transcript_live_fillers() + .into_iter() + .filter(|(_, filler)| categories[category_index(filler.kind)]) + .map(|(_, filler)| filler.words) + .collect(); + self.transcript.selection = None; + self.transcript_cut_runs(&runs, "transcript-remove-fillers", window, cx); + self.invalidate_transcript(cx); + } + + fn transcript_remove_filler( + &mut self, + words: Range, + window: &mut Window, + cx: &mut Context, + ) { + self.transcript.selection = None; + self.transcript_cut_runs(&[words], "transcript-remove-filler", window, cx); + self.invalidate_transcript(cx); + } + + fn transcript_focus_filler( + &mut self, + words: Range, + listen: bool, + cx: &mut Context, + ) { + let Some((doc, edl)) = self.transcript_doc() else { + return; + }; + self.transcript.selection = Some(WordSelection { + anchor: words.start, + focus: words.end - 1, + }); + self.transcript_reveal(words.start, false); + if listen + && let (Some(start), Some(end)) = ( + edl.output_start_of(&doc.words[words.start]), + edl.output_end_of(&doc.words[words.end - 1]), + ) + { + self.play_range((start - LISTEN_BEFORE).max(0.0), end + LISTEN_AFTER, cx); + } else { + self.transcript_seek_word(words.start, cx); + } + self.invalidate_transcript(cx); + } + + fn transcript_pause_plan(&self) -> Vec { + let (Some(doc), Some(edl)) = (&self.transcript.doc, &self.transcript.edl) else { + return Vec::new(); + }; + cuts::plan_pause_cuts( + doc, + edl, + self.transcript.energy.as_deref(), + self.transcript.cleanup.pause_longer_than, + self.transcript.cleanup.pause_keep, + ) + } + + pub(super) fn transcript_shorten_pauses( + &mut self, + window: &mut Window, + cx: &mut Context, + ) { + let cuts: Vec> = self + .transcript_pause_plan() + .into_iter() + .map(|pause| pause.cut) + .collect(); + self.transcript_apply_cuts(&cuts, "transcript-shorten-pauses", window, cx); + self.invalidate_transcript(cx); + } + + fn transcript_step_pause(&mut self, longer: bool, step: f64, cx: &mut Context) { + let cleanup = &mut self.transcript.cleanup; + let (value, (min, max)) = if longer { + (&mut cleanup.pause_longer_than, PAUSE_LONGER_RANGE) + } else { + (&mut cleanup.pause_keep, PAUSE_KEEP_RANGE) + }; + *value = ((*value + step) * 10.0).round() / 10.0; + *value = value.clamp(min, max); + if cleanup.pause_keep >= cleanup.pause_longer_than { + if longer { + cleanup.pause_keep = (cleanup.pause_longer_than - 0.1).max(PAUSE_KEEP_RANGE.0); + } else { + cleanup.pause_longer_than = (cleanup.pause_keep + 0.1).min(PAUSE_LONGER_RANGE.1); + } + } + cleanup.persist_pauses(); + self.invalidate_transcript(cx); + } + + pub(crate) fn transcript_resize_move( + &mut self, + x: f32, + row_width: f32, + cx: &mut Context, + ) { + let Some((start_x, start_share)) = self.transcript.resize else { + return; + }; + if row_width <= 0.0 { + return; + } + let share = + (start_share + (x - start_x) / row_width).clamp(MIN_PLAYER_SHARE, MAX_PLAYER_SHARE); + if (share - self.transcript.player_share).abs() > f32::EPSILON { + self.transcript.player_share = share; + cx.notify(); + } + } + + pub(crate) fn transcript_resize_end(&mut self, cx: &mut Context) { + if self.transcript.resize.take().is_some() { + self.transcript.persist_split(); + cx.notify(); + } + } + + pub(crate) fn render_transcript( + &mut self, + window: &mut Window, + cx: &mut Context, + ) -> AnyElement { + let project_changed = self.transcript.dirty; + self.transcript_refresh(); + if project_changed { + self.transcript_load_energy(cx); + } + self.transcript.layouts.borrow_mut().clear(); + let theme = self.theme; + let palette = Palette::new(&theme); + let editor = cx.entity().downgrade(); + + let body: AnyElement = match (self.transcript.doc.clone(), self.transcript.edl.clone()) { + (Some(doc), edl) if !doc.is_empty() => { + let search = self.transcript.search.as_ref(); + let painter = ParagraphPainter { + doc, + edl, + selection: self.transcript.selection.map(WordSelection::range), + active: self.transcript.active, + hovered_cut: self.transcript.hovered_cut.and_then(|run| { + self.transcript + .edl + .as_ref() + .and_then(|edl| edl.cut_runs.get(run).cloned()) + }), + matches: search + .map_or_else(|| Arc::new(Vec::new()), |search| search.matches.clone()), + current_match: search + .and_then(|search| search.matches.get(search.current).cloned()), + ignored: Arc::new(self.transcript.cleanup.ignored.clone()), + palette, + editor: editor.clone(), + layouts: self.transcript.layouts.clone(), + }; + let scroll_editor = editor.clone(); + self.transcript.list.set_scroll_handler(move |_, _, cx| { + scroll_editor + .update(cx, |this, _| { + this.transcript.user_scrolled = Some(Instant::now()) + }) + .ok(); + }); + div() + .id("transcript-body") + .flex_1() + .min_h_0() + .px(px(14.)) + .pt(px(10.)) + .text_size(px(TEXT_SIZE)) + .line_height(px(LINE_HEIGHT)) + .text_color(palette.text_1) + .child( + gpui::list(self.transcript.list.clone(), move |index, _, _| { + painter.paragraph(index) + }) + .size_full(), + ) + .into_any_element() + } + _ => self.render_transcript_empty(cx), + }; + + let focused = self.transcript.focus.is_focused(window); + div() + .id("transcript-panel") + .size_full() + .flex() + .flex_col() + .rounded(px(12.)) + .border_1() + .border_color(if focused { + Hsla::from(theme.editor.line_strong) + } else { + self.card_line() + }) + .bg(self.panel_bg()) + .shadow(theme.editor.card_shadow()) + .overflow_hidden() + .track_focus(&self.transcript.focus) + .on_key_down(cx.listener(Self::transcript_key_down)) + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _: &MouseDownEvent, window, cx| { + window.focus(&this.transcript.focus, cx); + if this.transcript.selection.take().is_some() { + this.invalidate_transcript(cx); + } + }), + ) + .on_mouse_up( + MouseButton::Left, + cx.listener(|this, _, _, cx| this.transcript_end_drag(cx)), + ) + .on_mouse_up_out( + MouseButton::Left, + cx.listener(|this, _, _, cx| this.transcript_end_drag(cx)), + ) + .on_hover(cx.listener(|this, hovered: &bool, _, cx| { + if !*hovered && this.transcript.hovered_cut.take().is_some() { + this.invalidate_transcript(cx); + } + })) + .child(self.render_transcript_header(cx)) + .children(self.render_transcript_search(cx)) + .children(self.render_transcript_cleanup(cx)) + .child(body) + .child(self.render_transcript_footer()) + .into_any_element() + } + + fn render_transcript_header(&self, cx: &mut Context) -> impl IntoElement { + let theme = self.theme; + let words = self + .transcript + .edl + .as_ref() + .map(|edl| edl.kept_count) + .or_else(|| self.transcript.doc.as_ref().map(|doc| doc.words.len())); + let has_doc = self + .transcript + .doc + .as_ref() + .is_some_and(|doc| !doc.is_empty()); + div() + .flex() + .flex_row() + .items_center() + .justify_between() + .flex_none() + .h(px(44.)) + .px(px(12.)) + .border_b_1() + .border_color(Hsla::from(theme.editor.line)) + .child( + div() + .flex() + .flex_row() + .items_baseline() + .gap(px(8.)) + .min_w_0() + .child( + div() + .text_size(px(13.)) + .font_weight(FontWeight::MEDIUM) + .text_color(Hsla::from(theme.editor.text_1)) + .child(tr::editor::transcript::title()), + ) + .children(words.filter(|_| has_doc).map(|count| { + div() + .text_size(px(12.)) + .text_color(Hsla::from(theme.editor.text_3)) + .truncate() + .child(SharedString::from(tr::editor::transcript::words(count))) + })), + ) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(2.)) + .child( + ui::EditorButton::plain(&theme, "transcript-search") + .left_icon("icons/search.svg") + .tooltip(&theme, tr::editor::transcript::search()) + .disabled(!has_doc) + .pressed(self.transcript.search.is_some()) + .on_click(cx.listener(|this, _, window, cx| { + if this.transcript.search.is_some() { + this.transcript_close_search(window, cx); + } else { + this.transcript_open_search(window, cx); + } + })), + ) + .child( + ui::EditorButton::plain(&theme, "transcript-cleanup") + .left_icon("icons/scissors.svg") + .label(tr::editor::transcript::cleanup()) + .tooltip(&theme, tr::editor::transcript::cleanup_tooltip()) + .disabled(!has_doc) + .pressed(self.transcript.cleanup.open) + .on_click(cx.listener(|this, _, _, cx| { + this.transcript.cleanup.open = !this.transcript.cleanup.open; + this.invalidate_transcript(cx); + })), + ), + ) + } + + fn render_transcript_search(&self, cx: &mut Context) -> Option { + let search = self.transcript.search.as_ref()?; + let theme = self.theme; + let count = search.matches.len(); + let label = if search.query.trim().is_empty() { + SharedString::default() + } else if count == 0 { + SharedString::from(tr::editor::transcript::search_none()) + } else { + SharedString::from(tr::editor::transcript::search_count( + search.current + 1, + count, + )) + }; + Some( + div() + .flex() + .flex_row() + .items_center() + .gap(px(6.)) + .flex_none() + .px(px(12.)) + .py(px(8.)) + .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation()) + .border_b_1() + .border_color(Hsla::from(theme.editor.line)) + .child( + div().flex_1().min_w_0().child( + ui::TextInput::plain(&theme, "transcript-search-input", &search.input) + .height(px(28.)) + .text_size(px(13.)), + ), + ) + .child( + div() + .flex_none() + .text_size(px(12.)) + .text_color(Hsla::from(theme.editor.text_3)) + .child(label), + ) + .child( + ui::EditorButton::plain(&theme, "transcript-search-previous") + .left_icon("icons/chevron-up.svg") + .tooltip(&theme, tr::editor::transcript::previous_match()) + .disabled(count == 0) + .on_click(cx.listener(|this, _, _, cx| this.transcript_step_match(-1, cx))), + ) + .child( + ui::EditorButton::plain(&theme, "transcript-search-next") + .left_icon("icons/chevron-down.svg") + .tooltip(&theme, tr::editor::transcript::next_match()) + .disabled(count == 0) + .on_click(cx.listener(|this, _, _, cx| this.transcript_step_match(1, cx))), + ) + .child( + ui::EditorButton::plain(&theme, "transcript-search-delete") + .left_icon("icons/trash.svg") + .label(tr::editor::transcript::delete_matches()) + .tooltip(&theme, tr::editor::transcript::delete_matches_tooltip()) + .disabled(count == 0) + .on_click(cx.listener(|this, _, window, cx| { + this.transcript_delete_matches(window, cx); + })), + ) + .into_any_element(), + ) + } + + fn render_transcript_cleanup(&self, cx: &mut Context) -> Option { + if !self.transcript.cleanup.open { + return None; + } + let doc = self.transcript.doc.clone()?; + let edl = self.transcript.edl.clone()?; + let theme = self.theme; + let palette = Palette::new(&theme); + let cleanup = &self.transcript.cleanup; + let fillers = self.transcript_live_fillers(); + let mut counts = [0usize; 4]; + for (_, filler) in &fillers { + counts[category_index(filler.kind)] += 1; + } + let listed: Vec<(usize, Disfluency)> = fillers + .into_iter() + .filter(|(_, filler)| cleanup.category_enabled(filler.kind)) + .collect(); + let pauses = self.transcript_pause_plan(); + let saved: f64 = pauses.iter().map(|pause| pause.saves).sum(); + let on_pauses = cleanup.tab == CleanupTab::Pauses; + + let tabs = ui::SegmentedControl::editor( + &theme, + "transcript-cleanup-tabs", + vec![ + ui::SegmentOption::new(tr::editor::transcript::fillers::title(), !on_pauses), + ui::SegmentOption::new(tr::editor::transcript::pauses::title(), on_pauses), + ], + ) + .on_select(cx.listener(|this, index: &usize, _, cx| { + this.transcript.cleanup.tab = if *index == 1 { + CleanupTab::Pauses + } else { + CleanupTab::Fillers + }; + this.invalidate_transcript(cx); + })); + + let action = if on_pauses { + ui::Button::plain( + &theme, + "transcript-shorten-pauses", + ui::ButtonVariant::Primary, + ui::ButtonSize::Sm, + ) + .label(tr::editor::transcript::pauses::apply()) + .disabled(pauses.is_empty()) + .on_click(cx.listener(|this, _, window, cx| { + this.transcript_shorten_pauses(window, cx); + })) + } else { + ui::Button::plain( + &theme, + "transcript-remove-fillers", + ui::ButtonVariant::Primary, + ui::ButtonSize::Sm, + ) + .label(SharedString::from( + tr::editor::transcript::fillers::remove_all(listed.len()), + )) + .disabled(listed.is_empty()) + .on_click(cx.listener(|this, _, window, cx| { + this.transcript_remove_fillers(window, cx); + })) + }; + + let header = div() + .flex() + .flex_row() + .items_center() + .justify_between() + .flex_none() + .gap(px(8.)) + .px(px(12.)) + .py(px(8.)) + .child(tabs) + .child(action); + + let body = if on_pauses { + self.render_transcript_pause_list(&doc, &edl, pauses, saved, palette, cx) + } else { + self.render_transcript_filler_list(&doc, &edl, listed, counts, palette, cx) + }; + + Some( + div() + .flex() + .flex_col() + .flex_none() + .max_h(gpui::relative(0.6)) + .border_b_1() + .border_color(Hsla::from(theme.editor.line)) + .bg(Hsla::from(theme.editor.card_2)) + .child(header) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_h_0() + .px(px(6.)) + .pb(px(8.)) + .child(body), + ) + .into_any_element(), + ) + } + + fn render_transcript_filler_list( + &self, + doc: &Arc, + edl: &Arc, + listed: Vec<(usize, Disfluency)>, + counts: [usize; 4], + palette: Palette, + cx: &mut Context, + ) -> AnyElement { + let theme = self.theme; + let cleanup = &self.transcript.cleanup; + let categories = DisfluencyKind::ALL.into_iter().map(|kind| { + let index = category_index(kind); + let checked = cleanup.categories[index]; + div() + .id(("transcript-category", index)) + .flex() + .flex_row() + .flex_none() + .items_center() + .gap(px(8.)) + .h(px(28.)) + .px(px(6.)) + .rounded(px(6.)) + .cursor_pointer() + .hover(|style| style.bg(Hsla::from(theme.editor.ctl))) + .on_click(cx.listener(move |this, _, _, cx| { + this.transcript.cleanup.categories[index] = + !this.transcript.cleanup.categories[index]; + this.invalidate_transcript(cx); + })) + .child( + div() + .flex_none() + .size(px(14.)) + .rounded(px(4.)) + .border_1() + .border_color(if checked { + palette.accent + } else { + Hsla::from(theme.editor.line_strong) + }) + .when(checked, |this| this.bg(palette.accent)) + .flex() + .items_center() + .justify_center() + .when(checked, |this| { + this.child( + svg() + .path("icons/check.svg") + .size(px(10.)) + .text_color(gpui::white()), + ) + }), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_row() + .items_baseline() + .gap(px(6.)) + .child( + div() + .flex_none() + .text_size(px(13.)) + .text_color(palette.text_1) + .child(kind_label(kind)), + ) + .child( + div() + .min_w_0() + .text_size(px(12.)) + .text_color(palette.text_3) + .truncate() + .child(kind_hint(kind)), + ), + ) + .child( + div() + .flex_none() + .text_size(px(12.)) + .text_color(palette.text_2) + .child(SharedString::from(counts[index].to_string())), + ) + }); + + let count = listed.len(); + let rows = { + let doc = doc.clone(); + let edl = edl.clone(); + let listed = Arc::new(listed); + let selection = self.transcript.selection.map(WordSelection::range); + let editor = cx.entity().downgrade(); + gpui::uniform_list("transcript-filler-rows", count, move |range, _, _| { + range + .filter_map(|row| listed.get(row)) + .map(|(index, filler)| { + filler_row( + &theme, + palette, + &doc, + &edl, + *index, + filler.words.clone(), + selection.as_ref() == Some(&filler.words), + editor.clone(), + ) + }) + .collect::>() + }) + .track_scroll(&cleanup.filler_rows) + .min_h(px(ROW_HEIGHT * count.min(2) as f32)) + .h(px(ROW_HEIGHT * count.min(MAX_VISIBLE_ROWS) as f32)) + }; + + div() + .flex() + .flex_col() + .flex_1() + .min_h_0() + .child( + div() + .flex() + .flex_col() + .flex_none() + .pb(px(4.)) + .children(categories), + ) + .child( + div() + .flex_none() + .h(px(1.)) + .mx(px(6.)) + .mb(px(4.)) + .bg(Hsla::from(theme.editor.line)), + ) + .when(count == 0, |this| { + this.child( + div() + .flex_none() + .px(px(6.)) + .py(px(6.)) + .text_size(px(12.)) + .text_color(palette.text_3) + .child(tr::editor::transcript::fillers::none()), + ) + }) + .child(rows) + .into_any_element() + } + + fn render_transcript_pause_list( + &self, + doc: &Arc, + edl: &Arc, + pauses: Vec, + saved: f64, + palette: Palette, + cx: &mut Context, + ) -> AnyElement { + let theme = self.theme; + let cleanup = &self.transcript.cleanup; + let control = |label: &'static str, id: &'static str, value: f64, longer: bool| { + div() + .flex() + .flex_row() + .flex_none() + .items_center() + .justify_between() + .h(px(30.)) + .px(px(6.)) + .child( + div() + .text_size(px(13.)) + .text_color(palette.text_1) + .child(label), + ) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(px(2.)) + .child( + ui::EditorButton::plain(&theme, (id, 0usize)) + .left_icon("icons/minus.svg") + .on_click(cx.listener(move |this, _, _, cx| { + this.transcript_step_pause(longer, -0.1, cx); + })), + ) + .child( + div() + .w(px(46.)) + .text_size(px(13.)) + .text_color(palette.text_1) + .flex() + .justify_center() + .child(seconds_label(value)), + ) + .child( + ui::EditorButton::plain(&theme, (id, 1usize)) + .left_icon("icons/plus.svg") + .on_click(cx.listener(move |this, _, _, cx| { + this.transcript_step_pause(longer, 0.1, cx); + })), + ), + ) + }; + let longer = control( + tr::editor::transcript::pauses::longer_than(), + "transcript-pause-longer", + cleanup.pause_longer_than, + true, + ); + let shorter = control( + tr::editor::transcript::pauses::keep(), + "transcript-pause-keep", + cleanup.pause_keep, + false, + ); + let summary = if pauses.is_empty() { + SharedString::from(tr::editor::transcript::pauses::none()) + } else { + SharedString::from(tr::editor::transcript::pauses::summary( + pauses.len(), + crate::i18n::decimal(format!("{saved:.1}")), + )) + }; + let count = pauses.len(); + let rows = { + let doc = doc.clone(); + let edl = edl.clone(); + let pauses = Arc::new(pauses); + let keep = cleanup.pause_keep; + let editor = cx.entity().downgrade(); + gpui::uniform_list("transcript-pause-rows", count, move |range, _, _| { + range + .filter_map(|row| pauses.get(row)) + .map(|pause| { + pause_row(&theme, palette, &doc, &edl, pause, keep, editor.clone()) + }) + .collect::>() + }) + .track_scroll(&cleanup.pause_rows) + .min_h(px(ROW_HEIGHT * count.min(2) as f32)) + .h(px(ROW_HEIGHT * count.min(MAX_VISIBLE_ROWS) as f32)) + }; + div() + .flex() + .flex_col() + .flex_1() + .min_h_0() + .child(longer) + .child(shorter) + .child( + div() + .flex_none() + .px(px(6.)) + .py(px(6.)) + .text_size(px(12.)) + .text_color(palette.text_3) + .child(summary), + ) + .child( + div() + .flex_none() + .h(px(1.)) + .mx(px(6.)) + .mb(px(4.)) + .bg(Hsla::from(theme.editor.line)), + ) + .child(rows) + .into_any_element() + } + + fn render_transcript_footer(&self) -> impl IntoElement { + let theme = self.theme; + let doc = self.transcript.doc.as_ref(); + let edl = self.transcript.edl.as_ref(); + let message: SharedString = match (doc, edl) { + (Some(doc), Some(edl)) if !doc.is_empty() => { + if let Some(run) = self + .transcript + .hovered_cut + .and_then(|run| edl.cut_runs.get(run)) + { + tr::editor::transcript::restore_hint(run.len()).into() + } else if let Some(selection) = self.transcript.selection { + let range = selection.range(); + let kept = range.clone().filter(|word| edl.is_kept(*word)).count(); + if kept == 0 { + tr::editor::transcript::selection_cut(range.len()).into() + } else { + let mut kept_words = range.clone().filter(|word| edl.is_kept(*word)); + let first = kept_words.next().unwrap_or(range.start); + let last = kept_words.next_back().unwrap_or(first); + let seconds = edl + .output_end_of(&doc.words[last]) + .zip(edl.output_start_of(&doc.words[first])) + .map_or(0.0, |(end, start)| (end - start).max(0.0)); + tr::editor::transcript::selection( + kept, + crate::i18n::decimal(format!("{seconds:.1}")), + ) + .into() + } + } else { + tr::editor::transcript::hint().into() + } + } + _ => SharedString::default(), + }; + div() + .flex() + .flex_row() + .items_center() + .flex_none() + .h(px(32.)) + .px(px(12.)) + .border_t_1() + .border_color(Hsla::from(theme.editor.line)) + .text_size(px(12.)) + .text_color(Hsla::from(theme.editor.text_3)) + .child(div().truncate().child(message)) + } + + fn render_transcript_empty(&self, cx: &mut Context) -> AnyElement { + let theme = self.theme; + self.ensure_captions_init(cx); + let snapshot = crate::transcription::ui_snapshot(&self.project_path); + let model = self.selected_caption_model(); + let downloaded = snapshot.downloaded.contains(model.name); + let download = snapshot + .download + .as_ref() + .filter(|download| download.state == crate::transcription::DownloadState::Downloading); + let has_audio = self + .summary() + .is_some_and(|summary| summary.has_microphone || summary.has_system_audio); + let generating = snapshot.generating; + + let action: AnyElement = if !has_audio { + div() + .text_size(px(12.)) + .text_color(Hsla::from(theme.editor.text_3)) + .child(tr::editor::transcript::no_audio()) + .into_any_element() + } else if downloaded { + ui::Button::plain( + &theme, + "transcript-transcribe", + ui::ButtonVariant::Primary, + ui::ButtonSize::Md, + ) + .label(if generating { + tr::editor::transcript::transcribing() + } else { + tr::editor::transcript::transcribe() + }) + .disabled(generating || snapshot.deleting.is_some()) + .on_click(cx.listener(|this, _, window, cx| { + this.generate_transcript(false, window, cx); + this.spawn_transcript_generation_poll(cx); + })) + .into_any_element() + } else { + let percent = download.map_or(0, |download| { + download.progress.clamp(0.0, 100.0).round() as u32 + }); + ui::Button::plain( + &theme, + "transcript-download-model", + ui::ButtonVariant::Primary, + ui::ButtonSize::Md, + ) + .when(download.is_none(), |button| { + button.icon("icons/download.svg") + }) + .label(if download.is_some() { + tr::editor::tabs::captions::downloading((model.label)(), percent) + } else { + tr::editor::tabs::captions::download((model.label)()) + }) + .disabled(download.is_some()) + .on_click(cx.listener(|this, _, _, cx| { + this.start_caption_model_download(cx); + })) + .into_any_element() + }; + + div() + .flex_1() + .min_h_0() + .flex() + .flex_col() + .items_center() + .justify_center() + .gap(px(10.)) + .px(px(32.)) + .child( + svg() + .path("icons/scan-text.svg") + .size(px(28.)) + .text_color(Hsla::from(theme.editor.text_3)), + ) + .child( + div() + .text_size(px(14.)) + .font_weight(FontWeight::MEDIUM) + .text_color(Hsla::from(theme.editor.text_1)) + .child(tr::editor::transcript::empty_title()), + ) + .child( + div() + .max_w(px(300.)) + .text_size(px(12.)) + .line_height(px(18.)) + .text_center() + .text_color(Hsla::from(theme.editor.text_2)) + .child(tr::editor::transcript::empty_description()), + ) + .child(div().pt(px(6.)).child(action)) + .children(snapshot.generation_error.map(|error| { + div() + .max_w(px(300.)) + .text_size(px(12.)) + .text_center() + .text_color(Hsla::from(theme.red_9)) + .child(error) + })) + .into_any_element() + } + + fn transcript_energy_offsets(&self) -> Option> { + let instance = self.instance.as_ref()?; + Some( + instance + .segment_medias + .iter() + .enumerate() + .map(|(index, media)| { + let clip = self + .project + .clips + .iter() + .find(|clip| clip.index == index as u32) + .map(|clip| clip.offsets) + .unwrap_or_default(); + let repair = media.audio_timing_repair; + ( + f64::from(clip.mic + repair.mic_offset_secs), + f64::from(clip.system_audio + repair.system_audio_offset_secs), + ) + }) + .collect(), + ) + } + + pub(super) fn transcript_energy_loaded( + &mut self, + loaded_with: Vec<(f64, f64)>, + current: Option>, + envelope: super::energy::EnergyEnvelope, + cx: &mut Context, + ) -> bool { + self.transcript.energy_loading = false; + if current.as_ref() != Some(&loaded_with) { + self.transcript.energy = None; + self.transcript.energy_offsets.clear(); + self.transcript.dirty = true; + self.transcript_load_energy(cx); + self.invalidate_transcript(cx); + return false; + } + if !envelope.is_empty() { + self.transcript.energy = Some(Arc::new(envelope)); + } + self.invalidate_transcript(cx); + true + } + + fn transcript_load_energy(&mut self, cx: &mut Context) { + if self.transcript.energy_loading { + return; + } + let Some(instance) = self.instance.clone() else { + return; + }; + let durations = self.clip_display_durations.clone(); + let Some(offsets) = self.transcript_energy_offsets() else { + return; + }; + if self.transcript.energy.is_some() && self.transcript.energy_offsets == offsets { + return; + } + self.transcript.energy_offsets = offsets.clone(); + self.transcript.energy_loading = true; + let loaded_with = offsets.clone(); + cx.spawn(async move |this, cx| { + let task = cx.update(|cx| { + gpui_tokio::Tokio::spawn(cx, async move { + let mut tracks = Vec::with_capacity(instance.segment_medias.len()); + for media in instance.segment_medias.iter() { + tracks.push(( + media.audio.get().await.ok().flatten(), + media.system_audio.get().await.ok().flatten(), + )); + } + tracks + }) + }); + let tracks = task.await.unwrap_or_default(); + let started = Instant::now(); + let envelope = cx + .background_executor() + .spawn(async move { + let clips = tracks + .iter() + .zip(&offsets) + .zip(&durations) + .map(|(((mic, system), (mic_offset, system_offset)), duration)| { + let tracks: Vec = [ + mic.as_ref().map(|audio| (audio, *mic_offset)), + system.as_ref().map(|audio| (audio, *system_offset)), + ] + .into_iter() + .flatten() + .map(|(audio, offset_seconds)| super::energy::EnvelopeTrack { + slices: audio.sample_slices().collect(), + channels: audio.channels(), + offset_seconds, + }) + .collect(); + super::energy::clip_envelope(&tracks, *duration) + }) + .collect(); + super::energy::EnergyEnvelope::new(clips, &durations) + }) + .await; + tracing::info!( + elapsed_ms = started.elapsed().as_secs_f64() * 1000.0, + "transcript loudness envelope ready" + ); + this.update(cx, |this, cx| { + let current = this.transcript_energy_offsets(); + this.transcript_energy_loaded(loaded_with, current, envelope, cx); + }) + .ok(); + }) + .detach(); + } + + fn spawn_transcript_generation_poll(&mut self, cx: &mut Context) { + let path = self.project_path.clone(); + cx.spawn(async move |this, cx| { + loop { + cx.background_executor() + .timer(std::time::Duration::from_millis(250)) + .await; + let generating = crate::transcription::ui_snapshot(&path).generating; + if this + .update(cx, |this, cx| this.invalidate_transcript(cx)) + .is_err() + || !generating + { + break; + } + } + }) + .detach(); + } +} diff --git a/crates/editor/src/audio.rs b/crates/editor/src/audio.rs index 7bf3fb9abd9..448dff78691 100644 --- a/crates/editor/src/audio.rs +++ b/crates/editor/src/audio.rs @@ -271,6 +271,8 @@ impl AudioRenderer { // it, so timeline-positioned music is aligned to the same grid. let frame_start = self.elapsed_samples; let (written, mut buf) = self.render_timeline_frame_raw(samples, project, timeline)?; + let joins = crate::join_fade::hard_cut_joins(timeline, Self::SAMPLE_RATE); + crate::join_fade::apply_join_fades(&mut buf, frame_start, &joins); if !self.music.is_empty() && !timeline.audio_segments.is_empty() { mix_music(&self.music, timeline, frame_start, written, &mut buf); @@ -320,6 +322,7 @@ impl AudioRenderer { self.cursor.samples += written; return Ok((written != 0).then_some(written)); }; + let joins = crate::join_fade::hard_cut_joins(timeline, Self::SAMPLE_RATE); while written < samples { sources.check_cancelled()?; let (mapping, span) = if !timeline.transitions.is_empty() @@ -417,6 +420,11 @@ impl AudioRenderer { ); } } + crate::join_fade::apply_join_fades( + output, + self.elapsed_samples + span_offset, + &joins, + ); emit(written + span_offset, output)?; span_offset += count; } diff --git a/crates/editor/src/join_fade.rs b/crates/editor/src/join_fade.rs new file mode 100644 index 00000000000..178074d5876 --- /dev/null +++ b/crates/editor/src/join_fade.rs @@ -0,0 +1,159 @@ +use cap_project::TimelineConfiguration; + +/// Length of the fade on each side of a hard cut, in 48 kHz samples (5 ms). +/// Long enough that the jump between two unrelated waveforms cannot click, +/// short enough that it never audibly dips speech. +pub(crate) const JOIN_FADE_SAMPLES: usize = 240; + +/// Output sample positions where playback jumps from one clip to another that +/// does not continue it in the source: a cut. Transitions already crossfade, +/// and contiguous halves of a split (even at a speed change) play through, so +/// neither is listed. +pub(crate) fn hard_cut_joins(timeline: &TimelineConfiguration, sample_rate: u32) -> Vec { + if timeline.segments.len() < 2 { + return Vec::new(); + } + let holds = timeline.hold_windows(); + let mut joins = Vec::new(); + let mut effective = 0.0; + for (index, segment) in timeline.segments.iter().enumerate() { + let transition = timeline + .effective_transition(index) + .map(|transition| transition.duration); + effective -= transition.unwrap_or(0.0); + if index > 0 && transition.is_none() { + let previous = &timeline.segments[index - 1]; + let continues = previous.recording_clip == segment.recording_clip + && (previous.end - segment.start).abs() < 1e-6; + if !continues { + let mut output = effective; + for (start, end) in &holds { + if output >= *start { + output += end - start; + } else { + break; + } + } + joins.push((output * f64::from(sample_rate)).round() as usize); + } + } + effective += segment.duration(); + } + joins.sort_unstable(); + joins +} + +fn fade_gain(distance: usize) -> f32 { + let t = (distance as f32 - 0.5) / JOIN_FADE_SAMPLES as f32; + 0.5 - 0.5 * (std::f32::consts::PI * t).cos() +} + +pub(crate) fn apply_join_fades(samples: &mut [f32], start: usize, joins: &[usize]) { + let frames = samples.len() / 2; + let end = start + frames; + let first = joins.partition_point(|join| join + JOIN_FADE_SAMPLES <= start); + for &join in &joins[first..] { + if join >= end + JOIN_FADE_SAMPLES { + break; + } + let from = join.saturating_sub(JOIN_FADE_SAMPLES).max(start); + let to = (join + JOIN_FADE_SAMPLES).min(end); + for position in from..to { + let distance = if position < join { + join - position + } else { + position - join + 1 + }; + let gain = fade_gain(distance); + let index = (position - start) * 2; + samples[index] *= gain; + samples[index + 1] *= gain; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use cap_project::{ClipTransition, ClipTransitionType, TimelineSegment}; + + fn segment(recording_clip: u32, start: f64, end: f64) -> TimelineSegment { + TimelineSegment { + recording_clip, + timescale: 1.0, + start, + end, + name: None, + speed_audio_mode: None, + volume: None, + hide_cursor: None, + } + } + + fn timeline(segments: Vec) -> TimelineConfiguration { + serde_json::from_value::(serde_json::json!({ + "segments": [], + "zoomSegments": [], + })) + .map(|mut timeline| { + timeline.segments = segments; + timeline + }) + .unwrap() + } + + #[test] + fn only_discontinuous_boundaries_are_joins() { + let timeline = timeline(vec![ + segment(0, 0.0, 1.0), + segment(0, 1.0, 2.0), + segment(0, 2.5, 3.0), + segment(1, 0.0, 1.0), + ]); + assert_eq!(hard_cut_joins(&timeline, 48_000), [96_000, 120_000]); + } + + #[test] + fn transitions_are_not_joins() { + let mut timeline = timeline(vec![segment(0, 0.0, 2.0), segment(0, 3.0, 5.0)]); + timeline.transitions.push(ClipTransition { + segment_index: 1, + kind: ClipTransitionType::CrossFade, + duration: 0.5, + }); + assert!(hard_cut_joins(&timeline, 48_000).is_empty()); + } + + #[test] + fn fades_reach_silence_at_the_join_and_are_chunking_independent() { + let joins = [1_000usize]; + let mut whole = vec![1.0f32; 4_000]; + apply_join_fades(&mut whole, 0, &joins); + let mut pieces = vec![1.0f32; 4_000]; + for (index, chunk) in pieces.chunks_mut(2 * 137).enumerate() { + apply_join_fades(chunk, index * 137, &joins); + } + assert_eq!(whole, pieces); + assert!(whole[999 * 2] < 0.001 && whole[1_000 * 2] < 0.001); + assert!((whole[(1_000 - JOIN_FADE_SAMPLES) * 2] - 1.0).abs() < 0.001); + assert_eq!(whole[(1_000 - JOIN_FADE_SAMPLES - 1) * 2], 1.0); + assert_eq!(whole[(1_000 + JOIN_FADE_SAMPLES) * 2], 1.0); + let steps = whole + .chunks(2) + .map(|frame| frame[0]) + .collect::>() + .windows(2) + .map(|pair| (pair[1] - pair[0]).abs()) + .fold(0.0f32, f32::max); + assert!(steps < 0.01, "{steps}"); + } + + #[test] + fn joins_at_the_buffer_edges_do_not_panic() { + let mut samples = vec![1.0f32; 20]; + apply_join_fades(&mut samples, 0, &[0, 3, 10, 9_999]); + apply_join_fades(&mut samples, 1_000_000, &[0, 3]); + apply_join_fades(&mut [], 5, &[5]); + assert!(samples[0] < 0.01); + } +} diff --git a/crates/editor/src/lib.rs b/crates/editor/src/lib.rs index 2c6daa24c4e..0cf317f97f8 100644 --- a/crates/editor/src/lib.rs +++ b/crates/editor/src/lib.rs @@ -4,6 +4,7 @@ mod completed_audio; mod editor; mod editor_instance; mod export_audio; +mod join_fade; mod playback; mod preparing_audio; mod preparing_editor; diff --git a/crates/editor/src/preparing_audio/mixer.rs b/crates/editor/src/preparing_audio/mixer.rs index 9a309333db2..99a97cafbe2 100644 --- a/crates/editor/src/preparing_audio/mixer.rs +++ b/crates/editor/src/preparing_audio/mixer.rs @@ -427,6 +427,10 @@ impl PreparingAudioMixer { &mut samples, ); } + if let Some(timeline) = self.sources.project.timeline.as_ref() { + let joins = crate::join_fade::hard_cut_joins(timeline, AudioData::SAMPLE_RATE); + crate::join_fade::apply_join_fades(&mut samples, self.position, &joins); + } self.sources.check_terminal()?; let start_frame = self.position; self.position = end; diff --git a/crates/project/src/disfluency.rs b/crates/project/src/disfluency.rs new file mode 100644 index 00000000000..f0353599202 --- /dev/null +++ b/crates/project/src/disfluency.rs @@ -0,0 +1,759 @@ +pub const HESITATION_FILLERS: &[&str] = &[ + "um", "umm", "uh", "uhh", "uhm", "er", "erm", "ah", "ahh", "eh", "hm", "hmm", "mm", "mmm", +]; + +pub fn normalize_word(text: &str) -> String { + text.trim_matches(|c: char| !c.is_alphanumeric() && c != '\'') + .to_lowercase() +} + +pub fn is_hesitation_filler(text: &str) -> bool { + HESITATION_FILLERS.contains(&normalize_word(text).as_str()) +} + +pub fn is_hesitation(text: &str) -> bool { + let normalized = normalize_word(text); + HESITATION_FILLERS.contains(&normalized.as_str()) || is_drawn_out_hesitation(&normalized) +} + +#[cfg(test)] +mod corpus_tests; +#[cfg(test)] +mod tests; + +const DRAWN_OUT_HESITATIONS: &[&str] = &["um", "uh", "uhm", "er", "erm", "ehm", "ah", "eh", "hm"]; + +/// "Ummmm", "uhhh", "errrm", "hmmmm" and "mmmm" collapse onto a listed form +/// once repeated letters are squeezed. Backchannels such as "uh-huh" and +/// "mm-hmm" keep their hyphen, so they never match and are left in. +fn is_drawn_out_hesitation(normalized: &str) -> bool { + if normalized.is_empty() || !normalized.chars().all(|c| c.is_ascii_alphabetic()) { + return false; + } + if normalized.len() >= 2 && normalized.chars().all(|c| c == 'm') { + return true; + } + let mut squeezed = String::with_capacity(normalized.len()); + for c in normalized.chars() { + if !squeezed.ends_with(c) { + squeezed.push(c); + } + } + DRAWN_OUT_HESITATIONS.contains(&squeezed.as_str()) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum DisfluencyKind { + Hesitation, + Repetition, + FalseStart, + Discourse, +} + +impl DisfluencyKind { + pub const ALL: [Self; 4] = [ + Self::Hesitation, + Self::Repetition, + Self::FalseStart, + Self::Discourse, + ]; + + fn priority(self) -> u8 { + match self { + Self::Hesitation => 0, + Self::Repetition => 1, + Self::FalseStart => 2, + Self::Discourse => 3, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Disfluency { + pub kind: DisfluencyKind, + pub words: std::ops::Range, + pub phrase: String, +} + +#[derive(Clone, Copy, Debug)] +pub struct DisfluencyToken<'a> { + pub text: &'a str, + pub start: f64, + pub end: f64, +} + +const SENTENCE_PAUSE: f64 = 1.0; +const MAX_REPEATED_PHRASE: usize = 4; +const MAX_FALSE_START: usize = 3; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +enum Trailing { + #[default] + None, + Comma, + Terminal, + Question, + Break, +} + +impl Trailing { + fn from_text(text: &str) -> Self { + let trimmed = text.trim_end_matches(['"', '\'', '”', '’', ')', ']']); + if trimmed.ends_with("...") || trimmed.ends_with('…') { + return Self::Break; + } + match trimmed.chars().last() { + Some('?') => Self::Question, + Some('.' | '!' | '。' | '!' | '?') => Self::Terminal, + Some(',' | ';' | ':' | ',' | '、') => Self::Comma, + Some('-' | '—' | '–') => Self::Break, + _ => Self::None, + } + } + + fn merge(self, other: Self) -> Self { + if other == Self::None { self } else { other } + } + + fn ends_sentence(self) -> bool { + matches!(self, Self::Terminal | Self::Question) + } + + fn sets_off(self) -> bool { + self != Self::None + } +} + +#[derive(Debug)] +struct Word { + index: usize, + norm: String, + trailing: Trailing, + cut_off: bool, + start: f64, + end: f64, + hesitation: bool, +} + +fn words_of(tokens: &[DisfluencyToken<'_>]) -> Vec { + let mut words: Vec = Vec::with_capacity(tokens.len()); + for (index, token) in tokens.iter().enumerate() { + let norm = normalize_word(token.text); + let trailing = Trailing::from_text(token.text.trim()); + if norm.is_empty() { + if let Some(previous) = words.last_mut() { + previous.trailing = previous.trailing.merge(trailing); + } + continue; + } + let trimmed = token.text.trim().trim_end_matches(['"', '\'', '”', '’']); + let cut_off = (trimmed.ends_with('-') || trimmed.ends_with('—') || trimmed.ends_with('–')) + && !trimmed.ends_with("--"); + words.push(Word { + index, + hesitation: is_hesitation(&norm), + norm, + trailing, + cut_off, + start: token.start, + end: token.end, + }); + } + words +} + +fn is_number_word(norm: &str) -> bool { + norm.chars().all(|c| c.is_ascii_digit() || c == '\'') + || matches!( + norm, + "zero" + | "oh" + | "one" + | "two" + | "three" + | "four" + | "five" + | "six" + | "seven" + | "eight" + | "nine" + | "ten" + | "hundred" + | "thousand" + | "million" + | "billion" + ) +} + +/// Doubled words that English uses on purpose: intensifiers, emphatic +/// answers, and the grammatical "had had" / "that that" / "is is". +fn is_intentional_double(norm: &str) -> bool { + is_number_word(norm) + || matches!( + norm, + "very" + | "really" + | "no" + | "yes" + | "yeah" + | "bye" + | "ha" + | "haha" + | "ho" + | "la" + | "knock" + | "many" + | "much" + | "more" + | "far" + | "long" + | "had" + | "that" + | "is" + | "do" + | "well" + | "go" + | "chop" + | "tick" + | "night" + | "boo" + | "hush" + | "bang" + | "beep" + | "blah" + | "bla" + | "yada" + | "wow" + | "hey" + | "hi" + | "oh" + | "ok" + | "okay" + | "please" + | "quick" + | "come" + | "now" + | "pretty" + | "super" + ) +} + +fn is_clause_opener(norm: &str) -> bool { + matches!( + norm, + "i" | "i'm" + | "i've" + | "i'll" + | "i'd" + | "we" + | "we're" + | "we've" + | "we'll" + | "you" + | "you're" + | "you'll" + | "he" + | "she" + | "it" + | "it's" + | "they" + | "they're" + | "this" + | "that" + | "these" + | "those" + | "there" + | "there's" + | "the" + | "a" + | "an" + | "my" + | "our" + | "your" + | "if" + | "when" + | "what" + | "how" + | "why" + | "so" + | "and" + | "but" + | "to" + | "in" + | "on" + | "at" + | "for" + | "with" + | "let's" + | "let" + | "can" + | "is" + | "was" + | "do" + | "does" + | "did" + ) +} + +/// A clause ending in one of these is complete before an "um", so "I think, +/// um, I can" keeps its "I think". "Is" and "was" only count after a noun +/// phrase ("the thing is, um, the server"), not after a lone pronoun ("this +/// is, uh, this was"). +fn takes_clause_complement(norm: &str, clause_len: usize) -> bool { + if matches!(norm, "is" | "was") { + return clause_len >= 3; + } + matches!( + norm, + "think" + | "thought" + | "guess" + | "know" + | "knew" + | "mean" + | "meant" + | "believe" + | "feel" + | "felt" + | "said" + | "say" + | "says" + | "hope" + | "bet" + | "suppose" + | "remember" + | "realized" + | "realised" + | "found" + | "noticed" + | "see" + | "saw" + | "wish" + | "heard" + | "decided" + | "figured" + | "wonder" + | "promise" + | "assume" + | "understand" + | "imagine" + ) +} + +fn longest_silence(words: &[Word], from: usize, to: usize) -> f64 { + (from + 1..=to.min(words.len().saturating_sub(1))) + .map(|at| words[at].start - words[at - 1].end) + .fold(0.0, f64::max) +} + +struct Context<'a> { + words: &'a [Word], +} + +impl Context<'_> { + fn gap_before(&self, at: usize) -> f64 { + match at + .checked_sub(1) + .and_then(|previous| self.words.get(previous)) + { + Some(previous) => self.words[at].start - previous.end, + None => f64::INFINITY, + } + } + + fn starts_sentence(&self, at: usize, pauses: bool) -> bool { + let mut cursor = at; + loop { + let Some(previous) = cursor.checked_sub(1) else { + return true; + }; + if self.words[previous].trailing.ends_sentence() + || (pauses && self.gap_before(cursor) >= SENTENCE_PAUSE) + { + return true; + } + if !self.words[previous].hesitation && !is_opening_marker(&self.words[previous].norm) { + return false; + } + cursor = previous; + } + } + + fn set_off_before(&self, at: usize) -> bool { + if self.starts_sentence(at, true) { + return true; + } + let previous = &self.words[at - 1]; + previous.trailing.sets_off() || previous.hesitation || previous.cut_off + } + + fn set_off_after(&self, last: usize, sentence_end: bool) -> bool { + let word = &self.words[last]; + match word.trailing { + Trailing::Comma | Trailing::Break => return true, + Trailing::Terminal | Trailing::Question => return sentence_end, + Trailing::None => {} + } + match self.words.get(last + 1) { + None => sentence_end, + Some(next) => next.hesitation || self.gap_before(last + 1) >= SENTENCE_PAUSE, + } + } + + fn matches(&self, at: usize, phrase: &[&str]) -> bool { + phrase.len() <= self.words.len().saturating_sub(at) + && phrase + .iter() + .zip(&self.words[at..]) + .all(|(expected, word)| word.norm == *expected) + && self.words[at..at + phrase.len() - 1] + .iter() + .all(|word| !word.trailing.sets_off()) + } +} + +fn is_opening_marker(norm: &str) -> bool { + matches!( + norm, + "so" | "okay" | "ok" | "alright" | "right" | "well" | "basically" | "actually" | "like" + ) +} + +fn detect_hesitations(words: &[Word], out: &mut Vec<(DisfluencyKind, usize, usize)>) { + for (at, word) in words.iter().enumerate() { + if word.hesitation { + out.push((DisfluencyKind::Hesitation, at, at + 1)); + } + } +} + +fn detect_repetitions(words: &[Word], out: &mut Vec<(DisfluencyKind, usize, usize)>) { + let spoken: Vec = (0..words.len()) + .filter(|&at| !words[at].hesitation && !words[at].cut_off) + .collect(); + let mut cursor = 0; + while cursor < spoken.len() { + let mut matched = None; + for size in (1..=MAX_REPEATED_PHRASE).rev() { + if cursor + size * 2 > spoken.len() { + continue; + } + let first = &spoken[cursor..cursor + size]; + let second = &spoken[cursor + size..cursor + size * 2]; + if !first + .iter() + .zip(second) + .all(|(a, b)| words[*a].norm == words[*b].norm) + { + continue; + } + if first + .iter() + .chain(&second[..size - 1]) + .any(|&at| words[at].trailing.ends_sentence()) + { + continue; + } + let last_of_first = first[size - 1]; + if size == 1 && is_intentional_double(&words[last_of_first].norm) + || size > 1 + && first + .iter() + .all(|&at| is_intentional_double(&words[at].norm)) + { + continue; + } + if longest_silence(words, first[0], second[size - 1]) >= SENTENCE_PAUSE { + continue; + } + let coordinated = |at: &usize| matches!(words[*at].norm.as_str(), "and" | "or" | "nor"); + let chained = cursor + .checked_sub(1) + .is_some_and(|previous| words[spoken[previous]].norm == words[last_of_first].norm); + if size > 1 && (coordinated(&last_of_first) || first.iter().any(coordinated) && chained) + { + continue; + } + if size == 1 + && words[last_of_first].norm == "so" + && spoken + .get(cursor + 2) + .is_some_and(|&next| so_is_degree_word(&words[next])) + { + continue; + } + matched = Some(size); + break; + } + match matched { + Some(size) => { + let first = spoken[cursor]; + let last = spoken[cursor + size - 1]; + let fragment = words[last + 1..spoken[cursor + size]] + .iter() + .any(|word| word.cut_off); + let kind = if fragment { + DisfluencyKind::FalseStart + } else { + DisfluencyKind::Repetition + }; + out.push((kind, first, last + 1)); + cursor += size; + } + None => cursor += 1, + } + } +} + +/// A cut-off fragment ("wh-", "comp—") is always a false start. A clause is +/// a false start when it starts at a clause boundary, is abandoned with a +/// dash, an ellipsis, a fragment or a hesitation, and the speaker restarts on +/// the same opening word with different words: "we should, um, we need to". +/// "For the bug report, uh, the user" is not one: its "the" is inside a +/// phrase, not opening a clause. +fn detect_false_starts(words: &[Word], out: &mut Vec<(DisfluencyKind, usize, usize)>) { + for (at, word) in words.iter().enumerate() { + if word.cut_off && !word.hesitation { + out.push((DisfluencyKind::FalseStart, at, at + 1)); + } + } + let context = Context { words }; + for start in 0..words.len() { + let opener = &words[start]; + if opener.hesitation || opener.cut_off || !is_clause_opener(&opener.norm) { + continue; + } + let at_boundary = context.set_off_before(start) + || start.checked_sub(1).is_some_and(|previous| { + matches!( + words[previous].norm.as_str(), + "and" | "but" | "so" | "then" | "because" | "or" | "if" | "when" + ) + }); + if !at_boundary { + continue; + } + for size in 2..=MAX_FALSE_START { + let last = start + size - 1; + let Some(abandoned) = words.get(last) else { + break; + }; + if words[start..=last] + .iter() + .any(|word| word.hesitation || word.cut_off) + || words[start..last] + .iter() + .any(|word| word.trailing.sets_off()) + || abandoned.trailing.ends_sentence() + { + break; + } + let mut restart = last + 1; + let mut interrupted = abandoned.trailing == Trailing::Break; + while words + .get(restart) + .is_some_and(|next| next.hesitation || next.cut_off) + { + interrupted = true; + restart += 1; + } + let Some(restarted) = words.get(restart) else { + break; + }; + if !interrupted + || restarted.norm != opener.norm + || takes_clause_complement(&abandoned.norm, size) + || longest_silence(words, last, restart) >= SENTENCE_PAUSE + { + continue; + } + let restated = words[restart..] + .iter() + .take(size) + .map(|word| word.norm.as_str()) + .eq(words[start..=last].iter().map(|word| word.norm.as_str())); + if !restated { + out.push((DisfluencyKind::FalseStart, start, last + 1)); + } + break; + } + } +} + +const SET_OFF_PHRASES: &[(&[&str], bool)] = &[ + (&["you", "know", "what", "i", "mean"], true), + (&["you", "know"], true), + (&["i", "mean"], false), + (&["sort", "of"], false), + (&["kind", "of"], false), + (&["like"], false), + (&["basically"], false), + (&["actually"], false), + (&["literally"], false), + (&["honestly"], false), +]; + +const SENTENCE_OPENERS: &[&[&str]] = &[ + &["all", "right"], + &["okay"], + &["ok"], + &["alright"], + &["right"], + &["well"], +]; + +fn so_is_degree_word(next: &Word) -> bool { + matches!( + next.norm.as_str(), + "much" + | "many" + | "far" + | "long" + | "few" + | "little" + | "what" + | "to" + | "called" + | "good" + | "bad" + | "cool" + | "fast" + | "slow" + | "easy" + | "hard" + | "big" + | "small" + | "close" + | "sorry" + | "glad" + | "happy" + | "do" + | "did" + | "does" + ) +} + +fn detect_discourse(words: &[Word], out: &mut Vec<(DisfluencyKind, usize, usize)>) { + let context = Context { words }; + for at in 0..words.len() { + if words[at].hesitation { + continue; + } + if let Some((phrase, sentence_end)) = SET_OFF_PHRASES + .iter() + .find(|(phrase, _)| context.matches(at, phrase)) + { + let last = at + phrase.len() - 1; + let surrounded = + context.set_off_before(at) && context.set_off_after(last, *sentence_end); + let opening = context.starts_sentence(at, false) + && matches!(words[last].trailing, Trailing::Comma | Trailing::Break); + if surrounded || opening { + out.push((DisfluencyKind::Discourse, at, last + 1)); + continue; + } + } + if words[at].norm == "right" + && words[at].trailing == Trailing::Question + && at > 0 + && (words[at - 1].trailing == Trailing::Comma || words[at - 1].hesitation) + { + out.push((DisfluencyKind::Discourse, at, at + 1)); + continue; + } + if !context.starts_sentence(at, false) { + continue; + } + if words[at].norm == "so" { + let continues = !words[at].trailing.ends_sentence(); + if let Some(next) = words.get(at + 1) + && continues + && (words[at].trailing.sets_off() || !so_is_degree_word(next)) + { + out.push((DisfluencyKind::Discourse, at, at + 1)); + } + continue; + } + if let Some(phrase) = SENTENCE_OPENERS + .iter() + .find(|phrase| context.matches(at, phrase)) + { + let last = at + phrase.len() - 1; + let trailing = words[last].trailing; + let next = words.get(last + 1); + let followed_by_so = next.is_some_and(|next| next.norm == "so"); + let acknowledgement = trailing.ends_sentence() + && matches!(words[last].norm.as_str(), "okay" | "ok" | "alright") + && next.is_some(); + let doubled = next.is_some_and(|next| next.norm == words[last].norm) + || at + .checked_sub(1) + .is_some_and(|previous| words[previous].norm == words[at].norm); + if doubled { + continue; + } + if matches!(trailing, Trailing::Comma | Trailing::Break) + || (followed_by_so && trailing == Trailing::None) + || acknowledgement + { + out.push((DisfluencyKind::Discourse, at, last + 1)); + } + } + } +} + +/// Finds hesitations, repeated words, false starts and discourse fillers in a +/// timed transcript. Each token belongs to at most one result; where two +/// readings overlap, hesitation wins over repetition, then false start, then +/// discourse. Results are sorted by position. +/// +/// Discourse fillers are only proposed with punctuation or pause evidence +/// that the word is set off from the sentence ("it was, like, huge"), so "I +/// like pizza" and "you know how" are left alone. +pub fn detect_disfluencies(tokens: &[DisfluencyToken<'_>]) -> Vec { + let words = words_of(tokens); + let mut candidates = Vec::new(); + detect_hesitations(&words, &mut candidates); + detect_repetitions(&words, &mut candidates); + detect_false_starts(&words, &mut candidates); + detect_discourse(&words, &mut candidates); + candidates.sort_by_key(|(kind, start, end)| (kind.priority(), *start, *end)); + + let mut taken = vec![false; words.len()]; + let mut kept = Vec::new(); + for (kind, start, end) in candidates { + if taken[start..end].iter().any(|taken| *taken) { + continue; + } + taken[start..end].iter_mut().for_each(|taken| *taken = true); + kept.push((kind, start, end)); + } + kept.sort_by_key(|(_, start, _)| *start); + + let mut merged: Vec<(DisfluencyKind, usize, usize)> = Vec::with_capacity(kept.len()); + for (kind, start, end) in kept { + match merged.last_mut() { + Some((previous, _, previous_end)) + if *previous == DisfluencyKind::FalseStart + && kind == DisfluencyKind::FalseStart + && *previous_end == start => + { + *previous_end = end; + } + _ => merged.push((kind, start, end)), + } + } + + merged + .into_iter() + .map(|(kind, start, end)| Disfluency { + kind, + words: words[start].index..words[end - 1].index + 1, + phrase: words[start..end] + .iter() + .map(|word| word.norm.as_str()) + .collect::>() + .join(" "), + }) + .collect() +} diff --git a/crates/project/src/disfluency/corpus_tests.rs b/crates/project/src/disfluency/corpus_tests.rs new file mode 100644 index 00000000000..4a6e5d997ae --- /dev/null +++ b/crates/project/src/disfluency/corpus_tests.rs @@ -0,0 +1,507 @@ +use super::*; + +/// Hand-labelled narration in the style of screen recordings: tutorials, +/// walkthroughs, bug reports and team updates. A bracket marks what a careful +/// editor would cut and why: `[H ...]` hesitation, `[R ...]` repeated words, +/// `[F ...]` false start, `[D ...]` discourse filler. `|` is a pause of more +/// than a second. Lines with no brackets are there to catch false alarms, +/// most of them using "like", "so", "actually", "you know" and friends in +/// their ordinary sense. +const CORPUS: &str = r#" +[D So,] [H um,] today I want to show you how exports work. +[H Uh,] let me open the settings first. +I like pizza, but I prefer pasta. +It looks like the upload finished. +[R We] we just shipped the new editor. +[R The] the button is in the top right corner. +[D Okay,] [D so] let's get started. +[D Basically,] you drag the clip onto the timeline. +It was, [D like,] really slow before the fix. +This is what I meant by a clean cut. +I think, [H um,] I can fix that later today. +[F We should,] [H uh,] we need to restart the server. +[F It was-] it is really simple once you see it. +You can see [F the wh-] the waveform here. +That makes sense, [D right?] +Is that right? +Turn right at the second menu. +Would you like to try it yourself? +Just like that, the clip is gone. +So far so good. +So much for the old workflow. +We saved the file so we could share it. +It was so fast that I missed it. +[D Well,] that is all for today. +Well done to the whole team. +[D Actually,] this setting matters a lot. +It actually works on Windows now. +The video was literally three seconds long. +[D Honestly,] I did not expect that. +[D I mean,] it works, but it is slow. +What I mean is that the cache is stale. +I mean it when I say thank you. +It was hard to debug, [D you know?] +[D You know,] this used to take an hour. +You know how to do this already. +Do you know where the export went? +You know what to click next. +It is kind of cool how fast it is. +It was, [D kind of,] a mess before. +This is a different sort of tool. +She had had enough of the old editor. +I know that that is confusing. +No no no, not that one. +Dial nine one one if it catches fire. +The build number is 4 4 2. +It is very very fast now. +That was really really helpful, thanks. +[H Hmm,] where did that file go? +[H Ummm] let me think about that. +[H Uhhh] I forgot the password. +[H Er,] the second option, sorry. +[H Erm,] maybe the third one. +[H Ah,] there it is. +Uh-huh, that is exactly right. +Mm-hmm, I agree with that. +The umbrella icon is the weather setting. +[D Okay.] Let's look at the timeline. +It was okay, nothing special. +[D Right,] [D so] the next step is captions. +[D All right,] let's move on. +All right answers get a green tick. +[R I] I think this is the last bug. +[R We we] we finally fixed it. +[R I want to,] [H um,] I want to show you this part. +Click on [R the,] [H uh,] the export button. +[R Of the] of the three options, pick the first. +[F I was gonna,] [H uh,] I am going to skip this. +[F The thing,] [H um,] the main thing is speed. +The thing is, [H uh,] the server was down. +I went home and I slept. +[D So] today we are talking about captions. +[D So] I opened the project and it crashed. +So what do we do now? +We went home, so we rested. +| [D So] the next part is the timeline. +I like how clean this looks. +It feels like, [H um,] forever since the last release. +[D Like,] I do not even know what happened. +They were, [D like,] five minutes late. +Things like apples and oranges are fruit. +The new UI is like the old one. +[D Basically,] [D like,] you just press record. +And then, [H um,] you press stop. +[H Uh,] [D so,] where was I? +You can, [H um,] trim the start here. +[R It] it should be fine. +Bye bye for now. +[D Okay,] [D so] [D basically,] that is the whole flow. +We tested it | it worked on the first try. +Go. Go now before it closes. +[H Um] [H uh] [H um] I lost my train of thought. +[F My-] my microphone was muted. +[F The c-] the camera was off. +I have the code here. [D So] let me paste it. +It is what it is. +What it is is a cache. +Do not do that. +[R That] that way is wrong, so we changed it. +He said that that was fine. +[R They] they did not answer. +[R This is] this is the important bit. +[F This is,] [H uh,] this was a problem last week. +I can see it on the right side. +Right now the export is faster. +Okay is the default button. +The okay button is disabled. +I was like, wow, that is fast. +She was like no, that is wrong. +[D You know what I mean?] It just works. +[D I mean,] [D you know,] it is fine. +Literally everyone asked for this feature. +It is literally the best update so far. +[D Actually,] [H um,] let me go back. +Actually the first one was better. +This actually matters for long recordings. +It works, actually. +I sort of see what you mean. +[R So] [D so] the first step is the upload. +[H Mmm,] not quite. +[H Hmm] interesting. +[H Ehm,] I am not sure. +I think [R the] the second clip is shorter. +Let me just, [H uh,] zoom in a bit. +We need to, [H um,] check the logs. +Can you, [H er,] share your screen? +[R You can] you can drag it here. +[F If you,] [H um,] if we look at the graph it is clear. +[F And we,] [H uh,] and then we saw the spike. +[R So the,] [H um,] so the result was faster. +It is a kind of shortcut for power users. +The kind of feedback we want is honest. +He is kind of right about that. +Basically everything works now. +That is basically it. +Honestly I think it is fine. +Seriously, this is great. +We really need to talk about pricing. +I did not like the old icons. +The like button moved to the left. +There are like five ways to do this. +[D Well,] [H um,] I guess that is it. +Well, well, look at that. +Well it depends on the project. +That went well. +[D So,] so many people asked for this. +[D So] yeah, that is the update. +[H Uh] [D so] [D okay,] here we go. +The video is about ten minutes long. +It was a long long time ago. +Many many thanks to everyone. +We met at nine and talked until ten. +I said no, and I meant no. +It was [R the] the best version we shipped. +Please, please send me the logs. +He tried and tried and tried. +Again and again it crashed. +Step by step it gets easier. +Day by day the queue shrinks. +Right click the clip to split it. +The right answer is the second one. +Click right here. +That is right, the second one. +It is not right yet. +Is it okay if I share this? +Everything is okay now. +[D Okay] [D so] the timeline is loaded. +"#; + +/// Written after the rules above were frozen and never used to tune them: +/// stand-ups, bug reports and support replies, read aloud. Its scores are the +/// honest estimate of how the classifier does on speech it has not seen. +const HELD_OUT: &str = r#" +[H Um,] yesterday I finished the billing page. +[D So] the main blocker is still the flaky test. +[R I] I pushed a fix for it this morning. +[H Uh,] it only fails on the slow runners. +[D Basically,] the mock server starts too late. +I like the new retry logic a lot. +It was, [D like,] twenty seconds before the first request. +[F We could,] [H um,] we might just raise the timeout. +That would hide the real problem though. +[D You know,] I think the order of the setup is wrong. +The setup runs before the database is ready. +[H Hmm,] let me check the logs again. +[R The] the logs say the port was busy. +So we need a random port per test. +[D Okay,] [D so] that is my update. +For the bug report, [H uh,] the user sees a blank screen. +It happens right after they log in. +[F It is-] it was fine last week. +I think [R we we] we broke it with the new router. +[D Actually,] the router change shipped on Monday. +The screen is blank for, [D like,] two seconds. +Then [R it,] [H um,] it comes back on its own. +That sounds like a loading state problem. +[D I mean,] the data is there, it just does not render. +Do you know which version they are on? +They are on the latest one, I checked. +[D Right,] [D so] I will add a spinner for now. +[H Ah,] and the support ticket from yesterday. +They asked how to, [H uh,] export without the camera. +You can turn the camera off in the sidebar. +It is kind of hidden, to be honest. +[D Well,] we should probably make it more obvious. +I would like to move it to the top. +[R Can you] can you take a look at the design? +[F The design,] [H um,] the current design has room for it. +It looks like there is space next to the title. +That is a good spot, actually. +[D So] next week I will focus on performance. +[H Um] [H uh] the profiler shows two hot paths. +The first one is the thumbnail cache. +The second one is, [D you know,] the waveform drawing. +[R It it] it redraws every frame right now. +We only need to redraw when the zoom changes. +That should cut the CPU use by half. +[F My-] my guess is more than half. +So far so good on the memory side. +No no, the memory is fine. +[D Okay.] That is everything from me. +Thanks, everyone. +"#; + +#[test] +fn held_out_precision_and_recall() { + let (scores, removal, mistakes) = evaluate_text(HELD_OUT); + let report = scores + .iter() + .map(|(kind, score)| { + format!( + "{kind:?}: precision {:.3} recall {:.3} ({score:?})", + score.precision(), + score.recall() + ) + }) + .chain([format!( + "Any removal: precision {:.3} recall {:.3} ({removal:?})", + removal.precision(), + removal.recall() + )]) + .collect::>() + .join("\n"); + println!("held out\n{report}\n{}", mistakes.join("\n")); + assert!( + removal.precision() >= 0.95 && removal.recall() >= 0.85, + "{report}\n{}", + mistakes.join("\n") + ); + let hesitation = scores[0].1; + assert!(hesitation.precision() == 1.0 && hesitation.recall() == 1.0); +} + +/// A second held-out set, written after the clause-boundary fix that the first +/// one exposed, and measured once: a teacher walking through a spreadsheet and +/// a podcast intro. +const HELD_OUT_SECOND: &str = r#" +[H Um,] welcome back to the show. +[D So] this week we have a really fun guest. +She builds, [H uh,] tiny robots out of old phones. +[D Honestly,] I did not know that was possible. +[R She she] she showed me one before we started. +It walks, [D like,] really slowly across the desk. +[D Okay,] [D so] let's get into the spreadsheet. +Column A has the names of every student. +[H Uh,] column B has their scores. +I want to, [H um,] sort them from high to low. +[F You click,] [H uh,] you right click the header. +Then you pick sort from the menu. +[D You know,] most people miss that option. +The scores are, [D kind of,] all over the place. +[R Some] some students did really well. +Others, [H um,] need a bit more help. +I think we should talk about the average next. +The average is just the sum divided by the count. +[D Basically,] the formula does that for you. +[H Hmm,] the average looks low. +[D Well,] one student has a zero. +That zero is, [H uh,] a missing test. +[F We need,] [H um,] we should mark it as absent. +Then the average makes more sense. +I like using colors for the grades. +Green is good and red needs work. +[D Right,] that covers the basics. +[D So] next time we will build a chart. +A chart makes the trends much easier to see. +[H Ah,] one more thing before I go. +Save your work often, [D you know?] +The app does not always save on its own. +[R It it] it crashed on me last week. +I lost, [D like,] an hour of work. +[D Anyway,] thanks for listening. +See you next week. +"#; + +#[test] +fn second_held_out_precision_and_recall() { + let (scores, removal, mistakes) = evaluate_text(HELD_OUT_SECOND); + let report = scores + .iter() + .map(|(kind, score)| { + format!( + "{kind:?}: precision {:.3} recall {:.3} ({score:?})", + score.precision(), + score.recall() + ) + }) + .chain([format!( + "Any removal: precision {:.3} recall {:.3} ({removal:?})", + removal.precision(), + removal.recall() + )]) + .collect::>() + .join("\n"); + println!("second held out\n{report}\n{}", mistakes.join("\n")); + assert!(scores[0].1.precision() == 1.0, "{report}"); +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +struct Gold(Option); + +fn kind_for(letter: char) -> DisfluencyKind { + match letter { + 'H' => DisfluencyKind::Hesitation, + 'R' => DisfluencyKind::Repetition, + 'F' => DisfluencyKind::FalseStart, + 'D' => DisfluencyKind::Discourse, + other => panic!("unknown label {other}"), + } +} + +fn parse_line(line: &str) -> Vec<(String, f64, f64, Gold)> { + let mut out = Vec::new(); + let mut time = 0.0; + let mut open: Option = None; + for raw in line.split_whitespace() { + if raw == "|" { + time += 1.4; + continue; + } + let mut text = raw; + if let Some(rest) = text.strip_prefix('[') { + open = Some(kind_for(rest.chars().next().expect("label"))); + continue; + } + let closes = text.ends_with(']'); + if closes { + text = &text[..text.len() - 1]; + } + out.push((text.to_string(), time, time + 0.24, Gold(open))); + time += 0.3; + if closes { + open = None; + } + } + out +} + +#[derive(Default, Debug, Clone, Copy)] +struct Score { + true_positive: usize, + false_positive: usize, + false_negative: usize, +} + +impl Score { + fn precision(self) -> f64 { + let predicted = self.true_positive + self.false_positive; + if predicted == 0 { + 1.0 + } else { + self.true_positive as f64 / predicted as f64 + } + } + + fn recall(self) -> f64 { + let actual = self.true_positive + self.false_negative; + if actual == 0 { + 1.0 + } else { + self.true_positive as f64 / actual as f64 + } + } +} + +fn evaluate() -> (Vec<(DisfluencyKind, Score)>, Score, Vec) { + evaluate_text(CORPUS) +} + +fn evaluate_text(corpus: &str) -> (Vec<(DisfluencyKind, Score)>, Score, Vec) { + let mut scores: Vec<(DisfluencyKind, Score)> = DisfluencyKind::ALL + .iter() + .map(|kind| (*kind, Score::default())) + .collect(); + let mut removal = Score::default(); + let mut mistakes = Vec::new(); + for line in corpus.lines().filter(|line| !line.trim().is_empty()) { + let parsed = parse_line(line); + let tokens: Vec<_> = parsed + .iter() + .map(|(text, start, end, _)| DisfluencyToken { + text, + start: *start, + end: *end, + }) + .collect(); + let mut predicted = vec![None; parsed.len()]; + for found in detect_disfluencies(&tokens) { + for slot in &mut predicted[found.words] { + *slot = Some(found.kind); + } + } + for ((text, _, _, Gold(gold)), predicted) in parsed.iter().zip(&predicted) { + match (gold, predicted) { + (Some(_), Some(_)) => removal.true_positive += 1, + (None, Some(_)) => removal.false_positive += 1, + (Some(_), None) => removal.false_negative += 1, + (None, None) => {} + } + for (kind, score) in &mut scores { + let is_gold = *gold == Some(*kind); + let is_predicted = *predicted == Some(*kind); + match (is_gold, is_predicted) { + (true, true) => score.true_positive += 1, + (false, true) => score.false_positive += 1, + (true, false) => score.false_negative += 1, + (false, false) => {} + } + } + if *gold != *predicted { + mistakes.push(format!( + "{text:?}: expected {gold:?}, found {predicted:?} in {line:?}" + )); + } + } + } + (scores, removal, mistakes) +} + +#[test] +fn corpus_precision_and_recall_per_category() { + let (scores, removal, mistakes) = evaluate(); + let report = scores + .iter() + .map(|(kind, score)| { + format!( + "{kind:?}: precision {:.3} recall {:.3} ({score:?})", + score.precision(), + score.recall() + ) + }) + .chain([format!( + "Any removal: precision {:.3} recall {:.3} ({removal:?})", + removal.precision(), + removal.recall() + )]) + .collect::>() + .join("\n"); + println!("{report}\n{}", mistakes.join("\n")); + + for (kind, score) in &scores { + let (min_precision, min_recall) = match kind { + DisfluencyKind::Hesitation => (1.0, 1.0), + DisfluencyKind::Repetition => (0.95, 0.9), + DisfluencyKind::FalseStart => (0.9, 0.8), + DisfluencyKind::Discourse => (0.95, 0.75), + }; + assert!( + score.precision() >= min_precision && score.recall() >= min_recall, + "{report}\n{}", + mistakes.join("\n") + ); + } + assert!( + removal.precision() >= 0.97, + "{report}\n{}", + mistakes.join("\n") + ); +} + +#[test] +fn corpus_has_enough_of_every_category() { + let mut counts = [0usize; 4]; + let mut negatives = 0; + for line in CORPUS.lines().filter(|line| !line.trim().is_empty()) { + let parsed = parse_line(line); + if parsed.iter().all(|(.., gold)| gold.0.is_none()) { + negatives += 1; + } + for (.., Gold(gold)) in parsed { + if let Some(kind) = gold { + counts[kind.priority() as usize] += 1; + } + } + } + assert!(counts.iter().all(|count| *count >= 10), "{counts:?}"); + assert!(negatives >= 60, "{negatives}"); +} diff --git a/crates/project/src/disfluency/tests.rs b/crates/project/src/disfluency/tests.rs new file mode 100644 index 00000000000..8e64f035815 --- /dev/null +++ b/crates/project/src/disfluency/tests.rs @@ -0,0 +1,419 @@ +use super::*; + +fn tokens(text: &str) -> Vec<(String, f64, f64)> { + let mut time = 0.0; + let mut out = Vec::new(); + for raw in text.split_whitespace() { + if raw == "|" { + time += 1.2; + continue; + } + out.push((raw.to_string(), time, time + 0.25)); + time += 0.3; + } + out +} + +fn detect(text: &str) -> Vec<(DisfluencyKind, String)> { + let owned = tokens(text); + let borrowed: Vec<_> = owned + .iter() + .map(|(text, start, end)| DisfluencyToken { + text, + start: *start, + end: *end, + }) + .collect(); + detect_disfluencies(&borrowed) + .into_iter() + .map(|found| { + let text = owned[found.words.clone()] + .iter() + .map(|(text, _, _)| text.as_str()) + .collect::>() + .join(" "); + (found.kind, text) + }) + .collect() +} + +use DisfluencyKind::*; + +#[test] +fn starter_helpers_keep_their_contract() { + assert_eq!(normalize_word("Um,"), "um"); + assert_eq!(normalize_word("\"Don't!\""), "don't"); + assert_eq!(normalize_word("..."), ""); + assert!(is_hesitation_filler("Uh.")); + assert!(is_hesitation_filler("hmm")); + assert!(!is_hesitation_filler("ummmm")); + assert!(!is_hesitation_filler("umbrella")); +} + +#[test] +fn drawn_out_hesitations_are_caught() { + for spelling in [ + "ummmm", "Uhhhh,", "UMMM", "hmmmm", "mmmmm", "errrm", "errr", "aaah", "ahhhh", "ehhh", + "uhmmm", "ehm", "um-", "(um)", "[uh]", "Umm...", + ] { + assert!(is_hesitation(spelling), "{spelling}"); + } +} + +#[test] +fn words_that_only_look_like_hesitations_are_left() { + for word in [ + "uh-huh", "mm-hmm", "mhm", "uh-uh", "a", "I", "umbrella", "hum", "her", "era", "aha", "oh", + "huh", "m", "em", "hey", "um1", "", + ] { + assert!(!is_hesitation(word), "{word}"); + } +} + +#[test] +fn hesitations_are_found_anywhere() { + assert_eq!( + detect("Um, so I think, uh, we can go."), + vec![ + (Hesitation, "Um,".into()), + (Discourse, "so".into()), + (Hesitation, "uh,".into()) + ] + ); +} + +#[test] +fn repeated_words_mark_every_copy_but_the_last() { + assert_eq!( + detect("I I think we we we should go"), + vec![ + (Repetition, "I".into()), + (Repetition, "we".into()), + (Repetition, "we".into()) + ] + ); + assert_eq!( + detect("open the the settings"), + vec![(Repetition, "the".into())] + ); +} + +#[test] +fn repeated_phrases_are_found_through_hesitations() { + assert_eq!( + detect("I want to, um, I want to show you this"), + vec![ + (Repetition, "I want to,".into()), + (Hesitation, "um,".into()) + ] + ); + assert_eq!( + detect("click on the, uh, the button"), + vec![(Repetition, "the,".into()), (Hesitation, "uh,".into())] + ); +} + +#[test] +fn intentional_doubles_are_kept() { + for sentence in [ + "it is very very fast", + "she had had enough", + "I know that that works", + "no no no, not that one", + "call nine one one", + "the code is 4 4 2", + "bye bye everyone", + "what it is is a cache", + "it was really really good", + ] { + assert!( + detect(sentence).iter().all(|(kind, _)| *kind != Repetition), + "{sentence}" + ); + } +} + +#[test] +fn repeats_across_a_sentence_break_or_long_pause_are_kept() { + assert!(detect("Go. Go now.").is_empty()); + assert!(detect("we tested it | it worked").is_empty()); +} + +#[test] +fn cut_off_fragments_are_false_starts() { + assert_eq!( + detect("we need the wh- the settings"), + vec![(FalseStart, "the wh-".into())] + ); +} + +#[test] +fn restarted_clauses_are_false_starts() { + assert_eq!( + detect("we should, um, we need to restart"), + vec![ + (FalseStart, "we should,".into()), + (Hesitation, "um,".into()) + ] + ); + assert_eq!( + detect("it was- it is really simple"), + vec![(FalseStart, "it was-".into())] + ); +} + +#[test] +fn complete_clauses_before_a_hesitation_are_not_false_starts() { + assert_eq!( + detect("I think, um, I can fix it"), + vec![(Hesitation, "um,".into())] + ); + assert_eq!( + detect("the thing is, uh, the server is down"), + vec![(Hesitation, "uh,".into())] + ); + assert!(detect("I went home and I slept").is_empty()); +} + +#[test] +fn like_is_only_a_filler_when_set_off() { + assert_eq!( + detect("it was, like, huge"), + vec![(Discourse, "like,".into())] + ); + assert_eq!( + detect("Like, I don't know."), + vec![(Discourse, "Like,".into())] + ); + for sentence in [ + "I like pizza", + "it looks like a bug", + "just like that", + "would you like to see it", + "I like it.", + "feels like, um, forever", + ] { + assert!( + detect(sentence).iter().all(|(kind, _)| *kind != Discourse), + "{sentence}" + ); + } +} + +#[test] +fn you_know_and_i_mean_need_to_be_set_off() { + assert_eq!( + detect("it was hard, you know?"), + vec![(Discourse, "you know?".into())] + ); + assert_eq!( + detect("You know, this is better"), + vec![(Discourse, "You know,".into())] + ); + assert_eq!( + detect("I mean, it works"), + vec![(Discourse, "I mean,".into())] + ); + for sentence in [ + "you know how to do it", + "do you know where it is", + "what I mean is simple", + "I mean it.", + "you know what to click", + ] { + assert!(detect(sentence).is_empty(), "{sentence}"); + } +} + +#[test] +fn hedges_only_count_with_commas() { + assert_eq!( + detect("it was, kind of, a mess"), + vec![(Discourse, "kind of,".into())] + ); + assert!(detect("it's kind of cool").is_empty()); + assert!(detect("a different sort of tool").is_empty()); +} + +#[test] +fn adverbs_need_to_be_set_off() { + assert_eq!( + detect("Basically, you click here"), + vec![(Discourse, "Basically,".into())] + ); + assert_eq!( + detect("Actually, it works"), + vec![(Discourse, "Actually,".into())] + ); + assert!(detect("it actually works").is_empty()); + assert!(detect("it works, actually.").is_empty()); + assert!(detect("it was literally translated").is_empty()); +} + +#[test] +fn sentence_openers_are_fillers() { + assert_eq!( + detect("So today we will look at exports"), + vec![(Discourse, "So".into())] + ); + assert_eq!( + detect("Okay, so let's start."), + vec![(Discourse, "Okay,".into()), (Discourse, "so".into())] + ); + assert_eq!( + detect("Okay. Let's start."), + vec![(Discourse, "Okay.".into())] + ); + assert_eq!( + detect("Well, that is it."), + vec![(Discourse, "Well,".into())] + ); + assert_eq!( + detect("Right, so the next step"), + vec![(Discourse, "Right,".into()), (Discourse, "so".into())] + ); +} + +#[test] +fn so_in_the_middle_or_as_a_degree_word_is_kept() { + for sentence in [ + "it was so fast", + "I saved it so I could share it", + "So much for that.", + "So far so good.", + "So what?", + "We went home, so we rested.", + "it was okay", + "turn right here", + "Is that right?", + "Well done.", + ] { + assert!( + detect(sentence).iter().all(|(kind, _)| *kind != Discourse), + "{sentence}" + ); + } +} + +#[test] +fn right_as_a_tag_question_is_a_filler() { + assert_eq!( + detect("that makes sense, right?"), + vec![(Discourse, "right?".into())] + ); +} + +#[test] +fn punctuation_tokens_attach_to_the_previous_word() { + let owned = [ + ("it", 0.0, 0.2), + ("was", 0.3, 0.5), + (",", 0.5, 0.5), + ("like", 0.6, 0.8), + (",", 0.8, 0.8), + ("huge", 0.9, 1.2), + ]; + let tokens: Vec<_> = owned + .iter() + .map(|(text, start, end)| DisfluencyToken { + text, + start: *start, + end: *end, + }) + .collect(); + let found = detect_disfluencies(&tokens); + assert_eq!(found.len(), 1); + assert_eq!(found[0].kind, Discourse); + assert_eq!(found[0].words, 3..4); + assert_eq!(found[0].phrase, "like"); +} + +#[test] +fn each_token_belongs_to_one_result() { + let owned = tokens("um um um so so the the the, like, uh, you know, I I I"); + let borrowed: Vec<_> = owned + .iter() + .map(|(text, start, end)| DisfluencyToken { + text, + start: *start, + end: *end, + }) + .collect(); + let found = detect_disfluencies(&borrowed); + assert!( + found + .windows(2) + .all(|pair| pair[0].words.end <= pair[1].words.start) + ); + assert!(found.iter().all(|found| !found.words.is_empty())); + assert_eq!( + found + .iter() + .filter(|found| found.kind == Hesitation) + .count(), + 4 + ); +} + +#[test] +fn hostile_inputs_do_not_panic() { + assert!(detect_disfluencies(&[]).is_empty()); + let odd = [ + DisfluencyToken { + text: "", + start: f64::NAN, + end: f64::NAN, + }, + DisfluencyToken { + text: ",", + start: 0.0, + end: 0.0, + }, + DisfluencyToken { + text: "um", + start: f64::INFINITY, + end: f64::NEG_INFINITY, + }, + DisfluencyToken { + text: "-", + start: 1.0, + end: 0.5, + }, + DisfluencyToken { + text: "日本語", + start: 2.0, + end: 2.5, + }, + DisfluencyToken { + text: "日本語", + start: 2.5, + end: 3.0, + }, + ]; + let found = detect_disfluencies(&odd); + assert!(found.iter().any(|found| found.kind == Hesitation)); +} + +#[test] +fn twenty_thousand_words_classify_quickly() { + let sentence = "So, um, I think we we should, uh, we need to look at, like, the export settings, you know? It was really really good. "; + let text = sentence.repeat(20_000 / sentence.split_whitespace().count() + 1); + let owned = tokens(&text); + let borrowed: Vec<_> = owned + .iter() + .map(|(text, start, end)| DisfluencyToken { + text, + start: *start, + end: *end, + }) + .collect(); + let started = std::time::Instant::now(); + let found = detect_disfluencies(&borrowed); + let elapsed = started.elapsed(); + assert!(found.len() > 5_000); + assert!( + elapsed < std::time::Duration::from_millis(if cfg!(debug_assertions) { 500 } else { 60 }), + "{elapsed:?} for {} words", + borrowed.len() + ); +} diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs index f5fe2aa2fd5..0a6cf9b1c9b 100644 --- a/crates/project/src/lib.rs +++ b/crates/project/src/lib.rs @@ -5,6 +5,7 @@ pub mod caption_words; mod config_write_tests; mod configuration; pub mod cursor; +pub mod disfluency; pub mod keyboard; mod meta;