Class: AssemblyaiClient

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
app/services/assemblyai_client.rb

Overview

Service object: assemblyai client.

Constant Summary collapse

BASE_URL =

URL for base.

'https://api.assemblyai.com/v2'
LLM_GATEWAY_URL =

URL for llm gateway.

'https://llm-gateway.assemblyai.com/v1'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ AssemblyaiClient

Returns a new instance of AssemblyaiClient.

Parameters:

  • options (Hash) (defaults to: {})

    client options

Options Hash (options):

  • logger (Logger)

    logger to use (defaults to Rails.logger)



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'app/services/assemblyai_client.rb', line 19

def initialize(options = {})
  @logger = options[:logger] || Rails.logger
  @api_key = Heatwave::Configuration.fetch(:assemblyai, :api_key)

  # Faraday with the http.rb adapter. Authorization is the only header that
  # belongs on every request; Content-Type is set per-POST so GETs don't
  # send it spuriously and `upload_file` (raw bytes) can send the right
  # content type for binary upload.
  # Default timeouts apply to most calls; the long-running Speech
  # Understanding endpoints (identify_speakers / translate_transcript)
  # override `req.options.timeout` per call to allow 120s+ work.
  @client = Faraday.new(
    headers: { 'Authorization' => @api_key },
    request: { open_timeout: 5, timeout: 60 }
  ) do |f|
    f.adapter Faraday.default_adapter
  end
end

Instance Attribute Details

#api_keyObject (readonly)

Returns the value of attribute api_key.



15
16
17
# File 'app/services/assemblyai_client.rb', line 15

def api_key
  @api_key
end

#clientObject (readonly)

Returns the value of attribute client.



15
16
17
# File 'app/services/assemblyai_client.rb', line 15

def client
  @client
end

#loggerObject (readonly)

Returns the value of attribute logger.



15
16
17
# File 'app/services/assemblyai_client.rb', line 15

def logger
  @logger
end

Instance Method Details

#export_paragraphs(transcript_id) ⇒ Object



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'app/services/assemblyai_client.rb', line 198

def export_paragraphs(transcript_id)
  logger.info "[assemblyai:export_paragraphs] Exporting paragraphs for transcript: #{transcript_id}"
  export_url = "#{BASE_URL}/transcript/#{transcript_id}/paragraphs"
  begin
    response = @client.get(export_url)
    if response.status == 200
      result = JSON.parse(response.body)
      logger.info "[assemblyai:export_paragraphs] Success: #{result['paragraphs']&.length || 0} paragraphs"
      result
    else
      logger.error "[assemblyai:export_paragraphs] Failed with status #{response.status}: #{response.body}"
      raise "AssemblyAI paragraphs export failed: #{response.status} - #{response.body}"
    end
  rescue StandardError => e
    logger.error "[assemblyai:export_paragraphs] Exception: #{e.message}"
    raise "AssemblyAI paragraphs export failed: #{e.message}"
  end
end

#export_sentences(transcript_id) ⇒ Object

Export transcript as sentences



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'app/services/assemblyai_client.rb', line 218

def export_sentences(transcript_id)
  logger.info "[assemblyai:export_sentences] Exporting sentences for transcript: #{transcript_id}"

  export_url = "#{BASE_URL}/transcript/#{transcript_id}/sentences"

  begin
    response = @client.get(export_url)

    if response.status == 200
      result = JSON.parse(response.body)
      logger.info "[assemblyai:export_sentences] Success: #{result['sentences']&.length || 0} sentences"
      result
    else
      logger.error "[assemblyai:export_sentences] Failed with status #{response.status}: #{response.body}"
      raise "AssemblyAI sentences export failed: #{response.status} - #{response.body}"
    end
  rescue StandardError => e
    logger.error "[assemblyai:export_sentences] Exception: #{e.message}"
    raise "AssemblyAI sentences export failed: #{e.message}"
  end
end

#export_vtt(transcript_id, chars_per_caption = 32) ⇒ Object

Export transcript as VTT captions



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'app/services/assemblyai_client.rb', line 241

