xref: /aosp_15_r20/external/tflite-support/tensorflow_lite_support/cc/task/text/qa/question_answerer.h (revision b16991f985baa50654c05c5adbb3c8bbcfb40082)
1 /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
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     http://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 
16 #ifndef TENSORFLOW_LITE_SUPPORT_CC_TASK_TEXT_QA_QUESTION_ANSWERER_H_
17 #define TENSORFLOW_LITE_SUPPORT_CC_TASK_TEXT_QA_QUESTION_ANSWERER_H_
18 
19 #include <string>
20 #include <utility>
21 #include <vector>
22 
23 #include "tensorflow_lite_support/cc/task/core/base_task_api.h"
24 #include "tensorflow_lite_support/cc/task/core/tflite_engine.h"
25 
26 namespace tflite {
27 namespace task {
28 namespace text {
29 namespace qa {
30 
31 // Struct for the Answer to QuestionAnswerer.
32 struct QaAnswer {
33   // struct to represent the logit and offset of the answer related to context.
34   struct Pos {
PosQaAnswer::Pos35     Pos(int arg_start, int arg_end, float arg_logit)
36         : start(arg_start), end(arg_end), logit(arg_logit) {}
37     int start, end;
38     float logit;
39     bool operator<(const Pos& rhs) const { return rhs.logit < logit; }
40   };
41 
QaAnswerQaAnswer42   QaAnswer(std::string arg_text, Pos arg_pos)
43       : text(std::move(arg_text)), pos(arg_pos) {}
44   std::string text;
45   Pos pos;
46 };
47 
48 // Interface for an Question-Answer API.
49 class QuestionAnswerer
50     : public core::BaseTaskApi<std::vector<QaAnswer>, const std::string&,
51                                const std::string&> {
52  public:
QuestionAnswerer(std::unique_ptr<core::TfLiteEngine> engine)53   explicit QuestionAnswerer(std::unique_ptr<core::TfLiteEngine> engine)
54       : BaseTaskApi(std::move(engine)) {}
55 
56   virtual std::vector<QaAnswer> Answer(const std::string& context,
57                                        const std::string& question) = 0;
58 };
59 
60 }  // namespace qa
61 }  // namespace text
62 }  // namespace task
63 }  // namespace tflite
64 
65 #endif  // TENSORFLOW_LITE_SUPPORT_CC_TASK_TEXT_QA_QUESTION_ANSWERER_H_
66