comic-ocr-reader 0.0.2__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.
File without changes
@@ -0,0 +1,3 @@
1
+ from pathlib import Path
2
+
3
+ PROJECT_FOLDER: Path = Path(__file__).parent.parent
@@ -0,0 +1,58 @@
1
+ from datetime import datetime
2
+ from pathlib import Path
3
+
4
+ from PIL import Image
5
+ from easyocr import Reader
6
+ from manga_ocr import MangaOcr
7
+
8
+ from comic_ocr_reader.html_utils import Textbox, Page
9
+ from comic_ocr_reader.img_utils import merge_textboxes_easyocr
10
+
11
+ def process_page(
12
+ manga: dict[int, Page],
13
+ filepath: Path,
14
+ detector: Reader,
15
+ recogniser: MangaOcr,
16
+ page_num: int
17
+ ) -> None:
18
+
19
+ result = detector.detect(str(filepath))
20
+ with Image.open(filepath) as img:
21
+ textboxes: list[Textbox] = []
22
+ width, height = img.size
23
+
24
+ count: int = 0
25
+ page: Page = Page(
26
+ img_filepath=f"{filepath.stem}{filepath.suffix}",
27
+ page_num=page_num,
28
+ page_class="page"
29
+ )
30
+ merged_regions: list[list[int]] = merge_textboxes_easyocr(
31
+ result[0][0],
32
+ padding=1
33
+ )
34
+ for item in merged_regions:
35
+ count += 1
36
+ nums: list[int] = []
37
+ for np_num in item:
38
+ nums.append(int(np_num))
39
+
40
+ box_width: int = nums[1] - nums[0]
41
+ box_height: int = nums[3] - nums[2]
42
+ percent_width: int = round(box_width / width * 100)
43
+ percent_height: int = round(box_height / height * 100)
44
+
45
+ region = img.crop((nums[0], nums[2], nums[1], nums[3]))
46
+ start = datetime.now()
47
+ text: str = recogniser(region)
48
+ end = datetime.now()
49
+ textbox: Textbox = Textbox(
50
+ top=round(nums[2] / height * 100),
51
+ left=round(nums[0] / width * 100),
52
+ height=int(percent_height),
53
+ width=int(percent_width),
54
+ text=text
55
+ )
56
+ textboxes.append(textbox)
57
+ page.textboxes = textboxes
58
+ manga[page_num] = page
@@ -0,0 +1,111 @@
1
+ from pathlib import Path
2
+
3
+ HTML_UTILS_FOLDER: Path = Path(__file__).parent
4
+ class Textbox:
5
+ """Class containing details of the textbox on a page
6
+ Attributes:
7
+ top %-age of page down from top of page to place textbox.
8
+ left %-age of page right from left of page to place textbox.
9
+ width %-age width of textbox in terms of containing page.
10
+ height %-age height of textbox in terms of containing page.
11
+ """
12
+ top: int
13
+ left: int
14
+ width: int
15
+ height: int
16
+ text: str
17
+ btn_class: str
18
+ def __init__(
19
+ self,
20
+ top: int,
21
+ left: int,
22
+ width: int,
23
+ height: int,
24
+ text: str
25
+ ) -> None:
26
+ self.top = top
27
+ self.left = left
28
+ self.width = width
29
+ self.height = height
30
+ self.text = text
31
+
32
+ class Page:
33
+ textboxes: list[Textbox] = []
34
+ img_filepath: Path
35
+ page_num: int
36
+ page_html: str
37
+ page_class: str
38
+
39
+ def __init__(
40
+ self,
41
+ img_filepath: Path|str,
42
+ page_num: int,
43
+ page_class: str
44
+ ):
45
+ self.img_filepath = img_filepath
46
+ self.page_num = page_num
47
+ self.page_class = page_class
48
+
49
+ def make_page_html(self) -> None:
50
+ """
51
+ Constructs the HTML of a page, shoves it into the page_html attribute of this object.
52
+ :return:
53
+ """
54
+ page_html: str = f"""
55
+ <div class="{self.page_class}" id="page{self.page_num}">
56
+ <button class="page-nav prev" onclick="lastPage()">Prev. Page</button>
57
+ <button class="page-nav next" onclick="nextPage()">Next Page</button>
58
+ <div class="zoom-hint">Ctrl + wheel to zoom</div>
59
+ <div class="page-content">
60
+ <div class="page-content-inner">
61
+ <img src="{self.img_filepath}" alt="Snow">
62
+ """
63
+ for textbox in self.textboxes:
64
+ page_html += f"""
65
+ <button class="text-btn"
66
+ style="--top:{textbox.top}%;--left:{textbox.left}%;--height:{textbox.height}%;--width:{textbox.width}%;">
67
+ <span>{textbox.text}</span>
68
+ </button>
69
+ """
70
+ page_html+="""
71
+ </div>
72
+ </div>
73
+ </div>
74
+ """
75
+ self.page_html = page_html
76
+
77
+ def set_page_class(self, page_class: str):
78
+ self.page_class = page_class
79
+
80
+
81
+ def make_html_file(
82
+ pages: dict[int, Page],
83
+ template: str|Path = f"{HTML_UTILS_FOLDER}/html_template.html"
84
+ ) -> str:
85
+ html_body: str = ""
86
+ for i in range(1, len(pages.keys())+1):
87
+ if (i - 1) % 2 == 0:
88
+ html_body += """
89
+ <div class="spread">
90
+ <button class="spread-nav prev" onclick="lastPage()">Prev. Page</button>
91
+ <button class="spread-nav next" onclick="nextPage()">Next Page</button>
92
+ <div class="spread-hint">Ctrl + wheel to zoom</div>
93
+ <div class="spread-scroll">
94
+ <div class="spread-content">
95
+ """
96
+ if i == len(pages):
97
+ pages[i].set_page_class("page last")
98
+ elif i == 1:
99
+ pages[i].set_page_class("page first")
100
+ pages[i].make_page_html()
101
+ html_body += pages[i].page_html
102
+ if (i - 1) % 2 == 1 or i == len(pages):
103
+ html_body += """
104
+ </div>
105
+ </div>
106
+ </div>
107
+ """
108
+ with open(template, "r", encoding="utf-8") as html_template:
109
+ template: str = html_template.read()
110
+ template = template.replace("{{BODY}}", html_body)
111
+ return template
@@ -0,0 +1,789 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <title>Title</title>
6
+ </head>
7
+ <style>
8
+ @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap');
9
+
10
+ body {
11
+ margin: 0;
12
+ min-height: 100vh;
13
+ display: grid;
14
+ place-items: center;
15
+ /* Leave room for the three fixed view controls. */
16
+ padding: 10rem 1rem 1rem;
17
+ box-sizing: border-box;
18
+ background: #2b2b2b;
19
+ font-family: 'Roboto', sans-serif;
20
+ }
21
+
22
+ body.two-page-mode {
23
+ display: block;
24
+ place-items: initial;
25
+ overflow-y: auto;
26
+ padding-top: 10rem;
27
+ }
28
+
29
+ .view-toggle {
30
+ display: inline-flex;
31
+ align-items: center;
32
+ gap: 0.5rem;
33
+ padding: 0.45rem 0.7rem;
34
+ border-radius: 999px;
35
+ background: rgba(245, 245, 245, 0.94);
36
+ border: 1px solid #666;
37
+ color: #222;
38
+ box-shadow: 0 1px 6px rgba(0, 0, 0, 0.22);
39
+ user-select: none;
40
+ }
41
+
42
+ .view-controls {
43
+ position: fixed;
44
+ top: 0.75rem;
45
+ left: 0.75rem;
46
+ right: 0.75rem;
47
+ z-index: 40;
48
+ display: flex;
49
+ flex-wrap: wrap;
50
+ align-items: center;
51
+ gap: 0.5rem;
52
+ }
53
+
54
+ .view-toggle input {
55
+ margin: 0;
56
+ }
57
+
58
+ .view-toggle.text-toggle {
59
+ position: static;
60
+ }
61
+
62
+ body.show-text-buttons .page .text-btn {
63
+ opacity: 1 !important;
64
+ }
65
+
66
+ body.hide-page-navigation .page-nav,
67
+ body.hide-page-navigation .spread-nav {
68
+ display: none !important;
69
+ }
70
+
71
+ .page{
72
+ position: relative;
73
+ width: min(95vw, 1600px);
74
+ container-type: inline-size;
75
+ display: none;
76
+ }
77
+
78
+ .page.active{
79
+ display: block;
80
+ }
81
+
82
+ .spread {
83
+ display: none;
84
+ position: relative;
85
+ }
86
+
87
+ .spread.active {
88
+ display: block;
89
+ }
90
+
91
+ body.two-page-mode .page {
92
+ display: block;
93
+ margin: 0;
94
+ width: auto;
95
+ flex: 1 1 0;
96
+ min-width: 0;
97
+ }
98
+
99
+ body.two-page-mode .spread {
100
+ width: min(95vw, 1800px);
101
+ margin: 0 auto;
102
+ }
103
+
104
+ body.two-page-mode .spread.active {
105
+ display: block;
106
+ margin: 0 auto 1rem;
107
+ padding: 0;
108
+ background: transparent;
109
+ border: none;
110
+ border-radius: 0;
111
+ box-shadow: none;
112
+ overflow: visible;
113
+ }
114
+
115
+ body.two-page-mode .page-nav {
116
+ display: none;
117
+ }
118
+
119
+ .spread-nav {
120
+ position: absolute;
121
+ top: 50%;
122
+ transform: translateY(-50%);
123
+ z-index: 25;
124
+ padding: 0.75rem 0.5rem;
125
+ border: 1px solid #666;
126
+ background: rgba(245, 245, 245, 0.94);
127
+ color: #111;
128
+ cursor: pointer;
129
+ user-select: none;
130
+ display: none;
131
+ }
132
+
133
+ body.two-page-mode .spread-nav {
134
+ display: block;
135
+ }
136
+
137
+ .spread-nav.prev {
138
+ left: 0;
139
+ border-left: none;
140
+ border-radius: 0 10px 10px 0;
141
+ }
142
+
143
+ .spread-nav.next {
144
+ right: 0;
145
+ border-right: none;
146
+ border-radius: 10px 0 0 10px;
147
+ }
148
+
149
+ .spread-hint {
150
+ position: absolute;
151
+ top: -2.1rem;
152
+ left: 50%;
153
+ transform: translateX(-50%);
154
+ z-index: 30;
155
+ display: none;
156
+ width: fit-content;
157
+ padding: 0.4rem 0.7rem;
158
+ border-radius: 999px;
159
+ background: rgba(245, 245, 245, 0.94);
160
+ border: 1px solid #666;
161
+ color: #222;
162
+ font-size: 0.85rem;
163
+ pointer-events: none;
164
+ box-shadow: 0 1px 6px rgba(0, 0, 0, 0.22);
165
+ }
166
+
167
+ body.two-page-mode .spread-hint {
168
+ display: block;
169
+ }
170
+
171
+ body.two-page-mode .zoom-hint {
172
+ display: none;
173
+ }
174
+
175
+ .page-content {
176
+ position: relative;
177
+ width: 100%;
178
+ height: 80vh;
179
+ margin: 0;
180
+ overflow: auto;
181
+ box-sizing: border-box;
182
+ background: #f4f4f4;
183
+ border: 1px solid #666;
184
+ border-radius: 10px;
185
+ box-shadow: 0 4px 14px rgba(0, 0, 0, 0.3);
186
+ }
187
+
188
+ body.two-page-mode .page-content {
189
+ height: auto;
190
+ overflow: visible;
191
+ border: none;
192
+ background: transparent;
193
+ box-shadow: none;
194
+ border-radius: 0;
195
+ }
196
+
197
+ .spread-scroll {
198
+ display: block;
199
+ }
200
+
201
+ body.two-page-mode .spread-scroll {
202
+ display: block;
203
+ height: 80vh;
204
+ overflow: auto;
205
+ box-sizing: border-box;
206
+ background: #f4f4f4;
207
+ border: 1px solid #666;
208
+ border-radius: 10px;
209
+ box-shadow: 0 4px 14px rgba(0, 0, 0, 0.3);
210
+ }
211
+
212
+ .spread-content {
213
+ display: block;
214
+ }
215
+
216
+ body.two-page-mode .spread-content {
217
+ display: flex;
218
+ flex-direction: row-reverse;
219
+ gap: 0;
220
+ align-items: flex-start;
221
+ justify-content: center;
222
+ width: calc(100% * var(--spread-zoom, 1));
223
+ min-height: 100%;
224
+ margin: 0 auto;
225
+ }
226
+
227
+ .page-nav {
228
+ position: absolute;
229
+ top: 50%;
230
+ transform: translateY(-50%);
231
+ z-index: 20;
232
+ padding: 0.75rem 0.5rem;
233
+ border: 1px solid #666;
234
+ background: rgba(245, 245, 245, 0.94);
235
+ color: #111;
236
+ cursor: pointer;
237
+ user-select: none;
238
+ }
239
+
240
+ .page-nav.prev {
241
+ left: 0;
242
+ border-left: none;
243
+ border-radius: 0 10px 10px 0;
244
+ }
245
+
246
+ .page-nav.next {
247
+ right: 0;
248
+ border-right: none;
249
+ border-radius: 10px 0 0 10px;
250
+ }
251
+
252
+ .zoom-hint {
253
+ position: static;
254
+ display: block;
255
+ width: fit-content;
256
+ margin: 0 0 0.6rem auto;
257
+ z-index: 20;
258
+ padding: 0.4rem 0.7rem;
259
+ border-radius: 999px;
260
+ background: rgba(245, 245, 245, 0.94);
261
+ border: 1px solid #666;
262
+ color: #222;
263
+ font-size: 0.85rem;
264
+ pointer-events: none;
265
+ box-shadow: 0 1px 6px rgba(0, 0, 0, 0.22);
266
+ }
267
+
268
+ .page-content-inner {
269
+ position: relative;
270
+ width: calc(100% * var(--zoom, 1));
271
+ margin: 0 auto;
272
+ }
273
+
274
+ body.two-page-mode .page-content-inner {
275
+ width: 100%;
276
+ margin: 0;
277
+ }
278
+
279
+ .page {
280
+ margin: 0 auto;
281
+ }
282
+
283
+ /* Make the image responsive inside the viewport */
284
+ .page-content-inner img {
285
+ display: block;
286
+ width: 100%;
287
+ height: auto;
288
+ }
289
+
290
+ .page .text-btn{
291
+ position: absolute;
292
+ container-type: size;
293
+ padding: 8px;
294
+ top: var(--top);
295
+ left: var(--left);
296
+ width: var(--width);
297
+ height: var(--height);
298
+ opacity: 0;
299
+ display: flex;
300
+ overflow: hidden;
301
+ box-sizing: content-box;
302
+ user-select: text;
303
+ -webkit-user-select: text;
304
+ cursor: text;
305
+ }
306
+ .page.active .text-btn:hover {
307
+ opacity: 1;
308
+ }
309
+ .page .text-btn span{
310
+ line-height: var(--text-line-height, 1.35);
311
+ white-space: normal;
312
+ overflow-wrap: anywhere;
313
+ writing-mode: vertical-rl;
314
+ text-orientation: upright;
315
+ width: auto;
316
+ height: 100%;
317
+ user-select: text;
318
+ -webkit-user-select: text;
319
+ color: black;
320
+ }
321
+ </style>
322
+ <body>
323
+ <div class="view-controls">
324
+ <label class="view-toggle" for="two-page-toggle">
325
+ <input type="checkbox" id="two-page-toggle">
326
+ Two-page spread
327
+ </label>
328
+ <label class="view-toggle text-toggle" for="text-buttons-toggle">
329
+ <input type="checkbox" id="text-buttons-toggle">
330
+ Show text buttons
331
+ </label>
332
+ <label class="view-toggle" for="page-navigation-toggle">
333
+ <input type="checkbox" id="page-navigation-toggle" checked>
334
+ Show page navigation
335
+ </label>
336
+ </div>
337
+ {{BODY}}
338
+ <script>
339
+ function isTwoPageMode() {
340
+ return document.body.classList.contains("two-page-mode");
341
+ }
342
+
343
+ let singlePageZoom = 1;
344
+ let spreadZoom = 1;
345
+
346
+ function updateTextButtonVisibility(enabled) {
347
+ document.body.classList.toggle("show-text-buttons", enabled);
348
+ }
349
+
350
+ function updatePageNavigationVisibility(enabled) {
351
+ document.body.classList.toggle("hide-page-navigation", !enabled);
352
+ }
353
+
354
+ function getPages() {
355
+ return Array.from(document.querySelectorAll(".page"));
356
+ }
357
+
358
+ function getSpreads() {
359
+ return Array.from(document.querySelectorAll(".spread"));
360
+ }
361
+
362
+ function getActivePageIndex(pages) {
363
+ return pages.findIndex((page) => page.classList.contains("active"));
364
+ }
365
+
366
+ function clearActivePages(pages) {
367
+ pages.forEach((page) => page.classList.remove("active"));
368
+ }
369
+
370
+ function getActiveSpreadIndex(spreads) {
371
+ return spreads.findIndex((spread) => spread.classList.contains("active"));
372
+ }
373
+
374
+ function clearActiveSpreads(spreads) {
375
+ spreads.forEach((spread) => spread.classList.remove("active"));
376
+ }
377
+
378
+ function getSpreadForPage(page) {
379
+ return page ? page.closest(".spread") : null;
380
+ }
381
+
382
+ function getActiveSpread() {
383
+ return document.querySelector(".spread.active");
384
+ }
385
+
386
+ function getActiveSpreadScroll() {
387
+ const activeSpread = getActiveSpread();
388
+ return activeSpread ? activeSpread.querySelector(".spread-scroll") : null;
389
+ }
390
+
391
+ function resetActiveSpreadScroll() {
392
+ const scroll = getActiveSpreadScroll();
393
+ if (!scroll) {
394
+ return;
395
+ }
396
+ scroll.scrollLeft = 0;
397
+ scroll.scrollTop = 0;
398
+ }
399
+
400
+ function getSpreadStartIndex(pages) {
401
+ const activeIndex = getActivePageIndex(pages);
402
+ if (activeIndex === -1) {
403
+ return 0;
404
+ }
405
+ return activeIndex - (activeIndex % 2);
406
+ }
407
+
408
+ function setSingleActivePage(pages, index) {
409
+ if (!pages[index]) {
410
+ return;
411
+ }
412
+ clearActivePages(pages);
413
+ pages[index].classList.add("active");
414
+ const spread = getSpreadForPage(pages[index]);
415
+ if (spread) {
416
+ clearActiveSpreads(getSpreads());
417
+ spread.classList.add("active");
418
+ }
419
+ const viewport = pages[index].querySelector(".page-content");
420
+ setViewportZoom(viewport, singlePageZoom);
421
+ }
422
+
423
+ function activateSinglePageByOffset(pages, offset) {
424
+ const currentIndex = getActivePageIndex(pages);
425
+ const nextIndex = currentIndex === -1 ? 0 : currentIndex + offset;
426
+ if (!pages[nextIndex]) {
427
+ return;
428
+ }
429
+ setSingleActivePage(pages, nextIndex);
430
+ }
431
+
432
+ function setActiveSpreadByIndex(spreads, spreadIndex) {
433
+ if (!spreads[spreadIndex]) {
434
+ return;
435
+ }
436
+ const pages = getPages();
437
+ clearActivePages(pages);
438
+ clearActiveSpreads(spreads);
439
+
440
+ const spread = spreads[spreadIndex];
441
+ spread.classList.add("active");
442
+ const spreadContent = spread.querySelector(".spread-content");
443
+ if (spreadContent) {
444
+ spreadContent.style.setProperty("--spread-zoom", spreadZoom);
445
+ }
446
+ spread.querySelectorAll(".page").forEach((page) => {
447
+ page.classList.add("active");
448
+ });
449
+ }
450
+
451
+ function scrollActiveTargetIntoView(twoPageEnabled) {
452
+ if (twoPageEnabled) {
453
+ resetActiveSpreadScroll();
454
+ return;
455
+ }
456
+
457
+ const pages = getPages();
458
+ if (!pages.length) {
459
+ return;
460
+ }
461
+
462
+ const activeIndex = getActivePageIndex(pages);
463
+ if (activeIndex === -1) {
464
+ return;
465
+ }
466
+
467
+ const target = pages[activeIndex];
468
+
469
+ target.scrollIntoView({
470
+ block: twoPageEnabled ? "start" : "center",
471
+ inline: "nearest"
472
+ });
473
+ }
474
+
475
+ function activateSpreadByOffset(spreads, offset) {
476
+ const currentSpreadIndex = getActiveSpreadIndex(spreads);
477
+ const nextSpreadIndex = currentSpreadIndex === -1 ? 0 : currentSpreadIndex + offset;
478
+ if (!spreads[nextSpreadIndex]) {
479
+ return false;
480
+ }
481
+ setActiveSpreadByIndex(spreads, nextSpreadIndex);
482
+ return true;
483
+ }
484
+
485
+ function updateViewMode(twoPageEnabled) {
486
+ document.body.classList.toggle("two-page-mode", twoPageEnabled);
487
+ const pages = getPages();
488
+ const spreads = getSpreads();
489
+ if (!pages.length) {
490
+ return;
491
+ }
492
+
493
+ if (twoPageEnabled) {
494
+ setActiveSpreadByIndex(spreads, Math.floor(getSpreadStartIndex(pages) / 2));
495
+ } else {
496
+ clearActiveSpreads(spreads);
497
+ const activeIndex = getActivePageIndex(pages);
498
+ setSingleActivePage(pages, activeIndex === -1 ? 0 : activeIndex);
499
+ }
500
+
501
+ scrollActiveTargetIntoView(twoPageEnabled);
502
+ resizeAllButtonText();
503
+ }
504
+
505
+ function nextPage() {
506
+ const pages = getPages();
507
+ const spreads = getSpreads();
508
+ if (!pages.length) {
509
+ return;
510
+ }
511
+
512
+ if (isTwoPageMode()) {
513
+ if (!activateSpreadByOffset(spreads, 1)) {
514
+ return;
515
+ }
516
+ const event = new Event("newpage");
517
+ window.dispatchEvent(event);
518
+ resetActiveSpreadScroll();
519
+ return;
520
+ }
521
+
522
+ const currentIndex = getActivePageIndex(pages);
523
+ if (currentIndex === -1) {
524
+ setSingleActivePage(pages, 0);
525
+ } else if (pages[currentIndex].classList.contains("last")) {
526
+ return;
527
+ } else {
528
+ activateSinglePageByOffset(pages, 1);
529
+ }
530
+
531
+ const event = new Event("newpage");
532
+ window.dispatchEvent(event);
533
+ scrollActiveTargetIntoView(false);
534
+ }
535
+ </script>
536
+ <script>
537
+ function lastPage() {
538
+ const pages = getPages();
539
+ const spreads = getSpreads();
540
+ if (!pages.length) {
541
+ return;
542
+ }
543
+
544
+ if (isTwoPageMode()) {
545
+ const currentSpreadIndex = getActiveSpreadIndex(spreads);
546
+ if (currentSpreadIndex <= 0) {
547
+ return;
548
+ }
549
+
550
+ if (!activateSpreadByOffset(spreads, -1)) {
551
+ return;
552
+ }
553
+ const event = new Event("newpage");
554
+ window.dispatchEvent(event);
555
+ resetActiveSpreadScroll();
556
+ return;
557
+ }
558
+
559
+ const currentIndex = getActivePageIndex(pages);
560
+ if (currentIndex === -1) {
561
+ setSingleActivePage(pages, 0);
562
+ const event = new Event("newpage");
563
+ window.dispatchEvent(event);
564
+ scrollActiveTargetIntoView(false);
565
+ return;
566
+ }
567
+
568
+ if (pages[currentIndex].classList.contains("first")) {
569
+ return;
570
+ }
571
+
572
+ activateSinglePageByOffset(pages, -1);
573
+ const event = new Event("newpage");
574
+ window.dispatchEvent(event);
575
+ scrollActiveTargetIntoView(false);
576
+ }
577
+ </script>
578
+ <script>
579
+ function fitTextToButton(button, options = {}) {
580
+ const text = button.querySelector(".text-btn span");
581
+
582
+ if (!text) {
583
+ return;
584
+ }
585
+
586
+ const {
587
+ minFontSize = 4,
588
+ maxFontSize = 100,
589
+ precision = 0.1
590
+ } = options;
591
+
592
+ const buttonStyles = getComputedStyle(button);
593
+
594
+ const availableWidth =
595
+ button.clientWidth -
596
+ parseFloat(buttonStyles.paddingLeft) -
597
+ parseFloat(buttonStyles.paddingRight);
598
+
599
+ const availableHeight =
600
+ button.clientHeight -
601
+ parseFloat(buttonStyles.paddingTop) -
602
+ parseFloat(buttonStyles.paddingBottom);
603
+
604
+ text.style.width = `${availableWidth}px`;
605
+ text.style.setProperty("--text-line-height", "1.12");
606
+ text.style.fontSize = `${maxFontSize}px`;
607
+
608
+ let low = minFontSize;
609
+ let high = maxFontSize;
610
+ let bestSize = minFontSize;
611
+
612
+ while (high - low > precision) {
613
+ const middle = (low + high) / 2;
614
+
615
+ text.style.fontSize = `${middle}px`;
616
+
617
+ const fitsWidth = text.scrollWidth <= availableWidth + 0.5;
618
+ const fitsHeight = text.scrollHeight <= availableHeight + 0.5;
619
+
620
+ if (fitsWidth && fitsHeight) {
621
+ bestSize = middle;
622
+ low = middle;
623
+ } else {
624
+ high = middle;
625
+ }
626
+ }
627
+
628
+ text.style.fontSize = `${bestSize}px`;
629
+
630
+ const rawText = (text.textContent || "").replace(/\s+/g, "");
631
+ const punctuationMatches = rawText.match(/[。、,.・「」『』()\(\)!?…—‥]/g) || [];
632
+ const punctuationDensity = rawText.length > 0
633
+ ? punctuationMatches.length / rawText.length
634
+ : 0;
635
+ const renderedColumns = Math.max(1, Math.ceil(text.scrollWidth / Math.max(1, availableWidth)));
636
+ const adaptiveLineHeight = Math.min(
637
+ 1.62,
638
+ Math.max(
639
+ 1.12,
640
+ 1.12 +
641
+ Math.min((renderedColumns - 1) * 0.09, 0.38) +
642
+ Math.min(punctuationDensity * 0.25, 0.12)
643
+ )
644
+ );
645
+ text.style.setProperty("--text-line-height", adaptiveLineHeight.toFixed(2));
646
+ }
647
+ function resizeAllButtonText() {
648
+ document.querySelectorAll(".text-btn").forEach((button) => {
649
+ fitTextToButton(button, {
650
+ minFontSize: 4,
651
+ maxFontSize: 100,
652
+ precision: 0.1
653
+ });
654
+ });
655
+ }
656
+ window.addEventListener("resize", resizeAllButtonText);
657
+ window.addEventListener("newpage",resizeAllButtonText);
658
+ function getViewportContent(viewport) {
659
+ return viewport ? viewport.querySelector(".page-content-inner") : null;
660
+ }
661
+
662
+ function setViewportZoom(viewport, zoom) {
663
+ const content = getViewportContent(viewport);
664
+ if (!content) {
665
+ return;
666
+ }
667
+ const clampedZoom = Math.min(3, Math.max(0.25, zoom));
668
+ content.style.setProperty("--zoom", clampedZoom);
669
+ return clampedZoom;
670
+ }
671
+
672
+ function handleViewportWheel(event) {
673
+ if (isTwoPageMode()) {
674
+ return;
675
+ }
676
+ if (!event.ctrlKey) {
677
+ return;
678
+ }
679
+
680
+ const viewport = event.currentTarget;
681
+ const content = getViewportContent(viewport);
682
+ if (!content) {
683
+ return;
684
+ }
685
+
686
+ const currentZoom = parseFloat(getComputedStyle(content).getPropertyValue("--zoom")) || 1;
687
+ const zoomFactor = event.deltaY > 0 ? 0.9 : 1.1;
688
+ const nextZoom = Math.min(3, Math.max(0.25, currentZoom * zoomFactor));
689
+
690
+ if (nextZoom === currentZoom) {
691
+ return;
692
+ }
693
+
694
+ const rect = viewport.getBoundingClientRect();
695
+ const cursorX = event.clientX - rect.left;
696
+ const cursorY = event.clientY - rect.top;
697
+
698
+ const anchorX = (viewport.scrollLeft + cursorX) / currentZoom;
699
+ const anchorY = (viewport.scrollTop + cursorY) / currentZoom;
700
+
701
+ setViewportZoom(viewport, nextZoom);
702
+ singlePageZoom = nextZoom;
703
+ viewport.scrollLeft = anchorX * nextZoom - cursorX;
704
+ viewport.scrollTop = anchorY * nextZoom - cursorY;
705
+
706
+ event.preventDefault();
707
+ }
708
+
709
+ function handleSpreadWheel(event) {
710
+ if (!isTwoPageMode() || !event.ctrlKey) {
711
+ return;
712
+ }
713
+
714
+ const scroll = event.currentTarget;
715
+ const activeSpread = scroll.closest(".spread");
716
+ if (!activeSpread || !activeSpread.classList.contains("active")) {
717
+ return;
718
+ }
719
+
720
+ const spreadContent = activeSpread.querySelector(".spread-content");
721
+ if (!spreadContent) {
722
+ return;
723
+ }
724
+
725
+ const currentZoom = parseFloat(getComputedStyle(spreadContent).getPropertyValue("--spread-zoom")) || 1;
726
+ const zoomFactor = event.deltaY > 0 ? 0.9 : 1.1;
727
+ const nextZoom = Math.min(3, Math.max(0.25, currentZoom * zoomFactor));
728
+
729
+ if (nextZoom === currentZoom) {
730
+ return;
731
+ }
732
+
733
+ const rect = scroll.getBoundingClientRect();
734
+ const cursorX = event.clientX - rect.left;
735
+ const cursorY = event.clientY - rect.top;
736
+
737
+ const anchorX = (scroll.scrollLeft + cursorX) / currentZoom;
738
+ const anchorY = (scroll.scrollTop + cursorY) / currentZoom;
739
+
740
+ spreadContent.style.setProperty("--spread-zoom", nextZoom);
741
+ spreadZoom = nextZoom;
742
+
743
+ scroll.scrollLeft = anchorX * nextZoom - cursorX;
744
+ scroll.scrollTop = anchorY * nextZoom - cursorY;
745
+ event.preventDefault();
746
+ }
747
+
748
+ function attachViewportWheelHandlers() {
749
+ document.querySelectorAll(".page-content").forEach((viewport) => {
750
+ setViewportZoom(viewport, 1);
751
+ viewport.addEventListener("wheel", handleViewportWheel, { passive: false });
752
+ });
753
+ document.querySelectorAll(".spread-scroll").forEach((scroll) => {
754
+ const spreadContent = scroll.querySelector(".spread-content");
755
+ if (spreadContent) {
756
+ spreadContent.style.setProperty("--spread-zoom", 1);
757
+ }
758
+ scroll.addEventListener("wheel", handleSpreadWheel, { passive: false });
759
+ });
760
+ }
761
+
762
+ attachViewportWheelHandlers();
763
+ const twoPageToggle = document.getElementById("two-page-toggle");
764
+ twoPageToggle.addEventListener("change", (event) => {
765
+ updateViewMode(event.target.checked);
766
+ });
767
+ const textButtonsToggle = document.getElementById("text-buttons-toggle");
768
+ textButtonsToggle.addEventListener("change", (event) => {
769
+ updateTextButtonVisibility(event.target.checked);
770
+ });
771
+ const pageNavigationToggle = document.getElementById("page-navigation-toggle");
772
+ pageNavigationToggle.addEventListener("change", (event) => {
773
+ updatePageNavigationVisibility(event.target.checked);
774
+ });
775
+ window.addEventListener("keydown", (event) => {
776
+ if (event.key === "ArrowLeft" || event.key === "a" || event.key === "A") {
777
+ event.preventDefault();
778
+ lastPage();
779
+ } else if (event.key === "ArrowRight" || event.key === "d" || event.key === "D") {
780
+ event.preventDefault();
781
+ nextPage();
782
+ }
783
+ });
784
+ updateViewMode(false);
785
+ updateTextButtonVisibility(false);
786
+ updatePageNavigationVisibility(pageNavigationToggle.checked);
787
+ </script>
788
+ </body>
789
+ </html>
@@ -0,0 +1,64 @@
1
+ import numpy as np
2
+
3
+ def __compare_regions(
4
+ r1: list[int],
5
+ r2: list[int],
6
+ padding: int = 0,
7
+ ) -> bool:
8
+ ef_r1: list[int] = [r1[0]-padding, r1[1]+padding, r1[2]-padding, r1[3]+padding]
9
+ ef_r2: list[int] = [r2[0]-padding, r2[1]+padding, r2[2]-padding, r2[3]+padding]
10
+ return (ef_r1[1] > ef_r2[0] and ef_r1[0] < ef_r2[1]) and (ef_r1[3] > ef_r2[2] and ef_r1[2] < ef_r2[3])
11
+
12
+ def __merge_regions(
13
+ r1: list[int],
14
+ r2: list[int],
15
+ ) -> list[int]:
16
+ y_cords: list[int] = [r1[2], r2[2], r1[3], r2[3]]
17
+ x_cords: list[int] = [r1[0], r2[0], r1[1], r2[1]]
18
+ x_max: int = max(x_cords)
19
+ x_min: int = min(x_cords)
20
+ y_max: int = max(y_cords)
21
+ y_min: int = min(y_cords)
22
+ new_region: list[int] = [x_min, x_max, y_min, y_max]
23
+ return new_region
24
+
25
+ def merge_textboxes_easyocr(
26
+ region_list: list[list[int]],
27
+ padding: int = 0
28
+ ) -> list[list[int]]:
29
+ """
30
+ :param padding: Leniency for region merging. Larger number means more regions likely to be merged.
31
+ :param region_list: A list of regions where text is detected from easyOCR. This takes the form
32
+ [x_min, x_max, y_min, y_max]
33
+ :return: A list where close/overlapping regions have been merged into a larger box.
34
+ """
35
+ """
36
+ """
37
+ all_merged: bool = False
38
+ last_region_list: list[list[int]] = region_list
39
+ merged_regions: list[list[int]] = []
40
+ while not all_merged:
41
+ region_created: bool = False
42
+ for counter_1 in range(len(last_region_list)):
43
+ r1 = last_region_list[counter_1]
44
+ for counter_2 in range(len(last_region_list)):
45
+ if counter_2 == counter_1:
46
+ continue
47
+ r2 = last_region_list[counter_2]
48
+ if __compare_regions(r1, r2, padding):
49
+ new_region: list[int] = __merge_regions(r1, r2)
50
+ merged_regions.append(new_region)
51
+ leftover_regions: list[list[int]] = [
52
+ region for index, region in enumerate(last_region_list) if index not in [counter_1, counter_2]
53
+ ]
54
+ merged_regions += leftover_regions
55
+ last_region_list = merged_regions
56
+ merged_regions = []
57
+ region_created = True
58
+ break
59
+ if region_created:
60
+ break
61
+ if not region_created:
62
+ all_merged = True
63
+
64
+ return last_region_list
@@ -0,0 +1,103 @@
1
+ import os
2
+ from pathlib import Path
3
+ from typing import Final
4
+ from tqdm import tqdm
5
+ from loguru import logger
6
+
7
+ from easyocr import Reader
8
+ from manga_ocr import MangaOcr
9
+
10
+ from html_utils import Page, make_html_file
11
+ from functions import process_page
12
+
13
+ VALID_EXTENSIONS: Final[list[str]] = [
14
+ "jpg",
15
+ "jpeg",
16
+ "png",
17
+ "bmp",
18
+ "tiff"
19
+ ]
20
+ logger.disable("manga_ocr")
21
+
22
+ def main(
23
+ folder_path: str,
24
+ manga_name: str = ...
25
+ ) -> bool:
26
+ path_folder: Path = Path(folder_path)
27
+ file_list: list[str] = os.listdir(path_folder)
28
+ images: list[str] = []
29
+ page_num = 0
30
+ manga: dict[int, Page] = {}
31
+ manga_name: str = path_folder.name if manga_name is ... else manga_name
32
+ print(f"Processing the folder of manga titled \"{manga_name}\"")
33
+ for file in file_list:
34
+ if Path(f"{path_folder}/{file}").is_file():
35
+ if file.split('.')[-1] in VALID_EXTENSIONS:
36
+ images.append(file)
37
+ else:
38
+ continue
39
+ else:
40
+ continue
41
+ print(f"Found {len(images)} pages in folder.")
42
+ try:
43
+ images.sort(key=lambda fname: int(fname.split('.')[0]))
44
+ except ValueError:
45
+ print("One of the image files in the folder you have entered has a non-integer name. (e.g. 123abc.jpeg instead of 123.jpeg)\n"
46
+ "All image files within the folder *must* have an integer name for ordering purposes.")
47
+ return False
48
+ detector = Reader(
49
+ lang_list=['ja'],
50
+ recognizer=False,
51
+ gpu=True
52
+ )
53
+ recogniser = MangaOcr()
54
+ for file in tqdm(images):
55
+ page_num += 1
56
+ process_page(
57
+ manga=manga,
58
+ filepath=Path(f"{folder_path}/{file}"),
59
+ detector=detector,
60
+ recogniser=recogniser,
61
+ page_num=page_num
62
+ )
63
+
64
+ final_html: str = make_html_file(manga)
65
+ with open(f"{folder_path}/{manga_name}.html", "w+", encoding="utf-8") as f:
66
+ f.write(final_html)
67
+ f.flush()
68
+ return True
69
+
70
+ while True:
71
+ try:
72
+ user_input: str = input(
73
+ f"Hello! Please type in \"help\" to see a list of commands. Otherwise, please type in a valid command.\n"
74
+ )
75
+ user_input = user_input.strip()
76
+ match user_input:
77
+ case "help":
78
+ print(
79
+ """
80
+ The valid commands are:
81
+ - folder
82
+ Allows you to specify a folder containing the image files for the manga you want to process.
83
+ Also optionally allows you to give the manga a name. Otherwise the folder name will be used.
84
+ Supported file formats for images in folder: .jpg, .jpeg, .png, .bmp, .tiff
85
+ And of course,
86
+ - help
87
+ Which you are currently using.
88
+ """
89
+ )
90
+ case "folder":
91
+ target_folder: str = input("Please input a target folder.\n")
92
+ if os.path.isdir(target_folder):
93
+ if main(target_folder):
94
+ print("Success! Please press Ctrl+C to exit.")
95
+ else:
96
+ print("Something went wrong.")
97
+ else:
98
+ print("Please input a valid folder.")
99
+ case _:
100
+ print("That was not a valid command.")
101
+ except KeyboardInterrupt:
102
+ print("\nGoodbye!")
103
+ exit(0)
@@ -0,0 +1,56 @@
1
+ Metadata-Version: 2.4
2
+ Name: comic_ocr_reader
3
+ Version: 0.0.2
4
+ Summary: A Python package made for processing Japanese manga into a format usable with web-based on-screen dictionaries like Yomitan.
5
+ Project-URL: Homepage, https://github.com/HagantaRG/comic-ocr
6
+ Author-email: HRG <rhaganta@gmail.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE.MD
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.9
12
+ Requires-Dist: easyocr~=1.7.2
13
+ Requires-Dist: loguru
14
+ Requires-Dist: manga-ocr
15
+ Requires-Dist: numpy~=2.5.1
16
+ Requires-Dist: pillow~=12.3.0
17
+ Requires-Dist: tqdm
18
+ Description-Content-Type: text/markdown
19
+
20
+ # Jelly's Manga Reading Thingy.
21
+ This is my own rendition of the excellent [Mokuro](https://github.com/kha-white/mokuro) project, made mostly just to do it.
22
+ That being said, if you have any suggestions, please give me a heads-up and I will be happy to implement it. Probably.
23
+
24
+ ## Usage
25
+ 1. Prepare a folder containing the images you would like to process. As of v.0.0.1 the images in this folder must be named the page number you would like that image to be.
26
+ (e.g. the PNG image you would like to use as the second page should be titled "2.png")
27
+ The name of the folder will be the name of the resultant HTML file. (e.g. if your folder is titled "Naruto" the output HTML file will be "Naruto.html" )
28
+ 2. Run comic-reader-ocr and enter the "folder" command.
29
+ 3. Enter the absolute path of the folder from step 1 and wait for comic-reader-ocr to process all the images.
30
+ 4. Once finished, the resulting HTML file will be placed in an outputs folder within the folder from step 1.
31
+ 5. Open the resulting HTML using your web browser of choice.
32
+
33
+ ## FAQs (as decided by Myself)
34
+ 1. Is this a worse version of various other projects (e.g. [Mokuro](https://github.com/kha-white/mokuro))?
35
+
36
+ - Yes.
37
+
38
+ 2. Do you know how to like. Write things. That work?
39
+
40
+ - No.
41
+
42
+ 3. Why did you do this?
43
+
44
+ - As a learning exercise, mostly. Plus, I like trying to reinvent wheels.
45
+
46
+ 4. Can I make suggestions?
47
+
48
+ - Yes.
49
+
50
+ 5. Did you use AI for this?
51
+
52
+ - Yes. Most of the HTML and JS was AI generated, as unfortunately I really *really* don't like looking at either of those things.
53
+
54
+ 6. Are you going to try to make this a webapp because that probably makes a lot of sense or just. Like. Something that isn't Python so that it's easier to distribute or something?
55
+
56
+ - Yes. I'll probably try to rewrite this in Rust or do something like the [mokuro-reader](https://github.com/Gnathonic/mokuro-reader) project.
@@ -0,0 +1,11 @@
1
+ comic_ocr_reader/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ comic_ocr_reader/filepaths.py,sha256=EfdHE04NexfQQ6TasbZefDZ-IvFmBOUBLcz8UHcthm0,79
3
+ comic_ocr_reader/main.py,sha256=AySN1rtI4ZSq1h6WBe5G2QzfEyLGCt1eus1JcZnzlgA,3448
4
+ comic_ocr_reader/functions/__init__.py,sha256=6ZpVEsVXP3UOUfSz3J9cMKiyCxHyoP9tk6s7K3zC95M,1887
5
+ comic_ocr_reader/html_utils/__init__.py,sha256=cJ_Ty22JDeF69jkvDoit2a3BqdT4GVYjPMY9nb2sTjA,3642
6
+ comic_ocr_reader/html_utils/html_template.html,sha256=XvrnZVtfHyVXeI-KaXDXY9uv1rLlztHQfmSHmRY-vxI,21717
7
+ comic_ocr_reader/img_utils/__init__.py,sha256=vjU13Y2FrcQ-BXraOqgngMokzBrUrHR6BMmjLl8bugI,2527
8
+ comic_ocr_reader-0.0.2.dist-info/METADATA,sha256=a_dZSeHAqoyuw0JCDp8ab0hk-62Y3xqckf4b3FWyu0M,2545
9
+ comic_ocr_reader-0.0.2.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
10
+ comic_ocr_reader-0.0.2.dist-info/licenses/LICENSE.MD,sha256=ziuoPeOm0imLaM2XWeL7s5zZ6iaqWj3EJFTQ-MULm30,1094
11
+ comic_ocr_reader-0.0.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Haganta R. Ginting
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.