File size: 2,271 Bytes
b69de73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Lilylet output post-processing (vendored from deep-starry, torch-free).

Cleans raw generated Lilylet text for readability:
  - move each `[r:x/y]` stream marker from the measure head to a trailing
    comment `% r:x/y` at the measure end (the line ending in `|`),
  - insert a blank line after the metadata block,
  - insert a blank line at every measure boundary.

Because a blank line is inserted at each measure boundary, the postprocessed
text is naturally segmented measure-by-measure — which is what the editor pane
displays as generation streams in.

Source: deep-starry/starry/lilylet/patchyGenerator.py (postprocess / _STREAM_RE).
"""

import re


# matches a stream marker like `[r:12/34]` (and a trailing partial `[r:12/` at EOF);
# group 1 captures the `x/y` payload.
_STREAM_RE = re.compile(r'\[r:(\d+/\d*)\]?')


def postprocess (text: str) -> str:
	lines = [ln.rstrip() for ln in text.split('\n')]
	out = []
	meta_done = False
	pending = None		# marker payload waiting to be attached at the measure end

	for ln in lines:
		# extract the stream marker (sits at the measure head); remember its
		# payload and strip the marker text from the line.
		m = _STREAM_RE.search(ln)
		if m:
			# a still-pending marker means the previous measure had no barline
			# (e.g. truncated); keep it as a standalone comment so it isn't lost.
			if pending is not None:
				out.append('% r:' + pending)
			pending = m.group(1)
			ln = _STREAM_RE.sub('', ln).rstrip()

		is_meta = ln.startswith('[') and ln.endswith(']')
		# blank line once the metadata block ends and the body begins
		if not meta_done and out and not is_meta and ln:
			out.append('')
			meta_done = True

		is_measure_end = ln.endswith('|')
		if is_measure_end and pending is not None:
			ln = ln + ' % r:' + pending
			pending = None

		out.append(ln)

		# blank line after a measure-ending line
		if meta_done and is_measure_end:
			out.append('')

	# any marker left pending at EOF -> attach as a trailing comment
	if pending is not None:
		out.append('% r:' + pending)

	# collapse runs of blank lines, trim leading/trailing blanks
	cleaned = []
	for ln in out:
		if ln == '' and (not cleaned or cleaned[-1] == ''):
			continue
		cleaned.append(ln)
	return '\n'.join(cleaned).strip('\n') + '\n'