关于Microsoft Cognitive Services Image Search API V5在Ruby on Rails中的集成,以下是详细解答:
Microsoft Cognitive Services(现称Azure Cognitive Services)的Image Search API属于AI视觉服务,提供基于关键词的图像搜索能力。V5版本是较新的API接口,支持更精准的图像检索和过滤功能。
目前官方没有为Image Search API V5提供专属的Rails Gem,但可通过以下两种方式实现集成:
通过rest-client
或httparty
等Gem直接调用API:
# Gemfile
gem 'rest-client'
gem 'json'
# 调用示例
require 'rest-client'
require 'json'
subscription_key = 'YOUR_AZURE_KEY'
endpoint = 'https://api.cognitive.microsoft.com/bing/v7.0/images/search'
query = 'cats'
params = { q: query, count: 10 }
headers = { 'Ocp-Apim-Subscription-Key' => subscription_key }
response = RestClient.get(endpoint, { params: params, headers: headers })
results = JSON.parse(response.body)
微软提供了通用的azure_cognitiveservices
Gem(非Rails专属):
# Gemfile
gem 'azure_cognitiveservices_imagesearch'
# 初始化客户端
require 'azure_cognitiveservices_imagesearch'
include Azure::CognitiveServices::ImageSearch::V1_0
credentials = MsRestAzure::CognitiveServicesCredentials.new('YOUR_KEY')
client = ImageSearchClient.new(credentials)
client.endpoint = 'https://YOUR_REGION.api.cognitive.microsoft.com'
# 执行搜索
results = client.images.search('dogs', count: 5)
若需更Rails化的集成,可考虑自行封装Gem:
# lib/bing_image_search.rb
module BingImageSearch
class Client
def initialize(key)
@key = key
end
def search(term, options = {})
# 实现API调用逻辑
end
end
end
Ocp-Apim-Subscription-Key
请求头westus.api.cognitive.microsoft.com
)问题:返回403错误
问题:结果不符合预期
如需进一步简化调用,建议参考微软官方Ruby SDK文档(注意:链接已去除品牌相关域名)。
没有搜到相关的文章