script_config.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. import os
  2. import sys
  3. import traceback
  4. import uuid
  5. from datetime import date
  6. from datetime import timedelta
  7. from io import BytesIO
  8. from typing import Optional, List
  9. from urllib.parse import quote
  10. import pandas as pd
  11. import yaml
  12. from fastapi import APIRouter
  13. from fastapi.responses import StreamingResponse
  14. from loguru import logger
  15. from pydantic import BaseModel, Field
  16. curr_path = os.path.abspath(os.path.dirname(__file__))
  17. project_root_path = curr_path[:curr_path.find("video_to_word") + len("video_to_word")]
  18. sys.path.append(project_root_path)
  19. from config.url_and_db import toutiao_static_video_url, ai_word_engine
  20. from time_task.get_material_and_script_by_query_word import get_material_and_script
  21. router = APIRouter(tags=['script_config_server'])
  22. with open('/data/pythonProject/video_to_word/config/config.yaml', mode='r', encoding='utf-8') as f:
  23. config = yaml.load(f.read(), Loader=yaml.FullLoader)
  24. source_name_map = config['source_name_map']
  25. class BaseResponse(BaseModel):
  26. message: str = Field(..., description='消息')
  27. success: bool = Field(..., description='true or false')
  28. code: int = Field(..., description='')
  29. class TaskDetail(BaseModel):
  30. source_name: str = Field('内部创意', description='数据来源名称')
  31. query_word: str = Field('红包', description='关键词')
  32. stat_date: str = Field('2021-11-11', description='日期')
  33. script_num: str = Field('', description='脚本数量')
  34. task_status: str = Field('执行成功', description='状态')
  35. number: int = Field(0, description='序号')
  36. class ConfigDetail(BaseModel):
  37. config_id: str = Field(..., description="脚本配置id")
  38. query_word: List[str] = Field(..., description="关键词")
  39. recommended_word: List[str] = Field(..., description="推荐词")
  40. create_time: str = Field(..., description="创建时间")
  41. operator: str = Field(..., description="创建人")
  42. number: int = Field(..., description="序号")
  43. user_id: str = Field(..., description="用户id")
  44. class TaskResponse(BaseResponse):
  45. total_num: int = Field(0, description="总个数")
  46. page_num: int = Field(1, description="第几页")
  47. page_size: int = Field(10, description="每页个数")
  48. config_id: str = Field('', description="脚本配置id")
  49. result: List[TaskDetail] = Field(..., description="结果详情")
  50. class ConfigResponse(BaseResponse):
  51. total_num: int = Field(0, description="总个数")
  52. page_num: int = Field(1, description="第几页")
  53. page_size: int = Field(10, description="每页个数")
  54. result: List[ConfigDetail] = Field(..., description="结果详情")
  55. class QueryWordItem(BaseModel):
  56. query_word: str = Field("红包", description="查询词", min_length=1)
  57. stat_date: str = Field("2021-11-16", description="日期", min_length=10, max_length=10)
  58. source_code: int = Field(2, description="数据来源编码{1:'内部创意', 2:'巨量创意', 3:'开眼快创'}")
  59. class ScriptConfigLst(BaseModel):
  60. start_date: Optional[date] = Field(date.today() + timedelta(days=-29), description="开始日期-用于查询")
  61. end_date: Optional[date] = Field(date.today(), description="结束日期-用于查询")
  62. search_word: Optional[str] = Field('', description="关键词/推荐词-用于查询")
  63. page_num: int = Field(1, description="第几页")
  64. page_size: int = Field(10, description="每页的大小")
  65. class QueryWordTaskInfoLst(BaseModel):
  66. start_date: Optional[date] = Field(date.today() + timedelta(days=-30), description="开始日期-用于查询")
  67. end_date: Optional[date] = Field(date.today(), description="结束日期-用于查询")
  68. search_word: Optional[str] = Field('', description="关键词-用于查询")
  69. page_num: int = Field(1, description="第几页")
  70. page_size: int = Field(10, description="每页的大小")
  71. config_id: Optional[str] = Field('', description="脚本配置id")
  72. source_code: Optional[List[int]] = Field([0], description="数据来源编码{1:'内部创意', 2:'巨量创意', 3:'开眼快创'}")
  73. class QueryWordAndRecommendedWordPair(BaseModel):
  74. query_word: str = Field('红包', description='关键字')
  75. recommended_word: List[str] = Field(['推荐词1', '推荐词2'], description='推荐词')
  76. class AddScriptConfig(BaseModel):
  77. query_word_pair: List[QueryWordAndRecommendedWordPair] = Field(..., description="关键词-推荐词")
  78. operator: str = Field(..., description="操作者")
  79. user_id: str = Field(..., description="user_id")
  80. class Config:
  81. schema_extra = {
  82. "example": {
  83. "query_word_pair": [{"query_word": "红包", "recommended_word": ["购物券", "优惠券", "现金"]}],
  84. "operator": "管理员",
  85. "user_id": "e9ca23d68d884d4ebb19d07889727dae"
  86. }
  87. }
  88. @logger.catch
  89. @router.post('/export_script_file/',
  90. description="导出文件",
  91. summary='导出文件',
  92. response_model=BaseResponse
  93. )
  94. def export_script_file(item: List[QueryWordItem]):
  95. try:
  96. video_df = pd.DataFrame()
  97. out_df = pd.DataFrame()
  98. # 1 从数据库获取视频数据
  99. # 如果同一个素材有多个查询词,则合并打上这多个查询词
  100. for obj in item:
  101. query_word = obj.query_word
  102. stat_date = obj.stat_date
  103. source_code = obj.source_code
  104. sql = f"select signature, video_url, query_word, stat_date, {source_code} source_code from {source_name_map[source_code]['table']} " \
  105. f"where query_word = '{query_word}' " \
  106. f"and stat_date = '{stat_date}'"
  107. df = pd.read_sql(sql, ai_word_engine)
  108. video_df = video_df.append(df)
  109. if not video_df.empty:
  110. # 按 'signature' + 'query_word' + 'stat_date' 进行去重
  111. video_df.drop_duplicates(['signature', 'query_word', 'stat_date', 'source_code'], keep='last', inplace=True)
  112. video_query_word_df = video_df.groupby('signature').apply(lambda x: pd.Series({'query_word_lst': x['query_word'].unique(),
  113. 'video_url': x['video_url'].values[0],
  114. 'source_code': x['source_code'].values[0]}))
  115. video_query_word_df.reset_index(inplace=True, drop=False)
  116. # 如果来源==2 (头条巨量引擎),把视频链接替换为永久链接
  117. video_query_word_df['video_url'] = video_query_word_df.apply(
  118. lambda row: toutiao_static_video_url + row['signature'] if row.get('source_code') == 2 else row['video_url'], axis=1)
  119. # 2 根据第一步的视频数据获取脚本
  120. signature_lst = list(video_query_word_df.signature.values) if len(video_query_word_df.signature.values) > 1 \
  121. else list(video_query_word_df.signature.values) * 2
  122. sql = f"select signature, word_text from tb_asr_result where signature in {tuple(signature_lst)}" \
  123. f"and word_text is not null"
  124. script_df = pd.read_sql(sql, ai_word_engine)
  125. out_df = video_query_word_df.merge(script_df, on='signature', how='inner')
  126. # 3 返回流数据
  127. if not out_df.empty:
  128. bio = BytesIO()
  129. writer = pd.ExcelWriter(bio, engine='xlsxwriter')
  130. out_df[['signature', 'query_word_lst', 'word_text', 'video_url']].to_excel(writer, index=False, encoding='utf8mb4')
  131. writer.save()
  132. bio.seek(0)
  133. # 组装header
  134. now_date = date.today().strftime('%Y-%m-%d')
  135. headers = {"content-type": "application/vnd.ms-excel",
  136. "content-disposition": f"attachment;filename={quote('优质素材脚本_')}{now_date}.xlsx"
  137. }
  138. logger.info(f"request body: {item}, message: 数据导出成功")
  139. return StreamingResponse(bio, media_type='xlsx', headers=headers)
  140. else:
  141. logger.info(f"request body: {item}, message: 没有获取到对应的数据")
  142. return {"code": 0,
  143. "message": "没有获取到对应的数据",
  144. "success": True}
  145. except:
  146. logger.error(f"request body: {item}, message: {traceback.format_exc()}")
  147. return {"code": 0,
  148. "message": {traceback.format_exc()},
  149. "success": False}
  150. @logger.catch
  151. @router.post('/get_script_config_lst/', response_model=ConfigResponse,
  152. description="脚本配置列表",
  153. summary='脚本配置列表'
  154. )
  155. def get_script_config_lst(item: ScriptConfigLst):
  156. try:
  157. end_date = item.end_date + timedelta(days=1)
  158. sql = f"select * from ctop_ai_script_query_word_config where config_id in " \
  159. f"(select distinct(config_id) config_id from ctop_ai_script_query_word_config " \
  160. f"where start_time >= '{item.start_date}' and start_time < '{end_date}' " \
  161. f"and ('{item.search_word}' = '' or query_word like '%%{item.search_word}%%') or recommended_word like '%%{item.search_word}%%') "
  162. org_df = pd.read_sql(sql, ai_word_engine)
  163. if not org_df.empty:
  164. g_df = org_df.groupby('config_id').apply(lambda x: pd.Series({'query_word': list(x['query_word'].unique()),
  165. 'recommended_word': list(x['recommended_word'].unique()),
  166. 'operator': x['operator'].min(),
  167. 'create_time': str(x['start_time'].min()),
  168. 'user_id': x['user_id'].min()}))
  169. g_df.reset_index(drop=False, inplace=True)
  170. g_df.sort_values(by='create_time', ascending=False, inplace=True)
  171. g_df['number'] = list(range(1, len(g_df) + 1))
  172. total_num = g_df.shape[0]
  173. detail = g_df.iloc[(item.page_num - 1) * item.page_size: item.page_num * item.page_size].to_dict('records')
  174. response = {'code': 0,
  175. "message": "查询成功",
  176. "success": True,
  177. "result": detail,
  178. "total_num": total_num,
  179. "page_num": item.page_num,
  180. "page_size": item.page_size}
  181. logger.info(f"request body: {item}, response body: {response}")
  182. return response
  183. else:
  184. response = {'code': 0,
  185. "message": "没有符合条件的数据",
  186. "success": True,
  187. "result": [],
  188. "total_num": 0,
  189. "page_num": item.page_num,
  190. "page_size": item.page_size}
  191. logger.info(f"request body: {item}, response body: {response}")
  192. return response
  193. except:
  194. response = {"code": -1,
  195. "message": traceback.format_exc(),
  196. "success": False,
  197. "result": None}
  198. logger.error(f"request body: {item}, response body: {response}")
  199. return response
  200. @logger.catch
  201. @router.post('/get_query_word_task_info_lst/', response_model=TaskResponse,
  202. description="脚本数据导出列表",
  203. summary='脚本数据导出列表'
  204. )
  205. def get_query_word_task_info_lst(item: QueryWordTaskInfoLst):
  206. try:
  207. end_date = item.end_date + timedelta(days=1)
  208. source_code_lst = item.source_code * 2 if len(item.source_code) == 1 else item.source_code
  209. df = pd.DataFrame()
  210. if item.config_id != '':
  211. sql = f"select distinct(query_word) query_word from ctop_ai_script_query_word_config where config_id = '{item.config_id}'"
  212. query_word_lst = list(pd.read_sql(sql, ai_word_engine).query_word.values)
  213. if len(query_word_lst) > 0:
  214. query_word_lst = query_word_lst * 2 if len(query_word_lst) == 1 else query_word_lst
  215. sql = f"select * from ctop_ai_query_word_task_record where query_word in {tuple(query_word_lst)}" \
  216. f"and stat_date >= '{item.start_date}' and stat_date < '{end_date}' " \
  217. f"and ('{item.source_code}' = '[0]' or source_code in {tuple(source_code_lst)}) " \
  218. f"and ('{item.search_word}' = '' or query_word = '{item.search_word}')"
  219. df = pd.read_sql(sql, ai_word_engine)
  220. else:
  221. sql = f"select * from ctop_ai_query_word_task_record where " \
  222. f"stat_date >= '{item.start_date}' and stat_date < '{end_date}' " \
  223. f"and ('{item.source_code}' = '[0]' or source_code in {tuple(source_code_lst)}) " \
  224. f"and ('{item.search_word}' = '' or query_word = '{item.search_word}')"
  225. df = pd.read_sql(sql, ai_word_engine)
  226. if not df.empty:
  227. df['source_name'] = df['source_code'].apply(lambda x: source_name_map[x]['name'])
  228. df = df[['source_name', 'query_word', 'stat_date', 'script_num', 'task_status']]
  229. df.sort_values(['stat_date', 'source_name', 'query_word'], ascending=False, inplace=True)
  230. df['number'] = list(range(1, len(df) + 1))
  231. # script_num 字段类型由 np.array 转化为 str 类型,解决返回 np.nan 时, responseModel 验证不通过
  232. df['script_num'] = df['script_num'].astype(pd.Int64Dtype())
  233. df['script_num'] = df['script_num'].astype(str)
  234. df.replace('<NA>', '', inplace=True)
  235. total_num = df.shape[0]
  236. detail = df.iloc[(item.page_num - 1) * item.page_size: item.page_num * item.page_size].to_dict('records')
  237. response = {'code': 0,
  238. "message": "查询成功",
  239. "success": True,
  240. "result": detail,
  241. "total_num": total_num,
  242. "page_num": item.page_num,
  243. "page_size": item.page_size,
  244. "config_id": item.config_id}
  245. logger.info(f"request body: {item}, response body: {response}")
  246. return response
  247. else:
  248. response = {'code': 0,
  249. "message": "没有符合条件的数据",
  250. "success": True,
  251. "result": [],
  252. "total_num": 0,
  253. "page_num": item.page_num,
  254. "page_size": item.page_size,
  255. "config_id": item.config_id}
  256. logger.info(f"request body: {item}, response body: {response}")
  257. return response
  258. except:
  259. response = {"code": -1,
  260. "message": traceback.format_exc(),
  261. "success": False,
  262. "result": None}
  263. logger.error(f"request body: {item}, response body: {response}")
  264. return response
  265. @logger.catch
  266. @router.post('/add_script_config/',
  267. description="新增脚本配置",
  268. summary='新增脚本配置',
  269. response_model=BaseResponse)
  270. def add_script_config(item: AddScriptConfig):
  271. try:
  272. multi_config_df = pd.DataFrame()
  273. for pair in item.query_word_pair:
  274. config_id = str(uuid.uuid4())
  275. config_df = pd.DataFrame({'query_word': pair.query_word,
  276. 'recommended_word': pair.recommended_word,
  277. 'config_id': config_id})
  278. multi_config_df = multi_config_df.append(config_df)
  279. multi_config_df['operator'] = item.operator
  280. multi_config_df['operate_type'] = 1
  281. multi_config_df['user_id'] = item.user_id
  282. # 新增配置记录插入到 ctop_ai_script_query_word_config
  283. multi_config_df.to_sql(name="ctop_ai_script_query_word_config",
  284. con=ai_word_engine,
  285. if_exists='append',
  286. index=False)
  287. logger.info(f"request body: {item}, code:0, message: add_script_config success")
  288. return {"code": 0,
  289. "message": "add success",
  290. "success": True}
  291. except:
  292. logger.error(f"request body: {item}, code:-1, message: add_script_config fail {traceback.format_exc()}")
  293. return {"code": -1,
  294. "message": traceback.format_exc(),
  295. "success": False}
  296. @logger.catch
  297. @router.post('/get_material_and_script_time_task/',
  298. response_model=BaseResponse,
  299. description="获取素材和脚本任务",
  300. summary='获取素材和脚本任务')
  301. def get_material_and_script_time_task():
  302. try:
  303. get_material_and_script()
  304. logger.info(f"{date.today().strftime('%Y-%m-%d')}, 获取素材和脚本任务执行完成.")
  305. return {"code": 0,
  306. "success": True,
  307. "message": f"{date.today().strftime('%Y-%m-%d')},获取素材和脚本任务执行完成."}
  308. except:
  309. logger.error(f"{date.today().strftime('%Y-%m-%d')}, 获取素材和脚本任务执行发生异常. {traceback.format_exc()}")
  310. return {"code": -1,
  311. "success": False,
  312. "message": f"{date.today().strftime('%Y-%m-%d')},获取素材和脚本任务执行发生异常 .{traceback.format_exc()}"}