Reportage/Services/Narrative/PlacePhrase.swift (1933B)
1import NaturalLanguage
2
3
4
5
6@MainActor
7enum PlacePhrase {
8
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
24
25
26 private static func compute(_ text: String) -> String {
27 let lower = text.lowercased()
28 if barePlaces.contains(lower) { return lower }
29
30
31
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}