在Watson Studio的Jupyter笔记本中,如何引用上传到" assets"?的文件

时间:2018-04-17 14:56:51

标签: jupyter-notebook watson-studio

在Watson Studio中我在Jupyter Notebook中编写代码以使用Watson Visual Recognition自定义模型。 它适用于外部图像。 我还没有能够参考我上传到项目资产的图片。 资产的网址只显示整页,而不是图片: https://dataplatform.ibm.com/projects/2f4b89d9-b93a-4c98-a327-9b863a467b7c/data-assets/ed16c385-e09e-4bcb-bfab-67ee864538e4/?context=data

谢谢

1 个答案:

答案 0 :(得分:1)

在Watson中,资产文件保存在Cloud Object Store或COS中。您必须将图像从COS下载到笔记本服务器文件系统,然后您可以将笔记本中的文件称为常规本地文件。 / p>

我使用cos api来获取文件。 https://github.com/IBM/ibm-cos-sdk-python

https://console.bluemix.net/docs/services/cloud-object-storage/libraries/python.html#using-python

首先,找出你的凭据是什么

  1. 突出显示笔记本电脑,
  2. 点击数据菜单,
  3. 选择文件,
  4. "插入代码"
  5. 凭证。
  6. 然后,您可以使用API​​将文件下载到本地磁盘存储。例如,要从COS下载文件:

    # The following code contains the credentials for a file in your IBM Cloud Object Storage. 
    # You might want to remove those credentials before you share your notebook.
    credentials_1 = {
        'IBM_API_KEY_ID': '**************************************',
        'IAM_SERVICE_ID': 'iam-ServiceId-**************************',
        'ENDPOINT': 'https://s3-api.us-geo.objectstorage.service.networklayer.com',
        'IBM_AUTH_ENDPOINT': 'https://iam.ng.bluemix.net/oidc/token',
        'BUCKET': '********************************',
        'FILE': 'file.xlsx'
    }
    
    from ibm_botocore.client import Config
    import ibm_boto3
    def download_file_cos(credentials, local_file_name, key):  
        cos = ibm_boto3.client(service_name='s3',
        ibm_api_key_id=credentials['IBM_API_KEY_ID'],
        ibm_service_instance_id=credentials['IAM_SERVICE_ID'],
        ibm_auth_endpoint=credentials['IBM_AUTH_ENDPOINT'],
        config=Config(signature_version='oauth'),
        endpoint_url=credentials['ENDPOINT'])
        try:
            res=cos.download_file(Bucket=credentials['BUCKET'], Key=key, Filename=local_file_name)
        except Exception as e:
            print(Exception, e)
        else:
            print("Dowloaded:", key, 'from IBM COS to local:', local_file_name)
    

    在Notebook单元格列表目录内容中:

    %%script bash
    ls -l
    
    
    # to list all .png files in COS you can use a function like this:        
    def list_objects(credentials):  
        cos = ibm_boto3.client(service_name='s3',
        ibm_api_key_id=credentials['IBM_API_KEY_ID'],
        ibm_service_instance_id=credentials['IAM_SERVICE_ID'],
        ibm_auth_endpoint=credentials['IBM_AUTH_ENDPOINT'],
        config=Config(signature_version='oauth'),
        endpoint_url=credentials['ENDPOINT'])
        return cos.list_objects(Bucket=credentials['BUCKET'])
    
    response = list_objects(credentials_1)
    for c in response['Contents']:
        if c['Key'].endswith('.png'):
            print(c['Key'], "last modified:", c['LastModified'])