Skip to content

Instantly share code, notes, and snippets.

@cblgh
Last active June 4, 2021 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cblgh/55b3a076584d4d167f275b0bd647c061 to your computer and use it in GitHub Desktop.
Save cblgh/55b3a076584d4d167f275b0bd647c061 to your computer and use it in GitHub Desktop.
convert a file containing prompts with markdown to a tsv file with cards containing html (easy to import via anki)
package main
import (
"github.com/gomarkdown/markdown"
"strings"
"path/filepath"
"time"
"fmt"
"io"
"os"
"log"
)
func check (err error) {
if err != nil {
log.Fatalln(err)
}
}
func markup (s string) string {
return strings.ReplaceAll(string(markdown.ToHTML([]byte(s), nil, nil)), "\n", "<br>")
}
func main () {
if len(os.Args) < 2 {
fmt.Println("usage: prompts <path/to/prompts.md>\noutputs <path/to/prompts-yyyy-mm-dd-hhmm.tsv>")
os.Exit(0)
}
filename := os.Args[1]
file, err := os.Open(filename)
check(err)
contents, err := io.ReadAll(file)
check(err)
// create cards using blanklines as delimiters; handle windows delimiters
cards := strings.Split(strings.ReplaceAll(string(contents), "\r\n", "\n"), "\n\n")
// if file started with a title, remove that "card"
if strings.HasPrefix(cards[0], "#") { cards = cards[1:] }
processed := make([]string, 0, len(cards))
for _, card := range cards {
// get the front & back fields of the card by using \n as the field delimiter
fields := strings.Split(strings.TrimSpace(card), "\n")
fmt.Printf("%q\n", fields)
// treat first field as special (question), remaining fields should be collapsed into the same string
question := markup(fields[0])
answer := markup(strings.Join(fields[1:], "\n"))
processed = append(processed, strings.Join([]string{question, answer}, "\t"))
}
// output the processed prompt data to a file we can import in anki
date := time.Now().Format("2006-01-02")
outpath := filepath.Join(filepath.Dir(filename), fmt.Sprintf("prompts-%s.tsv", date))
fmt.Println(outpath)
err = os.WriteFile(outpath, []byte(strings.Join(processed, "\n")), 0644)
check(err)
}
@cblgh
Copy link
Author

cblgh commented Jun 4, 2021

example card formatting:

In golang, what package do you use to create files?
`os`

In golang, what is the signature for creating a file?
`os.Create(string, []byte, uint) error`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment