sean-luis/ibm-php-sdk

IBM Cloud SDK for PHP

v0.1.0 2023-04-17 18:03 UTC

This package is auto-updated.

Last update: 2024-09-14 03:00:34 UTC


README

IBM Cloud SDK for PHP 是一个库,它提供了从用 PHP 编写的应用程序与 IBM Cloud 服务交互的简单方法。SDK 当前支持 IBM NLU 和 IBM COS。

需求

确保服务器环境中启用了所需的 PHP 扩展非常重要。SDK 还需要访问它交互的 IBM Cloud 服务,例如 IBM Cloud Object Storage 和 IBM Watson 自然语言理解。

请注意,Composer 包管理器将在安装 SDK 时自动安装所有必需的依赖项及其依赖项。

安装

要安装 SDK,您可以使用 Composer。如果您尚未在系统上安装 Composer,请按照https://composer.php.ac.cn 上的说明进行安装。

在您的终端中运行以下命令以安装 SDK

composer require sean-luis/ibm-php-sdk

设置

在使用 SDK 之前,您必须设置您的 IBM Cloud 凭据。您可以通过在项目的根目录中创建一个包含以下键的 YAML 文件或 ENV 文件来完成此操作

ibm:
    api_key: "<IBM_CLOUD_API_KEY>"
    url: "<IBM_CLOUD_URL>"

nlu:
    api_key: "<IBM_NLU_API_KEY>"
    url: "<IBM_NLU_URL>"
    version: "<IBM_NLU_VERSION>"

cos:
    api_key: "<IBM_COS_API_KEY>"
    url: "<IBM_COS_URL>"
    region: "<IBM_COS_REGION>"
    bucket: "<IBM_COS_BUCKET>"
    instance_id: "<IBM_COS_INSTANCE_ID>"

tts:
    api_key: "<IBM_TTS_API_KEY>"
    url: "<IBM_TTS_URL>"
    version: "<IBM_TTS_VERSION>"
    
stt:
    api_key: "<IBM_STT_API_KEY>"
    url: "<IBM_STT_URL>"
    version: "<IBM_STT_VERSION>"

或者您可以使用 ENV

IBM_NLU_API_KEY=<IBM_NLU_API_KEY>
IBM_NLU_URL=<IBM_NLU_URL>
IBM_NLU_VERSION=<IBM_NLU_VERSION>

IBM_COS_API_KEY=<IBM_COS_API_KEY>
IBM_COS_URL=<IBM_COS_URL>
IBM_COS_REGION=<IBM_COS_REGION>
IBM_COS_BUCKET=<IBM_COS_BUCKET>
IBM_COS_REFERENCE_SERCICE_ID=<IBM_COS_INSTANCE_ID>

IBM_TTS_API_KEY=<IBM_TTS_API_KEY>
IBM_TTS_URL=<IBM_TTS_URL>
IBM_TTS_VERSION=<IBM_TTS_VERSION>

IBM_STT_API_KEY=<IBM_STT_API_KEY>
IBM_STT_URL=<IBM_STT_URL>
IBM_STT_VERSION=<IBM_STT_VERSION>

IBM_CLOUD_API_KEY=<IBM_CLOUD_APIKEY>
IBM_CLOUD_URL=<IBM_CLOUD_URL>

在每个情况下,用您自己的 IBM Cloud 凭据替换您认为合适的变量。

实现

自然语言理解

NaturalLanguageUnderstanding 类提供了一种简单的方法与 IBM NLU 交互。

use IBMCloud\Helpers\Config;
use IBMCloud\NLU\NaturalLanguageUnderstanding;

// Load IBM Cloud credentials from a YAML file
$credentials = Config::getCredentials('ibm-cloud.yaml');

$authenticator = new IamAuthenticator($credentials['ibm']['api_key']);

$token = $authenticator->getAccessToken();

// Create an instance of NaturalLanguageUnderstanding
$nlu = new NaturalLanguageUnderstanding($token, $url, $version);

// Define the text to analyze
$text = "I am very happy with the result of today's game.";

// Define your feature options for text analysis
$options = [
    'entities' => [
        'sentiment' => true,
        'emotion' => true,
        'limit' => 10,
    ],
    'keywords' => [
        'sentiment' => true,
        'emotion' => true,
        'limit' => 10,
    ],
    'sentiment' => [
        'document' => true,
    ],
    'categories' => [
        'limit' => 5,
    ],
];

