File: gabc.py

package info (click to toggle)
python-pandocfilters 1.5.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 376 kB
  • sloc: python: 802; makefile: 26
file content (218 lines) | stat: -rwxr-xr-x 7,043 bytes parent folder | download | duplicates (3)
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
#!/usr/bin/env python3
"""
Pandoc filter to convert code blocks with class "gabc" to LaTeX
\\gabcsnippet commands in LaTeX output, and to images in HTML output.
Assumes Ghostscript, LuaLaTeX, [Gregorio](http://gregorio-project.github.io/)
and a reasonable selection of LaTeX packages are installed.
"""

import os
from sys import getfilesystemencoding, stderr
from subprocess import Popen, call, PIPE
from itertools import chain
from glob import iglob
from hashlib import sha1
from pandocfilters import toJSONFilter, RawBlock, RawInline, Para, Image


STDERR = stderr
IMAGEDIR = "tmp_gabc"
LATEX_DOC = """\\documentclass{article}
\\usepackage{libertine}
\\usepackage[autocompile,allowdeprecated=false]{gregoriotex}
\\catcode`\\℣=\\active \\def ℣#1{{\\Vbar\\hspace{-.25ex}#1}}
\\catcode`\\℟=\\active \\def ℟#1{{\\Rbar\\hspace{-.25ex}#1}}
\\catcode`\\†=\\active \\def †{{\\GreDagger}}
\\catcode`\\✠=\\active \\def ✠{{\\grecross}}
\\pagestyle{empty}
\\begin{document}
%s
\\end{document}
"""


def sha(code):
    """Returns sha1 hash of the code"""
    return sha1(code.encode(getfilesystemencoding())).hexdigest()


def latex(code):
    """LaTeX inline"""
    return RawInline('latex', code)


def latexblock(code):
    """LaTeX block"""
    return RawBlock('latex', code)


def htmlblock(code):
    """Html block"""
    return RawBlock('html', code)


def latexsnippet(code, kvs, staffsize=17, initiallines=1):
    """Take in account key/values"""
    snippet = ''
    staffsize = int(kvs['staffsize']) if 'staffsize' in kvs \
        else staffsize
    initiallines = int(kvs['initiallines']) if 'initiallines' in kvs \
        else initiallines
    annotationsize = .5 * staffsize
    if 'mode' in kvs:
        snippet = (
            "\\greannotation{{\\fontsize{%s}{%s}\\selectfont{}%s}}\n" %
            (annotationsize, annotationsize, kvs['mode'])
        ) + snippet
    if 'annotation' in kvs:
        snippet = (
            "\\grechangedim{annotationseparation}{%s mm}{fixed}\n"
            "\\greannotation{{\\fontsize{%s}{%s}\\selectfont{}%s}}\n" %
            (staffsize / 60, annotationsize, annotationsize, kvs['annotation'])
        ) + snippet
    snippet = (
        "\\gresetinitiallines{%s}\n" % initiallines +
        "\\grechangestaffsize{%s}\n" % staffsize +
        "\\grechangestyle{initial}{\\fontsize{%s}{%s}\\selectfont{}}" %
        (2.5 * staffsize, 2.5 * staffsize)
    ) + snippet
    snippet = "\\setlength{\\parskip}{0pt}\n" + snippet + code
    return snippet


def latex2png(snippet, outfile):
    """Compiles a LaTeX snippet to png"""
    pngimage = os.path.join(IMAGEDIR, outfile + '.png')
    texdocument = os.path.join(IMAGEDIR, 'tmp.tex')
    with open(texdocument, 'w') as doc:
        doc.write(LATEX_DOC % (snippet))
    environment = os.environ
    environment['shell_escape_commands'] = \
        "bibtex,bibtex8,kpsewhich,makeindex,mpost,repstopdf," + \
        ','.join(
            os.path.basename(n) for n in chain.from_iterable(
                iglob(os.path.join(chemin, 'gregorio*'))
                for chemin in os.environ["PATH"].split(os.pathsep)
            )
        )
    proc = Popen(
        ["lualatex", '-output-directory=' + IMAGEDIR, texdocument],
        stdin=PIPE,
        stdout=STDERR,
        env=environment
    )
    proc.communicate()
    proc.stdin.close()
    call(["pdfcrop", os.path.join(IMAGEDIR, "tmp.pdf")], stdout=STDERR)
    call(
        [
            "gs",
            "-sDEVICE=pngalpha",
            "-r144",
            "-sOutputFile=" + pngimage,
            os.path.join(IMAGEDIR, "tmp-crop.pdf"),
        ],
        stdout=STDERR,
    )


def png(contents, latex_command):
    """Creates a png if needed."""
    outfile = sha(contents + latex_command)
    src = os.path.join(IMAGEDIR, outfile + '.png')
    if not os.path.isfile(src):
        try:
            os.mkdir(IMAGEDIR)
            stderr.write('Created directory ' + IMAGEDIR + '\n')
        except OSError:
            pass
        latex2png(latex_command + "{" + contents + "}", outfile)
        stderr.write('Created image ' + src + '\n')
    return src


def properties(meta):
    try:
        staffsize = int(
            meta['music']['c']['gregorio']['c']['staffsize']['c']
        )
    except (KeyError, TypeError):
        staffsize = 17
    try:
        initiallines = int(
            meta['music']['c']['gregorio']['c']['initiallines']['c']
        )
    except (KeyError, TypeError):
        initiallines = 1
    return staffsize, initiallines


def gabc(key, value, fmt, meta):                   # pylint:disable=I0011,W0613
    """Handle gabc file inclusion and gabc code block."""
    if key == 'Code':
        [[ident, classes, kvs], contents] = value  # pylint:disable=I0011,W0612
        kvs = {key: value for key, value in kvs}
        if "gabc" in classes:
            staffsize, initiallines = properties(meta)
            if fmt == "latex":
                if ident == "":
                    label = ""
                else:
                    label = '\\label{' + ident + '}'
                return latex(
                    "\n\\smallskip\n{%\n" +
                    latexsnippet(
                        '\\gregorioscore{' + contents + '}',
                        kvs, staffsize, initiallines
                    ) +
                    "%\n}" +
                    label
                )
            else:
                infile = contents + (
                    '.gabc' if '.gabc' not in contents else ''
                )
                with open(infile, 'r') as doc:
                    code = doc.read().split('%%\n')[1]
                return [Image(['', [], []], [], [
                    png(
                        contents,
                        latexsnippet(
                            '\\gregorioscore', kvs, staffsize, initiallines
                        )
                    ),
                    ""
                ])]
    elif key == 'CodeBlock':
        [[ident, classes, kvs], contents] = value
        kvs = {key: value for key, value in kvs}
        if "gabc" in classes:
            staffsize, initiallines = properties(meta)
            if fmt == "latex":
                if ident == "":
                    label = ""
                else:
                    label = '\\label{' + ident + '}'
                return [latexblock(
                    "\n\\smallskip\n{%\n" +
                    latexsnippet(
                        '\\gabcsnippet{' + contents + '}',
                        kvs, staffsize, initiallines
                    ) +
                    "%\n}" +
                    label
                    )]
            else:
                return Para([Image(['', [], []], [], [
                    png(
                        contents,
                        latexsnippet(
                            '\\gabcsnippet', kvs, staffsize, initiallines
                        )
                    ),
                    ""
                ])])


if __name__ == "__main__":
    toJSONFilter(gabc)