getTranscriptionResult method

Future<TranscriptionResult> getTranscriptionResult(
  1. String transcriptionIdOrUrl
)

Gets transcription results by task ID or URL

transcriptionIdOrUrl - task ID or full URL for getting the result Returns TranscriptionResult with transcription results

Implementation

Future<TranscriptionResult> getTranscriptionResult(
    String transcriptionIdOrUrl) async {
  try {
    String url;
    bool isAbsoluteUrl = false;

    // Check if the passed parameter is URL or ID
    if (transcriptionIdOrUrl.startsWith('http')) {
      url = transcriptionIdOrUrl;
      isAbsoluteUrl = true;
    } else {
      // Update path for new API
      url = 'v2/pre-recorded/$transcriptionIdOrUrl';
    }

    // Make request
    final Response<dynamic> response;
    if (isAbsoluteUrl) {
      // For absolute URL create temporary Dio without baseUrl
      final tempDio = Dio();
      tempDio.options.headers = _dio.options.headers;

      if (enableLogging) {
        tempDio.interceptors.add(LogInterceptor(
          requestBody: true,
          responseBody: true,
        ));
      }

      response = await tempDio.get(url);
    } else {
      response = await _dio.get(url);
    }

    // Check that the response contains data and is of the correct type
    if (response.data == null) {
      throw GladiaApiException(message: 'Empty response from server');
    }

    // Convert data to Map<String, dynamic>
    Map<String, dynamic> responseData;

    if (response.data is Map<String, dynamic>) {
      responseData = response.data as Map<String, dynamic>;
    } else if (response.data is String) {
      try {
        // Try to parse the string as JSON
        final jsonData = json.decode(response.data as String);
        if (jsonData is Map<String, dynamic>) {
          responseData = jsonData;
        } else {
          throw const FormatException(
              'Response is not a correct JSON object');
        }
      } catch (e) {
        throw GladiaApiException(
          message: 'Unable to parse response as JSON: ${response.data}',
        );
      }
    } else {
      throw GladiaApiException(
        message:
            'Invalid response format from server: ${response.data.runtimeType}',
      );
    }

    // Check transcription status
    final status = responseData['status'];
    if (status == null) {
      throw GladiaApiException(
        message: 'Status field is missing in response',
        responseData: responseData,
      );
    }

    final String statusStr = status is String ? status : status.toString();

    if (statusStr == 'done') {
      // Transcription completed, return result
      try {
        // Use new model for parsing full answer
        final result = TranscriptionResult.fromJson(responseData);

        return result;
      } catch (e) {
        try {
          // If an error occurred during parsing full structure,
          // use simplified method for extracting basic data
          final result = responseData['result'];
          if (result is! Map<String, dynamic>) {
            throw const FormatException('Result field is not an object');
          }

          final transcription = result['transcription'];
          if (transcription is! Map<String, dynamic>) {
            throw const FormatException(
                'Transcription field is not an object');
          }

          // Get full transcription text
          String fullTranscript = '';
          final transcript = transcription['full_transcript'];
          if (transcript is String) {
            fullTranscript = transcript;
          } else if (transcript != null) {
            fullTranscript = transcript.toString();
          }

          // Extract metadata
          final metadata = result['metadata'] as Map<String, dynamic>?;
          String? language;
          double? duration;

          if (metadata != null) {
            final langValue = metadata['language'];
            if (langValue is String) {
              language = langValue;
            } else if (langValue != null) {
              language = langValue.toString();
            }

            final durationValue = metadata['audio_duration'];
            if (durationValue is double) {
              duration = durationValue;
            } else if (durationValue is int) {
              duration = durationValue.toDouble();
            } else if (durationValue is String) {
              try {
                duration = double.parse(durationValue);
              } catch (_) {
                duration = null;
              }
            }
          }

          // Create basic transcription result
          return TranscriptionResult(
            id: responseData['id'] as String? ?? 'unknown_id',
            status: 'done',
            file: FileInfo(
              audioDuration: duration,
            ),
            result: TranscriptionResultData(
              transcription: TranscriptionData(
                fullTranscript: fullTranscript,
                languages: language != null ? [language] : null,
              ),
            ),
          );
        } catch (innerError) {
          // If even backup option didn't work, throw original error with useful information
          throw GladiaApiException(
            message:
                'Unable to parse result: $e. Additional error: $innerError',
            responseData: responseData,
          );
        }
      }
    } else if (statusStr == 'processing' || statusStr == 'queued') {
      // Transcription not completed yet
      throw GladiaApiException(
        message:
            'Transcription not completed yet. Current status: $statusStr',
        statusCode: 202,
        responseData: responseData,
      );
    } else {
      // Transcription error
      final errorMessage = responseData['error'];
      final errorText =
          errorMessage != null ? errorMessage.toString() : statusStr;

      throw GladiaApiException(
        message: 'Transcription error: $errorText',
        statusCode: 400,
        responseData: responseData,
      );
    }
  } on DioException catch (e) {
    throw GladiaApiException.fromDioError(e);
  } catch (e) {
    if (e is GladiaApiException) {
      rethrow;
    }
    throw GladiaApiException(message: e.toString());
  }
}