// Instantiate NLUFeaturesParams with custom options
$nluFeaturesParams = new NLUFeaturesParams($options);

// Make the request to IBM NLU
$response = $nlu->analyze($text, $features);

// Print the results
foreach ($response['keywords'] as $keyword) {
    echo $keyword['text'].' => Sentiment: '.$keyword['sentiment']['score'].', Emotion: '.$keyword['emotion']['sadness']
    .'<br>';
}

创建 NaturalLanguageUnderstanding 类的新实例。

new NaturalLanguageUnderstanding($token, $url, $version)

参数

$token (string): The IBM Cloud response token.
$url (string): IBM NLU URL.
$version (string): The version of IBM NLU.

分析

使用 IBM NLU 解析提供的文本并返回结果。

$nlu->analyze($text, $features)

参数

$text (string): The text to analyze.
$features (array): The characteristics that you want to analyze. See the IBM NLU documentation for a complete list of available features.

响应: 包含分析结果的数组。

分析功能

代表可以由自然语言理解分析的特性。

new NLUFeaturesParams($options)

云对象存储

CloudObjectStorage 类提供了一种简单的方法与 IBM COS 交互。

use IBMCloud\Helpers\Config;
use IBMCloud\COS\CloudObjectStorage;

// Load IBM Cloud credentials from a YAML file
$credentials = Config::getCredentials('ibm-cloud.yaml');

// Sign in and get IBM Cloud token
$authenticator = new IamAuthenticator($credentials['ibm']['api_key']);

$token = $authenticator->getAccessToken();

// Create an instance of CloudObjectStorage
$this->cos = new CloudObjectStorage(
    $token,
    $credentials['cos']['instance_id'],
    $credentials['cos']['url']
);        

// Upload a file to IBM COS
$objectName = 'test.txt';
$body = 'This is a test file.';
$response = $cos->putObject($credentials['cos']['bucket'], $objectName, $body);

// Download a file from IBM COS
$fileName = 'test.txt';
$response = $cos->getObject($bucket, $fileName);

// Print the content of the downloaded file
echo $response;

创建 CloudObjectStorage 类的新实例。

new CloudObjectStorage($token, $serviceInstanceId, $endpoint, $bucketName)

参数

$token (string): The IBM Cloud response token.
$serviceInstanceId (string): The IBM COS service instance ID.
$endpoint (string): The IBM COS endpoint.
$bucketName (string): The name of the IBM COS bucket.

上传对象

将文件上传到 IBM COS。

$cos->putObject($bucketName, $objectName, $body);

参数

$bucketName (string): Bucket name where the object is to be uploaded.
$objectName (string): The name of the object to load.
$body (string): The content of the object to load, either as a string or a resource.
$contentType (string|null): The content type of the object. If not specified, the service will choose a default content type.
$metadata (array): Optional metadata to add to the target object.

响应: 请求结束时的响应 true 或 false。

获取对象

从 IBM COS 下载文件。

$cos->getObject($bucket, $fileName);

参数

$bucket (string): The name of the bucket from which the file will be downloaded.
$fileName (string): The name of the file to download.

响应: 下载文件的正文内容。

复制对象

将对象复制到另一个存储桶,可选地重命名对象。

$cos->copyObject($sourceBucket, $sourceObject, $destinationBucket, $destinationObject, $contentType = null, $metadata = []);

参数

$sourceBucket (string): Origin bucket name.
$sourceObject (string): The name of the source object to copy.
$destinationBucket (string): Destination bucket name.
$destinationObject (string): Name of the target object. If not specified, the name of the source object is used.
$contentType (string|null): The content type of the object. If not specified, the service will choose a default content type.
$metadata (array): Optional metadata to add to the target object.

响应: 如果操作成功完成,则为 true,否则为 false。

删除对象

从指定存储桶中删除对象。

$cos->deleteObject($bucketName, $objectName);

参数

$bucketName (string): Bucket name.
$objectName (string): Name of the object to delete.

响应: 如果操作成功完成,则为 true,否则为 false。

列出对象

列出指定存储桶中的对象。

$cos->listObjects($bucketName, $prefix = null, $delimiter = null);

参数

$bucketName (string): Bucket name.
$prefix (string|null): Prefix used to filter objects by key name.
$delimiter (string|null): Used delimiter

响应: 包含属于提供的存储桶的对象列表的响应。

创建存储桶

在指定区域中创建新的存储桶。

$cos->createBucket($bucketName, $region);

参数

$bucketName (string): The name of the new bucket.
$region (string|null): The region in which the bucket will be created. If not specified, the service's default region will be used.

响应: 如果操作成功完成,则为 true,否则为 false。

删除存储桶

删除现有的存储桶。

$cos->deleteBucket($bucketName);

参数

$bucketName (string):The name of the bucket to delete.

响应: 如果操作成功完成,则为 true,否则为 false。

文本到语音

TextToSpeech 类提供了一种简单的方法与 IBM TTS 交互。

use IBMCloud\Helpers\Config;
use IBMCloud\TTS\TextToSpeech;

// Load IBM Cloud credentials from a YAML file
$credentials = Config::getCredentials('ibm-cloud.yaml');

$token = $authenticator->getAccessToken();

// Create an instance of TextToSpeech
$tts = new TextToSpeech(
    $token,
    $credentials['tts']['url']
);

// Define the necessary parameters
$text = 'This is a test.';

// The VoiceOptionsEnum class contains the supported voice models.
use Sean\IbmPhpSdk\IBMCloud\TTS\Enum\VoiceOptions;
$voice = VoiceOptions::EN_US_ALLISON_V3_VOICE;

// The AcceptOptionsEnum class contains the accepted audio formats.
use Sean\IbmPhpSdk\IBMCloud\TTS\Enum\AcceptOptions;
$accept = AcceptOptions::AUDIO_MP3;

// Make the request to IBM TTS
$audio = $tts->synthesize($text, $accept, $voice);

// Export the audio to a folder
file_put_contents('./path/to/audio.mp3', $audio);

创建 Text To Speech 类的新实例。

new TextToSpeech($token, $url)

参数

$token (string): The IBM Cloud response token.
$url (string): IBM TTS URL.
$version (string): Service version, by deafault V1.

合成

使用文本到语音服务从文本合成音频。

$ttf->synthesize($text, $accept, $voice);

参数

$text (string): The text to synthesize audio from.
$accept (string): The audio format to return. Acceptable values can be found in the AcceptOptionsEnum class.
$voice (string): The voice to use for the audio. Acceptable values can be found in the VoiceOptionsEnum class.

响应: 请求格式中请求的合成音频。

语音到文本

SpeechToText 类提供了一种简单的方法与 IBM STT 交互。

use IBMCloud\Helpers\Config;
use IBMCloud\STT\SpeechToText;

// Load IBM Cloud credentials from a YAML file
$credentials = Config::getCredentials('ibm-cloud.yaml');

$token = $authenticator->getAccessToken();

// Create an instance of TextToSpeech
$sst = new SpeechToText(
    $token,
    $credentials['stt']['url']
);

// Define the necessary parameters
$path = __DIR__.'\audio.mp3';

$params = new SpeechToTextParams([
    'audio' => $path,
    'content_type' => 'audio/mp3',
    'model' => MultimediaModels::SPANISH_CASTILIAN,
    'timestamps' => true,
    'word_alternatives_threshold' => 0.9,
    'keywords' => ['example', 'keyword'],
    'keywords_threshold' => 0.5
]);

// Make the request to IBM STT
$transcript = $sst->recognize($params);

// Display transcribed content based on sent audio.
echo $transcript;

创建 Speech To Text 类的新实例。

new SpeechToText($token, $url)

参数

$token (string): The IBM Cloud response token.
$url (string): IBM TTS URL.
$version (string): Service version, by deafault V1.

识别

“识别”是一种方法,通过向IBM Cloud语音到文本API发送POST请求来转录音频文件。

$stt->recognize($params);

参数

