Skip to content

Commit

Permalink
initial SDK setup
Browse files Browse the repository at this point in the history
  • Loading branch information
viv-cheung committed Sep 12, 2024
1 parent 268ca82 commit 0650d76
Show file tree
Hide file tree
Showing 12 changed files with 7,644 additions and 0 deletions.
59 changes: 59 additions & 0 deletions .github/scripts/translate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
const { execSync } = require('child_process');
const fs = require('fs').promises;
const path = require('path');
const FrenglishSDK = require('../../frenglish-sdk/src/index');

const ORIGIN_LANGUAGE_DIR = 'src/locales/en'; // Adjust this to your origin language directory
const FRENGLISH_API_KEY = process.env.FRENGLISH_API_KEY;

const sdk = new FrenglishSDK(FRENGLISH_API_KEY);

async function getChangedFiles() {
const output = execSync('git diff --name-only HEAD~1 HEAD').toString().trim();
return output.split('\n');
}

async function main() {
const changedFiles = await getChangedFiles();
const filesToTranslate = changedFiles.filter(file => file.startsWith(ORIGIN_LANGUAGE_DIR));

if (filesToTranslate.length === 0) {
console.log('No files to translate');
return;
}

const fileContents = await Promise.all(filesToTranslate.map(async (file) => {
const content = await fs.readFile(file, 'utf-8');
return { filename: path.basename(file), content };
}));

const filenames = fileContents.map(file => file.filename);
const contents = fileContents.map(file => file.content);

try {
const translationId = await sdk.requestTranslation(filenames, contents);
console.log(`Translation requested with ID: ${translationId}`);

let status;
do {
await new Promise(resolve => setTimeout(resolve, 5000)); // Wait 5 seconds between checks
status = await sdk.getTranslationStatus(translationId);
console.log(`Translation status: ${status}`);
} while (status !== 'COMPLETED');

const translation = await sdk.getTranslation(translationId);

for (const [index, file] of filesToTranslate.entries()) {
const translatedContent = translation[filenames[index]];
const translatedFilePath = file.replace('/en/', '/fr/'); // Assuming French translation
await fs.mkdir(path.dirname(translatedFilePath), { recursive: true });
await fs.writeFile(translatedFilePath, translatedContent);
console.log(`Translated file written: ${translatedFilePath}`);
}
} catch (error) {
console.error('Error during translation process:', error);
process.exit(1);
}
}

main();
10 changes: 10 additions & 0 deletions .github/workflows/README
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
1. Create a file named .github/workflows/frenglish-translation.yml in your repository.
2. Copy the provided GitHub Actions workflow into this file. The workflow is found in this folder called
"frenglish-translation.yml".
3. Set up the FRENGLISH_API_KEY secret in your GitHub repository settings. You could find the FRENGLISH_API_KEY at
wwww.frenglish.ai when you log in and go to the "Translate" page.
4. If you haven't created a project in Frenglish yet, create a CLI/SDK project and get the API key.
5. Configure your translation configuration in that project as well.
6. Install the Frenglish SDK in your project:
`npm install frenglish-sdk`
7. Use the SDK to send translation requests and handle the responses.
42 changes: 42 additions & 0 deletions .github/workflows/frenglish-translation.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: Frenglish Translation

on:
push:
branches:
- '**' # This will trigger on pushes to any branch

jobs:
translate:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'

- name: Install dependencies
run: npm install

- name: Get branch name
id: branch-name
run: echo "::set-output name=branch::${GITHUB_REF#refs/heads/}"

- name: Run translation script
env:
FRENGLISH_API_KEY: ${{ secrets.FRENGLISH_API_KEY }}
run: node .github/scripts/translate.js

- name: Create Pull Request
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
git config user.name github-actions
git config user.email [email protected]
git checkout -b ${{ steps.branch-name.outputs.branch }}-frenglish-translations
git add .
git commit -m "Add translated files"
git push origin ${{ steps.branch-name.outputs.branch }}-frenglish-translations
gh pr create --base ${{ steps.branch-name.outputs.branch }} --head ${{ steps.branch-name.outputs.branch }}-frenglish-translations --title "Frenglish Translation Update for ${{ steps.branch-name.outputs.branch }}" --body "This PR contains updated translations for the changed files in branch ${{ steps.branch-name.outputs.branch }}."
108 changes: 108 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# Configs
.env
.env.*

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# TypeScript v1 declaration files
typings/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test

# parcel-bundler cache (https://parceljs.org/)
.cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port
28 changes: 28 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import pluginJs from "@eslint/js"
import tseslint from "typescript-eslint"
import prettierConfig from 'eslint-config-prettier'
import enforceAccessMiddleware from './.eslint/rules/enforce-access-middleware.js'

export default [
pluginJs.configs.recommended,
...tseslint.configs.recommended,
{
plugins: {
custom: {
rules: {
'enforce-access-middleware': enforceAccessMiddleware
}
}
},
rules: {
...prettierConfig.rules,
"no-console": "off",
"@typescript-eslint/no-explicit-any": "off",
"no-trailing-spaces": "error",
"no-multiple-empty-lines": ["error", { "max": 1, "maxEOF": 0 }],
"semi": ["error", "never"],
"indent": ["error", 2],
"custom/enforce-access-middleware": "error"
}
}
]
55 changes: 55 additions & 0 deletions examples/callingSDK.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
// Example client usage:
npm install frenglish-sdk

// Import the Frenglish SDK
const FrenglishSDK = require('frenglish-sdk');

// Initialize the SDK with the API key
const apiKey = 'your-frenglish-api-key-here';
const frenglish = new FrenglishSDK(apiKey);

async function main() {
try {
// Register a webhook to receive translation notifications
await frenglish.registerWebhook('https://your-app.com/frenglish-webhook');
console.log('Webhook registered successfully');

// Request a translation
const translationId = await frenglish.requestTranslation({
text: 'Hello, world!',
sourceLanguage: 'en',
targetLanguage: 'fr'
});
console.log(`Translation requested. ID: ${translationId}`);

// Later, when you receive a webhook notification, you can get the translation
const translation = await frenglish.getTranslation(translationId);
console.log('Received translation:', translation);
} catch (error) {
console.error('Error:', error.message);
}
}

// Set up a webhook endpoint in your application
const express = require('express');
const app = express();
app.use(express.json());

app.post('/frenglish-webhook', (req, res) => {
const { translationId, status } = req.body;
console.log(`Received webhook: Translation ${translationId} status is ${status}`);
if (status === 'completed') {
// Fetch the completed translation
frenglish.getTranslation(translationId)
.then(translation => {
console.log('Completed translation:', translation);
// Process the translation as needed
})
.catch(error => console.error('Error fetching translation:', error));
}
res.sendStatus(200);
});

main();
**/
Loading

0 comments on commit 0650d76

Please sign in to comment.