itam-assistant 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
@@ -0,0 +1,127 @@
1
+ import json
2
+
3
+ import lark_oapi as lark
4
+ from lark_oapi.api.auth.v3 import *
5
+ from lark_oapi.api.aily.v1 import *
6
+
7
+
8
+ # SDK 使用说明: https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/server-side-sdk/python--sdk/preparations-before-development
9
+ # 以下示例代码默认根据文档示例值填充,如果存在代码问题,请在 API 调试台填上相关必要参数后再复制代码使用
10
+ # 复制该 Demo 后, 需要将 "YOUR_APP_ID", "YOUR_APP_SECRET" 替换为自己应用的 APP_ID, APP_SECRET.
11
+
12
+
13
+ class AilyLarkClient():
14
+ def __init__(self,clientinfo):
15
+ """
16
+ 初始化 Client 实例,tenant_access_token 会在 Client 初始化时自动获取
17
+ """
18
+ self.aily_app_id = clientinfo.get("aily_app_id") or "spring_f17d05d924__c"
19
+ self.app_id = clientinfo.get("app_id") or "cli_a6e3aea1a13c900c"
20
+ self.app_secret = clientinfo.get("app_secret") or "J0fAPt3BL6bv4KUJV0dJMdTUdr0pv3xx"
21
+ # 创建 Lark-tenant tenant客户端
22
+ self.tlark_client = lark.Client.builder().app_id(self.app_id).app_secret(self.app_secret).build()
23
+
24
+ # 创建 Lark-tenant user 客户端
25
+ self.ulark_client = lark.Client.builder().enable_set_token(True).log_level(lark.LogLevel.DEBUG).build()
26
+
27
+ def get_tenant_access_token(self):
28
+ # 构造请求对象
29
+ request: InternalTenantAccessTokenRequest = InternalTenantAccessTokenRequest.builder() \
30
+ .request_body(InternalTenantAccessTokenRequestBody.builder()
31
+ .app_id(self.app_id)
32
+ .app_secret(self.app_secret)
33
+ .build()) \
34
+ .build()
35
+
36
+ # 发起请求
37
+ response: InternalTenantAccessTokenResponse = self.tlark_client.auth.v3.tenant_access_token.internal(request)
38
+
39
+ # 处理失败返回
40
+ if not response.success():
41
+ lark.logger.error(
42
+ f"client.auth.v3.tenant_access_token.internal failed, code: {response.code}, msg: {response.msg}, log_id: {response.get_log_id()}, resp: \n{json.dumps(json.loads(response.raw.content), indent=4, ensure_ascii=False)}")
43
+ return
44
+ # 处理业务结果
45
+ lark.logger.info(lark.JSON.marshal(response.raw, indent=4))
46
+ tenant_access_token = json.loads(response.raw.content).get("tenant_access_token")
47
+ if tenant_access_token:
48
+ return tenant_access_token
49
+ else:
50
+ lark.logger.error(
51
+ f"client.auth.v3.tenant_access_token.internal failed, code: {response.code}, msg: {response.msg}, log_id: {response.get_log_id()}, resp: \n{json.dumps(json.loads(response.raw.content), indent=4, ensure_ascii=False)}")
52
+ return
53
+
54
+ def create_ailysession(self, access_token):
55
+ # 创建会话
56
+ # 构造请求对象
57
+ request: CreateAilySessionRequest = CreateAilySessionRequest.builder() \
58
+ .request_body(CreateAilySessionRequestBody.builder()
59
+ .channel_context("{}")
60
+ .metadata("{}")
61
+ .build()) \
62
+ .build()
63
+
64
+ # 发起请求
65
+ option = lark.RequestOption.builder().user_access_token(access_token).build()
66
+ response: CreateAilySessionResponse = self.ulark_client.aily.v1.aily_session.create(request, option)
67
+
68
+ # 处理失败返回
69
+ if not response.success():
70
+ lark.logger.error(
71
+ f"client.aily.v1.aily_session.create failed, code: {response.code}, msg: {response.msg}, log_id: {response.get_log_id()}, resp: \n{json.dumps(json.loads(response.raw.content), indent=4, ensure_ascii=False)}")
72
+ return
73
+
74
+ # 处理业务结果
75
+ lark.logger.info(lark.JSON.marshal(response.data, indent=4))
76
+ return response.data.session.id
77
+
78
+ def create_ailysessionaily_message(self, access_token, session_id, content):
79
+ # 发送智能伙伴消息
80
+ # 构造请求对象
81
+ request: CreateAilySessionAilyMessageRequest = CreateAilySessionAilyMessageRequest.builder() \
82
+ .aily_session_id(session_id) \
83
+ .request_body(CreateAilySessionAilyMessageRequestBody.builder()
84
+ .content(content)
85
+ .content_type("MDX")
86
+ .idempotent_id("idempotent_id_1")
87
+ .build()) \
88
+ .build()
89
+ # 发起请求
90
+ option = lark.RequestOption.builder().user_access_token(access_token).build()
91
+ response: CreateAilySessionAilyMessageResponse = self.ulark_client.aily.v1.aily_session_aily_message.create(
92
+ request,
93
+ option)
94
+ # 处理失败返回
95
+ if not response.success():
96
+ lark.logger.error(
97
+ f"client.aily.v1.aily_session_aily_message.create failed, code: {response.code}, msg: {response.msg}, log_id: {response.get_log_id()}, resp: \n{json.dumps(json.loads(response.raw.content), indent=4, ensure_ascii=False)}")
98
+ return
99
+ # 处理业务结果
100
+ lark.logger.info(lark.JSON.marshal(response.data, indent=4))
101
+ return response.data.message.id
102
+
103
+ def create_ailysession_run(self, access_token, aily_session_id):
104
+ # 创建运行
105
+ # 构造请求对象
106
+ request: CreateAilySessionRunRequest = CreateAilySessionRunRequest.builder() \
107
+ .aily_session_id(aily_session_id) \
108
+ .request_body(CreateAilySessionRunRequestBody.builder()
109
+ .app_id(self.aily_app_id)
110
+ .build()) \
111
+ .build()
112
+ # 发起请求
113
+ option = lark.RequestOption.builder().user_access_token(
114
+ access_token).build()
115
+ response: CreateAilySessionRunResponse = self.ulark_client.aily.v1.aily_session_run.create(request, option)
116
+ # 处理失败返回
117
+ if not response.success():
118
+ lark.logger.error(
119
+ f"client.aily.v1.aily_session_run.create failed, code: {response.code}, msg: {response.msg}, log_id: {response.get_log_id()}, resp: \n{json.dumps(json.loads(response.raw.content), indent=4, ensure_ascii=False)}")
120
+ return
121
+
122
+ # 处理业务结果
123
+ lark.logger.info(lark.JSON.marshal(response.data, indent=4))
124
+
125
+
126
+ if __name__ == '__main__':
127
+ aily_app_id = AilyLarkClient({}).get_tenant_access_token()
it_assistant/config.py ADDED
@@ -0,0 +1,51 @@
1
+ # -*- coding: utf-8 -*-
2
+ #初始化 表单数据
3
+
4
+ Clientin = {
5
+ "aily_app_id": "spring_f17d05d924__c",
6
+ "app_id": "cli_a6e3aea1a13c900c",
7
+ "app_secret": "J0fAPt3BL6bv4KUJV0dJMdTUdr0pv3xx",
8
+ "cookie": "X-Kunlun-SessionId=L%3A3b34958803f34f43a52c.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2YWwiOnsidGVuYW50X2lkIjozOTAsInVzZXJfaWQiOjE3MjIxNjYwNzMxOTk2NDUsInRlbmFudF9kb21haW5fbmFtZSI6ImFwYWFzIiwic2Vzc2lvbl92ZXJzaW9uIjoidjIwMjAtMDUtMTkiLCJ3c190b2tlbiI6Ilc6OTk3Y2MwNTA3OTRlNGFmYWFkYzEiLCJsb2dpbl90b2tlbiI6IjE3MDE3ZmFlMWJlNjVlMzdzSzBhMzA0ZjY0N2MyZmFjY2QwSjRFYmNmNGVjNzAzZDgwOWYxNDVnNDY0MzY1ZjEyNWI0YmZlZDhhTmMiLCJzb3VyY2VfY2hhbm5lbCI6ImZlaXNodSIsInRlbmFudF9rZXkiOiI3MzY1ODhjOTI2MGYxNzVkIiwiZXh0ZXJuYWxfZG9tYWluX25hbWUiOiJieXRlZGFuY2UiLCJvcmlnaW5hbF90ZW5hbnRfaWQiOjAsIm9yaWdpbmFsX3VzZXJfaWQiOjAsImlkcF9jaGFubmVsIjoiIn0sImV4cCI6MTc1ODk0MTY3MH0.l9yn5zbWFhOEJml5iA69TpFwZ7qgLMzj7L0cj4Ryozc; passport_web_did=7487801556726579201; passport_trace_id=7487801556748156956; QXV0aHpDb250ZXh0=2f506053fdd544e7aa0df84c66a287f9; locale=zh-CN; landing_url=https://accounts.feishu.cn/accounts/page/login?app_id=107&no_trap=1&redirect_uri=https%3A%2F%2Fapaas.feishu.cn%2Fai%2Fspring_f17d05d924__c%2Fmanagement%2Fchat-log; _gcl_au=1.1.1249684330.1743389657; s_v_web_id=verify_m8wh6ssk_JRUTLUkb_AJsu_4Xjm_ANzV_gLPDip941iqw; __tea__ug__uid=7487801495396992562; _ga=GA1.2.1834362348.1743389657; _gid=GA1.2.758422620.1743389658; session=XN0YXJ0-4e7g6c2c-da65-4492-a6f6-6413002bd949-WVuZA; session_list=XN0YXJ0-4e7g6c2c-da65-4492-a6f6-6413002bd949-WVuZA; login_recently=1; _ga_VPYRHN104D=GS1.1.1743389657.1.1.1743389669.48.0.0; msToken=4W_kQaUJyB5jBl5FX8vjfY6SYAFcNAp7NiDqM3-QyBN0XIF24a5SyaOeTpfzIZAuNfH-cGjXK1u3tNXV3ETo8Z2ZTQFLGSTFF2KmMr35XQsODVrddz8FdHAfyJg4F7ayxiDsicO5ObKgK0Y_95Bq1d12vKKbJ99vm9IZWEpcRFLG; kunlun-session-v2=L%3A3b34958803f34f43a52c.eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ2YWwiOnsidGVuYW50X2lkIjozOTAsInVzZXJfaWQiOjE3MjIxNjYwNzMxOTk2NDUsInRlbmFudF9kb21haW5fbmFtZSI6ImFwYWFzIiwic2Vzc2lvbl92ZXJzaW9uIjoidjIwMjAtMDUtMTkiLCJ3c190b2tlbiI6Ilc6OTk3Y2MwNTA3OTRlNGFmYWFkYzEiLCJsb2dpbl90b2tlbiI6IjE3MDE3ZmFlMWJlNjVlMzdzSzBhMzA0ZjY0N2MyZmFjY2QwSjRFYmNmNGVjNzAzZDgwOWYxNDVnNDY0MzY1ZjEyNWI0YmZlZDhhTmMiLCJzb3VyY2VfY2hhbm5lbCI6ImZlaXNodSIsInRlbmFudF9rZXkiOiI3MzY1ODhjOTI2MGYxNzVkIiwiZXh0ZXJuYWxfZG9tYWluX25hbWUiOiJieXRlZGFuY2UiLCJvcmlnaW5hbF90ZW5hbnRfaWQiOjAsIm9yaWdpbmFsX3VzZXJfaWQiOjAsImlkcF9jaGFubmVsIjoiIn0sImV4cCI6MTc1ODk0MTY3MH0.l9yn5zbWFhOEJml5iA69TpFwZ7qgLMzj7L0cj4Ryozc; kunlun-session-token=2b32fc3c28f44fb89bab94ad072a05c9f2f844c49705c95d76bae40479a189b7; _tea_utm_cache_1229=undefined; sl_session=eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NDM0MzI4NzEsInVuaXQiOiJldV9uYyIsInJhdyI6eyJtZXRhIjoiQVdIazBuRzhRUUFDQUFBQUFBQUFBQUZuNmdQWUFVNEFBV2ZxQTlnQlRnQUJaK29ENWRES3dBSUNLZ0VBUVVGQlFVRkJRVUZCUVVKdU5tZFFiRE40ZDBGQlp6MDkiLCJzdW0iOiJlMmM4YTIwMTcyMDcxNmVjYTFiOWRlOTQ5Yjc3OGJkNDczOGIzOTAwNWJiNTJhYTkyOTM2YTRhZWIzMGI2ZTY0IiwibG9jIjoiemhfY24iLCJhcGMiOiJSZWxlYXNlIiwiaWF0IjoxNzQzMzg5NjcxLCJzYWMiOnsiVXNlclN0YWZmU3RhdHVzIjoiMSIsIlVzZXJUeXBlIjoiNDIifSwibG9kIjpudWxsLCJjbmYiOnsiamt0IjoiYkx6aTdPRDBHS09mNllOQ0xGamtPZWtuQkNRSHM2ZFh5STdmcTVubE93VSJ9LCJucyI6ImxhcmsiLCJuc191aWQiOiI3MDUzOTk0MzAyMzAwNTUzMjE4IiwibnNfdGlkIjoiMSIsIm90IjozLCJjdCI6MTc0MzM4OTY3MCwicnQiOjE3NDMzODk2NzB9fQ.2pQlqU6fuqnw_iqtJe1sH1FfSSXBpFQ0RAoaRccxHEaHSBvqsdc9_7e4zjgcHOhTjISi3mGw3EC3EXftLj5Otw; passport_app_access_token=eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3NDM0MzI4NzIsInVuaXQiOiJldV9uYyIsInJhdyI6eyJtX2FjY2Vzc19pbmZvIjp7IjEwNyI6eyJpYXQiOjE3NDMzODk2NzIsImFjY2VzcyI6dHJ1ZX19LCJzdW0iOiJlMmM4YTIwMTcyMDcxNmVjYTFiOWRlOTQ5Yjc3OGJkNDczOGIzOTAwNWJiNTJhYTkyOTM2YTRhZWIzMGI2ZTY0In19.jtfbxALtDnZYTJx4cb6ohPy2uDVCHTuh0x-Dg7Ui1F4vMO3aka7rvOeZTIwGJ7IlAn0b-OjBOWQEVQvHthhEwQ; swp_csrf_token=a239a297-e0f7-4820-aa3a-6349c8a04977; t_beda37=10a0c227407070710f979ef9d5b530118d080fd0ec27f2c3ce04c251a5a20d70",
9
+ "x-kunlun-token": "17017fae1be65e37sK0a304f647c2faccd0J4Ebcf4ec703d809f145g464365f125b4bfed8aNc",
10
+ "x-tt-env": "ppe_cn_env_self_test_feat_cr_a",
11
+ "Authorization": "Basic cm40cmFpdTRwenY1cGlsYTo2bWhvOXV3ZXFrOHZpbDllcXRxMHZ1YmVnc2xjeXBucg==",
12
+ }
13
+
14
+ class SingletonMeta(type):
15
+ _instances = {}
16
+
17
+ def __call__(cls, *args, **kwargs):
18
+ if cls not in cls._instances:
19
+ cls._instances[cls] = super().__call__(*args, **kwargs)
20
+ return cls._instances[cls]
21
+
22
+ class Clientassign(metaclass=SingletonMeta):
23
+ """
24
+ 定义一个全局变量 Client
25
+ 该类为单例类,确保整个应用中只有一个实例
26
+ """
27
+ def __init__(self, Clientinfox):
28
+
29
+ self.aily_app_id = Clientinfox.get("data_set_ailyappid") or Clientin["aily_app_id"]
30
+ self.app_id = Clientinfox.get("data_set_appid") or Clientin["app_id"]
31
+ self.app_secret = Clientinfox.get("data_set_appsecret") or Clientin["app_secret"]
32
+ self.cookie = Clientinfox.get("data_set_cookie") or Clientin["cookie"]
33
+ self.x_kunlun_token = Clientinfox.get("data_set_kunluntoken") or Clientin["x-kunlun-token"]
34
+ self.x_tt_env = Clientinfox.get("data_set_ppeenv") or Clientin["x-tt-env"]
35
+ self.authorization = Clientinfox.get("data_set_auth") or Clientin["Authorization"]
36
+
37
+
38
+ if __name__ == '__main__':
39
+ Clientinfox = {
40
+ "data_set_ailyappid": "123",
41
+ "data_set_appid": "456",
42
+ "data_set_appsecret": "789",
43
+ "data_set_cookie": "012",
44
+ "data_set_kunluntoken": "345",
45
+ "data_set_ppeenv": "678",
46
+ "data_set_auth": "901",
47
+ }
48
+ b=Clientassign(Clientinfox)
49
+
50
+
51
+
it_assistant/do_ai.py ADDED
@@ -0,0 +1,490 @@
1
+ # -*- coding: utf-8 -*-
2
+ import time
3
+ from it_assistant.ailyapp_client import AilyLarkClient
4
+ from it_assistant.lark_client import LarkdocsClient
5
+ from it_assistant.intent_detail import *
6
+ from it_assistant.openapi import *
7
+ import datetime
8
+ import copy
9
+ import os
10
+ import csv
11
+
12
+
13
+ # 定义一个全局变量Client
14
+ # Testsuitelink = "https://bytedance.larkoffice.com/sheets/ZVzfsw4rMhkMF6tjtxmc4BdSnMb"
15
+
16
+
17
+ def do_ai_auto(Testk_data, clientinfo):
18
+ """
19
+ 自动化执行AI测试用例
20
+ """
21
+ startAt = 0
22
+ try:
23
+ # 获取租户访问令牌
24
+ tenant_access_token = AilyLarkClient(clientinfo).get_tenant_access_token()
25
+ if not tenant_access_token:
26
+ raise ValueError("未能获取到有效的租户访问令牌")
27
+ # 判断Testsuitelink中是否包含https://
28
+ if "https://" in Testk_data:
29
+
30
+ # 通过文档链接获取spreadsheet_token
31
+ spreadsheet_token = Testk_data.split("/")[-1]
32
+ if not spreadsheet_token:
33
+ raise ValueError("未能从文档链接中提取到有效的spreadsheet_token")
34
+ # 读取表格用户输入
35
+ spreadsheet = LarkdocsClient().get_the_worksheet(spreadsheet_token)
36
+ if not spreadsheet:
37
+ raise ValueError("未能获取到有效的工作表数据")
38
+ for i in spreadsheet.sheets:
39
+ column_count = i.grid_properties.column_count
40
+ row_count = i.grid_properties.row_count
41
+ sheet_id = i.sheet_id
42
+ title = i.title
43
+ if title == "测试集":
44
+ # 构建JSON字符串
45
+ json_str = {"ranges": [sheet_id + "!A1:A" + str(row_count)]}
46
+ # 获取纯文本内容
47
+ test = LarkdocsClient().get_plaintextcontent(json_str, spreadsheet_token, sheet_id)
48
+ test = json.loads(test)
49
+ userinput = test['data']['value_ranges'][0]['values']
50
+ print(f"表头为{userinput[0]}")
51
+ for i in range(1, row_count):
52
+ if userinput[i][0]:
53
+ if startAt == 0:
54
+ startAt = int(time.time())
55
+ # 创建会话
56
+ seseion_id = AilyLarkClient(clientinfo).create_ailysession(tenant_access_token)
57
+ if not seseion_id:
58
+ raise ValueError("未能成功创建会话")
59
+ # 创建消息
60
+ message_id = AilyLarkClient(clientinfo).create_ailysessionaily_message(tenant_access_token,
61
+ seseion_id,
62
+ userinput[i][0])
63
+ if not message_id:
64
+ raise ValueError("未能成功创建消息")
65
+ # 创建运行实例
66
+ runs = AilyLarkClient(clientinfo).create_ailysession_run(tenant_access_token, seseion_id)
67
+ # 可不需等待运行实例创建完成
68
+ # if not runs:
69
+ # raise ValueError("未能成功创建运行实例")
70
+ time.sleep(1)
71
+ else:
72
+ return startAt, i
73
+ break
74
+ return startAt, row_count
75
+ break
76
+ elif Testk_data[0].get('ext'):
77
+ num = 0
78
+ for i in Testk_data:
79
+ aa = i['ext']['input']
80
+ if startAt == 0:
81
+ startAt = int(time.time())
82
+ # 创建会话
83
+ seseion_id = AilyLarkClient(clientinfo).create_ailysession(tenant_access_token)
84
+ if not seseion_id:
85
+ raise ValueError("未能成功创建会话")
86
+ # 创建消息
87
+ message_id = AilyLarkClient(clientinfo).create_ailysessionaily_message(tenant_access_token, seseion_id,
88
+ aa)
89
+ if not message_id:
90
+ raise ValueError("未能成功创建消息")
91
+ # 创建运行实例
92
+ runs = AilyLarkClient(clientinfo).create_ailysession_run(tenant_access_token, seseion_id)
93
+ num = num + 1
94
+ return startAt, num
95
+ except KeyError as ke:
96
+ print(f"KeyError 发生: 数据中缺少必要的键,错误详情: {ke}")
97
+ return None, None
98
+ except json.JSONDecodeError as jde:
99
+ print(f"JSON 解析错误: {jde}")
100
+ return None, None
101
+ except ValueError as ve:
102
+ print(f"值错误: {ve}")
103
+ return None, None
104
+ except Exception as e:
105
+ print(f"发生未知错误: {e}")
106
+ return None, None
107
+
108
+
109
+ def get_results(num,res):
110
+ """
111
+ 获取结果
112
+ """
113
+ labels = []
114
+ a = len(res["body"]["Results"])
115
+ #判断res["body"]["Results"]的个数,如果大于num,则取num个值,小于num,则取res["body"]["Results"]的个数
116
+ if a > num:
117
+ num = num
118
+ else:
119
+ num = a
120
+ #提取res["body"]["Results"]的前num个值
121
+ res["body"]["Results"] = res["body"]["Results"][:num]
122
+ #遍历res["body"]["Results"]提取 name_zh、brand_zh、model_zh、specification_zh 并拼接
123
+ for i in range(0, num):
124
+ res["body"]["Results"][i]['Item']['sku_zh'] = res["body"]["Results"][i]['Item']['name_zh'] + " " + res["body"]["Results"][i]['Item']['brand_zh'] + " " + res["body"]["Results"][i]['Item']['model_zh'] + " " + res["body"]["Results"][i]['Item']['specification_zh']
125
+ label = {"label" :res["body"]["Results"][i]['Item']['sku_zh'], "score" : res["body"]["Results"][i]['Score']}
126
+ labels.append(copy.deepcopy(label))
127
+ return labels
128
+
129
+
130
+
131
+ def do_waterlevellineres_list(res, info):
132
+ """
133
+ 获取结果,并组装水位线info
134
+ """
135
+ if res == '':
136
+ info['label'] = [{'label': '', 'score': 0}, {'label': '', 'score': 0}]
137
+ info['rt'] = False
138
+ return info
139
+
140
+
141
+ # 判断res["body"]["Results"]不为空,空则:label0 label1 为空,label默认2级
142
+ if res["body"]["Results"]:
143
+ # 取["Results"]下前2个结果,若只有1个结果,label1为空
144
+ if len(res["body"]["Results"]) > 1:
145
+ info['label'] = [
146
+ {'label': res["body"]["Results"][0]['Item']['name_zh'],
147
+ 'score': res["body"]["Results"][0]['Score']},
148
+ {'label': res["body"]["Results"][1]['Item']['name_zh'],
149
+ 'score': res["body"]["Results"][1]['Score']}]
150
+
151
+ else:
152
+ info['label'] = [
153
+ {'label': res["body"]["Results"][0]['Item']['name_zh'],
154
+ 'score': res["body"]["Results"][0]['Score']},
155
+ {'label': '', 'score': 0}]
156
+ # 判断label0和label1是否为空,为空则:label默认2级
157
+ # 判断exp和label是否一致,一致则:rt=True,不一致则:rt=False
158
+ if info['exp'][0]['label'] == info['label'][0]['label'] and info['exp'][1]['label'] == info['label'][1][
159
+ 'label'] and info['exp'][0]['score'] <= info['label'][0]['score'] and info['exp'][1]['score'] <= \
160
+ info['label'][1]['score']:
161
+ info['rt'] = True
162
+ else:
163
+ info['rt'] = False
164
+
165
+ else:
166
+ info['label'] = info['label'] = [{'label': '', 'score': 0}, {'label': '', 'score': 0}]
167
+ info['rt'] = False
168
+
169
+ return info
170
+
171
+
172
+ def do_metricsevaluation_list(collections,data,score_threshold):
173
+ """
174
+ 指标 评测
175
+ """
176
+ info = {
177
+ "input": {
178
+ "用户输入/userInput": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
179
+ },
180
+ "output": {
181
+ "用户输入/output": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
182
+ },
183
+ "rt": True,
184
+ "label": [{"label": "GUI 软件申请", "score": 0.6}, {"label": "软件申请", "score": 0.5}],
185
+ "exp": [{"label": "GUI 软件申请", " score": 0.9}, {"label": "软件申请", "score": 0.8 }],
186
+ "artificial": []
187
+ }
188
+ info_list = []
189
+ businessscenario = []
190
+ for i in collections:
191
+ for j in data:
192
+ if i['content'] == j['用户输入/userInput']:
193
+ info['input']['用户输入/userInput'] = i['ext']['output']
194
+ info['output']['用户输入/output'] = j['用户输入/userInput']
195
+ if i['ext']['BPO标注-AP-分发技能'] != '' and i['ext']['BPO标注-AP-分发技能'] in j['分发技能/skill'][0]:
196
+ info['rt'] = True
197
+ info['label'] = [{'label': j['分发技能/skill'][0], 'score': score_threshold}]
198
+ info['exp'] = [{'label': j['分发技能/skill'][0], 'score': score_threshold}]
199
+ info['artificial'] = info['exp']
200
+ else:
201
+ info['rt'] = False
202
+ info['label'] = [{'label': j['分发技能/skill'][0], 'score': score_threshold}]
203
+ info['exp'] = [{'label': i['ext']['BPO标注-AP-分发技能'], 'score': score_threshold}]
204
+ info['artificial'] = info['exp']
205
+ if i['ext']['BPO标注-AP-分发技能'] not in businessscenario:
206
+ businessscenario.append(i['ext']['BPO标注-AP-分发技能'])
207
+ info_list.append(copy.deepcopy(info))
208
+ return info_list,businessscenario
209
+
210
+
211
+ def do_scenereview_list(collections,data,score_threshold):
212
+ """
213
+ 场景 评测 提取关键词
214
+ """
215
+ score_threshold=0.8
216
+ info = {
217
+ "input": {
218
+ "用户输入/userInput": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
219
+ },
220
+ "output": {
221
+ "用户输入/output": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
222
+ },
223
+ "rt": True,
224
+ "label": [{"label": "GUI 软件申请", "score": 0.6}, {"label": "软件申请", "score": 0.5}],
225
+ "exp": [{"label": "GUI 软件申请", " score": 0.9}, {"label": "软件申请", "score": 0.8 }],
226
+ "artificial": []
227
+ }
228
+ info_list = []
229
+ for i in collections:
230
+ for j in data:
231
+ if i['content'] == j['用户输入/userInput']:
232
+ info['input']['用户输入/userInput'] = i['ext']['output']
233
+ info['output']['用户输入/output'] = j['用户输入/userInput']
234
+ if i['ext']['BPO标注-AP-资产名称'] == j['llm关键词']:
235
+ info['rt'] = True
236
+ info['label'] = [{'label': str(j['llm关键词']), 'score': score_threshold}]
237
+ else:
238
+ info['rt'] = False
239
+ info['label'] = [{'label': str(i['ext']['BPO标注-AP-资产名称']), 'score': score_threshold}]
240
+ info['exp'] = [{'label': str(i['ext']['BPO标注-AP-资产名称']), 'score': score_threshold}]
241
+ info['artificial'] = info['exp']
242
+ info_list.append(copy.deepcopy(info))
243
+ return info_list
244
+
245
+ def do_waterlevelline_autotest(collections, clientinfo, score_threshold):
246
+ """
247
+ 水位线评测- 返回 符合报告模式的结果
248
+ """
249
+ keywprd= []
250
+ info_list = []
251
+ info = {
252
+ "input": {
253
+ "用户输入/userInput": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
254
+ },
255
+ "output": {
256
+ "用户输入/output": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
257
+ },
258
+ "rt": True,
259
+ "label": [{"label": "GUI 软件申请", "score": 0.6}, {"label": "软件申请", "score": 0.5}],
260
+ "exp": [{"label": "GUI 软件申请", " score": 0.9}, {"label": "软件申请", "score": 0.8
261
+ }],
262
+ "artificial": []
263
+ }
264
+ a =0
265
+ for i in collections:
266
+ info['input']['用户输入/userInput'] = i['ext']['BPO标注-AP-资产名称']
267
+ info['output']['用户输入/output'] = i['ext']['BPO标注-AP-资产名称']
268
+ info['exp'] = [
269
+ {'label': i['ext']['BPO标注-AP-资产型号'], 'score': score_threshold},
270
+ {'label': i['ext'].get('BPO标注-AP-资产型号1', ''), 'score': score_threshold}]
271
+ info['artificial'] = info['exp']
272
+ if i['ext']['BPO标注-AP-资产名称']:
273
+ if "软件申请" in i['ext']['BPO标注-AP-分发技能']:
274
+ keywprd = software_asset_sku_structure(json.loads(i['ext']['BPO标注-AP-资产名称']))
275
+ res = json.loads(get_query_vector(keywprd, clientinfo))
276
+ if "设备/配件申请" in i['ext']['BPO标注-AP-分发技能']:
277
+ keywprd = equipmentrequest_structure(json.loads(i['ext']['BPO标注-AP-资产名称']), i['ext']['asset_type'])
278
+ res0 = json.loads(get_query_vector(keywprd, clientinfo))
279
+ res = get_by_AssetModelBizTypes(keywprd,res0)
280
+ if "设备/配件退还" in i['ext']['BPO标注-AP-分发技能']:
281
+ keywprd = equipmentreturn_structure0(json.loads(i['ext']['BPO标注-AP-资产名称']), i['ext']['asset_type'])
282
+ res0 = json.loads(get_query_vector(keywprd, clientinfo))
283
+ res = get_by_AssetModelBizTypes(keywprd, res0)
284
+ else:
285
+ res = ""
286
+ infoout = do_waterlevellineres_list(res, info)
287
+ info_list.append(copy.deepcopy(infoout))
288
+ a = a+1
289
+ print("这是"+str(a))
290
+ bbb = a
291
+ return info_list
292
+
293
+
294
+ def get_conversationlogs1(startAt):
295
+ """
296
+ 对话ID 技能分发 用户输入
297
+ res_data = {
298
+ 'intentID': 7485259579248705537,
299
+ 'skillLabels': ["GUI 设备/配件申请"],
300
+ 'userInput': "我要申请一个鼠标",
301
+
302
+ }
303
+ """
304
+ data = webapiClient().get_intent_detail_list(startAt)
305
+
306
+
307
+ def get_conversationlogs(startAt, pageSize=10):
308
+ """
309
+ 对话ID 技能分发 用户输入
310
+ res_data = {
311
+ 'intentID': 7485259579248705537,
312
+ 'skillLabels': ["GUI 设备/配件申请"],
313
+ 'userInput': "我要申请一个鼠标",
314
+
315
+ }
316
+ """
317
+ try:
318
+ # 之前提到形参 'pageSize' 未填,这里假设默认值为 10,你可按需修改
319
+ data = webapiClient().get_intent_detail_list(startAt, pageSize=10)
320
+ return data
321
+ except KeyError as ke:
322
+ print(f"KeyError 发生: 数据中缺少必要的键,错误详情: {ke}")
323
+ return None
324
+ except IndexError as ie:
325
+ print(f"IndexError 发生: 索引超出范围,错误详情: {ie}")
326
+ return None
327
+ except Exception as e:
328
+ print(f"发生未知错误: {e}")
329
+ return None
330
+
331
+
332
+ def write_reslut(data, Testsuitelink, title):
333
+ """
334
+ 写入表格
335
+ """
336
+ try:
337
+ # 解析 spreadsheet_token
338
+ spreadsheet_token = Testsuitelink.split("/")[-1]
339
+
340
+ # 生成新工作表名称
341
+ new_sheet_title = f"{title}{datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')}"
342
+ sheetinfo = {"index": 0, "title": new_sheet_title}
343
+
344
+ # 创建新工作表
345
+ spreadsheet0 = LarkdocsClient().createsheets(spreadsheet_token, sheetinfo)
346
+ sheet_id = spreadsheet0['sheet_id']
347
+
348
+ # 准备表头数据
349
+ headers = list(data[0].keys())
350
+ header_data = [
351
+ {
352
+ "range": f"{sheet_id}!{chr(ord('A') + col)}1:{chr(ord('A') + col)}1",
353
+ "values": [[[{"text": {"text": header}, "type": "text"}]]]
354
+ }
355
+ for col, header in enumerate(headers)
356
+ ]
357
+
358
+ # 写入表头
359
+ LarkdocsClient().writesheets(spreadsheet_token, sheet_id, {"value_ranges": header_data})
360
+
361
+ # 写入数据
362
+ for row, row_data in enumerate(data, start=1):
363
+ row_values = [
364
+ {
365
+ "range": f"{sheet_id}!{chr(ord('A') + col)}{row + 1}:{chr(ord('A') + col)}{row + 1}",
366
+ "values": [[[{"text": {"text": str(row_data[header])}, "type": "text"}]]]
367
+ }
368
+ for col, header in enumerate(headers)
369
+ ]
370
+ LarkdocsClient().writesheets(spreadsheet_token, sheet_id, {"value_ranges": row_values})
371
+
372
+ return True
373
+ except KeyError as ke:
374
+ print(f"KeyError 发生: 数据中缺少必要的键,错误详情: {ke}")
375
+ return False
376
+ except IndexError as ie:
377
+ print(f"IndexError 发生: 索引超出范围,错误详情: {ie}")
378
+ return False
379
+ except Exception as e:
380
+ print(f"发生未知错误: {e}")
381
+ return False
382
+
383
+
384
+ def write_excletolist(data_name):
385
+ """
386
+ 1. 读取本地表格
387
+ 2. 将表格内容拼接为text
388
+ """
389
+ try:
390
+ # 查看当前工作目录
391
+ print(f"当前工作目录: {os.getcwd()}")
392
+ # /Users/bytedance/it_assistant/it_assistant/accessory.csv
393
+ # 构建文件路径
394
+ file_path = f'data/{data_name}.csv'
395
+ Candidates = []
396
+ Candidate = {
397
+ "Score": 0,
398
+ "Text": "IOS手机",
399
+ "Attrs": {"id": "", "type": ""}}
400
+ text = ""
401
+ with open(file_path, 'r', encoding='utf-8', newline='') as file:
402
+ reader = csv.reader(file)
403
+ headers = next(reader) # 读取表头
404
+ for header in headers:
405
+ text += f"{header}: "
406
+ text = text.rstrip(': ') + '\n'
407
+
408
+ for row in reader:
409
+ textout = ""
410
+ textout += ', '.join(row)
411
+ Candidate['Text'] = textout
412
+ Candidates.append(copy.deepcopy(Candidate))
413
+ return Candidates
414
+ except FileNotFoundError:
415
+ print(f"未找到文件: {file_path}")
416
+ return None
417
+ except Exception as e:
418
+ print(f"发生未知错误: {e}")
419
+ return None
420
+
421
+
422
+
423
+
424
+ if __name__ == '__main__':
425
+ clientinfo={
426
+ "Authorization": "Basic cm40cmFpdTRwenY1cGlsYTo2bWhvOXV3ZXFrOHZpbDllcXRxMHZ1YmVnc2xjeXBucg==",
427
+ "x_tt_env": "ppe_cn_env_self_test_feat_cr_a"
428
+ }
429
+
430
+
431
+ # 读取 CSV 文件
432
+ with open('/Users/bytedance/it_assistant/test.csv', mode='r', encoding='utf-8') as file:
433
+ csv_reader = csv.reader(file)
434
+ for row in csv_reader:
435
+
436
+ print(row)
437
+ parm = {
438
+ "From": 0,
439
+ "Size": 10,
440
+ "MinScore": 0.1,
441
+ "AssetModelFieldsWithOr": [
442
+ {
443
+ "FieldName": "vec_name",
444
+ "FieldType": "knn",
445
+ "QueryValue": row
446
+ },
447
+ {
448
+ "FieldName": "vec_brand",
449
+ "FieldType": "knn",
450
+ "QueryValue": row
451
+ },
452
+ {
453
+ "FieldName": "vec_specification",
454
+ "FieldType": "knn",
455
+ "QueryValue": row
456
+ },
457
+ {
458
+ "FieldName": "vec_model_name",
459
+ "FieldType": "knn",
460
+ "QueryValue": row
461
+ }
462
+ ],
463
+ "AssetModelBizTypes": ["asset_sku"]
464
+ }
465
+ # 每一行是一个列表
466
+
467
+ info={
468
+ "score":0.8,
469
+ "itams": ""
470
+ }
471
+ info_list = []
472
+
473
+ cccc = get_query_vector(parm,clientinfo)
474
+ bbbb = json.loads(cccc)['body']['Results']
475
+ bbbb[0]['Score']
476
+ #将bbbb[0]['Score']写入test.csv的score0列
477
+
478
+
479
+
480
+ for i in bbbb:
481
+ info['score']=i['Score']/4
482
+ info['itams']=i['Item']['brand_zh']+i['Item']['model_zh']+i['Item']['specification_zh']
483
+
484
+
485
+
486
+
487
+
488
+
489
+
490
+