File size: 27,891 Bytes
087187f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
# storage_manager.py
# -*- coding: utf-8 -*-

import io
import json
import os
import tempfile
import threading
import time
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Sequence, Tuple

from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
from report_manager import ReportManager


VERSION = "storage_manager_v5_single_repo_three_internal_folders"


@dataclass(frozen=True)
class RepositoryConfig:
    key: str
    repo_id: str
    repo_type: str = "dataset"
    input_file: str = "tts.txt"
    output_file: str = "tts.wav"


class StorageManager:
    LEGACY_REPO_KEY = "aiocr_assistant"
    RAW_BOOKS_REPO_KEY = "raw_books"
    PREPARED_BOOKS_REPO_KEY = "prepared_books"
    AUDIO_BOOKS_REPO_KEY = "audio_books"

    """
    مدير التخزين المركزي لمحطة الصوت.

    يدعم عقد TTS المباشر:
      tts.txt -> tts.wav

    ويضيف عقد الكتب:
      books/<book_id>/source/original.txt
      books/<book_id>/prepared/full.txt
      books/<book_id>/manifest.json
      books/<book_id>/conversions/<engine>/text_segments/segment_XXXX.txt
      books/<book_id>/conversions/<engine>/audio_segments/segment_XXXX.mp3
      books/<book_id>/conversions/<engine>/full/book_full.mp3

    BookPreparationManager و AITaskManager لا يتعاملان مباشرة مع Hugging Face.
    """

    def __init__(self, token: Optional[str] = None, report_manager: Optional[ReportManager] = None):
        self.token = (token or os.getenv("HF_TOKEN", "")).strip()
        self.report_manager = report_manager
        self._report_context = threading.local()
        self.api = HfApi(token=self.token or None)

        # Dataset واحد فعلياً على Hugging Face:
        # Asem75/aiocr_asistant
        #
        # المفاتيح raw_books / prepared_books / audio_books ليست Repositories مستقلة،
        # بل أسماء منطقية لثلاثة مجلدات داخل الـDataset نفسه.
        # نبقي المفاتيح الثلاثة للتوافق مع بقية النظام، لكن repo_id واحد للجميع.
        self._repositories: Dict[str, RepositoryConfig] = {
            "aiocr_assistant": RepositoryConfig(
                key="aiocr_assistant",
                repo_id=os.getenv(
                    "AIOCR_DATASET_REPO",
                    "Asem75/aiocr_asistant",
                ).strip(),
                repo_type="dataset",
                input_file="tts.txt",
                output_file="tts.wav",
            ),
            "raw_books": RepositoryConfig(
                key="raw_books",
                repo_id=os.getenv(
                    "AIOCR_RAW_BOOKS_REPO",
                    "Asem75/aiocr_asistant",
                ).strip(),
                repo_type="dataset",
                input_file="",
                output_file="",
            ),
            "prepared_books": RepositoryConfig(
                key="prepared_books",
                repo_id=os.getenv(
                    "AIOCR_PREPARED_BOOKS_REPO",
                    "Asem75/aiocr_asistant",
                ).strip(),
                repo_type="dataset",
                input_file="",
                output_file="",
            ),
            "audio_books": RepositoryConfig(
                key="audio_books",
                repo_id=os.getenv(
                    "AIOCR_AUDIO_BOOKS_REPO",
                    "Asem75/aiocr_asistant",
                ).strip(),
                repo_type="dataset",
                input_file="",
                output_file="",
            ),
        }
        self._repo_locks: Dict[str, threading.Lock] = {}
        self._load_extra_repositories()

    def set_report_context(self, *, trace_id: str = "", task_id: str = "", book_id: str = "") -> None:
        self._report_context.trace_id = trace_id or ""
        self._report_context.task_id = task_id or ""
        self._report_context.book_id = book_id or ""

    @contextmanager
    def report_context(self, *, trace_id: str = "", task_id: str = "", book_id: str = ""):
        old = (getattr(self._report_context, "trace_id", ""), getattr(self._report_context, "task_id", ""), getattr(self._report_context, "book_id", ""))
        self.set_report_context(trace_id=trace_id, task_id=task_id, book_id=book_id)
        try:
            yield self
        finally:
            self.set_report_context(trace_id=old[0], task_id=old[1], book_id=old[2])

    def _report(self, event: str, *, status: str = "ok", repo_key: str = "", path: str = "", duration_ms: float = 0.0, input_size_bytes: int = 0, output_size_bytes: int = 0, error: str = "", metadata: Optional[Dict[str, Any]] = None) -> None:
        if not self.report_manager:
            return
        try:
            self.report_manager.record(
                event=event,
                trace_id=getattr(self._report_context, "trace_id", ""),
                task_id=getattr(self._report_context, "task_id", ""),
                book_id=getattr(self._report_context, "book_id", ""),
                manager="StorageManager",
                status=status,
                repo_key=repo_key,
                path=path,
                duration_ms=duration_ms,
                input_size_bytes=input_size_bytes,
                output_size_bytes=output_size_bytes,
                metadata=metadata or {},
                error=error,
            )
        except Exception:
            pass

    # ---------------------------------------------------------
    # إعداد الخزنات
    # ---------------------------------------------------------

    def _load_extra_repositories(self) -> None:
        raw = os.getenv("AIOCR_TTS_REPOSITORIES_JSON", "").strip()
        if not raw:
            return
        try:
            data = json.loads(raw)
        except Exception as exc:
            print("⚠️ تعذر قراءة AIOCR_TTS_REPOSITORIES_JSON:", exc)
            return
        if not isinstance(data, dict):
            return

        for key, item in data.items():
            if not isinstance(item, dict):
                continue
            repo_id = str(item.get("repo_id", "")).strip()
            if not repo_id:
                continue
            self._repositories[str(key)] = RepositoryConfig(
                key=str(key),
                repo_id=repo_id,
                repo_type=str(item.get("repo_type", "dataset")).strip() or "dataset",
                input_file=str(item.get("input_file", "tts.txt")).strip() or "tts.txt",
                output_file=str(item.get("output_file", "tts.wav")).strip() or "tts.wav",
            )

    def list_repository_keys(self) -> List[str]:
        return sorted(self._repositories.keys())

    def get_repository(self, repo_key: str) -> RepositoryConfig:
        key = (repo_key or "aiocr_assistant").strip()
        if key not in self._repositories:
            raise KeyError(f"الخزنة غير معرفة في StorageManager: {key}")
        return self._repositories[key]

    def get_repository_lock(self, repo_key: str) -> threading.Lock:
        key = (repo_key or "aiocr_assistant").strip()
        if key not in self._repo_locks:
            self._repo_locks[key] = threading.Lock()
        return self._repo_locks[key]

    def describe_repository(self, repo_key: str) -> Dict[str, str]:
        repo = self.get_repository(repo_key)
        role_map = {
            self.LEGACY_REPO_KEY: "legacy_api_tts",
            self.RAW_BOOKS_REPO_KEY: "raw_books",
            self.PREPARED_BOOKS_REPO_KEY: "prepared_books",
            self.AUDIO_BOOKS_REPO_KEY: "audio_books",
        }
        return {
            "repo_key": repo.key,
            "repo_id": repo.repo_id,
            "repo_type": repo.repo_type,
            "input_file": repo.input_file,
            "output_file": repo.output_file,
            "role": role_map.get(repo.key, "custom"),
        }

    # ---------------------------------------------------------
    # عمليات عامة
    # ---------------------------------------------------------

    def list_repo_files(self, repo_key: str) -> List[str]:
        repo = self.get_repository(repo_key)
        files = self.api.list_repo_files(
            repo_id=repo.repo_id,
            repo_type=repo.repo_type,
            token=self.token or None,
        )
        return sorted(str(path) for path in files if path and not str(path).endswith("/"))

    def file_exists(self, repo_key: str, path_in_repo: str, known_files: Optional[set] = None) -> bool:
        target = (path_in_repo or "").strip()
        if not target:
            return False
        if known_files is not None:
            return target in known_files
        return target in set(self.list_repo_files(repo_key))

    def list_text_files(self, repo_key: str) -> List[str]:
        return [p for p in self.list_repo_files(repo_key) if p.lower().endswith(".txt")]

    def list_audio_files(self, repo_key: str) -> List[str]:
        extensions = (".wav", ".mp3", ".m4a", ".ogg", ".flac")
        return [p for p in self.list_repo_files(repo_key) if p.lower().endswith(extensions)]

    def list_report_files(
        self,
        repo_key: str,
        *,
        book_id: str = "",
        engine: str = "",
    ) -> List[str]:
        files = self.list_repo_files(repo_key)
        prefix = ""
        if book_id:
            prefix = (
                self.audio_book_conversion_root(book_id, engine)
                if engine
                else self.book_root(book_id)
            )
            prefix = prefix.rstrip("/") + "/"
        reports = [
            path for path in files
            if path.lower().endswith(".json")
            and "/reports/" in f"/{path.lower()}"
            and "/report_" in f"/{path.lower()}"
            and (not prefix or path.startswith(prefix))
        ]
        return sorted(reports, reverse=True)

    def download_file(self, repo_key: str, file_path: str) -> str:
        repo = self.get_repository(repo_key)
        selected = (file_path or "").strip()
        if not selected:
            raise ValueError("لم يتم تحديد ملف من الخزنة.")
        started = time.perf_counter()
        try:
            local_path = hf_hub_download(
                repo_id=repo.repo_id, filename=selected, repo_type=repo.repo_type,
                token=self.token or None, force_download=True,
            )
            size = os.path.getsize(local_path) if os.path.isfile(local_path) else 0
            self._report("storage.download.completed", repo_key=repo_key, path=selected,
                         duration_ms=(time.perf_counter()-started)*1000, output_size_bytes=size)
            return local_path
        except Exception as exc:
            self._report("storage.download.failed", status="error", repo_key=repo_key, path=selected,
                         duration_ms=(time.perf_counter()-started)*1000, error=str(exc))
            raise

    def read_text_file(self, repo_key: str, file_path: Optional[str] = None) -> str:
        repo = self.get_repository(repo_key)
        selected = (file_path or repo.input_file).strip()
        local_path = self.download_file(repo_key, selected)
        with open(local_path, "r", encoding="utf-8-sig") as handle:
            text = handle.read()
        if not text.strip():
            raise ValueError(f"الملف {selected} موجود لكنه فارغ.")
        return text

    def read_json(self, repo_key: str, file_path: str) -> Dict[str, Any]:
        local_path = self.download_file(repo_key, file_path)
        with open(local_path, "r", encoding="utf-8-sig") as handle:
            data = json.load(handle)
        if not isinstance(data, dict):
            raise ValueError(f"ملف JSON ليس كائناً: {file_path}")
        return data

    def upload_file(self, repo_key: str, local_path: str, path_in_repo: str) -> str:
        repo = self.get_repository(repo_key)
        if not os.path.isfile(local_path):
            raise FileNotFoundError(f"الملف المحلي غير موجود: {local_path}")
        target = (path_in_repo or "").strip()
        if not target:
            raise ValueError("مسار الحفظ داخل الخزنة فارغ.")
        size = os.path.getsize(local_path)
        started = time.perf_counter()
        try:
            self.api.upload_file(path_or_fileobj=local_path, path_in_repo=target, repo_id=repo.repo_id,
                                 repo_type=repo.repo_type, token=self.token or None)
            self._report("storage.upload.completed", repo_key=repo_key, path=target,
                         duration_ms=(time.perf_counter()-started)*1000, input_size_bytes=size)
            return target
        except Exception as exc:
            self._report("storage.upload.failed", status="error", repo_key=repo_key, path=target,
                         duration_ms=(time.perf_counter()-started)*1000, input_size_bytes=size, error=str(exc))
            raise

    def write_text(self, repo_key: str, path_in_repo: str, text: str) -> str:
        repo = self.get_repository(repo_key)
        payload = (text or "").encode("utf-8")
        started = time.perf_counter()
        try:
            self.api.upload_file(path_or_fileobj=io.BytesIO(payload), path_in_repo=path_in_repo, repo_id=repo.repo_id,
                                 repo_type=repo.repo_type, token=self.token or None)
            self._report("storage.upload.completed", repo_key=repo_key, path=path_in_repo,
                         duration_ms=(time.perf_counter()-started)*1000, input_size_bytes=len(payload), metadata={"content_type":"text"})
            return path_in_repo
        except Exception as exc:
            self._report("storage.upload.failed", status="error", repo_key=repo_key, path=path_in_repo,
                         duration_ms=(time.perf_counter()-started)*1000, input_size_bytes=len(payload), error=str(exc))
            raise

    def write_json(self, repo_key: str, path_in_repo: str, data: Dict[str, Any]) -> str:
        payload = json.dumps(data, ensure_ascii=False, indent=2).encode("utf-8")
        repo = self.get_repository(repo_key)
        started = time.perf_counter()
        try:
            self.api.upload_file(path_or_fileobj=io.BytesIO(payload), path_in_repo=path_in_repo, repo_id=repo.repo_id,
                                 repo_type=repo.repo_type, token=self.token or None)
            self._report("storage.upload.completed", repo_key=repo_key, path=path_in_repo,
                         duration_ms=(time.perf_counter()-started)*1000, input_size_bytes=len(payload), metadata={"content_type":"json"})
            return path_in_repo
        except Exception as exc:
            self._report("storage.upload.failed", status="error", repo_key=repo_key, path=path_in_repo,
                         duration_ms=(time.perf_counter()-started)*1000, input_size_bytes=len(payload), error=str(exc))
            raise

    def upload_many(self, repo_key: str, items: Sequence[Tuple[str, str]], commit_message: str) -> List[str]:
        repo = self.get_repository(repo_key)
        operations: List[CommitOperationAdd] = []
        targets: List[str] = []
        total_size = 0
        for local_path, target in items:
            if not os.path.isfile(local_path):
                raise FileNotFoundError(f"الملف المحلي غير موجود: {local_path}")
            operations.append(CommitOperationAdd(path_in_repo=target, path_or_fileobj=local_path))
            targets.append(target)
            total_size += os.path.getsize(local_path)
        started = time.perf_counter()
        try:
            if operations:
                self.api.create_commit(repo_id=repo.repo_id, repo_type=repo.repo_type, operations=operations,
                                       commit_message=commit_message, token=self.token or None)
            self._report("storage.upload.completed", repo_key=repo_key, path=f"batch:{len(targets)}",
                         duration_ms=(time.perf_counter()-started)*1000, input_size_bytes=total_size,
                         metadata={"files_count":len(targets),"targets":targets})
            return targets
        except Exception as exc:
            self._report("storage.upload.failed", status="error", repo_key=repo_key, path=f"batch:{len(targets)}",
                         duration_ms=(time.perf_counter()-started)*1000, input_size_bytes=total_size, error=str(exc))
            raise

    # ---------------------------------------------------------
    # عقد TTS المباشر
    # ---------------------------------------------------------

    def read_tts_text(self, repo_key: str) -> str:
        return self.read_text_file(repo_key, self.get_repository(repo_key).input_file).strip()

    def upload_tts_audio(self, repo_key: str, local_wav_path: str) -> str:
        repo = self.get_repository(repo_key)
        return self.upload_file(repo_key, local_wav_path, repo.output_file)

    def resolve_output_path(self, repo_key: str, source_text_file: Optional[str] = None) -> str:
        repo = self.get_repository(repo_key)
        selected = (source_text_file or repo.input_file).strip()
        if selected == repo.input_file:
            return repo.output_file
        root, _ = os.path.splitext(selected)
        return root + ".wav"

    def upload_audio(self, repo_key: str, local_wav_path: str, output_path: Optional[str] = None) -> str:
        repo = self.get_repository(repo_key)
        return self.upload_file(repo_key, local_wav_path, (output_path or repo.output_file).strip())

    def download_audio_file(self, repo_key: str, file_path: str) -> str:
        return self.download_file(repo_key, file_path)

    # ---------------------------------------------------------
    # مسارات الكتب - ثلاث خزنات منفصلة
    # ---------------------------------------------------------

    # 1) خزنة المادة الخام
    @staticmethod
    def raw_book_root(book_id: str) -> str:
        return f"raw_books/{book_id}"

    @classmethod
    def raw_book_original_path(cls, book_id: str, filename: str = "original.txt") -> str:
        safe_name = (filename or "original.txt").strip().replace("/", "_").replace("\\", "_")
        return f"{cls.raw_book_root(book_id)}/{safe_name}"

    @classmethod
    def raw_book_manifest_path(cls, book_id: str) -> str:
        return f"{cls.raw_book_root(book_id)}/raw_manifest.json"

    # 2) خزنة النص المجهز والمقسم
    @staticmethod
    def book_root(book_id: str) -> str:
        # الاسم محفوظ للتوافق مع بقية النظام، لكنه الآن يعني prepared_books.
        return f"prepared_books/{book_id}"

    @classmethod
    def book_original_text_path(cls, book_id: str) -> str:
        # للتوافق فقط مع نسخ أقدم. الأصل الحقيقي يجب أن يكون في raw_books.
        return f"{cls.book_root(book_id)}/source/original.txt"

    @classmethod
    def book_prepared_text_path(cls, book_id: str) -> str:
        return f"{cls.book_root(book_id)}/prepared/full.txt"

    @classmethod
    def book_manifest_path(cls, book_id: str) -> str:
        return f"{cls.book_root(book_id)}/manifest.json"

    @classmethod
    def book_conversion_root(cls, book_id: str, engine: str) -> str:
        # هذا الجذر خاص بالتقسيم النصي للمحرك داخل prepared_books.
        safe_engine = (engine or "unknown").strip().lower()
        return f"{cls.book_root(book_id)}/conversions/{safe_engine}"

    @classmethod
    def book_segmentation_manifest_path(cls, book_id: str, engine: str) -> str:
        return f"{cls.book_conversion_root(book_id, engine)}/segmentation_manifest.json"

    @classmethod
    def book_text_segment_path(cls, book_id: str, engine: str, segment_id: str) -> str:
        return f"{cls.book_conversion_root(book_id, engine)}/text_segments/{segment_id}.txt"

    # 3) خزنة الصوت
    @staticmethod
    def audio_book_root(book_id: str) -> str:
        return f"audio_books/{book_id}"

    @classmethod
    def audio_book_conversion_root(cls, book_id: str, engine: str) -> str:
        safe_engine = (engine or "unknown").strip().lower()
        return f"{cls.audio_book_root(book_id)}/conversions/{safe_engine}"

    @classmethod
    def book_audio_segment_path(cls, book_id: str, engine: str, segment_id: str) -> str:
        return f"{cls.audio_book_conversion_root(book_id, engine)}/audio_segments/{segment_id}.mp3"

    @classmethod
    def book_conversion_manifest_path(cls, book_id: str, engine: str) -> str:
        return f"{cls.audio_book_conversion_root(book_id, engine)}/conversion_manifest.json"

    @classmethod
    def book_full_audio_path(cls, book_id: str, engine: str) -> str:
        return f"{cls.audio_book_conversion_root(book_id, engine)}/full/book_full.mp3"

    @classmethod
    def book_report_path(cls, book_id: str, engine: str, trace_id: str) -> str:
        safe_trace = (trace_id or "latest").strip().replace("/", "_").replace("\\", "_")
        return f"{cls.audio_book_conversion_root(book_id, engine)}/reports/report_{safe_trace}.json"

    @classmethod
    def book_operation_report_path(cls, book_id: str, trace_id: str) -> str:
        safe_trace = (trace_id or "latest").strip().replace("/", "_").replace("\\", "_")
        return f"{cls.book_root(book_id)}/reports/report_{safe_trace}.json"

    @staticmethod
    def system_report_path(trace_id: str) -> str:
        safe_trace = (trace_id or "latest").strip().replace("/", "_").replace("\\", "_")
        return f"reports/system/report_{safe_trace}.json"

    def save_raw_book_bundle(
        self,
        repo_key: str,
        book_id: str,
        title: str,
        source_files: Sequence[Tuple[str, str]],
        *,
        created_at: str,
        total_chars: int,
    ) -> Dict[str, Any]:
        """
        يحفظ المادة الخام فقط في خزنة raw_books.
        source_files = [(local_path, original_filename), ...]
        """
        if repo_key != self.RAW_BOOKS_REPO_KEY:
            raise ValueError(
                f"المادة الخام يجب أن تحفظ في الخزنة {self.RAW_BOOKS_REPO_KEY} وليس {repo_key}."
            )

        manifest = {
            "book_id": book_id,
            "book_name": title,
            "created_at": created_at,
            "source_files": [name for _, name in source_files],
            "total_files": len(source_files),
            "total_chars": int(total_chars or 0),
        }

        with tempfile.TemporaryDirectory(prefix="aiocr_raw_book_") as tmp:
            items: List[Tuple[str, str]] = []
            for index, (local_path, original_name) in enumerate(source_files, start=1):
                if not os.path.isfile(local_path):
                    raise FileNotFoundError(f"الملف الخام غير موجود: {local_path}")
                safe_name = (original_name or f"original_{index:02d}.txt").strip().replace("/", "_").replace("\\", "_")
                target = self.raw_book_original_path(book_id, safe_name)
                items.append((local_path, target))

            local_manifest = os.path.join(tmp, "raw_manifest.json")
            with open(local_manifest, "w", encoding="utf-8") as handle:
                json.dump(manifest, handle, ensure_ascii=False, indent=2)
            items.append((local_manifest, self.raw_book_manifest_path(book_id)))

            self.upload_many(
                repo_key,
                items,
                commit_message=f"Save raw book {book_id}",
            )

        return {
            "manifest": manifest,
            "manifest_path": self.raw_book_manifest_path(book_id),
            "root": self.raw_book_root(book_id),
        }

    def save_prepared_book_bundle(
        self,
        repo_key: str,
        book_id: str,
        original_text: str,
        prepared_text: str,
        manifest: Dict[str, Any],
    ) -> Dict[str, str]:
        paths = {
            "original": self.book_original_text_path(book_id),
            "prepared": self.book_prepared_text_path(book_id),
            "manifest": self.book_manifest_path(book_id),
        }
        with tempfile.TemporaryDirectory(prefix="aiocr_book_prepare_") as tmp:
            local_original = os.path.join(tmp, "original.txt")
            local_prepared = os.path.join(tmp, "full.txt")
            local_manifest = os.path.join(tmp, "manifest.json")
            with open(local_original, "w", encoding="utf-8") as handle:
                handle.write(original_text or "")
            with open(local_prepared, "w", encoding="utf-8") as handle:
                handle.write(prepared_text or "")
            with open(local_manifest, "w", encoding="utf-8") as handle:
                json.dump(manifest, handle, ensure_ascii=False, indent=2)
            self.upload_many(
                repo_key,
                [
                    (local_original, paths["original"]),
                    (local_prepared, paths["prepared"]),
                    (local_manifest, paths["manifest"]),
                ],
                commit_message=f"Prepare book {book_id}",
            )
        return paths

    def save_book_segmentation(
        self,
        repo_key: str,
        book_id: str,
        engine: str,
        segments: List[Dict[str, Any]],
        manifest: Dict[str, Any],
    ) -> str:
        manifest_path = self.book_segmentation_manifest_path(book_id, engine)
        with tempfile.TemporaryDirectory(prefix="aiocr_book_segments_") as tmp:
            items: List[Tuple[str, str]] = []
            for item in segments:
                segment_id = str(item["segment_id"])
                local_path = os.path.join(tmp, f"{segment_id}.txt")
                with open(local_path, "w", encoding="utf-8") as handle:
                    handle.write(str(item.get("text") or ""))
                items.append((local_path, str(item["text_path"])))

            local_manifest = os.path.join(tmp, "segmentation_manifest.json")
            with open(local_manifest, "w", encoding="utf-8") as handle:
                json.dump(manifest, handle, ensure_ascii=False, indent=2)
            items.append((local_manifest, manifest_path))

            self.upload_many(
                repo_key,
                items,
                commit_message=f"Segment book {book_id} for {engine}",
            )
        return manifest_path

    def list_book_ids(self, repo_key: str) -> List[str]:
        prefix = "prepared_books/"
        suffix = "/manifest.json"
        book_ids: List[str] = []
        for path in self.list_repo_files(repo_key):
            if path.startswith(prefix) and path.endswith(suffix):
                middle = path[len(prefix):-len(suffix)]
                if middle and "/" not in middle:
                    book_ids.append(middle)
        return sorted(set(book_ids))

    def save_audio_segment(
        self,
        repo_key: str,
        book_id: str,
        engine: str,
        segment_id: str,
        local_mp3_path: str,
    ) -> str:
        target = self.book_audio_segment_path(book_id, engine, segment_id)
        return self.upload_file(repo_key, local_mp3_path, target)

    def save_conversion_manifest(
        self,
        repo_key: str,
        book_id: str,
        engine: str,
        manifest: Dict[str, Any],
    ) -> str:
        target = self.book_conversion_manifest_path(book_id, engine)
        return self.write_json(repo_key, target, manifest)

    def save_full_book_audio(
        self,
        repo_key: str,
        book_id: str,
        engine: str,
        local_mp3_path: str,
    ) -> str:
        target = self.book_full_audio_path(book_id, engine)
        return self.upload_file(repo_key, local_mp3_path, target)