|
| 1 | +from typing import List, AsyncGenerator |
| 2 | +from querent.common.types.collected_bytes import CollectedBytes |
| 3 | +from querent.ingestors.base_ingestor import BaseIngestor |
| 4 | +from querent.ingestors.ingestor_factory import IngestorFactory |
| 5 | +from querent.processors.async_processor import AsyncProcessor |
| 6 | +from querent.config.ingestor_config import IngestorBackend |
| 7 | + |
| 8 | + |
| 9 | +class TextIngestorFactory(IngestorFactory): |
| 10 | + SUPPORTED_EXTENSIONS = {"txt"} |
| 11 | + |
| 12 | + async def supports(self, file_extension: str) -> bool: |
| 13 | + return file_extension.lower() in self.SUPPORTED_EXTENSIONS |
| 14 | + |
| 15 | + async def create( |
| 16 | + self, file_extension: str, processors: List[AsyncProcessor] |
| 17 | + ) -> BaseIngestor: |
| 18 | + if not self.supports(file_extension): |
| 19 | + return None |
| 20 | + |
| 21 | + return TextIngestor(processors) |
| 22 | + |
| 23 | + |
| 24 | +class TextIngestor(BaseIngestor): |
| 25 | + def __init__(self, processors: List[AsyncProcessor]): |
| 26 | + super().__init__(IngestorBackend.TEXT) |
| 27 | + self.processors = processors |
| 28 | + |
| 29 | + async def ingest( |
| 30 | + self, poll_function: AsyncGenerator[CollectedBytes, None] |
| 31 | + ) -> AsyncGenerator[List[str], None]: |
| 32 | + try: |
| 33 | + collected_bytes = b"" |
| 34 | + current_file = None |
| 35 | + |
| 36 | + async for chunk_bytes in poll_function: |
| 37 | + if chunk_bytes.is_error(): |
| 38 | + continue |
| 39 | + |
| 40 | + if chunk_bytes.file != current_file: |
| 41 | + if current_file: |
| 42 | + text = await self.extract_and_process_text( |
| 43 | + CollectedBytes(file=current_file, data=collected_bytes) |
| 44 | + ) |
| 45 | + yield text |
| 46 | + |
| 47 | + collected_bytes = b"" |
| 48 | + current_file = chunk_bytes.file |
| 49 | + |
| 50 | + collected_bytes += chunk_bytes.data |
| 51 | + |
| 52 | + if current_file: |
| 53 | + text = await self.extract_and_process_text( |
| 54 | + CollectedBytes(file=current_file, data=collected_bytes) |
| 55 | + ) |
| 56 | + yield text |
| 57 | + |
| 58 | + except Exception as e: |
| 59 | + print(e) |
| 60 | + yield [] |
| 61 | + |
| 62 | + async def extract_and_process_text( |
| 63 | + self, collected_bytes: CollectedBytes |
| 64 | + ) -> List[str]: |
| 65 | + text = await self.extract_text_from_file(collected_bytes) |
| 66 | + return await self.process_data(text=text) |
| 67 | + |
| 68 | + async def extract_text_from_file(self, collected_bytes: CollectedBytes) -> str: |
| 69 | + text = collected_bytes.data.decode("utf-8") |
| 70 | + return text |
| 71 | + |
| 72 | + async def process_data(self, text: str) -> List[str]: |
| 73 | + processed_data = text |
| 74 | + for processor in self.processors: |
| 75 | + processed_data = await processor.process(processed_data) |
| 76 | + return processed_data |
0 commit comments