Spaces:
Running
Running
Download app.py from cringo/bbb: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/spaces/cringo/bbb/resolve/main/app.py
- Command line
-
hf download hf://spaces/cringo/bbb/app.py
-
curl -L -o app.py https://huggingface.co/spaces/cringo/bbb/resolve/main/app.py
13.1 kB
| import os | |
| import sys | |
| import uuid | |
| import time | |
| import json | |
| import shutil | |
| import logging | |
| import tempfile | |
| import threading | |
| import multiprocessing | |
| import gradio as gr | |
| from pathlib import Path | |
| from bbb import BBB | |
| from bbb.bbb import Config | |
| ALIGN_MODEL = os.environ.get("ALIGN_MODEL", "LaBSE") | |
| SPLIT_MODEL = os.environ.get("SPLIT_MODEL", "sat-3l") | |
| CPU_CORES = int(os.environ.get("CPU_CORES", 2)) | |
| JOB_MAX_AGE_SECONDS = 24 * 3600 | |
| LOG_MODULES = ['bbb', 'bertalign', 'sentence_transformers'] | |
| def _process_job_worker(job_id, work_dir, source_path, target_path, source_lang, target_lang): | |
| status_file = Path(work_dir) / "status.txt" | |
| out_epub = Path(work_dir) / "bilingual.epub" | |
| progress_file = Path(work_dir) / "progress.json" | |
| status_file.write_text("processing") | |
| def progress_callback(phase_id, description: str, step: int, total: int, message: str = None): | |
| data = { | |
| "description": description, | |
| "step": step, | |
| "total": total, | |
| "timestamp": time.time() | |
| } | |
| with open(progress_file, "w") as f: | |
| json.dump(data, f) | |
| try: | |
| shutil.copy2(source_path, Path(work_dir) / "source.epub") | |
| shutil.copy2(target_path, Path(work_dir) / "target.epub") | |
| config = Config( | |
| source_path=str(Path(work_dir) / "source.epub"), | |
| target_path=str(Path(work_dir) / "target.epub"), | |
| source_language=source_lang, | |
| target_language=target_lang, | |
| output=str(out_epub), | |
| manual=False, | |
| threads=CPU_CORES, | |
| auto_threshold=0.6, | |
| align_model=ALIGN_MODEL, | |
| split_model=SPLIT_MODEL, | |
| simple_split=False, | |
| verbosity='verbose', | |
| progress_callback=progress_callback, | |
| ) | |
| bbb = BBB(config) | |
| bbb.run() | |
| if out_epub.exists(): | |
| status_file.write_text("done") | |
| else: | |
| status_file.write_text("error: output file not found after successful run()") | |
| except Exception as e: | |
| status_file.write_text(f"error: {e}") | |
| class JobManager: | |
| def __init__(self): | |
| self.jobs = {} | |
| self.lock = threading.Lock() | |
| self._start_cleaner() | |
| def submit(self, source_path, target_path, source_lang, target_lang, | |
| source_name, target_name, upload_dir): | |
| job_id = uuid.uuid4().hex | |
| work_dir = str(Path(tempfile.mkdtemp(prefix=f"bbb_{job_id}_work_"))) | |
| job = { | |
| "status": "processing", | |
| "work_dir": work_dir, | |
| "upload_dir": upload_dir, | |
| "source_path": source_path, | |
| "target_path": target_path, | |
| "source_name": source_name, | |
| "target_name": target_name, | |
| "source_lang": source_lang or "", | |
| "target_lang": target_lang or "", | |
| "output_path": None, | |
| "created_at": time.time(), | |
| "finished_at": None, | |
| "process": None, | |
| "progress": None, | |
| } | |
| p = multiprocessing.Process( | |
| target=_process_job_worker, | |
| args=(job_id, work_dir, source_path, target_path, source_lang or None, target_lang or None) | |
| ) | |
| p.daemon = False | |
| p.start() | |
| with self.lock: | |
| job["process"] = p | |
| self.jobs[job_id] = job | |
| return job_id | |
| def get_job(self, job_id): | |
| with self.lock: | |
| job = self.jobs.get(job_id) | |
| if not job: | |
| return None | |
| p = job.get("process") | |
| if p and p.is_alive(): | |
| progress_file = Path(job["work_dir"]) / "progress.json" | |
| if progress_file.exists(): | |
| try: | |
| with open(progress_file) as f: | |
| job["progress"] = json.load(f) | |
| except Exception: | |
| job["progress"] = None | |
| else: | |
| job["progress"] = None | |
| return job | |
| status_file = Path(job["work_dir"]) / "status.txt" | |
| if not status_file.exists(): | |
| job["status"] = "error: process died unexpectedly" | |
| job["process"] = None | |
| return job | |
| content = status_file.read_text().strip() | |
| if content == "processing": | |
| job["status"] = "error: process died unexpectedly" | |
| elif content == "done": | |
| output_path = str(Path(job["work_dir"]) / "bilingual.epub") | |
| if Path(output_path).exists(): | |
| job["status"] = "done" | |
| job["output_path"] = output_path | |
| if job.get("upload_dir"): | |
| shutil.rmtree(job["upload_dir"], ignore_errors=True) | |
| job["upload_dir"] = None | |
| else: | |
| job["status"] = "error: output file was not created" | |
| elif content.startswith("error:"): | |
| job["status"] = content | |
| else: | |
| job["status"] = "error: unknown state" | |
| if content == "done" or content.startswith("error:"): | |
| if job.get("finished_at") is None: | |
| job["finished_at"] = os.path.getmtime(str(status_file)) | |
| job["process"] = None | |
| return job | |
| def cancel(self, job_id): | |
| with self.lock: | |
| job = self.jobs.get(job_id) | |
| if not job: | |
| return | |
| p = job.get("process") | |
| if p and p.is_alive(): | |
| p.terminate() | |
| p.join(timeout=5) | |
| if p.is_alive(): | |
| p.kill() | |
| p.join() | |
| upload_dir = job.get("upload_dir") | |
| if upload_dir: | |
| shutil.rmtree(upload_dir, ignore_errors=True) | |
| work_dir = job.get("work_dir") | |
| if work_dir: | |
| shutil.rmtree(work_dir, ignore_errors=True) | |
| del self.jobs[job_id] | |
| def _start_cleaner(self): | |
| def clean_loop(): | |
| while True: | |
| time.sleep(3600) | |
| now = time.time() | |
| with self.lock: | |
| to_delete = [] | |
| for jid, job in self.jobs.items(): | |
| age = now - (job.get("finished_at") or job["created_at"]) | |
| if age > JOB_MAX_AGE_SECONDS: | |
| to_delete.append(jid) | |
| for jid in to_delete: | |
| if self.jobs[jid].get("upload_dir"): | |
| shutil.rmtree(self.jobs[jid]["upload_dir"], ignore_errors=True) | |
| if self.jobs[jid].get("work_dir"): | |
| shutil.rmtree(self.jobs[jid]["work_dir"], ignore_errors=True) | |
| del self.jobs[jid] | |
| t = threading.Thread(target=clean_loop, daemon=True) | |
| t.start() | |
| manager = JobManager() | |
| def load_job(job_id: str): | |
| if not job_id: | |
| return ( | |
| "", | |
| "", | |
| gr.Textbox(value="", interactive=True), | |
| gr.Textbox(value="", interactive=True), | |
| gr.File(value=None), | |
| gr.File(value=None, interactive=True), | |
| gr.File(value=None, interactive=True), | |
| gr.Button(interactive=True), | |
| gr.Button(visible=False), | |
| ) | |
| job = manager.get_job(job_id) | |
| if job is None: | |
| return load_job("") | |
| if job["status"] == "processing": | |
| progress = job.get("progress") | |
| if progress and progress.get("total", 0) > 0: | |
| step = progress["step"] | |
| total = progress["total"] | |
| desc = progress["description"] | |
| status = f"Processing `{job['source_name']}` and `{job['target_name']}`…\n\n{desc} — {step}/{total} ({step/total*100:.0f}%)" | |
| else: | |
| status = f"Processing `{job['source_name']}` and `{job['target_name']}`… (initializing)" | |
| return ( | |
| job_id, | |
| status, | |
| gr.Textbox(value=job["source_lang"], interactive=False), | |
| gr.Textbox(value=job["target_lang"], interactive=False), | |
| gr.File(value=None), | |
| gr.File(value=None, interactive=False), | |
| gr.File(value=None, interactive=False), | |
| gr.Button(interactive=False), | |
| gr.Button(visible=True), | |
| ) | |
| elif job["status"] == "done": | |
| status = f"✅ Bilingual EPUB ready (source: `{job['source_name']}`, target: `{job['target_name']}`)" | |
| return ( | |
| job_id, | |
| status, | |
| gr.Textbox(value=job["source_lang"], interactive=True), | |
| gr.Textbox(value=job["target_lang"], interactive=True), | |
| gr.File(value=job["output_path"]), | |
| gr.File(value=None, interactive=True), | |
| gr.File(value=None, interactive=True), | |
| gr.Button(interactive=True), | |
| gr.Button(visible=False), | |
| ) | |
| else: | |
| status = f"❌ Error: {job['status']}" | |
| return ( | |
| job_id, | |
| status, | |
| gr.Textbox(value=job["source_lang"], interactive=True), | |
| gr.Textbox(value=job["target_lang"], interactive=True), | |
| gr.File(value=None), | |
| gr.File(value=None, interactive=True), | |
| gr.File(value=None, interactive=True), | |
| gr.Button(interactive=True), | |
| gr.Button(visible=False), | |
| ) | |
| def start_job(source_file, target_file, source_lang, target_lang, | |
| source_name="", target_name=""): | |
| if source_file is None or target_file is None: | |
| raise gr.Error("Please upload both EPUB files.") | |
| src_name = source_name if source_name else Path(source_file).name | |
| tgt_name = target_name if target_name else Path(target_file).name | |
| upload_dir = tempfile.mkdtemp(prefix="bbb_uploads_") | |
| src_path = os.path.join(upload_dir, src_name) | |
| tgt_path = os.path.join(upload_dir, tgt_name) | |
| shutil.copy2(source_file, src_path) | |
| shutil.copy2(target_file, tgt_path) | |
| job_id = manager.submit( | |
| source_path=src_path, | |
| target_path=tgt_path, | |
| source_lang=source_lang, | |
| target_lang=target_lang, | |
| source_name=src_name, | |
| target_name=tgt_name, | |
| upload_dir=upload_dir, | |
| ) | |
| return load_job(job_id) | |
| def cancel_job(job_id): | |
| if job_id: | |
| manager.cancel(job_id) | |
| return load_job("") | |
| with gr.Blocks(title="📚 Bilingual Book Builder") as demo: | |
| storage_hours = JOB_MAX_AGE_SECONDS // 3600 | |
| gr.Markdown(f""" | |
| # Bilingual Book Builder | |
| Upload a **source** (original) EPUB and a **target** (translation) EPUB to create a side‑by‑side bilingual book. | |
| Processing may take some time, even hours – you can close this page and return later. | |
| When ready, the bilingual EPUB will be stored for **{storage_hours} hours**. | |
| You can also run this locally, it's way faster if you have a graphic card (but requires model downloading). | |
| ### [⭐ Source Code](https://github.com/kerivin/bilingual-book-builder) | |
| """) | |
| job_state = gr.BrowserState("") | |
| job_id_hidden = gr.Textbox(visible=False) | |
| with gr.Row(): | |
| with gr.Column(): | |
| source_file = gr.File(label="Source EPUB", file_types=[".epub"], value=None) | |
| source_lang = gr.Textbox(label="Source language (en, ru, de)", placeholder="Auto‑detect") | |
| source_name = gr.Textbox(visible=False) | |
| with gr.Column(): | |
| target_file = gr.File(label="Target EPUB", file_types=[".epub"], value=None) | |
| target_lang = gr.Textbox(label="Target language (en, ru, de)", placeholder="Auto‑detect") | |
| target_name = gr.Textbox(visible=False) | |
| with gr.Column(): | |
| output_file = gr.File(label="Download Bilingual EPUB", interactive=False) | |
| with gr.Row(): | |
| process_btn = gr.Button("🚀 Build Bilingual EPUB", variant="primary") | |
| cancel_btn = gr.Button("❌ Cancel", variant="stop", visible=False) | |
| refresh_btn = gr.Button("🔄 Check Status") | |
| status_msg = gr.Markdown("") | |
| all_outputs = [ | |
| job_state, | |
| status_msg, | |
| source_lang, | |
| target_lang, | |
| output_file, | |
| source_file, | |
| target_file, | |
| process_btn, | |
| cancel_btn, | |
| ] | |
| process_btn.click( | |
| fn=start_job, | |
| inputs=[source_file, target_file, source_lang, target_lang, | |
| source_name, target_name], | |
| outputs=all_outputs, | |
| ) | |
| cancel_btn.click( | |
| fn=cancel_job, | |
| inputs=job_state, | |
| outputs=all_outputs, | |
| ) | |
| refresh_btn.click( | |
| fn=load_job, | |
| inputs=job_state, | |
| outputs=all_outputs, | |
| ) | |
| demo.load( | |
| fn=load_job, | |
| inputs=job_state, | |
| outputs=all_outputs, | |
| ) | |
| if __name__ == "__main__": | |
| handler = logging.StreamHandler(sys.stdout) | |
| for module in LOG_MODULES: | |
| logger = logging.getLogger(module) | |
| logger.setLevel(logging.INFO) | |
| logger.addHandler(handler) | |
| demo.launch() |