The LibreTranslate API for Rust.

Overview

libretranslate-rs

A LibreTranslate API for Rust.

libretranslate = "0.2.4"

libretranslate allows you to use open source machine translation in your projects through an easy to use API that connects to the official webpage.

Basic Example

All translations are done through the translate() function:

use libretranslate::{translate, Language};

fn main() {
    let source = Language::French;
    let target = Language::English;
    let input = "le texte français.";

    let data = translate(Some(source), target, input).unwrap();

    println!("Input {}: {}", data.source.as_pretty(), data.input);
    println!("Output {}: {}", data.target.as_pretty(), data.output);
}

Output:

Input French: le texte français.
Output English: the French text.

See In Examples Folder

Language Detection

libretranslate uses whatlang to detect language so you can translate unknown languages into a target language of your choice.

whatlang isn't perfect though, and for short sentences it can be very bad at detecting language. whatlang can detect more languages than libretranslate can translate, so if it detects your input as a language that libretranslate can't translate, the translate function will return a TranslateError::DetectError.

Here's a simple example.

use libretranslate::{Language, translate};

fn main() {
    let target = Language::English;
    let text = "le texte français.";

    let data = translate(None, target, text).unwrap();

    println!("Input {}: {}", data.source.as_pretty(), data.input);
    println!("Output {}: {}", data.target.as_pretty(), data.output);
}

Output:

Input French: le texte français.
Output English: the French text.

See In Examples Folder

Language Functionality

The Language enum has a lot of functionality so you can create a Language from all sorts of different user inputs.

You can return a &str with the language's name in English using as_pretty(), or the language's code using as_code().

