perplexity-hackathon-LawMitra / perplexity_hackathon / src / services / translationService.ts
translationService.ts
Raw
import { TranslationServiceClient } from '@google-cloud/translate';
import path from 'path';

interface TranslationResult {
  originalText: string;
  translatedText: string;
  detectedLanguage?: string;
  confidence?: number;
}

class TranslationService {
  private client: TranslationServiceClient | null;
  private projectId: string;
  private location = 'global';
  private isDev: boolean;

  constructor() {
    this.isDev = process.env.NODE_ENV === 'development';
    this.projectId = process.env.GOOGLE_PROJECT_ID || '';

    if (!this.isDev) {
      const credentials = require(path.join(__dirname, '../../google-credentials.json'));
      this.client = new TranslationServiceClient({
        credentials,
        projectId: this.projectId,
      });
    } else {
      this.client = null;
    }
  }

  async translateToEnglish(text: string): Promise<TranslationResult> {
    try {
      if (this.isDev) {
        // In development, just return the original text
        return {
          originalText: text,
          translatedText: text,
          detectedLanguage: 'en',
          confidence: 1.0,
        };
      }

      const request = {
        parent: `projects/${this.projectId}/locations/${this.location}`,
        contents: [text],
        mimeType: 'text/plain',
        sourceLanguageCode: 'auto',
        targetLanguageCode: 'en',
      };

      const [response] = await this.client!.translateText(request);
      const translation = response.translations?.[0];

      if (!translation) {
        throw new Error('No translation returned');
      }

      return {
        originalText: text,
        translatedText: translation.translatedText || text,
        detectedLanguage: translation.detectedLanguageCode || undefined,
        confidence: translation.model ? parseFloat(translation.model) : undefined,
      };
    } catch (error) {
      console.error('Translation error:', error);
      // In case of error in development, return original text
      if (this.isDev) {
        return {
          originalText: text,
          translatedText: text,
          detectedLanguage: 'en',
          confidence: 1.0,
        };
      }
      throw new Error('Failed to translate text');
    }
  }

  async translateFromEnglish(text: string, targetLanguage: string): Promise<TranslationResult> {
    try {
      if (this.isDev) {
        // In development, just return the original text
        return {
          originalText: text,
          translatedText: text,
        };
      }

      const request = {
        parent: `projects/${this.projectId}/locations/${this.location}`,
        contents: [text],
        mimeType: 'text/plain',
        sourceLanguageCode: 'en',
        targetLanguageCode: targetLanguage,
      };

      const [response] = await this.client!.translateText(request);
      const translation = response.translations?.[0];

      if (!translation) {
        throw new Error('No translation returned');
      }

      return {
        originalText: text,
        translatedText: translation.translatedText || text,
      };
    } catch (error) {
      console.error('Translation error:', error);
      // In case of error in development, return original text
      if (this.isDev) {
        return {
          originalText: text,
          translatedText: text,
        };
      }
      throw new Error('Failed to translate text');
    }
  }

  async detectLanguage(text: string): Promise<{
    language: string;
    confidence: number;
  }> {
    try {
      if (this.isDev) {
        // In development, assume English
        return {
          language: 'en',
          confidence: 1.0,
        };
      }

      const request = {
        parent: `projects/${this.projectId}/locations/${this.location}`,
        content: text,
        mimeType: 'text/plain',
      };

      const [response] = await this.client!.detectLanguage(request);
      const detection = response.languages?.[0];

      if (!detection || !detection.languageCode) {
        throw new Error('Language detection failed');
      }

      return {
        language: detection.languageCode,
        confidence: detection.confidence || 0,
      };
    } catch (error) {
      console.error('Language detection error:', error);
      // In case of error in development, assume English
      if (this.isDev) {
        return {
          language: 'en',
          confidence: 1.0,
        };
      }
      throw new Error('Failed to detect language');
    }
  }
}

export const translationService = new TranslationService();