Commit f5c6c568 authored by Kourser's avatar Kourser
Browse files

feat: lire en vis-à-vis, le livre d'un côté et le français de l'autre

D'abord fait de travers : une feuille par-dessus le livre, avec une
liste de paragraphes appariés. « Je n'arrive pas à comprendre ce que tu
as fait » — c'était la bonne réaction. Lire en deux langues, c'est
traverser de l'une à l'autre sans quitter la page ; tout ce qui couvre
le livre tue l'affaire. C'est maintenant un volet dans le lecteur.

En paysage, deux colonnes. En portrait, un bandeau sous la page : il
n'y a pas la place pour une seconde colonne lisible. EPUB et PDF.

La séparation se déplace au doigt, et chaque disposition garde son
propre rapport — une bonne largeur de colonne n'est pas une bonne
hauteur de bandeau. Les deux côtés sont bornés : une colonne de deux
centimètres n'est pas une colonne, et un séparateur sans prise est un
piège. Le geste part des bornes du début, pas des bornes courantes, le
défaut déjà corrigé sur les signatures.

Le volet montre le passage qui commence à la page affichée, paragraphe
par paragraphe, et pas un miroir ligne à ligne. Readium pose son texte
dans une vue web et PDFKit pagine à sa façon : ni l'un ni l'autre ne
dira « ces lignes-là sont visibles », donc promettre un miroir serait
promettre quelque chose qui dérive. Commencer au bon paragraphe est ce
dont l'œil a besoin.

Côté PDF, les retours de ligne de la mise en page sont recollés avant
traduction : couper « He had his own » de « wounds to hide » ne donne
rien.

« Traduire tout le livre » apparaît quand un modèle est configuré. Tout
va dans le cache de la traduction au tap : payé d'un côté, gratuit de
l'autre, et une passe interrompue reprend où elle s'est arrêtée. Une
réponse de modèle bien plus longue que l'original est refusée — une
mauvaise traduction, c'est au lecteur de juger ; un paragraphe de
commentaire rangé comme traduction, c'est la faute de l'app.

Un défaut attrapé en relisant : le lecteur vivait dans deux branches
d'un `if`, donc ouvrir le volet ou tourner l'iPad en faisait une
nouvelle vue et rechargeait le livre. Une seule branche, et `AnyLayout`
pour passer de l'horizontale à la verticale sans changer l'identité.

Non vérifié à l'écran : les simulateurs de la machine ont disparu entre
deux sessions, et le nouveau attend une autorisation. 332 tests verts,
build iOS et macOS d'accord.

