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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import uuid
|
| 3 |
+
import time
|
| 4 |
+
import shutil
|
| 5 |
+
import tempfile
|
| 6 |
+
import threading
|
| 7 |
+
import multiprocessing
|
| 8 |
+
import gradio as gr
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
from bbb import BBB
|
| 12 |
+
|
| 13 |
+
MODEL = "sentence-transformers/LaBSE"
|
| 14 |
+
CPU_CORES = int(os.environ.get("CPU_CORES", 2))
|
| 15 |
+
JOB_MAX_AGE_SECONDS = 24 * 3600
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _process_job_worker(job_id, work_dir, source_path, target_path, source_lang, target_lang):
|
| 19 |
+
status_file = Path(work_dir) / "status.txt"
|
| 20 |
+
out_epub = Path(work_dir) / "bilingual.epub"
|
| 21 |
+
|
| 22 |
+
status_file.write_text("processing")
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
shutil.copy2(source_path, Path(work_dir) / "source.epub")
|
| 26 |
+
shutil.copy2(target_path, Path(work_dir) / "target.epub")
|
| 27 |
+
|
| 28 |
+
bbb = BBB(
|
| 29 |
+
source_epub_path=str(Path(work_dir) / "source.epub"),
|
| 30 |
+
target_epub_path=str(Path(work_dir) / "target.epub"),
|
| 31 |
+
source_language=source_lang,
|
| 32 |
+
target_language=target_lang,
|
| 33 |
+
output=str(out_epub),
|
| 34 |
+
auto_match_chapter_threshold=0.6,
|
| 35 |
+
model=MODEL,
|
| 36 |
+
threads=CPU_CORES,
|
| 37 |
+
)
|
| 38 |
+
bbb.run()
|
| 39 |
+
status_file.write_text("done")
|
| 40 |
+
except Exception as e:
|
| 41 |
+
status_file.write_text(f"error: {e}")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class JobManager:
|
| 45 |
+
def __init__(self):
|
| 46 |
+
self.jobs = {}
|
| 47 |
+
self.lock = threading.Lock()
|
| 48 |
+
self._start_cleaner()
|
| 49 |
+
|
| 50 |
+
def submit(self, source_path, target_path, source_lang, target_lang,
|
| 51 |
+
source_name, target_name, upload_dir):
|
| 52 |
+
job_id = uuid.uuid4().hex
|
| 53 |
+
work_dir = str(Path(tempfile.mkdtemp(prefix=f"bbb_{job_id}_work_")))
|
| 54 |
+
job = {
|
| 55 |
+
"status": "processing",
|
| 56 |
+
"work_dir": work_dir,
|
| 57 |
+
"upload_dir": upload_dir,
|
| 58 |
+
"source_path": source_path,
|
| 59 |
+
"target_path": target_path,
|
| 60 |
+
"source_name": source_name,
|
| 61 |
+
"target_name": target_name,
|
| 62 |
+
"source_lang": source_lang or "",
|
| 63 |
+
"target_lang": target_lang or "",
|
| 64 |
+
"output_path": None,
|
| 65 |
+
"created_at": time.time(),
|
| 66 |
+
"process": None,
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
p = multiprocessing.Process(
|
| 70 |
+
target=_process_job_worker,
|
| 71 |
+
args=(job_id, work_dir, source_path, target_path, source_lang or None, target_lang or None)
|
| 72 |
+
)
|
| 73 |
+
p.daemon = False
|
| 74 |
+
p.start()
|
| 75 |
+
|
| 76 |
+
with self.lock:
|
| 77 |
+
job["process"] = p
|
| 78 |
+
self.jobs[job_id] = job
|
| 79 |
+
return job_id
|
| 80 |
+
|
| 81 |
+
def get_job(self, job_id):
|
| 82 |
+
with self.lock:
|
| 83 |
+
job = self.jobs.get(job_id)
|
| 84 |
+
if not job:
|
| 85 |
+
return None
|
| 86 |
+
p = job.get("process")
|
| 87 |
+
if p and p.is_alive():
|
| 88 |
+
return job
|
| 89 |
+
status_file = Path(job["work_dir"]) / "status.txt"
|
| 90 |
+
if not status_file.exists():
|
| 91 |
+
job["status"] = "error: process died unexpectedly"
|
| 92 |
+
job["process"] = None
|
| 93 |
+
return job
|
| 94 |
+
content = status_file.read_text().strip()
|
| 95 |
+
if content == "processing":
|
| 96 |
+
job["status"] = "error: process died unexpectedly"
|
| 97 |
+
elif content == "done":
|
| 98 |
+
job["status"] = "done"
|
| 99 |
+
job["output_path"] = str(Path(job["work_dir"]) / "bilingual.epub")
|
| 100 |
+
elif content.startswith("error:"):
|
| 101 |
+
job["status"] = content
|
| 102 |
+
else:
|
| 103 |
+
job["status"] = "error: unknown state"
|
| 104 |
+
job["process"] = None
|
| 105 |
+
return job
|
| 106 |
+
|
| 107 |
+
def cancel(self, job_id):
|
| 108 |
+
with self.lock:
|
| 109 |
+
job = self.jobs.get(job_id)
|
| 110 |
+
if not job:
|
| 111 |
+
return
|
| 112 |
+
p = job.get("process")
|
| 113 |
+
if p and p.is_alive():
|
| 114 |
+
p.terminate()
|
| 115 |
+
p.join(timeout=5)
|
| 116 |
+
if p.is_alive():
|
| 117 |
+
p.kill()
|
| 118 |
+
p.join()
|
| 119 |
+
upload_dir = job.get("upload_dir")
|
| 120 |
+
if upload_dir:
|
| 121 |
+
shutil.rmtree(upload_dir, ignore_errors=True)
|
| 122 |
+
work_dir = job.get("work_dir")
|
| 123 |
+
if work_dir:
|
| 124 |
+
shutil.rmtree(work_dir, ignore_errors=True)
|
| 125 |
+
del self.jobs[job_id]
|
| 126 |
+
|
| 127 |
+
def _start_cleaner(self):
|
| 128 |
+
def clean_loop():
|
| 129 |
+
while True:
|
| 130 |
+
time.sleep(3600)
|
| 131 |
+
now = time.time()
|
| 132 |
+
with self.lock:
|
| 133 |
+
to_delete = []
|
| 134 |
+
for jid, job in self.jobs.items():
|
| 135 |
+
if now - job["created_at"] > JOB_MAX_AGE_SECONDS:
|
| 136 |
+
to_delete.append(jid)
|
| 137 |
+
for jid in to_delete:
|
| 138 |
+
if self.jobs[jid].get("upload_dir"):
|
| 139 |
+
shutil.rmtree(self.jobs[jid]["upload_dir"], ignore_errors=True)
|
| 140 |
+
if self.jobs[jid].get("work_dir"):
|
| 141 |
+
shutil.rmtree(self.jobs[jid]["work_dir"], ignore_errors=True)
|
| 142 |
+
del self.jobs[jid]
|
| 143 |
+
t = threading.Thread(target=clean_loop, daemon=True)
|
| 144 |
+
t.start()
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
manager = JobManager()
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def submit_job(source_file, target_file, source_lang, target_lang):
|
| 151 |
+
if source_file is None or target_file is None:
|
| 152 |
+
raise gr.Error("Please upload both EPUB files.")
|
| 153 |
+
|
| 154 |
+
src_name = Path(source_file).name
|
| 155 |
+
tgt_name = Path(target_file).name
|
| 156 |
+
|
| 157 |
+
upload_dir = tempfile.mkdtemp(prefix="bbb_uploads_")
|
| 158 |
+
src_path = os.path.join(upload_dir, src_name)
|
| 159 |
+
tgt_path = os.path.join(upload_dir, tgt_name)
|
| 160 |
+
shutil.copy2(source_file, src_path)
|
| 161 |
+
shutil.copy2(target_file, tgt_path)
|
| 162 |
+
|
| 163 |
+
job_id = manager.submit(
|
| 164 |
+
source_path=src_path,
|
| 165 |
+
target_path=tgt_path,
|
| 166 |
+
source_lang=source_lang,
|
| 167 |
+
target_lang=target_lang,
|
| 168 |
+
source_name=src_name,
|
| 169 |
+
target_name=tgt_name,
|
| 170 |
+
upload_dir=upload_dir,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
status = f"🔄 Job **{job_id[:8]}** submitted. Processing `{src_name}` → `{tgt_name}`."
|
| 174 |
+
return job_id, status
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def load_job(job_id):
|
| 178 |
+
if not job_id:
|
| 179 |
+
return (
|
| 180 |
+
"",
|
| 181 |
+
gr.update(value=""),
|
| 182 |
+
gr.update(value="", interactive=True),
|
| 183 |
+
gr.update(value="", interactive=True),
|
| 184 |
+
gr.update(value=None, visible=False),
|
| 185 |
+
gr.update(value=None, interactive=True),
|
| 186 |
+
gr.update(value=None, interactive=True),
|
| 187 |
+
gr.update(interactive=True),
|
| 188 |
+
gr.update(visible=False),
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
job = manager.get_job(job_id)
|
| 192 |
+
if job is None:
|
| 193 |
+
return load_job("")
|
| 194 |
+
|
| 195 |
+
if job["status"] == "processing":
|
| 196 |
+
status = f"🔄 Processing `{job['source_name']}` and `{job['target_name']}` …"
|
| 197 |
+
output = gr.update(value=None, visible=False)
|
| 198 |
+
src_file_update = gr.update(value=job["source_path"], interactive=False)
|
| 199 |
+
tgt_file_update = gr.update(value=job["target_path"], interactive=False)
|
| 200 |
+
cancel_visible = gr.update(visible=True)
|
| 201 |
+
return (
|
| 202 |
+
job_id,
|
| 203 |
+
status,
|
| 204 |
+
gr.update(value=job["source_lang"], interactive=False),
|
| 205 |
+
gr.update(value=job["target_lang"], interactive=False),
|
| 206 |
+
output,
|
| 207 |
+
src_file_update,
|
| 208 |
+
tgt_file_update,
|
| 209 |
+
gr.update(interactive=False),
|
| 210 |
+
cancel_visible,
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
elif job["status"] == "done":
|
| 214 |
+
status = f"✅ Bilingual EPUB ready (source: `{job['source_name']}`, target: `{job['target_name']}`)"
|
| 215 |
+
output = gr.update(value=job["output_path"], visible=True)
|
| 216 |
+
clear_file = gr.update(value=None, interactive=True)
|
| 217 |
+
return (
|
| 218 |
+
job_id,
|
| 219 |
+
status,
|
| 220 |
+
gr.update(value=job["source_lang"], interactive=True),
|
| 221 |
+
gr.update(value=job["target_lang"], interactive=True),
|
| 222 |
+
output,
|
| 223 |
+
clear_file,
|
| 224 |
+
clear_file,
|
| 225 |
+
gr.update(interactive=True),
|
| 226 |
+
gr.update(visible=False),
|
| 227 |
+
)
|
| 228 |
+
else:
|
| 229 |
+
status = f"❌ Error: {job['status']}"
|
| 230 |
+
clear_file = gr.update(value=None, interactive=True)
|
| 231 |
+
return (
|
| 232 |
+
job_id,
|
| 233 |
+
status,
|
| 234 |
+
gr.update(value=job["source_lang"], interactive=True),
|
| 235 |
+
gr.update(value=job["target_lang"], interactive=True),
|
| 236 |
+
gr.update(value=None, visible=False),
|
| 237 |
+
clear_file,
|
| 238 |
+
clear_file,
|
| 239 |
+
gr.update(interactive=True),
|
| 240 |
+
gr.update(visible=False),
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def cancel_current_job(job_id):
|
| 245 |
+
if job_id:
|
| 246 |
+
manager.cancel(job_id)
|
| 247 |
+
empty = load_job("")
|
| 248 |
+
return ("",) + empty
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
with gr.Blocks(title="📚 Bilingual Book Builder") as demo:
|
| 252 |
+
storage_hours = JOB_MAX_AGE_SECONDS // 3600
|
| 253 |
+
gr.Markdown(f"""
|
| 254 |
+
Upload a **source** (original) EPUB and a **target** (translation) EPUB to create a side‑by‑side bilingual book.
|
| 255 |
+
Processing may take hours – you can close this page and return later.
|
| 256 |
+
When ready, the bilingual EPUB will be stored for **{storage_hours} hours**.
|
| 257 |
+
""")
|
| 258 |
+
|
| 259 |
+
gr.Markdown("[⭐ Source Code](https://github.com/kerivin/bilingual-book-builder)")
|
| 260 |
+
|
| 261 |
+
job_state = gr.BrowserState("")
|
| 262 |
+
job_id_hidden = gr.Textbox(visible=False)
|
| 263 |
+
|
| 264 |
+
with gr.Row():
|
| 265 |
+
with gr.Column():
|
| 266 |
+
source_file = gr.File(label="Source EPUB", file_types=[".epub"], value=None)
|
| 267 |
+
target_file = gr.File(label="Target EPUB", file_types=[".epub"], value=None)
|
| 268 |
+
with gr.Column():
|
| 269 |
+
source_lang = gr.Textbox(label="Source language, e.g. en, ru, de", placeholder="Auto‑detect")
|
| 270 |
+
target_lang = gr.Textbox(label="Target language, e.g. en, ru, de", placeholder="Auto‑detect")
|
| 271 |
+
|
| 272 |
+
with gr.Row():
|
| 273 |
+
process_btn = gr.Button("🚀 Build Bilingual EPUB", variant="primary")
|
| 274 |
+
cancel_btn = gr.Button("❌ Cancel", variant="stop", visible=False)
|
| 275 |
+
|
| 276 |
+
status_msg = gr.Markdown("")
|
| 277 |
+
output_file = gr.File(label="Download Bilingual EPUB", interactive=False, visible=False)
|
| 278 |
+
|
| 279 |
+
process_btn.click(
|
| 280 |
+
fn=submit_job,
|
| 281 |
+
inputs=[source_file, target_file, source_lang, target_lang],
|
| 282 |
+
outputs=[job_state, status_msg],
|
| 283 |
+
).then(
|
| 284 |
+
fn=load_job,
|
| 285 |
+
inputs=job_state,
|
| 286 |
+
outputs=[
|
| 287 |
+
job_id_hidden,
|
| 288 |
+
status_msg,
|
| 289 |
+
source_lang,
|
| 290 |
+
target_lang,
|
| 291 |
+
output_file,
|
| 292 |
+
source_file,
|
| 293 |
+
target_file,
|
| 294 |
+
process_btn,
|
| 295 |
+
cancel_btn,
|
| 296 |
+
],
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
cancel_btn.click(
|
| 300 |
+
fn=cancel_current_job,
|
| 301 |
+
inputs=job_state,
|
| 302 |
+
outputs=[
|
| 303 |
+
job_state,
|
| 304 |
+
job_id_hidden,
|
| 305 |
+
status_msg,
|
| 306 |
+
source_lang,
|
| 307 |
+
target_lang,
|
| 308 |
+
output_file,
|
| 309 |
+
source_file,
|
| 310 |
+
target_file,
|
| 311 |
+
process_btn,
|
| 312 |
+
cancel_btn,
|
| 313 |
+
],
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
demo.load(
|
| 317 |
+
fn=load_job,
|
| 318 |
+
inputs=job_state,
|
| 319 |
+
outputs=[
|
| 320 |
+
job_id_hidden,
|
| 321 |
+
status_msg,
|
| 322 |
+
source_lang,
|
| 323 |
+
target_lang,
|
| 324 |
+
output_file,
|
| 325 |
+
source_file,
|
| 326 |
+
target_file,
|
| 327 |
+
process_btn,
|
| 328 |
+
cancel_btn,
|
| 329 |
+
],
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
refresh_btn = gr.Button("🔄 Check Status")
|
| 333 |
+
refresh_btn.click(
|
| 334 |
+
fn=load_job,
|
| 335 |
+
inputs=job_state,
|
| 336 |
+
outputs=[
|
| 337 |
+
job_id_hidden,
|
| 338 |
+
status_msg,
|
| 339 |
+
source_lang,
|
| 340 |
+
target_lang,
|
| 341 |
+
output_file,
|
| 342 |
+
source_file,
|
| 343 |
+
target_file,
|
| 344 |
+
process_btn,
|
| 345 |
+
cancel_btn,
|
| 346 |
+
],
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
if __name__ == "__main__":
|
| 350 |
+
demo.launch()
|