-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmetawrap.go
109 lines (90 loc) · 2.02 KB
/
metawrap.go
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
package metawrap
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"os/exec"
)
type MappingCandidate struct {
CandidateScore string
CandidateCUI string
CandidateMatched string
CandidatePreferred string
Negated string
SemTypes []string
Sources []string
MatchedWords []string
}
type Mapping struct {
MappingScore string
MappingCandidates []MappingCandidate
}
type Phrase struct {
PhraseText string
Mappings []Mapping
}
type Utterance struct {
UttText string
Phrases []Phrase
}
type Document struct {
Utterances []Utterance
}
type X struct {
Document Document
}
type MetaMapping struct {
AllDocuments []X
}
type MetaMap struct {
path string
}
// NewMetaMapClient creates a new metawrap client.
func NewMetaMapClient(path string) MetaMap {
return MetaMap{path: path}
}
// Map uses MetaMap to map text to candidates.
func (m MetaMap) Map(text string) (MetaMapping, error) {
cmd := exec.Command("bash", "-c", fmt.Sprintf("echo '%v' | %v --JSONn --silent --negex", text, m.path))
r, err := cmd.StdoutPipe()
if err != nil {
return MetaMapping{}, err
}
cmd.Start()
reader := bufio.NewReader(r)
// Skip the first line.
_, _ = reader.ReadBytes('\n')
buff, err := reader.ReadBytes('\n')
if err != nil {
panic(err)
}
if err := cmd.Wait(); err != nil {
return MetaMapping{}, err
}
var d MetaMapping
if err := json.NewDecoder(bytes.NewReader(buff)).Decode(&d); err != nil {
return MetaMapping{}, err
}
return d, nil
}
// PreferredCandidates extracts only the MetaMap preferred candidates.
func (m MetaMap) PreferredCandidates(text string) ([]MappingCandidate, error) {
mapping, err := m.Map(text)
if err != nil {
return nil, err
}
var candidates []MappingCandidate
for _, d := range mapping.AllDocuments {
for _, u := range d.Document.Utterances {
for _, p := range u.Phrases {
for _, m := range p.Mappings {
for _, c := range m.MappingCandidates {
candidates = append(candidates, c)
}
}
}
}
}
return candidates, nil
}