$params (array): List of possible options.
new SpeechToTextParams([
    'audio' => $path,
    'content_type' => 'audio/mp3',
    'model' => MultimediaModels::SPANISH_CASTILIAN,
    'timestamps' => true,
    'word_alternatives_threshold' => 0.9,
    'keywords' => ['example', 'keyword'],
    'keywords_threshold' => 0.5
])
  • audio: 要转录的音频文件的路径或内容。
  • audio_metrics: 一个布尔值,表示是否需要有关输入音频质量的信息,例如是否存在噪音或语音是否清晰。
  • continuous: 一个布尔值,表示是否需要连续转录(继续转录,直到音频输入停止)或单文件转录。
  • customization_id: 用于转录的定制语言模型的ID。如果没有指定,则使用通用语言模型。
  • events: 一个字符串,指定要发送到返回URL的事件类型。如果没有指定,则不会发送任何事件。
  • inactivity_timeout: 在转录会话关闭之前,必须经过的无音频输入活动时间(以秒为单位)。如果没有指定,则使用默认值30秒。
  • interim_results: 一个布尔值,表示是否返回中间转录结果(最终转录之前的中间结果)。
  • keywords: 要在转录中搜索的关键词数组。如果找到关键词,则可以将事件发送到返回URL。
  • keywords_threshold: 必须达到的关键词的最小置信水平,才能将其视为找到。如果没有指定,则使用默认值0.5。
  • language_customization_id: 用于语言检测的定制语言模型的ID。如果没有指定,则使用通用语言检测模型。
  • max_alternatives: 要返回的转录替代品的最大数量。如果没有指定,则使用默认值1。
  • model: 用于转录的语言模型的ID。如果没有指定,则使用通用语言模型。
  • profanity_filter: 一个布尔值,表示是否在转录中删除冒犯性内容。
  • smart_formatting: 一个布尔值,表示是否在转录中添加标点符号和大小写修正。
  • speaker_labels: 一个布尔值,表示是否在转录中识别和标记说话人。
  • timestamps: 一个布尔值,表示是否在转录中包含时间戳。
  • word_alternatives_threshold: 必须达到的单词的最小置信水平,才能在转录替代品中将单词视为找到。如果没有指定,则使用默认值0.1。
  • word_confidence: 一个布尔值,表示是否返回转录中单个单词的置信水平。

Response: 以请求格式返回的转录文本。

运行测试

1. 要运行本项目实现的所有IBM Cloud服务的测试,请按照以下步骤进行

  • 将存储库克隆到您的本地计算机。
  • 通过运行composer install安装必要的依赖项。
  • 创建一个.env或.yaml文件(如果使用yaml,您必须尊重项目根目录中的文件名(ibm-cloud.yaml),并添加环境变量

2. 使用以下命令运行所有服务的测试

vendor/bin/phpunit ./tests

将ServiceName替换为您要测试的服务名称,例如COS、NLU、TTS或STT。

vendor/bin/phpunit ./tests/ SERVICE / TEST_CLASS

这将运行IBM Cloud对象存储服务的测试。

4. 如果所有测试都通过,您应该会看到以下类似的消息

OK (XX tests, XX assertions)

如果任何测试失败,您将看到错误消息,指出失败的原因。

注意:如果您的IBM Cloud账户没有必要的凭据或权限来访问某些资源,某些测试可能会失败。

常见问题

我如何获取IBM Cloud凭据?

您可以从IBM Cloud控制面板获取IBM Cloud凭据。有关更多信息,请参阅IBM Cloud文档。

如何修复认证错误?

请确保IBM Cloud凭据正确,并且在YAML或ENV文件中设置正确。您还可以尝试重新生成凭据并重新配置。

如何报告错误或请求新功能?

您可以在SDK GitHub仓库中报告错误或请求新功能。有关更多信息,请参阅SDK README.md文件中的“贡献”部分。

贡献

如果您想为SDK的开发做出贡献,可以通过多种方式实现。

如果您发现错误或问题,可以在SDK GitHub仓库中报告。如果您想请求新功能或增强功能,也可以在SDK GitHub仓库中这样做。如果您想修复错误或添加新功能,可以fork仓库并提交包含您更改的pull request。在提交任何更改之前,请确保您已经为您的更改创建了适当的单元和集成测试,并且相应地更新了文档。

结论

IBM Cloud SDK for PHP是用于从用PHP编写的应用程序中与IBM Cloud服务交互的有用工具。有了适当的安装和配置说明,最终用户可以使用SDK与IBM NLU和IBM COS交互。清晰的完整文档,以及用例和集成测试,将帮助最终用户正确使用SDK并减少支持问题的数量。此外,能够为SDK的开发做出贡献使其成为任何使用IBM Cloud的项目有用的灵活工具。

即将到来的集成