@ai4bharat/indic-transliterate

中文文档
1.3.8发布于 2024/09/20MITTypeScriptESM + CJS近 30 天下载 2136

Transliterate component for React

原始使用文档
文档目录19 节
  1. Table of contents
  2. 1. About
  3. 2. Demo
  4. 3. Install
  5. 4. Usage
  6. 4.1. Basic example
  7. 4.2. With custom component
  8. 4.3. With TypeScript
  9. 4.4. With Material-UI
  10. 4.5. With External API for transliteration
  11. 5. Get transliteration suggestions
  12. 5.1. Standalone example
  13. 5.2. Custom trigger keys
  14. 5.3. Props
  15. 6. Languages
  16. 6.1. Get supported languages
  17. 6.2. List of language codes
  18. 7. New Feature: Caching for Frequently Used Words
  19. 8. License

Indic Transliterate

Transliteration component for React with support for 21 Indic languages. Uses API from AI4Bharat IndicXlit.

NPM

Table of contents

1. About

This is a frontend library to enable your users to type in many different languages of South Asia, and can be integrated into any React-based application. This library is a fork of react-transliterate, which uses Google Transliterate API which supports around 40 languages across the globe. In this module, our focus is to provide high-quality transliteration-suggestions for Indic languages, especially for low-resource languages like Kashmiri, Manipuri, etc. (which are not supported by Google). For more details about the AI system behind this, please check AI4Bhārat Indic-Xlit.

2. Demo

Click-here to try our demo!

Source of this demo is available in the example folder of the repo.

3. Install

npm install --save @ai4bharat/indic-transliterate

OR

yarn add @ai4bharat/indic-transliterate

4. Usage

4.1. Basic example

import React, { useState } from "react";

import { IndicTransliterate } from "@ai4bharat/indic-transliterate";
import "@ai4bharat/indic-transliterate/dist/index.css";

const App = () => {
  const [text, setText] = useState("");

  return (
    <IndicTransliterate
      value={text}
      onChangeText={(text) => {
        setText(text);
      }}
      lang="hi"
    />
  );
};

export default App;

4.2. With custom component

import React, { useState } from "react";

import { IndicTransliterate } from "@ai4bharat/indic-transliterate";
import "@ai4bharat/indic-transliterate/dist/index.css";

const App = () => {
  const [text, setText] = useState("");

  return (
    <IndicTransliterate
      renderComponent={(props) => <textarea {...props} />}
      value={text}
      onChangeText={(text) => {
        setText(text);
      }}
      lang="hi"
    />
  );
};

export default App;

4.3. With TypeScript

import React, { useState } from "react";

import { IndicTransliterate, Language } from "@ai4bharat/indic-transliterate";
import "@ai4bharat/indic-transliterate/dist/index.css";

const App = () => {
  const [text, setText] = useState("");
  const [lang, setLang] = useState<Language>("hi");

  return (
    <IndicTransliterate
      renderComponent={(props) => <textarea {...props} />}
      value={text}
      onChangeText={(text) => {
        setText(text);
      }}
      lang={lang}
    />
  );
};

export default App;

4.4. With Material-UI

import React, { useState } from "react";

import { IndicTransliterate, Language } from "@ai4bharat/indic-transliterate";
import "@ai4bharat/indic-transliterate/dist/index.css";

import Input from "@material-ui/core/Input";

const App = () => {
  const [text, setText] = useState("");
  const [lang, setLang] = useState<Language>("hi");

  return (
    <IndicTransliterate
      renderComponent={(props) => {
        const inputRef = props.ref;
        delete props["ref"];
        return <Input {...props} inputRef={inputRef} />;
      }}
      value={text}
      onChangeText={(text) => {
        setText(text);
      }}
      lang={lang}
    />
  );
};

export default App;

4.5. With External API for transliteration

import { IndicTransliterate } from "@ai4bharat/indic-transliterate";
import "@ai4bharat/indic-transliterate/dist/index.css";

