import gradio as gr import os import tempfile import requests import subprocess import zipfile import shutil import time import asyncio import re import json from collections import defaultdict from bs4 import BeautifulSoup from concurrent.futures import ThreadPoolExecutor, as_completed # ─── HUGGING FACE BUCKET ──────────────────────────────────────────────────── # Repo ID matching https://huggingface.co/datasets/Krixter/storage # Set HF_TOKEN as a Secret in your Space settings (Settings → Secrets) HF_REPO_ID = "Krixter/storage" HF_REPO_TYPE = "dataset" try: from huggingface_hub import HfApi, hf_hub_download _HF_AVAILABLE = True except ImportError: _HF_AVAILABLE = False def _hf_api(token: str): if not _HF_AVAILABLE: return None return HfApi(token=token) def hf_upload_files(paths: list, token: str, subfolder: str = "webbooks") -> list[str]: """Upload a list of local file paths to the HF bucket. Returns list of errors.""" if not token: return ["No HF token provided – skipping upload."] api = _hf_api(token) if api is None: return ["huggingface_hub not installed."] errors = [] for path in paths: remote = subfolder + "/" + os.path.basename(path) try: api.upload_file( path_or_fileobj=path, path_in_repo=remote, repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE, commit_message=f"WebBook Studio: add {os.path.basename(path)}", ) except Exception as e: errors.append(f"{os.path.basename(path)}: {e}") return errors def hf_list_files(token: str, subfolder: str = "webbooks") -> list[str]: """Return a list of remote file paths inside `subfolder` in the bucket.""" if not token or not _HF_AVAILABLE: return [] try: api = _hf_api(token) all_files = api.list_repo_files( repo_id=HF_REPO_ID, repo_type=HF_REPO_TYPE, ) return [f for f in all_files if f.startswith(subfolder + "/")] except Exception: return [] def hf_download_file(remote_path: str, token: str) -> str | None: """Download a file from the bucket and return its local path.""" if not token or not _HF_AVAILABLE: return None try: local = hf_hub_download( repo_id=HF_REPO_ID, filename=remote_path, repo_type=HF_REPO_TYPE, token=token, ) return local except Exception: return None # ─── CONFIGURATION ────────────────────────────────────────────────────────── FIXED_SPEED = 1.6 THREADS = 10 MAX_CHUNK = 200 # ─── CONCURRENCY GATES ────────────────────────────────────────────────────── download_door = asyncio.Semaphore(1) kitchen_door = asyncio.Semaphore(1) # ════════════════════════════════════════════════════════════════════════════ # TEXT EXTRACTION # ════════════════════════════════════════════════════════════════════════════ def extract_local_text(path, temp_dir): content = "" ext = os.path.splitext(path)[1].lower() try: if ext == ".txt": with open(path, "r", encoding="utf-8", errors="ignore") as f: content = f.read() elif ext == ".epub": with zipfile.ZipFile(path, "r") as z: for filename in sorted(z.namelist()): if filename.endswith((".html", ".xhtml")): with z.open(filename) as f: soup = BeautifulSoup(f.read(), "html.parser") part = soup.get_text(separator="\n") if part: content += part + "\n" elif ext == ".pdf": import PyPDF2 reader = PyPDF2.PdfReader(path) for page in reader.pages: txt = page.extract_text() if txt: content += txt + "\n" except Exception: return None if not content: return None # Normalise horizontal whitespace on each line, keep paragraph breaks content = re.sub(r"[ \t]+", " ", content) content = re.sub(r"\n{3,}", "\n\n", content) content = "\n".join(line.rstrip() for line in content.splitlines()) out = os.path.join(temp_dir, "extracted.txt") with open(out, "w", encoding="utf-8") as f: f.write(content) return out # ════════════════════════════════════════════════════════════════════════════ # TTS ENGINE # ════════════════════════════════════════════════════════════════════════════ class GoogleTTSEngine: def split_text(self, text, max_len=MAX_CHUNK): chunks = [] while text: if len(text) <= max_len: chunks.append(text.strip()) break best_i = -1 for punct in [". ", "! ", "? ", "; "]: i = text[:max_len].rfind(punct) if i > best_i: best_i = i if best_i == -1: best_i = text[:max_len].rfind(" ") if best_i == -1: best_i = max_len else: best_i += 1 chunks.append(text[:best_i].strip()) text = text[best_i:].lstrip() return [c for c in chunks if c] def strip_id3(self, mp3_data): if mp3_data[:3] == b"ID3": size = ( (mp3_data[6] & 0x7F) << 21 | (mp3_data[7] & 0x7F) << 14 | (mp3_data[8] & 0x7F) << 7 | (mp3_data[9] & 0x7F) ) mp3_data = mp3_data[10 + size:] if len(mp3_data) > 128 and mp3_data[-128:-125] == b"TAG": mp3_data = mp3_data[:-128] return mp3_data def download_chunk(self, text): url = "https://translate.google.com/translate_tts" params = {"ie": "UTF-8", "q": text, "tl": "en-IN", "client": "tw-ob"} headers = {"User-Agent": "Mozilla/5.0"} for _ in range(5): try: r = requests.get(url, params=params, headers=headers, timeout=8) if r.status_code == 200: return self.strip_id3(r.content) except Exception: time.sleep(0.5) return None # ════════════════════════════════════════════════════════════════════════════ # AUDIO HELPERS # ════════════════════════════════════════════════════════════════════════════ def get_duration_ms(path): result = subprocess.run( ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) try: return int(float(result.stdout.strip()) * 1000) except Exception: return 0 def process_chunk_audio(args): in_path, proc_path, speed = args if speed <= 2.0: atempo_chain = "atempo=%.4f" % speed else: import math f1 = math.sqrt(speed) f2 = speed / f1 atempo_chain = "atempo=%.4f,atempo=%.4f" % (f1, f2) af_chain = ( "aresample=44100," + atempo_chain + ",loudnorm=I=-16:TP=-1.5:LRA=11" + ",aresample=44100" ) # Output WAV (lossless) to avoid MP3 encoder-delay accumulation. # Each MP3 carries a ~13 ms encoder-delay header; summed across hundreds # of chunks that drifts timestamps by several seconds. WAV has zero # encoder delay, so get_duration_ms() returns exact values that will # perfectly match the single MP3 encode done at the final concat step. ret = subprocess.run( ["ffmpeg", "-y", "-i", in_path, "-af", af_chain, "-ar", "44100", "-threads", "1", proc_path], # proc_path now ends in .wav (see caller) stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) if ret.returncode != 0 or not os.path.exists(proc_path): ret2 = subprocess.run( ["ffmpeg", "-y", "-i", in_path, "-ar", "44100", "-threads", "1", proc_path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) if ret2.returncode != 0 or not os.path.exists(proc_path): # last-resort: decode the raw MP3 to WAV with no filters subprocess.run( ["ffmpeg", "-y", "-i", in_path, "-ar", "44100", "-threads", "1", proc_path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) return get_duration_ms(proc_path) # ════════════════════════════════════════════════════════════════════════════ # CHAPTER PARSING ── format-locked detection # # Step 1 → scan the whole text to COUNT how many times each candidate # format appears on its own line (using a line-anchored scan # regex so we only count genuine headers, not mid-sentence hits). # Step 2 → keep the ONE format that has the highest count (≥ 2 matches). # Step 3 → split ONLY on that format and never look for another. # # This prevents the old problem where a novel that uses "Season-Chapter" # headers (e.g. "1-1", "2-3") would also be split on stray "N: …" # patterns that appear inside the chapter body text. # ════════════════════════════════════════════════════════════════════════════ # Each entry: (format_name, scan_compiled_re, split_compiled_re) # scan_re — used only to COUNT occurrences (determines the winner) # split_re — pre-compiled with capturing group; used in re.split() # # NOTE: Python's re.split() requires that inline flags (?m) etc. appear at # the root of the pattern, not inside a group. We pre-compile with explicit # flags so we can safely wrap the core pattern in a capturing group. _FORMAT_REGISTRY = [ ( # "1-1", "2-10" etc. alone on a line (season–chapter) "season_chapter", re.compile(r"^[ \t]*\d+[-–]\d+[ \t]*$", re.MULTILINE), re.compile(r"(^[ \t]*\d+[-–]\d+[ \t]*$)", re.MULTILINE), ), ( # "Chapter 1", "Chapter 1: Title", "Ch. 3 — Revolt", etc. "chapter_word", re.compile(r"^[ \t]*(?:chapter|ch\.?)[ \t]*[-:]?[ \t]*\d+[^\n]*", re.MULTILINE | re.IGNORECASE), re.compile(r"(^[ \t]*(?:chapter|ch\.?)[ \t]*[-:]?[ \t]*\d+[^\n]*)", re.MULTILINE | re.IGNORECASE), ), ( # "1:", "12: Some Title" at the very start of a line "number_colon", re.compile(r"^[ \t]*\d+[ \t]*:(?!\d)[^\n]*", re.MULTILINE), re.compile(r"(^[ \t]*\d+[ \t]*:(?!\d)[^\n]*)", re.MULTILINE), ), ( # "Part 1", "Arc 3", "Volume 2", etc. "part_arc", re.compile(r"^[ \t]*(?:part|arc|volume|vol\.?|book)[ \t]*\d+[^\n]*", re.MULTILINE | re.IGNORECASE), re.compile(r"(^[ \t]*(?:part|arc|volume|vol\.?|book)[ \t]*\d+[^\n]*)", re.MULTILINE | re.IGNORECASE), ), ] def _detect_format(full_text: str): """ Return (format_name, split_compiled_re) for the most common chapter format found in `full_text`, or (None, None) if none qualifies. """ best_name = None best_split = None best_count = 1 # require at least 2 matches to be accepted for name, scan_re, split_re in _FORMAT_REGISTRY: count = len(scan_re.findall(full_text)) if count > best_count: best_count = count best_name = name best_split = split_re return best_name, best_split def _extract_title_from_body(raw_body: str, fmt_name: str, header: str) -> str: """ For season_chapter format the real human-readable title often lives in the first "Chapter N: …" line of the body. Extract it and combine with the season-chapter marker so the sidebar reads nicely, e.g. "1-1 – Chapter 1: Lustful Mother". For all other formats we just return `header` as-is. """ if fmt_name != "season_chapter": return header.strip() # Look in the first 15 lines of the body for a Chapter/Ch. line for line in raw_body.splitlines()[:15]: line = line.strip() if re.match(r"(?i)^(?:chapter|ch\.?)[\s\d]", line): return header.strip() + " \u2013 " + line return header.strip() def parse_chapters(full_text: str) -> list[list]: """ Detect the dominant chapter-header format in `full_text`, split on it (and ONLY on it), and return a list of [title, body_text] pairs. """ fmt_name, split_re = _detect_format(full_text) # ── No recognisable format → treat entire text as one chapter ──────────── if split_re is None: return [["Full Book", full_text]] # re.split with a capturing group keeps the delimiter in the result list. # Result looks like: [pre_text, hdr1, body1, hdr2, body2, ...] # split_re is already pre-compiled with the capturing group included. splits = split_re.split(full_text) chapters: list[list] = [] # Text before the first chapter header (preamble / intro) if splits[0].strip(): chapters.append(["Intro", splits[0]]) i = 1 while i < len(splits): raw_header = splits[i] body = splits[i + 1] if i + 1 < len(splits) else "" i += 2 title = _extract_title_from_body(body, fmt_name, raw_header) # Clamp extremely long titles if len(title) > 120: title = title[:120] + "\u2026" # ── Deduplication: skip a header whose key equals the previous one. # For season_chapter ("1-1", "1-2") the FULL header is the key # so "1-1" and "1-2" are never accidentally merged. # For other formats only the leading number is compared. if fmt_name == "season_chapter": cur_key = raw_header.strip() else: _m = re.search(r"\d+", raw_header) cur_key = _m.group() if _m else raw_header.strip() if chapters: last_hdr = chapters[-1][0] if fmt_name == "season_chapter": prev_key = last_hdr.split(" \u2013 ")[0].strip() else: _pm = re.search(r"\d+", last_hdr) prev_key = _pm.group() if _pm else last_hdr.strip() if cur_key == prev_key: chapters[-1][1] += "\n" + body continue if len(chapters[-1][1]) < 150: chapters[-1][1] += "\n" + title + ".\n" + body chapters[-1][0] = title continue chapters.append([title, title + ".\n" + body]) if not chapters: chapters = [["Full Book", full_text]] return chapters # ════════════════════════════════════════════════════════════════════════════ # MAIN SYNC PIPELINE # ════════════════════════════════════════════════════════════════════════════ def sync_process_book(file_path, temp_dir, progress_obj, book_idx, total_books): text_file = extract_local_text(file_path, temp_dir) if not text_file: return None, None, None, None base_name = os.path.splitext(os.path.basename(file_path))[0] book_label = "[Book %d/%d]" % (book_idx, total_books) with open(text_file, "r", encoding="utf-8") as f: full_text = f.read() chapters = parse_chapters(full_text) engine = GoogleTTSEngine() all_chunks = [] for c_idx, (_, c_text) in enumerate(chapters): tts_text = c_text.replace("\n", " ") tts_text = re.sub(r" {2,}", " ", tts_text).strip() for local_idx, chunk_text in enumerate(engine.split_text(tts_text)): all_chunks.append((c_idx, local_idx, chunk_text)) chunk_text_map = {(c, l): t for c, l, t in all_chunks} total_chunks = len(all_chunks) chunk_dir = os.path.join(temp_dir, "chunks_raw") proc_dir = os.path.join(temp_dir, "chunks_proc") os.makedirs(chunk_dir, exist_ok=True) os.makedirs(proc_dir, exist_ok=True) # ── PHASE 1: DOWNLOAD (parallel) ────────────────────────────────────── start_time = time.time() completed = 0 with ThreadPoolExecutor(max_workers=THREADS) as pool: futures = { pool.submit(engine.download_chunk, text): (c_idx, local_idx) for c_idx, local_idx, text in all_chunks } for fut in as_completed(futures): c_idx, local_idx = futures[fut] data = fut.result() if data: fpath = os.path.join(chunk_dir, "c%03d_%05d.mp3" % (c_idx, local_idx)) with open(fpath, "wb") as af: af.write(data) completed += 1 elapsed = time.time() - start_time avg = elapsed / completed eta = avg * (total_chunks - completed) progress_obj( completed / (total_chunks * 2), desc="%s Downloading: %d/%d | ETA %02d:%02d" % ( book_label, completed, total_chunks, int(eta // 60), int(eta % 60)), ) # ── PHASE 2: SPEED-PROCESS (parallel ffmpeg) ─────────────────────────── downloaded = sorted(f for f in os.listdir(chunk_dir) if f.endswith(".mp3")) # Use .wav for intermediate files so durations are exact (no MP3 encoder delay). process_args = [ (os.path.join(chunk_dir, cf), os.path.join(proc_dir, cf[:-4] + ".wav"), # .mp3 → .wav FIXED_SPEED) for cf in downloaded ] durations = {} with ThreadPoolExecutor(max_workers=THREADS) as pool: fut_map = {pool.submit(process_chunk_audio, a): a[1] for a in process_args} proc_done = 0 for fut in as_completed(fut_map): proc_path = fut_map[fut] dur_ms = fut.result() durations[os.path.basename(proc_path)] = dur_ms proc_done += 1 progress_obj( 0.50 + (proc_done / max(len(downloaded), 1)) * 0.30, desc="%s Speed-processing: %d/%d" % (book_label, proc_done, len(downloaded)), ) # ── PHASE 3: BUILD TIMESTAMPS ────────────────────────────────────────── chunk_metadata = [] current_ms = 0 chunk_idx = 0 for cf in downloaded: m = re.match(r"c(\d+)_(\d+)\.mp3", cf) if not m: continue c_idx = int(m.group(1)) local_idx = int(m.group(2)) dur_ms = durations.get(cf[:-4] + ".wav", 0) # keyed as .wav text = chunk_text_map.get((c_idx, local_idx), "") chunk_metadata.append({ "idx": chunk_idx, "cIdx": c_idx, "text": text, "start": current_ms, "end": current_ms + dur_ms, }) current_ms += dur_ms chunk_idx += 1 chunks_by_chapter = defaultdict(list) for cm in chunk_metadata: chunks_by_chapter[cm["cIdx"]].append(cm) chapter_info = [] for c_idx, (title, raw_body) in enumerate(chapters): first = chunks_by_chapter[c_idx][0] if chunks_by_chapter[c_idx] else None chapter_info.append({ "idx": c_idx, "title": title, "start": first["start"] if first else 0, "chunkStart": first["idx"] if first else 0, "raw_text": raw_body, }) # ── PHASE 4: FINAL MERGE (stream-copy concat) ────────────────────────── progress_obj(0.85, desc=book_label + " Merging audio…") concat_path = os.path.join(temp_dir, "concat.txt") with open(concat_path, "w") as f: for cf in downloaded: p = os.path.join(proc_dir, cf[:-4] + ".wav") # .wav intermediate if os.path.exists(p): f.write("file '" + os.path.abspath(p).replace("\\", "/") + "'\n") output_mp3 = os.path.join(tempfile.gettempdir(), base_name + "_Audio.mp3") subprocess.run( ["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", concat_path, "-ar", "44100", "-ab", "192k", "-q:a", "2", output_mp3], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) shutil.rmtree(temp_dir) return output_mp3, chunk_metadata, chapter_info, base_name # ════════════════════════════════════════════════════════════════════════════ # HTML TEMPLATE # ════════════════════════════════════════════════════════════════════════════ _HTML = ( "\n" '\n' "\n" ' \n' ' \n' " __BOOK_TITLE__ — WebBook\n" " \n" "\n" "\n" '\n\n' "\n" '
\n' ' \n' '
\n' ' __BOOK_TITLE__\n' ' Loading…\n' "
\n" ' \n' ' \n' ' \n' '
\n' ' \n' "
\n" ' 0:00 / 0:00\n' '
\n' ' Speed\n' ' \n' ' 1.0×\n' "
\n" '
\n' ' 🔊\n' ' \n' "
\n" ' \n' "
\n" "\n" '
\n' ' \n" '
\n' "__CHAPTERS_HTML__\n" "
\n" "
\n" "\n" "\n" "\n" "\n" ) # ════════════════════════════════════════════════════════════════════════════ # HTML GENERATION # ════════════════════════════════════════════════════════════════════════════ def _esc(text): return (text .replace("&", "&") .replace("<", "<") .replace(">", ">") .replace('"', """)) def _text_to_paragraphs(raw_text): paras = re.split(r"\n{2,}", raw_text) result = [] for p in paras: p = p.strip() if p: result.append(p) return result def generate_webbook_html(chunk_metadata, chapter_info, base_name, audio_filename): chunks_by_chapter = defaultdict(list) for cm in chunk_metadata: chunks_by_chapter[cm["cIdx"]].append(cm) chapters_html = "" for ch in chapter_info: c_idx = ch["idx"] c_chunks = chunks_by_chapter[c_idx] c_text = ch.get("raw_text", "") chapters_html += ( '
\n' '

