UNPKG

@rekhtya/pashto-linguistic-toolkit

Version:

A toolkit for processing Pashto language, providing translation and part of speech analysis using Google's APIs.

129 lines (108 loc) 4.79 kB
class PashtoLinguisticToolkit { /** * @param {string} apiKey - The API key required for Google Translate and Natural Language API. */ constructor(apiKey) { // Check if API key is provided if (!apiKey) { throw new Error('Google API key is required.'); } this.apiKey = apiKey; } /** * Translates Pashto text to English using the Google Translate API. * @param {string} text - The Pashto text to be translated. * @param {string} targetLang - The target language code (default is 'en' for English). * @returns {Promise<string>} - The translated text or a fallback message if translation fails. */ async translate(text, targetLang = 'en') { const url = `https://translation.googleapis.com/language/translate/v2?key=${this.apiKey}`; try { const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ q: text, target: targetLang, source: 'ps', }), }); // Check if response is OK (status 200-299) if (!response.ok) { throw new Error(`Error: ${response.statusText}`); } const data = await response.json(); // Return translated text or a fallback if not found return data.data?.translations[0]?.translatedText || 'Translation not found'; } catch (error) { console.error('Error during translation:', error); return 'Translation failed'; } } /** * Retrieves the part of speech of a given word using the Google Cloud Natural Language API. * @param {string} word - The word to analyze for part of speech. * @returns {Promise<string>} - The part of speech (e.g., noun, verb) or 'N/A' if not found. */ async getPartOfSpeech(word) { const url = `https://language.googleapis.com/v1/documents:analyzeSyntax?key=${this.apiKey}`; const body = { document: { type: 'PLAIN_TEXT', content: word, }, }; try { const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); // Check if response is OK (status 200-299) if (!response.ok) { throw new Error(`Error: ${response.statusText}`); } const data = await response.json(); // Ensure tokens are present and return part of speech of the first token if (data.tokens && data.tokens.length > 0) { const token = data.tokens[0]; return token.partOfSpeech.tag || 'N/A'; // Return part of speech for the first token (word) } return 'N/A'; } catch (error) { console.error('Error during part of speech analysis:', error); return 'N/A'; // Return 'N/A' in case of error } } /** * Parses a sentence into word metadata including translation and part of speech for each word. * @param {string} sentence - The sentence to be parsed. * @returns {Promise<Array>} - A list of objects with word, translated word, and part of speech. */ async parseSentence(sentence) { const words = sentence.split(/\s+/); // Split sentence into words try { const wordMetadata = await Promise.all( words.map(async (word) => { try { // First, translate the word to English const translatedWord = await this.translate(word); // Then, get the part of speech of the translated word const partOfSpeech = await this.getPartOfSpeech(translatedWord); // Return word metadata return { word, translatedWord, partOfSpeech }; } catch (error) { console.error(`Error processing word "${word}":`, error); return { word, translatedWord: 'Error', partOfSpeech: 'N/A' }; } }) ); return wordMetadata; } catch (error) { console.error('Error during sentence parsing:', error); return []; } } } // Export as an NPM module export default PashtoLinguisticToolkit;