-
Notifications
You must be signed in to change notification settings - Fork 0
/
translation_fetcher.go
192 lines (155 loc) · 5.4 KB
/
translation_fetcher.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package main
import (
"fmt"
"net/http"
"strings"
"regexp"
"github.com/PuerkitoBio/goquery"
"github.com/getsentry/sentry-go"
"golang.org/x/net/html"
)
const (
baseURLEstRus = "http://www.eki.ee/dict/evs/index.cgi?Q="
baseURLRusEst = "http://www.eki.ee/dict/ves/index.cgi?Q="
baseURLEstUkr = "http://www.eki.ee/dict/ukraina/index.cgi?Q="
cartSelector = ".tervikart"
articleUseCaseSelectorEst = ".m.x_m.m"
articleUseCaseSelectorRus = ".ms.leitud_id"
translationSelectorEstRus = ".x_x[lang=\"ru\"]"
exampleEstSelector = ".x_n[lang=\"et\"]"
exampleRusSelector = ".x_qn[lang=\"ru\"]"
grammarFormSelectorEst = ".mv.x_mv.mv[lang=\"et\"]"
articleUseCaseSelectorEstUkr = ".k_m.m"
translationSelectorEstUkr = ".k_x.x[lang=\"uk\"]"
grammarFormSelectorEstUkr = ".k_mv.mv[lang=\"et\"]"
)
var cleanupRegex, _ = regexp.Compile("[^\\p{L}]+")
func IsMatchingArticle(searchWord string, givenWord string) bool {
a := strings.Split(givenWord, " ")
var isMatch = false
for i := range a {
form := cleanupRegex.ReplaceAllString(a[i], "")
if form == searchWord {
isMatch = true
break
}
}
return isMatch
}
func extractTranslationsFromDoc(doc *goquery.Document, searchWord string, useCase string, translationSelector string, grammarFormSelector string) []string {
var translations []string
grammarForms := doc.Find(grammarFormSelector).Text()
// filter garbage
if !IsMatchingArticle(searchWord, useCase) && !IsMatchingArticle(searchWord, grammarForms) {
return translations
}
doc.Find(translationSelector).Each(func(i int, translation *goquery.Selection) {
translations = append(translations, translation.Text())
})
return translations
}
func GetSingleArticleWithDirection(searchWord string, node *html.Node, direction string) (string, bool) {
var articeUseCaseSelector string
var grammarFormSelector string
var translationSelector string
var useCase string
doc := goquery.NewDocumentFromNode(node)
// TODO: add constants for directions
if direction == "est-ukr" {
articeUseCaseSelector = articleUseCaseSelectorEstUkr
grammarFormSelector = grammarFormSelectorEstUkr
translationSelector = translationSelectorEstUkr
} else if direction == "est-rus" {
articeUseCaseSelector = articleUseCaseSelectorEst
grammarFormSelector = grammarFormSelectorEst
translationSelector = translationSelectorEstRus
} else if direction == "rus-est" {
articeUseCaseSelector = articleUseCaseSelectorRus
}
useCase = doc.Find(articeUseCaseSelector).Text()
if !IsMatchingArticle(searchWord, useCase) {
return "", false
}
if direction == "rus-est" {
text := doc.Text()
text = strings.Replace(text, ";", "\r\n", -1)
return text, false
}
grammarForms := doc.Find(grammarFormSelector).Text()
translations := extractTranslationsFromDoc(doc, searchWord, useCase, translationSelector, grammarFormSelector)
if grammarForms == "" {
return fmt.Sprintf("<b>%s</b>\r\n%s",
useCase,
strings.Join(translations, "\r\n"),
), false
}
return fmt.Sprintf("<b>%s</b><i> (%s) </i>\r\n%s",
useCase,
grammarForms,
strings.Join(translations, "\r\n"),
),
true
}
// ParseArticles extracts article from the HTML node doc
func ParseArticles(doc *goquery.Document, searchWord string, translationDirection string) []string {
var articles []string
// Check if the search word is found at all
foundArticlesInfo := doc.Find("P.inf").Text()
// TODO: define separate filter function
// TODO: check cases when found articles are not what we are looking for
if strings.Contains(foundArticlesInfo, "Küsitud kujul või valitud artikli osast otsitut ei leitud, kasutan laiendatud otsingut") {
return articles
}
doc.Find(cartSelector).Each(func(i int, page *goquery.Selection) {
for i := 0; i < len(page.Nodes); i++ {
article, isMainArticle := GetSingleArticleWithDirection(searchWord, page.Nodes[i], translationDirection)
if article == "" {
continue
}
if translationDirection == "est-ukr" {
// prepend ukrainian flag emoji
article = "🇺🇦 " + article
}
if isMainArticle {
articles = append([]string{article}, articles...) // Put main article to the first position
continue
}
articles = append(articles, article)
}
})
return articles
}
// GetArticles fetches HTML page and extract separate word-related articles
func GetArticles(searchWord string) []string {
// Request the HTML page.
var urls []string
var translationDirections []string
if isCyrillicScript(searchWord) {
urls = []string{baseURLRusEst}
translationDirections = []string{"rus-est"}
} else {
urls = []string{baseURLEstUkr, baseURLEstRus}
translationDirections = []string{"est-ukr", "est-rus"}
}
var articles []string
for i := 0; i < len(urls); i++ {
url := urls[i]
translationDirection := translationDirections[i]
res, err := http.Get(fmt.Sprintf("%s%s", url, searchWord))
captureErrorIfNotNull(err)
defer res.Body.Close()
if res.StatusCode != 200 {
sentry.CaptureException(fmt.Errorf("status code error: %d %s", res.StatusCode, res.Status))
}
// Load the HTML document
doc, err := goquery.NewDocumentFromReader(res.Body)
captureErrorIfNotNull(err)
articlesPerDirection := ParseArticles(doc, searchWord, translationDirection)
articles = append(articles, articlesPerDirection...)
}
return articles
}
func isCyrillicScript(searchWord string) bool {
var rxCyrillic = regexp.MustCompile("^[\u0400-\u04FF\u0500-\u052F]+$")
return rxCyrillic.MatchString(searchWord)
}