Libre Translate Logic - abhiram-shaji/Langroove GitHub Wiki

Developer Documentation: Chat Language Management and Translation Utilities

This documentation provides a detailed explanation of the chat language management and translation utilities implemented in the provided code.


Overview

The utilities include functions to:

  1. Ensure a chat document with language settings exists (ensureChatLanguage).
  2. Set a specific language for a chat participant (setChatLanguage).
  3. Translate text between languages using the LibreTranslate API (translateText).

1. Ensuring Chat Language (ensureChatLanguage)

Purpose

  • Verifies the existence of a chat document with the correct structure for storing participant language preferences.
  • Initializes a chat document with default values if it does not exist.

Implementation

  1. Functionality:

    • Checks if a chat document exists in Firestore for the given chatId.
    • If the document is missing, creates it with default values, including languages fields for participants.
  2. Code Snippet:

    export const ensureChatLanguage = async (
      chatId: string,
      currentUserId: string,
      recipientId: string
    ) => {
      const chatDocRef = doc(db, "chats", chatId);
      const chatDoc = await getDoc(chatDocRef);
    
      if (!chatDoc.exists()) {
        await setDoc(chatDocRef, {
          participants: [currentUserId, recipientId],
          isGroupChat: false,
          createdAt: Timestamp.now(),
          languages: {
            [currentUserId]: null,
            [recipientId]: null,
          },
        });
        return { userLanguage: null, recipientLanguage: null };
      }
    
      const data = chatDoc.data();
      return {
        userLanguage: data?.languages?.[currentUserId] || null,
        recipientLanguage: data?.languages?.[recipientId] || null,
      };
    };
  3. Process:

    • Fetches the chat document using getDoc.
    • If missing, creates a new document with default languages fields.
    • Returns the current language preferences for the user and recipient.

2. Setting Chat Language (setChatLanguage)

Purpose

  • Updates the preferred language of a specific user in a chat.

Implementation

  1. Functionality:

    • Updates the languages field of a chat document for a specified userId.
  2. Code Snippet:

    export const setChatLanguage = async (
      chatId: string,
      userId: string,
      selectedLanguage: string
    ) => {
      const chatDocRef = doc(db, "chats", chatId);
    
      try {
        await setDoc(
          chatDocRef,
          { languages: { [userId]: selectedLanguage } },
          { merge: true }
        );
        return selectedLanguage;
      } catch (error) {
        console.error("Error updating chat language:", error);
        throw error;
      }
    };
  3. Process:

    • Updates the languages field in the chat document using setDoc with merge: true.
    • Returns the updated language.

3. Text Translation (translateText)

Purpose

  • Translates a given text to a specified target language using the LibreTranslate API.

Implementation

  1. Functionality:

    • Converts the target language name to its ISO code if needed.
    • Sends a request to the LibreTranslate API with the source text and language codes.
    • Returns the translated text from the API response.
  2. Code Snippet:

    export const translateText = async (
      text: string,
      targetLanguage: string,
      sourceLanguage: string = "auto"
    ): Promise<string> => {
      const targetLangCode = languageCodes[targetLanguage] || targetLanguage;
      const requestData = {
        q: text,
        source: sourceLanguage,
        target: targetLangCode,
        api_key: "6b35d883-0347-4e33-8e04-a7097c5f0e6a",
        format: "text",
      };
    
      try {
        const response = await axios.post<TranslationResponse>(
          "https://libretranslate.com/translate",
          requestData,
          { headers: { "Content-Type": "application/json" } }
        );
        return response.data.translatedText;
      } catch (error) {
        console.error("Error translating text:", error);
        throw new Error("Translation failed");
      }
    };
  3. Process:

    • Uses languageCodes to convert language names to ISO codes.
    • Sends a POST request to the LibreTranslate API with the text and language parameters.
    • Handles and logs errors, throwing a generic "Translation failed" error if unsuccessful.

Key Properties and Methods

Function Description
ensureChatLanguage Ensures a chat document exists with language fields, initializing if needed.
setChatLanguage Sets a user's preferred language in a chat document.
translateText Translates text to a target language using the LibreTranslate API.
languageCodes Maps language names to ISO codes (e.g., "English" -> "en").

Notes

Error Handling

  • Logs errors for debugging and provides fallback responses where necessary.
  • Handles API errors and throws a user-friendly "Translation failed" message if translation fails.

Caching

  • Relies on Firestore's real-time capabilities for consistent data updates.
  • Translation requests are always fresh; consider caching frequent translations to optimize API usage.

For more information about LibreTranslate, visit the LibreTranslate Documentation. For Firebase Firestore, refer to the Firebase Documentation.

⚠️ **GitHub.com Fallback** ⚠️