Download storage_manager.py from Asem75/aiocr_asistant: direct link, hf CLI and curl.
- Browser
- Download file 27.9 kB
-
https://huggingface.co/datasets/Asem75/aiocr_asistant/resolve/main/storage_manager.py
- Command line
-
hf download hf://datasets/Asem75/aiocr_asistant/storage_manager.py
-
curl -L -o storage_manager.py https://huggingface.co/datasets/Asem75/aiocr_asistant/resolve/main/storage_manager.py
27.9 kB
| # 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" | |
| 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 "" | |
| 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) خزنة المادة الخام | |
| def raw_book_root(book_id: str) -> str: | |
| return f"raw_books/{book_id}" | |
| 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}" | |
| def raw_book_manifest_path(cls, book_id: str) -> str: | |
| return f"{cls.raw_book_root(book_id)}/raw_manifest.json" | |
| # 2) خزنة النص المجهز والمقسم | |
| def book_root(book_id: str) -> str: | |
| # الاسم محفوظ للتوافق مع بقية النظام، لكنه الآن يعني prepared_books. | |
| return f"prepared_books/{book_id}" | |
| def book_original_text_path(cls, book_id: str) -> str: | |
| # للتوافق فقط مع نسخ أقدم. الأصل الحقيقي يجب أن يكون في raw_books. | |
| return f"{cls.book_root(book_id)}/source/original.txt" | |
| def book_prepared_text_path(cls, book_id: str) -> str: | |
| return f"{cls.book_root(book_id)}/prepared/full.txt" | |
| def book_manifest_path(cls, book_id: str) -> str: | |
| return f"{cls.book_root(book_id)}/manifest.json" | |
| 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}" | |
| def book_segmentation_manifest_path(cls, book_id: str, engine: str) -> str: | |
| return f"{cls.book_conversion_root(book_id, engine)}/segmentation_manifest.json" | |
| 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) خزنة الصوت | |
| def audio_book_root(book_id: str) -> str: | |
| return f"audio_books/{book_id}" | |
| 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}" | |
| 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" | |
| 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" | |
| 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" | |
| 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" | |
| 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" | |
| 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) | |