IBM watson API解析2-Document Conversion(文本转换)

时间:2022-02-27 14:05:29

前期准备

1、注册Bluemix账号

需要一个IBM的Bluemix账号,已有账号的可直接登陆,若无账号,点击注册进行注册。
注册时国家或地区默认的,否则可能会出错。

2、安装watson-developer-cloud

pip install --upgrade watson-developer-cloud

3、创建应用服务

  1. 登录Bluemix后,点击左上角目录栏,点击”服务“,然后点击”Watson“。则会看到一系列服务。如图所示:IBM watson API解析2-Document Conversion(文本转换)
  2. 点击Document Conversion
  3. 点击创建,则会创建一个相应的服务凭证
  4. 进入后,点击左边的服务凭证,则会看到创建的服务
  5. 点击查看凭证,则会显示服务的URL、用户名、密码,这些在调用相应API时会用到

Docuemnt Conversion

1、基本概念

Document Conversion 服务将单一的 HTML、PDF 或 Microsoft Word™ 文档转换为标准化的 HTML、纯文本或一组可用于其他 Watson 服务的 JSON 格式的答案单元

2、目前版本号

API 版本格式为:version=YYYY-MM-DD。以年月日作为版本号,目前版本号为:2015-12-15.

简单样例(Python实现)

Document Conversion API提供了两个方法,一下分别介绍这个两个方法。

1、Convert a document方法

用于将文档转换成为应答单位(answer units),HTML以及文本。

以下是使用Python进行简单实例,但是没有得到想要的结果,报了错误,现在将此贴出来。如有解决方法,请各位大神不吝赐教。之后将使用其他方法实现。
实现代码如下:

# encoding: UTF-8
import json
from watson_developer_cloud import DocumentConversionV1,WatsonException
document_conversion = DocumentConversionV1(
username="324e088a-5375-4f53-a863-417453290f90",
password="dTwCrjHosJn2",
version="2015-12-15"
)
config = {
'conversion_target': 'NORMALIZED_TEXT',
# Use a custom configuration.
'pdf':{
'heading':{
'fonts':[
{'level':1,'min_size':24},
{'level':2,'min_size':16,'max_size':23,'bold':True},
{'level':2,'min_size':14,'max_size':17,'italic':False}
]
}
}
}
try:
with open(('MySQL.pdf'),'r') as document:
print(json.dumps(
document_conversion.convert_document(
document=document,config=config),
indent=2
))
except WatsonException as e:
print e

结果显示:

Error: expected='endstream' actual='' at offset 105, Code: 400

抛出异常了。
以下将代码中的参数进行解释:

document:为文件的索引。必须填写的内容。最大文件大小为50MB。可以指定的文件类型有text/xhtml+xml,text/html,application/pdf, application/msword, 和 application/vnd.openxmlformats-officedocument.wordprocessingml.document。

config:一个配置对象,用于定义转换输出中的标签和结构。 对象的最大大小为1 MB。

config中的参数:

conversion_target:控制转换的输出格式。 有效值为ANSWER_UNITS,NORMALIZED_HTML和NORMALIZED_TEXT。
{input configuration}:定义如何输出输入文档的标签和结构的对象。

下面介绍使用cUrl方法进行文本转换:
代码如下:

curl -X POST  -u "324e088a-5375-4f53-a863-417453290f90":"dTwCrjHosJn2" -F config="{\"conversion_target\":\"normalized_text\"}" -F "file=@C:\Users\RoyZ\Desktop\IBM-Annual-Report.pdf;type=application/pdf" "https://gateway.watsonplatform.net/document-conversion/api/v1/convert_document?version=2015-12-15"

结果输出:
IBM watson API解析2-Document Conversion(文本转换)

注意:当文档是中文时,会输出乱码。

若想将内容输出到本地指定文件内,只需要加一句“-o filename”即可。如下代码所示:

