Coder Social home page Coder Social logo

ibm / max-chinese-phonetic-similarity-estimator Goto Github PK

View Code? Open in Web Editor NEW
34.0 14.0 12.0 410 KB

Estimate the phonetic distance between Chinese words and get similar sounding candidate words.

License: Apache License 2.0

Dockerfile 5.45% Python 94.55%

max-chinese-phonetic-similarity-estimator's Introduction

Build Status Website Status

IBM Developer Model Asset Exchange: Chinese Phonetic Similarity Estimator

This repository contains code to instantiate and deploy a Chinese Phonetic Similarity Estimator. The model provides a phonetic algorithm for indexing Chinese characters by sound. Given two Chinese words of the same length, the model determines the distances between the two words and also returns a few candidate words which are close to the given word(s). The code complies with the phonetic principles of Mandarin Chinese as guided by the Romanization defined in ISO 7098:2015.

The model is based on the DimSim model. The code in this repository deploys the model as a web service in a Docker container. This repository was developed as part of the IBM Developer Model Asset Exchange and the public API is powered by IBM Cloud.

Model Metadata

Domain Application Industry Framework Training Data Input Data Format
NLP Text Clustering/Phonetics Social Media Python N/A Chinese Text (utf-8 encoded)

References

Licenses

Component License Link
This repository Apache 2.0 LICENSE
Model Weights N/A N/A
Model Code (3rd party) Apache 2.0 LICENSE
Test Samples N/A N/A

Pre-requisites:

  • docker: The Docker command-line interface. Follow the installation instructions for your system.
  • The minimum recommended resources for this model is 4 GB Memory and 4 CPUs.

Deployment options

Run using PyPi

Installing the library

Dependencies:

  • pypinyin: used for translating Chinese characters into their corresponding pinyins.

There are two ways to install this library:

  • Install from PyPi
$ pip install dimsim
  • Install from GitHub
$ pip install git+https://github.com/System-T/Dimsim.git

How to use the library

Once you have the package installed you can use it for the two functions as shown below.

  • Computing phonetic distance of two Chinese phrases. The optional argument pinyin (False by default) can be used to provide a pinyin string list directly. See example usage below.
import dimsim

dist = dimsim.get_distance("大侠","大虾")
0.0002380952380952381

dist = dimsim.get_distance("大侠","大人")
25.001417183349876

dist = dimsim.get_distance(['da4','xia2'],['da4','xia1']], pinyin=True)
0.0002380952380952381

dist = dimsim.get_distance(['da4','xia2'],['da4','ren2']], pinyin=True)
25.001417183349876

  • Return top-k phonetically similar phrases of a given Chinese phrase with two optional parameters:
    • mode controls the character type of the returned Chinese phrases, where 'simplified' represents simplified Chinese and 'traditional' represents traditional Chinese. Default value is 'simplified'.
    • theta controls the size of search space for the candidate phrases. Default value is 1.
import dimsim

candidates = dimsim.get_candidates("大侠", mode="simplified", theta=1)
['打下', '大虾', '大侠']

candidates = dimsim.get_candidates("粉丝", mode="traditional", theta=1)
['門市', '分時', '焚屍', '粉飾', '粉絲']

Deploy from Quay

To run the docker image, which automatically starts the model serving API, run:

$ docker run -it -p 5000:5000 quay.io/codait/max-chinese-phonetic-similarity-estimator

This will pull a pre-built image from the Quay.io container registry (or use an existing image if already cached locally) and run it. If you'd rather checkout and build the model locally you can follow the run locally steps below.

Deploy on Red Hat OpenShift

You can deploy the model-serving microservice on Red Hat OpenShift by following the instructions for the OpenShift web console or the OpenShift Container Platform CLI in this tutorial, specifying quay.io/codait/max-chinese-phonetic-similarity-estimator as the image name.

Deploy on Kubernetes

You can also deploy the model on Kubernetes using the latest docker image on Quay.

On your Kubernetes cluster, run the following commands:

$ kubectl apply -f https://github.com/IBM/MAX-Chinese-Phonetic-Similarity-Estimator/raw/master/max-chinese-phonetic-similarity-estimator.yaml

The model will be available internally at port 5000, but can also be accessed externally through the NodePort.

A more elaborate tutorial on how to deploy this MAX model to production on IBM Cloud can be found here.

Run Locally

  1. Build the Model
  2. Deploy the Model
  3. Use the Model
  4. Development
  5. Cleanup

1. Build the Model

Clone this repository locally. In a terminal, run the following command:

$ git clone https://github.com/IBM/MAX-Chinese-Phonetic-Similarity-Estimator.git

Change directory into the repository base folder:

$ cd MAX-Chinese-Phonetic-Similarity-Estimator

To build the docker image locally, run:

$ docker build -t max-chinese-phonetic-similarity-estimator .

All required model assets will be downloaded during the build process. Note that currently this docker image is CPU only (we will add support for GPU images later).

2. Deploy the Model

To run the docker image, which automatically starts the model serving API, run:

$ docker run -it -p 5000:5000 max-chinese-phonetic-similarity-estimator

3. Use the Model

The API server automatically generates an interactive Swagger documentation page. Go to http://localhost:5000 to load it. From there you can explore the API and also create test requests.

Use the model/predict endpoint to pass the input to the model. The input has one required field - first_word. The other inputs are optional. Providing a second_word would return distance between the first_word and second_word, in addition to the closest candidate words to both of them.

