-
Notifications
You must be signed in to change notification settings - Fork 56
refactor(phase-5): core domain logic parsers #354
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Ahmath-Gadji
wants to merge
13
commits into
refactor/hexagonal
from
refactor/phase-5-core-domain-logic-parsers
Closed
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
dba5dbd
refactor(core/utils): extend ValidationError, add decode_bytes, extra…
Ahmath-Gadji d60d94b
refactor(core/models): ImageBlock contract + Document.as_temporary_file
Ahmath-Gadji 9dfbd1b
refactor(core/indexing): add text/image preprocessors, validators, co…
Ahmath-Gadji fcdcc66
feat(core/indexing/parsers): native parsers (text, html, md, image, d…
Ahmath-Gadji 714bb49
feat(parsers/pdf): OpenAI VLM PDF parser (core facade + services/infe…
Ahmath-Gadji e2fa735
feat(parsers): Marker + local-Whisper Ray-backed parsers
Ahmath-Gadji 93476a6
refactor(compat): re-export shims for moved utilities
Ahmath-Gadji 75551aa
docs(refactoring): log Phase 5D decisions
Ahmath-Gadji 3ddc6b4
test(core/indexing): cover preprocessors, validators, docx/doc/audio …
Ahmath-Gadji 548b161
refactor(core/indexing/parsers): register concrete parsers with parse…
Ahmath-Gadji d68a7b1
refactor(loaders): adapter shims onto core parsers + runtime fixes
Ahmath-Gadji d85a27e
fix(core/parsers): address CodeRabbit review issues
Ahmath-Gadji 57d80ad
fix(loaders): address CodeRabbit review issues on loader shims
Ahmath-Gadji File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
152 changes: 49 additions & 103 deletions
152
openrag/components/indexer/loaders/audio/local_whisper.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,121 +1,67 @@ | ||
| """ | ||
| Local Whisper-backed audio loader. | ||
|
|
||
| The Ray actor + pool that drive ``faster-whisper`` (``WhisperActor``, | ||
| ``WhisperPool``) and the services-side :class:`BasePooledParser` | ||
| implementation now live in | ||
| ``services/workers/parsers/whisper_workers.py``; this module re-exports | ||
| ``WhisperActor`` and ``WhisperPool`` for legacy import paths | ||
| (``components.indexer.loaders.audio.local_whisper.WhisperActor`` is | ||
| still used by the OpenAI audio loader for language detection, and by | ||
| ``utils/dependencies.py`` for the actor bootstrap). | ||
|
|
||
| ``LocalWhisperLoader`` is now a thin :class:`BaseLoader` adapter that | ||
| delegates to | ||
| :class:`core.indexing.parsers.audio.local_whisper.LocalWhisperParser`, | ||
| which itself wraps the services-side pool. New code should call the | ||
| core parser directly; this shim keeps the legacy loader-discovery path | ||
| alive until consumers migrate. | ||
| """ | ||
|
|
||
| import asyncio | ||
| from pathlib import Path | ||
|
|
||
| import ray | ||
| import torch | ||
| from config import load_config | ||
| from faster_whisper import WhisperModel | ||
| from core.indexing.parsers.audio.local_whisper import LocalWhisperParser | ||
| from core.models.document import Document as CoreDocument | ||
| from langchain_core.documents.base import Document | ||
| from services.workers.parsers.whisper_workers import ( # noqa: F401 (re-exported for legacy import paths) | ||
| LocalWhisperLoader as _ServicesWhisperPool, | ||
| ) | ||
| from services.workers.parsers.whisper_workers import ( # noqa: F401 | ||
| WhisperActor, | ||
| WhisperPool, | ||
| ) | ||
| from utils.logger import get_logger | ||
|
|
||
| from ..base import BaseLoader | ||
|
|
||
| logger = get_logger() | ||
| config = load_config() | ||
|
|
||
|
|
||
| if torch.cuda.is_available(): | ||
| WHISPER_NUM_GPUS = config.loader.local_whisper.whisper_num_gpus | ||
| else: # On CPU | ||
| WHISPER_NUM_GPUS = 0 | ||
|
|
||
| WHISPER_CONCURRENCY_PER_WORKER = config.loader.local_whisper.whisper_concurrency_per_worker | ||
|
|
||
|
|
||
| @ray.remote( | ||
| num_gpus=WHISPER_NUM_GPUS, max_restarts=5, max_concurrency=WHISPER_CONCURRENCY_PER_WORKER | ||
| ) # Ensure each worker processes one file at a time | ||
| class WhisperActor: | ||
| def __init__(self): | ||
| import torch | ||
| from config import load_config | ||
| from utils.logger import get_logger | ||
|
|
||
| self.logger = get_logger() | ||
| self.config = load_config() | ||
|
|
||
| device = "cuda" if torch.cuda.is_available() else "cpu" | ||
| compute_type = "float16" if device == "cuda" else "int8" | ||
| model_name = self.config.loader.local_whisper.model | ||
|
|
||
| self.logger.info("Loading Whisper model", model_name=model_name, device=device, compute_type=compute_type) | ||
| self.model = WhisperModel(model_name, device=device, compute_type=compute_type) | ||
| self.logger.info("Whisper model loaded successfully", model_name=model_name, device=device) | ||
|
|
||
| async def transcribe(self, wav_path: str | Path) -> str: | ||
| self.logger.info("Transcribing audio file", file_path=Path(wav_path).name) | ||
|
|
||
| def _transcribe_sync() -> str: | ||
| segments, _ = self.model.transcribe(str(wav_path)) | ||
| return "".join(segment.text for segment in segments) | ||
|
|
||
| return await asyncio.to_thread(_transcribe_sync) | ||
|
|
||
| async def detect_language(self, wav_path: str | Path, fallback_language="en") -> str: | ||
| try: | ||
| self.logger.info("Detecting language for audio file", file_path=Path(wav_path).name) | ||
|
|
||
| def _detect_language_sync() -> str: | ||
| # beam_size=1 + max_new_tokens=1 runs only language detection, no full transcription | ||
| _, info = self.model.transcribe(str(wav_path), beam_size=1, max_new_tokens=1) | ||
| return info.language | ||
|
|
||
| return await asyncio.to_thread(_detect_language_sync) | ||
|
|
||
| except Exception as e: | ||
| self.logger.error("Error detecting language", error=str(e)) | ||
| return fallback_language | ||
|
|
||
|
|
||
| @ray.remote | ||
| class WhisperPool: | ||
| def __init__(self): | ||
| from utils.logger import get_logger | ||
|
|
||
| self.logger = get_logger() | ||
|
|
||
| n_workers = config.loader.local_whisper.whisper_n_workers | ||
| self.logger.info(f"Starting WhisperPool with {n_workers} workers") | ||
| self.workers = [WhisperActor.remote() for _ in range(n_workers)] | ||
| self._pending = [0] * n_workers | ||
|
|
||
| async def transcribe(self, path): | ||
| from components.ray_utils import call_ray_actor_with_timeout, retry_with_backoff | ||
|
|
||
| timeout = config.loader.local_whisper.whisper_timeout | ||
|
|
||
| async def attempt(i: int): | ||
| idx = min(range(len(self._pending)), key=lambda j: self._pending[j]) | ||
| self._pending[idx] += 1 | ||
| try: | ||
| return await call_ray_actor_with_timeout( | ||
| self.workers[idx].transcribe.remote(path), | ||
| timeout=timeout, | ||
| task_description=f"WhisperPool transcribe ({path})", | ||
| ) | ||
| finally: | ||
| self._pending[idx] -= 1 | ||
|
|
||
| return await retry_with_backoff( | ||
| attempt, | ||
| max_retries=config.loader.local_whisper.whisper_max_task_retry, | ||
| base_delay=config.loader.local_whisper.whisper_retry_base_delay, | ||
| task_description=f"WhisperPool transcribe ({path})", | ||
| ) | ||
|
|
||
|
|
||
| class LocalWhisperLoader(BaseLoader): | ||
| """Adapter shim — delegates to ``LocalWhisperParser`` via the services-side pool.""" | ||
|
|
||
| def __init__(self, **kwargs): | ||
| super().__init__(**kwargs) | ||
| self.whisper_actor: WhisperPool = ray.get_actor("WhisperPool", namespace="openrag") | ||
| self._parser = LocalWhisperParser(pool=_ServicesWhisperPool()) | ||
|
|
||
| async def aload_document(self, file_path, metadata: dict = None, save_markdown=False): | ||
| path = Path(file_path) | ||
| raw_bytes = await asyncio.to_thread(path.read_bytes) | ||
| core_doc = CoreDocument( | ||
| filename=path.name, | ||
| content_type=CoreDocument.detect_content_type(path.name), | ||
| raw_bytes=raw_bytes, | ||
| metadata=dict(metadata) if metadata else {}, | ||
| ) | ||
| try: | ||
| content = await self.whisper_actor.transcribe.remote(file_path) | ||
| doc = Document(page_content=content, metadata=metadata) | ||
| if save_markdown: | ||
| self.save_content(content, str(file_path)) | ||
| return doc | ||
| processed = await self._parser.parse(core_doc) | ||
| except Exception as e: | ||
| self.logger.error("Error loading document", error=str(e)) | ||
| raise e | ||
| logger.error("Error loading document", error=str(e)) | ||
| raise | ||
|
|
||
| content = "".join(b.text for b in processed.text_blocks) | ||
| doc = Document(page_content=content, metadata=dict(metadata) if metadata else {}) | ||
| if save_markdown: | ||
| self.save_content(content, str(file_path)) | ||
| return doc |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.