-
Notifications
You must be signed in to change notification settings - Fork 0
/
alto.go
1490 lines (1381 loc) · 32.8 KB
/
alto.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
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
// TODO: documentatie
// TODO: code opschonen, documenteren, opsplitsen over bestanden
/*
#cgo LDFLAGS: -lxqilla -lxerces-c
#include <stdlib.h>
#include "alto.h"
*/
import "C"
import (
"archive/zip"
"bufio"
"bytes"
"encoding/xml"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"sort"
//"runtime"
"strings"
"unsafe"
"github.com/jbowtie/gokogiri"
"github.com/jbowtie/gokogiri/xpath"
"github.com/pebbe/compactcorpus"
"github.com/pebbe/dbxml"
"github.com/pebbe/util"
"github.com/rug-compling/alpinods"
"github.com/rug-compling/alud/v2"
"github.com/wamuir/go-xslt"
)
type Item struct {
arch string
name string
oriname string
data string
match []string
skipfilter bool // als het eerste XPath-filter al is toegepast bij inlezen vanuit DACT, dan kan het eerste filter alles doorlaten
original bool // als dit een origineel XML-bestand is, dan hoeft er geen tijdelijk bestand gemaakt te worden voor XQilla
transformed bool
}
const (
DEVIDER = "((<<<))"
)
var (
chDone = make(chan bool)
compactSeen = make(map[string]bool)
tempdir = os.TempDir()
cDEVIDER = C.CString(DEVIDER)
cEMPTY = C.CString("")
cFILENAME = C.CString("filename")
verbose = true
warnings = true
overwrite = false
macrofile = ""
showExpansion = false
exprToExpand = ""
replace = false
markMatch = false
readStdin = false
version1 = false
version2xpath = false
version2xslt = false
variables = []*C.char{
C.CString("filename"),
cEMPTY,
C.CString("corpusname"),
cEMPTY,
}
xsltVariables = make([]xslt.Parameter, 0)
macros = make(map[string]string)
macroRE = regexp.MustCompile(`([a-zA-Z][_a-zA-Z0-9]*)\s*=\s*"""((?s:.*?))"""`)
macroKY = regexp.MustCompile(`%[a-zA-Z][_a-zA-Z0-9]*%`)
macroCOM = regexp.MustCompile(`(?m:^\s*#.*)`)
reSpace = regexp.MustCompile(`[ \t\r\n]+`)
x = util.CheckErr
)
func usage() {
major, minor, patch := dbxml.Version()
fmt.Printf(
`
Usage: %s (option | action | filename) ...
Options:
-e expression : show macro-expansion, and exit
-f : overwrite existing files
-i : read input filenames from stdin
-m filename : use this macrofile for xpath
(or use environment variable ALTO_MACROFILE)
-n : mark matching node
-o filename : output
-r : replace xml in existing dact file
-v name=value : set global variable (can be used multiple times)
-1 : use XPath version 1 for searching in DACT files
-2 : use XPath2 and XSLT2 (slow)
-2p : use XPath2 (slow)
-2s : use XSLT2 (slow)
-w : suppress warnings
Actions:
ds:ud : insert Universal Dependencies
ds:noud : remove Universal Dependencies
ds:extra : add extra attributes: is_np, is_vorfeld, is_nachfeld
ds:minimal : removes all but essential entities and attributes
fp:{expression} : filter by XPath {expression}
tq:{xqueryfile} : transform with XQuery {xqueryfile}
ts:{stylefile} : transform with XSLT {stylefile}
tt:{template} : transform with {template}
Tq:{xqueryfile} : like tq, match data as input
Ts:{stylefile} : like ts, match data as input
ac:item : item count
ac:line : line count
ac:node : count of cat, pos, postag, rel
ac:word : count of lemma, root, sense, word
ac:nw : combination of ac:node and ac:word
vt:{type} : save tree as image, type = dot, svg, png, eps, pdf
vm:{type} : save subtree as image
vu:{type} : save Universal Dependencies as image, type = svg, png, eps, pdf
vx:{type} : save Extended Universal Dependencies as image
Template placeholders:
%%%% %%
%%c corpusname
%%f filename
%%F if corpusname then corpusname::filename else filename
%%b file body
%%i id of matching node
%%j ids of all matching nodes
%%I sentence id
%%s sentence
%%S colored sentence
%%o comments
%%m match
%%M match as tree
%%w match words
%%l match lemmas
%%p match pts
%%P match postags
%%d metadata
%%u universal dependencies
\t tab
\n newline
Input filenames can be given as arguments, or/and
one name per line on stdin, using option -i
Examples:
%s *.xml -o output.zip
%s -o output.dact input.zip
find . -name '*.xml' | %s -o output.zip -i
Valid input filenames:
*.xml
*.dact (or *.dbxml)
*.data.dz (or *.index)
*.zip
directory name
an input filename can also be in the format corpusfile::xmlfile
Valid output filenames:
*.dact (or *.dbxml)
*.data.dz (or *.index)
*.zip
*.txt
directory name
Default output is stdout
%s uses DbXML version %d.%d.%d
`,
os.Args[0],
os.Args[0],
os.Args[0],
os.Args[0],
os.Args[0],
major, minor, patch)
}
func w(err error, msg ...interface{}) error {
if warnings {
return util.WarnErr(err, msg...)
}
return err
}
func main() {
if len(os.Args) == 1 && util.IsTerminal(os.Stdin) {
usage()
return
}
macrofile = os.Getenv("ALTO_MACROFILE")
outfile := ""
inputfiles := make([]string, 0)
actions := make([]string, 0)
for i := 1; i < len(os.Args); i++ {
arg := os.Args[i]
if strings.HasPrefix(arg, "-") {
switch arg {
case "-e":
i++
if i == len(os.Args) {
fmt.Fprintln(os.Stderr, "Missing expression for option -e")
return
}
showExpansion = true
exprToExpand = os.Args[i]
case "-f":
overwrite = true
case "-h":
usage()
return
case "-i":
readStdin = true
case "-m":
i++
if i == len(os.Args) {
fmt.Fprintln(os.Stderr, "Missing filename for option -m")
return
}
macrofile = os.Args[i]
case "-n":
markMatch = true
case "-o":
i++
if i == len(os.Args) {
fmt.Fprintln(os.Stderr, "Missing filename for option -o")
return
}
outfile = os.Args[i]
case "-r":
replace = true
case "-v":
i++
if i == len(os.Args) {
fmt.Fprintln(os.Stderr, "Missing variable for option -v")
return
}
a := strings.SplitN(os.Args[i], "=", 2)
if len(a) != 2 || a[0] == "" /* || a[1] == "" */ {
fmt.Fprintln(os.Stderr, "Invalid name=value for option -v:", os.Args[i])
return
}
variables = append(variables, C.CString(a[0]), C.CString(a[1]))
xsltVariables = append(xsltVariables, xslt.Parameter(xslt.StringParameter{Name: a[0], Value: a[1]}))
case "-1":
version1 = true
case "-2":
version2xpath = true
version2xslt = true
case "-2p":
version2xpath = true
case "-2x":
version2xslt = true
case "-w":
warnings = false
default:
fmt.Fprintln(os.Stderr, "Unknown option", arg)
return
}
} else if len(arg) > 2 && arg[2] == ':' {
actions = append(actions, arg)
} else {
inputfiles = append(inputfiles, arg)
}
}
if showExpansion {
expandMacros(exprToExpand)
return
}
if replace {
if !(strings.HasSuffix(outfile, ".dact") || strings.HasSuffix(outfile, ".dbxml")) {
fmt.Fprintln(os.Stderr, "Option -r only valid for output to dact")
return
}
}
if readStdin {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
inputfiles = append(inputfiles, scanner.Text())
}
x(scanner.Err())
}
if len(inputfiles) == 0 {
fmt.Fprintln(os.Stderr, "Missing input file(s)")
return
}
firstFilter := ""
chStart := make(chan Item, 100)
chIn := chStart
for i, action := range actions {
act := action[:2]
arg := action[3:]
if action == "ds:ud" {
chOut := make(chan Item, 100)
go doUD(chIn, chOut)
chIn = chOut
} else if action == "ds:noud" {
chOut := make(chan Item, 100)
go undoUD(chIn, chOut)
chIn = chOut
} else if action == "ds:extra" {
chOut := make(chan Item, 100)
go doExtra(chIn, chOut)
chIn = chOut
} else if action == "ds:minimal" {
chOut := make(chan Item, 100)
go doMinimal(chIn, chOut)
chIn = chOut
} else if act == "fp" {
arg = expandMacros(arg)
if i == 0 && !version1 {
firstFilter = arg
}
chOut := make(chan Item, 100)
if version2xpath {
go filterXpath2(chIn, chOut, arg)
} else {
go filterXpath(chIn, chOut, arg)
}
chIn = chOut
} else if act == "tq" || act == "ts" || act == "Tq" || act == "Ts" {
var lang C.Language
switch act {
case "tq", "Tq":
lang = C.langXQUERY
case "ts", "Ts":
lang = C.langXSLT
}
b, err := os.ReadFile(arg)
x(err)
style := expandMacros(string(b))
chOut := make(chan Item, 100)
if act[1] == 's' && !version2xslt {
go transformLibXSLT(chIn, chOut, act[0] == 'T', style)
} else {
go transformStylesheet(chIn, chOut, lang, act[0] == 'T', style)
}
chIn = chOut
} else if act == "tt" {
chOut := make(chan Item, 100)
go transformTemplate(chIn, chOut, arg)
chIn = chOut
} else if act == "ac" {
chOut := make(chan Item, 100)
if arg == "item" || arg == "line" {
go aggregateCount(chIn, chOut, arg == "line")
} else if arg == "node" || arg == "word" || arg == "nw" {
go aggregateAttribs(chIn, chOut, arg == "node" || arg == "nw", arg == "word" || arg == "nw")
} else {
fmt.Fprintf(os.Stderr, "Unknown action %q\n", action)
return
}
chIn = chOut
} else if act == "vt" || act == "vm" {
if arg != "dot" && arg != "svg" && arg != "png" && arg != "eps" && arg != "pdf" {
fmt.Fprintf(os.Stderr, "Unknown visualisation %q\n", action)
return
}
chOut := make(chan Item, 100)
go vizTree(chIn, chOut, act == "vm", arg)
chIn = chOut
} else if act == "vu" || act == "vx" {
if arg != "svg" && arg != "png" && arg != "eps" && arg != "pdf" {
fmt.Fprintf(os.Stderr, "Unknown visualisation %q\n", action)
return
}
chOut := make(chan Item, 100)
go vizUD(chIn, chOut, act == "vx", arg)
chIn = chOut
} else {
fmt.Fprintf(os.Stderr, "Unknown action %q\n", action)
return
}
}
if strings.HasSuffix(outfile, ".data.dz") || strings.HasSuffix(outfile, ".index") {
go writeCompact(chIn, outfile)
} else if strings.HasSuffix(outfile, ".dbxml") || strings.HasSuffix(outfile, ".dact") {
go writeDact(chIn, outfile)
} else if strings.HasSuffix(outfile, ".zip") {
go writeZip(chIn, outfile)
} else if strings.HasSuffix(outfile, ".txt") {
go writeTxt(chIn, outfile)
} else if outfile == "" {
verbose = false
go writeStdout(chIn)
} else {
go writeDir(chIn, outfile)
}
n := len(inputfiles)
for i, infile := range inputfiles {
var xmlfiles []string
a := strings.Split(infile, "::")
if len(a) > 1 {
infile = a[0]
xmlfiles = a[1:]
}
infile = filepath.Clean(infile)
if strings.HasSuffix(infile, ".data.dz") || strings.HasSuffix(infile, ".index") {
readCompact(chStart, infile, i+1, n, xmlfiles)
} else if strings.HasSuffix(infile, ".dbxml") || strings.HasSuffix(infile, ".dact") {
readDact(chStart, infile, i+1, n, firstFilter, xmlfiles)
} else if strings.HasSuffix(infile, ".zip") {
readZip(chStart, infile, i+1, n, xmlfiles)
} else if xmlfiles != nil {
fmt.Fprintf(os.Stderr, "Invalid corpus/file combination: %s::%s\n", infile, strings.Join(xmlfiles, "::"))
return
} else if strings.HasSuffix(infile, ".xml") {
readXml(chStart, infile, i+1, n)
} else {
readDir(chStart, infile, "", i+1, n, firstFilter)
}
}
close(chStart)
<-chDone
if verbose {
fmt.Fprintln(os.Stderr)
}
}
func aggregateAttribs(chIn <-chan Item, chOut chan<- Item, doNode, doWord bool) {
var cat, pos, postag, rel int
var lemma, root, sense, word int
cats := make(map[string]int)
poss := make(map[string]int)
postags := make(map[string]int)
rels := make(map[string]int)
lemmas := make(map[string]int)
roots := make(map[string]int)
senses := make(map[string]int)
words := make(map[string]int)
for item := range chIn {
for _, match := range item.match {
var node alpinods.Node
x(xml.Unmarshal([]byte(match), &node))
if doNode {
if node.Cat != "" {
if _, ok := cats[node.Cat]; !ok {
cats[node.Cat] = 0
}
cats[node.Cat] += 1
cat++
}
if node.Pos != "" {
if _, ok := poss[node.Pos]; !ok {
poss[node.Pos] = 0
}
poss[node.Pos] += 1
pos++
}
if node.Postag != "" {
if _, ok := postags[node.Postag]; !ok {
postags[node.Postag] = 0
}
postags[node.Postag] += 1
postag++
}
if node.Rel != "" {
if _, ok := rels[node.Rel]; !ok {
rels[node.Rel] = 0
}
rels[node.Rel] += 1
rel++
}
}
if doWord {
if node.Lemma != "" {
if _, ok := lemmas[node.Lemma]; !ok {
lemmas[node.Lemma] = 0
}
lemmas[node.Lemma] += 1
lemma++
}
if node.Root != "" {
if _, ok := roots[node.Root]; !ok {
roots[node.Root] = 0
}
roots[node.Root] += 1
root++
}
if node.Sense != "" {
if _, ok := senses[node.Sense]; !ok {
senses[node.Sense] = 0
}
senses[node.Sense] += 1
sense++
}
if node.Word != "" {
if _, ok := words[node.Word]; !ok {
words[node.Word] = 0
}
words[node.Word] += 1
word++
}
}
}
}
var buf bytes.Buffer
f := func(label string, sum int, count map[string]int) {
fmt.Fprintf(&buf, "%s:\n", label)
keys := make([]string, 0, len(count))
for key := range count {
keys = append(keys, key)
}
sort.Strings(keys)
fsum := float64(sum)
for _, key := range keys {
fmt.Fprintf(&buf, "%8d %8.4f %s\n", count[key], float64(count[key])/fsum, key)
}
}
if doNode {
f("cat", cat, cats)
f("pos", pos, poss)
f("postag", postag, postags)
f("rel", rel, rels)
}
if doWord {
f("lemma", lemma, lemmas)
f("root", root, roots)
f("sense", sense, senses)
f("word", word, words)
}
chOut <- Item{
name: "result",
data: buf.String(),
match: make([]string, 0),
}
close(chOut)
}
func aggregateCount(chIn <-chan Item, chOut chan<- Item, byline bool) {
var sum int
count := make(map[string]int)
for item := range chIn {
for _, m := range item.match {
m = strings.TrimSpace(m)
if byline {
for _, ml := range strings.Split(m, "\n") {
ml = strings.TrimSpace(ml)
if _, ok := count[ml]; !ok {
count[ml] = 0
}
count[ml]++
sum++
}
} else {
if _, ok := count[m]; !ok {
count[m] = 0
}
count[m]++
sum++
}
}
}
keys := make([]string, 0, len(count))
for key := range count {
keys = append(keys, key)
}
sort.Strings(keys)
lines := make([]string, len(keys))
fsum := float64(sum)
for i, key := range keys {
lines[i] = fmt.Sprintf("%8d %8.4f %s", count[key], float64(count[key])/fsum, key)
}
chOut <- Item{
name: "result",
data: strings.Join(lines, "\n"),
match: make([]string, 0),
}
close(chOut)
}
func doUD(chIn <-chan Item, chOut chan<- Item) {
for item := range chIn {
s, err := alud.UdAlpino([]byte(item.data), item.oriname, "")
if err != nil {
fmt.Fprintf(os.Stderr, "Error %s: %v\n", item.name, err)
}
if s != "" {
item.data = s
}
item.original = false
chOut <- item
}
close(chOut)
}
func undoUD(chIn <-chan Item, chOut chan<- Item) {
var f func(*alpinods.Node)
f = func(node *alpinods.Node) {
node.Ud = nil
if node.Node != nil {
for _, n := range node.Node {
f(n)
}
}
}
for item := range chIn {
var alpino alpinods.AlpinoDS
x(xml.Unmarshal([]byte(item.data), &alpino))
f(alpino.Node)
alpino.Root = nil
alpino.Conllu = nil
item.data = alpino.String()
item.original = false
chOut <- item
}
close(chOut)
}
func doExtra(chIn <-chan Item, chOut chan<- Item) {
for item := range chIn {
var alpino alpinods.AlpinoDS
x(xml.Unmarshal([]byte(item.data), &alpino))
alpino.Enhance(alpinods.Fall)
item.data = alpino.String()
item.original = false
chOut <- item
}
close(chOut)
}
func doMinimal(chIn <-chan Item, chOut chan<- Item) {
for item := range chIn {
var alpino alpinods.AlpinoDS
x(xml.Unmarshal([]byte(item.data), &alpino))
item.data = alpinods.Reduce(&alpino).String()
item.original = false
chOut <- item
}
close(chOut)
}
func filterXpath(chIn <-chan Item, chOut chan<- Item, xp string) {
var expr *xpath.Expression
xp = reSpace.ReplaceAllLiteralString(xp, " ")
for item := range chIn {
if item.skipfilter {
// eerste filter is toegepast bij lezen vanuit dbxml-bestand
item.skipfilter = false
chOut <- item
continue
}
if expr == nil {
expr = xpath.Compile(xp)
if expr == nil {
os.Exit(1)
}
}
doc, err := gokogiri.ParseXml([]byte(item.data))
x(err)
root := doc.Root()
matches, err := root.Search(expr)
x(err)
if len(matches) > 0 {
item.match = item.match[0:0]
for _, match := range matches {
item.match = append(item.match, match.String())
}
if markMatch {
var alpino alpinods.AlpinoDS
x(xml.Unmarshal([]byte(item.data), &alpino))
markMatchingNode(alpino.Node, item.match...)
item.data = alpino.String()
item.original = false
}
chOut <- item
}
doc.Free()
}
close(chOut)
}
func filterXpath2(chIn <-chan Item, chOut chan<- Item, xpath string) {
// runtime.LockOSThread()
cxpath := C.CString(xpath)
vars := make([]*C.char, 1)
for item := range chIn {
if item.skipfilter {
// eerste filter is toegepast bij lezen vanuit dbxml-bestand
item.skipfilter = false
chOut <- item
continue
}
var cs *C.char
var filename string
if item.original {
cs = C.CString(item.oriname)
} else {
fp, err := os.CreateTemp(tempdir, "mkcFXP")
x(err)
_, err = fp.WriteString(item.data)
x(err)
filename = fp.Name()
x(fp.Close())
cs = C.CString(filename)
}
result := C.xq_call(cs, cxpath, C.langXPATH, cDEVIDER, 0, &(vars[0]))
C.free(unsafe.Pointer(cs))
if !item.original {
os.Remove(filename)
}
if C.xq_error(result) != 0 {
x(fmt.Errorf("xqilla error"))
} else {
item.match = make([]string, 0)
for _, m := range strings.Split(C.GoString(C.xq_text(result)), DEVIDER) {
if len(m) > 0 {
item.match = append(item.match, m)
}
}
if len(item.match) > 0 {
if markMatch {
var alpino alpinods.AlpinoDS
x(xml.Unmarshal([]byte(item.data), &alpino))
markMatchingNode(alpino.Node, item.match...)
item.data = alpino.String()
item.original = false
}
chOut <- item
}
}
C.xq_free(result)
}
close(chOut)
}
func markMatchingNode(node *alpinods.Node, matches ...string) {
var f func(*alpinods.Node, int) bool
f = func(n *alpinods.Node, id int) bool {
if n.ID == id {
if n.Data == nil {
n.Data = make([]*alpinods.Data, 0)
}
n.Data = append(n.Data, &alpinods.Data{
Name: "match",
})
return true
}
if n.Node != nil {
for _, n2 := range n.Node {
if f(n2, id) {
return true
}
}
}
return false
}
for _, match := range matches {
var matchNode alpinods.Node
if xml.Unmarshal([]byte(match), &matchNode) == nil {
f(node, matchNode.ID)
}
}
}
func transformLibXSLT(chIn <-chan Item, chOut chan<- Item, useMatch bool, style string) {
xs, err := xslt.NewStylesheet([]byte(style))
x(err)
for item := range chIn {
matchdata := item.match
for i := 0; ; i++ {
if useMatch {
if i >= len(matchdata) {
break
}
} else if i > 0 {
break
}
if !item.transformed {
item.transformed = true
item.name = trimXML(item.name) + ".t"
}
params := []xslt.Parameter{
xslt.Parameter(xslt.StringParameter{Name: "filename", Value: item.oriname}),
xslt.Parameter(xslt.StringParameter{Name: "corpusname", Value: item.arch}),
}
params = append(params, xsltVariables...)
var result []byte
if useMatch {
result, err = xs.Transform([]byte(matchdata[i]), params...)
} else {
result, err = xs.Transform([]byte(item.data), params...)
}
x(err)
item.data = string(result)
item.match = []string{item.data}
if len(item.data) > 0 {
chOut <- item
}
}
}
close(chOut)
}
func transformStylesheet(chIn <-chan Item, chOut chan<- Item, lang C.Language, useMatch bool, style string) {
// runtime.LockOSThread()
cstyle := C.CString(style)
for item := range chIn {
matchdata := item.match
for i := 0; ; i++ {
if useMatch {
if i >= len(matchdata) {
break
}
} else if i > 0 {
break
}
variables[1] = C.CString(item.oriname)
variables[3] = C.CString(item.arch)
if !item.transformed {
item.transformed = true
item.name = trimXML(item.name) + ".t"
}
var cs *C.char
var filename string
if item.original && !useMatch {
cs = C.CString(item.oriname)
} else {
fp, err := os.CreateTemp(tempdir, "mkcTST")
x(err)
if useMatch {
_, err = fp.WriteString(matchdata[i])
} else {
_, err = fp.WriteString(item.data)
}
x(err)
filename = fp.Name()
x(fp.Close())
cs = C.CString(filename)
}
result := C.xq_call(cs, cstyle, lang, cEMPTY, C.int(len(variables)/2), &(variables[0]))
C.free(unsafe.Pointer(cs))
C.free(unsafe.Pointer(variables[1]))
C.free(unsafe.Pointer(variables[3]))
if useMatch {
item.original = false
os.Remove(filename)
} else {
if item.original {
item.original = false
} else {
os.Remove(filename)
}
}
if C.xq_error(result) == 0 {
item.data = C.GoString(C.xq_text(result))
item.match = []string{item.data}
if len(item.data) > 0 {
chOut <- item
}
}
C.xq_free(result)
}
}
close(chOut)
}
func writeCompact(chIn <-chan Item, outfile string) {
seen := make(map[string]bool)
outfile = strings.TrimSuffix(outfile, ".data.dz")
outfile = strings.TrimSuffix(outfile, ".index")
if overwrite {
os.Remove(outfile + ".data.dz")
os.Remove(outfile + ".index")
} else {
mustNotExist(outfile + ".data.dz")
mustNotExist(outfile + ".index")
}
corpus, err := compactcorpus.NewCorpus(outfile)
x(err)
for item := range chIn {
name := filepath.Base(item.name)
if seen[name] {
x(fmt.Errorf("Duplicate filename: %s", name))
}
seen[name] = true
x(corpus.WriteString(name, item.data))
}
x(corpus.Close())
close(chDone)
}
func writeDact(chIn <-chan Item, outfile string) {
// runtime.LockOSThread()
if overwrite {
os.Remove(outfile)
} else if !replace {
mustNotExist(outfile)
}
db, err := dbxml.OpenReadWrite(outfile)
x(err)
for item := range chIn {
x(db.PutXml(item.name, item.data, replace))
}
db.Close()
close(chDone)
}
func writeZip(chIn <-chan Item, outfile string) {
if !overwrite {
mustNotExist(outfile)
}
fp, err := os.Create(outfile)
x(err)
w := zip.NewWriter(fp)
for item := range chIn {
f, err := w.Create(item.name)
x(err)
_, err = f.Write([]byte(item.data))
x(err)
}
x(w.Close())
x(fp.Close())
close(chDone)
}
func writeTxt(chIn <-chan Item, outfile string) {
if !overwrite {
mustNotExist(outfile)
}
fp, err := os.Create(outfile)
x(err)
for item := range chIn {
_, err := fp.WriteString(item.data)
x(err)
if !strings.HasSuffix(item.data, "\n") {
_, err := fp.WriteString("\n")
x(err)
}
}
x(fp.Close())
close(chDone)
}
func writeStdout(chIn <-chan Item) {
for item := range chIn {
_, err := os.Stdout.WriteString(item.data)
x(err)