Krixter commited on
Commit
082ce73
·
verified ·
1 Parent(s): 56645f3

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -851
app.py DELETED
@@ -1,851 +0,0 @@
1
- import gradio as gr
2
- import os
3
- import tempfile
4
- import requests
5
- import subprocess
6
- import zipfile
7
- import shutil
8
- import time
9
- import asyncio
10
- import re
11
- import json
12
- from collections import defaultdict
13
- from bs4 import BeautifulSoup
14
- from concurrent.futures import ThreadPoolExecutor, as_completed
15
-
16
- # ─── CONFIGURATION ──────────────────────────────────────────────────────────
17
- FIXED_SPEED = 1.6
18
- THREADS = 10
19
- MAX_CHUNK = 200
20
-
21
- # ─── CONCURRENCY GATES ──────────────────────────────────────────────────────
22
- download_door = asyncio.Semaphore(1)
23
- kitchen_door = asyncio.Semaphore(1)
24
-
25
-
26
- # ════════════════════════════════════════════════════════════════════════════
27
- # TEXT EXTRACTION
28
- # ════════════════════════════════════════════════════════════════════════════
29
-
30
- def extract_local_text(path, temp_dir):
31
- content = ""
32
- ext = os.path.splitext(path)[1].lower()
33
- try:
34
- if ext == ".txt":
35
- with open(path, "r", encoding="utf-8", errors="ignore") as f:
36
- content = f.read()
37
- elif ext == ".epub":
38
- with zipfile.ZipFile(path, "r") as z:
39
- for filename in sorted(z.namelist()):
40
- if filename.endswith((".html", ".xhtml")):
41
- with z.open(filename) as f:
42
- soup = BeautifulSoup(f.read(), "html.parser")
43
- part = soup.get_text(separator="\n")
44
- if part:
45
- content += part + "\n"
46
- elif ext == ".pdf":
47
- import PyPDF2
48
- reader = PyPDF2.PdfReader(path)
49
- for page in reader.pages:
50
- txt = page.extract_text()
51
- if txt:
52
- content += txt + "\n"
53
- except Exception:
54
- return None
55
-
56
- if not content:
57
- return None
58
-
59
- content = re.sub(r"[ \t]+", " ", content)
60
- content = re.sub(r"\n\s*\n", "\n\n", content)
61
-
62
- out = os.path.join(temp_dir, "extracted.txt")
63
- with open(out, "w", encoding="utf-8") as f:
64
- f.write(content)
65
- return out
66
-
67
-
68
- # ════════════════════════════════════════════════════════════════════════════
69
- # TTS ENGINE
70
- # ════════════════════════════════════════════════════════════════════════════
71
-
72
- class GoogleTTSEngine:
73
- def split_text(self, text, max_len=MAX_CHUNK):
74
- chunks = []
75
- while text:
76
- if len(text) <= max_len:
77
- chunks.append(text.strip())
78
- break
79
- best_i = -1
80
- for punct in [". ", "! ", "? ", "; "]:
81
- i = text[:max_len].rfind(punct)
82
- if i > best_i:
83
- best_i = i
84
- if best_i == -1:
85
- best_i = text[:max_len].rfind(" ")
86
- if best_i == -1:
87
- best_i = max_len
88
- else:
89
- best_i += 1
90
- chunks.append(text[:best_i].strip())
91
- text = text[best_i:].lstrip()
92
- return [c for c in chunks if c]
93
-
94
- def strip_id3(self, mp3_data):
95
- if mp3_data[:3] == b"ID3":
96
- size = (
97
- (mp3_data[6] & 0x7F) << 21
98
- | (mp3_data[7] & 0x7F) << 14
99
- | (mp3_data[8] & 0x7F) << 7
100
- | (mp3_data[9] & 0x7F)
101
- )
102
- mp3_data = mp3_data[10 + size:]
103
- if len(mp3_data) > 128 and mp3_data[-128:-125] == b"TAG":
104
- mp3_data = mp3_data[:-128]
105
- return mp3_data
106
-
107
- def download_chunk(self, text):
108
- url = "https://translate.google.com/translate_tts"
109
- params = {"ie": "UTF-8", "q": text, "tl": "en-IN", "client": "tw-ob"}
110
- headers = {"User-Agent": "Mozilla/5.0"}
111
- for _ in range(5):
112
- try:
113
- r = requests.get(url, params=params, headers=headers, timeout=8)
114
- if r.status_code == 200:
115
- return self.strip_id3(r.content)
116
- except Exception:
117
- time.sleep(0.5)
118
- return None
119
-
120
-
121
- # ════════════════════════════════════════════════════════════════════════════
122
- # AUDIO HELPERS
123
- # ════════════════════════════════════════════════════════════════════════════
124
-
125
- def get_duration_ms(path):
126
- result = subprocess.run(
127
- ["ffprobe", "-v", "error",
128
- "-show_entries", "format=duration",
129
- "-of", "default=noprint_wrappers=1:nokey=1", path],
130
- stdout=subprocess.PIPE, stderr=subprocess.PIPE,
131
- )
132
- try:
133
- return int(float(result.stdout.strip()) * 1000)
134
- except Exception:
135
- return 0
136
-
137
-
138
- def process_chunk_audio(args):
139
- in_path, proc_path, speed = args
140
- ret = subprocess.run(
141
- ["ffmpeg", "-y", "-i", in_path,
142
- "-af", "atempo=" + str(speed),
143
- "-threads", "1", proc_path],
144
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
145
- )
146
- if ret.returncode != 0 or not os.path.exists(proc_path):
147
- shutil.copy2(in_path, proc_path)
148
- return get_duration_ms(proc_path)
149
-
150
-
151
- # ════════════════════════════════════════════════════════════════════════════
152
- # CHAPTER PARSING
153
- # ════════════════════════════════════════════════════════════════════════════
154
-
155
- def parse_chapters(full_text):
156
- splits = re.split(
157
- r"(?i)(\b(?:chapter|ch\.?)\s*[-:]?\s*\d+\b[^\n]*|\b\d+\s*:(?!\d)[^\n]*)",
158
- full_text,
159
- )
160
- chapters = []
161
-
162
- if splits[0].strip():
163
- chapters.append(["Intro", splits[0].strip()])
164
-
165
- for i in range(1, len(splits), 2):
166
- title = splits[i].strip()
167
- body = splits[i + 1].strip() if i + 1 < len(splits) else ""
168
-
169
- if len(title) > 100:
170
- body = title[100:] + " " + body
171
- title = title[:100] + "..."
172
-
173
- num_match = re.search(r"\d+", title)
174
- current_num = num_match.group() if num_match else title
175
-
176
- if chapters:
177
- prev_nm = re.search(r"\d+", chapters[-1][0])
178
- prev_num = prev_nm.group() if prev_nm else chapters[-1][0]
179
-
180
- if current_num == prev_num:
181
- chapters[-1][1] += ("\n" + body)
182
- continue
183
- if len(chapters[-1][1]) < 150:
184
- chapters[-1][1] += ("\n" + title + ". " + body)
185
- chapters[-1][0] = title
186
- continue
187
-
188
- chapters.append([title, (title + ". " + body)])
189
-
190
- if not chapters:
191
- chapters = [["Full Book", full_text]]
192
-
193
- return chapters
194
-
195
-
196
- # ════════════════════════════════════════════════════════════════════════════
197
- # MAIN SYNC PIPELINE
198
- # ════════════════════════════════════════════════════════════════════════════
199
-
200
- def sync_process_book(file_path, temp_dir, progress_obj, book_idx, total_books):
201
- text_file = extract_local_text(file_path, temp_dir)
202
- if not text_file:
203
- return None, None, None, None
204
-
205
- base_name = os.path.splitext(os.path.basename(file_path))[0]
206
- book_label = "[Book %d/%d]" % (book_idx, total_books)
207
-
208
- with open(text_file, "r", encoding="utf-8") as f:
209
- full_text = f.read()
210
-
211
- chapters = parse_chapters(full_text)
212
- engine = GoogleTTSEngine()
213
-
214
- all_chunks = []
215
- for c_idx, (_, c_text) in enumerate(chapters):
216
- for local_idx, chunk_text in enumerate(engine.split_text(c_text)):
217
- all_chunks.append((c_idx, local_idx, chunk_text))
218
-
219
- chunk_text_map = {(c, l): t for c, l, t in all_chunks}
220
- total_chunks = len(all_chunks)
221
-
222
- chunk_dir = os.path.join(temp_dir, "chunks_raw")
223
- proc_dir = os.path.join(temp_dir, "chunks_proc")
224
- os.makedirs(chunk_dir, exist_ok=True)
225
- os.makedirs(proc_dir, exist_ok=True)
226
-
227
- # ── PHASE 1: DOWNLOAD (parallel) ─────────────────────────────────────
228
- start_time = time.time()
229
- completed = 0
230
-
231
- with ThreadPoolExecutor(max_workers=THREADS) as pool:
232
- futures = {
233
- pool.submit(engine.download_chunk, text): (c_idx, local_idx)
234
- for c_idx, local_idx, text in all_chunks
235
- }
236
- for fut in as_completed(futures):
237
- c_idx, local_idx = futures[fut]
238
- data = fut.result()
239
- if data:
240
- fpath = os.path.join(chunk_dir, "c%03d_%05d.mp3" % (c_idx, local_idx))
241
- with open(fpath, "wb") as af:
242
- af.write(data)
243
- completed += 1
244
- elapsed = time.time() - start_time
245
- avg = elapsed / completed
246
- eta = avg * (total_chunks - completed)
247
- progress_obj(
248
- completed / (total_chunks * 2),
249
- desc="%s Downloading: %d/%d | ETA %02d:%02d" % (
250
- book_label, completed, total_chunks,
251
- int(eta // 60), int(eta % 60)),
252
- )
253
-
254
- # ── PHASE 2: SPEED-PROCESS (parallel ffmpeg) ──────────────────────────
255
- downloaded = sorted(f for f in os.listdir(chunk_dir) if f.endswith(".mp3"))
256
-
257
- process_args = [
258
- (os.path.join(chunk_dir, cf), os.path.join(proc_dir, cf), FIXED_SPEED)
259
- for cf in downloaded
260
- ]
261
-
262
- durations = {}
263
- with ThreadPoolExecutor(max_workers=THREADS) as pool:
264
- fut_map = {pool.submit(process_chunk_audio, a): a[1] for a in process_args}
265
- proc_done = 0
266
- for fut in as_completed(fut_map):
267
- proc_path = fut_map[fut]
268
- dur_ms = fut.result()
269
- durations[os.path.basename(proc_path)] = dur_ms
270
- proc_done += 1
271
- progress_obj(
272
- 0.50 + (proc_done / max(len(downloaded), 1)) * 0.30,
273
- desc="%s Speed-processing: %d/%d" % (book_label, proc_done, len(downloaded)),
274
- )
275
-
276
- # ── PHASE 3: BUILD TIMESTAMPS ─────────────────────────────────────────
277
- chunk_metadata = []
278
- current_ms = 0
279
- chunk_idx = 0
280
-
281
- for cf in downloaded:
282
- m = re.match(r"c(\d+)_(\d+)\.mp3", cf)
283
- if not m:
284
- continue
285
- c_idx = int(m.group(1))
286
- local_idx = int(m.group(2))
287
- dur_ms = durations.get(cf, 0)
288
- text = chunk_text_map.get((c_idx, local_idx), "")
289
-
290
- chunk_metadata.append({
291
- "idx": chunk_idx,
292
- "cIdx": c_idx,
293
- "text": text,
294
- "start": current_ms,
295
- "end": current_ms + dur_ms,
296
- })
297
- current_ms += dur_ms
298
- chunk_idx += 1
299
-
300
- chunks_by_chapter = defaultdict(list)
301
- for cm in chunk_metadata:
302
- chunks_by_chapter[cm["cIdx"]].append(cm)
303
-
304
- chapter_info = []
305
- for c_idx, (title, _) in enumerate(chapters):
306
- first = chunks_by_chapter[c_idx][0] if chunks_by_chapter[c_idx] else None
307
- chapter_info.append({
308
- "idx": c_idx,
309
- "title": title,
310
- "start": first["start"] if first else 0,
311
- "chunkStart": first["idx"] if first else 0,
312
- })
313
-
314
- # ── PHASE 4: FINAL MERGE (stream-copy concat) ─────────────────────────
315
- progress_obj(0.85, desc=book_label + " Merging audio...")
316
-
317
- concat_path = os.path.join(temp_dir, "concat.txt")
318
- with open(concat_path, "w") as f:
319
- for cf in downloaded:
320
- p = os.path.join(proc_dir, cf)
321
- if os.path.exists(p):
322
- f.write("file '" + os.path.abspath(p).replace("\\", "/") + "'\n")
323
-
324
- output_mp3 = os.path.join(tempfile.gettempdir(), base_name + "_Audio.mp3")
325
- subprocess.run(
326
- ["ffmpeg", "-y", "-f", "concat", "-safe", "0",
327
- "-i", concat_path, "-c", "copy", output_mp3],
328
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
329
- )
330
-
331
- shutil.rmtree(temp_dir)
332
- return output_mp3, chunk_metadata, chapter_info, base_name
333
-
334
-
335
- # ════════════════════════════════════════════════════════════════════════════
336
- # HTML TEMPLATE
337
- #
338
- # Stored as a plain (non-f) string. Dynamic content is injected with
339
- # .replace() using __SENTINEL__ tokens — no curly-brace escaping needed,
340
- # so CSS / JS never causes SyntaxErrors regardless of Python version.
341
- # ════════════════════════════════════════════════════════════════════════════
342
-
343
- _HTML = (
344
- "<!DOCTYPE html>\n"
345
- '<html lang="en" data-theme="light">\n'
346
- "<head>\n"
347
- ' <meta charset="UTF-8">\n'
348
- ' <meta name="viewport" content="width=device-width, initial-scale=1.0">\n'
349
- " <title>__BOOK_TITLE__ &mdash; WebBook</title>\n"
350
- " <style>\n"
351
- " :root {\n"
352
- " --bg: #f5f0e8;\n"
353
- " --text: #2c2c2c;\n"
354
- " --border: #e0d9cc;\n"
355
- " --ch-title: #1a1a2e;\n"
356
- " --hl-bg: #ffe082;\n"
357
- " --hl-text: #1a1200;\n"
358
- " --chunk-hover: rgba(200,134,10,0.13);\n"
359
- " --sb-bg: #1a1a2e;\n"
360
- " --sb-text: #cccce0;\n"
361
- " --sb-hover: #2d2d4a;\n"
362
- " --sb-accent: #e8b86d;\n"
363
- " --pl-bg: rgba(14,14,30,0.97);\n"
364
- " --accent: #e8b86d;\n"
365
- " }\n"
366
- " [data-theme=dark] {\n"
367
- " --bg: #0f0f1a;\n"
368
- " --text: #e0e0f0;\n"
369
- " --border: #2d2d4a;\n"
370
- " --ch-title: #e8b86d;\n"
371
- " --hl-bg: #5c4400;\n"
372
- " --hl-text: #ffe082;\n"
373
- " --chunk-hover: rgba(232,184,109,0.1);\n"
374
- " }\n"
375
- " *,*::before,*::after{box-sizing:border-box;margin:0;padding:0}\n"
376
- " html{font-size:18px;scroll-behavior:smooth}\n"
377
- " body{\n"
378
- ' font-family:Georgia,"Times New Roman",serif;\n'
379
- " background:var(--bg);color:var(--text);\n"
380
- " overflow-x:hidden;transition:background .25s,color .25s;\n"
381
- " }\n"
382
- " #player-bar{\n"
383
- " position:fixed;top:0;left:0;right:0;height:62px;\n"
384
- " background:var(--pl-bg);\n"
385
- " backdrop-filter:blur(18px);-webkit-backdrop-filter:blur(18px);\n"
386
- " display:flex;align-items:center;gap:10px;\n"
387
- " padding:0 14px;z-index:1000;\n"
388
- " box-shadow:0 2px 24px rgba(0,0,0,.5);\n"
389
- " }\n"
390
- " #audio-el{display:none}\n"
391
- " .bk-meta{display:flex;flex-direction:column;flex:0 0 auto;max-width:170px}\n"
392
- " #bk-title-pl{\n"
393
- " font-size:.78rem;font-weight:bold;color:var(--accent);\n"
394
- " white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-family:sans-serif;\n"
395
- " }\n"
396
- " #ch-ind{\n"
397
- " font-size:.68rem;color:rgba(255,255,255,.42);\n"
398
- " white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-family:sans-serif;\n"
399
- " }\n"
400
- " .pl-btn{\n"
401
- " background:none;border:none;color:#fff;\n"
402
- " cursor:pointer;font-size:1rem;padding:6px 8px;\n"
403
- " border-radius:50%;transition:background .15s;flex-shrink:0;\n"
404
- " }\n"
405
- " .pl-btn:hover{background:rgba(255,255,255,.1)}\n"
406
- " #btn-play{font-size:1.3rem}\n"
407
- " #seek-wrap{flex:1;display:flex;align-items:center;gap:8px;min-width:0}\n"
408
- " input[type=range]{\n"
409
- " -webkit-appearance:none;height:4px;\n"
410
- " border-radius:2px;outline:none;cursor:pointer;\n"
411
- " }\n"
412
- " input[type=range]::-webkit-slider-thumb{\n"
413
- " -webkit-appearance:none;width:13px;height:13px;\n"
414
- " border-radius:50%;background:var(--accent);cursor:pointer;\n"
415
- " }\n"
416
- " #seek-sl{\n"
417
- " flex:1;\n"
418
- " background:linear-gradient(to right,var(--accent) 0%,rgba(255,255,255,.18) 0%);\n"
419
- " }\n"
420
- " #time-disp{\n"
421
- " font-size:.7rem;color:rgba(255,255,255,.6);\n"
422
- " white-space:nowrap;font-family:monospace;flex-shrink:0;\n"
423
- " }\n"
424
- " .ctrl-grp{display:flex;align-items:center;gap:5px;flex-shrink:0}\n"
425
- " .ctrl-lbl{font-size:.67rem;color:rgba(255,255,255,.42);font-family:sans-serif}\n"
426
- " #spd-sl{width:64px;background:rgba(255,255,255,.18)}\n"
427
- " #spd-val{font-size:.7rem;color:rgba(255,255,255,.7);font-family:monospace;min-width:34px}\n"
428
- " #vol-sl{width:68px;background:rgba(255,255,255,.18)}\n"
429
- " #vol-ico{cursor:pointer;font-size:.9rem}\n"
430
- " #theme-btn{\n"
431
- " background:none;border:1px solid rgba(255,255,255,.2);\n"
432
- " color:#fff;padding:3px 9px;border-radius:20px;\n"
433
- " cursor:pointer;font-size:.7rem;font-family:sans-serif;flex-shrink:0;\n"
434
- " }\n"
435
- " #sb-toggle{\n"
436
- " display:none;background:none;border:none;\n"
437
- " color:#fff;font-size:1.2rem;cursor:pointer;padding:4px 8px;\n"
438
- " }\n"
439
- " #layout{display:flex;margin-top:62px;min-height:calc(100vh - 62px)}\n"
440
- " #sidebar{\n"
441
- " width:255px;flex-shrink:0;\n"
442
- " background:var(--sb-bg);color:var(--sb-text);\n"
443
- " position:fixed;top:62px;left:0;bottom:0;\n"
444
- " overflow-y:auto;overflow-x:hidden;z-index:100;\n"
445
- " display:flex;flex-direction:column;\n"
446
- " transition:transform .3s ease;\n"
447
- " }\n"
448
- " #sidebar::-webkit-scrollbar{width:4px}\n"
449
- " #sidebar::-webkit-scrollbar-thumb{background:rgba(255,255,255,.12);border-radius:2px}\n"
450
- " #sb-hdr{padding:18px 16px 14px;border-bottom:1px solid rgba(255,255,255,.07)}\n"
451
- " #bk-title-sb{\n"
452
- " font-size:.9rem;font-weight:bold;\n"
453
- " color:var(--sb-accent);line-height:1.3;font-family:Georgia,serif;\n"
454
- " }\n"
455
- " #sb-sub{\n"
456
- " font-size:.67rem;color:rgba(255,255,255,.35);\n"
457
- " margin-top:4px;text-transform:uppercase;\n"
458
- " letter-spacing:.06em;font-family:sans-serif;\n"
459
- " }\n"
460
- " #ch-list{list-style:none;padding:6px 0;flex:1}\n"
461
- " .sb-item{\n"
462
- " padding:9px 16px;cursor:pointer;\n"
463
- " font-size:.8rem;font-family:sans-serif;line-height:1.4;\n"
464
- " border-left:3px solid transparent;transition:all .15s;\n"
465
- " }\n"
466
- " .sb-item:hover{background:var(--sb-hover);color:#fff}\n"
467
- " .sb-item.active{\n"
468
- " color:var(--sb-accent);border-left-color:var(--sb-accent);\n"
469
- " background:rgba(232,184,109,.08);font-weight:600;\n"
470
- " }\n"
471
- " #content{margin-left:255px;flex:1;padding:44px 64px 100px;max-width:900px}\n"
472
- " .chapter{margin-bottom:60px}\n"
473
- " .chapter-title{\n"
474
- " font-family:Georgia,serif;font-size:1.45rem;font-weight:bold;\n"
475
- " color:var(--ch-title);margin-bottom:18px;padding-bottom:12px;\n"
476
- " border-bottom:2px solid var(--border);line-height:1.3;\n"
477
- " }\n"
478
- " .chapter-body{line-height:1.9;font-size:1rem;white-space:pre-wrap;word-wrap:break-word;font-family:inherit}\n"
479
- " .chunk{\n"
480
- " cursor:pointer;border-radius:3px;padding:1px 0;\n"
481
- " display:inline;transition:background .12s,color .12s;white-space:normal;\n"
482
- " }\n"
483
- " .chunk:hover{background:var(--chunk-hover)}\n"
484
- " .chunk.active{\n"
485
- " background:var(--hl-bg);color:var(--hl-text);\n"
486
- " padding:1px 3px;margin:0 -3px;\n"
487
- " }\n"
488
- " @media(max-width:780px){\n"
489
- " #sb-toggle{display:block}\n"
490
- " #sidebar{transform:translateX(-100%)}\n"
491
- " #sidebar.open{transform:translateX(0)}\n"
492
- " #content{margin-left:0;padding:24px 18px 80px}\n"
493
- " .bk-meta,#ch-ind,.ctrl-grp{display:none}\n"
494
- " }\n"
495
- " </style>\n"
496
- "</head>\n"
497
- "<body>\n"
498
- '\n<audio id="audio-el" src="__AUDIO_SRC__" preload="metadata"></audio>\n'
499
- "\n"
500
- '<header id="player-bar">\n'
501
- ' <button id="sb-toggle" onclick="toggleSB()">&#9776;</button>\n'
502
- ' <div class="bk-meta">\n'
503
- ' <span id="bk-title-pl">__BOOK_TITLE__</span>\n'
504
- ' <span id="ch-ind">Loading&hellip;</span>\n'
505
- " </div>\n"
506
- ' <button class="pl-btn" onclick="seekRel(-10)" title="Back 10s">&#9198;</button>\n'
507
- ' <button class="pl-btn" id="btn-play" onclick="togglePlay()" title="Space=play/pause">&#9654;</button>\n'
508
- ' <button class="pl-btn" onclick="seekRel(10)" title="Forward 10s">&#9197;</button>\n'
509
- ' <div id="seek-wrap">\n'
510
- ' <input type="range" id="seek-sl" min="0" max="10000" value="0"\n'
511
- ' oninput="onSeekInput(this)" onchange="onSeekChange(this)">\n'
512
- " </div>\n"
513
- ' <span id="time-disp">0:00 / 0:00</span>\n'
514
- ' <div class="ctrl-grp">\n'
515
- ' <span class="ctrl-lbl">Speed</span>\n'
516
- ' <input type="range" id="spd-sl" min="0.5" max="2.5" step="0.1" value="1.0"\n'
517
- ' oninput="onSpdChange(this)">\n'
518
- ' <span id="spd-val">1.0&times;</span>\n'
519
- " </div>\n"
520
- ' <div class="ctrl-grp">\n'
521
- ' <span id="vol-ico" onclick="toggleMute()">&#128266;</span>\n'
522
- ' <input type="range" id="vol-sl" min="0" max="1" step="0.01" value="1"\n'
523
- ' oninput="onVolChange(this)">\n'
524
- " </div>\n"
525
- ' <button id="theme-btn" onclick="toggleTheme()">&#127769; Dark</button>\n'
526
- "</header>\n"
527
- "\n"
528
- '<div id="layout">\n'
529
- ' <nav id="sidebar">\n'
530
- ' <div id="sb-hdr">\n'
531
- ' <h1 id="bk-title-sb">__BOOK_TITLE__</h1>\n'
532
- ' <p id="sb-sub">Table of Contents</p>\n'
533
- " </div>\n"
534
- ' <ul id="ch-list">\n'
535
- "__SIDEBAR_ITEMS__\n"
536
- " </ul>\n"
537
- " </nav>\n"
538
- ' <main id="content">\n'
539
- "__CHAPTERS_HTML__\n"
540
- " </main>\n"
541
- "</div>\n"
542
- "\n"
543
- "<script>\n"
544
- "var CHUNKS = __CHUNKS_JSON__;\n"
545
- "var CHAPTERS = __CHAPTERS_JSON__;\n"
546
- "\n"
547
- "var audio = document.getElementById('audio-el');\n"
548
- "var btnPlay = document.getElementById('btn-play');\n"
549
- "var seekSl = document.getElementById('seek-sl');\n"
550
- "var timeDisp = document.getElementById('time-disp');\n"
551
- "var spdSl = document.getElementById('spd-sl');\n"
552
- "var spdVal = document.getElementById('spd-val');\n"
553
- "var volSl = document.getElementById('vol-sl');\n"
554
- "var chInd = document.getElementById('ch-ind');\n"
555
- "var sbItems = Array.from(document.querySelectorAll('.sb-item'));\n"
556
- "var chunkEls = document.querySelectorAll('.chunk');\n"
557
- "\n"
558
- "var activeChunk = -1, activeCh = -1;\n"
559
- "var isSeeking = false, scrollTmr = null, isDark = false;\n"
560
- "\n"
561
- "function findChunkAt(ms) {\n"
562
- " var lo = 0, hi = CHUNKS.length - 1;\n"
563
- " while (lo <= hi) {\n"
564
- " var mid = (lo + hi) >> 1;\n"
565
- " if (CHUNKS[mid].end <= ms) { lo = mid + 1; }\n"
566
- " else if (CHUNKS[mid].start > ms) { hi = mid - 1; }\n"
567
- " else { return mid; }\n"
568
- " }\n"
569
- " return -1;\n"
570
- "}\n"
571
- "\n"
572
- "function findChapterAt(ms) {\n"
573
- " var best = 0;\n"
574
- " for (var i = 0; i < CHAPTERS.length; i++) {\n"
575
- " if (CHAPTERS[i].start <= ms) { best = i; } else { break; }\n"
576
- " }\n"
577
- " return best;\n"
578
- "}\n"
579
- "\n"
580
- "audio.addEventListener('timeupdate', function() {\n"
581
- " if (isSeeking) { return; }\n"
582
- " var ms = audio.currentTime * 1000;\n"
583
- " var total = (audio.duration || 0) * 1000 || 1;\n"
584
- " var pct = ms / total;\n"
585
- " seekSl.value = pct * 10000;\n"
586
- " updateGrad(pct);\n"
587
- " timeDisp.textContent = fmt(audio.currentTime) + ' / ' + fmt(audio.duration || 0);\n"
588
- " var ni = findChunkAt(ms);\n"
589
- " if (ni !== activeChunk) {\n"
590
- " if (activeChunk >= 0) {\n"
591
- " var prev = document.querySelector('[data-idx=\"' + activeChunk + '\"]');\n"
592
- " if (prev) { prev.classList.remove('active'); }\n"
593
- " }\n"
594
- " if (ni >= 0) {\n"
595
- " var el = document.querySelector('[data-idx=\"' + ni + '\"]');\n"
596
- " if (el) {\n"
597
- " el.classList.add('active');\n"
598
- " if (!scrollTmr) {\n"
599
- " scrollTmr = setTimeout(function() {\n"
600
- " el.scrollIntoView({ behavior: 'smooth', block: 'center' });\n"
601
- " scrollTmr = null;\n"
602
- " }, 300);\n"
603
- " }\n"
604
- " }\n"
605
- " }\n"
606
- " activeChunk = ni;\n"
607
- " }\n"
608
- " var ci = findChapterAt(ms);\n"
609
- " if (ci !== activeCh) {\n"
610
- " activeCh = ci;\n"
611
- " if (CHAPTERS[ci]) { chInd.textContent = CHAPTERS[ci].title; }\n"
612
- " sbItems.forEach(function(e, i) { e.classList.toggle('active', i === ci); });\n"
613
- " }\n"
614
- "});\n"
615
- "\n"
616
- "audio.addEventListener('play', function() { btnPlay.innerHTML = '&#9646;&#9646;'; });\n"
617
- "audio.addEventListener('pause', function() { btnPlay.innerHTML = '&#9654;'; });\n"
618
- "audio.addEventListener('ended', function() { btnPlay.innerHTML = '&#9654;'; });\n"
619
- "audio.addEventListener('loadedmetadata', function() {\n"
620
- " timeDisp.textContent = '0:00 / ' + fmt(audio.duration);\n"
621
- "});\n"
622
- "\n"
623
- "function togglePlay() { audio.paused ? audio.play() : audio.pause(); }\n"
624
- "function seekRel(s) { audio.currentTime = Math.max(0, Math.min(audio.duration||0, audio.currentTime+s)); }\n"
625
- "\n"
626
- "function onSeekInput(s) {\n"
627
- " isSeeking = true;\n"
628
- " var pct = s.value / 10000;\n"
629
- " updateGrad(pct);\n"
630
- " timeDisp.textContent = fmt(pct*(audio.duration||0)) + ' / ' + fmt(audio.duration||0);\n"
631
- "}\n"
632
- "function onSeekChange(s) {\n"
633
- " audio.currentTime = (s.value/10000)*(audio.duration||0);\n"
634
- " isSeeking = false;\n"
635
- "}\n"
636
- "function onSpdChange(s) {\n"
637
- " audio.playbackRate = parseFloat(s.value);\n"
638
- " spdVal.textContent = parseFloat(s.value).toFixed(1) + '\\u00d7';\n"
639
- "}\n"
640
- "function onVolChange(s) {\n"
641
- " audio.volume = parseFloat(s.value);\n"
642
- " document.getElementById('vol-ico').textContent = audio.volume===0 ? '\\ud83d\\udd07' : '\\ud83d\\udd0a';\n"
643
- "}\n"
644
- "function toggleMute() {\n"
645
- " audio.muted = !audio.muted;\n"
646
- " document.getElementById('vol-ico').textContent = audio.muted ? '\\ud83d\\udd07' : '\\ud83d\\udd0a';\n"
647
- "}\n"
648
- "\n"
649
- "chunkEls.forEach(function(el) {\n"
650
- " el.addEventListener('click', function() {\n"
651
- " var ms = parseInt(el.dataset.start, 10);\n"
652
- " if (ms < 0) { return; }\n"
653
- " audio.currentTime = ms / 1000;\n"
654
- " if (audio.paused) { audio.play(); }\n"
655
- " });\n"
656
- "});\n"
657
- "\n"
658
- "sbItems.forEach(function(el) {\n"
659
- " el.addEventListener('click', function() {\n"
660
- " audio.currentTime = parseInt(el.dataset.start,10) / 1000;\n"
661
- " if (audio.paused) { audio.play(); }\n"
662
- " if (window.innerWidth <= 780) { document.getElementById('sidebar').classList.remove('open'); }\n"
663
- " });\n"
664
- "});\n"
665
- "\n"
666
- "document.addEventListener('keydown', function(e) {\n"
667
- " if (e.target.tagName==='INPUT') { return; }\n"
668
- " if (e.key===' ') { e.preventDefault(); togglePlay(); }\n"
669
- " else if (e.key==='ArrowRight') { seekRel(10); }\n"
670
- " else if (e.key==='ArrowLeft') { seekRel(-10); }\n"
671
- " else if (e.key==='ArrowUp') { audio.volume=Math.min(1,audio.volume+0.1); volSl.value=audio.volume; }\n"
672
- " else if (e.key==='ArrowDown') { audio.volume=Math.max(0,audio.volume-0.1); volSl.value=audio.volume; }\n"
673
- "});\n"
674
- "\n"
675
- "function toggleTheme() {\n"
676
- " isDark = !isDark;\n"
677
- " document.documentElement.setAttribute('data-theme', isDark?'dark':'light');\n"
678
- " document.getElementById('theme-btn').innerHTML = isDark ? '&#9728; Light' : '&#127769; Dark';\n"
679
- "}\n"
680
- "function toggleSB() { document.getElementById('sidebar').classList.toggle('open'); }\n"
681
- "\n"
682
- "function fmt(sec) {\n"
683
- " if (!isFinite(sec)||sec<0) { return '0:00'; }\n"
684
- " var h=Math.floor(sec/3600), m=Math.floor((sec%3600)/60), s=Math.floor(sec%60);\n"
685
- " var p=function(n){return String(n).padStart(2,'0');};\n"
686
- " return h>0 ? h+':'+p(m)+':'+p(s) : m+':'+p(s);\n"
687
- "}\n"
688
- "function updateGrad(pct) {\n"
689
- " var v=(pct*100).toFixed(2)+'%';\n"
690
- " seekSl.style.background='linear-gradient(to right,var(--accent) '+v+',rgba(255,255,255,.18) '+v+')';\n"
691
- "}\n"
692
- "</script>\n"
693
- "</body>\n"
694
- "</html>\n"
695
- )
696
-
697
-
698
- # ══════════════════════════════════════════════════════���═════════════════════
699
- # HTML GENERATION
700
- # ════════════════════════════════════════════════════════════════════════════
701
-
702
- def _esc(text):
703
- return (text
704
- .replace("&", "&amp;")
705
- .replace("<", "&lt;")
706
- .replace(">", "&gt;")
707
- .replace('"', "&quot;"))
708
-
709
-
710
- def generate_webbook_html(chunk_metadata, chapter_info, base_name, audio_filename):
711
- chunks_by_chapter = defaultdict(list)
712
- for cm in chunk_metadata:
713
- chunks_by_chapter[cm["cIdx"]].append(cm)
714
-
715
- chapters_html = ""
716
- for ch in chapter_info:
717
- c_idx = ch["idx"]
718
- c_chunks = chunks_by_chapter[c_idx]
719
- chapters_html += (
720
- ' <section class="chapter" id="chapter-' + str(c_idx) + '">\n'
721
- ' <h2 class="chapter-title">' + _esc(ch["title"]) + '</h2>\n'
722
- ' <div class="chapter-body">\n'
723
- )
724
- for ck in c_chunks:
725
- chapters_html += (
726
- '<span class="chunk"'
727
- ' data-idx="' + str(ck["idx"]) + '"'
728
- ' data-start="' + str(ck["start"]) + '"'
729
- ' data-end="' + str(ck["end"]) + '">'
730
- + _esc(ck["text"]) + '</span> '
731
- )
732
- chapters_html += "\n </div>\n </section>\n"
733
-
734
- sidebar_items = "\n".join(
735
- ' <li class="sb-item"'
736
- ' data-chapter="' + str(ch["idx"]) + '"'
737
- ' data-start="' + str(ch["start"]) + '">'
738
- + _esc(ch["title"]) + '</li>'
739
- for ch in chapter_info
740
- )
741
-
742
- return (
743
- _HTML
744
- .replace("__BOOK_TITLE__", _esc(base_name))
745
- .replace("__AUDIO_SRC__", audio_filename)
746
- .replace("__SIDEBAR_ITEMS__", sidebar_items)
747
- .replace("__CHAPTERS_HTML__", chapters_html)
748
- .replace("__CHUNKS_JSON__", json.dumps(chunk_metadata, ensure_ascii=False))
749
- .replace("__CHAPTERS_JSON__", json.dumps(chapter_info, ensure_ascii=False))
750
- )
751
-
752
-
753
- # ════════════════════════════════════════════════════════════════════════════
754
- # WEBBOOK PACKAGING
755
- # ════════════════════════════════════════════════════════════════════════════
756
-
757
- def build_webbook(output_mp3, chunk_metadata, chapter_info, base_name):
758
- audio_filename = os.path.basename(output_mp3)
759
- html_str = generate_webbook_html(chunk_metadata, chapter_info, base_name, audio_filename)
760
-
761
- html_path = os.path.join(tempfile.gettempdir(), base_name + "_WebBook.html")
762
- with open(html_path, "w", encoding="utf-8") as f:
763
- f.write(html_str)
764
-
765
- zip_path = os.path.join(tempfile.gettempdir(), base_name + "_WebBook.zip")
766
- with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
767
- zf.write(html_path, arcname=os.path.basename(html_path))
768
- zf.write(output_mp3, arcname=audio_filename)
769
-
770
- return html_path, zip_path
771
-
772
-
773
- # ════════════════════════════════════════════════════════════════════════════
774
- # ASYNC ORCHESTRATION
775
- # ════════════════════════════════════════════════════════════════════════════
776
-
777
- async def process_single_book(file_path, progress_obj, book_idx, total_books):
778
- temp_dir = tempfile.mkdtemp()
779
-
780
- async with download_door:
781
- result = await asyncio.to_thread(
782
- sync_process_book,
783
- file_path, temp_dir, progress_obj, book_idx, total_books,
784
- )
785
-
786
- output_mp3, chunk_metadata, chapter_info, base_name = result
787
- if not output_mp3:
788
- return []
789
-
790
- async with kitchen_door:
791
- html_path, zip_path = await asyncio.to_thread(
792
- build_webbook, output_mp3, chunk_metadata, chapter_info, base_name,
793
- )
794
-
795
- return [zip_path, html_path, output_mp3]
796
-
797
-
798
- async def process_books(file_paths, progress=gr.Progress()):
799
- if not file_paths:
800
- yield []
801
- return
802
- if not isinstance(file_paths, list):
803
- file_paths = [file_paths]
804
-
805
- total = len(file_paths)
806
- tasks = [
807
- asyncio.create_task(process_single_book(f, progress, idx + 1, total))
808
- for idx, f in enumerate(file_paths)
809
- ]
810
- all_files = []
811
-
812
- for coro in asyncio.as_completed(tasks):
813
- results = await coro
814
- if results:
815
- all_files.extend(results)
816
- yield all_files
817
-
818
- if total > 1:
819
- master = os.path.join(tempfile.gettempdir(), "WebBooks_Batch.zip")
820
- with zipfile.ZipFile(master, "w", zipfile.ZIP_DEFLATED) as zf:
821
- for fp in all_files:
822
- zf.write(fp, arcname=os.path.basename(fp))
823
- all_files.insert(0, master)
824
- yield all_files
825
-
826
-
827
- # ════════════════════════════════════════════════════════════════════════════
828
- # GRADIO UI
829
- # ════════════════════════════════════════════════════════════════════════════
830
-
831
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo")) as app:
832
- gr.Markdown(
833
- "# 📖 Interactive WebBook Studio\n"
834
- "Upload `.txt`, `.epub`, or `.pdf` files and receive a fully synced audio + HTML WebBook.\n\n"
835
- "**Per book:** `_WebBook.zip` (unzip → open HTML) &nbsp;|&nbsp; "
836
- "`_WebBook.html` &nbsp;|&nbsp; `_Audio.mp3`"
837
- )
838
- with gr.Row():
839
- with gr.Column(scale=1):
840
- file_in = gr.File(label="Upload Books", file_count="multiple")
841
- with gr.Row():
842
- start_btn = gr.Button("Generate WebBook", variant="primary")
843
- stop_btn = gr.Button("Stop", variant="stop")
844
- with gr.Column(scale=1):
845
- file_out = gr.File(label="Downloads", file_count="multiple", interactive=False)
846
-
847
- event = start_btn.click(fn=process_books, inputs=file_in, outputs=file_out)
848
- stop_btn.click(fn=None, inputs=None, outputs=None, cancels=[event])
849
-
850
- if __name__ == "__main__":
851
- app.launch()