• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7    http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15#import "tensorflow_lite_support/ios/task/text/qa/Sources/TFLBertQuestionAnswerer.h"
16#import "GTMDefines.h"
17#include "tensorflow_lite_support/cc/task/text/qa/bert_qa_c_api.h"
18
19NS_ASSUME_NONNULL_BEGIN
20
21@implementation TFLQAAnswer
22@synthesize pos;
23@synthesize text;
24@end
25
26@interface TFLBertQuestionAnswerer()
27/** BertQuestionAnswerer backed by C API */
28@property(nonatomic) BertQuestionAnswerer *bertQuestionAnswerer;
29@end
30
31@implementation TFLBertQuestionAnswerer
32
33- (void)dealloc {
34  BertQuestionAnswererDelete(_bertQuestionAnswerer);
35}
36
37+ (instancetype)questionAnswererWithModelPath:(NSString *)modelPath {
38  BertQuestionAnswerer* bert_qa = BertQuestionAnswererFromFile(modelPath.UTF8String);
39
40  _GTMDevAssert(bert_qa, @"Failed to create BertQuestionAnswerer");
41  return [[TFLBertQuestionAnswerer alloc]
42      initWithBertQuestionAnswerer:bert_qa];
43}
44
45- (instancetype)initWithBertQuestionAnswerer:(BertQuestionAnswerer *)bertQuestionAnswerer {
46  self = [super init];
47  if (self) {
48    _bertQuestionAnswerer = bertQuestionAnswerer;
49  }
50  return self;
51}
52
53- (NSArray<TFLQAAnswer *> *)answerWithContext:(NSString *)context question:(NSString *)question {
54  struct QaAnswers *cAnswers =
55      BertQuestionAnswererAnswer(_bertQuestionAnswerer, context.UTF8String, question.UTF8String);
56  NSMutableArray<TFLQAAnswer *> *ret = [NSMutableArray arrayWithCapacity:cAnswers->size];
57  for (int i = 0; i < cAnswers->size; i++) {
58    struct QaAnswer cAnswer = cAnswers->answers[i];
59    TFLQAAnswer *answer = [[TFLQAAnswer alloc] init];
60    struct TFLPos pos = {.start = cAnswer.start,
61                         .end = cAnswer.end,
62                         .logit = cAnswer.logit};
63    [answer setPos:pos];
64    [answer setText:[NSString stringWithUTF8String:cAnswer.text]];
65    [ret addObject:answer];
66  }
67  BertQuestionAnswererQaAnswersDelete(cAnswers);
68  return ret;
69}
70@end
71NS_ASSUME_NONNULL_END
72