pai_flow_operator2.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  1. # -*- coding: utf-8 -*-
  2. import os
  3. import re
  4. import time
  5. import json
  6. import pandas as pd
  7. from alibabacloud_paistudio20210202.client import Client as PaiStudio20210202Client
  8. from alibabacloud_tea_openapi import models as open_api_models
  9. from alibabacloud_paistudio20210202 import models as pai_studio_20210202_models
  10. from alibabacloud_tea_util import models as util_models
  11. from alibabacloud_tea_util.client import Client as UtilClient
  12. from alibabacloud_eas20210701.client import Client as eas20210701Client
  13. from alibabacloud_paiflow20210202 import models as paiflow_20210202_models
  14. from alibabacloud_paiflow20210202.client import Client as PAIFlow20210202Client
  15. from datetime import datetime, timedelta
  16. from odps import ODPS
  17. from ad_monitor_util import _monitor
  18. target_names = {
  19. '样本shuffle',
  20. '模型训练-样本shufle',
  21. '模型训练-自定义',
  22. '模型增量训练',
  23. '模型导出-2',
  24. '更新EAS服务(Beta)-1',
  25. '虚拟起始节点',
  26. '二分类评估-1',
  27. '二分类评估-2',
  28. '预测结果对比'
  29. }
  30. experiment_id = "draft-wqgkag89sbh9v1zvut"
  31. MAX_RETRIES = 3
  32. def retry(func):
  33. def wrapper(*args, **kwargs):
  34. retries = 0
  35. while retries < MAX_RETRIES:
  36. try:
  37. result = func(*args, **kwargs)
  38. if result is not False:
  39. return result
  40. except Exception as e:
  41. print(f"函数 {func.__name__} 执行时发生异常: {e},重试第 {retries + 1} 次")
  42. retries += 1
  43. print(f"函数 {func.__name__} 重试 {MAX_RETRIES} 次后仍失败。")
  44. return False
  45. return wrapper
  46. def get_odps_instance(project):
  47. odps = ODPS(
  48. access_id='LTAIWYUujJAm7CbH',
  49. secret_access_key='RfSjdiWwED1sGFlsjXv0DlfTnZTG1P',
  50. project=project,
  51. endpoint='http://service.cn.maxcompute.aliyun.com/api',
  52. )
  53. return odps
  54. def get_data_from_odps(project, table, num):
  55. odps = get_odps_instance(project)
  56. try:
  57. # 要查询的 SQL 语句
  58. sql = f'select * from {table} limit {num}'
  59. # 执行 SQL 查询
  60. with odps.execute_sql(sql).open_reader() as reader:
  61. df = reader.to_pandas()
  62. # 查询数量小于目标数量时 返回空
  63. if len(df) < num:
  64. return None
  65. return df
  66. except Exception as e:
  67. print(f"发生错误: {e}")
  68. def get_dict_from_odps(project, table):
  69. odps = get_odps_instance(project)
  70. try:
  71. # 要查询的 SQL 语句
  72. sql = f'select * from {table}'
  73. # 执行 SQL 查询
  74. with odps.execute_sql(sql).open_reader() as reader:
  75. data = {}
  76. for record in reader:
  77. record_list = list(record)
  78. key = record_list[0][1]
  79. value = record_list[1][1]
  80. data[key] = value
  81. return data
  82. except Exception as e:
  83. print(f"发生错误: {e}")
  84. def get_dates_between(start_date_str, end_date_str):
  85. start_date = datetime.strptime(start_date_str, '%Y%m%d')
  86. end_date = datetime.strptime(end_date_str, '%Y%m%d')
  87. dates = []
  88. current_date = start_date
  89. while current_date <= end_date:
  90. dates.append(current_date.strftime('%Y%m%d'))
  91. current_date += timedelta(days=1)
  92. return dates
  93. def read_file_to_list():
  94. try:
  95. current_dir = os.getcwd()
  96. file_path = os.path.join(current_dir, 'ad', 'holidays.txt')
  97. with open(file_path, 'r', encoding='utf-8') as file:
  98. content = file.read()
  99. return content.split('\n')
  100. except FileNotFoundError:
  101. raise Exception(f"错误:未找到 {file_path} 文件。")
  102. except Exception as e:
  103. raise Exception(f"错误:发生了一个未知错误: {e}")
  104. return []
  105. def get_previous_days_date(days):
  106. current_date = datetime.now()
  107. previous_date = current_date - timedelta(days=days)
  108. return previous_date.strftime('%Y%m%d')
  109. def remove_elements(lst1, lst2):
  110. return [element for element in lst1 if element not in lst2]
  111. def process_list(lst, append_str):
  112. # 给列表中每个元素拼接相同的字符串
  113. appended_list = [append_str + element for element in lst]
  114. # 将拼接后的列表元素用逗号拼接成一个字符串
  115. result_str = ','.join(appended_list)
  116. return result_str
  117. def get_train_data_list():
  118. start_date = '20250223'
  119. end_date = get_previous_days_date(2)
  120. date_list = get_dates_between(start_date, end_date)
  121. filter_date_list = read_file_to_list()
  122. date_list = remove_elements(date_list, filter_date_list)
  123. return date_list
  124. def update_train_tables(old_str):
  125. date_list = get_train_data_list()
  126. train_list = ["'" + item + "'" for item in date_list]
  127. result = ','.join(train_list)
  128. start_index = old_str.find('where dt in (')
  129. if start_index != -1:
  130. equal_sign_index = start_index + len('where dt in (')
  131. # 找到下一个双引号的位置
  132. next_quote_index = old_str.find(')', equal_sign_index)
  133. if next_quote_index != -1:
  134. # 进行替换
  135. new_value = old_str[:equal_sign_index] + result + old_str[next_quote_index:]
  136. return new_value
  137. return None
  138. def compare_timestamp_with_today_start(time_str):
  139. # 解析时间字符串为 datetime 对象
  140. time_obj = datetime.fromisoformat(time_str)
  141. # 将其转换为时间戳
  142. target_timestamp = time_obj.timestamp()
  143. # 获取今天开始的时间
  144. today_start = datetime.combine(datetime.now().date(), datetime.min.time())
  145. # 将今天开始时间转换为时间戳
  146. today_start_timestamp = today_start.timestamp()
  147. return target_timestamp > today_start_timestamp
  148. def update_train_table(old_str, table):
  149. address = 'odps://pai_algo/tables/'
  150. train_table = address + table
  151. start_index = old_str.find('-Dtrain_tables="')
  152. if start_index != -1:
  153. # 确定等号的位置
  154. equal_sign_index = start_index + len('-Dtrain_tables="')
  155. # 找到下一个双引号的位置
  156. next_quote_index = old_str.find('"', equal_sign_index)
  157. if next_quote_index != -1:
  158. # 进行替换
  159. new_value = old_str[:equal_sign_index] + train_table + old_str[next_quote_index:]
  160. return new_value
  161. return None
  162. class PAIClient:
  163. def __init__(self):
  164. pass
  165. @staticmethod
  166. def create_client() -> PaiStudio20210202Client:
  167. """
  168. 使用AK&SK初始化账号Client
  169. @return: Client
  170. @throws Exception
  171. """
  172. # 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
  173. # 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378659.html。
  174. config = open_api_models.Config(
  175. access_key_id="LTAI5tFGqgC8f3mh1fRCrAEy",
  176. access_key_secret="XhOjK9XmTYRhVAtf6yii4s4kZwWzvV"
  177. )
  178. # Endpoint 请参考 https://api.aliyun.com/product/PaiStudio
  179. config.endpoint = f'pai.cn-hangzhou.aliyuncs.com'
  180. return PaiStudio20210202Client(config)
  181. @staticmethod
  182. def create_eas_client() -> eas20210701Client:
  183. """
  184. 使用AK&SK初始化账号Client
  185. @return: Client
  186. @throws Exception
  187. """
  188. # 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
  189. # 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378659.html。
  190. config = open_api_models.Config(
  191. access_key_id="LTAI5tFGqgC8f3mh1fRCrAEy",
  192. access_key_secret="XhOjK9XmTYRhVAtf6yii4s4kZwWzvV"
  193. )
  194. # Endpoint 请参考 https://api.aliyun.com/product/PaiStudio
  195. config.endpoint = f'pai-eas.cn-hangzhou.aliyuncs.com'
  196. return eas20210701Client(config)
  197. @staticmethod
  198. def create_flow_client() -> PAIFlow20210202Client:
  199. """
  200. 使用AK&SK初始化账号Client
  201. @return: Client
  202. @throws Exception
  203. """
  204. # 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
  205. # 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378659.html。
  206. config = open_api_models.Config(
  207. # 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。,
  208. access_key_id="LTAI5tFGqgC8f3mh1fRCrAEy",
  209. # 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。,
  210. access_key_secret="XhOjK9XmTYRhVAtf6yii4s4kZwWzvV"
  211. )
  212. # Endpoint 请参考 https://api.aliyun.com/product/PAIFlow
  213. config.endpoint = f'paiflow.cn-hangzhou.aliyuncs.com'
  214. return PAIFlow20210202Client(config)
  215. @staticmethod
  216. def get_work_flow_draft_list(workspace_id: str):
  217. client = PAIClient.create_client()
  218. list_experiments_request = pai_studio_20210202_models.ListExperimentsRequest(
  219. workspace_id=workspace_id
  220. )
  221. runtime = util_models.RuntimeOptions()
  222. headers = {}
  223. try:
  224. resp = client.list_experiments_with_options(list_experiments_request, headers, runtime)
  225. return resp.body.to_map()
  226. except Exception as error:
  227. raise Exception(f"get_work_flow_draft_list error {error}")
  228. @staticmethod
  229. def get_work_flow_draft(experiment_id: str):
  230. client = PAIClient.create_client()
  231. runtime = util_models.RuntimeOptions()
  232. headers = {}
  233. try:
  234. # 复制代码运行请自行打印 API 的返回值
  235. resp = client.get_experiment_with_options(experiment_id, headers, runtime)
  236. return resp.body.to_map()
  237. except Exception as error:
  238. raise Exception(f"get_work_flow_draft error {error}")
  239. @staticmethod
  240. def get_describe_service(service_name: str):
  241. client = PAIClient.create_eas_client()
  242. runtime = util_models.RuntimeOptions()
  243. headers = {}
  244. try:
  245. # 复制代码运行请自行打印 API 的返回值
  246. resp = client.describe_service_with_options('cn-hangzhou', service_name, headers, runtime)
  247. return resp.body.to_map()
  248. except Exception as error:
  249. raise Exception(f"get_describe_service error {error}")
  250. @staticmethod
  251. def update_experiment_content(experiment_id: str, content: str, version: int):
  252. client = PAIClient.create_client()
  253. update_experiment_content_request = pai_studio_20210202_models.UpdateExperimentContentRequest(content=content,
  254. version=version)
  255. runtime = util_models.RuntimeOptions()
  256. headers = {}
  257. try:
  258. # 复制代码运行请自行打印 API 的返回值
  259. resp = client.update_experiment_content_with_options(experiment_id, update_experiment_content_request,
  260. headers, runtime)
  261. print(resp.body.to_map())
  262. except Exception as error:
  263. raise Exception(f"update_experiment_content error {error}")
  264. @staticmethod
  265. def create_job(experiment_id: str, node_id: str, execute_type: str):
  266. client = PAIClient.create_client()
  267. create_job_request = pai_studio_20210202_models.CreateJobRequest()
  268. create_job_request.experiment_id = experiment_id
  269. create_job_request.node_id = node_id
  270. create_job_request.execute_type = execute_type
  271. runtime = util_models.RuntimeOptions()
  272. headers = {}
  273. try:
  274. # 复制代码运行请自行打印 API 的返回值
  275. resp = client.create_job_with_options(create_job_request, headers, runtime)
  276. return resp.body.to_map()
  277. except Exception as error:
  278. raise Exception(f"create_job error {error}")
  279. @staticmethod
  280. def get_jobs_list(experiment_id: str, order='DESC'):
  281. client = PAIClient.create_client()
  282. list_jobs_request = pai_studio_20210202_models.ListJobsRequest(
  283. experiment_id=experiment_id,
  284. order=order
  285. )
  286. runtime = util_models.RuntimeOptions()
  287. headers = {}
  288. try:
  289. # 复制代码运行请自行打印 API 的返回值
  290. resp = client.list_jobs_with_options(list_jobs_request, headers, runtime)
  291. return resp.body.to_map()
  292. except Exception as error:
  293. raise Exception(f"get_jobs_list error {error}")
  294. @staticmethod
  295. def get_job_detail(job_id: str, verbose=False):
  296. client = PAIClient.create_client()
  297. get_job_request = pai_studio_20210202_models.GetJobRequest(
  298. verbose=verbose
  299. )
  300. runtime = util_models.RuntimeOptions()
  301. headers = {}
  302. try:
  303. # 复制代码运行请自行打印 API 的返回值
  304. resp = client.get_job_with_options(job_id, get_job_request, headers, runtime)
  305. return resp.body.to_map()
  306. except Exception as error:
  307. # 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
  308. # 错误 message
  309. print(error.message)
  310. # 诊断地址
  311. print(error.data.get("Recommend"))
  312. UtilClient.assert_as_string(error.message)
  313. @staticmethod
  314. def get_flow_out_put(pipeline_run_id: str, node_id: str, depth: int):
  315. client = PAIClient.create_flow_client()
  316. list_pipeline_run_node_outputs_request = paiflow_20210202_models.ListPipelineRunNodeOutputsRequest(
  317. depth=depth
  318. )
  319. runtime = util_models.RuntimeOptions()
  320. headers = {}
  321. try:
  322. # 复制代码运行请自行打印 API 的返回值
  323. resp = client.list_pipeline_run_node_outputs_with_options(pipeline_run_id, node_id,
  324. list_pipeline_run_node_outputs_request, headers,
  325. runtime)
  326. return resp.body.to_map()
  327. except Exception as error:
  328. # 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
  329. # 错误 message
  330. print(error.message)
  331. # 诊断地址
  332. print(error.data.get("Recommend"))
  333. UtilClient.assert_as_string(error.message)
  334. def extract_date_yyyymmdd(input_string):
  335. pattern = r'\d{8}'
  336. matches = re.findall(pattern, input_string)
  337. if matches:
  338. return matches[0]
  339. return None
  340. def get_online_version_dt(service_name: str):
  341. model_detail = PAIClient.get_describe_service(service_name)
  342. service_config_str = model_detail['ServiceConfig']
  343. service_config = json.loads(service_config_str)
  344. model_path = service_config['model_path']
  345. online_date = extract_date_yyyymmdd(model_path)
  346. return online_date
  347. def update_online_flow():
  348. try:
  349. online_version_dt = get_online_version_dt('ad_rank_dnn_v11_easyrec')
  350. draft = PAIClient.get_work_flow_draft(experiment_id)
  351. print(json.dumps(draft, ensure_ascii=False))
  352. content = draft['Content']
  353. version = draft['Version']
  354. print(content)
  355. content_json = json.loads(content)
  356. nodes = content_json.get('nodes')
  357. global_params = content_json.get('globalParams')
  358. bizdate = get_previous_days_date(1)
  359. for global_param in global_params:
  360. try:
  361. if global_param['name'] == 'bizdate':
  362. global_param['value'] = bizdate
  363. if global_param['name'] == 'online_version_dt':
  364. global_param['value'] = online_version_dt
  365. if global_param['name'] == 'eval_date':
  366. global_param['value'] = bizdate
  367. except KeyError:
  368. raise Exception("在处理全局参数时,字典中缺少必要的键")
  369. for node in nodes:
  370. try:
  371. name = node['name']
  372. if name == '样本shuffle':
  373. properties = node['properties']
  374. for property in properties:
  375. if property['name'] == 'sql':
  376. value = property['value']
  377. new_value = update_train_tables(value)
  378. if new_value is None:
  379. print("error")
  380. property['value'] = new_value
  381. except KeyError:
  382. raise Exception("在处理节点属性时,字典中缺少必要的键")
  383. new_content = json.dumps(content_json, ensure_ascii=False)
  384. PAIClient.update_experiment_content(experiment_id, new_content, version)
  385. except json.JSONDecodeError:
  386. raise Exception("JSON 解析错误,可能是草稿内容格式不正确")
  387. except Exception as e:
  388. raise Exception(f"发生未知错误: {e}")
  389. def update_shuffle_flow(table):
  390. draft = PAIClient.get_work_flow_draft(experiment_id)
  391. print(json.dumps(draft, ensure_ascii=False))
  392. content = draft['Content']
  393. version = draft['Version']
  394. content_json = json.loads(content)
  395. nodes = content_json.get('nodes')
  396. for node in nodes:
  397. name = node['name']
  398. if name == '模型训练-样本shufle':
  399. properties = node['properties']
  400. for property in properties:
  401. if property['name'] == 'sql':
  402. value = property['value']
  403. new_value = update_train_table(value, table)
  404. if new_value is None:
  405. print("error")
  406. property['value'] = new_value
  407. new_content = json.dumps(content_json, ensure_ascii=False)
  408. PAIClient.update_experiment_content(experiment_id, new_content, version)
  409. def update_shuffle_flow_1():
  410. draft = PAIClient.get_work_flow_draft(experiment_id)
  411. print(json.dumps(draft, ensure_ascii=False))
  412. content = draft['Content']
  413. version = draft['Version']
  414. print(content)
  415. content_json = json.loads(content)
  416. nodes = content_json.get('nodes')
  417. for node in nodes:
  418. name = node['name']
  419. if name == '模型训练-样本shufle':
  420. properties = node['properties']
  421. for property in properties:
  422. if property['name'] == 'sql':
  423. value = property['value']
  424. new_value = update_train_tables(value)
  425. if new_value is None:
  426. print("error")
  427. property['value'] = new_value
  428. new_content = json.dumps(content_json, ensure_ascii=False)
  429. PAIClient.update_experiment_content(experiment_id, new_content, version)
  430. def wait_job_end(job_id: str):
  431. while True:
  432. job_detail = PAIClient.get_job_detail(job_id)
  433. print(job_detail)
  434. statue = job_detail['Status']
  435. # Initialized: 初始化完成 Starting:开始 WorkflowServiceStarting:准备提交 Running:运行中 ReadyToSchedule:准备运行(前序节点未完成导致)
  436. if (statue == 'Initialized' or statue == 'Starting' or statue == 'WorkflowServiceStarting'
  437. or statue == 'Running' or statue == 'ReadyToSchedule'):
  438. # 睡眠300s 等待下次获取
  439. time.sleep(300)
  440. continue
  441. # Failed:运行失败 Terminating:终止中 Terminated:已终止 Unknown:未知 Skipped:跳过(前序节点失败导致) Succeeded:运行成功
  442. if statue == 'Failed' or statue == 'Terminating' or statue == 'Unknown' or statue == 'Skipped' or statue == 'Succeeded':
  443. return job_detail
  444. def get_node_dict():
  445. draft = PAIClient.get_work_flow_draft(experiment_id)
  446. content = draft['Content']
  447. content_json = json.loads(content)
  448. nodes = content_json.get('nodes')
  449. node_dict = {}
  450. for node in nodes:
  451. name = node['name']
  452. # 检查名称是否在目标名称集合中
  453. if name in target_names:
  454. node_dict[name] = node['id']
  455. return node_dict
  456. def get_job_dict():
  457. job_dict = {}
  458. jobs_list = PAIClient.get_jobs_list(experiment_id)
  459. for job in jobs_list['Jobs']:
  460. # 解析时间字符串为 datetime 对象
  461. if not compare_timestamp_with_today_start(job['GmtCreateTime']):
  462. break
  463. job_id = job['JobId']
  464. job_detail = PAIClient.get_job_detail(job_id, verbose=True)
  465. for name in target_names:
  466. if job_detail['Status'] != 'Succeeded':
  467. continue
  468. if name in job_dict:
  469. continue
  470. if name in job_detail['RunInfo']:
  471. job_dict[name] = job_detail['JobId']
  472. return job_dict
  473. @retry
  474. def shuffle_table():
  475. try:
  476. node_dict = get_node_dict()
  477. train_node_id = node_dict['样本shuffle']
  478. execute_type = 'EXECUTE_ONE'
  479. validate_res = PAIClient.create_job(experiment_id, train_node_id, execute_type)
  480. validate_job_id = validate_res['JobId']
  481. validate_job_detail = wait_job_end(validate_job_id)
  482. if validate_job_detail['Status'] == 'Succeeded':
  483. return True
  484. return False
  485. except Exception as e:
  486. error_message = f"在执行 shuffle_table 函数时发生异常: {str(e)}"
  487. print(error_message)
  488. raise Exception(error_message)
  489. @retry
  490. def shuffle_train_model():
  491. try:
  492. node_dict = get_node_dict()
  493. job_dict = get_job_dict()
  494. job_id = job_dict['样本shuffle']
  495. validate_job_detail = wait_job_end(job_id)
  496. if validate_job_detail['Status'] == 'Succeeded':
  497. pipeline_run_id = validate_job_detail['RunId']
  498. node_id = validate_job_detail['PaiflowNodeId']
  499. flow_out_put_detail = PAIClient.get_flow_out_put(pipeline_run_id, node_id, 2)
  500. out_puts = flow_out_put_detail['Outputs']
  501. table = None
  502. for out_put in out_puts:
  503. if out_put["Producer"] == node_dict['样本shuffle'] and out_put["Name"] == "outputTable":
  504. value1 = json.loads(out_put["Info"]['value'])
  505. table = value1['location']['table']
  506. if table is not None:
  507. update_shuffle_flow(table)
  508. node_dict = get_node_dict()
  509. train_node_id = node_dict['模型训练-样本shufle']
  510. execute_type = 'EXECUTE_ONE'
  511. train_res = PAIClient.create_job(experiment_id, train_node_id, execute_type)
  512. train_job_id = train_res['JobId']
  513. train_job_detail = wait_job_end(train_job_id)
  514. if train_job_detail['Status'] == 'Succeeded':
  515. return True
  516. return False
  517. except Exception as e:
  518. error_message = f"在执行 shuffle_train_model 函数时发生异常: {str(e)}"
  519. print(error_message)
  520. raise Exception(error_message)
  521. @retry
  522. def export_model():
  523. try:
  524. node_dict = get_node_dict()
  525. export_node_id = node_dict['模型导出-2']
  526. execute_type = 'EXECUTE_ONE'
  527. export_res = PAIClient.create_job(experiment_id, export_node_id, execute_type)
  528. export_job_id = export_res['JobId']
  529. export_job_detail = wait_job_end(export_job_id)
  530. if export_job_detail['Status'] == 'Succeeded':
  531. return True
  532. return False
  533. except Exception as e:
  534. error_message = f"在执行 export_model 函数时发生异常: {str(e)}"
  535. print(error_message)
  536. raise Exception(error_message)
  537. def update_online_model():
  538. try:
  539. node_dict = get_node_dict()
  540. train_node_id = node_dict['更新EAS服务(Beta)-1']
  541. execute_type = 'EXECUTE_ONE'
  542. train_res = PAIClient.create_job(experiment_id, train_node_id, execute_type)
  543. train_job_id = train_res['JobId']
  544. train_job_detail = wait_job_end(train_job_id)
  545. if train_job_detail['Status'] == 'Succeeded':
  546. return True
  547. return False
  548. except Exception as e:
  549. error_message = f"在执行 update_online_model 函数时发生异常: {str(e)}"
  550. print(error_message)
  551. raise Exception(error_message)
  552. @retry
  553. def get_validate_model_data():
  554. try:
  555. node_dict = get_node_dict()
  556. train_node_id = node_dict['虚拟起始节点']
  557. execute_type = 'EXECUTE_FROM_HERE'
  558. validate_res = PAIClient.create_job(experiment_id, train_node_id, execute_type)
  559. validate_job_id = validate_res['JobId']
  560. validate_job_detail = wait_job_end(validate_job_id)
  561. if validate_job_detail['Status'] == 'Succeeded':
  562. return True
  563. return False
  564. except Exception as e:
  565. error_message = f"在执行 get_validate_model_data 函数时出现异常: {e}"
  566. print(error_message)
  567. raise Exception(error_message)
  568. def validate_model_data_accuracy():
  569. try:
  570. table_dict = {}
  571. node_dict = get_node_dict()
  572. job_dict = get_job_dict()
  573. job_id = job_dict['虚拟起始节点']
  574. validate_job_detail = wait_job_end(job_id)
  575. if validate_job_detail['Status'] == 'Succeeded':
  576. pipeline_run_id = validate_job_detail['RunId']
  577. node_id = validate_job_detail['PaiflowNodeId']
  578. flow_out_put_detail = PAIClient.get_flow_out_put(pipeline_run_id, node_id, 3)
  579. print(flow_out_put_detail)
  580. out_puts = flow_out_put_detail['Outputs']
  581. for out_put in out_puts:
  582. if out_put["Producer"] == node_dict['二分类评估-1'] and out_put["Name"] == "outputMetricTable":
  583. value1 = json.loads(out_put["Info"]['value'])
  584. table_dict['二分类评估-1'] = value1['location']['table']
  585. if out_put["Producer"] == node_dict['二分类评估-2'] and out_put["Name"] == "outputMetricTable":
  586. value2 = json.loads(out_put["Info"]['value'])
  587. table_dict['二分类评估-2'] = value2['location']['table']
  588. if out_put["Producer"] == node_dict['预测结果对比'] and out_put["Name"] == "outputTable":
  589. value3 = json.loads(out_put["Info"]['value'])
  590. table_dict['预测结果对比'] = value3['location']['table']
  591. num = 10
  592. df = get_data_from_odps('pai_algo', table_dict['预测结果对比'], 10)
  593. # 对指定列取绝对值再求和
  594. old_abs_avg = df['old_error'].abs().sum() / num
  595. new_abs_avg = df['new_error'].abs().sum() / num
  596. new_auc = get_dict_from_odps('pai_algo', table_dict['二分类评估-1'])['AUC']
  597. old_auc = get_dict_from_odps('pai_algo', table_dict['二分类评估-2'])['AUC']
  598. bizdate = get_previous_days_date(1)
  599. score_diff = abs(old_abs_avg - new_abs_avg)
  600. msg = ""
  601. result = False
  602. if new_abs_avg > 0.1:
  603. msg += f'线上模型评估{bizdate}的数据,绝对误差大于0.1,请检查'
  604. level = 'error'
  605. elif score_diff > 0.05:
  606. msg += f'两个模型评估${bizdate}的数据,两个模型分数差异为: ${score_diff}, 大于0.05, 请检查'
  607. level = 'error'
  608. else:
  609. msg += 'DNN广告模型更新完成'
  610. level = 'info'
  611. result = True
  612. # 初始化表格头部
  613. top10_msg = "| CID | 老模型相对真实CTCVR的变化 | 新模型相对真实CTCVR的变化 |"
  614. top10_msg += "\n| ---- | --------- | -------- |"
  615. for index, row in df.iterrows():
  616. # 获取指定列的元素
  617. cid = row['cid']
  618. old_error = row['old_error']
  619. new_error = row['new_error']
  620. top10_msg += f"\n| {int(cid)} | {old_error} | {new_error} | "
  621. print(top10_msg)
  622. msg += f"\n\t - 老模型AUC: {old_auc}"
  623. msg += f"\n\t - 新模型AUC: {new_auc}"
  624. msg += f"\n\t - 老模型Top10差异平均值: {old_abs_avg}"
  625. msg += f"\n\t - 新模型Top10差异平均值: {new_abs_avg}"
  626. return result, msg, level, top10_msg
  627. except Exception as e:
  628. error_message = f"在执行 validate_model_data_accuracy 函数时出现异常: {str(e)}"
  629. print(error_message)
  630. raise Exception(error_message)
  631. if __name__ == '__main__':
  632. start_time = int(time.time())
  633. functions = [shuffle_table, shuffle_train_model, export_model, get_validate_model_data]
  634. for func in functions:
  635. if not func():
  636. print(f"{func.__name__} 执行失败,后续函数不再执行。")
  637. break
  638. else:
  639. print("所有函数都成功执行,可以继续下一步操作。")
  640. result, msg, level, top10_msg = validate_model_data_accuracy()
  641. if result:
  642. # update_online_model()
  643. print("success")
  644. step_end_time = int(time.time())
  645. elapsed = step_end_time - start_time
  646. print(level, msg, start_time, elapsed, top10_msg)
  647. _monitor(level, msg, start_time, elapsed, top10_msg)