Model usage tutorials

更新时间:
复制 MD 格式

The API, model, and SDK interfaces of the NLP Self-Learning Platform support Natural Language Processing (NLP) capabilities for various scenarios, such as product review parsing and telesales in the E-commerce industry, and applications for general industries. For information about how to call these interfaces, see the following sections.

Use the NLP Self-Learning Platform SDK

You can import the SDK for the NLP Self-Learning Platform. For more information, see the latest SDK version.

For an example of an SDK call, see SDK examples.

<dependency>    
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-core</artifactId>
  <version>3.5.0</version>
</dependency>
<dependency>
  <groupId>com.aliyun</groupId>
  <artifactId>aliyun-java-sdk-nlp-automl</artifactId>
  <version>0.0.8</version>
</dependency>

Model invocation API examples

For API documentation, see RunPreTrainService.

For API testing, see OpenAPI Explorer.

Long text invocation API examples

You can use the asynchronous prediction API to asynchronously invoke a model for prediction. This API supports offline invocation for long text.

For an example of how to use the asynchronous prediction API, see Create an asynchronous API.

To retrieve asynchronous prediction results, see Get asynchronous results.

Configure access credentials using environment variables

  1. Note:

    1. An AccessKey for an Alibaba Cloud account has permissions to access all APIs. This creates a high security risk. We recommend that you create and use a Resource Access Management (RAM) user for API access or daily O&M. To create a RAM user, you can log on to the RAM console.

    2. To prevent key leaks, do not save your AccessKey ID and AccessKey secret in your code. Instead, configure environment variables to store and access them.

  2. Configuration for Linux and macOS systems

    export NLP_AK_ENV=<access_key_id>
    export NLP_SK_ENV=<access_key_secret>

    Replace <access_key_id> with your AccessKey ID and <access_key_secret> with your AccessKey secret. For more information about how to obtain an AccessKey ID and an AccessKey secret, see Step 2: Obtain the AccessKey of an account.

  3. Configuring Windows

    1. Create an environment variable file. Add the NLP_AK_ENV and NLP_SK_ENV environment variables. Then, set their values to your AccessKey ID and AccessKey secret.

    2. Restart Windows.

Product review parsing service

For an example of how to use the product review parsing service, see Product review parsing service example.

Hierarchical news classification service

For an example of how to use the hierarchical news classification service, see Hierarchical news classification service example.

Resume parsing (Chinese)

For an example of how to use the resume parsing service, see Resume parsing service example.

Resume parsing (English)

For an example of how to use the resume parsing service (English), see Resume parsing service (English) example.

Legal document extraction

For an example of how to use the legal document extraction service, see Legal document extraction example.

Conviction and sentencing prediction service

The following example shows how to use the conviction and sentencing prediction service. The current version supports predictions for criminal cases only.

Note

To call the criminal conviction and sentencing service, set the ServiceName parameter to convictionSentencingService.

Java code example

/**
 * An AccessKey for an Alibaba Cloud account has permissions to access all APIs. This is a high security threat. 
 * Create and use a Resource Access Management (RAM) user for API access or daily O&M. To create a RAM user, log on to the RAM console.
 * This example shows how to save the AccessKey ID and AccessKey secret in environment variables. You can also save them in a configuration file as needed.
 * To prevent key leaks, do not save your AccessKey ID and AccessKey secret in your code.
 */
String accessKeyId = System.getenv("NLP_AK_ENV");
String accessKeySecret = System.getenv("NLP_SK_ENV");
DefaultProfile defaultProfile = DefaultProfile.getProfile("cn-hangzhou",accessKeyId,accessKeySecret);
IAcsClient client = new DefaultAcsClient(defaultProfile);

Map<String, Object> input = new HashMap();
input.put("reqId","reqId");
input.put("text","Case description");