Other optional arguments are: theta - indicates the distance threshold for candidate words and controls the size of search space for the candidate words. Higher theta returns more candidate words. Default is 1. mode - indicates the output type of the Chinese characters - traditional or simplified. Default is simplified.

INSERT SWAGGER UI SCREENSHOT HERE

You can also test it on the command line, for example:

$ curl -X POST "http://localhost:5000/model/predict?first_word=%E5%A4%A7%E8%99%BE&second_word=%E5%A4%A7%E4%BE%A0&mode=simplified&theta=1" -H  "accept: application/json"

You should see a JSON response like that below:

{
  "status": "ok",
  "predictions": [
    {
      "distance": "0.0002380952380952381",
      "candidates": [
        [
          "打下",
          "大虾",
          "大侠"
        ],
        [
          "打下",
          "大虾",
          "大侠"
        ]
      ]
    }
  ]
}

This means the given words had a distance of 0.00024 between them, and they can be inferred to be very close. The candidate words contains list of candidate words.

4. Development

To run the Flask API app in debug mode, edit config.py to set DEBUG = True under the application settings. You will then need to rebuild the docker image (see step 1).

5. Cleanup

To stop the Docker container, type CTRL + C in your terminal.

Resources and Contributions

If you are interested in contributing to the Model Asset Exchange project or have any queries, please follow the instructions here.

max-chinese-phonetic-similarity-estimator's People

Contributors

bdwyer2 avatar imgbot[bot] avatar kmh4321 avatar ptitzler avatar splovyt avatar stevemar avatar yil532 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

max-chinese-phonetic-similarity-estimator's Issues

/model/predict error message requires clarification

Posting an invalid character sequence, like so

curl -X POST "http://0.0.0.0:5000/model/predict?first_word=abc&mode=traditional&theta=999" -H "accept: application/json" 

yields the following response:

{
  "message": "Invalid input to Pinyin converter, please check!"
}

The message text should be improved to state something more user friendly like "The specified characters are not a valid utf-8 encoded Chinese word.". The current message exposes internals that should not be of relevance to the microservice consumer.

/model/predict error response format is not consistent

I tried several error scenarios and noticed that the JSON response is inconsistent, which makes it more difficult to programmatically evaluate the error condition.

invalid theta (ignoring the message text issue for now)

curl -X POST "http://0.0.0.0:5000/model/predict?first_word=abc&mode=traditional&theta=999a" -H "accept: application/json"

{"errors": {"theta": "Distance threshold for number of candidate words to return. A higher theta returns more candidate words invalid literal for int() with base 10: '999a'"}, "message": "Input payload validation failed"}

invalid mode

curl -X POST "http://0.0.0.0:5000/model/predict?first_word=abc&mode=traditiona&theta=999" -H "accept: application/json"

{"errors": {"mode": "Chinese: simplified or traditional. The value 'traditiona' is not a valid choice for 'mode'."}, "message": "Input payload validation failed"}

invalid character sequence (note there is no errors property that identifies which payload is invalid.) - (first_word)

curl -X POST "http://0.0.0.0:5000/model/predict?first_word=abc&mode=traditional&theta=999" -H "accept: application/json"

{"message": "Invalid input to Pinyin converter, please check!"}

This is a problem because in the following scenario the caller would not know which of the words is invalid:

curl -X POST "http://0.0.0.0:5000/model/predict?first_word=abc&second_word=%E5%A4%A7%E4%BE%A0&mode=traditional&theta=999" -H "accept: application/json"

{"message": "Invalid input to Pinyin converter, please check!"}

The error output is correct/as expected for the following scenario:

curl -X POST "http://0.0.0.0:5000/model/predict?second_word=%E5%A4%A7%E4%BE%A0&mode=traditional&theta=999" -H "accept: application/json"

{"errors": {"first_word": "utf-8 encoded Chinese word. Missing required parameter in the JSON body or the post body or the query string"}, "message": "Input payload validation failed"}

README improvements

  1. Prefix all command line inputs with $, e.g.
 $ pip install dimsim
  1. pip install: is there really a need to clone the repo? pip can install packages from GitHub directly ...
  2. Formatting: "Return top-k phonetically similar phrases of a given Chinese phrase. Two parameters:" - the following bulleted list requires indentation

/model/predict results data structure is defined as list(list(string))

The candidates property value is defined as a list of list(s) of str:

{
  "status": "ok",
  "predictions": [
    {
      "distance": "0",
      "candidates": [
        [
          "打下",
          "大蝦",
          "大俠"
        ]
      ]
    }
  ]
}

Under which conditions would the list include more than one list element, like so?

[
        [
          "打下",
          "大蝦",
          "大俠"
        ],
        [
          "打下2",
          "大蝦2",
          "大俠2"
        ]
]

If there's no known scenario, the response should return

     ...
      "candidates": [
          "打下",
          "大蝦",
          "大俠"
      ]
     ...

Error message formatting issue

Note A higher theta returns more candidate words invalid literal for int() with base 10: 'a'"

curl -X POST "http://0.0.0.0:5000/model/predict?first_word=%E6%89%93%E4%B8%8B&mode=traditional&theta=a" -H "accept: application/json"
{"errors": {"theta": "Distance threshold for number of candidate words to return. A higher theta returns more candidate words invalid literal for int() with base 10: 'a'"}, "message": "Input payload validation failed"}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.