def export_vtt(transcript_id, chars_per_caption = 32)
  logger.info "[assemblyai:export_vtt] Exporting VTT for transcript: #{transcript_id}"

  export_url = "#{BASE_URL}/transcript/#{transcript_id}/vtt"

  # Add query parameters for customization
  params = { chars_per_caption: chars_per_caption }
  query_string = params.map { |k, v| "#{k}=#{v}" }.join('&')
  full_url = query_string.present? ? "#{export_url}?#{query_string}" : export_url

  begin
    response = @client.get(full_url)

    if response.status == 200
      logger.info "[assemblyai:export_vtt] Success: #{response.body.length} characters"
      response.body
    else
      logger.error "[assemblyai:export_vtt] Failed with status #{response.status}: #{response.body}"
      raise "AssemblyAI VTT export failed: #{response.status} - #{response.body}"
    end
  rescue StandardError => e
    logger.error "[assemblyai:export_vtt] Exception: #{e.message}"
    raise "AssemblyAI VTT export failed: #{e.message}"
  end
end

#get_transcription(transcript_id) ⇒ Object

Get transcription result



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'app/services/assemblyai_client.rb', line 112

def get_transcription(transcript_id)
  logger.info "[assemblyai:get_transcription] Getting result for: #{transcript_id}"

  transcript_url = "#{BASE_URL}/transcript/#{transcript_id}"

  begin
    response = @client.get(transcript_url)

    if response.status == 200
      result = JSON.parse(response.body)
      logger.info "[assemblyai:get_transcription] Success: #{result['status']}"
      result
    else
      logger.error "[assemblyai:get_transcription] Failed with status #{response.status}: #{response.body}"
      raise "AssemblyAI get transcription failed: #{response.status} - #{response.body}"
    end
  rescue StandardError => e
    logger.error "[assemblyai:get_transcription] Exception: #{e.message}"
    raise "AssemblyAI get transcription failed: #{e.message}"
  end
end

#identify_speakers(transcript_id:, known_values:, speaker_type: 'name') ⇒ Hash

Speaker Identification via AssemblyAI Speech Understanding API (Method 2 - post-transcription).
Takes a completed transcript ID and returns utterances with name/role labels instead of A/B.
Use this to identify speakers on an already-completed transcript without re-transcribing.

Parameters:

  • transcript_id (String)

    Completed AssemblyAI transcript ID

  • known_values (Array<String>)

    Speaker names or roles (max 35 chars each)

  • speaker_type (String) (defaults to: 'name')

    'name' or 'role' (default: 'name')

Returns:

  • (Hash)

    Response with updated utterances keyed by speaker name/role



445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# File 'app/services/assemblyai_client.rb', line 445

def identify_speakers(transcript_id:, known_values:, speaker_type: 'name')
  logger.info "[assemblyai:identify_speakers] Running speaker identification for transcript #{transcript_id}"
  logger.info "[assemblyai:identify_speakers] known_values: #{known_values.inspect}"

  request_body = {
    transcript_id: transcript_id,
    speech_understanding: {
      request: {
        speaker_identification: {
          speaker_type: speaker_type,
          known_values: known_values.map { |v| v.to_s.gsub(/[[:space:]]/, ' ').squeeze(' ').strip.slice(0, 35) }.compact_blank
        }
      }
    }
  }

  begin
    response = @client.post("#{LLM_GATEWAY_URL}/understanding") do |req|
      req.body = request_body.to_json
      req.headers['Content-Type'] = 'application/json'
      req.options.timeout = 120
    end

    if response.status == 200
      result = JSON.parse(response.body)
      utterance_count = result['utterances']&.length || 0
      logger.info "[assemblyai:identify_speakers] Success - #{utterance_count} utterances returned"
      result
    else
      error_body = response.body.to_s.truncate(500)
      logger.error "[assemblyai:identify_speakers] Failed with status #{response.status}: #{error_body}"
      raise "Speaker identification failed: #{response.status} - #{error_body}"
    end
  rescue StandardError => e
    logger.error "[assemblyai:identify_speakers] Exception: #{e.message}"
    raise "Speaker identification failed: #{e.message}"
  end
