← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Reportage/Services/Narrative/NarrativeBuilder.swift (8836B)

1import Foundation
2
3/// An answer the narrative doesn't cover, shown as its question and answer.
4struct AnswerDetail: Equatable, Identifiable, Sendable {
5    var id: String { questionID }
6    var questionID: String
7    var prompt: String
8    var answer: String
9}
10
11/// Builds narratives from answers using each question's `NarrativeRule`, in
12/// the questions' current order.
13@MainActor
14enum NarrativeBuilder {
15    static func build(
16        responses: [Response],
17        lookup: SummaryLookup
18    ) -> (narrative: String?, details: [AnswerDetail]) {
19        var sentences: [Sentence] = []
20        var details: [AnswerDetail] = []
21        var activities: [String] = []
22        var people: [String] = []
23        var place: String?
24        // The main clause goes where its first answer would have.
25        var clauseIndex: Int?
26
27        // Stable, so answers to the same or unknown questions keep their order.
28        let ordered = responses.enumerated().sorted { a, b in
29            let orders = (lookup.questionOrder[a.element.questionID], lookup.questionOrder[b.element.questionID])
30            return (orders.0 ?? .max, a.offset) < (orders.1 ?? .max, b.offset)
31        }.map(\.element)
32
33        for response in ordered {
34            guard let value = response.value, !lookup.hiddenQuestions.contains(response.questionID)
35            else { continue }
36            switch (lookup.questionRules[response.questionID], value) {
37            case (.activities, .tokens(let ids)):
38                activities += distinct(ids, lookup).compactMap { form(of: $0, rule: .activities, lookup: lookup) }
39                clauseIndex = clauseIndex ?? sentences.count
40            case (.people, .tokens(let ids)):
41                people += distinct(ids, lookup).compactMap { form(of: $0, rule: .people, lookup: lookup) }
42                clauseIndex = clauseIndex ?? sentences.count
43            case (.place, .place(let answer)):
44                place = place ?? form(of: answer.tokenID, rule: .place, lookup: lookup)
45                clauseIndex = clauseIndex ?? sentences.count
46            case (.phrases(let yes, let no), .options(let options)):
47                let phrases = [ResponseValue.yesOption: yes, ResponseValue.noOption: no]
48                if let phrase = options.lazy.compactMap({ phrases[$0] }).first(where: { !$0.isBlank }) {
49                    sentences.append(Sentence(phrase))
50                } else {
51                    details.append(detail(for: response, answer: displayOptions(options)))
52                }
53            case (.template(let format), .options(let options)) where !format.isBlank:
54                let answer = joined(options.map(InlineCasing.inline))
55                sentences.append(Sentence(format.replacingOccurrences(of: "%@", with: answer)))
56            case (.template(let format), .tokens(let ids)) where !format.isBlank:
57                let answers = distinct(ids, lookup).compactMap { form(of: $0, rule: .activities, lookup: lookup) }
58                guard !answers.isEmpty else { continue }
59                sentences.append(Sentence(format.replacingOccurrences(of: "%@", with: joined(answers))))
60            case (.count(let singular, let plural), .number(let number))
61            where !singular.isBlank && !plural.isBlank:
62                let noun = number == 1 ? singular : plural
63                sentences.append(Sentence("\(number.formatted()) \(noun)"))
64            case (.quote(let lead), .text(let note)) where !lead.isBlank:
65                let note = note.trimmingCharacters(in: .whitespacesAndNewlines)
66                let ended = note.last.map { ".!?".contains($0) } ?? false
67                sentences.append(Sentence("\(lead): '\(note)'", isEnded: ended))
68            default:
69                details.append(detail(for: response, answer: describe(value, lookup: lookup)))
70            }
71        }
72
73        if let clause = mainClause(activities: activities, place: place, people: people) {
74            sentences.insert(clause, at: min(clauseIndex ?? 0, sentences.count))
75        }
76        guard !sentences.isEmpty else { return (nil, details) }
77
78        let narrative = sentences.map { sentence in
79            sentence.capitalised + (sentence.isEnded ? "" : ".")
80        }
81        return (narrative.joined(separator: " "), details)
82    }
83
84    private struct Sentence {
85        var text: String
86        var isEnded = false
87
88        init(_ text: String, isEnded: Bool = false) {
89            self.text = text
90            self.isEnded = isEnded
91        }
92
93        var capitalised: String {
94            guard let initial = text.first else { return text }
95            return initial.uppercased() + text.dropFirst()
96        }
97    }
98
99    /// 'Reading and drinking coffee at the library, with Sam and Kai'.
100    private static func mainClause(activities: [String], place: String?, people: [String]) -> Sentence? {
101        var text = ""
102        if !activities.isEmpty {
103            text += joined(activities)
104        }
105        if let place {
106            text += (text.isEmpty ? "At " : " at ") + place
107        }
108        if !people.isEmpty {
109            text += (text.isEmpty ? "With " : ", with ") + joined(people)
110        }
111        return text.isEmpty ? nil : Sentence(text)
112    }
113
114    /// How the token with `id` reads in the main clause under `rule`: its
115    /// narrative form if it has one, or else the form the rules give it. A
116    /// place reads after 'at', and a directory's name is shown as written.
117    static func form(of id: String, rule: NarrativeRule, lookup: SummaryLookup) -> String? {
118        if let form = lookup.narrativeForms[id] { return form }
119        guard let text = lookup.tokenTexts[id] else { return nil }
120        switch rule {
121        case .activities: return InlineCasing.inline(text)
122        case .people: return shortName(text)
123        case .place: return lookup.directoryPlaces.contains(id) ? text : PlacePhrase.phrase(for: text)
124        default: return text
125        }
126    }
127
128    /// How a person reads when they have no narrative form: the part of
129    /// their name before the first space, 'Sam' for 'Sam Lee'. Names in
130    /// Chinese, Japanese or Korean script put the family name first, so
131    /// they're shown whole.
132    static func shortName(_ name: String) -> String {
133        let isCJK = name.unicodeScalars.contains { scalar in
134            scalar.properties.isIdeographic
135                || (0x3040...0x30FF).contains(scalar.value)  // Hiragana and Katakana
136                || (0xAC00...0xD7AF).contains(scalar.value)  // Hangul syllables
137        }
138        guard !isCJK, let first = name.split(separator: " ", maxSplits: 1).first else { return name }
139        return String(first)
140    }
141
142    /// `ids` without those that read as a token earlier in the list, so an
143    /// answer that used two tokens since merged names the token once.
144    static func distinct(_ ids: [String], _ lookup: SummaryLookup) -> [String] {
145        var seen: Set<String> = []
146        return ids.filter { seen.insert(lookup.mergedIDs[$0] ?? $0).inserted }
147    }
148
149    /// 'a', 'a and b', 'a, b and c'.
150    private static func joined(_ items: [String]) -> String {
151        guard items.count > 2 else { return items.joined(separator: " and ") }
152        return items.dropLast().joined(separator: ", ") + " and " + items[items.count - 1]
153    }
154
155    private static func detail(for response: Response, answer: String) -> AnswerDetail {
156        AnswerDetail(questionID: response.questionID, prompt: response.prompt, answer: answer)
157    }
158
159    /// An answer as text, with token IDs replaced by their names.
160    static func describe(_ value: ResponseValue, lookup: SummaryLookup) -> String {
161        switch value {
162        case .options(let options): displayOptions(options)
163        case .tokens(let ids): joined(distinct(ids, lookup).compactMap { lookup.tokenTexts[$0] })
164        case .place(let answer): lookup.tokenTexts[answer.tokenID] ?? ""
165        case .number(let number): number.formatted()
166        case .text(let text): text
167        }
168    }
169
170    /// Yes/no answers are stored as fixed values; everything else is the
171    /// user's own text.
172    private static func displayOptions(_ options: [String]) -> String {
173        joined(
174            options.map { option in
175                switch option {
176                case ResponseValue.yesOption:
177                    String(localized: "Yes", comment: "Answer to a yes/no question")
178                case ResponseValue.noOption:
179                    String(localized: "No", comment: "Answer to a yes/no question")
180                default: option
181                }
182            })
183    }
184}
185
186extension String {
187    /// Whether a rule's text is empty once whitespace is trimmed, which
188    /// leaves the answer to be shown as prompt and answer.
189    fileprivate var isBlank: Bool {
190        trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
191    }
192}