RunPreTrainServiceRequest request = new RunPreTrainServiceRequest();
request.setServiceName("convictionSentencingService");
request.setPredictContent(JSON.toJSONString(input));
RunPreTrainServiceResponse response = client.getAcsResponse(request);
System.out.println(response.getPredictResult());

Python code example

# Install dependencies
pip install aliyun-python-sdk-core
pip install aliyun-python-sdk-nlp-automl
# -*- coding: utf8 -*-
import json
import os

from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdknlp_automl.request.v20191111 import RunPreTrainServiceRequest

/**
 * An AccessKey for an Alibaba Cloud account has permissions to access all APIs. This is a high security threat. 
 * Create and use a Resource Access Management (RAM) user for API access or daily O&M. To create a RAM user, log on to the RAM console.
 * This example shows how to save the AccessKey ID and AccessKey secret in environment variables. You can also save them in a configuration file as needed.
 * To prevent key leaks, do not save your AccessKey ID and AccessKey secret in your code.
 */
access_key_id = os.environ['NLP_AK_ENV']
access_key_secret = os.environ['NLP_SK_ENV']

# Initialize AcsClient instance
client = AcsClient(
  access_key_id,
  access_key_secret,
  "cn-hangzhou"
);

reqid = 'reqid'
text = 'Case description'
input_params = {
 "reqId": reqid,
 "text": text
}

# Initialize a request and set parameters
request = RunPreTrainServiceRequest.RunPreTrainServiceRequest()
request.set_ServiceName('convictionSentencingService')
request.set_PredictContent(json.dumps(input_params))

# Print response
response = client.do_action_with_exception(request)
resp_obj = json.loads(response)
predict_result = json.loads(resp_obj['PredictResult'])
print(json.dumps(predict_result['data']))

PredictContent example

The PredictContent parameter is a JSON string. The following example shows the content of this string.

{
 "reqId": "123445aad",
 "text": "The prosecution alleges that drug user Tang Mou, at approximately 15:00 on March 8, 2013, contacted another man (handled in a separate case) by phone and arranged a drug transaction in Room 303 of the Hanming Hotel on Jinling North Road, Nansha District, Guangzhou. At approximately 17:00 on the same day, the defendant Yin Mou, instructed by the aforementioned man, went to the location and sold a small packet of transparent crystals to drug user Wen Moupeng for CNY 300. Yin Mou was then caught in the act by public security officers. The officers also seized two strips of tin foil from the defendant Yin Mou. After being brought to justice, the defendant Yin Mou truthfully confessed his criminal facts to the public security organs. Upon examination, the seized small packet of transparent crystals had a net weight of 0.4 grams and tested positive for methamphetamine. The public security organs tested the defendant Yin Mou for methamphetamine, and the result was positive. The prosecution recommends that this court sentence the defendant Yin Mou to a term of imprisonment ranging from XX to one year and impose a fine."
}

Request parameters

Parameter

Type

Description

reqId

String

Request ID

text

String

Case description

PredictResult example

PredictResult is a JSON string that you must deserialize and parse. For the structure, see the following example.

