itam-assistant 0.1.4__py3-none-any.whl → 0.1.6__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.
@@ -0,0 +1,933 @@
1
+ # -*- coding: utf-8 -*-
2
+ import time
3
+ from itam_assistant.ailyapp_client import AilyLarkClient
4
+ from itam_assistant.lark_client import LarkdocsClient
5
+ from itam_assistant.intent_detail import *
6
+ from itam_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
+ # 判断Testsuitelink中是否包含https://
25
+ if "https://" in Testk_data:
26
+
27
+ # 通过文档链接获取spreadsheet_token
28
+ spreadsheet_token = Testk_data.split("/")[-1]
29
+ if not spreadsheet_token:
30
+ raise ValueError("未能从文档链接中提取到有效的spreadsheet_token")
31
+ # 读取表格用户输入
32
+ spreadsheet = LarkdocsClient().get_the_worksheet(spreadsheet_token)
33
+ if not spreadsheet:
34
+ raise ValueError("未能获取到有效的工作表数据")
35
+ for i in spreadsheet.sheets:
36
+ column_count = i.grid_properties.column_count
37
+ row_count = i.grid_properties.row_count
38
+ sheet_id = i.sheet_id
39
+ title = i.title
40
+ if title == "测试集":
41
+ # 构建JSON字符串
42
+ json_str = {"ranges": [sheet_id + "!A1:A" + str(row_count)]}
43
+ # 获取纯文本内容
44
+ test = LarkdocsClient().get_plaintextcontent(json_str, spreadsheet_token, sheet_id)
45
+ test = json.loads(test)
46
+ userinput = test['data']['value_ranges'][0]['values']
47
+ print(f"表头为{userinput[0]}")
48
+ # 获取租户访问令牌
49
+ tenant_access_token = AilyLarkClient(clientinfo).get_tenant_access_token()
50
+ if not tenant_access_token:
51
+ raise ValueError("未能获取到有效的租户访问令牌")
52
+ for i in range(1, row_count):
53
+ if userinput[i][0]:
54
+ if startAt == 0:
55
+ startAt = int(time.time())
56
+ # 创建会话
57
+ seseion_id = AilyLarkClient(clientinfo).create_ailysession(tenant_access_token)
58
+ if not seseion_id:
59
+ raise ValueError("未能成功创建会话")
60
+ # 创建消息
61
+ message_id = AilyLarkClient(clientinfo).create_ailysessionaily_message(tenant_access_token,
62
+ seseion_id,
63
+ userinput[i][0])
64
+ if not message_id:
65
+ raise ValueError("未能成功创建消息")
66
+ # 创建运行实例
67
+ runs = AilyLarkClient(clientinfo).create_ailysession_run(tenant_access_token, seseion_id)
68
+ # 可不需等待运行实例创建完成
69
+ # if not runs:
70
+ # raise ValueError("未能成功创建运行实例")
71
+ time.sleep(5)
72
+ else:
73
+ return startAt, i
74
+ break
75
+ return startAt, row_count
76
+ break
77
+ elif Testk_data[0].get('ext'):
78
+ num = 0
79
+ for i in Testk_data:
80
+ # 获取租户访问令牌
81
+ tenant_access_token = AilyLarkClient(clientinfo).get_tenant_access_token()
82
+ if not tenant_access_token:
83
+ raise ValueError("未能获取到有效的租户访问令牌")
84
+ aa = i['ext']['input']
85
+ if startAt == 0:
86
+ startAt = int(time.time())
87
+ # 创建会话
88
+ seseion_id = AilyLarkClient(clientinfo).create_ailysession(tenant_access_token)
89
+ time.sleep(10)
90
+ if not seseion_id:
91
+ raise ValueError("未能成功创建会话")
92
+ # 创建消息
93
+ message_id = AilyLarkClient(clientinfo).create_ailysessionaily_message(tenant_access_token, seseion_id,
94
+ aa)
95
+ time.sleep(5)
96
+ if not message_id:
97
+ raise ValueError("未能成功创建消息")
98
+ # 创建运行实例
99
+ runs = AilyLarkClient(clientinfo).create_ailysession_run(tenant_access_token, seseion_id)
100
+ time.sleep(5)
101
+ num = num + 1
102
+ return startAt, num
103
+ except KeyError as ke:
104
+ print(f"KeyError 发生: 数据中缺少必要的键,错误详情: {ke}")
105
+ return None, None
106
+ except json.JSONDecodeError as jde:
107
+ print(f"JSON 解析错误: {jde}")
108
+ return None, None
109
+ except ValueError as ve:
110
+ print(f"值错误: {ve}")
111
+ return None, None
112
+ except Exception as e:
113
+ print(f"发生未知错误: {e}")
114
+ return None, None
115
+
116
+
117
+ def get_results(num,res):
118
+ """
119
+ 获取结果
120
+ """
121
+ labels = []
122
+ a = len(res["body"]["Results"])
123
+ #判断res["body"]["Results"]的个数,如果大于num,则取num个值,小于num,则取res["body"]["Results"]的个数
124
+ if a > num:
125
+ num = num
126
+ else:
127
+ num = a
128
+ #提取res["body"]["Results"]的前num个值
129
+ res["body"]["Results"] = res["body"]["Results"][:num]
130
+ #遍历res["body"]["Results"]提取 name_zh、brand_zh、model_zh、specification_zh 并拼接
131
+ for i in range(0, num):
132
+ 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']
133
+ label = {"label" :res["body"]["Results"][i]['Item']['sku_zh'], "score" : res["body"]["Results"][i]['Score']}
134
+ labels.append(copy.deepcopy(label))
135
+ return labels
136
+
137
+
138
+
139
+ def do_waterlevellineres_list(res, info):
140
+ """
141
+ 获取结果,并组装水位线info
142
+ """
143
+ if res == '':
144
+ info['label'] = [{'label': '', 'score': 0}, {'label': '', 'score': 0}]
145
+ info['rt'] = False
146
+ return info
147
+
148
+ # 判断res["body"]["Results"]不为空,空则:label0 label1 为空,label默认2级
149
+ if res["body"]["Results"]:
150
+ info['output']['用户输入/output']='log_id:'+res['log_id']
151
+ # 取["Results"]下前2个结果,若只有1个结果,label1为空
152
+ if len(res["body"]["Results"]) > 0:
153
+ for j in range(len(res["body"]["Results"])):
154
+ aaa = {'label': res["body"]["Results"][j]['Item']['name_zh']+"&"+res["body"]["Results"][j]['Item']['brand_zh']+"&"+res["body"]["Results"][j]['Item']['model_zh']+"&"+res["body"]["Results"][j]['Item']['specification_zh'],
155
+ 'score': res["body"]["Results"][j]['Score']}
156
+ info['label'].append(copy.deepcopy(aaa))
157
+ # 判断label0和label1是否为空,为空则:label默认2级
158
+ # 判断exp和label是否一致,一致则:rt=True,不一致则:rt=False
159
+ if info['exp'][0]['label'] == info['label'][0]['label'] and info['exp'][1]['label'] == info['label'][1][
160
+ 'label'] and info['exp'][0]['score'] <= info['label'][0]['score'] and info['exp'][1]['score'] <= \
161
+ info['label'][1]['score']:
162
+ info['rt'] = True
163
+ else:
164
+ info['rt'] = False
165
+
166
+ else:
167
+ info['label'] = info['label'] = [{'label': '', 'score': 0}, {'label': '', 'score': 0}]
168
+ info['rt'] = False
169
+
170
+ return info
171
+
172
+ def do_waterlevellineres_listv2(res, info):
173
+ """
174
+ 获取结果,并组装水位线info
175
+ """
176
+ if res == '':
177
+ info['label'] = [{'label': '', 'score': 0}, {'label': '', 'score': 0}]
178
+ info['rt'] = False
179
+ return info
180
+ reslist = res["body"]["Results"]
181
+ info['output']['用户输入/output'] = 'log_id:' + res.get('log_id') or res.get('requestId')
182
+ if reslist:
183
+ #取所有结果并追加到info['label']
184
+ info['label'] = []
185
+ if len(reslist) > 0:
186
+ for j in range(len(reslist)):
187
+ aaa = {'label': reslist[j]['Item']['name_zh'],
188
+ 'score': reslist[j]['Score'],
189
+ 'info':reslist[j]['Item']['name_zh']+"&"+reslist[j]['Item']['brand_zh']+"&"+reslist[j]['Item']['model_zh']+"&"+reslist[j]['Item']['specification_zh'],}
190
+ info['label'].append(copy.deepcopy(aaa))
191
+ # 判断exp和label是否一致,一致则:rt=True,不一致则:rt=False
192
+ for a in range(len(info['exp'])):
193
+ if info['exp'][a]['label']== info['label'][a]['label']:
194
+ info['rt'] = True
195
+ else:
196
+ info['rt'] = False
197
+ break
198
+ else:
199
+ info['label'] = info['label'] = [{'label': '', 'score': 0}, {'label': '', 'score': 0}]
200
+ info['rt'] = False
201
+
202
+ return info
203
+
204
+ def do_waterlevellineres_listassetspu(res, info,hardtype):
205
+ """
206
+ 获取结果,并组装水位线info
207
+ """
208
+ if res == '':
209
+ info['label'] = [{'label': '', 'score': 0}]
210
+ info['rt'] = False
211
+ return info
212
+ if res["data"].get("AiBorrowAndUseResponseList") == None:
213
+ info['label'] = [{'label': '', 'score': 0},{'label': '', 'score': 0.8}]
214
+ info['rt'] = False
215
+ if info['exp']==[]:
216
+ info['rt'] = True
217
+ return info
218
+ reslist=res["data"]["AiBorrowAndUseResponseList"]
219
+ info['output']['用户输入/output']='requestId:'+res['requestId']
220
+ aaa ={}
221
+ # 判断res["body"]["Results"]不为空,空则:label0 label1 为空,label默认2级
222
+ if reslist:
223
+ # 取["Results"]下前2个结果,若只有1个结果,label1为空
224
+ if len(reslist) > 0:
225
+ for j in range(len(reslist)):
226
+ if hardtype==2:
227
+ aaa = {'label': reslist[j]['AccessoryModelScope']['AccessoryModelInfo']['Name']['ValueZh'],
228
+ 'score': reslist[j]['Score']}
229
+ info['label'].append(copy.deepcopy(aaa))
230
+ if hardtype == 1:
231
+ aaa = {'label': reslist[j]['AssetModelScope']['SpuNameZh'] or reslist[j]['AssetModelScope']['NameZh']+reslist[j]['AssetModelScope']['ModelZh']+reslist[j]['AssetModelScope']['SpecificationZh'],
232
+ 'score': reslist[j]['Score']}
233
+ info['label'].append(copy.deepcopy(aaa))
234
+ # 判断label0和label1是否为空,为空则:label默认2级
235
+ for a in range(len(info['exp'])):
236
+ if info['exp'][a]['label'] == info['label'][a]['label']:
237
+ info['rt'] = True
238
+ else:
239
+ info['rt'] = False
240
+ break
241
+ else:
242
+ info['label'] = info['label'] = [{'label': '', 'score': 0}, {'label': '', 'score': 0}]
243
+ info['rt'] = False
244
+ return info
245
+
246
+ def do_waterlevellineres_listassetspu_pre(res, info,hardtype):
247
+ """
248
+ 获取结果,并组装水位线info
249
+ """
250
+ if res == '':
251
+ info['label'] = [{'label': '', 'score': 0}]
252
+ info['rt'] = False
253
+ return info
254
+ if res.get("body") == None:
255
+ info['label'] = [{'label': '', 'score': 0},{'label': '', 'score': 0.8}]
256
+ info['rt'] = False
257
+ if info['exp'][0]['label']=='':
258
+ info['rt'] = True
259
+ return info
260
+ reslist=res["body"]
261
+ aaa ={}
262
+ # 判断res["body"]["Results"]不为空,空则:label0 label1 为空,label默认2级
263
+ if reslist:
264
+ # 取["Results"]下前2个结果,若只有1个结果,label1为空
265
+ if len(reslist) > 0:
266
+ for j in range(len(reslist)):
267
+ if hardtype==2:
268
+ aaa = {'label': reslist[j]['AccessoryModelScope']['AccessoryModelInfo']['Name']['ValueZh'],
269
+ 'score': reslist[j]['Score']}
270
+ info['label'].append(copy.deepcopy(aaa))
271
+ if hardtype == 1:
272
+ aaa = {'label': reslist[j]['Item']['name_zh']+reslist[j]['Item']['brand_zh']+reslist[j]['Item']['model_zh']+reslist[j]['Item']['specification_zh'],
273
+ 'score': reslist[j]['Score']}
274
+ info['label'].append(copy.deepcopy(aaa))
275
+ # 判断label0和label1是否为空,为空则:label默认2级
276
+ # 判断exp和label是否一致,一致则:rt=True,不一致则:rt=False
277
+ if info['exp'][0]['label'] == info['label'][0]['label'] and info['exp'][1]['label'] == info['label'][1][
278
+ 'label'] and info['exp'][0]['score'] <= info['label'][0]['score'] and info['exp'][1]['score'] <= \
279
+ info['label'][1]['score']:
280
+ info['rt'] = True
281
+ else:
282
+ info['rt'] = False
283
+ else:
284
+ info['label'] = info['label'] = [{'label': '', 'score': 0}, {'label': '', 'score': 0}]
285
+ info['rt'] = False
286
+ return info
287
+
288
+ def do_waterlevellineres_sr(res, info,hardtype):
289
+ """
290
+ 获取结果,并组装水位线info
291
+ """
292
+ if res == '':
293
+ info['label'] = [{'label': '', 'score': 0}]
294
+ info['rt'] = False
295
+ return info
296
+ if res["data"].get("AiBorrowAndUseResponseList") == None:
297
+ info['label'] = [{'label': '', 'score': 0},{'label': '', 'score': 0.8}]
298
+ info['rt'] = False
299
+ if info['exp'][0]['label']=='':
300
+ info['rt'] = True
301
+ return info
302
+ reslist=res["data"]["AssetModels"]
303
+ aaa ={}
304
+ # 判断res["body"]["Results"]不为空,空则:label0 label1 为空,label默认2级
305
+ if reslist:
306
+ # 取["Results"]下前2个结果,若只有1个结果,label1为空
307
+ if len(reslist) > 0:
308
+ for j in range(len(reslist)):
309
+ if hardtype==2:
310
+ aaa = {'label': reslist[j]['AccessoryModelScope']['AccessoryModelInfo']['Name']['ValueZh'],
311
+ 'score': reslist[j]['Score']}
312
+ info['label'].append(copy.deepcopy(aaa))
313
+ if hardtype == 1:
314
+ aaa = {'label': reslist[j]['SpuNameZh'] or reslist[j]['NameZh']+reslist[j]['ModelZh']+reslist[j]['SpecificationZh'],
315
+ 'score': 0.5}
316
+ info['label'].append(copy.deepcopy(aaa))
317
+ # 判断label0和label1是否为空,为空则:label默认2级
318
+ # 判断exp和label是否一致,一致则:rt=True,不一致则:rt=False
319
+ if info['exp'][0]['label'] == info['label'][0]['label'] and info['exp'][1]['label'] == info['label'][1][
320
+ 'label'] and info['exp'][0]['score'] <= info['label'][0]['score'] and info['exp'][1]['score'] <= \
321
+ info['label'][1]['score']:
322
+ info['rt'] = True
323
+ else:
324
+ info['rt'] = False
325
+ else:
326
+ info['label'] = info['label'] = [{'label': '', 'score': 0}, {'label': '', 'score': 0}]
327
+ info['rt'] = False
328
+ return info
329
+
330
+
331
+ def do_metricsevaluation_list(collections,data,score_threshold):
332
+ """
333
+ 指标 评测
334
+ """
335
+ info = {
336
+ "input": {
337
+ "用户输入/userInput": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
338
+ },
339
+ "output": {
340
+ "用户输入/output": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
341
+ },
342
+ "rt": True,
343
+ "label": [{"label": "测试"}, {"label": "测试"}],
344
+ "exp": [{"label": "测试"}, {"label": "测试" }],
345
+ "artificial": []
346
+ }
347
+ info_list = []
348
+ businessscenario = []
349
+ for i in collections:
350
+ for j in data:
351
+ if i['content'] == j['用户输入/userInput']:
352
+ info = {
353
+ "input": {},
354
+ "output": {},
355
+ "rt": False,
356
+ "label": [{"label": "测试"}, {"label": "测试"}],
357
+ "exp": [{"label": "测试",}, {"label": "测试"}],
358
+ "artificial": []
359
+ }
360
+ info['input']['用户输入/userInput'] = i['ext']['output']
361
+ info['output']['用户输入/output'] = "对话id:"+j['对话日志/intentID']+" 对话内容:"+j['用户输入/userInput']
362
+ if i['ext']['BPO标注-AP-分发技能'] != '' and i['ext']['BPO标注-AP-分发技能'] in j['分发技能/skill'][0]:
363
+ info['rt'] = True
364
+ info['label'] = [{'label': j['分发技能/skill'][0]}]
365
+ info['exp'] = [{'label': j['分发技能/skill'][0]}]
366
+ info['artificial'] = info['exp']
367
+ else:
368
+ info['rt'] = False
369
+ info['label'] = [{'label': j['分发技能/skill'][0]}]
370
+ info['exp'] = [{'label': i['ext']['BPO标注-AP-分发技能']}]
371
+ info['artificial'] = info['exp']
372
+ if i['ext']['BPO标注-AP-分发技能'] not in businessscenario:
373
+ businessscenario.append(i['ext']['BPO标注-AP-分发技能'])
374
+ #将data中的j删除
375
+ data.remove(j)
376
+ break
377
+ info_list.append(copy.deepcopy(info))
378
+ return info_list,businessscenario
379
+
380
+
381
+ def do_scenereview_list(collections,data,score_threshold):
382
+ """
383
+ 场景 评测 提取关键词
384
+ """
385
+ score_threshold=0.8
386
+ info = {
387
+ "input": {
388
+ "用户输入/userInput": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
389
+ },
390
+ "output": {
391
+ "用户输入/output": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
392
+ },
393
+ "rt": True,
394
+ "label": [{"label": "GUI 软件申请", "score": 0.6}, {"label": "软件申请", "score": 0.5}],
395
+ "exp": [{"label": "GUI 软件申请", " score": 0.9}, {"label": "软件申请", "score": 0.8 }],
396
+ "artificial": []
397
+ }
398
+ info_list = []
399
+ for i in collections:
400
+ for j in data:
401
+ if i['content'] == j['用户输入/userInput']:
402
+ info['input']['用户输入/userInput'] = i['ext']['output']
403
+ info['output']['用户输入/output'] = j['用户输入/userInput']
404
+ if i['ext']['BPO标注-AP-资产名称'] == j['llm关键词']:
405
+ info['rt'] = True
406
+ info['label'] = [{'label': str(j['llm关键词']), 'score': score_threshold}]
407
+ else:
408
+ info['rt'] = False
409
+ info['label'] = [{'label': str(i['ext']['BPO标注-AP-资产名称']), 'score': score_threshold}]
410
+ info['exp'] = [{'label': str(i['ext']['BPO标注-AP-资产名称']), 'score': score_threshold}]
411
+ info['artificial'] = info['exp']
412
+ info_list.append(copy.deepcopy(info))
413
+ return info_list
414
+
415
+ def do_waterlevelline_autotest(collections, clientinfo, score_threshold):
416
+ """
417
+ 水位线评测- 返回 符合报告模式的结果
418
+ """
419
+ keywprd= []
420
+ info_list = []
421
+ info = {
422
+ "input": {
423
+ "用户输入/userInput": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
424
+ },
425
+ "output": {
426
+ "用户输入/output": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
427
+ },
428
+ "rt": True,
429
+ "label": [{"label": "GUI 软件申请", "score": 0.6}, {"label": "软件申请", "score": 0.5}],
430
+ "exp": [{"label": "GUI 软件申请", " score": 0.9}, {"label": "软件申请", "score": 0.8
431
+ }],
432
+ "artificial": []
433
+ }
434
+ a =0
435
+ for i in collections:
436
+ info['input']['用户输入/userInput'] = i['ext']['BPO标注-AP-资产名称']
437
+ info['output']['用户输入/output'] = i['ext']['BPO标注-AP-资产名称']
438
+ info['exp'] = []
439
+ for j in [i['ext']['BPO标注-AP-资产型号'], i['ext'].get('BPO标注-AP-资产型号1'),i['ext'].get('BPO标注-AP-资产型号2'),i['ext'].get('BPO标注-AP-资产型号3'),i['ext'].get('BPO标注-AP-资产型号4'),i['ext'].get('BPO标注-AP-资产型号5'),i['ext'].get('BPO标注-AP-资产型号6'),i['ext'].get('BPO标注-AP-资产型号7'),i['ext'].get('BPO标注-AP-资产型号8'),i['ext'].get('BPO标注-AP-资产型号9'),i['ext'].get('BPO标注-AP-资产型号10')]:
440
+ if j:
441
+ info['exp'].append({'label': j, 'score': score_threshold})
442
+ #判断i['ext']['BPO标注-AP-资产型号']是否为空,为空就不用读取,不为空就读取
443
+ if i['ext']['BPO标注-AP-资产型号']:
444
+ asset_name = i['ext']['BPO标注-AP-资产名称']
445
+ try:
446
+ if isinstance(asset_name, str):
447
+ asset_name = json.loads(asset_name)
448
+ except json.JSONDecodeError:
449
+ # 若解析失败,说明不是 JSON 格式,保持原样
450
+ pass
451
+ info['artificial'] = info['exp']
452
+ if i['ext']['BPO标注-AP-资产名称']:
453
+ asset_name = i['ext']['BPO标注-AP-资产名称']
454
+ try:
455
+ if isinstance(asset_name, str):
456
+ asset_name = json.loads(asset_name)
457
+ except json.JSONDecodeError:
458
+ # 若解析失败,说明不是 JSON 格式,保持原样
459
+ pass
460
+ if "软件申请" in i['ext']['BPO标注-AP-分发技能']:
461
+ keywprd = software_asset_sku_structure(asset_name)
462
+ res = json.loads(get_query_vector(keywprd, clientinfo))
463
+ if "设备/配件申请" in i['ext']['BPO标注-AP-分发技能']:
464
+ #keywprd = equipmentrequest_structure(asset_name, i['ext']['asset_type'])
465
+ keywprd = {
466
+ "From": 0,
467
+ "Size": 10,
468
+ "MinScore": 0.7,
469
+ "AssetModelFieldsWithAnd": [
470
+ {
471
+ "FieldName": "vec_search",
472
+ "FieldType": "knn",
473
+ "QueryValue": [
474
+ asset_name
475
+ ]
476
+ }
477
+ ],
478
+ "SPUIDs": None,
479
+ "AssetModelBizTypes": [
480
+ "asset_sku"
481
+ ]
482
+ }
483
+ res = json.loads(get_query_vector(keywprd, clientinfo))
484
+ #res = get_by_AssetModelBizTypes(keywprd,res0)
485
+ if "设备/配件退还" in i['ext']['BPO标注-AP-分发技能']:
486
+ keywprd = equipmentreturn_structure0(asset_name, i['ext']['asset_type'])
487
+ res0 = json.loads(get_query_vector(keywprd, clientinfo))
488
+ res = get_by_AssetModelBizTypes(keywprd, res0)
489
+ else:
490
+ res = ""
491
+ infoout = do_waterlevellineres_listv2(res, info)
492
+ info_list.append(copy.deepcopy(infoout))
493
+ a = a+1
494
+ print("这是"+str(a))
495
+ bbb = a
496
+ return info_list
497
+
498
+ def do_waterlevelline_autotest_aseetspu(collections, clientinfo, score_threshold):
499
+ """
500
+ 水位线评测- 返回 符合报告模式的结果
501
+ """
502
+ keywprd= []
503
+ info_list = []
504
+ info = {
505
+ "input": {
506
+ "用户输入/userInput": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
507
+ },
508
+ "output": {
509
+ "用户输入/output": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
510
+ },
511
+ "rt": True,
512
+ "label": [{"label": "GUI 软件申请", "score": 0.6}, {"label": "软件申请", "score": 0.5}],
513
+ "exp": [{"label": "GUI 软件申请", " score": 0.9}, {"label": "软件申请", "score": 0.8
514
+ }],
515
+ "artificial": []
516
+ }
517
+ a =0
518
+ for i in collections:
519
+ info['input']['用户输入/userInput'] = i['ext']['BPO标注-AP-资产名称']
520
+ info['output']['用户输入/output'] = i['ext']['BPO标注-AP-资产名称']
521
+ info['exp'] = []
522
+ for j in [i['ext']['BPO标注-AP-资产型号'], i['ext'].get('BPO标注-AP-资产型号1'),
523
+ i['ext'].get('BPO标注-AP-资产型号2'), i['ext'].get('BPO标注-AP-资产型号3'),
524
+ i['ext'].get('BPO标注-AP-资产型号4'), i['ext'].get('BPO标注-AP-资产型号5'),
525
+ i['ext'].get('BPO标注-AP-资产型号6'), i['ext'].get('BPO标注-AP-资产型号7'),
526
+ i['ext'].get('BPO标注-AP-资产型号8'), i['ext'].get('BPO标注-AP-资产型号9'),
527
+ i['ext'].get('BPO标注-AP-资产型号10')]:
528
+ if j:
529
+ info['exp'].append({'label': j, 'score': score_threshold})
530
+ info['artificial'] = info['exp']
531
+ info['label']=[]
532
+ if i['ext']['BPO标注-AP-资产名称']:
533
+ if "设备" in i['ext']['BPO标注-AP-分发技能'] or "配件" in i['ext']['BPO标注-AP-分发技能']:
534
+ asset_name = i['ext']['BPO标注-AP-资产名称']
535
+ try:
536
+ # 尝试将其解析为 JSON 对象
537
+ if isinstance(asset_name, str):
538
+ asset_name0 = json.loads(asset_name)
539
+ asset_name = asset_name0['asset_name']
540
+ except json.JSONDecodeError:
541
+ # 若解析失败,说明不是 JSON 格式,保持原样
542
+ pass
543
+ key = asset_name.get('asset_name') if isinstance(asset_name, dict) else asset_name
544
+ if i['ext']['BPO标注-AP-资产类型'] == "设备":
545
+ hardtype = 1
546
+ elif i['ext']['BPO标注-AP-资产类型'] == "配件" or i['ext']['BPO标注-AP-资产类型'] == '2.0' :
547
+ hardtype = 2
548
+ res = GetBestMatchItemonline(key,hardtype,clientinfo)
549
+ else:
550
+ res = ""
551
+ infoout = do_waterlevellineres_listassetspu(res, info,hardtype)
552
+ info_list.append(copy.deepcopy(infoout))
553
+ a = a+1
554
+ print("这是"+str(a))
555
+ bbb = a
556
+ return info_list
557
+
558
+ def do_waterlevelline_autotest_aseetspu_old(collections, clientinfo, score_threshold):
559
+ """
560
+ 水位线评测- 返回 符合报告模式的结果
561
+ """
562
+ keywprd= []
563
+ info_list = []
564
+ info = {
565
+ "input": {
566
+ "用户输入/userInput": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
567
+ },
568
+ "output": {
569
+ "用户输入/output": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
570
+ },
571
+ "rt": True,
572
+ "label": [{"label": "GUI 软件申请", "score": 0.6}, {"label": "软件申请", "score": 0.5}],
573
+ "exp": [{"label": "GUI 软件申请", " score": 0.9}, {"label": "软件申请", "score": 0.8
574
+ }],
575
+ "artificial": []
576
+ }
577
+ a =0
578
+ for i in collections:
579
+ info['input']['用户输入/userInput'] = i['ext']['BPO标注-AP-资产名称']
580
+ info['output']['用户输入/output'] = i['ext']['BPO标注-AP-资产名称']
581
+ info['exp'] = [
582
+ {'label': i['ext']['BPO标注-AP-资产型号'], 'score': score_threshold},
583
+ {'label': i['ext'].get('BPO标注-AP-资产型号1', ''), 'score': score_threshold}]
584
+ info['artificial'] = info['exp']
585
+ info['label']=[]
586
+ if i['ext']['BPO标注-AP-资产名称']:
587
+ if "设备" in i['ext']['BPO标注-AP-分发技能'] or "配件" in i['ext']['BPO标注-AP-分发技能']:
588
+ asset_name = i['ext']['BPO标注-AP-资产名称']
589
+ asset_name = i['ext']['BPO标注-AP-资产类型']
590
+ try:
591
+ # 尝试将其解析为 JSON 对象
592
+ if isinstance(asset_name, str):
593
+ asset_name = json.loads(asset_name)
594
+ except json.JSONDecodeError:
595
+ # 若解析失败,说明不是 JSON 格式,保持原样
596
+ pass
597
+ key = asset_name.get('asset_name') if isinstance(asset_name, dict) else asset_name
598
+ if i['ext']['BPO标注-AP-资产型号'] == "设备":
599
+ hardtype = 1
600
+ elif i['ext']['BPO标注-AP-资产型号'] == "配件" :
601
+ hardtype = 2
602
+ res = GetBestMatchItemonline_old(key,hardtype,clientinfo)
603
+ else:
604
+ res = ""
605
+ infoout = do_waterlevellineres_listassetspu(res, info,hardtype)
606
+ info_list.append(copy.deepcopy(infoout))
607
+ a = a+1
608
+ print("这是"+str(a))
609
+ bbb = a
610
+ return info_list
611
+
612
+
613
+ def do_waterlevelline_autotest_aseetspu_pre(collections, clientinfo, score_threshold):
614
+ """
615
+ 水位线评测- 返回 符合报告模式的结果
616
+ """
617
+ keywprd= []
618
+ info_list = []
619
+ info = {
620
+ "input": {
621
+ "用户输入/userInput": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
622
+ },
623
+ "output": {
624
+ "用户输入/output": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
625
+ },
626
+ "rt": True,
627
+ "label": [{"label": "GUI 软件申请", "score": 0.6}, {"label": "软件申请", "score": 0.5}],
628
+ "exp": [{"label": "GUI 软件申请", " score": 0.9}, {"label": "软件申请", "score": 0.8
629
+ }],
630
+ "artificial": []
631
+ }
632
+ a =0
633
+ for i in collections:
634
+ info['input']['用户输入/userInput'] = i['ext']['BPO标注-AP-资产名称']
635
+ info['output']['用户输入/output'] = i['ext']['BPO标注-AP-资产名称']
636
+ info['exp'] = [
637
+ {'label': i['ext']['BPO标注-AP-资产型号'], 'score': score_threshold},
638
+ {'label': i['ext'].get('BPO标注-AP-资产型号1', ''), 'score': score_threshold}]
639
+ info['artificial'] = info['exp']
640
+ info['label']=[]
641
+ if i['ext']['BPO标注-AP-资产名称']:
642
+ if "设备" in i['ext']['BPO标注-AP-分发技能'] or "配件" in i['ext']['BPO标注-AP-分发技能']:
643
+ asset_name = i['ext']['BPO标注-AP-资产名称']
644
+ asset_name = i['ext']['BPO标注-AP-资产类型']
645
+ try:
646
+ # 尝试将其解析为 JSON 对象
647
+ if isinstance(asset_name, str):
648
+ asset_name = json.loads(asset_name)
649
+ except json.JSONDecodeError:
650
+ # 若解析失败,说明不是 JSON 格式,保持原样
651
+ pass
652
+ key = asset_name.get('asset_name') if isinstance(asset_name, dict) else asset_name
653
+ if i['ext']['BPO标注-AP-资产型号'] == "设备":
654
+ hardtype = 1
655
+ elif i['ext']['BPO标注-AP-资产型号'] == "配件" :
656
+ hardtype = 2
657
+ res = test_hardware_match(key,hardtype,clientinfo)
658
+ else:
659
+ res = ""
660
+ infoout = do_waterlevellineres_listassetspu_pre(res, info,hardtype)
661
+ info_list.append(copy.deepcopy(infoout))
662
+ a = a+1
663
+ print("这是"+str(a))
664
+ bbb = a
665
+ return info_list
666
+
667
+ def do_waterlevelline_autotest_search(collections, clientinfo, score_threshold):
668
+ """
669
+ 水位线评测- 返回 符合报告模式的结果
670
+ """
671
+ keywprd= []
672
+ info_list = []
673
+ info = {
674
+ "input": {
675
+ "用户输入/userInput": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
676
+ },
677
+ "output": {
678
+ "用户输入/output": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
679
+ },
680
+ "rt": True,
681
+ "label": [{"label": "GUI 软件申请", "score": 0.6}, {"label": "软件申请", "score": 0.5}],
682
+ "exp": [{"label": "GUI 软件申请", " score": 0.9}, {"label": "软件申请", "score": 0.8
683
+ }],
684
+ "artificial": []
685
+ }
686
+ a =0
687
+ for i in collections:
688
+ info['input']['用户输入/userInput'] = i['ext']['BPO标注-AP-资产名称']
689
+ info['output']['用户输入/output'] = i['ext']['BPO标注-AP-资产名称']
690
+ info['exp'] = [
691
+ {'label': i['ext']['BPO标注-AP-资产型号'], 'score': score_threshold},
692
+ {'label': i['ext'].get('BPO标注-AP-资产型号1', ''), 'score': score_threshold}]
693
+ info['artificial'] = info['exp']
694
+ info['label']=[]
695
+ if i['ext']['BPO标注-AP-资产名称']:
696
+ if "设备" in i['ext']['BPO标注-AP-分发技能'] or "配件" in i['ext']['BPO标注-AP-分发技能']:
697
+ asset_name = i['ext']['BPO标注-AP-资产名称']
698
+ asset_name = i['ext']['BPO标注-AP-资产类型']
699
+ try:
700
+ # 尝试将其解析为 JSON 对象
701
+ if isinstance(asset_name, str):
702
+ asset_name = json.loads(asset_name)
703
+ except json.JSONDecodeError:
704
+ # 若解析失败,说明不是 JSON 格式,保持原样
705
+ pass
706
+ key = asset_name.get('asset_name') if isinstance(asset_name, dict) else asset_name
707
+ if i['ext']['BPO标注-AP-资产型号'] == "设备":
708
+ hardtype = 1
709
+ elif i['ext']['BPO标注-AP-资产型号'] == "配件" :
710
+ hardtype = 2
711
+ res = searchListAssetModelScope(key,hardtype,clientinfo)
712
+ else:
713
+ res = ""
714
+ infoout = do_waterlevellineres_sr(res, info,hardtype)
715
+ info_list.append(copy.deepcopy(infoout))
716
+ a = a+1
717
+ print("这是"+str(a))
718
+ bbb = a
719
+ return info_list
720
+
721
+
722
+ def do_waterlevelline_autotest_SoftwareApplyRecommendList(collections, clientinfo, score_threshold):
723
+ """
724
+ 水位线评测- 返回 符合报告模式的结果
725
+ """
726
+ keywprd= []
727
+ info_list = []
728
+ info = {
729
+ "input": {
730
+ "用户输入/userInput": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
731
+ },
732
+ "output": {
733
+ "用户输入/output": "我要申请软件,名字叫:ai_xzh_all_restricted_software完全受限软件"
734
+ },
735
+ "rt": True,
736
+ "label": [{"label": "GUI 软件申请", "score": 0.6}, {"label": "软件申请", "score": 0.5}],
737
+ "exp": [{"label": "GUI 软件申请", " score": 0.9}, {"label": "软件申请", "score": 0.8
738
+ }],
739
+ "artificial": []
740
+ }
741
+ a =0
742
+ for i in collections:
743
+ info['input']['用户输入/userInput'] = i['ext'].get('BP标注-AP-资产名称') or i['ext'].get('BPO标注-AP-资产名称')
744
+ info['output']['用户输入/output'] = i['ext']['BP标注-AP-资产名称']
745
+ info['exp'] = [
746
+ {'label': i['ext']['BP标注-AP-资产名称'], 'score': score_threshold},
747
+ {'label': i['ext'].get('BP标注-AP-资产型号1', ''), 'score': score_threshold}]
748
+ info['artificial'] = info['exp']
749
+ info['label']=[]
750
+ if i['ext']['BP标注-AP-资产名称']:
751
+ if "软件" in i['ext']['BP标注-AP-分发技能']:
752
+ asset_name = i['ext']['BP标注-AP-资产名称']
753
+ try:
754
+ # 尝试将其解析为 JSON 对象
755
+ if isinstance(asset_name, str):
756
+ asset_name = json.loads(asset_name)
757
+ except json.JSONDecodeError:
758
+ # 若解析失败,说明不是 JSON 格式,保持原样
759
+ pass
760
+ key = asset_name.get('asset_name') if isinstance(asset_name, dict) else asset_name
761
+ res = SoftwareApplyGetBestMatchItem(key,clientinfo)
762
+ else:
763
+ res = ""
764
+ infoout = do_waterlevellineres_software(res, info)
765
+ info_list.append(copy.deepcopy(infoout))
766
+ a = a+1
767
+ print("这是"+str(a))
768
+ bbb = a
769
+ return info_list
770
+
771
+
772
+ def do_waterlevellineres_software(res, info):
773
+ """
774
+ 获取结果,并组装水位线info
775
+ """
776
+ if res == '':
777
+ info['label'] = [{'label': '', 'score': 0}]
778
+ info['rt'] = False
779
+ return info
780
+ if res["data"].get("SoftwareApplyRecommendList") == None:
781
+ info['label'] = [{'label': '', 'score': 0},{'label': '', 'score': 0.8}]
782
+ info['rt'] = False
783
+ if info['exp'][0]['label']=='':
784
+ info['rt'] = True
785
+ return info
786
+ reslist=res["data"]["SoftwareApplyRecommendList"]
787
+ aaa ={}
788
+ # 判断res["body"]["Results"]不为空,空则:label0 label1 为空,label默认2级
789
+ if reslist:
790
+ # 取["Results"]下前2个结果,若只有1个结果,label1为空
791
+ if len(reslist) > 0:
792
+ for j in range(len(reslist)):
793
+ aaa = {'label': reslist[j]['Data']['Name']['ValueZh'],
794
+ 'score': reslist[j]['Score']}
795
+ info['label'].append(copy.deepcopy(aaa))
796
+ if info['exp'][0]['label'] == info['label'][0]['label'] and info['exp'][0]['score'] <= info['label'][0]['score']:
797
+ info['rt'] = True
798
+ else:
799
+ info['rt'] = False
800
+ else:
801
+ info['label'] = info['label'] = [{'label': '', 'score': 0}, {'label': '', 'score': 0}]
802
+ info['rt'] = False
803
+ return info
804
+
805
+ def get_conversationlogs1(startAt):
806
+ """
807
+ 对话ID 技能分发 用户输入
808
+ res_data = {
809
+ 'intentID': 7485259579248705537,
810
+ 'skillLabels': ["GUI 设备/配件申请"],
811
+ 'userInput': "我要申请一个鼠标",
812
+
813
+ }
814
+ """
815
+ data = webapiClient().get_intent_detail_list(startAt)
816
+
817
+
818
+ def get_conversationlogs(startAt, pageSize=10):
819
+ """
820
+ 对话ID 技能分发 用户输入
821
+ res_data = {
822
+ 'intentID': 7485259579248705537,
823
+ 'skillLabels': ["GUI 设备/配件申请"],
824
+ 'userInput': "我要申请一个鼠标",
825
+
826
+ }
827
+ """
828
+ try:
829
+ # 之前提到形参 'pageSize' 未填,这里假设默认值为 10,你可按需修改
830
+ data = webapiClient().get_intent_detail_list(startAt, pageSize=10)
831
+ return data
832
+ except KeyError as ke:
833
+ print(f"KeyError 发生: 数据中缺少必要的键,错误详情: {ke}")
834
+ return None
835
+ except IndexError as ie:
836
+ print(f"IndexError 发生: 索引超出范围,错误详情: {ie}")
837
+ return None
838
+ except Exception as e:
839
+ print(f"发生未知错误: {e}")
840
+ return None
841
+
842
+
843
+ def write_reslut(data, Testsuitelink, title):
844
+ """
845
+ 写入表格
846
+ """
847
+ try:
848
+ # 解析 spreadsheet_token
849
+ spreadsheet_token = Testsuitelink.split("/")[-1]
850
+
851
+ # 生成新工作表名称
852
+ new_sheet_title = f"{title}{datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')}"
853
+ sheetinfo = {"index": 0, "title": new_sheet_title}
854
+
855
+ # 创建新工作表
856
+ spreadsheet0 = LarkdocsClient().createsheets(spreadsheet_token, sheetinfo)
857
+ sheet_id = spreadsheet0['sheet_id']
858
+
859
+ # 准备表头数据
860
+ headers = list(data[0].keys())
861
+ header_data = [
862
+ {
863
+ "range": f"{sheet_id}!{chr(ord('A') + col)}1:{chr(ord('A') + col)}1",
864
+ "values": [[[{"text": {"text": header}, "type": "text"}]]]
865
+ }
866
+ for col, header in enumerate(headers)
867
+ ]
868
+
869
+ # 写入表头
870
+ LarkdocsClient().writesheets(spreadsheet_token, sheet_id, {"value_ranges": header_data})
871
+
872
+ # 写入数据
873
+ for row, row_data in enumerate(data, start=1):
874
+ row_values = [
875
+ {
876
+ "range": f"{sheet_id}!{chr(ord('A') + col)}{row + 1}:{chr(ord('A') + col)}{row + 1}",
877
+ "values": [[[{"text": {"text": str(row_data[header])}, "type": "text"}]]]
878
+ }
879
+ for col, header in enumerate(headers)
880
+ ]
881
+ LarkdocsClient().writesheets(spreadsheet_token, sheet_id, {"value_ranges": row_values})
882
+
883
+ return True
884
+ except KeyError as ke:
885
+ print(f"KeyError 发生: 数据中缺少必要的键,错误详情: {ke}")
886
+ return False
887
+ except IndexError as ie:
888
+ print(f"IndexError 发生: 索引超出范围,错误详情: {ie}")
889
+ return False
890
+ except Exception as e:
891
+ print(f"发生未知错误: {e}")
892
+ return False
893
+
894
+
895
+ def write_excletolist(data_name):
896
+ """
897
+ 1. 读取本地表格
898
+ 2. 将表格内容拼接为text
899
+ """
900
+ try:
901
+ # 查看当前工作目录
902
+ print(f"当前工作目录: {os.getcwd()}")
903
+ # /Users/bytedance/itam_assistant/itam_assistant/accessory.csv
904
+ # 构建文件路径
905
+ file_path = f'data/{data_name}.csv'
906
+ Candidates = []
907
+ Candidate = {
908
+ "Score": 0,
909
+ "Text": "IOS手机",
910
+ "Attrs": {"id": "", "type": ""}}
911
+ text = ""
912
+ with open(file_path, 'r', encoding='utf-8', newline='') as file:
913
+ reader = csv.reader(file)
914
+ headers = next(reader) # 读取表头
915
+ for header in headers:
916
+ text += f"{header}: "
917
+ text = text.rstrip(': ') + '\n'
918
+
919
+ for row in reader:
920
+ textout = ""
921
+ textout += ', '.join(row)
922
+ Candidate['Text'] = textout
923
+ Candidates.append(copy.deepcopy(Candidate))
924
+ return Candidates
925
+ except FileNotFoundError:
926
+ print(f"未找到文件: {file_path}")
927
+ return None
928
+ except Exception as e:
929
+ print(f"发生未知错误: {e}")
930
+ return None
931
+
932
+
933
+