Last active
June 4, 2021 18:29
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
example card formatting: