Text
Make predictions on passages of text

Make text predictions via URL

You can make predictions on passages of text hosted on the web
Python
PHP
Java
NodeJS
cURL
Javascript (REST)
1
# Insert here the initialization code as outlined on this page:
2
# https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
3
4
post_model_outputs_response = stub.PostModelOutputs(
5
service_pb2.PostModelOutputsRequest(
6
user_app_id=userDataObject, # The userDataObject is created in the overview and is required when using a PAT
7
model_id="{THE_MODEL_ID}",
8
version_id="{THE_MODEL_VERSION_ID}", # This is optional. Defaults to the latest model version.
9
inputs=[
10
resources_pb2.Input(
11
data=resources_pb2.Data(
12
text=resources_pb2.Text(
13
base64=file_bytes
14
)
15
)
16
)
17
]
18
),
19
metadata=metadata
20
)
21
if post_model_outputs_response.status.code != status_code_pb2.SUCCESS:
22
print("There was an error with your request!")
23
print("\tCode: {}".format(post_model_outputs_response.outputs[0].status.code))
24
print("\tDescription: {}".format(post_model_outputs_response.outputs[0].status.description))
25
print("\tDetails: {}".format(respopost_model_outputs_responsense.outputs[0].status.details))
26
raise Exception("Post model outputs failed, status: " + post_model_outputs_response.status.description)
27
28
# Since we have one input, one output will exist here.
29
output = post_model_outputs_response.outputs[0]
30
31
print("Predicted concepts:")
32
for concept in output.data.concepts:
33
print("%s %.2f" % (concept.name, concept.value))
Copied!
1
<?php
2
# Insert here the initialization code as outlined on this page:
3
# https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
4
5
///////////////////////////////////////////////////////////////////////////////
6
// Specifying the Request Data
7
///////////////////////////////////////////////////////////////////////////////
8
//
9
// In the Clarifai platform a text is defined by a special Text object.
10
// There are several ways in which a Text object can be populated including
11
// by url and raw string.
12
//
13
$text = new Text([
14
'url' => 'https://samples.clarifai.com/negative_sentence_12.txt'
15
]);
16
17
//
18
// After an Text object is created, a Data object is constructed around it.
19
// The Data object offers a container that contains additional text independent
20
// metadata. In this particular use case, no other metadata is needed to be
21
// specified.
22
//
23
$data = new Data([
24
'text' => $text
25
]);
26
27
//
28
// The Data object is then wrapped in an Input object in order to meet the
29
// API specification. Additional fields are available to populate in the Input
30
// object, but for the purposes of this example we can send in just the
31
// Data object.
32
//
33
$input = new Input([
34
'data' => $data
35
]);
36
37
///////////////////////////////////////////////////////////////////////////////
38
// Creating the request object
39
///////////////////////////////////////////////////////////////////////////////
40
//
41
// Finally, the request object itself is created. This object carries the request
42
// along with the request status and other metadata related to the request itself.
43
// In this example we populate:
44
// - the `user_app_id` field with the UserAppIDSet constructed above
45
// - the `model_id` field with the ID of the model we are referencing
46
// - the `inputs` field with an array of input objects constructed above
47
//
48
$request = new PostModelOutputsRequest([
49
'user_app_id' => $userDataObject, // This is defined above
50
'model_id' => 'aaa03c23b3724a16a56b629203edc62c', // This is the ID of the publicly available General model.
51
'inputs' => [$input]
52
]);
53
54
///////////////////////////////////////////////////////////////////////////////
55
// Making the RPC call
56
///////////////////////////////////////////////////////////////////////////////
57
//
58
// Once the request object is constructed, we can call the actual request to the
59
// Clarifai platform. This uses the opened gRPC client channel to communicate the
60
// request and then wait for the response.
61
//
62
[$response, $status] = $client->PostModelOutputs(
63
$request,
64
$metadata
65
)->wait();
66
67
///////////////////////////////////////////////////////////////////////////////
68
// Handling the Response
69
///////////////////////////////////////////////////////////////////////////////
70
//
71
// The response is returned and the first thing we do is check the status of it.
72
// A successful response will have a status code of 0, otherwise there is some
73
// reported error.
74
//
75
if ($status->code !== 0) throw new Exception("Error: {$status->details}");
76
77
//
78
// In addition to the RPC response status, there is a Clarifai API status that
79
// reports if the operationo was a success or failure (not just that the commuunication)
80
// was successful.
81
//
82
if ($response->getStatus()->getCode() != StatusCode::SUCCESS) {
83
throw new Exception("Failure response: " . $response->getStatus()->getDescription() . " " .
84
$response->getStatus()->getDetails());
85
}
86
87
//
88
// The output of a successful call can be used in many ways. In this example,
89
// we loop through all of the predicted concepts and print them out along with
90
// their numerical prediction value (confidence).
91
//
92
echo "Predicted concepts:\n";
93
foreach ($response->getOutputs()[0]->getData()->getConcepts() as $concept) {
94
echo $concept->getName() . ": " . number_format($concept->getValue(), 2) . "\n";
95
}
96
?>
Copied!
1
import com.clarifai.grpc.api.*;
2
import com.clarifai.grpc.api.status.*;
3
4
// Insert here the initialization code as outlined on this page:
5
// https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
6
7
MultiOutputResponse postModelOutputsResponse = stub.postModelOutputs(
8
PostModelOutputsRequest.newBuilder()
9
.setModelId("{THE_MODEL_ID}")
10
.setVersionId("{THE_MODEL_VERSION_ID") // This is optional. Defaults to the latest model version.
11
.addInputs(
12
Input.newBuilder().setData(
13
Data.newBuilder().setText(
14
Text.newBuilder().setUrl("https://samples.clarifai.com/negative_sentence_12.txt")
15
)
16
)
17
)
18
.build()
19
);
20
21
if (postModelOutputsResponse.getStatus().getCode() != StatusCode.SUCCESS) {
22
throw new RuntimeException("Post model outputs failed, status: " + postModelOutputsResponse.getStatus());
23
}
24
25
// Since we have one input, one output will exist here.
26
Output output = postModelOutputsResponse.getOutputs(0);
27
28
System.out.println("Predicted concepts:");
29
for (Concept concept : output.getData().getConceptsList()) {
30
System.out.printf("%s %.2f%n", concept.getName(), concept.getValue());
31
}
Copied!
1
// Insert here the initialization code as outlined on this page:
2
// https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
3
4
stub.PostModelOutputs(
5
{
6
model_id: "{THE_MODEL_ID}",
7
version_id: "{THE_MODEL_VERSION_ID}", // This is optional. Defaults to the latest model version.
8
inputs: [
9
{data: {text: {url: "https://samples.clarifai.com/negative_sentence_12.txt"}}}
10
]
11
},
12
metadata,
13
(err, response) => {
14
if (err) {
15
throw new Error(err);
16
}
17
18
if (response.status.code !== 10000) {
19
throw new Error("Post model outputs failed, status: " + response.status.description);
20
}
21
22
// Since we have one input, one output will exist here.
23
const output = response.outputs[0];
24
25
console.log("Predicted concepts:");
26
for (const concept of output.data.concepts) {
27
console.log(concept.name + " " + concept.value);
28
}
29
}
30
);
Copied!
1
curl -X POST
2
-H 'Authorization: Key YOUR_API_KEY'
3
-H "Content-Type: application/json"
4
-d '
5
{
6
"inputs": [
7
{
8
"data": {
9
"text": {
10
"url": "https://samples.clarifai.com/negative_sentence_12.txt"
11
}
12
}
13
}
14
]
15
}'
16
https://api.clarifai.com/v2/models/{THE_MODEL_ID}/versions/{THE_MODEL_VERSION_ID}/outputs
Copied!
1
const raw = JSON.stringify({
2
"user_app_id": {
3
"user_id": "{YOUR_USER_ID}",
4
"app_id": "{YOUR_APP_ID}"
5
},
6
"inputs": [
7
{
8
"data": {
9
"text": {
10
"url": "https://samples.clarifai.com/negative_sentence_12.txt"
11
}
12
}
13
}
14
]
15
});
16
17
const requestOptions = {
18
method: 'POST',
19
headers: {
20
'Accept': 'application/json',
21
'Authorization': 'Key {YOUR_PERSONAL_TOKEN}'
22
},
23
body: raw
24
};
25
26
// NOTE: MODEL_VERSION_ID is optional, you can also call prediction with the MODEL_ID only
27
// https://api.clarifai.com/v2/models/{YOUR_MODEL_ID}/outputs
28
// this will default to the latest version_id
29
30
fetch("https://api.clarifai.com/v2/models/{YOUR_MODEL_ID}/versions/{MODEL_VERSION_ID}/outputs", requestOptions)
31
.then(response => response.text())
32
.then(result => console.log(result))
33
.catch(error => console.log('error', error));
Copied!