curl -X POST -o C:\Users\RoyZ\Desktop\hu.txt -u "324e088a-5375-4f53-a863-417453290f90":"dTwCrjHosJn2" -F config="{\"conversion_target\":\"normalized_text\"}" -F "file=@C:\Users\RoyZ\Desktop\IBM-Annual-Report.pdf;type=application/pdf" "https://gateway.watsonplatform.net/document-conversion/api/v1/convert_document?version=2015-12-15"

2、Index a document方法

为检索和排序服务(Retrieve and Rank service)准备一个文档作为增强信息检索解决方案的一部分,然后将内容添加到Solr索引中,以便可以进行搜索。
实现代码如下:

# encoding: UTF-8
import json
from watson_developer_cloud import DocumentConversionV1,WatsonException

document_conversion = DocumentConversionV1(
username="324e088a-5375-4f53-a863-417453290f90",
password="dTwCrjHosJn2",
version="2015-12-15"
)
config = {
'convert_document':{
'normalized_html':{
'exclude_tags_completely':['script','sup']
}
},
'retrieve_and_rank':{
'dry_run':'false',
'service_instance_id': '692b4b66-bd13-42e6-9cf3-f7e77f8200e5',
'cluster_id': 'sc1ca23733_faa8_49ce_b3b6_dc3e193264c6',
'search_collection': 'example_collection',
'fields':{
'mappings':[{
'from':'Author',
'to':'Created By'
},{
'from':'Date Created',
'to':'Created On'
},{
'from':'Continent',
'to':'Region'
}],
'include':['Created By','Created On'],
'exclude':['Region']
}
}
}
metadata = {
'metadata':[
{'name':'Creator','value':'Some person'},
{'name':'Subject','value':'Application programing interfaces'}
]
}

with open(('sample-docx.docx'),'r') as document:
response = document_conversion.index_document(config=config,document=document,metadata=metadata)
print (json.dumps(response,indent=2))

结果显示(报错):

Traceback (most recent call last):
File "E:/python workspace/watson_API/Document_Conversion/dc_python.py", line 68, in <module>
response = document_conversion.index_document(config=config,document=document,metadata=metadata)
File "C:\Users\RoyZ\Anaconda2\lib\site-packages\watson_developer_cloud\document_conversion_v1.py", line 70, in index_document
files=files, params=params, accept_json=True)
File "C:\Users\RoyZ\Anaconda2\lib\site-packages\watson_developer_cloud\watson_developer_cloud_service.py", line 324, in request
raise WatsonException(error_message)
watson_developer_cloud.watson_developer_cloud_service.WatsonException: Error: Failed to convert the document. IOException in executing step WORD to HTML, Code: 400

以下将代码中的参数:

config:一个配置对象,标识目标Retrieve和Rank服务。 可以选择包括有关文档中的字段的信息以及有关如何处理文档的配置信息。 部件的最大大小为1 MB。

document:为文件的索引。必须填写的内容。最大文件大小为50MB。可以指定的文件类型有text/xhtml+xml,text/html,application/pdf, application/msword, 和 application/vnd.openxmlformats-officedocument.wordprocessingml.document。

metadata:描述文件的外部元数据的元数据部分。必需填写。 当没有要索引的文档内容(例如,使用数据库连接器)时,可以调用此方法而不使用文件部分。 部件的最大尺寸为1 MB。

config中的参数:

convert_document:允许定义转换输出结构的对象。由于正在指定如何在“检索和排序”服务中将文档添加到Solr中,因此某些转换配置设置将被忽略。例如,answer_units对象中的conversion_target或selector_tags的值将被忽略。

retrieve_and_rank:一个retrieve_and_rank对象,用于标识如何将文档转换服务连接到Retrieve and Rank服务实例。

具体方法,还有待完善,请大神们不吝赐教!
参考:https://www.ibm.com/watson/developercloud/document-conversion/api/v1/?python#index-document