/
find.go
176 lines (155 loc) · 5.16 KB
/
find.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
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
// Copyright © 2019 Dmitry Mozzherin <dmozzherin@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package cmd
import (
"fmt"
"io/ioutil"
"log"
"os"
"strings"
"github.com/gnames/gnfinder"
"github.com/gnames/gnfinder/dict"
"github.com/gnames/gnfinder/lang"
"github.com/gnames/gnfinder/verifier"
"github.com/spf13/cobra"
)
// findCmd represents the find command
var findCmd = &cobra.Command{
Use: "find text_with_names.txt",
Short: "Finds scientific names in UTF-8-encoded plain texts",
Long: `
Name finding happens in two stages. First we apply heuristic rules, and
then, unless opted out, Bayesian algorithms to find scientific names.
Optionally, gnfinder verifies found names against gnindex database located
at https://index.globalnames.org. Found names and metadata are returned in
JSON format to the standard output.
Optional verification process returns 'the best' result for the match. If
specific datasets are important for verification, they can be set with '-s'
'--sources' flag using IDs from https://index.globalnames.org/datasource.
The default sources are 'Catalogue of life' (ID 1), GBIF (ID 11), and Open
Tree of Life (ID 179).`,
Run: func(cmd *cobra.Command, args []string) {
var data []byte
sources := sources(cmd)
lang, err := cmd.Flags().GetString("lang")
if err != nil {
log.Println(err)
os.Exit(1)
}
noBayes, err := cmd.Flags().GetBool("no-bayes")
if err != nil {
log.Println(err)
os.Exit(1)
}
verify, err :=
cmd.Flags().GetBool("check-names")
if err != nil {
log.Println(err)
os.Exit(1)
}
switch len(args) {
case 0:
if !checkStdin() {
cmd.Help()
os.Exit(0)
}
data, err = ioutil.ReadAll(os.Stdin)
if err != nil {
log.Println(err)
}
case 1:
data, err = ioutil.ReadFile(args[0])
if err != nil {
log.Println(err)
os.Exit(1)
}
default:
cmd.Help()
os.Exit(0)
}
findNames(data, lang, noBayes, verify, sources)
},
}
func init() {
rootCmd.AddCommand(findCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// findCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// findCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
findCmd.Flags().BoolP("no-bayes", "n", false, "do not run Bayes algorithms.")
findCmd.Flags().BoolP("check-names", "c", false, "verify found name-strings.")
findCmd.Flags().StringP("lang", "l", "", "text's language or 'detect' for automatic detection.")
findCmd.Flags().IntSliceP("sources", "s", []int{1, 11, 179},
"IDs of data sources used in verification.")
}
func findNames(data []byte, langString string, noBayes bool,
verify bool, sources []int) {
var opts []gnfinder.Option
opts = append(opts, gnfinder.OptDict(dict.LoadDictionary()))
if langString == "detect" {
opts = append(opts, gnfinder.OptDetectLanguage(true))
} else if langString != "" {
l, err := lang.NewLanguage(langString)
if err != nil {
log.Printf("Error: %s\n", err)
log.Printf("Supported language codes: %s.\n", langsToString())
log.Printf("To detect language automatically use '-l detect'.")
os.Exit(1)
}
opts = append(opts, gnfinder.OptLanguage(l))
}
if verify {
opts = append(opts, gnfinder.OptVerify(verifier.OptSources(sources)))
}
opts = append(opts, gnfinder.OptBayes(!noBayes))
gnf := gnfinder.NewGNfinder(opts...)
res := gnf.FindNames(data)
if gnf.Verifier != nil {
verifiedNames := gnf.Verifier.Run(res.UniqueNameStrings())
res.MergeVerification(verifiedNames)
}
fmt.Println(string(res.ToJSON()))
}
func langsToString() string {
langs := lang.SupportedLanguages()
res := make([]string, len(langs))
for i, v := range langs {
res[i] = v.String()
}
return strings.Join(res, ", ")
}
func checkStdin() bool {
stdInFile := os.Stdin
stat, err := stdInFile.Stat()
if err != nil {
log.Panic(err)
}
return (stat.Mode() & os.ModeCharDevice) == 0
}
func sources(cmd *cobra.Command) []int {
res, err := cmd.Flags().GetIntSlice("sources")
if err != nil {
log.Panic(err)
}
return res
}