Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 97 additions & 10 deletions apps/app_macos/lib/application/services/gap_backfill.service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -90,17 +90,80 @@ final class GapBackfillService {
/// (jusqu'au segment intact suivant, 30 s au plus). Les autres sources,
/// les segments hors fenêtre et les passages non transcrits ne sont
/// jamais touchés.
///
/// Les repères rangés d'une source qui se recoupent ou se touchent (un
/// repère provisoire et un final après un arrêt brutal, sonde 7) forment
/// une union : un seul intervalle, sous le premier repère ; les autres
/// repères de l'union sont dans [BackfillGap.replacedIds] et partent quand
/// l'union est retrouvée.
static List<BackfillGap> plan(
List<TranscriptSegmentEntity> segments, {
List<DictatedInterval> dictated = const <DictatedInterval>[],
}) => <BackfillGap>[
for (final TranscriptSegmentEntity s in segments)
if (_isGapMarker(s))
if (_markerTimes.firstMatch(s.text) case final RegExpMatch m)
if (!_insideDictation(s, m, dictated))
..._planMarker(s, _ms(m, 4), segments, dictated),
for (final _MarkerUnion u in _unions(segments, dictated))
for (final BackfillGap g in _planMarker(
u.first,
u.end,
segments,
dictated,
endLimit: u.nextStart,
))
(
markerId: g.markerId,
source: g.source,
startMs: g.startMs,
endMs: g.endMs,
replacedIds: <String>[...g.replacedIds, ...u.others],
),
];

/// Unions des repères de perte d'une même source (début, fin), hors
/// dictée, triées par début.
static List<_MarkerUnion> _unions(
List<TranscriptSegmentEntity> segments,
List<DictatedInterval> dictated,
) {
final List<({TranscriptSegmentEntity marker, int end})> markers =
<({TranscriptSegmentEntity marker, int end})>[
for (final TranscriptSegmentEntity s in segments)
if (_isGapMarker(s))
if (_markerTimes.firstMatch(s.text) case final RegExpMatch m)
if (!_insideDictation(s, m, dictated))
(marker: s, end: _ms(m, 4)),
]..sort(
(
({TranscriptSegmentEntity marker, int end}) a,
({TranscriptSegmentEntity marker, int end}) b,
) => a.marker.timestampMs.compareTo(b.marker.timestampMs),
);
final List<_MarkerUnion> unions = <_MarkerUnion>[];
for (final ({TranscriptSegmentEntity marker, int end}) m in markers) {
_MarkerUnion? open;
for (final _MarkerUnion u in unions.reversed) {
if (u.first.source == m.marker.source &&
m.marker.timestampMs <= u.end) {
open = u;
break;
}
}
if (open == null) {
unions.add(_MarkerUnion(m.marker, m.end));
} else {
open.others.add(m.marker.id);
if (m.end > open.end) open.end = m.end;
}
}
for (int i = 0; i < unions.length; i++) {
for (int j = i + 1; j < unions.length; j++) {
if (unions[j].first.source == unions[i].first.source) {
unions[i].nextStart = unions[j].first.timestampMs;
break;
}
}
}
return unions;
}

/// Un segment qui commence à moins de [edgeTolerance] d'un bord de la
/// perte appartient à la phrase coupée (le texte arrive ~1 s après
/// l'audio ; sonde 5 : au plus 1,2 s après le début, 1 s avant la fin).
Expand All @@ -119,8 +182,9 @@ final class GapBackfillService {
TranscriptSegmentEntity marker,
int lostEnd,
List<TranscriptSegmentEntity> segments,
List<DictatedInterval> dictated,
) {
List<DictatedInterval> dictated, {
int? endLimit,
}) {
final int tolerance = edgeTolerance.inMilliseconds;
final List<TranscriptSegmentEntity> live =
segments
Expand Down Expand Up @@ -156,6 +220,11 @@ final class GapBackfillService {
: last + _afterReplacedSpan.inMilliseconds;
if (cover > end) end = cover;
}
// Le prolongement s'arrête où commence l'union suivante de la source :
// son audio est retranscrit par elle (jamais deux fois).
if (endLimit != null && end > endLimit) {
end = endLimit > lostEnd ? endLimit : lostEnd;
}
if (start < 0) start = 0;
final List<String> ids = <String>[
for (final TranscriptSegmentEntity x in replaced) x.id,
Expand Down Expand Up @@ -322,9 +391,14 @@ final class GapBackfillService {
// (gap_backfill_overlap_test) : on la garde et on retire le doublon.
// Tout ce qui commence avant la fin reste remplacé, quel que soit son
// texte (sonde 5).
final int? lostEnd = _markerTimes.firstMatch(marker.text) == null
? null
: _ms(_markerTimes.firstMatch(marker.text)!, 4);
// Fin de l'union : celle du plus tardif de ses repères.
final int? lostEnd = <int>[
for (final TranscriptSegmentEntity s in segments)
if ((s.id == marker.id || gap.replacedIds.contains(s.id)) &&
_isGapMarker(s))
if (_markerTimes.firstMatch(s.text) case final RegExpMatch m)
_ms(m, 4),
].fold<int?>(null, (int? a, int b) => a == null || b > a ? b : a);
final TranscriptSegmentEntity? edge = lostEnd == null
? null
: (segments
Expand Down Expand Up @@ -524,3 +598,16 @@ final class GapBackfillService {

/// Issue d'un morceau de repère.
enum _Part { noAudio, unavailable, failed, nothingNew, saved }

/// Union de repères de perte d'une source : le premier (par début), la fin
/// la plus tardive, et les autres repères qu'elle absorbe.
class _MarkerUnion {
_MarkerUnion(this.first, this.end);

final TranscriptSegmentEntity first;
int end;

/// Début de l'union suivante de la même source, s'il y en a une.
int? nextStart;
final List<String> others = <String>[];
}
125 changes: 110 additions & 15 deletions apps/app_macos/lib/application/services/live_transcription.service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,7 @@ final class LiveTranscriptionService {
_log.info('Audio subscription active, en attente de chunks...');
_running = true;
_lossOfPhrase.clear();
_gapMarkers.clear();
_lastSealed.clear();
_provisionalTimer = Timer.periodic(
const Duration(seconds: 1),
Expand Down Expand Up @@ -864,20 +865,115 @@ final class LiveTranscriptionService {
when startMs < sealed.timestampMs) {
_savePartial(sealed.copyWith(timestampMs: startMs));
}
_writeGapMarker(
session,
gap.source,
startMs,
_offsetOf(session, gap.endMs),
);
}

// Repères de perte écrits dans cette session, par source, dans l'ordre :
// (id, début, fin) en heures de réunion.
final Map<AudioSource, List<({String id, int start, int end})>> _gapMarkers =
<AudioSource, List<({String id, int start, int end})>>{};

/// Seul endroit qui écrit un repère de perte. Les repères d'une source ne
/// se chevauchent jamais (sonde 7 : trois repères emboîtés) : une perte
/// qui touche ou recoupe des repères de la même source les fusionne en un
/// seul, l'union, sous l'id du premier ; les autres sont retirés.
void _writeGapMarker(
SessionEntity session,
AudioSource source,
int start,
int end,
) {
final List<({String id, int start, int end})> markers = _gapMarkers
.putIfAbsent(source, () => <({String id, int start, int end})>[]);
final List<({String id, int start, int end})> touched = markers
.where(
(({String id, int start, int end}) m) =>
m.start <= end && start <= m.end,
)
.toList();
int from = start;
int to = end;
for (final ({String id, int start, int end}) m in touched) {
if (m.start < from) from = m.start;
if (m.end > to) to = m.end;
}
final String id = touched.isEmpty
? _newSegmentId(session, source)
: touched.first.id;
final List<String> absorbed = <String>[
for (final ({String id, int start, int end}) m in touched.skip(1)) m.id,
];
markers
..removeWhere(touched.contains)
..add((id: id, start: from, end: to));
final TranscriptSegmentEntity marker = TranscriptSegmentEntity(
id: _newSegmentId(session, gap.source),
id: id,
sessionId: session.id,
source: gap.source,
text: gapMarkerText(startMs, _offsetOf(session, gap.endMs)),
timestampMs: startMs,
source: source,
text: gapMarkerText(from, to),
timestampMs: from,
createdAt: clock.now(),
);
_log.warning('Audio non transcrit: ${marker.text} (${gap.source.name})');
_log.warning('Audio non transcrit: ${marker.text} (${source.name})');
// Atomique pour l'utilisateur : l'union est rangée d'abord (réessayée si
// l'écriture échoue), les repères absorbés ne partent qu'ensuite ; aucun
// intervalle ne reste sans repère.
final List<Future<void>> absorbedWrites = <Future<void>>[
for (final String other in absorbed) ?_segmentWrites[other],
];
_chainWrite(id, () async {
await Future.wait(absorbedWrites);
if (!await _saveWithRetry(marker)) return;
_sortAndDedupeSegments();
for (final String other in absorbed) {
await _transcriptionService.discardProvisional(other);
_transcriptionService.segmentsStream.add(
List<TranscriptSegmentEntity>.from(
_transcriptionService.segmentsStream.value,
)..removeWhere((TranscriptSegmentEntity x) => x.id == other),
);
}
});
}

// Un repère qui ne se range pas est réessayé : 1, 2, 4, 8 s.
// ponytail: 5 essais (15 s, Stop attend au pire autant) puis abandon
// journalisé ; file durable si un disque plein doit tenir plus longtemps.
static const int _markerWriteAttempts = 5;

Future<bool> _saveWithRetry(TranscriptSegmentEntity segment) async {
for (int attempt = 0; attempt < _markerWriteAttempts; attempt++) {
if (attempt > 0) {
await Future<void>.delayed(Duration(seconds: 1 << (attempt - 1)));
}
if (await _transcriptionService.saveSegment(segment)) return true;
}
_log.error('Repère non rangé après $_markerWriteAttempts essais');
return false;
}

// Écritures chaînées par id de segment : la dernière valeur voulue est
// toujours écrite en dernier (revue : un re-rangement non chaîné pouvait
// être écrasé par la première écriture, plus lente).
final Map<String, Future<void>> _segmentWrites = <String, Future<void>>{};

void _chainWrite(String id, Future<void> Function() write) {
late final Future<void> task;
task = _transcriptionService
.saveSegment(marker)
.then((_) => _sortAndDedupeSegments())
.whenComplete(() => _pendingFinalizations.remove(task));
// Une écriture ratée plus tôt pour cet id n'empêche pas la suivante.
task = (_segmentWrites[id] ?? Future<void>.value())
.catchError((Object e) => _log.error('Écriture de $id ratée', e))
.then((_) => write())
.catchError((Object e) => _log.error('Écriture de $id ratée', e))
.whenComplete(() {
_pendingFinalizations.remove(task);
if (identical(_segmentWrites[id], task)) _segmentWrites.remove(id);
});
_segmentWrites[id] = task;
_pendingFinalizations.add(task);
}

Expand Down Expand Up @@ -1144,12 +1240,11 @@ final class LiveTranscriptionService {
<AudioSource, TranscriptSegmentEntity>{};

void _savePartial(TranscriptSegmentEntity segment, {Future<void>? after}) {
late final Future<void> task;
task = (after ?? Future<void>.value())
.then((_) => _transcriptionService.saveSegment(segment))
.then((_) => _sortAndDedupeSegments())
.whenComplete(() => _pendingFinalizations.remove(task));
_pendingFinalizations.add(task);
_chainWrite(segment.id, () async {
await after;
await _transcriptionService.saveSegment(segment);
_sortAndDedupeSegments();
});
}

static final RegExp _wordChar = RegExp(r'[\p{L}\p{N}]', unicode: true);
Expand Down
Loading
Loading