' + _esc(ch["title"]) + '

\n' '
\n' ) if c_text and c_chunks: paragraphs = _text_to_paragraphs(c_text) flat_full = " ".join(p.replace("\n", " ") for p in paragraphs) chunk_para = {} search_pos = 0 for ck in c_chunks: needle = ck["text"].strip() pos = flat_full.find(needle, search_pos) if pos == -1: pos = flat_full.find(needle) running = 0 para_idx = 0 for pi, para in enumerate(paragraphs): flat_para = para.replace("\n", " ") end = running + len(flat_para) if pos == -1 or end >= pos: para_idx = pi break running = end + 1 chunk_para[ck["idx"]] = para_idx if pos != -1: search_pos = pos + len(needle) from collections import defaultdict as _dd para_chunks = _dd(list) for ck in c_chunks: para_chunks[chunk_para.get(ck["idx"], 0)].append(ck) for pi, para in enumerate(paragraphs): p_chunks = para_chunks.get(pi, []) flat_para = para.replace("\n", " ") already_covered = False if not p_chunks: for ck in c_chunks: if flat_para.strip() and ( flat_para.strip() in ck["text"] or ck["text"].strip() in flat_para ): already_covered = True break if already_covered: continue chapters_html += '

' if p_chunks: for ck in p_chunks: chapters_html += ( '' + _esc(ck["text"]) + ' ' ) else: nearest_ck = None for ck in reversed(c_chunks): if chunk_para.get(ck["idx"], 0) <= pi: nearest_ck = ck break if nearest_ck is None and c_chunks: nearest_ck = c_chunks[0] if nearest_ck: chapters_html += ( '' + _esc(flat_para) + '' ) else: chapters_html += _esc(flat_para) chapters_html += '

