Class: SentimentInsights::Clients::Entities::AwsClient
- Inherits:
-
Object
- Object
- SentimentInsights::Clients::Entities::AwsClient
- Defined in:
- lib/sentiment_insights/clients/entities/aws_client.rb
Constant Summary collapse
- MAX_BATCH_SIZE =
25
Instance Method Summary collapse
- #extract_batch(entries, question: nil, prompt: nil) ⇒ Object
-
#initialize(region: 'us-east-1') ⇒ AwsClient
constructor
A new instance of AwsClient.
Constructor Details
#initialize(region: 'us-east-1') ⇒ AwsClient
Returns a new instance of AwsClient.
10 11 12 13 |
# File 'lib/sentiment_insights/clients/entities/aws_client.rb', line 10 def initialize(region: 'us-east-1') @client = Aws::Comprehend::Client.new(region: region) @logger = Logger.new($stdout) end |
Instance Method Details
#extract_batch(entries, question: nil, prompt: nil) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/sentiment_insights/clients/entities/aws_client.rb', line 15 def extract_batch(entries, question: nil, prompt: nil) responses = [] entity_map = Hash.new { |h, k| h[k] = [] } entries.each_slice(MAX_BATCH_SIZE).with_index do |batch, batch_idx| texts = batch.map { |e| e[:answer].to_s.strip[0...5000] } begin resp = @client.batch_detect_entities({ text_list: texts, language_code: 'en' }) resp.result_list.each_with_index do |res, idx| entry_index = (batch_idx * MAX_BATCH_SIZE) + idx entry = entries[entry_index] sentence = texts[idx] response_id = "r_#{entry_index + 1}" responses << { id: response_id, sentence: sentence, segment: entry[:segment] || {} } entities = res.entities.map do |e| { text: e.text.downcase.strip, type: e.type } end.uniq { |e| [e[:text], e[:type]] } entities.each do |ent| key = [ent[:text], ent[:type]] entity_map[key] << response_id end end resp.error_list.each do |error| @logger.warn "AWS entity error at index #{error.index}: #{error.error_code}" end rescue Aws::Comprehend::Errors::ServiceError => e @logger.error "AWS Comprehend error: #{e.}" batch.each_with_index do |entry, i| entry_index = (batch_idx * MAX_BATCH_SIZE) + i responses << { id: "r_#{entry_index + 1}", sentence: entry[:answer], segment: entry[:segment] || {} } end end end entities = entity_map.map do |(text, type), ref_ids| { entity: text, type: type, mentions: ref_ids.uniq, summary: nil } end { entities: entities, responses: responses } end |