Repository navigation
Expand file tree
/
Copy pathfacts.go
More file actions
422 lines (390 loc) · 12.8 KB
/
Copy pathfacts.go
File metadata and controls
422 lines (390 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package main
// What somebody has said about themselves, pulled out of what they wrote.
//
// This is deliberately narrow. It reads first person statements, "I'm 34",
// "my daughter", "vivo en Sevilla", and nothing an attacker would have to
// infer. A model reading the same posts would also get the dialect, the
// local references and the hours, and would get more; that is the price of
// having no model in here, and the README says so. What it does read, it
// reads the way a person would: a quote from the comment being answered is
// not the author, "if I were a nurse" is not a nurse, and "my 10 year old
// laptop" is not a child.
import (
"regexp"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
)
type Kind int
const (
Lives Kind = iota
From
Age
Sex
Job
Partner
Parent
Children
ChildBorn
Twins
Grandparent
Pet
Height
Hand
Degree
Condition
Sexuality
Gender
Speaks
Unpriced
)
type Fact struct {
Kind Kind
Value string
// Lo and Hi carry the numbers: a range of birth years for an age, a
// height in centimetres, a number of children.
Lo, Hi float64
Places []Place
Near bool
Said string
Post int
When time.Time
}
type rule struct {
re *regexp.Regexp
read func(r *reader, m []int)
}
func rules(patterns ...any) []rule {
var out []rule
for i := 0; i+1 < len(patterns); i += 2 {
out = append(out, rule{
re: regexp.MustCompile(patterns[i].(string)),
read: patterns[i+1].(func(*reader, []int)),
})
}
return out
}
type reader struct {
text string
post int
when time.Time
facts []Fact
// gender counts the times Spanish grammar agreed with the writer as a
// man and as a woman: "estoy cansado", "estoy cansada".
gender [2]int
hedges map[string]bool
lang string
bio bool
}
func (r *reader) group(m []int, i int) string {
if 2*i+1 >= len(m) || m[2*i] < 0 {
return ""
}
return r.text[m[2*i]:m[2*i+1]]
}
func (r *reader) add(f Fact) {
f.Post = r.post
f.When = r.when
r.facts = append(r.facts, f)
}
func (r *reader) run(rs []rule) {
for _, ru := range rs {
for _, m := range ru.re.FindAllStringSubmatchIndex(r.text, -1) {
if r.hedged(m[0]) {
continue
}
ru.read(r, m)
}
}
}
// hedged says whether a match sits in a sentence that is not the author
// talking about themselves: a hypothetical, a wish, or something inside
// quotation marks, which is almost always somebody else being quoted.
func (r *reader) hedged(at int) bool {
start := at
for start > 0 && at-start < 80 {
c := r.text[start-1]
if c == '.' || c == '!' || c == '?' || c == '\n' || c == ';' {
break
}
start--
}
before := strings.Fields(strings.ToLower(r.text[start:at]))
if len(before) > 4 {
before = before[len(before)-4:]
}
for _, w := range before {
if r.hedges[strings.Trim(w, ",:()\"'")] {
return true
}
}
line := strings.LastIndexByte(r.text[:at], '\n') + 1
return strings.Count(r.text[line:at], `"`)%2 == 1
}
// ageFact turns an age said at some moment into the years somebody could
// have been born in. That is what survives time: "I'm 34" written in 2019
// is somebody about 41 now, and two ages said years apart either agree on
// a birth year or one of them was not true.
func (r *reader) ageFact(age float64, said string) {
if age < 13 || age > 99 {
return
}
y := float64(r.when.Year())
r.add(Fact{Kind: Age, Lo: y - age - 1, Hi: y - age, Said: said})
}
func (r *reader) ageRange(lo, hi float64, said string) {
y := float64(r.when.Year())
r.add(Fact{Kind: Age, Lo: y - hi - 1, Hi: y - lo, Said: said})
}
func (r *reader) childAge(age float64, months bool, child, said string) {
y := float64(r.when.Year())
lo, hi := y-age-1, y-age
if months {
lo, hi = y-1, y
}
if age < 0 || age > 40 {
return
}
r.add(Fact{Kind: ChildBorn, Value: child, Lo: lo, Hi: hi, Said: said})
r.add(Fact{Kind: Parent, Value: "parent", Said: said})
}
// place reads the place named right after a match and files it.
func (r *reader) place(kind Kind, at int, near bool, lead string) {
m, ok := places().find(r.text, at)
if !ok {
return
}
r.add(Fact{Kind: kind, Places: m.places, Near: near, Said: strings.TrimSpace(lead + " " + m.said)})
}
// job reads a job named right after a match: "I'm a night shift ICU nurse"
// has two words in front of the job, and "I'm a huge Doctor Who fan" has
// no job at all. It returns where the job ends, or zero.
func (r *reader) job(at int, table map[string]jobName, lead string) int {
words := wordsFrom(r.text, at, 8)
for skip := 0; skip <= 2 && skip < len(words); skip++ {
if skip > 0 {
w := words[skip-1]
if capitalised(w.word) || notAdjective[strings.ToLower(w.word)] {
break
}
}
for n := min(5, len(words)-skip); n >= 1; n-- {
span := words[skip : skip+n]
key := foldWords(span)
name, ok := table[key]
if !ok {
continue
}
// Capitalised in the middle of a sentence is a name, not a job.
// Acronyms are the exception: RN and EMT are written that way.
if first := span[0].word; capitalised(first) && !isUpper(first) && !sentenceStart(r.text, span[0].start) {
continue
}
end := span[n-1].end
if next := nextWord(r.text, end); jobBreakers[strings.ToLower(next)] || strings.HasPrefix(r.text[end:], "'s") {
continue
}
said := strings.Join(strings.Fields(lead+" "+r.text[span[0].start:end]), " ")
r.add(Fact{Kind: Job, Value: name.title, Said: said})
if name.sex != 0 {
r.add(Fact{Kind: Sex, Value: string(name.sex), Said: said})
}
r.afterJob(end, said)
return end
}
}
return 0
}
// afterJob reads what people put straight after a job, which is very often
// where they do it: "a nurse in Leeds", "enfermera en Valencia", "an
// engineer at Globex".
func (r *reader) afterJob(end int, said string) {
rest := r.text[end:]
for _, in := range []string{" in ", " en ", " near ", " cerca de "} {
if strings.HasPrefix(rest, in) {
r.place(Lives, end+len(in), in != " in " && in != " en ", said+in)
return
}
}
for _, at := range []string{" at ", " for "} {
if strings.HasPrefix(rest, at) && capitalised(nextWord(r.text, end+len(at))) {
r.add(Fact{Kind: Unpriced, Value: "a named employer", Said: said + at + nextWord(r.text, end+len(at))})
return
}
}
}
// jobBreakers are words that turn a job into something else when they
// follow it: a nurse's daughter, a nursing student, a doctor wannabe.
var jobBreakers = map[string]bool{
"student": true, "students": true, "wife": true, "husband": true, "daughter": true,
"son": true, "kid": true, "child": true, "mom": true, "dad": true, "parent": true,
"girlfriend": true, "boyfriend": true, "partner": true, "friend": true, "fan": true,
"wannabe": true, "assistant": true, "school": true, "program": true, "course": true,
"shortage": true, "shortages": true, "strike": true, "costume": true, "show": true,
"game": true, "simulator": true, "character": true,
}
var notAdjective = map[string]bool{
"not": true, "no": true, "fan": true, "friend": true, "lover": true, "kind": true,
"sort": true, "type": true, "bit": true, "lot": true, "part": true, "member": true,
"child": true, "son": true, "daughter": true, "wife": true, "husband": true,
"de": true, "en": true, "con": true, "para": true, "muy": true,
}
type word struct {
word string
start, end int
}
func wordsFrom(text string, at, n int) []word {
var out []word
i := at
for len(out) < n && i < len(text) {
for i < len(text) && (text[i] == ' ' || text[i] == '-') {
i++
}
start := i
for i < len(text) {
c, size := utf8.DecodeRuneInString(text[i:])
inside := i > start && i+1 < len(text) && unicode.IsLetter(rune(text[i+1]))
if unicode.IsLetter(c) || unicode.IsDigit(c) || c == '/' || (c == '.' || c == '\'') && inside {
i += size
continue
}
break
}
if i == start {
break
}
out = append(out, word{text[start:i], start, i})
if i < len(text) && text[i] != ' ' && text[i] != '-' {
break
}
}
return out
}
func foldWords(ws []word) string {
parts := make([]string, len(ws))
for i, w := range ws {
parts[i] = w.word
}
return fold(strings.Join(parts, " "))
}
func nextWord(text string, at int) string {
ws := wordsFrom(text, at, 1)
if len(ws) == 0 {
return ""
}
return ws[0].word
}
func sentenceStart(text string, at int) bool {
i := at
for i > 0 && text[i-1] == ' ' {
i--
}
if i == 0 {
return true
}
switch text[i-1] {
case '.', '!', '?', '\n', '(', '"', ':':
return true
}
return false
}
var units = map[string]bool{
"%": true, "percent": true, "per": true, "minutes": true, "minute": true, "mins": true,
"hours": true, "hour": true, "hrs": true, "days": true, "day": true, "weeks": true,
"week": true, "months": true, "month": true, "feet": true, "foot": true, "ft": true,
"inches": true, "inch": true, "cm": true, "kg": true, "kgs": true, "lbs": true,
"lb": true, "pounds": true, "stone": true, "miles": true, "mile": true, "km": true,
"k": true, "grand": true, "dollars": true, "bucks": true, "euros": true, "times": true,
"degrees": true, "points": true, "games": true, "seconds": true, "hundred": true,
"thousand": true, "million": true, "x": true, "th": true, "st": true, "nd": true,
"rd": true, "of": true, "out": true, "in": true, "on": true,
"minutos": true, "horas": true, "días": true, "semanas": true, "meses": true,
"kilos": true, "metros": true, "por": true, "de": true,
}
// unitAfter says whether the number that ends at text[:at] is a quantity of
// something rather than an age: "I'm 30 minutes away", "I'm 99% sure".
func unitAfter(text string, at int) bool {
rest := strings.TrimLeft(text[at:], " ")
if rest == "" {
return false
}
switch rest[0] {
case '%', '$', '/', '\'', '"', 'k', 'K', '.', ',':
if rest[0] == '.' || rest[0] == ',' {
// "I'm 34." is an age; "I'm 3.5" or "1,80" is not.
return len(rest) > 1 && rest[1] >= '0' && rest[1] <= '9'
}
if rest[0] == 'k' || rest[0] == 'K' {
return len(rest) == 1 || !unicode.IsLetter(rune(rest[1]))
}
return true
}
return units[strings.ToLower(nextWord(text, at))]
}
var numberWords = map[string]int{
"a": 1, "an": 1, "one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6,
"seven": 7, "eight": 8, "nine": 9, "ten": 10, "eleven": 11, "twelve": 12,
"thirteen": 13, "fourteen": 14, "fifteen": 15, "sixteen": 16, "seventeen": 17,
"eighteen": 18, "nineteen": 19, "twenty": 20, "thirty": 30, "forty": 40,
"fifty": 50, "sixty": 60, "seventy": 70, "eighty": 80, "ninety": 90,
"un": 1, "una": 1, "uno": 1, "dos": 2, "tres": 3, "cuatro": 4, "cinco": 5,
"seis": 6, "siete": 7, "ocho": 8, "nueve": 9, "diez": 10, "once": 11, "doce": 12,
"trece": 13, "catorce": 14, "quince": 15, "dieciseis": 16, "diecisiete": 17,
"dieciocho": 18, "diecinueve": 19, "veinte": 20, "veintiuno": 21, "veintiun": 21,
"veintidos": 22, "veintitres": 23, "veinticuatro": 24, "veinticinco": 25,
"veintiseis": 26, "veintisiete": 27, "veintiocho": 28, "veintinueve": 29,
"treinta": 30, "cuarenta": 40, "cincuenta": 50, "sesenta": 60, "setenta": 70,
"ochenta": 80, "noventa": 90,
}
// numberWord reads "34", "thirty-four", "thirty four" and "treinta y
// cuatro". Ages get written out more often than people expect, and more
// often by exactly the people who think they are being careful.
func numberWord(s string) (float64, bool) {
s = fold(strings.TrimSpace(s))
if n, err := strconv.Atoi(s); err == nil {
return float64(n), true
}
total := 0
parts := strings.Fields(strings.NewReplacer(" y ", " ", " and ", " ").Replace(s))
if len(parts) == 0 || len(parts) > 2 {
return 0, false
}
for _, p := range parts {
n, ok := numberWords[p]
if !ok {
return 0, false
}
total += n
}
return float64(total), true
}
// numberPattern is what numberWord can read, for building the patterns
// that feed it.
const numberPattern = `(?:\d{1,2}|(?:twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety)(?:[\s-](?:one|two|three|four|five|six|seven|eight|nine))?|` +
`one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen)`
const numeroPattern = `(?:\d{1,2}|(?:treinta|cuarenta|cincuenta|sesenta|setenta|ochenta|noventa)(?:\s+y\s+(?:uno|un|dos|tres|cuatro|cinco|seis|siete|ocho|nueve))?|` +
`veinti(?:uno|ún|un|dós|dos|trés|tres|cuatro|cinco|séis|seis|siete|ocho|nueve)|` +
`uno|un|una|dos|tres|cuatro|cinco|seis|siete|ocho|nueve|diez|once|doce|trece|catorce|quince|dieci(?:séis|seis|siete|ocho|nueve)|veinte)`
// decade reads "early thirties", "mid 30s", "late twenties".
func decade(which, tens string) (lo, hi float64, ok bool) {
tens = strings.ToLower(strings.TrimSuffix(strings.TrimSuffix(tens, "'s"), "s"))
base := map[string]float64{
"twentie": 20, "thirtie": 30, "fortie": 40, "fiftie": 50, "sixtie": 60,
"seventie": 70, "eightie": 80, "20": 20, "30": 30, "40": 40, "50": 50,
"60": 60, "70": 70, "80": 80,
}[tens]
if base == 0 {
return 0, 0, false
}
switch strings.ToLower(which) {
case "early":
return base, base + 3, true
case "mid":
return base + 3, base + 6, true
case "late":
return base + 6, base + 9, true
}
return base, base + 9, true
}