end

#llm_gateway_chat(messages:, model: AiModelConstants.id(:assemblyai_gateway), max_tokens: 2000, temperature: nil, tools: nil, tool_choice: nil, model_region: 'global') ⇒ Object

LLM Gateway chat completion with transcript context
Uses the LLM Gateway to analyze transcripts with any supported model

Parameters:

  • messages (Array)

    Array of message hashes with :role and :content

  • model (String) (defaults to: AiModelConstants.id(:assemblyai_gateway))

    Gateway model id (bare name, e.g., 'claude-sonnet-4-6' or 'claude-haiku-4-5-20251001').
    Defaults to the :assemblyai_gateway registry role (a model confirmed on
    AssemblyAI's LeMUR supported-models list), NOT the Anthropic-tier
    :anthropic_sonnet — the tier default (claude-sonnet-5) may not be on the
    gateway yet, and Sonnet 5 rejects temperature.

  • max_tokens (Integer) (defaults to: 2000)

    Maximum tokens in response

  • temperature (Float, nil) (defaults to: nil)

    Sampling temperature (0-2). Omitted from the
    request when nil — required for models that deprecate it (e.g. opus-4-7).

  • tools (Array) (defaults to: nil)

    Optional array of tool definitions for structured output

  • tool_choice (String, Hash) (defaults to: nil)

    Optional tool choice ('auto', 'none', or specific tool)

  • model_region (String, nil) (defaults to: 'global')

    Routing region. Defaults to 'global', which
    routes to the provider's non-regional endpoints for lower-cost processing
    (Anthropic Claude only as of 2026-06). Pass nil to use standard in-region
    processing — required if a caller ever sends data-residency-sensitive
    content (e.g. customer PII) through the gateway.



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'app/services/assemblyai_client.rb', line 290

def llm_gateway_chat(messages:, model: AiModelConstants.id(:assemblyai_gateway), max_tokens: 2000, temperature: nil, tools: nil, tool_choice: nil, model_region: 'global')
  logger.info "[assemblyai:llm_gateway] Running chat completion with model: #{model}"

  request_body = {
    model: model,
    messages: messages,
    max_tokens: max_tokens
  }

  # `temperature` is omitted unless explicitly set: some gateway models now
  # reject it — claude-opus-4-7 (video chapterization) 400s with
  # "`temperature` is deprecated for this model". Pass a value only for a
  # model that still accepts it.
  request_body[:temperature] = temperature unless temperature.nil?

  # Opt into global (non-region) routing for lower-cost processing unless a
  # caller explicitly requests in-region by passing model_region: nil.
  request_body[:model_region] = model_region if model_region.present?

  # Add tools for structured output if provided
  if tools.present?
    request_body[:tools] = tools
    request_body[:tool_choice] = tool_choice if tool_choice.present?
  end

  begin
    response = @client.post("#{LLM_GATEWAY_URL}/chat/completions", request_body.to_json,
                            'Content-Type' => 'application/json')

    if response.status == 200
      result = JSON.parse(response.body)
      logger.info '[assemblyai:llm_gateway] Success'
      result
    else
      logger.error "[assemblyai:llm_gateway] Failed with status #{response.status}: #{response.body}"
      raise "LLM Gateway failed: #{response.status} - #{response.body}"
    end
  rescue StandardError => e
    logger.error "[assemblyai:llm_gateway] Exception: #{e.message}"
    raise "LLM Gateway failed: #{e.message}"
  end
end

#llm_gateway_structured(messages:, schema:, tool_name: 'structured_output', model: AiModelConstants.id(:assemblyai_gateway), max_tokens: 2000, temperature: nil) ⇒ Hash

LLM Gateway with structured output via tool calling
Forces the model to return data matching the provided JSON Schema

Parameters:

  • messages (Array)

    Array of message hashes

  • schema (Hash)

    JSON Schema defining the expected output structure

  • tool_name (String) (defaults to: 'structured_output')

    Name for the tool (default: 'structured_output')

  • model (String) (defaults to: AiModelConstants.id(:assemblyai_gateway))

    Model identifier

  • max_tokens (Integer) (defaults to: 2000)

    Maximum tokens

  • temperature (Float, nil) (defaults to: nil)

    Sampling temperature. Omitted when nil (see
    #llm_gateway_chat) — pass nil for models that deprecate it.

Returns:

  • (Hash)

    Parsed structured response matching the schema



343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'app/services/assemblyai_client.rb', line 343

def llm_gateway_structured(messages:, schema:, tool_name: 'structured_output', model: AiModelConstants.id(:assemblyai_gateway), max_tokens: 2000, temperature: nil)
  logger.info "[assemblyai:llm_gateway_structured] Running structured output with model: #{model}"

  # Define a tool with the schema as parameters
  tools = [
    {
      type: 'function',
      function: {
        name: tool_name,
        description: 'Return the structured output',
        parameters: schema
      }
    }
  ]

  # Force the model to call this specific tool
  tool_choice = {
    type: 'function',
    function: { name: tool_name }
  }

  result = llm_gateway_chat(
    messages: messages,
    model: model,
    max_tokens: max_tokens,
    temperature: temperature,
    tools: tools,
    tool_choice: tool_choice
  )

  # Log the response structure for debugging
  choice = result.dig('choices', 0)
  logger.debug "[assemblyai:llm_gateway_structured] Response choice keys: #{choice&.keys&.join(', ')}"
  logger.debug "[assemblyai:llm_gateway_structured] finish_reason: #{choice&.dig('finish_reason')}"
  logger.debug "[assemblyai:llm_gateway_structured] message keys: #{choice&.dig('message')&.keys&.join(', ')}"

  # Extract the structured arguments from the tool call
  # Claude via AssemblyAI may use 'tool_use' content blocks instead of 'tool_calls'
  # Check various locations where tool calls may appear
  tool_calls = choice&.dig('tool_calls') ||
               choice&.dig('message', 'tool_calls') ||
               choice&.dig('message', 'tool_use')

  # Claude's Anthropic format uses content blocks with type: tool_use
  if tool_calls.blank?
    content_blocks = choice&.dig('message', 'content')
    if content_blocks.is_a?(Array)
      tool_use_block = content_blocks.find { |block| block['type'] == 'tool_use' }
      if tool_use_block.present?
        logger.info '[assemblyai:llm_gateway_structured] Found tool_use in content blocks'
        input = tool_use_block['input']
        if input.is_a?(Hash)
          logger.info '[assemblyai:llm_gateway_structured] Successfully extracted structured output from tool_use block'
          return input
        elsif input.is_a?(String)
          parsed = JSON.parse(input)
          logger.info '[assemblyai:llm_gateway_structured] Successfully parsed tool_use input string'
          return parsed
        end
      end
    end
  end

  if tool_calls.present? && tool_calls.first.present?
    tool_call = tool_calls.first
    # Check both 'function.arguments' (OpenAI format) and 'input' (Anthropic format)
    arguments = tool_call.dig('function', 'arguments') || tool_call['input']

    if arguments.present?
      if arguments.is_a?(Hash)
        # Already parsed - return directly
        logger.info '[assemblyai:llm_gateway_structured] Successfully extracted structured output from tool_calls (Hash)'
        return arguments
      elsif arguments.is_a?(String)
        # Parse JSON string
        parsed = JSON.parse(arguments)
        logger.info '[assemblyai:llm_gateway_structured] Successfully extracted structured output from tool_calls (parsed JSON)'
        return parsed
      end
    end
  end

  # Fallback: try to parse content as JSON (some models may return directly)
  content = choice&.dig('message', 'content')
  if content.is_a?(String) && content.present?
    logger.warn "[assemblyai:llm_gateway_structured] No tool_calls found, attempting to parse string content (length: #{content.length})"
    cleaned = content.gsub(/```json\n?/, '').gsub(/```\n?/, '').strip
    return JSON.parse(cleaned)
  end

  # Log the full choice structure for debugging
  logger.error "[assemblyai:llm_gateway_structured] No valid response found. Full choice: #{choice.to_json.truncate(1000)}"
  raise 'LLM Gateway structured output: No valid response found'
end

#poll_transcription(transcript_id, max_wait_time = 600, progress_callback = nil) ⇒ Object

Poll for transcription completion



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'app/services/assemblyai_client.rb', line 135

def poll_transcription(transcript_id, max_wait_time = 600, progress_callback = nil)
  logger.info "[assemblyai:poll] Polling for completion: #{transcript_id}"

  start_time = Time.current
  poll_interval = 10 # seconds

  loop do
    result = get_transcription(transcript_id)
    status = result['status']

    case status
    when 'completed'
      logger.info '[assemblyai:poll] Transcription completed successfully'
      return result
    when 'error'
      error_msg = result['error'] || 'Unknown error'
      logger.error "[assemblyai:poll] Transcription failed: #{error_msg}"
      raise "AssemblyAI transcription failed: #{error_msg}"
    when 'queued', 'processing'
      elapsed_time = Time.current - start_time

      if elapsed_time > max_wait_time
        logger.error "[assemblyai:poll] Timeout waiting for transcription completion after #{elapsed_time.to_i} seconds (max: #{max_wait_time}s)"
        raise "AssemblyAI transcription timeout after #{elapsed_time.to_i} seconds. Video may be too long or AssemblyAI service is experiencing delays. Please try again later."
      end

      logger.info "[assemblyai:poll] Status: #{status}, waiting #{poll_interval}s... (elapsed: #{elapsed_time.to_i}s / max: #{max_wait_time}s)"

      # Call progress callback if provided
      progress_callback&.call(status, elapsed_time)

      sleep(poll_interval)
    else
      logger.error "[assemblyai:poll] Unknown status: #{status}"
      raise "AssemblyAI unknown transcription status: #{status}"
    end
  end
end

#submit_transcription(upload_url, options = {}) ⇒ String

Submit a transcription request

Parameters:

  • upload_url (String)

    The audio URL to transcribe

  • options (Hash) (defaults to: {})

    Transcription options (passed through to AssemblyAI API)

Options Hash (options):

  • language_code (String)

    language code (default 'en_us')

  • punctuate (Boolean)

    enable punctuation (default true)

  • format_text (Boolean)

    enable text formatting (default true)

  • speaker_labels (Boolean)

    enable speaker diarization (default true)

  • webhook_url (String)

    webhook notified on completion

Returns:

  • (String)

    The transcript ID



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
# File 'app/services/assemblyai_client.rb', line 71

def submit_transcription(upload_url, options = {})
  logger.info "[assemblyai:transcribe] Submitting transcription for: #{upload_url}"

  transcript_url = "#{BASE_URL}/transcript"

  # Start with defaults, then merge caller options
  # This allows callers to override or add any AssemblyAI API option
  defaults = {
    language_code: 'en_us',
    punctuate: true,
    format_text: true,
    speaker_labels: true # Enable speaker diarization by default
  }

  # Build request body: defaults -> caller options -> required audio_url
  request_body = defaults.merge(options).merge(audio_url: upload_url)

  # Remove nil values (AssemblyAI doesn't like them)
  request_body.compact!

  logger.debug("[assemblyai:transcribe] Request sent#{' with webhook' if options[:webhook_url].present?}")

  begin
    response = @client.post(transcript_url, request_body.to_json,
                            'Content-Type' => 'application/json')

    if response.status == 200
      result = JSON.parse(response.body)
      logger.info "[assemblyai:transcribe] Success: #{result['id']}"
      result['id']
    else
      logger.error "[assemblyai:transcribe] Failed with status #{response.status}: #{response.body}"
      raise "AssemblyAI transcription submission failed: #{response.status} - #{response.body}"
    end
  rescue StandardError => e
    logger.error "[assemblyai:transcribe] Exception: #{e.message}"
    raise "AssemblyAI transcription submission failed: #{e.message}"
  end
end

#transcribe_file(file_path, options = {}) ⇒ Hash

Complete transcription workflow: upload + transcribe + poll

Parameters:

  • file_path (String)

    path to the audio file to transcribe

  • options (Hash) (defaults to: {})

    transcription options (see #submit_transcription)

Options Hash (options):

  • max_wait_time (Integer)

    maximum poll wait in seconds (default 600)

Returns:

  • (Hash)

    formatted transcription result including the transcript id



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'app/services/assemblyai_client.rb', line 179

def transcribe_file(file_path, options = {})
  logger.info "[assemblyai:transcribe_file] Starting transcription workflow for: #{file_path}"

  # Step 1: Upload file
  upload_url = upload_file(file_path)

  # Step 2: Submit transcription
  transcript_id = submit_transcription(upload_url, options)

  # Step 3: Poll for completion
  result = poll_transcription(transcript_id, options[:max_wait_time])

  # Step 4: Format result and include transcript ID
  formatted_result = format_transcription_result(result)
  formatted_result['id'] = transcript_id

  formatted_result
end

#translate_transcript(transcript_id:, target_languages:, formal: true, match_utterances: true, timeout: 300) ⇒ Hash

Native translation using AssemblyAI Speech Understanding API
Translates transcript with utterance timing preserved in a single API call

Parameters:

  • transcript_id (String)

    AssemblyAI transcript ID

  • target_languages (Array<String>)

    Target language codes (e.g., ['es', 'fr', 'pl'])

  • formal (Boolean) (defaults to: true)

    Use formal language style (default: true)

  • match_utterances (Boolean) (defaults to: true)

    Preserve original utterance boundaries (default: true)

  • timeout (Integer) (defaults to: 300)

    Request timeout in seconds (default: 300 for long videos)

Returns:

  • (Hash)

    Response with translated texts and utterances



492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
# File 'app/services/assemblyai_client.rb', line 492

def translate_transcript(transcript_id:, target_languages:, formal: true, match_utterances: true, timeout: 300)
  logger.info "[assemblyai:translate_transcript] Translating transcript #{transcript_id} to #{target_languages.join(', ')}"

  request_body = {
    transcript_id: transcript_id,
    speech_understanding: {
      request: {
        translation: {
          target_languages: target_languages,
          formal: formal,
          match_original_utterance: match_utterances
        }
      }
    }
  }

  begin
    # Use longer timeout for translation of long videos
    response = @client.post("#{LLM_GATEWAY_URL}/understanding") do |req|
      req.body = request_body.to_json
      req.headers['Content-Type'] = 'application/json'
      req.options.timeout = timeout
    end

    if response.status == 200
      result = JSON.parse(response.body)
      logger.info "[assemblyai:translate_transcript] Success - translated to #{target_languages.length} languages"

      # Log utterance count if available
      logger.info "[assemblyai:translate_transcript] Utterances returned: #{result['utterances'].length}" if result['utterances'].present?

      result
    else
      error_body = response.body.to_s.truncate(500)
      logger.error "[assemblyai:translate_transcript] Failed with status #{response.status}: #{error_body}"
      raise "Speech Understanding translation failed: #{response.status} - #{error_body}"
    end
  rescue StandardError => e
    logger.error "[assemblyai:translate_transcript] Exception: #{e.message}"
    raise "Speech Understanding translation failed: #{e.message}"
  end
end

#upload_file(file_path) ⇒ Object

Upload a file to AssemblyAI and get upload URL



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'app/services/assemblyai_client.rb', line 39

def upload_file(file_path)
  logger.info "[assemblyai:upload] Uploading file: #{file_path}"

  upload_url = "#{BASE_URL}/upload"

  begin
    response = @client.post(upload_url, File.read(file_path),
                            'Content-Type' => 'application/octet-stream')

    if response.status == 200
      result = JSON.parse(response.body)
      logger.info "[assemblyai:upload] Success: #{result['upload_url']}"
      result['upload_url']
    else
      logger.error "[assemblyai:upload] Failed with status #{response.status}: #{response.body}"
      raise "AssemblyAI upload failed: #{response.status} - #{response.body}"
    end
  rescue StandardError => e
    logger.error "[assemblyai:upload] Exception: #{e.message}"
    raise "AssemblyAI upload failed: #{e.message}"
  end
end