Make text predictions on local text files

Make predictions based on local text files.
Python
Java
NodeJS
cURL
Javascript (REST)
1
# Insert here the initialization code as outlined on this page:
2
# https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
3
4
with open("{YOUR_IMAGE_FILE_LOCATION}", "rb") as f:
5
file_bytes = f.read()
6
7
post_model_outputs_response = stub.PostModelOutputs(
8
service_pb2.PostModelOutputsRequest(
9
user_app_id=userDataObject, # The userDataObject is created in the overview and is required when using a PAT
10
model_id="{THE_MODEL_ID}",
11
version_id="{THE_MODEL_VERSION_ID}", # This is optional. Defaults to the latest model version.
12
inputs=[
13
resources_pb2.Input(
14
data=resources_pb2.Data(
15
text=resources_pb2.Text(
16
raw="Butchart Gardens contains over 900 varieties of plants."
17
)
18
)
19
)
20
]
21
),
22
metadata=metadata
23
)
24
25
if post_model_outputs_response.status.code != status_code_pb2.SUCCESS:
26
print("There was an error with your request!")
27
print("\tCode: {}".format(post_model_outputs_response.outputs[0].status.code))
28
print("\tDescription: {}".format(post_model_outputs_response.outputs[0].status.description))
29
print("\tDetails: {}".format(respopost_model_outputs_responsense.outputs[0].status.details))
30
raise Exception("Post model outputs failed, status: " + post_model_outputs_response.status.description)
31
32
# Since we have one input, one output will exist here.
33
output = post_model_outputs_response.outputs[0]
34
35
print("Predicted concepts:")
36
for concept in output.data.concepts:
37
print("%s %.2f" % (concept.name, concept.value))
Copied!
1
import com.clarifai.grpc.api.*;
2
import com.clarifai.grpc.api.status.*;
3
import com.google.protobuf.ByteString;
4
import java.io.File;
5
import java.nio.file.Files;
6
7
// Insert here the initialization code as outlined on this page:
8
// https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
9
10
MultiOutputResponse postModelOutputsResponse = stub.postModelOutputs(
11
PostModelOutputsRequest.newBuilder()
12
.setModelId("{THE_MODEL_ID}")
13
.setVersionId("{THE_MODEL_VERSION_ID") // This is optional. Defaults to the latest model version.
14
.addInputs(
15
Input.newBuilder().setData(
16
Data.newBuilder().setText(
17
Text.newBuilder()
18
.setRaw(ByteString.copyFrom(Files.readAllBytes(
19
new File("{YOUR_IMAGE_FILE_LOCATION}").toPath()
20
)))
21
)
22
)
23
)
24
.build()
25
);
26
27
if (postModelOutputsResponse.getStatus().getCode() != StatusCode.SUCCESS) {
28
throw new RuntimeException("Post model outputs failed, status: " + postModelOutputsResponse.getStatus());
29
}
30
31
// Since we have one input, one output will exist here.
32
Output output = postModelOutputsResponse.getOutputs(0);
33
34
System.out.println("Predicted concepts:");
35
for (Concept concept : output.getData().getConceptsList()) {
36
System.out.printf("%s %.2f%n", concept.getName(), concept.getValue());
37
}
Copied!
1
// Insert here the initialization code as outlined on this page:
2
// https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions
3
4
const fs = require("fs");
5
const imageBytes = fs.readFileSync("{YOUR_IMAGE_FILE_LOCATION}");
6
7
stub.PostModelOutputs(
8
{
9
model_id: "{THE_MODEL_ID}",
10
version_id: "{THE_MODEL_VERSION_ID}", // This is optional. Defaults to the latest model version.
11
inputs: [
12
{data: {text: {raw: textFile}}}
13
]
14
},
15
metadata,
16
(err, response) => {
17
if (err) {
18
throw new Error(err);
19
}
20
21
if (response.status.code !== 10000) {
22
throw new Error("Post model outputs failed, status: " + response.status.description);
23
}
24
25
// Since we have one input, one output will exist here.
26
const output = response.outputs[0];
27
28
console.log("Predicted concepts:");
29
for (const concept of output.data.concepts) {
30
console.log(concept.name + " " + concept.value);
31
}
32
}
33
);
Copied!
1
// Smaller files (195 KB or less)
2
3
curl -X POST \
4
-H "Authorization: Key YOUR_API_KEY" \
5
-H "Content-Type: application/json" \
6
-d '
7
{
8
"inputs": [
9
{
10
"data": {
11
"text": {
12
"raw": "'"$(raw /home/user/image.jpeg)"'"
13
}
14
}
15
}
16
]
17
}'\
18
https://api.clarifai.com/v2/models/{THE_MODEL_ID}/outputs
Copied!
1
const raw = JSON.stringify({
2
"user_app_id": {
3
"user_id": "{YOUR_USER_ID}",
4
"app_id": "{YOUR_APP_ID}"
5
},
6
"inputs": [
7
{
8
"data": {
9
"text": {
10
"raw": "{YOUR_RAW_TEXT}"
11
}
12
}
13
}
14
]
15
});
16
17
const requestOptions = {
18
method: 'POST',
19
headers: {
20
'Accept': 'application/json',
21
'Authorization': 'Key {YOUR_PERSONAL_TOKEN}'
22
},
23
body: raw
24
};
25
26
// NOTE: MODEL_VERSION_ID is optional, you can also call prediction with the MODEL_ID only
27
// https://api.clarifai.com/v2/models/{YOUR_MODEL_ID}/outputs
28
// this will default to the latest version_id
29
30
fetch("https://api.clarifai.com/v2/models/{YOUR_MODEL_ID}/versions/{MODEL_VERSION_ID}/outputs", requestOptions)
31
.then(response => response.text())
32
.then(result => console.log(result))
33
.catch(error => console.log('error', error));
Copied!
Last modified 13m ago