ansibangla 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ansibangla/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """ansibangla: convert Bengali text, PDFs and Word files set in the SutonnyMJ (Bijoy) font to Unicode.
2
+
3
+ from ansibangla import convert_file, convert_pdf, convert_text
4
+ convert_file('story.docx', 'out/') # writes a Unicode .docx
5
+ convert_pdf('book.pdf', 'out/') # writes a Unicode .pdf
6
+ convert_pdf('book.pdf', 'out/', formats=('docx', 'epub', 'md')) # several at once
7
+ convert_text('wbwØ©avq') # -> 'নির্দ্বিধায়'
8
+ """
9
+ from .api import DEFAULT_FORMATS, FORMATS, convert_docx, convert_file, convert_pdf, convert_text
10
+ from .bijoy import convert as bijoy_convert
11
+
12
+ __all__ = ['convert_file', 'convert_pdf', 'convert_docx', 'convert_text', 'bijoy_convert', 'FORMATS', 'DEFAULT_FORMATS']
13
+ __version__ = '1.0.0'
ansibangla/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
ansibangla/_common.py ADDED
@@ -0,0 +1,230 @@
1
+ """Shared reading of SutonnyMJ PDFs: text lines, pictures and the measured page layout."""
2
+ import os
3
+ from collections import Counter
4
+
5
+ import pymupdf as fitz
6
+
7
+ from .bijoy import convert as bijoy_convert
8
+
9
+
10
+ def is_mj(font):
11
+ """True for spans set in the SutonnyMJ (Bijoy) font."""
12
+ return 'MJ' in font
13
+
14
+
15
+ def span_text(span):
16
+ """Span text as Unicode Bengali (SutonnyMJ spans) or unchanged (other fonts).
17
+ A | in another font is a danda typed after an English word, as in "(DNA)|"."""
18
+ if is_mj(span['font']):
19
+ return bijoy_convert(span['text'])
20
+ return span['text'].replace('|', '।')
21
+
22
+
23
+ _PRE_KEYS = None
24
+
25
+
26
+ def _needs_join(prev, nxt):
27
+ """True when two spans of one line must be shaped as one piece of text: the next span
28
+ starts with a vowel sign, chandrabindu or halant, or the previous one ends with a
29
+ pre-base vowel sign (their Unicode order only works inside one run)."""
30
+ if not (is_mj(prev['font']) and is_mj(nxt['font'])):
31
+ return False
32
+ first = bijoy_convert(nxt['text'][:1]) if nxt['text'] else ''
33
+ last = bijoy_convert(prev['text'][-1:]) if prev['text'] else ''
34
+ signs = '\u09be\u09bf\u09c0\u09c1\u09c2\u09c3\u09c7\u09c8\u09cb\u09cc\u09d7\u0981\u0982\u0983\u09cd'
35
+ return (first[:1] in signs and first[:1] != '') or (last[-1:] in '\u09bf\u09c7\u09c8' and last != '')
36
+
37
+
38
+ def _merge_spans(spans):
39
+ """Join spans that must shape together; the joined span keeps the first span's font."""
40
+ out = []
41
+ for sp in spans:
42
+ if out and _needs_join(out[-1], sp):
43
+ out[-1] = dict(out[-1], text=out[-1]['text'] + sp['text'])
44
+ else:
45
+ out.append(dict(sp))
46
+ return out
47
+
48
+
49
+ def read_lines(page):
50
+ """Text lines of a page, top to bottom, with their spans.
51
+
52
+ PyMuPDF splits a justified line with wide word gaps into several fragments on one
53
+ baseline; they are merged back into one line here."""
54
+ raw = []
55
+ for block in page.get_text('dict')['blocks']:
56
+ for line in block.get('lines', []):
57
+ spans = [s for s in line['spans'] if s['text'].strip() or s['text']]
58
+ if not any(s['text'].strip() for s in spans):
59
+ continue
60
+ raw.append(dict(
61
+ base=max(s['origin'][1] for s in spans if s['text'].strip()),
62
+ x0=line['bbox'][0], x1=line['bbox'][2], spans=spans))
63
+ raw.sort(key=lambda d: (round(d['base'] / 2.0), d['x0']))
64
+ merged = []
65
+ for r in raw:
66
+ prev = merged[-1] if merged else None
67
+ if prev and abs(prev['base'] - r['base']) < 1.5 and r['x0'] >= prev['x1'] - 1:
68
+ gap = dict(prev['spans'][-1], text=' ')
69
+ prev['spans'] = prev['spans'] + [gap] + r['spans']
70
+ prev['x1'] = max(prev['x1'], r['x1'])
71
+ else:
72
+ merged.append(dict(r))
73
+ lines = []
74
+ for r in merged:
75
+ spans = _merge_spans(r['spans'])
76
+ shown = [s for s in spans if s['text'].strip()]
77
+ mj_sizes = [s['size'] for s in shown if is_mj(s['font'])]
78
+ lines.append(dict(
79
+ x0=r['x0'], x1=r['x1'], base=r['base'],
80
+ size=max(s['size'] for s in shown),
81
+ mj_size=max(mj_sizes) if mj_sizes else 0.0,
82
+ spans=spans))
83
+ lines.sort(key=lambda d: d['base'])
84
+ return lines
85
+
86
+
87
+ class Layout:
88
+ """Page geometry and body-text metrics measured from the whole document."""
89
+
90
+ def __init__(self, doc, scale=0.9):
91
+ self.scale = scale # font-size factor for the Unicode PDF
92
+ self.page_w = doc[0].rect.width
93
+ self.page_h = doc[0].rect.height
94
+
95
+ self.page_bg = _page_colour(doc)
96
+ all_lines = [l for page in doc for l in read_lines(page)]
97
+ self.foot_y = self._footer_line(all_lines)
98
+ mj_lines = [l for l in all_lines if any(is_mj(s['font']) for s in l['spans'])]
99
+ # Left edge of the body column: the most common left edge of SutonnyMJ lines
100
+ self.body_l = Counter(round(l['x0']) for l in mj_lines).most_common(1)[0][0]
101
+ at_margin = [l for l in mj_lines if abs(l['x0'] - self.body_l) < 3]
102
+ # Body size: the most common size at the left margin
103
+ self.body_size = Counter(round(l['mj_size'], 2) for l in at_margin).most_common(1)[0][0]
104
+ # Right edge of justified lines: the most common right edge of body lines
105
+ wide = [l for l in at_margin if abs(l['mj_size'] - self.body_size) < .1 and l['x1'] > self.body_l + 150]
106
+ self.body_r = Counter(round(l['x1']) for l in wide).most_common(1)[0][0]
107
+
108
+ def _footer_line(self, lines):
109
+ """Baseline below which only page numbers sit.
110
+
111
+ Page numbers are lines of digits alone in the bottom quarter of the page; the
112
+ footer zone starts just above the highest common page-number baseline. Body text
113
+ can run close to it, so a fixed share of the page height is not safe. Without
114
+ page numbers nothing is treated as footer."""
115
+ bases = []
116
+ for line in lines:
117
+ if line['base'] < self.page_h * 0.75:
118
+ continue
119
+ text = ''.join(span_text(s) for s in line['spans']).strip()
120
+ if text and all(ch in '০১২৩৪৫৬৭৮৯0123456789' for ch in text):
121
+ bases.append((round(line['base']), line['size']))
122
+ if not bases:
123
+ return self.page_h
124
+ counts = Counter(b for b, _ in bases)
125
+ common = [b for b, n in counts.items() if n >= max(2, 0.2 * len(bases))] or [counts.most_common(1)[0][0]]
126
+ top = min(common)
127
+ size = max(s for b, s in bases if b == top)
128
+ return top - 0.8 * size
129
+
130
+ def is_body(self, line):
131
+ """Running text: not bold, at the left margin, up to body size (notes are smaller)."""
132
+ return (9.0 < line['mj_size'] <= self.body_size + 0.2
133
+ and line['x0'] < self.body_l + 23
134
+ and any(is_mj(s['font']) for s in line['spans'])
135
+ and not any('Bold' in s['font'] for s in line['spans'] if s['text'].strip()))
136
+
137
+ def is_indented(self, line):
138
+ return line['x0'] > self.body_l + 8
139
+
140
+ def is_short(self, line):
141
+ """A line that ends its paragraph (it does not reach the right edge)."""
142
+ return line['x1'] < self.body_r - 7
143
+
144
+ def is_centred(self, line):
145
+ """Centred on the page: short centred lines, or headings in a larger size however
146
+ long (a long chapter title can start near the margin)."""
147
+ mid = (line['x0'] + line['x1']) / 2
148
+ if abs(mid - self.page_w / 2) >= 10:
149
+ return False
150
+ return line['x0'] > self.page_w * 0.25 or line['mj_size'] > self.body_size + 1.5
151
+
152
+
153
+ def _page_colour(doc, pages=8):
154
+ """Page background as '#RRGGBB': the most common colour of the page margins (the outer
155
+ tenth of each side) on a few pages, skipping the first page (often a cover)."""
156
+ counts = Counter()
157
+ picks = list(range(1, len(doc)))[:pages] or [0]
158
+ for n in picks:
159
+ pix = doc[n].get_pixmap(dpi=12, alpha=False, colorspace=fitz.csRGB)
160
+ w, h = pix.width, pix.height
161
+ mx, my = max(1, w // 10), max(1, h // 10)
162
+ for y in range(h):
163
+ for x in range(w):
164
+ if x < mx or x >= w - mx or y < my or y >= h - my:
165
+ counts[pix.pixel(x, y)[:3]] += 1
166
+ r, g, b = counts.most_common(1)[0][0] if counts else (255, 255, 255)
167
+ return f'#{r:02X}{g:02X}{b:02X}'
168
+
169
+
170
+ def save_images(doc, page, page_no, img_dir, layout):
171
+ """Save the pictures of one page. Returns dicts with bbox, path and cover flag."""
172
+ saved = []
173
+ inline = None
174
+ infos = page.get_image_info(xrefs=True) # in drawing order
175
+ for k, info in enumerate(infos):
176
+ x0, y0, x1, y1 = info['bbox']
177
+ if _hidden(info, infos[k + 1:]):
178
+ continue # a backdrop under a later picture
179
+ if info['xref']:
180
+ pix = fitz.Pixmap(doc, info['xref'])
181
+ name = f'p{page_no + 1}_{info["xref"]}'
182
+ else:
183
+ # an inline image (inside the page's content stream) has no xref
184
+ if inline is None:
185
+ inline = _inline_images(page)
186
+ data = _match_inline(inline, info['bbox'])
187
+ if data is None:
188
+ continue
189
+ pix = fitz.Pixmap(data)
190
+ name = f'p{page_no + 1}_inline{k}'
191
+ if pix.n - pix.alpha >= 4: # CMYK -> RGB
192
+ pix = fitz.Pixmap(fitz.csRGB, pix)
193
+ cover = (x1 - x0) * (y1 - y0) > 0.5 * layout.page_w * layout.page_h
194
+ path = os.path.join(img_dir, f'{name}.' + ('jpg' if cover else 'png'))
195
+ if cover:
196
+ with open(path, 'wb') as fh:
197
+ fh.write(pix.tobytes('jpeg', 88))
198
+ else:
199
+ pix.save(path)
200
+ saved.append(dict(bbox=info['bbox'], path=path, cover=cover))
201
+ return saved
202
+
203
+
204
+ def _area(rect):
205
+ """Area of a rectangle; 0 when empty (works on every PyMuPDF version)."""
206
+ return max(rect.width, 0) * max(rect.height, 0) if not rect.is_empty else 0.0
207
+
208
+
209
+ def _hidden(info, later):
210
+ """True when a picture drawn later covers at least 90% of this one."""
211
+ rect = fitz.Rect(info['bbox'])
212
+ area = _area(rect)
213
+ return area > 0 and any(_area(rect & fitz.Rect(o['bbox'])) >= 0.9 * area for o in later)
214
+
215
+
216
+ def _inline_images(page):
217
+ """(bbox, image bytes) of the page's image blocks; these include inline images."""
218
+ blocks = page.get_text('dict', flags=fitz.TEXT_PRESERVE_IMAGES)['blocks']
219
+ return [(fitz.Rect(b['bbox']), b['image']) for b in blocks if b.get('type') == 1 and b.get('image')]
220
+
221
+
222
+ def _match_inline(inline, bbox):
223
+ """Bytes of the image block that covers the same area as bbox, or None."""
224
+ target = fitz.Rect(bbox)
225
+ best, best_area = None, 0.0
226
+ for rect, data in inline:
227
+ area = _area(rect & target)
228
+ if area > best_area:
229
+ best, best_area = data, area
230
+ return best if best_area > 0.5 * max(_area(target), 1e-6) else None
ansibangla/api.py ADDED
@@ -0,0 +1,173 @@
1
+ """Public functions: convert SutonnyMJ PDFs and Word files to Unicode PDF, DOCX, EPUB, Markdown
2
+ and printable HTML (the PDF's pages with fonts and pictures embedded, for printing in a browser)."""
3
+ import contextlib
4
+ import os
5
+ import sys
6
+ import tempfile
7
+
8
+ import pymupdf as fitz
9
+
10
+ from ._common import Layout
11
+ from .bijoy import convert as convert_text_string
12
+ from .blocks import read_blocks
13
+ from .docxexport import export_docx
14
+ from .epubexport import export_epub
15
+ from .mdexport import export_markdown
16
+ from .pdfbuild import build_html, build_pdf
17
+
18
+ FORMATS = ('pdf', 'docx', 'epub', 'md', 'html') # any combination can be asked for
19
+ DEFAULT_FORMATS = ('pdf',) # a PDF gives a PDF unless asked otherwise
20
+ DOCX_DEFAULT_FORMATS = ('docx',) # a .docx gives a .docx unless asked otherwise
21
+ FONT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fonts')
22
+
23
+
24
+ def _check_formats(formats):
25
+ formats = tuple(dict.fromkeys(f.strip().lower() for f in formats if f.strip()))
26
+ unknown = set(formats) - set(FORMATS)
27
+ if unknown:
28
+ raise ValueError(f'unknown formats: {sorted(unknown)}; choose from {", ".join(FORMATS)}')
29
+ if not formats:
30
+ raise ValueError(f'no output format; choose one or more of {", ".join(FORMATS)}')
31
+ return formats
32
+
33
+
34
+ def _convert_pdf(src, out_dir='.', *, stem=None, formats=DEFAULT_FORMATS, scale=0.9,
35
+ font_dir=None, chrome=None, title=None):
36
+ """Convert one SutonnyMJ PDF.
37
+
38
+ formats is any combination of 'pdf', 'docx', 'epub', 'md' and 'html', written as
39
+ <stem>_unicode.pdf, .docx, .epub, .md and .html (Markdown pictures go in
40
+ <stem>_unicode_images/). title is the e-book title (default: the first heading).
41
+ Returns {format: path}.
42
+ """
43
+ formats = _check_formats(formats)
44
+ stem = stem or os.path.splitext(os.path.basename(src))[0]
45
+ os.makedirs(out_dir, exist_ok=True)
46
+ base = os.path.join(out_dir, f'{stem}_unicode')
47
+ font_dir = font_dir or FONT_DIR
48
+ doc = fitz.open(src)
49
+ layout = Layout(doc, scale=scale)
50
+ written = {}
51
+
52
+ img_name = f'{stem}_unicode_images'
53
+ with tempfile.TemporaryDirectory(prefix='ansibangla_img_') as tmp:
54
+ # pictures are saved next to the Markdown when it is written, else only for a while
55
+ img_dir = os.path.join(out_dir, img_name) if 'md' in formats else tmp
56
+ blocks = read_blocks(doc, layout, img_dir)
57
+ if 'md' in formats:
58
+ written['md'] = base + '.md'
59
+ with open(written['md'], 'w', encoding='utf-8') as fh:
60
+ fh.write(export_markdown(doc, layout, img_dir, img_name, blocks=blocks))
61
+ if 'docx' in formats:
62
+ written['docx'] = export_docx(doc, layout, blocks, base + '.docx', font_dir)
63
+ if 'epub' in formats:
64
+ written['epub'] = export_epub(doc, layout, blocks, base + '.epub', font_dir, title=title)
65
+ if 'pdf' in formats:
66
+ with tempfile.TemporaryDirectory(prefix='ansibangla_img_') as tmp:
67
+ written['pdf'] = build_pdf(doc, layout, base + '.pdf', font_dir, tmp, chrome=chrome)
68
+ if 'html' in formats:
69
+ with tempfile.TemporaryDirectory(prefix='ansibangla_img_') as tmp:
70
+ written['html'] = build_html(doc, layout, base + '.html', font_dir, tmp)
71
+ return {f: written[f] for f in formats}
72
+
73
+
74
+ def _convert_docx(src, out_dir='.', *, stem=None, formats=DOCX_DEFAULT_FORMATS, font_dir=None,
75
+ scale=0.9, chrome=None, title=None):
76
+ """Convert one Word document typed in SutonnyMJ.
77
+
78
+ formats is any combination of 'docx' (the same document with its SutonnyMJ text in
79
+ Unicode and the bundled fonts embedded), 'pdf' (that document laid out at its page
80
+ size and printed with Chrome), 'html' (that layout as one printable HTML file), 'epub'
81
+ and 'md', written as <stem>_unicode.docx, .pdf, .html, .epub and .md. Returns {format: path}.
82
+ """
83
+ formats = _check_formats(formats)
84
+ from .docxinput import convert_docx as _convert
85
+ stem = stem or os.path.splitext(os.path.basename(src))[0]
86
+ os.makedirs(out_dir, exist_ok=True)
87
+ base = os.path.join(out_dir, f'{stem}_unicode')
88
+ img_name = f'{stem}_unicode_images'
89
+ out_docx = base + '.docx'
90
+ if os.path.abspath(out_docx) == os.path.abspath(src):
91
+ raise ValueError(f'output would overwrite the input {src}; choose another --out-dir')
92
+ written = {}
93
+ tmp_docx = None
94
+ if 'docx' not in formats: # the other outputs are built from the converted file
95
+ tmp = tempfile.NamedTemporaryFile(suffix='.docx', delete=False)
96
+ tmp.close()
97
+ out_docx = tmp_docx = tmp.name
98
+ font_dir = font_dir or FONT_DIR
99
+ try:
100
+ files = _convert(src, out_docx, font_dir, scale=scale)
101
+ finally:
102
+ if tmp_docx:
103
+ os.remove(tmp_docx)
104
+ if 'docx' in formats:
105
+ written['docx'] = out_docx
106
+
107
+ others = [f for f in formats if f != 'docx']
108
+ if others:
109
+ # Markdown, PDF and EPUB come from one model of the converted document; its
110
+ # pictures are saved next to the Markdown when it is written, else only for a while
111
+ from . import docxrender
112
+ with tempfile.TemporaryDirectory(prefix='ansibangla_media_') as tmp:
113
+ media = os.path.join(out_dir, img_name) if 'md' in formats else tmp
114
+ model = docxrender.build_model(files, media)
115
+ for ext, n in model['skipped'].items():
116
+ print(f'note: {src}: {n} picture(s) in {ext} format are left out of the '
117
+ f'{"/".join(others)} (browsers and e-readers cannot show them)', file=sys.stderr)
118
+ if 'md' in formats:
119
+ written['md'] = base + '.md'
120
+ with open(written['md'], 'w', encoding='utf-8') as fh:
121
+ fh.write(docxrender.export_markdown(model, img_name))
122
+ if 'epub' in formats:
123
+ written['epub'] = docxrender.export_epub(model, base + '.epub', font_dir, title=title)
124
+ if 'pdf' in formats:
125
+ written['pdf'] = docxrender.export_pdf(model, base + '.pdf', font_dir, chrome=chrome)
126
+ if 'html' in formats:
127
+ written['html'] = docxrender.export_html(model, base + '.html', font_dir)
128
+ return {f: written[f] for f in formats}
129
+
130
+
131
+ @contextlib.contextmanager
132
+ def _keep_latin(words):
133
+ """Use a list of English words to keep for one conversion, then restore the previous one."""
134
+ from . import bijoy
135
+ previous = list(bijoy.LATIN_KEEP)
136
+ if words is not None:
137
+ bijoy.set_latin_keep(words)
138
+ try:
139
+ yield
140
+ finally:
141
+ bijoy.set_latin_keep(previous)
142
+
143
+
144
+ def convert_pdf(src, out_dir='.', *, keep_latin=None, **options):
145
+ """Convert one SutonnyMJ PDF. Options: stem, formats (any of 'pdf', 'docx', 'epub',
146
+ 'md', 'html'; default 'pdf'), scale, font_dir, chrome, title; keep_latin lists English words
147
+ typed in the SutonnyMJ font that stay as typed. Returns {format: path}."""
148
+ with _keep_latin(keep_latin):
149
+ return _convert_pdf(src, out_dir, **options)
150
+
151
+
152
+ def convert_docx(src, out_dir='.', *, keep_latin=None, **options):
153
+ """Convert one Word document typed in SutonnyMJ. Options as for convert_pdf; formats
154
+ defaults to 'docx'. Returns {format: path}."""
155
+ with _keep_latin(keep_latin):
156
+ return _convert_docx(src, out_dir, **options)
157
+
158
+
159
+ def convert_file(src, out_dir='.', *, formats=None, **options):
160
+ """Convert a SutonnyMJ PDF or .docx, choosing by the file extension. formats is any
161
+ combination of 'pdf', 'docx', 'epub', 'md' and 'html'; None gives the same format as the
162
+ input (pdf for PDFs, docx for Word files)."""
163
+ if src.lower().endswith('.docx'):
164
+ options = {k: v for k, v in options.items()
165
+ if k in ('stem', 'font_dir', 'scale', 'chrome', 'title', 'keep_latin')}
166
+ return convert_docx(src, out_dir, formats=DOCX_DEFAULT_FORMATS if formats is None else formats,
167
+ **options)
168
+ return convert_pdf(src, out_dir, formats=DEFAULT_FORMATS if formats is None else formats, **options)
169
+
170
+
171
+ def convert_text(text):
172
+ """Convert a SutonnyMJ string (as extracted from a PDF) to Unicode Bengali."""
173
+ return convert_text_string(text)