← All repositories

reportage

A life-logging app for iPhone

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


Shared/Persistence/Vocabulary.swift (8499B)

1import CoreData
2import Foundation
3
4/// A token offered as a suggestion when answering a `tokens`, `people` or
5/// `location` question.
6struct VocabularyEntry: Identifiable, Hashable, Sendable {
7    var id: String
8    var text: String
9    var useCount: Int
10    var lastUsed: Date?
11    /// For places: the token's coordinate, or the centre of the answers
12    /// given for it.
13    var coordinate: Coordinate?
14    /// For places picked from a directory.
15    var externalID: ExternalPlaceID?
16    /// For places: the locality of the most recent report that used it,
17    /// which tells apart places with the same name.
18    var locality: String?
19    /// How the token reads in a narrative, when that differs from `text`.
20    var narrativeForm: String?
21    /// For places from a directory: whether the user has renamed it, so its
22    /// name is no longer the directory's.
23    var isRenamed = false
24    /// The tokens merged into this one, directly or along a chain, most
25    /// used first. Their names still find it.
26    var merged: [MergedToken] = []
27
28    /// Whether the token's name, its narrative form or the name of a token
29    /// merged into it contains `text`.
30    func matches(_ text: String) -> Bool {
31        self.text.localizedStandardContains(text)
32            || narrativeForm?.localizedStandardContains(text) == true
33            || merged.contains { $0.text.localizedStandardContains(text) }
34    }
35}
36
37/// A token merged into another, which can be separated again.
38struct MergedToken: Identifiable, Hashable, Sendable {
39    var id: String
40    var text: String
41    /// How many reports use this token itself, before the merge.
42    var useCount: Int
43}
44
45/// The derived, local-only index that ranks suggestions from response
46/// history. It's rebuilt from responses and never synced: token identity and
47/// text live in the `Token` records.
48enum Vocabulary {
49    /// Suggestions for each of `questionIDs`, most used first, then most
50    /// recently used. Archived tokens and tokens merged into others are left
51    /// out; uses of a merged token count towards the token it was merged into,
52    /// and the merged token is listed in that token's `merged`, wherever its
53    /// question.
54    /// A place with no coordinate of its own is placed at the centre of where
55    /// its answers were given, and each place has the locality of the last
56    /// report that used it.
57    static func entries(
58        for questionIDs: [String],
59        in context: NSManagedObjectContext
60    ) throws -> [String: [VocabularyEntry]] {
61        guard !questionIDs.isEmpty else { return [:] }
62
63        let tokenRequest = TokenEntity.fetchRequest()
64        tokenRequest.predicate = NSPredicate(
65            format: "questionID IN %@ OR mergedInto != nil", questionIDs)
66        let tokens = try context.fetch(tokenRequest).map { try $0.token() }
67        let mergedInto = Dictionary(
68            uniqueKeysWithValues: tokens.compactMap { token in
69                token.mergedInto.map { (token.id, $0) }
70            })
71
72        func canonical(_ id: String) -> String {
73            var id = id
74            var seen: Set<String> = [id]
75            while let next = mergedInto[id], seen.insert(next).inserted {
76                id = next
77            }
78            return id
79        }
80
81        var useCounts: [String: Int] = [:]
82        var ownUseCounts: [String: Int] = [:]
83        var lastUsed: [String: Date] = [:]
84        var answerCoordinates: [String: (latitude: Double, longitude: Double, count: Int)] = [:]
85        var lastReports: [String: NSManagedObjectID] = [:]
86        let responseRequest = NSFetchRequest<NSDictionary>(entityName: "ResponseEntity")
87        responseRequest.resultType = .dictionaryResultType
88        responseRequest.predicate = NSPredicate(
89            format: "questionID IN %@ AND value != nil", questionIDs)
90        responseRequest.propertiesToFetch = ["value", "report", "report.date"]
91        for row in try context.fetch(responseRequest) {
92            guard let data = row["value"] as? Data else { continue }
93            let ids: [String]
94            switch try ModelCoding.decode(ResponseValue.self, from: data) {
95            case .tokens(let tokenIDs): ids = tokenIDs
96            case .place(let place):
97                ids = [place.tokenID]
98                let id = canonical(place.tokenID)
99                if let report = row["report"] as? NSManagedObjectID,
100                    let date = row["report.date"] as? Date, date >= lastUsed[id] ?? .distantPast
101                {
102                    lastReports[id] = report
103                }
104                if let coordinate = place.coordinate {
105                    let sum = answerCoordinates[id] ?? (0, 0, 0)
106                    answerCoordinates[id] = (
107                        sum.latitude + coordinate.latitude,
108                        sum.longitude + coordinate.longitude,
109                        sum.count + 1
110                    )
111                }
112            default: continue
113            }
114            let date = row["report.date"] as? Date
115            for id in Set(ids) where mergedInto[id] != nil {
116                ownUseCounts[id, default: 0] += 1
117            }
118            for id in Set(ids.map(canonical)) {
119                useCounts[id, default: 0] += 1
120                if let date, date > lastUsed[id] ?? .distantPast {
121                    lastUsed[id] = date
122                }
123            }
124        }
125
126        let localities = try self.localities(of: lastReports, in: context)
127
128        var merged: [String: [MergedToken]] = [:]
129        for token in tokens where token.mergedInto != nil {
130            merged[canonical(token.id), default: []].append(
131                MergedToken(id: token.id, text: token.text, useCount: ownUseCounts[token.id] ?? 0))
132        }
133
134        var entries: [String: [VocabularyEntry]] = [:]
135        for token in tokens
136        where questionIDs.contains(token.questionID) && token.mergedInto == nil && token.archivedAt == nil {
137            let centre = answerCoordinates[token.id].map {
138                Coordinate(
139                    latitude: $0.latitude / Double($0.count),
140                    longitude: $0.longitude / Double($0.count))
141            }
142            entries[token.questionID, default: []].append(
143                VocabularyEntry(
144                    id: token.id,
145                    text: token.text,
146                    useCount: useCounts[token.id] ?? 0,
147                    lastUsed: lastUsed[token.id],
148                    coordinate: token.place?.coordinate ?? centre,
149                    externalID: token.place?.externalID,
150                    locality: localities[token.id],
151                    narrativeForm: token.narrativeForm,
152                    isRenamed: token.place?.externalID != nil && !token.isNamedByDirectory,
153                    merged: (merged[token.id] ?? []).sorted { lhs, rhs in
154                        lhs.useCount != rhs.useCount
155                            ? lhs.useCount > rhs.useCount
156                            : lhs.text.localizedStandardCompare(rhs.text) == .orderedAscending
157                    }
158                ))
159        }
160        for questionID in entries.keys {
161            entries[questionID]?.sort(by: ranksBefore)
162        }
163        return entries
164    }
165
166    /// The locality of each report in `reports`, by token ID.
167    private static func localities(
168        of reports: [String: NSManagedObjectID],
169        in context: NSManagedObjectContext
170    ) throws -> [String: String] {
171        guard !reports.isEmpty else { return [:] }
172        let request = ReportEntity.fetchRequest()
173        request.predicate = NSPredicate(format: "self IN %@", Array(Set(reports.values)))
174        var byReport: [NSManagedObjectID: String] = [:]
175        for entity in try context.fetch(request) {
176            guard let data = entity.context,
177                let locality = try ModelCoding.decode(Context.self, from: data).location?.placemark?
178                    .displayLocality
179            else { continue }
180            byReport[entity.objectID] = locality
181        }
182        return reports.compactMapValues { byReport[$0] }
183    }
184
185    static func ranksBefore(_ lhs: VocabularyEntry, _ rhs: VocabularyEntry) -> Bool {
186        if lhs.useCount != rhs.useCount { return lhs.useCount > rhs.useCount }
187        let lhsDate = lhs.lastUsed ?? .distantPast
188        let rhsDate = rhs.lastUsed ?? .distantPast
189        if lhsDate != rhsDate { return lhsDate > rhsDate }
190        return lhs.text.localizedStandardCompare(rhs.text) == .orderedAscending
191    }
192}