-
Notifications
You must be signed in to change notification settings - Fork 0
/
irgen-ng.go
277 lines (254 loc) · 6.75 KB
/
irgen-ng.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
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
package main
import (
"fmt"
"golang.org/x/net/html"
"io"
"regexp"
"strings"
"time"
"path/filepath"
"bytes"
"os"
"encoding/csv"
"flag"
"net/http"
"net/url"
"sort"
"github.com/gookit/color"
"github.com/k0kubun/pp"
"github.com/PuerkitoBio/goquery"
"github.com/yosssi/gohtml"
"github.com/rs/zerolog"
)
var (
CurrentDir string
ContentSelector = "body"
inFile *string
WantedTitleLen = 3
reCleanHTML = regexp.MustCompile(`^\s*(.*?)\s*$`)
Extractor ExtractorType
Article ArticleType
log = zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr}).With().Timestamp().Logger()
)
type ArticleType struct {
Name, Lang string
}
type NoteType struct {
QNode *goquery.Selection
ID, Title, Txt, Context string
Tags []string
hasContent bool
}
func main() {
log.Info().Msg("Started")
inFile = flag.String("i", CurrentDir + string(os.PathSeparator) + "article.html", "file path or URL of an HTML article\n")
flag.Parse()
Article.Name = filepath.Base((*inFile)[:len(*inFile) - len(filepath.Ext(*inFile))])
var outFile string
if pref.DestDir == "" {
outFile = strings.TrimSuffix(*inFile, filepath.Ext(*inFile)) + ".txt"
} else {
outFile = pref.DestDir + strings.TrimSuffix(filepath.Base(*inFile), filepath.Ext(*inFile)) + ".txt"
}
log.Debug().
Bool("AbsPath?", filepath.IsAbs(*inFile)).
Bool("canStat?", canStat(*inFile)).
Str("path||url", *inFile).
Msg("init")
var file []byte
var err error
if filepath.IsAbs(*inFile){
if !canStat(*inFile) {
log.Error().Msg("No input file specified or default file location unaccessible: " + *inFile)
os.Exit(1)
}
Extractor = local
file, err = os.ReadFile(*inFile)
check(err)
} else {
for _, extractor := range extractors {
if extractor.Validator.MatchString(*inFile) {
Extractor = extractor
if extractor.Validator.NumSubexp() > 0 {
Article.Lang = extractor.Validator.FindStringSubmatch(*inFile)[1]
}
if extractor.Validator.NumSubexp() > 1 {
Article.Name, _ = url.QueryUnescape(extractor.Validator.FindStringSubmatch(*inFile)[2])
Article.Name = strings.ReplaceAll(Article.Name, "_", " ")
}
outFile = fmt.Sprint(pref.DestDir, Extractor.Name, "–",Article.Name, ".txt")
break
}
}
}
log.Info().
Str("source", Extractor.Name).
Str("lang", Article.Lang).
Str("Out", outFile).
Msg("init")
if Extractor.Name != "local" {
resp, err := http.Get(*inFile)
check(err)
if resp.StatusCode != http.StatusOK {
log.Error().Str("Received response status", resp.Status).Msg("HTTP")
} else {
log.Info().Str("Received response status", resp.Status).Msg("HTTP")
}
file, err = io.ReadAll(resp.Body)
check(err)
}
launch := time.Now()
doc, err := goquery.NewDocumentFromReader(bytes.NewReader(file))
check(err)
Extractor.Clean(doc, Article.Lang)
n := doc.Find(Extractor.ContentSelector)
// drag the headings up until they are direct children of the content-containing tag
// this make things safe to monkey-patch with Cut()
n.Children().EachWithBreak(func(i int, s *goquery.Selection) bool {
h := s.Find("h1,h2,h3,h4,h5,h6")
if h.Nodes == nil {
return false
}
s.ReplaceWithSelection(h)
return true
})
Extractor.TakeImgAlong(n)
// this returns InnerHTML
content, err := n.Html()
check(err)
content = "<cutpattern>" + Cut(content) + "</cutpattern>"
doc, err = goquery.NewDocumentFromReader(strings.NewReader(content))
check(err)
Preprocess(doc)
var Notes []NoteType
doc.Find("cutpattern").Each(func(i int, s *goquery.Selection) {
node := s.Nodes[0]
if Text(node) == "" {
return
}
loc, ok := LocRegister[node]
if !ok {
fmt.Println("LOC NOT FOUND for", node.Data, stringCapLen(InnerHTML(node), 200))
}
TitleStack := loc.Stack()
if len(TitleStack) > 1 && Extractor.MustSkip(TitleStack) {
return
}
Note := NoteType {
QNode: s,
ID: fmt.Sprintf("%s–%s %s", Article.Name, loc.miniStr(), fmtTl(TitleStack, -1)),
Title: fmtTl(TitleStack, pref.MaxTitles),
Txt: InnerHTML(s.Nodes[0]),
}
Note.Context = Note.MkCxt(loc, TitleStack)
// keep this after MkCxt to be able to ez check for duplicate img
Note.Txt = gohtml.Format(Note.Txt)
Notes = append(Notes, Note)
})
csvout, err := os.OpenFile(outFile, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
check(err)
writer := csv.NewWriter(csvout)
writer.Comma = '\t'
defer csvout.Close()
defer writer.Flush()
for _, Note := range Notes {
_ = writer.Write([]string{Note.ID, Note.Title, Note.Txt, Note.Context})
}
log.Info().Msg(fmt.Sprint(len(Notes), " Notes in total"))
elapsed := time.Since(launch)
log.Info().Msg(fmt.Sprintf("\x1b[1;37;45mTOOK %s\x1b[0m\n", elapsed))
}
type RatingType struct {
sort.IntSlice
idx []ThumbnailType
}
func (Rating RatingType) Swap(i, j int) {
Rating.idx[i], Rating.idx[j] = Rating.idx[j], Rating.idx[i]
Rating.IntSlice.Swap(i, j)
}
func fmtTl(TitleStack []*html.Node, max int) (s string) {
added := 0
for _, n := range(TitleStack[1:]) {
if max < 0 {
s = "❱"+Text(n)+s
} else if added < max {
s = "<span class=heading>"+Text(n)+"</span><span class=del></span>"+s
added += 1
}
}
s = strings.TrimPrefix(s, "❱")
if s == "" {
s = "<span class=heading>"+Article.Name+"</span>"
}
return
}
func Text(n *html.Node) string {
s := goquery.Selection{Nodes: []*html.Node{n}}
return reCleanHTML.ReplaceAllString(s.Text(), `$1`)
}
var reInnerHTML = regexp.MustCompile(`(?s)^<.*?>(.*)</.*?>$`)
func InnerHTML(n *html.Node) (s string) {
s = RenderNode(n)
s = reInnerHTML.ReplaceAllString(s, `$1`)
return
}
func RenderNode(n *html.Node) string {
var buf bytes.Buffer
w := io.Writer(&buf)
html.Render(w, n)
return buf.String()
}
var reHeading = regexp.MustCompile("(?si)<h[0-9]+[^<]*?>(.*?)</h[0-9]+>")
func Cut(str string) string {
var done []string
for _, h := range reHeading.FindAllStringSubmatch(str, -1) {
outer := h[0]
inner := h[1]
// ensure only actual html pairs of tags get found
if reHeading.MatchString(inner) {
continue
}
// string of individual heading may occasionally be the same
// throughout the document, make sure to not ReplaceAll multiple time
if contains(done, outer) {
continue
}
str = strings.ReplaceAll(str, outer, "</cutpattern>" + outer + "<cutpattern>")
done = append(done, outer)
}
return str
}
func contains[T comparable](arr []T, i T) bool {
for _, a := range arr {
if a == i {
return true
}
}
return false
}
func stringCapLen(s string, max int) string{
trimmed := false
for len(s) > max {
s = s[:len(s)-1]
trimmed = true
}
if trimmed {
s += "…"
}
return s
}
func canStat(path string) bool {
if _, err := os.Stat(path); err != nil {
return false
}
return true
}
func check(e error) {
if e != nil {
panic(e)
}
}
func placeholder() {
color.Redln(" 𝒻*** 𝓎ℴ𝓊 𝒸ℴ𝓂𝓅𝒾𝓁ℯ𝓇")
pp.Println("𝓯*** 𝔂𝓸𝓾 𝓬𝓸𝓶𝓹𝓲𝓵𝓮𝓻")
}