|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Defines common functionality between executors.""" |
| 16 | + |
| 17 | +from concurrent import futures |
| 18 | + |
| 19 | +from garf_executors import execution_context |
| 20 | + |
| 21 | + |
| 22 | +class Executor: |
| 23 | + """Defines common functionality between executors.""" |
| 24 | + |
| 25 | + def execute_batch( |
| 26 | + self, |
| 27 | + batch: dict[str, str], |
| 28 | + context: execution_context.ExecutionContext, |
| 29 | + parallel_threshold: int = 10, |
| 30 | + ) -> list[str]: |
| 31 | + """Executes batch of queries for a common context. |
| 32 | +
|
| 33 | + Args: |
| 34 | + batch: Mapping between query_title and its text. |
| 35 | + context: Execution context. |
| 36 | + parallel_threshold: Number of queries to execute in parallel. |
| 37 | +
|
| 38 | + Returns: |
| 39 | + Results of execution. |
| 40 | + """ |
| 41 | + results = [] |
| 42 | + with futures.ThreadPoolExecutor(max_workers=parallel_threshold) as executor: |
| 43 | + future_to_query = { |
| 44 | + executor.submit( |
| 45 | + self.execute, |
| 46 | + query, |
| 47 | + title, |
| 48 | + context, |
| 49 | + ): query |
| 50 | + for title, query in batch.items() |
| 51 | + } |
| 52 | + for future in futures.as_completed(future_to_query): |
| 53 | + results.append(future.result()) |
| 54 | + return results |
0 commit comments