File size: 13,117 Bytes
89ed4f8
f78e4c8
89ed4f8
 
ade5ccc
89ed4f8
f78e4c8
89ed4f8
 
 
 
 
 
 
e1db0f4
89ed4f8
8928d1b
 
78c6a05
89ed4f8
 
 
b56dbe4
f78e4c8
89ed4f8
 
 
 
ade5ccc
89ed4f8
 
 
16fee07
ade5ccc
16fee07
ade5ccc
 
 
 
 
 
 
89ed4f8
 
 
 
e1db0f4
4cc483e
 
89ed4f8
 
 
8e750ca
89ed4f8
8e750ca
78c6a05
 
ecf3642
493d106
ade5ccc
89ed4f8
e1db0f4
89ed4f8
753e08d
 
 
 
89ed4f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e601273
89ed4f8
ade5ccc
89ed4f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ade5ccc
 
 
 
 
 
 
 
 
89ed4f8
ade5ccc
89ed4f8
 
 
 
 
e601273
89ed4f8
 
 
 
753e08d
 
 
 
a059723
 
 
753e08d
 
89ed4f8
 
 
 
e601273
 
 
 
 
89ed4f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e601273
 
89ed4f8
 
 
 
 
 
 
 
 
 
 
 
 
 
e4c8fbf
89ed4f8
 
5c2f1aa
 
 
 
 
 
 
 
 
89ed4f8
 
 
 
 
 
 
ade5ccc
e4c8fbf
ade5ccc
 
e4c8fbf
 
ade5ccc
e4c8fbf
ade5ccc
89ed4f8
 
 
e4c8fbf
 
5c2f1aa
 
 
 
 
89ed4f8
 
 
 
 
 
 
e4c8fbf
 
5c2f1aa
 
 
 
 
89ed4f8
e4c8fbf
89ed4f8
 
 
 
 
e4c8fbf
 
5c2f1aa
 
 
 
 
89ed4f8
 
 
7a61a92
 
e4c8fbf
 
 
7a61a92
 
e4c8fbf
 
 
 
7a61a92
 
e4c8fbf
 
 
 
 
 
 
 
 
 
 
 
 
5c2f1aa
e4c8fbf
89ed4f8
 
e4c8fbf
89ed4f8
 
 
 
 
10c87d1
ce595e8
89ed4f8
ce595e8
0c9dc93
ce595e8
89ed4f8
ce595e8
e601273
ce595e8
 
e601273
89ed4f8
 
 
 
5416f6a
d6e116d
e4c8fbf
 
7a61a92
5488874
 
e4c8fbf
7a61a92
5488874
1b1d78f
5488874
 
 
3a104c2
 
e4c8fbf
 
5c2f1aa
 
 
 
 
 
 
 
 
e4c8fbf
 
89ed4f8
e4c8fbf
7a61a92
 
e4c8fbf
89ed4f8
 
 
e4c8fbf
d6e116d
e4c8fbf
89ed4f8
 
e4c8fbf
89ed4f8
 
e4c8fbf
89ed4f8
 
e4c8fbf
89ed4f8
 
e4c8fbf
89ed4f8
 
e4c8fbf
89ed4f8
b56dbe4
 
 
 
 
 
89ed4f8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
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()