APIギャラリー



この記事は、txtai、AI動力セマンティック検索プラットフォームのチュートリアルシリーズの一部です.
TXTAI APIは、FastAPIによって支持されるウェブベースのサービスです.類似性検索、抽出QAとゼロショットのラベリングを含むすべてのTXTI機能は、APIを介して入手可能です.
この記事では、Txtai APIをインストールし、Txtai用のサポートされている言語バインディングの各使用例を示します.

依存関係のインストール

txtaiとすべての依存関係をインストールします.この記事はAPIを使用しているので、APIエクストラパッケージをインストールする必要があります.
pip install txtai[api]

Python


最初の方法はPython経由での直接アクセスです.ここでのすべての例については、ゼロショットラベリングを使用します.ゼロショット分類の詳細についてはを参照してください.
import os
from IPython.core.display import display, HTML
from txtai.pipeline import Labels

def table(rows):
    html = """
    <style type='text/css'>
    @import url('https://fonts.googleapis.com/css?family=Oswald&display=swap');
    table {
      border-collapse: collapse;
      width: 900px;
    }
    th, td {
        border: 1px solid #9e9e9e;
        padding: 10px;
        font: 20px Oswald;
    }
    </style>
    """

    html += "<table><thead><tr><th>Text</th><th>Label</th></tr></thead>"
    for text, label in rows:
        html += "<tr><td>%s</td><td>%s</td></tr>" % (text, label)
    html += "</table>"

    display(HTML(html))

# Create labels model
labels = Labels()

テキストにラベルを適用する


data = ["Wears a red suit and says ho ho",
        "Pulls a flying sleigh",
        "This is cut down and decorated",
        "Santa puts these under the tree",
        "Best way to spend the holidays"]

# List of labels
tags = ["🎅 Santa Clause", "🦌 Reindeer", "🍪 Cookies", "🎄 Christmas Tree", "🎁 Gifts", "👪 Family"]

# Render output to table
table([(text, tags[labels(text, tags)[0][0]]) for text in data])
テキスト
ラベル
赤いスーツを着て、Ho Hoを言います
🎅 サンタクロース
飛ぶそりを引く
🦌 トナカイ
これを切り倒して飾る
🎄 クリスマスツリー
サンタは、木の下でこれらを置きます
🎁 贈り物
休日を過ごす最善の方法
👪 家族
もう一度、我々はゼロショット標識の力を見ます.モデルはこの例に特有のどんなデータでも訓練されませんでした.まだ多くの知識が大規模なNLPモデルに格納されて驚いた.

APIインスタンスを起動する


ここで、残りの例を実行するAPIインスタンスを開始します.APIは実行する設定ファイルを必要とします.以下の例は、ラベリングだけを含むように簡略化されます.より詳細な構成例についてはthis linkを参照してください.
APIインスタンスはバックグラウンドで開始されます.
CONFIG=index.yml nohup uvicorn "txtai.api:app" &> api.log &
sleep 90

ジャバスクリプト


TxtaiJSはNPM経由で利用可能で、次のようにインストールできます.
npm install txtai
この例では、txtaiをクローンします.JPプロジェクトのビルド構成をインポートします.
git clone https://github.com/neuml/txtai.js

ラベルを作る。js


以下のファイルは、ラベルの例のJavaScriptバージョンです.
import {Labels} from "txtai";
import {sprintf} from "sprintf-js";

const run = async () => {
    try {
        let labels = new Labels("http://localhost:8000");

        let data = ["Wears a red suit and says ho ho",
                    "Pulls a flying sleigh",
                    "This is cut down and decorated",
                    "Santa puts these under the tree",
                    "Best way to spend the holidays"];

        // List of labels
        let tags = ["🎅 Santa Clause", "🦌 Reindeer", "🍪 Cookies", "🎄 Christmas Tree", "🎁 Gifts", "👪 Family"];

        console.log(sprintf("%-40s %s", "Text", "Label"));
        console.log("-".repeat(75))

        for (let text of data) {
            let label = await labels.label(text, tags);
            label = tags[label[0].id];

            console.log(sprintf("%-40s %s", text, label));
        }
    }
    catch (e) {
        console.trace(e);
    }
};

run();

ビルドと実行のラベルの例


cd txtai.js/examples/node 
npm install
npm run build
node dist/labels.js
Text                                     Label
---------------------------------------------------------------------------
Wears a red suit and says ho ho          🎅 Santa Clause
Pulls a flying sleigh                    🦌 Reindeer
This is cut down and decorated           🎄 Christmas Tree
Santa puts these under the tree          🎁 Gifts
Best way to spend the holidays           👪 Family
JavaScriptプログラムは、ネイティブのPythonを実行したときと同じ結果を示しています!

ジャバ


TxtaiJavaは標準のJavaビルドツール(gradle、maven、sbt)と統合します.TxtaiをGradleに依存するように追加する方法を次のように示します.
implementation 'com.github.neuml:txtai.java:v2.0.0'
この例では、txtaiをクローンします.Javaプロジェクトのビルド構成をインポートします.
git clone https://github.com/neuml/txtai.java

を作成します。ジャバ