{
 "reqId": "123445aad",
 "penalty": "7-month fixed-term imprisonment", 
 "articles": [{
 "lawText": "Article 347 [Crime of Smuggling, Trafficking, Transporting, and Manufacturing Drugs] Smuggling, trafficking, transporting, or manufacturing drugs, regardless of the quantity, shall be investigated for criminal responsibility and punished. Whoever smuggles, traffics, transports, or manufactures drugs under any of the following circumstances shall be sentenced to fixed-term imprisonment of not less than 15 years, life imprisonment, or death, and shall also have their property confiscated: (1) Smuggling, trafficking, transporting, or manufacturing one thousand grams or more of opium, fifty grams or more of heroin or methamphetamine, or a large quantity of other drugs; (2) Being a ringleader of a drug smuggling, trafficking, transporting, or manufacturing group; (3) Using armed cover to smuggle, traffic, transport, or manufacture drugs; (4) Using violence to resist inspection, detention, or arrest, with serious circumstances; (5) Participating in organized international drug trafficking activities. Whoever smuggles, traffics, transports, or manufactures two hundred grams or more but less than one thousand grams of opium, ten grams or more but less than fifty grams of heroin or methamphetamine, or a large quantity of other drugs shall be sentenced to fixed-term imprisonment of not less than seven years and shall also be fined. Whoever smuggles, traffics, transports, or manufactures less than two hundred grams of opium, less than ten grams of heroin or methamphetamine, or a small quantity of other drugs shall be sentenced to fixed-term imprisonment of not more than three years, criminal detention, or public surveillance, and shall also be fined; if the circumstances are serious, they shall be sentenced to fixed-term imprisonment of not less than three years and not more than seven years, and shall also be fined. If a unit commits a crime specified in the second, third, or fourth paragraph, the unit shall be fined, and its directly responsible supervisors and other directly responsible personnel shall be punished in accordance with the provisions of the respective paragraphs. Whoever uses or instigates a minor to smuggle, traffic, transport, or manufacture drugs, or sells drugs to a minor, shall be given a heavier punishment. For multiple instances of smuggling, trafficking, transporting, or manufacturing drugs that have not been dealt with, the quantity of drugs shall be calculated cumulatively.",
 "provisionName": "Article 347 of the Criminal Law"
 }], // Predicted legal articles output
 "accusation": ["Smuggling, trafficking, transporting, and manufacturing drugs"], 
 "features": [{
 "span": [207, 212],
 "content": "Methamphetamine",
 "type": "Conviction factor",
 "name": "Drug type"
 }, {
 "span": [40, 122],
 "content": "contacted by phone and arranged a drug transaction in Room 303 of the Hanming Hotel on Jinling North Road, Nansha District, Guangzhou. At approximately 17:00 on the same day, the defendant Yin Mou, instructed by the aforementioned man, went to the location and sold a small packet of transparent crystals for CNY 300 to",
 "type": "Conviction factor",
 "name": "Trafficking drugs using information networks"
 }, {
 "span": [151, 212],
 "content": "seized two strips of tin foil from his person. After being brought to justice, the defendant Yin Mou truthfully confessed his criminal facts to the public security organs. Upon examination, the seized small packet of transparent crystals had a net weight of 0.4 grams and tested positive for methamphetamine",
 "type": "Conviction factor",
 "name": "Transporting drugs by carrying them"
 }, {
 "span": [151, 212],
 "content": "seized two strips of tin foil from his person. After being brought to justice, the defendant Yin Mou truthfully confessed his criminal facts to the public security organs. Upon examination, the seized small packet of transparent crystals had a net weight of 0.4 grams and tested positive for methamphetamine",
 "type": "Conviction factor",
 "name": "Drugs seized from the residence|vehicle of a drug trafficker"
 }, {
 "span": [207, 212],
 "content": "Methamphetamine",
 "type": "Sentencing factor",
 "name": "Drug type"
 }, {
 "span": [198, 204],
 "content": "Net weight 0.4 grams",
 "type": "Sentencing factor",
 "name": "Drug weight in grams"
 }, {
 "span": [198, 204],
 "content": "Net weight 0.4 grams",
 "type": "Sentencing factor",
 "name": "Drug weight in grams"
 }, {
 "span": [199, 204],
 "content": "Weight 0.4 grams",
 "type": "Sentencing factor",
 "name": "Drug weight in grams"
 }]
}

Response parameters

Parameter

Type

Description

reqId

String

Request ID

penalty

String

Predicted sentence

articles

List

Recommended legal articles

articles.lawText

String

Content of the legal article

articles.provisionName

String

Name of the legal article

accusation

List

Predicted accusation

features

List

Set of factors

features.span

[start int, end int]

The starting position of the element in the description.

features.content

String

The text content of the factor in the case description.

features.type

String

Factor type

features.name

String

Factor name