SemDB 示例教程
编程语言支持:Python

SemDB 系统提供了一套简易 Python 库用来简化对 SemDB API 的访问。

首先可以利用 pip 安装该 Python 库。

 pip install semdb-library 

然后我们即可在 Python 程序中引用该库:

 import semdb_library 

Python 库内置了模型的复现功能,可以基于导出的模型配置复现幕景中的模型,如下例所示:

import json

with open('classification.json', 'r') as file:
    config = json.loads(file.read())
    a = semdb_library.ClassificationModel(config)
    print(a.run([30, 50, 70]))

复现模型时,首先创建对应的 ClassificationModel 或者 RankingModel 对象,然后再调用其中的 run 函数即可。

除此之外,我们还可以使用该库来直接调用 SemDB 的外部 API。首先需要创建一个 Connection 对象,创建时需要指定服务器的 API 访问地址(可以在设置页面的其他设置栏查看)。

 conn = semdb_library.Connection('{api_address}') 

下面依次介绍 Connection 对象所附带的函数。

login(self, user: str, password: str)

用于从外部登录 SemDB 系统,每个 Connection 对象仅需执行一次该函数。

 conn.login('user', 'password') 
execute_capsule(self, capsule: str, data: object)

用于执行特定的胶囊,该函数的返回值为胶囊的返回值,例子见下:

 print(conn.execute_capsule('Dir.Capsule', { 'id': [{ 'id': 0 }] }))
 ------------
 {'MyValue': [{'A': 42, 'B': 23, 'C': 89}]}
read_json_index(self, index: str, item_id: int)

用于读取 JSON 索引,该函数的返回值为所读取的信息,例子见下:

 print(conn.read_json_index('Dir.MyJSONIndex', 1))
 ------------
 {'A': 20, 'B': 'Hello World Again!'}
insert_json_index(self, index: str, item_id: int, object: object)

用于更改 JSON 索引,例子见下:

 conn.insert_json_index('Dir.MyJSONIndex', 0, {'A': 10, 'B': 'Hello World!'}) 
close()

关闭连接,该 Connection 对象将不再可用。

© 2025