Co-Authored-By: default avatarClaude Opus 5 <noreply@anthropic.com>
parent bc81e130
Loading
Loading
Loading
Loading
+15 −0
Changes for CHANGELOG.md: 15 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -8,6 +8,21 @@ adopte le [versionnage sémantique](https://semver.org/lang/fr/).
## [Non publié]

### Ajouté
- Lecture bilingue dans le lecteur : le livre d'un côté, le français de
  l'autre. Deux colonnes quand l'iPad est en paysage, un bandeau sous la page
  en portrait, pour l'EPUB comme pour le PDF.
- La séparation se déplace au doigt, et chaque disposition garde son rapport :
  une bonne largeur de colonne n'est pas une bonne hauteur de bandeau. Ni l'un
  ni l'autre côté ne peut être écrasé — une colonne de deux centimètres n'est
  pas une colonne, et un séparateur sans prise est un piège. Réglable aussi à
  VoiceOver.
- Le volet suit la lecture : il se recharge à chaque tourne de page, amorti
  d'un quart de seconde pour ne pas relire le livre à chaque feuilletage.
- « Traduire tout le livre » quand un modèle de langue est configuré. Les
  traductions vont dans le même cache que la traduction au tap : ce qui est
  payé d'un côté est gratuit de l'autre, et une passe interrompue reprend où
  elle s'est arrêtée.

- Une icône. L'app n'en avait aucune : un livre ouvert d'où montent cinq
  barres d'égaliseur, sur un dégradé d'encre. Les deux idées sont fondues en
  une seule forme plutôt qu'empilées — à petite taille les barres se lisent
+98 −0
Changes for Packages/Core/Sources/PodbookUI/Translation/BilingualPage.swift: 98 added lines, 0 removed lines.
Original line number Diff line number Diff line
import Foundation
import Observation

/// The original and its translation, paragraph against paragraph.
///
/// Rows rather than two independent texts: two columns that scroll on their
/// own drift apart after a page and a half, and the whole point of reading in
/// two languages is that the eye can cross from one to the other on the same
/// sentence. So each row holds both sides and grows to the taller of them.
///
/// Translations come out of the same cache the tap-to-translate panel fills,
/// which is what makes « traduire tout le livre » worth doing once: a passage
/// paid for in either place is free in the other, and an interrupted run
/// resumes where it stopped.
@MainActor
@Observable
public final class BilingualPage {
    public struct Row: Identifiable, Sendable {
        public let id: Int
        public let source: String
        public var translation: String?
        /// Where this passage sits in the book, so a tap can take the reader
        /// there.
        public let locator: String?

        public var isTranslated: Bool { translation != nil }
    }

    public private(set) var rows: [Row] = []
    public private(set) var isWorking = false
    public private(set) var failure: String?

    private let cache: TranslationCache
    private let targetLanguage: String
    private let engineID: String

    public init(
        cache: TranslationCache,
        targetLanguage: String = "fr",
        engineID: String = "apple.translation"
    ) {
        self.cache = cache
        self.targetLanguage = targetLanguage
        self.engineID = engineID
    }

    public var translatedCount: Int { rows.count { $0.isTranslated } }

    public var progress: Double {
        rows.isEmpty ? 0 : Double(translatedCount) / Double(rows.count)
    }

    public var untranslated: [Row] { rows.filter { !$0.isTranslated } }

    /// Builds the rows and serves whatever the cache already holds.
    ///
    /// Passages shorter than a handful of characters are dropped: a chapter
    /// number or a lone « — » costs a translation request and tells the reader
    /// nothing.
    public func load(_ segments: [NarrationSegment]) async {
        var built: [Row] = []
        for (index, segment) in segments.enumerated() {
            let text = segment.text.trimmingCharacters(in: .whitespacesAndNewlines)
            guard text.count >= 4 else { continue }
            let cached = await cache.entry(
                source: text, targetLanguage: targetLanguage, engine: engineID
            )
            built.append(Row(
                id: index, source: text, translation: cached?.text, locator: segment.locator
            ))
        }
        rows = built
    }

    /// Records a translation and keeps it for next time.
    public func apply(_ translation: String, to source: String) async {
        let trimmed = translation.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty else { return }
        await cache.store(
            trimmed, source: source, targetLanguage: targetLanguage, engine: engineID
        )
        for index in rows.indices where rows[index].source == source {
            rows[index].translation = trimmed
        }
    }

    public func flush() async { await cache.flush() }

    public func beginWorking() {
        isWorking = true
        failure = nil
    }

    public func endWorking(failure: String? = nil) {
        isWorking = false
        self.failure = failure
    }
}
+64 −0
Changes for Packages/Core/Sources/PodbookUI/Translation/BookTranslator.swift: 64 added lines, 0 removed lines.
Original line number Diff line number Diff line
import Foundation

/// Translates a book passage by passage with a language model.
///
/// The second of the two engines, and the one that can do a whole book in one
/// go. Apple's framework translates a sentence at a time, for free and
/// offline, and that is the right tool while reading; a model served from the
/// Mac is the right tool for « traduis-moi tout ça pendant la nuit », because
/// it keeps a paragraph's register and its pronouns, which a sentence-by-
/// sentence pass cannot.
///
/// Nothing here is clever about batching: one passage, one request. A passage
/// is a paragraph, and paragraphs are the unit the reader's eye crosses on.
/// Batching several would be faster and would also make a single bad answer
/// poison the lot.
public struct BookTranslator: Sendable {
    private let client: any LLMClient
    private let targetLanguage: String

    public init(client: any LLMClient, targetLanguage: String = "français") {
        self.client = client
        self.targetLanguage = targetLanguage
    }

    public var engineID: String { "llm." + client.descriptor.model }

    static func system(target: String) -> String {
        [
            "Tu traduis en \(target) des passages de livre.",
            "",
            "Règles, non négociables :",
            "- Tu rends le passage et rien d'autre : pas de préambule, pas de note, pas de guillemets ajoutés.",
            "- Tu gardes le registre, le temps et la personne de l'original.",
            "- Un paragraphe entre, un paragraphe sort : tu ne découpes ni ne fusionnes.",
            "- Si le passage est déjà en \(target), tu le rends inchangé.",
            "- Tu ne commentes jamais ce que tu traduis.",
        ].joined(separator: "\n")
    }

    /// One passage. Returns `nil` when the model gives back something that is
    /// obviously not a translation — an apology, a refusal, a note about the
    /// text — rather than storing it in the cache where it would be taken for
    /// the real thing.
    public func translate(_ passage: String) async throws -> String? {
        let response = try await client.complete(LLMRequest(
            system: Self.system(target: targetLanguage),
            user: passage,
            maxOutputTokens: max(256, Int(Double(passage.count) / 2.0))
        ))
        return Self.accept(response.text, for: passage)
    }

    /// A model asked to translate sometimes answers *about* the text instead.
    ///
    /// The cheap tells: an answer many times longer than the original, or an
    /// empty one. A wrong translation is the reader's to judge; a paragraph of
    /// commentary stored as a translation is the app's fault.
    static func accept(_ answer: String, for passage: String) -> String? {
        let trimmed = answer.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmed.isEmpty else { return nil }
        guard trimmed.count < max(200, passage.count * 4) else { return nil }
        return trimmed
    }
}
+3 −1
Changes for Packages/Core/Sources/PodbookUI/Translation/SentenceTranslator.swift: 3 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -104,7 +104,9 @@ public final class SentenceTranslator {
        }
    }

    private let cache: TranslationCache
    /// Shared with the bilingual view on purpose: a passage paid for by a tap
    /// is free in the two-column view, and the other way round.
    public let cache: TranslationCache

    public init(cache: TranslationCache = TranslationCache(), targetLanguageCode: String = "fr") {
        self.cache = cache
+190 −0
Changes for Packages/Core/Sources/PodbookUI/Translation/TranslationPane.swift: 190 added lines, 0 removed lines.
Original line number Diff line number Diff line
import SwiftUI

#if canImport(Translation)
@preconcurrency import Translation
#endif

/// The translation of what is on the page, beside the page.
///
/// A panel inside the reader and not a sheet over it: the point of reading in
/// two languages is to cross from one to the other without leaving the book,
/// and anything that covers the page defeats that. The book keeps the left,
/// the translation takes the right in landscape and a band at the bottom when
/// there is no room for a second column.
///
/// What it shows is the passage **starting at the current page**, paragraph by
/// paragraph — not a line-for-line mirror. Readium lays out its own text in a
/// web view and PDFKit paginates its own way; neither will say « these exact
/// lines are visible », so promising a mirror would be promising something
/// that drifts. Starting at the right paragraph is what the eye needs.
struct TranslationPane: View {
    let page: BilingualPage
    let bookTranslator: BookTranslator?
    /// Told when the reader wants the passage re-read, after a page turn.
    let onRefresh: () -> Void

    @State private var work: Task<Void, Never>?

    #if canImport(Translation)
    @State private var configuration: TranslationSession.Configuration?
    #endif

    var body: some View {
        VStack(spacing: 0) {
            header
            Divider()
            body(for: page)
        }
        .background(.background)
        .modifier(AppleTranslationDriver(page: page, configuration: $configuration))
        .onChange(of: page.rows.map(\.id)) { _, _ in translateVisible() }
    }

    private var header: some View {
        HStack(spacing: 10) {
            Text("Français")
                .font(.subheadline.weight(.semibold))
            Spacer()
            if page.isWorking {
                ProgressView().controlSize(.small)
                Button("Arrêter") { stop() }
                    .font(.caption)
            } else if !page.rows.isEmpty, page.untranslated.isEmpty {
                Image(systemName: "checkmark.circle.fill")
                    .font(.caption)
                    .foregroundStyle(.green)
            }
            Menu {
                Button("Retraduire cette page") { translateVisible(force: true) }
                if bookTranslator != nil {
                    Button("Traduire tout le livre") { translateEverything() }
                }
                Button("Actualiser le passage") { onRefresh() }
            } label: {
                Image(systemName: "ellipsis.circle")
            }
        }
        .padding(.horizontal, 14)
        .padding(.vertical, 8)
        .background(.bar)
    }

    @ViewBuilder
    private func body(for page: BilingualPage) -> some View {
        if page.rows.isEmpty {
            ContentUnavailableView(
                "Rien à traduire ici",
                systemImage: "text.alignleft",
                description: Text("Tourne la page : le volet suit la lecture.")
            )
            .font(.footnote)
        } else {
            ScrollView {
                VStack(alignment: .leading, spacing: 14) {
                    ForEach(page.rows) { row in
                        if let translation = row.translation {
                            Text(translation)
                                .textSelection(.enabled)
                        } else {
                            Text(row.source)
                                .foregroundStyle(.tertiary)
                                .italic()
                        }
                    }
                    if let failure = page.failure {
                        Label(failure, systemImage: "exclamationmark.triangle.fill")
                            .font(.footnote)
                            .foregroundStyle(.orange)
                    }
                }
                .padding(14)
                .frame(maxWidth: .infinity, alignment: .leading)
            }
        }
    }

    // MARK: - Traduire

    private func stop() {
        work?.cancel()
        work = nil
        page.endWorking()
    }

    private func translateVisible(force: Bool = false) {
        #if canImport(Translation)
        guard force || !page.untranslated.isEmpty else { return }
        page.beginWorking()
        // Apple ne prête une session qu'à travers la vue : demander une
        // configuration est la façon d'en obtenir une.
        if configuration == nil {
            configuration = TranslationSession.Configuration(
                source: nil, target: Locale.Language(identifier: "fr")
            )
        } else {
            configuration?.invalidate()
        }
        #endif
    }

    private func translateEverything() {
        guard let bookTranslator else { return }
        page.beginWorking()
        work = Task {
            var failure: String?
            for row in page.untranslated {
                if Task.isCancelled { break }
                do {
                    if let translated = try await bookTranslator.translate(row.source) {
                        await page.apply(translated, to: row.source)
                    }
                } catch {
                    failure = (error as? LocalizedError)?.errorDescription
                        ?? error.localizedDescription
                    break
                }
            }
            await page.flush()
            page.endWorking(failure: failure)
        }
    }
}

/// Runs Apple's batch translation when the pane asks for a session.
private struct AppleTranslationDriver: ViewModifier {
    let page: BilingualPage
    #if canImport(Translation)
    @Binding var configuration: TranslationSession.Configuration?
    #endif

    func body(content: Content) -> some View {
        #if canImport(Translation)
        content.translationTask(configuration) { session in
            let pending = page.untranslated
            guard !pending.isEmpty else {
                page.endWorking()
                return
            }
            do {
                // Un lot plutôt qu'une requête par paragraphe : le framework
                // garde l'ordre et répond en une passe.
                let requests = pending.map {
                    TranslationSession.Request(sourceText: $0.source)
                }
                for try await response in session.translate(batch: requests) {
                    await page.apply(response.targetText, to: response.sourceText)
                }
                await page.flush()
                page.endWorking()
            } catch {
                page.endWorking(
                    failure: (error as? LocalizedError)?.errorDescription
                        ?? error.localizedDescription
                )
            }
        }
        #else
        content
        #endif
    }
}
Loading