Language also implements FromStr so you can create a Language using text like "en", or "English" (case doesn't matter). You can do this by either using Language::from() or .parse::<Language>().

Here's a simple example.

use libretranslate::Language;

fn main() {
    let english = Language::from("EnGlIsH").unwrap();
    let chinese = "zh".parse::<Language>().unwrap().as_pretty();
    let french  = "FRENCH".parse::<Language>().unwrap().as_code();

    println!("\"EnGlIsH\" parsed to code: {}", english);
    println!("\"zh\" parsed to pretty: {}", chinese);
    println!("\"FRENCH\" parsed to code: {}", french);
}

Output:

"EnGlIsH" parsed to code: en
"zh" parsed to pretty: Chinese
"FRENCH" parsed to code: fr

See In Examples Folder

String Methods

The trait Translate implements AsRef<str>, meaning that any &str or String can be translated into any other language.

Here's a simple example.

use libretranslate::{Translate, Language};

fn main() {
    let text = "Détecter une langue et un script par un texte donné.".to_english_from(Language::French).unwrap();
    
    println!("{}", text);
}

Output:

detect a language and script by a given text.

See In Examples Folder

Available Languages

  • English
  • Arabic
  • Chinese
  • French
  • German
  • Italian
  • Japanese
  • Portuguese
  • Russian
  • Spanish

Written in Rust, with love by Grant Handy.

Comments
  • Error in API call

    Error in API call

    Hi Grant - first of all - great work on the crate. I had set it up and was using it in testing in an Actix-Web app and it was working well, but a few days ago it stopped working with the following error:

    thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseError("Unable to find translatedText in parsed JSON")', src/main.rs:172:101

    I'm thinking there might have been a change in the LibreTranslate API

    Here's the test snippet that mirrors my app:

    use libretranslate::{translate, Language};
    
    #[tokio::main]
    async fn main() {
        let mut translate_strings: Vec<String> = Vec::new();
    
        let nodes = vec![
            ("father", "person"),
            ("manager", "role"),
            ("gen x", "person"),
        ];
        
        for n in &nodes {
            translate_strings.push(format!("{}.\n", &n.0));
        };
    
        let source = Language::English;
        let target = Language::French;
    
        let input = translate_strings.concat();
    
        let data = translate(source, target, input)
            .await
            .unwrap();
    
        let mut phrases: Vec<(String, String)> = Vec::new();
    
        //let en = data.input.split(". ").into_iter();
        let fr = data.output.split(".\n");
        let en = data.input.split(".\n");
    
        for (f, e) in fr.zip(en) {
            if e != "" {
                phrases.push((e.to_lowercase().replace("/", ""), f.to_lowercase().replace("/","")));
            };
        };
    
        println!("{:?}", &phrases);
    
    opened by ToferC 7
  • Compatibility unic-langid

    Compatibility unic-langid

    It would be nice to have some inbuilt or optional compatibility with https://crates.io/crates/unic-langid/0.9.0 which is used by a lot of localization/language related crates in the Rust ecosystem.

    opened by kellpossible 2
  • Update dependencies, formatting, refactoring

    Update dependencies, formatting, refactoring

    Should not affect any program functionality, just changes the structure a little bit + dependency update.

    Various commands ran include: cargo fix, cargo check, cargo fmt, cargo +nightly clippy, cargo clippy, cargo +nightly clippy --fix -Z unstable-options.

    PS: I was just going through my starred projects and you wrote both thes and libretranslate-rs! I didn't even notice this before. I use both of these including thes pretty much regularly (beats using the browser)! Thanks a bunch.

    opened by sigaloid 1
  • Proposal for change in the Translate by Method API

    Proposal for change in the Translate by Method API

    I saw your project a couple of days ago in Reddit, and I couldn't help but notice you had a bunch of hardcoded methods for translating to and from a series of languages.

    What do you think about the changes I've made in my fork of the project? https://github.com/Rafagd/libretranslate-rs

    opened by Rafagd 1
  • Support for more languages

    Support for more languages

    I see there are much more languages available on libretranslate.com than supported in this crate. Is there any reason for that, or would it be possible to add support for those less common languages as well?

    opened by tage64 1
Releases(0.4.1)
Owner
Grant Handy
FOSS ROCKS!
Grant Handy
An API for managing your servers

Intecture APIs Intecture is an API for managing your servers. Visit intecture.io. API docs can be found here: intecture.io/api/intecture_api/. Intectu

Intecture 30 Oct 18, 2022
A genetic algorithm for bechmark problems, written to learn Rust.

Genetic Algorithm A genetic algorithm in Rust for the following benchmark problems: Ackley Griewangk Rastrigin Rosenbrock Schwefel Sphere Usage: Insta

Andrew Schwartzmeyer 73 Dec 25, 2022
interative assembly shell written in rust

Overview this project is inspired by https://github.com/poppycompass/asmshell Preview Build from source git clone https://github.com/keystone-engine/k

Xargin 236 Dec 23, 2022
Distributed compute platform implemented in Rust, and powered by Apache Arrow.

Ballista: Distributed Compute Platform Overview Ballista is a distributed compute platform primarily implemented in Rust, powered by Apache Arrow. It

Ballista 2.3k Jan 3, 2023
Userspace WireGuard® Implementation in Rust

BoringTun BoringTun is an implementation of the WireGuard® protocol designed for portability and speed. BoringTun is successfully deployed on millions

Cloudflare 4.8k Jan 8, 2023
Drill is a HTTP load testing application written in Rust inspired by Ansible syntax

Drill Drill is a HTTP load testing application written in Rust. The main goal for this project is to build a really lightweight tool as alternative to

Ferran Basora 1.5k Dec 28, 2022
An experimental HTTP load testing application written in Rust.

Herd Herd was a small side project in building a HTTP load testing application in Rust with a main focus on being easy to use and low on OS level depe

Jacob Clark 100 Dec 27, 2022
A fast data collector in Rust

Flowgger is a fast, simple and lightweight data collector written in Rust. It reads log entries over a given protocol, extracts them, decodes them usi

Amazon Web Services - Labs 739 Jan 7, 2023
kytan: High Performance Peer-to-Peer VPN in Rust

kytan: High Performance Peer-to-Peer VPN kytan is a high performance peer to peer VPN written in Rust. The goal is to to minimize the hassle of config

Chang Lan 368 Dec 31, 2022
A purpose-built proxy for the Linkerd service mesh. Written in Rust.

This repo contains the transparent proxy component of Linkerd2. While the Linkerd2 proxy is heavily influenced by the Linkerd 1.X proxy, it comprises

Linkerd 1.7k Jan 7, 2023
A GPU-accelerated cross-platform terminal emulator and multiplexer written by @wez and implemented in Rust

Wez's Terminal A GPU-accelerated cross-platform terminal emulator and multiplexer written by @wez and implemented in Rust User facing docs and guide a

Wez Furlong 6.7k Jan 2, 2023
pastebin written in pure rust. A rewrite of ptpb/pb.

rspb rust fork of ptpb/pb TL;DR Create a new paste from the output of cmd: cmd | curl -F c=@- https://pb.mgt.moe/ Usage Creating pastes > echo hi | c

mgt 39 Jan 4, 2023
Yet another pager in Rust

rust-pager Yet another pager in Rust Features Vim like keybindings Search substring Mouse wheel support Install cargo install rust-pager Usage <comman

null 19 Dec 7, 2022
A Rust serverless function to retrieve and relay a playlist for Twitch livestreams/VODs.

City17 A Rust serverless function to retrieve and relay a playlist for Twitch livestreams/VODs. By running this in specific countries and using a brow

Malloc Voidstar 5 Dec 15, 2021
Fork of async-raft, the Tokio-based Rust implementation of the Raft protocol.

Agreed Fork of async-raft, the Tokio-based Rust implementation of the Raft distributed consensus protocol. Agreed is an implementation of the Raft con

NLV8 Technologies 8 Jul 5, 2022
Rust runtime for Vercel Functions.

Rust Rust runtime for Vercel Functions. Community-maintained package to support using Rust inside Vercel Functions as a Runtime. Usage First, you'll n

Vercel Community 378 Dec 30, 2022
Easy c̵̰͠r̵̛̠ö̴̪s̶̩̒s̵̭̀-t̶̲͝h̶̯̚r̵̺͐e̷̖̽ḁ̴̍d̶̖̔ ȓ̵͙ė̶͎ḟ̴͙e̸̖͛r̶̖͗ë̶̱́ṉ̵̒ĉ̷̥e̷͚̍ s̷̹͌h̷̲̉a̵̭͋r̷̫̊ḭ̵̊n̷̬͂g̵̦̃ f̶̻̊ơ̵̜ṟ̸̈́ R̵̞̋ù̵̺s̷̖̅ţ̸͗!̸̼͋

Rust S̵̓i̸̓n̵̉ I̴n̴f̶e̸r̵n̷a̴l mutability! Howdy, friendly Rust developer! Ever had a value get m̵̯̅ð̶͊v̴̮̾ê̴̼͘d away right under your nose just when

null 294 Dec 23, 2022
Modrinth API is a simple library for using, you guessed it, the Modrinth API in Rust projects

Modrinth API is a simple library for using, you guessed it, the Modrinth API in Rust projects. It uses reqwest as its HTTP(S) client and deserialises responses to typed structs using serde.

null 21 Jan 1, 2023
Modrinth API is a simple library for using Modrinth's API in Rust projects

Ferinth is a simple library for using the Modrinth API in Rust projects. It uses reqwest as its HTTP(S) client and deserialises responses to typed structs using serde.

null 20 Dec 8, 2022
A Rust API for Vega-Lite V4 to build chart with a rusty API.

Vega-Lite V4 for Rust A Rust API for Vega-Lite V4 to build chart with a rusty API. Similar to the Altair project in python, this crate build upon Vega

Procyon 18 Nov 26, 2022