Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ Install the package via npm (or yarn):
```bash
npm install react-ai-translator

```

# Usage

Wrap your application (or a section of it) in the `TranslatorProvider` to initialize the translation model.
Expand Down Expand Up @@ -97,6 +99,8 @@ function App() {

export default App

```


# How It Works

Expand Down
4 changes: 2 additions & 2 deletions lefthook.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ pre-commit:
run: pnpm biome check --write --unsafe --staged --no-errors-on-unmatched && git add -u
typecheck:
run: pnpm tsc
# build:
# run: pnpm build
build:
run: pnpm build
test:
run: pnpm test:ci
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
{
"name": "@joelshejar/react-ai-translator",
"name": "@codethicket/react-ai-translator",
"description": "",
"version": "0.0.60",
"version": "0.0.62",
"author": "Joel Rajesh",
"license": "MIT",
"keywords": [],
"keywords": ["translations", "ai", "react", "i18n"],
"repository": {
"type": "git",
"url": "https://github.com/joelshejar/practise-translations-ai"
"url": "https://github.com/CodeThicket/react-ai-translator"
},
"scripts": {
"dev": "concurrently \"pnpm build --watch\" \"pnpm storybook\" \"pnpm test\" ",
Expand Down
25 changes: 2 additions & 23 deletions src/hooks/useTranslation.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { useEffect, useRef, useState } from "react";

// Define the possible statuses returned by the worker
type WorkerStatus =
| "initiate"
| "progress"
Expand All @@ -9,21 +8,18 @@ type WorkerStatus =
| "update"
| "complete";

// Define the structure of the progress items
interface ProgressItem {
file?: string;
progress?: number;
}

// Define the data structure for worker messages
interface WorkerMessageData {
status: WorkerStatus;
output?: string;
progress?: number;
file?: string;
}

// Hook return type
interface UseTranslationReturn {
translate: (text: string, srcLang: string, tgtLang: string) => void;
translatedText: string;
Expand All @@ -36,29 +32,22 @@ interface UseTranslationReturn {
const useTranslation = (_workerScript: string): UseTranslationReturn => {
const worker = useRef<Worker | null>(null);

// States for managing translation
const [loading, setLoading] = useState<boolean>(false);
const [modelLoading, setModelLoading] = useState<boolean>(false);
const [progress, setProgress] = useState<ProgressItem[]>([]);
const [translatedText, setTranslatedText] = useState<string>("");
const [error, setError] = useState<string | null>(null);

console.log("hhhhh");

useEffect(() => {
if (!worker.current) {
// Initialize the worker
worker.current = new Worker(new URL("./worker.mjs", import.meta.url), {
type: "module",
});
}

// Handle worker messages
const onMessage = (e: MessageEvent<WorkerMessageData>) => {
const { status, output, progress: progressValue, file } = e.data;

console.log(status, "status");

switch (status) {
case "initiate": {
setLoading(true);
Expand All @@ -68,7 +57,6 @@ const useTranslation = (_workerScript: string): UseTranslationReturn => {
}

case "progress": {
console.log("progress");
setProgress((prev) =>
prev.map((item) =>
item.file === file ? { ...item, progress: progressValue } : item,
Expand All @@ -78,30 +66,24 @@ const useTranslation = (_workerScript: string): UseTranslationReturn => {
}

case "done": {
console.log("done");
setModelLoading(false);
setProgress((prev) => prev.filter((item) => item.file !== file));
break;
}

case "ready": {
console.log("ready");
setLoading(false);
break;
}

case "update": {
console.log("update");
console.log(output, "output");
// Append partial translations
if (output) {
setTranslatedText(output);
}
break;
}

case "complete": {
console.log("complete");
setLoading(false);
break;
}
Expand All @@ -111,25 +93,22 @@ const useTranslation = (_workerScript: string): UseTranslationReturn => {
worker.current.addEventListener("message", onMessage);

return () => {
// worker.current?.removeEventListener("message", onMessage)
// If you want the worker to be terminated on unmount, uncomment below:
// worker.current?.terminate();
// worker.current = null;
};
}, []);

// Function to send translation requests to the worker
const translate = (text: string, srcLang: string, tgtLang: string) => {
console.log("kkkk");
if (!worker.current) {
console.error("Worker is not initialized.");
return;
}

setLoading(true);
setError(null);
setTranslatedText(""); // Reset the output

console.log("lllll", text, srcLang, tgtLang);
setTranslatedText("");

worker.current.postMessage({
text,
Expand Down
11 changes: 0 additions & 11 deletions src/worker.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
// worker.ts

import { type PipelineType, pipeline } from "@xenova/transformers";

// Extend the global scope for a dedicated worker
declare const self: DedicatedWorkerGlobalScope & typeof globalThis;

/**
Expand Down Expand Up @@ -34,19 +31,12 @@ self.addEventListener("message", async (event: MessageEvent) => {
// Retrieve the translation pipeline. When called for the first time,
// this will load the pipeline and save it for future use.
const translator = await MyTranslationPipeline.getInstance((x) => {
// We also add a progress callback to the pipeline so that we can
// track model loading.
self.postMessage(x);
});

// Log the language codes
console.log(event.data.tgt_lang, event.data.src_lang, "langcode");

// Actually perform the translation
const output = await translator?.(event.data.text, {
tgt_lang: event.data.tgt_lang,
src_lang: event.data.src_lang,
// Allows for partial output
callback_function: (x: any) => {
self.postMessage({
status: "update",
Expand All @@ -57,7 +47,6 @@ self.addEventListener("message", async (event: MessageEvent) => {
},
});

// Send the output back to the main thread
self.postMessage({
status: "complete",
output: output,
Expand Down
9 changes: 0 additions & 9 deletions tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,6 @@ const common: Options = {
injectStyle: false,
target: "es2021",
platform: "browser",
// dts: {
// entry: 'src/index.js', // or whichever main file you want
// },
// loader: {
// '.worker.js': 'file', // Handle worker files as static files
// },
};

const getPackageName = async () => {
Expand Down Expand Up @@ -68,9 +62,6 @@ const linkSelf = async () => {

// biome-ignore lint/suspicious/noConsoleLog: <explanation>
// biome-ignore lint/suspicious/noConsole: <explanation>
console.log(
`Run 'pnpm link ${await getPackageName()} --global' inside another project to consume this package.`,
);
};

export default defineConfig({
Expand Down
Loading