← All repositories

reportage

A life-logging app for iPhone

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


Reportage/Services/Narrative/PlacePhrase.swift (1933B)

1import NaturalLanguage
2
3/// How a place the user named reads after 'at': 'at home', 'at the library',
4/// 'at Blue Bottle'. Names from a place directory don't come here; they're
5/// shown as written.
6@MainActor
7enum PlacePhrase {
8    /// Places that read without an article once lowercased: 'at home'.
9    static let barePlaces: Set<String> = [
10        "home", "work", "school", "bed", "church", "college", "university", "hospital", "town",
11        "class", "uni",
12    ]
13
14    private static var cache: [String: String] = [:]
15
16    static func phrase(for text: String) -> String {
17        if let cached = cache[text] { return cached }
18        let result = compute(text)
19        cache[text] = result
20        return result
21    }
22
23    /// Lowercased, with 'the' unless it reads without one, if the text is
24    /// ordinary words capitalised only at its start and isn't tagged as a
25    /// name. Anything else is taken to be a name and shown as written.
26    private static func compute(_ text: String) -> String {
27        let lower = text.lowercased()
28        if barePlaces.contains(lower) { return lower }
29
30        // 'Central Library' and 'IKEA' are names, and so is 'Mum's'. The
31        // spell checker passes scripts without case, such as Japanese.
32        let words = lower.split(separator: " ").map(String.init)
33        guard !words.isEmpty, text.dropFirst().allSatisfy({ !$0.isUppercase }),
34            words.allSatisfy({ word in
35                word.allSatisfy { $0.isLetter && $0.isCased } && InlineCasing.isDictionaryWord(word)
36            })
37        else { return text }
38
39        let tagger = NLTagger(tagSchemes: [.nameType])
40        tagger.string = text
41        let (tag, _) = tagger.tag(at: text.startIndex, unit: .word, scheme: .nameType)
42        if let tag, [.personalName, .placeName, .organizationName].contains(tag) { return text }
43
44        return ["the", "a", "an"].contains(words[0]) ? lower : "the " + lower
45    }
46}