const App = () => {
  const [text, setText] = useState("");

  return (
    <IndicTransliterate
      value={text}
      onChangeText={(text) => {
        setText(text);
      }}
      lang="hi"
      customApiURL="https://your-custom-transliteration-api/{language}/{text}"
    />
  );
};

export default App;

This allows users to integrate their own APIs instead of relying on the default transliteration API, as long as the external API is a GET API with the following format: https://your-custom-transliteration-api/{language}/{text} and returns a response in this format:

{
  "result": [
    "suggestion-1",
    "suggestion-2",
    "suggestion-3",
    "suggestion-4",
    "suggestion-5",
    ...
  ],
  ...
}

5. Get transliteration suggestions

5.1. Standalone example

import { getTransliterateSuggestions } from "@ai4bharat/indic-transliterate";

const data = await getTransliterateSuggestions(
  word, // word to fetch suggestions for
  {
    numOptions: 5, // number of suggestions to fetch
    showCurrentWordAsLastSuggestion: true, // add the word as the last suggestion
    lang: "hi", // target language
  },
);

5.2. Custom trigger keys

Keys which when pressed, input the current selection to the textbox

Indic Transliterate uses the event.keycode property to detect keys. Here are some predefined keys you can use. Or, you can enter the integer codes for any other key you'd like to use as the trigger

import React, { useState } from "react";

import { IndicTransliterate, TriggerKeys } from "@ai4bharat/indic-transliterate";
import "@ai4bharat/indic-transliterate/dist/index.css";

import Input from "@material-ui/core/Input";

const App = () => {
  const [text, setText] = useState("");

  return (
    <IndicTransliterate
      value={text}
      onChangeText={(text) => {
        setText(text);
      }}
      lang="hi"
      triggerKeys={[
        TriggerKeys.KEY_RETURN,
        TriggerKeys.KEY_ENTER,
        TriggerKeys.KEY_SPACE,
        TriggerKeys.KEY_TAB,
      ]}
    />
  );
};

export default App;

5.3. Props

PropRequired?DefaultDescription
onChangeTextYesListener for the current value from the component. (text: string) => void
valueYesvalue prop to pass to the component
enabledtrueControl whether suggestions should be shown
renderComponent(props) => <input {...props} />Component to render. You can pass components from your component library as this prop
langhiLanguage you want to transliterate. See the following section for language codes
maxOptions5Maximum number of suggestions to show in helper
offsetY0Extra space between the top of the helper and bottom of the caret
offsetX0Extra space between the caret and left of the helper
containerClassNameempty stringClassname passed to the container of the component
containerStyles{}CSS styles object passed to the container
activeItemStyles{}CSS styles object passed to the active item <li> tag
hideSuggestionBoxOnMobileDevicesfalseShould the suggestions be visible on mobile devices since keyboards like Gboard and Swiftkey support typing in multiple languages
hideSuggestionBoxBreakpoint450type: number. To be used when hideSuggestionBoxOnMobileDevices is true. Suggestion box will not be shown below this device width
triggerKeysKEY_SPACE, KEY_ENTER, KEY_TAB, KEY_RETURNKeys which when pressed, input the current selection to the textbox
insertCurrentSelectionOnBlurtrueShould the current selection be inserted when blur event occurs
showCurrentWordAsLastSuggestiontrueShow current input as the last option in the suggestion box
horizontalViewfalseWhen true suggestions appear side by side, improving readability and accessibility for users who prefer a compact layout
customApiURLindic transliterate apiFlexibility to use external API for transliteration, seamless integration as long as the response structure follows the required format 4.5

6. Languages

6.1. Get supported languages

import { getTransliterationLanguages } from "@ai4bharat/indic-transliterate";

const data = await getTransliterationLanguages();

6.2. List of language codes

Currently supports the following 21 languages from the Indian subcontinent:

ISO 639 codeLanguage
asAssamese - অসমীয়া
bnBangla - বাংলা
brxBoro - बड़ो
guGujarati - ગુજરાતી
hiHindi - हिंदी
knKannada - ಕನ್ನಡ
ksKashmiri - كٲشُر
gomKonkani Goan - कोंकणी
maiMaithili - मैथिली
mlMalayalam - മലയാളം
mniManipuri - ꯃꯤꯇꯩꯂꯣꯟ
mrMarathi - मराठी
neNepali - नेपाली
orOriya - ଓଡ଼ିଆ
paPanjabi - ਪੰਜਾਬੀ
saSanskrit - संस्कृतम्
sdSindhi - سنڌي
siSinhala - සිංහල
taTamil - தமிழ்
teTelugu - తెలుగు
urUrdu - اُردُو

7. New Feature: Caching for Frequently Used Words

Overview:
The module now supports caching of up to 10,000 words per language to enhance performance by reducing API calls. The caching mechanism stores words and their corresponding suggestions, improving the speed and efficiency of generating suggestions, especially for frequently used words.

How It Works:

  • Cache Initialization:
    When a user begins typing, the tool fetches suggestions for each word. If a word is used for the first time, it is added to the cache with its suggestions and an initial frequency count of 1.

  • Cache Structure:
    The cache is structured by language, where each language has its own dictionary of words and their suggestions:

    {
      language-1: {
        word-1: {
          suggestions: string[],
          frequency: number
        },
        word-2: {
          suggestions: string[],
          frequency: number
        },
        word-3: {
          suggestions: string[],
          frequency: number
        },
        ...
      },
      language-2:{
      ...
      },
      ...
    }
    
  • Cache Lookup:

    • When a word is typed, the tool first searches for it in the cache.
    • If found, the suggestions are retrieved, and the frequency count is incremented.
    • If not found, the tool fetches suggestions from the API, adds the word to the cache, and initializes the frequency count to 1.
  • Cache Management:

    • The cache is limited to 10,000 words per language.
    • When the cache for a specific language exceeds 10,000 words, the least frequently used word is removed to make room for new entries.
  • Example Workflow:

    1. User starts typing a word (e.g., "hello"):
      • The tool checks the cache for the word.
      • If "hello" is found, the suggestions are retrieved, and the frequency is incremented.
      • If "hello" is not found, suggestions are fetched from the API, and "hello" is added to the cache with a frequency of 1.
    2. Cache size exceeds 10,000 words:
      • The least frequently used word is replaced with the new word and its suggestions.
  • Key Benefits:

    • Improved Performance: Reduces the number of API calls by utilizing cached suggestions for frequently used words.
    • Adaptive Caching: Automatically adjusts to user behavior, increasing the frequency count for commonly used words.
    • Efficient Storage: Least frequently used words are replaced to maintain an optimal cache size.

8. License

MIT © ai4bharat

Sincere thanks to burhanuday for making his work open-source!

版本与发布记录

@ai4bharat/indic-transliterate 共发布 25 个版本,首次发布于 2022/08/12;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.3.8latest2024/09/202 年前
1.3.72024/07/312 年前
1.3.62024/07/242 年前
1.3.52024/07/232 年前
1.3.32024/07/022 年前
1.3.22024/04/272 年前

关于 @ai4bharat/indic-transliterate 的常见问题

@ai4bharat/indic-transliterate 是什么?

Transliterate component for React

如何安装 @ai4bharat/indic-transliterate?

在项目目录运行 npm install @ai4bharat/indic-transliterate,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^16.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@ai4bharat/indic-transliterate 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@ai4bharat/indic-transliterate 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@ai4bharat/indic-transliterate 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=10。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@ai4bharat/indic-transliterate 可以商用吗?

@ai4bharat/indic-transliterate 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@ai4bharat/indic-transliterate 的下载量有多少?

根据 npm 官方下载统计,@ai4bharat/indic-transliterate 在 2026/10/05 – 2026/11/03 这 30 天内被下载 2,136 次,日均约 71 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@ai4bharat/indic-transliterate 还在维护吗?

最新版本 1.3.8 发布于 2024/09/20(2 年前);至今共发布 25 个版本,其中过去 12 个月发布了 0 个;首次发布于 2022/08/12。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。