如何查看Google Cloud Vision API中的配额限制?

How to check the quota limit in Google Cloud Vision API?

是否有 API 可以查看您在这个计费周期中向 Google Cloud Vision API 拨打了多少次电话? 我想将此信息添加到 UI 以便用户知道他们何时将要进行收费查询。

最简单的方法是在控制台上使用 API page。这将显示请求的总数。考虑到您可以编辑 URL 以匹配所需的天数。例如,由于今天是 4 月 9 日,UI 上没有 9 天按钮,我将 URL 参数编辑为 &duration=P9D。结果是:

这也可以使用 Stackdriver Monitoring 以编程方式完成,但这并不简单。 serviceruntime 指标收集 Google API 秒的资源使用情况。 如果您导航到 SD 监控中的 Metrics Explorer 并开始在文本框中键入 serviceruntime,则您可以 select api/request_count 指标类型:

然后,在 filter 选项中,您可以 select Vision API 指标与 service=vision.googleapis.com。请注意,您还可以按其他参数(例如请求方法或响应代码)进行过滤和聚合。 这将显示对 Vision 的请求数 API(在我的例子中是 4):

但是,这不适合您的用例,因为这是 DELTA 指标而不是 CUMULATIVE 指标 (Metric Kinds)。您需要将所有请求相加以获得总数。 因为我不太熟悉 custom metrics, my idea was to look into the underlying API call 并使用 bash 脚本聚合时间序列中的所有数据点。

首先,我们需要项目 ID 和访问令牌:

TOKEN=$(gcloud auth application-default print-access-token)
PROJECT=$(gcloud config get-value project 2>\dev\null)

而且我们还需要在 TimeInterval format. We are interested in up-to-date statistics so the end time will be the current one (credit 中提供初始和最终时间戳。 对于初始时间,我们只需要解析当前的年份和月份,因为日期和时间是已知的:

NOW=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
AUX=-01T00:00:00Z
START_MONTH=$(echo $NOW | cut -c1-7)$AUX

不过请注意,您可能需要针对实际重新填充配额的时间进行调整。 然后你可以继续调用SD Monitoring API(修改过滤器以获得不同的选项或APIs而不是Vision):

curl "https://monitoring.googleapis.com/v3/projects/$PROJECT/timeSeries?filter=metric.type%3D%22serviceruntime.googleapis.com%2Fapi%2Frequest_count%22%20AND%20resource.labels.service%3D%22vision.googleapis.com%22&interval.endTime=$NOW&interval.startTime=$START_MONTH" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Accept: application/json" \
  --compressed > result.txt

您可以更改其他服务指标的过滤器属性。将结果保存到中间文件不是必需的,但有助于可视化。响应将包含一个 timeSeries 对象,每个数据点的值字段中包含请求计数:

{
  "timeSeries": [
    {

      ...

      },
      "metricKind": "DELTA",
      "valueType": "INT64",
      "points": [
        {
          "interval": {
            "startTime": "2018-04-08T11:20:48.224Z",
            "endTime": "2018-04-08T11:21:48.224Z"
          },
          "value": {
            "int64Value": "1"
          }
        },
        {
          "interval": {
            "startTime": "2018-04-08T11:18:18.224Z",
            "endTime": "2018-04-08T11:19:18.224Z"
          },
          "value": {
            "int64Value": "2"
          }
        },
        {
          "interval": {
            "startTime": "2018-04-08T11:18:08.224Z",
            "endTime": "2018-04-08T11:19:08.224Z"
          },
          "value": {
            "int64Value": "1"
          }
        }
      ]
    }
  ]
}

然后,您可以使用 jq 解析结果以将这些值相加,或者在我的例子中,bash 脚本 (credit):

cat result.txt | grep int64Value | cut -d '"' -f4 | awk '{s+=} END {printf "%.0f\n", s}'

这将输出 4,正如在我的例子中根据累积请求计数所预期的那样