\n' else: for ck in c_chunks: chapters_html += ( '' + _esc(ck["text"]) + ' ' ) chapters_html += "\n
\n
\n" sidebar_items = "\n".join( '
  • ' + _esc(ch["title"]) + '
  • ' for ch in chapter_info ) chapter_info_json = [ {k: v for k, v in ch.items() if k != "raw_text"} for ch in chapter_info ] return ( _HTML .replace("__BOOK_TITLE__", _esc(base_name)) .replace("__AUDIO_SRC__", audio_filename) .replace("__SIDEBAR_ITEMS__", sidebar_items) .replace("__CHAPTERS_HTML__", chapters_html) .replace("__CHUNKS_JSON__", json.dumps(chunk_metadata, ensure_ascii=False)) .replace("__CHAPTERS_JSON__", json.dumps(chapter_info_json, ensure_ascii=False)) ) # ════════════════════════════════════════════════════════════════════════════ # WEBBOOK PACKAGING # ════════════════════════════════════════════════════════════════════════════ def build_webbook(output_mp3, chunk_metadata, chapter_info, base_name): audio_filename = os.path.basename(output_mp3) html_str = generate_webbook_html(chunk_metadata, chapter_info, base_name, audio_filename) html_path = os.path.join(tempfile.gettempdir(), base_name + "_WebBook.html") with open(html_path, "w", encoding="utf-8") as f: f.write(html_str) zip_path = os.path.join(tempfile.gettempdir(), base_name + "_WebBook.zip") with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf: zf.write(html_path, arcname=os.path.basename(html_path)) zf.write(output_mp3, arcname=audio_filename) return html_path, zip_path # ════════════════════════════════════════════════════════════════════════════ # ASYNC ORCHESTRATION # ════════════════════════════════════════════════════════════════════════════ async def process_single_book(file_path, progress_obj, book_idx, total_books, hf_token): temp_dir = tempfile.mkdtemp() async with download_door: result = await asyncio.to_thread( sync_process_book, file_path, temp_dir, progress_obj, book_idx, total_books, ) output_mp3, chunk_metadata, chapter_info, base_name = result if not output_mp3: return [] async with kitchen_door: html_path, zip_path = await asyncio.to_thread( build_webbook, output_mp3, chunk_metadata, chapter_info, base_name, ) local_files = [zip_path, html_path, output_mp3] # ── Upload to HF bucket if token provided ───────────────────────────── if hf_token and hf_token.strip(): await asyncio.to_thread(hf_upload_files, local_files, hf_token.strip()) return local_files async def process_books(file_paths, hf_token, progress=gr.Progress()): if not file_paths: yield [] return if not isinstance(file_paths, list): file_paths = [file_paths] total = len(file_paths) tasks = [ asyncio.create_task( process_single_book(f, progress, idx + 1, total, hf_token) ) for idx, f in enumerate(file_paths) ] all_files = [] for coro in asyncio.as_completed(tasks): results = await coro if results: all_files.extend(results) yield all_files if total > 1: master = os.path.join(tempfile.gettempdir(), "WebBooks_Batch.zip") with zipfile.ZipFile(master, "w", zipfile.ZIP_DEFLATED) as zf: for fp in all_files: zf.write(fp, arcname=os.path.basename(fp)) all_files.insert(0, master) yield all_files # ── Bucket browser helpers ───────────────────────────────────────────────── def refresh_bucket(hf_token): files = hf_list_files(hf_token.strip()) if hf_token and hf_token.strip() else [] if not files: return gr.update(choices=[], value=None), "⚠️ No files found (check token / repo)." return gr.update(choices=files, value=None), f"✅ {len(files)} file(s) in bucket." def download_from_bucket(selected_file, hf_token): if not selected_file: return None, "Select a file first." local = hf_download_file(selected_file, hf_token.strip() if hf_token else "") if local: return local, f"✅ Downloaded: {os.path.basename(selected_file)}" return None, "❌ Download failed – check token and file path." # ════════════════════════════════════════════════════════════════════════════ # GRADIO UI # ════════════════════════════════════════════════════════════════════════════ # Read token from Space secret at startup (set via HF Space Settings → Secrets) _DEFAULT_TOKEN = os.environ.get("HF_TOKEN", "") with gr.Blocks(theme=gr.themes.Soft(primary_hue="indigo")) as app: gr.Markdown( "# 📖 Interactive WebBook Studio\n" "Upload `.txt`, `.epub`, or `.pdf` files and receive a fully synced audio + HTML WebBook.\n\n" "**Per book:** `_WebBook.zip` (unzip → open HTML)  |  " "`_WebBook.html`  |  `_Audio.mp3`" ) with gr.Tabs(): # ── TAB 1: Generate ────────────────────────────────────────────── with gr.Tab("🎙️ Generate WebBook"): with gr.Row(): with gr.Column(scale=1): file_in = gr.File(label="Upload Books", file_count="multiple") hf_token_box = gr.Textbox( label="HuggingFace Token (optional – auto-saves to bucket)", placeholder="hf_… (or set HF_TOKEN secret in Space settings)", value=_DEFAULT_TOKEN, type="password", ) with gr.Row(): start_btn = gr.Button("Generate WebBook", variant="primary") stop_btn = gr.Button("Stop", variant="stop") with gr.Column(scale=1): file_out = gr.File( label="Downloads", file_count="multiple", interactive=False ) event = start_btn.click( fn=process_books, inputs=[file_in, hf_token_box], outputs=file_out, ) stop_btn.click(fn=None, inputs=None, outputs=None, cancels=[event]) # ── TAB 2: Bucket Browser ──────────────────────────────────────── with gr.Tab("☁️ Bucket Browser"): gr.Markdown( f"Browse and download previously generated WebBooks stored in " f"`{HF_REPO_ID}` on HuggingFace.\n\n" "Enter your token below (or it will be pre-filled from the Space secret)." ) with gr.Row(): bucket_token = gr.Textbox( label="HuggingFace Token", placeholder="hf_…", value=_DEFAULT_TOKEN, type="password", scale=3, ) refresh_btn = gr.Button("🔄 Refresh List", scale=1) bucket_status = gr.Textbox(label="Status", interactive=False) bucket_picker = gr.Dropdown( label="Files in bucket", choices=[], interactive=True ) dl_btn = gr.Button("⬇️ Download Selected File", variant="primary") bucket_dl_out = gr.File(label="Downloaded File", interactive=False) refresh_btn.click( fn=refresh_bucket, inputs=[bucket_token], outputs=[bucket_picker, bucket_status], ) dl_btn.click( fn=download_from_bucket, inputs=[bucket_picker, bucket_token], outputs=[bucket_dl_out, bucket_status], ) if __name__ == "__main__": app.launch()