-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathegress.go
90 lines (80 loc) · 1.7 KB
/
egress.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
package main
import (
"fmt"
"log"
"os"
"sort"
"github.com/d4l3k/docconv"
"github.com/ubccsss/exams/examdb"
"github.com/urfave/cli"
)
func setupEgressCommands() cli.Command {
return cli.Command{
Name: "egress",
Aliases: []string{"e"},
Subcommands: []cli.Command{
{
Name: "ml",
Usage: "export data into a format that tensorflow can read",
Action: exportToML,
},
},
}
}
func exportToML(c *cli.Context) error {
// Map each label to be 1-n, 0 represents invalid label.
isLabel := map[string]int{}
for i, l := range examdb.ExamLabels {
isLabel[l] = i + 1
}
for _, f := range db.ProcessedFiles() {
class, ok := isLabel[f.Name]
if !ok {
continue
}
if err := convertAndSaveFileAsML(f, class); err != nil {
return err
}
}
return nil
}
func convertAndSaveFileAsML(f *examdb.File, class int) error {
log.Printf("Egressing %s", f)
in, err := f.Reader()
if err != nil {
return err
}
defer in.Close()
txt, meta, err := docconv.ConvertPDF(in)
if err != nil {
return err
}
out, err := os.OpenFile(fmt.Sprintf("ml/data/%s-%d.txt", f.Hash, class), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
return err
}
defer out.Close()
if _, err := out.WriteString(f.Source); err != nil {
return err
}
if _, err := out.WriteString("\n"); err != nil {
return err
}
var metalines []string
for k, v := range meta {
metalines = append(metalines, fmt.Sprintf("%s: %s", k, v))
}
sort.Strings(metalines)
for _, line := range metalines {
if _, err := out.WriteString(line); err != nil {
return err
}
if _, err := out.WriteString("\n"); err != nil {
return err
}
}
if _, err := out.WriteString(txt); err != nil {
return err
}
return nil
}