Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add translation endpoint to Igbo API #812

Merged
merged 20 commits into from
Nov 1, 2024
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ const SENDGRID_NEW_DEVELOPER_ACCOUNT_TEMPLATE_SOURCE = defineString(
// Igbo API
const ENV_MAIN_KEY = defineString('ENV_MAIN_KEY').value();

// Nkọwa okwu AI Models
const ENV_IGBO_TO_ENGLISH_URL = defineString('ENV_IGBO_TO_ENGLISH_URL').value();
ebubae marked this conversation as resolved.
Show resolved Hide resolved

// Google Analytics
const ANALYTICS_GA_TRACKING_ID = defineString('ANALYTICS_GA_TRACKING_ID').value();
const ANALYTICS_GA_API_SECRET = defineString('ANALYTICS_GA_API_SECRET').value();
Expand Down Expand Up @@ -101,11 +104,12 @@ export const CORS_CONFIG = {
export const API_ROUTE = isProduction ? '' : `http://localhost:${PORT}`;
export const API_DOCS = 'https://docs.igboapi.com';

// IgboSpeech
// Nkọwa okwu AI Models
export const SPEECH_TO_TEXT_API = isProduction
? 'https://speech.igboapi.com'
: 'http://localhost:3333';

export const IGBO_TO_ENGLISH_API = ENV_IGBO_TO_ENGLISH_URL;
ijemmao marked this conversation as resolved.
Show resolved Hide resolved
// SendGrid API
export const SENDGRID_API_KEY = SENDGRID_API_KEY_SOURCE || '';
export const SENDGRID_NEW_DEVELOPER_ACCOUNT_TEMPLATE =
Expand Down
1 change: 0 additions & 1 deletion src/controllers/__tests__/examples.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { exampleFixture } from '../../__tests__/shared/fixtures';
import LanguageEnum from '../../shared/constants/LanguageEnum';
import { SuggestionSourceEnum } from '../../shared/constants/SuggestionSourceEnum';
import { convertToV1Example } from '../examples';

describe('examples', () => {
Expand Down
62 changes: 62 additions & 0 deletions src/controllers/__tests__/translation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import axios from 'axios';
import {
requestFixture,
responseFixture,
nextFunctionFixture,
} from '../../../__tests__/shared/fixtures';
import { getTranslation } from '../translation';

describe('translation', () => {
beforeEach(() => {
jest.resetAllMocks();
});
it('calls Nkọwa okwu ML translation server', async () => {
const req = requestFixture({
body: { igbo: 'aka' },
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'main_key',
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i think we should import MAIN_KEY instead of hardcoding 'main_key'

},
});
const res = responseFixture();
const next = nextFunctionFixture();
jest.spyOn(axios, 'request').mockResolvedValue({
data: { igbo: 'aka' },
});
await getTranslation(req, res, next);
expect(res.send).toHaveBeenCalled();
});

it('throws validation error when input is too long', async () => {
const req = requestFixture({
body: { igbo: 'aka'.repeat(100) },
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'main_key',
},
});
const res = responseFixture();
const next = nextFunctionFixture();
jest.spyOn(axios, 'request').mockResolvedValue({
data: { igbo: 'aka'.repeat(100) },
});
await getTranslation(req, res, next);
expect(next).toHaveBeenCalled();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it possible to check the error message here too so we know which error was thrown?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

now doing that check!

});
it('throws validation error when input string is empty', async () => {
const req = requestFixture({
body: { igbo: '' },
headers: {
'Content-Type': 'application/json',
'X-API-Key': 'main_key',
},
});
const res = responseFixture();
const next = nextFunctionFixture();
jest.spyOn(axios, 'request').mockResolvedValue({
data: { igbo: '' },
});
await getTranslation(req, res, next);
expect(next).toHaveBeenCalled();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same thing here

});
});
52 changes: 52 additions & 0 deletions src/controllers/translation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import axios from 'axios';
import { MiddleWare } from '../types';
import { IGBO_TO_ENGLISH_API, MAIN_KEY } from '../config';

interface TranslationMetadata {
igbo: string;
Copy link
Collaborator

@ijemmao ijemmao Oct 31, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we would want to have a schema similar to something like the following:

Suggested change
igbo: string;
text: string;
sourceLanguageCode: LanguageEnum;
destinationLanguageCode: LanguageEnum;

LanguageEnum would include he ISO language codes, so for Igbo it would be ibo. LanguageEnum exists in our codebase right now. This way we can avoid the potential case where we need to add more fields when we want to support more languages

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm now validating the request body. For now, the call to the ML endpoint won't change but that's more of an implementation detail.

}

interface Translation {
translation: string;
}

// Due to limit on inputs used to train the model, the maximum
// Igbo translation input is 120 characters
const TRANSLATION_INPUT_MAX_LENGTH = 120;

/**
* Talks to Igbo-to-English translation model to translate the provided text.
* @param req
* @param res
* @param next
* @returns English text translation of the provided Igbo text
*/
export const getTranslation: MiddleWare = async (req, res, next) => {
try {
const igboText: string = req.body['igbo'];
if (!igboText) {
throw new Error('Cannot translate empty string');
}

if (igboText.length > TRANSLATION_INPUT_MAX_LENGTH) {
throw new Error('Cannot translate text greater than 120 characters');
}

const payload: TranslationMetadata = { igbo: igboText };

// Talks to prediction endpoint
const { data: response } = await axios.request<Translation>({
method: 'POST',
url: IGBO_TO_ENGLISH_API,
headers: {
'Content-Type': 'application/json',
'X-API-Key': MAIN_KEY,
},
data: payload,
});

return res.send({ translation: response.translation });
ebubae marked this conversation as resolved.
Show resolved Hide resolved
} catch (err) {
return next(err);
}
};
26 changes: 23 additions & 3 deletions src/middleware/helpers/authorizeDeveloperUsage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { findDeveloperUsage } from './findDeveloperUsage';
import { createDeveloperUsage } from './createDeveloperUsage';
import { DeveloperUsageDocument } from '../../types/developerUsage';
import ApiType from '../../shared/constants/ApiType';
import ApiTypeToRoute from '../../shared/constants/ApiTypeToRoute';
import ApiUsageLimit from '../../shared/constants/ApiUsageLimit';
import { DeveloperDocument } from '../../types';

Expand Down Expand Up @@ -58,8 +59,27 @@ export const authorizeDeveloperUsage = async ({
}: {
path: string,
developer: DeveloperDocument,
}) =>
handleDeveloperUsage({
}) => {
const extractedPath = getPath(path);
return handleDeveloperUsage({
developer,
apiType: path.startsWith('speech-to-text') ? ApiType.SPEECH_TO_TEXT : ApiType.DICTIONARY,
apiType: getApiTypeFromRoute(extractedPath),
});
};

const getApiTypeFromRoute = (route: string): ApiType => {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: can you add a comment for this function?

switch (route) {
case ApiTypeToRoute.SPEECH_TO_TEXT:
return ApiType.SPEECH_TO_TEXT;
case ApiTypeToRoute.TRANSLATE:
return ApiType.TRANSLATE;
default:
return ApiType.DICTIONARY;
}
};

const getPath = (path: string) => {
// Extract router path from full path
// ex. speech-to-text/params=param -> speech-to-text
return path.split(/[\/\?]/)[0];
};
13 changes: 13 additions & 0 deletions src/routers/routerV2.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
import { Router } from 'express';
import rateLimit from 'express-rate-limit';

Check warning on line 2 in src/routers/routerV2.ts

View workflow job for this annotation

GitHub Actions / Run linters

'rateLimit' is defined but never used
import { getWords, getWord } from '../controllers/words';
import { getExample, getExamples } from '../controllers/examples';
import { getNsibidiCharacter, getNsibidiCharacters } from '../controllers/nsibidi';
import { getTranscription } from '../controllers/speechToText';
import { getTranslation } from '../controllers/translation';
import validId from '../middleware/validId';
import validateApiKey from '../middleware/validateApiKey';
import analytics from '../middleware/analytics';
import attachRedisClient from '../middleware/attachRedisClient';
import { MiddleWare } from 'src/types';

Check warning on line 12 in src/routers/routerV2.ts

View workflow job for this annotation

GitHub Actions / Run linters

'MiddleWare' is defined but never used

// TODO: add rate limiting with upstash
// const ONE_DAY = 24 * 60 * 60 * 1000;
// const REQUESTS_PER_MS_TRANSLATION = 5;

// const translationRateLimiter: MiddleWare = rateLimit({
// windowMs: ONE_DAY,
// max: REQUESTS_PER_MS_TRANSLATION,
// });
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can delete this comment since you have a corresponding GitHub issue

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done!


const routerV2 = Router();

Expand All @@ -26,6 +38,7 @@

// Speech-to-Text
routerV2.post('/speech-to-text', analytics, validateApiKey, getTranscription);
routerV2.post('/translate', analytics, validateApiKey, getTranslation);

// Redirects to V1
routerV2.post('/developers', (_, res) => res.redirect('/api/v1/developers'));
Expand Down
1 change: 1 addition & 0 deletions src/shared/constants/ApiType.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
enum ApiType {
DICTIONARY = 'DICTIONARY',
SPEECH_TO_TEXT = 'SPEECH_TO_TEXT',
TRANSLATE = 'TRANSLATE',
}

export default ApiType;
8 changes: 8 additions & 0 deletions src/shared/constants/ApiTypeToRoute.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import ApiType from './ApiType';

const ApiTypeToRoute = {
[ApiType.SPEECH_TO_TEXT]: 'speech-to-text',
[ApiType.TRANSLATE]: 'translate',
};

export default ApiTypeToRoute;
1 change: 1 addition & 0 deletions src/shared/constants/ApiUsageLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import ApiType from './ApiType';
const ApiUsageLimit = {
[ApiType.DICTIONARY]: 2500,
[ApiType.SPEECH_TO_TEXT]: 20,
[ApiType.TRANSLATE]: 5,
};

export default ApiUsageLimit;
Loading