次のファイルは、ラベルの例のJavaバージョンです.
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;

import txtai.API.IndexResult;
import txtai.Labels;

public class LabelsDemo {
    public static void main(String[] args) {
        try {
            Labels labels = new Labels("http://localhost:8000");

            List <String> data = 
                Arrays.asList("Wears a red suit and says ho ho",
                              "Pulls a flying sleigh",
                              "This is cut down and decorated",
                              "Santa puts these under the tree",
                              "Best way to spend the holidays");

            // List of labels
            List<String> tags = Arrays.asList("🎅 Santa Clause", "🦌 Reindeer", "🍪 Cookies", "🎄 Christmas Tree", "🎁 Gifts", "👪 Family");

            System.out.printf("%-40s %s%n", "Text", "Label");
            System.out.println(new String(new char[75]).replace("\0", "-"));

            for (String text: data) {
                List<IndexResult> label = labels.label(text, tags);
                System.out.printf("%-40s %s%n", text, tags.get(label.get(0).id));
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
cd txtai.java/examples
../gradlew -q --console=plain labels 2> /dev/null
Text                                     Label
---------------------------------------------------------------------------
Wears a red suit and says ho ho          🎅 Santa Clause
Pulls a flying sleigh                    🦌 Reindeer
This is cut down and decorated           🎄 Christmas Tree
Santa puts these under the tree          🎁 Gifts
Best way to spend the holidays           👪 Family
Javaプログラムは、ネイティブのPythonを実行したときと同じ結果を示しています!


TxtaiRSはcrates経由で利用可能です.IOとあなたの貨物に以下を加えることによってインストールされることができます.tomlファイル.
[dependencies]
txtai = { version = "2.0" }
tokio = { version = "0.2", features = ["full"] }
この例では、txtaiをクローンします.RSプロジェクトは、ビルドの構成をインポートします.最初にさびをインストールする必要があります.
apt-get install rustc
git clone https://github.com/neuml/txtai.rs

ラベルを作る。RS


以下のファイルは、ラベルの例の錆バージョンです.
use std::error::Error;

use txtai::labels::Labels;

pub async fn labels() -> Result<(), Box<dyn Error>> {
    let labels = Labels::new("http://localhost:8000");

    let data = ["Wears a red suit and says ho ho",
                "Pulls a flying sleigh",
                "This is cut down and decorated",
                "Santa puts these under the tree",
                "Best way to spend the holidays"];

    println!("{:<40} {}", "Text", "Label");
    println!("{}", "-".repeat(75));

    for text in data.iter() {
        let tags = vec!["🎅 Santa Clause", "🦌 Reindeer", "🍪 Cookies", "🎄 Christmas Tree", "🎁 Gifts", "👪 Family"];
        let label = labels.label(text, &tags).await?[0].id;

        println!("{:<40} {}", text, tags[label]);
    }

    Ok(())
}

ビルドと実行のラベルの例


cd txtai.rs/examples/demo
cargo build
cargo run labels
Text                                     Label
--------------------------------------------------------------------------------
Wears a red suit and says ho ho          🎅 Santa Clause
Pulls a flying sleigh                    🦌 Reindeer
This is cut down and decorated           🎄 Christmas Tree
Santa puts these under the tree          🎁 Gifts
Best way to spend the holidays           👪 Family
錆プログラムは、ネイティブのPythonを実行しているときと同じ結果を示しています!

試み


TxtaiGOは次のインポート文を追加することでインストールできます.モジュールを使うとき、txtai.自動的にインストールされます.そうでなければgo getを使います.
import "github.com/neuml/txtai.go"
この例では、ラベルのスタンドアロンプロセスを作成します.まずgoをインストールする必要があります.
apt install golang-go
go get "github.com/neuml/txtai.go"

ラベルを作る。試み


以下のファイルは、ラベルの例の囲碁版です.
package main

import (
    "fmt"
    "strings"
    "github.com/neuml/txtai.go"
)

func main() {
    labels := txtai.Labels("http://localhost:8000")

    data := []string{"Wears a red suit and says ho ho",
                   "Pulls a flying sleigh",
                   "This is cut down and decorated",
                   "Santa puts these under the tree",
                   "Best way to spend the holidays"}

    // List of labels
    tags := []string{"🎅 Santa Clause", "🦌 Reindeer", "🍪 Cookies", "🎄 Christmas Tree", "🎁 Gifts", "👪 Family"}

    fmt.Printf("%-40s %s\n", "Text", "Label")
    fmt.Println(strings.Repeat("-", 75))

    for _, text := range data {
        label := labels.Label(text, tags)
        fmt.Printf("%-40s %s\n", text, tags[label[0].Id])
    }
}
go run labels.go
Text                                     Label
--------------------------------------------------------------------------------
Wears a red suit and says ho ho          🎅 Santa Clause
Pulls a flying sleigh                    🦌 Reindeer
This is cut down and decorated           🎄 Christmas Tree
Santa puts these under the tree          🎁 Gifts
Best way to spend the holidays           👪 Family
移動プログラムは、ネイティブのPythonを実行しているときと同じ結果を示しています!