main.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. import hashlib
  2. import os
  3. import sys
  4. import traceback
  5. import uuid
  6. from concurrent.futures import ThreadPoolExecutor
  7. from datetime import date
  8. from datetime import timedelta
  9. from io import BytesIO
  10. from typing import Optional, List
  11. from urllib.parse import quote
  12. import pandas as pd
  13. import uvicorn
  14. import yaml
  15. from fastapi import FastAPI
  16. from fastapi.middleware.cors import CORSMiddleware
  17. from fastapi.responses import StreamingResponse
  18. from loguru import logger
  19. from pydantic import BaseModel, Field
  20. curr_path = os.path.abspath(os.path.dirname(__file__))
  21. project_root_path = curr_path[:curr_path.find("video_to_word") + len("video_to_word")]
  22. sys.path.append(project_root_path)
  23. from asr_client import send_asr_request, send_task_request
  24. from common_func import get_db_engine
  25. from config.url import toutiao_static_video_url
  26. from database import insert, update, query, Task
  27. from time_task.get_material_and_script_by_query_word import get_material_and_script
  28. logger.remove() # 删去 import logger之后自动产生的handler,不删除的话会出现重复输出的现象
  29. logger.add("/data/pythonProject/video_to_word/logs/main_server.{time:YYYY-MM-DD}.log",
  30. rotation="00:00",
  31. format="{time:YYYY-MM-DD HH:mm:ss,SSS} [{process}] [{thread}] {level} {file} {line} - {message}",
  32. level="INFO")
  33. with open('/data/pythonProject/video_to_word/config/config.yaml', mode='r', encoding='utf-8') as f:
  34. config = yaml.load(f.read(), Loader=yaml.FullLoader)
  35. source_name_map = config['source_name_map']
  36. # 数据库连接引擎,依据开发、测试环境/生产环境 进行切换
  37. mac = uuid.UUID(int=uuid.getnode()).hex[-12:]
  38. if mac in ['5254003fa716', '52540003f5dd']:
  39. ai_word_engine = get_db_engine(config['ai_word_dev_db'])
  40. else:
  41. ai_word_engine = get_db_engine(config['ai_word_product_db'])
  42. threadPool = ThreadPoolExecutor(max_workers=4)
  43. app = FastAPI()
  44. origins = [
  45. "http://192.168.0.195:9001",
  46. "http://192.168.6.220:3000",
  47. "http://192.168.1.34",
  48. "http://192.168.1.34:8000",
  49. "http://192.168.1.105",
  50. "http://192.168.1.105:3000",
  51. "http://111.206.86.186",
  52. "http://111.206.86.186:3000",
  53. "http://adsp.tjyourong.com.cn",
  54. "http://adsp.tjyourong.com.cn:3000",
  55. "http://adsp.c-top.com.cn",
  56. "http://adsp.c-top.com.cn:3000"
  57. ]
  58. app.add_middleware(
  59. CORSMiddleware,
  60. allow_origins=origins,
  61. allow_credentials=True,
  62. allow_methods=["*"],
  63. allow_headers=["*"],
  64. )
  65. class QueryItem():
  66. signature: Optional[str] = None
  67. url: Optional[str] = None
  68. @app.get('/', tags=['back-end task'])
  69. def index():
  70. return {'message': '你已经正确创建 FastApi 服务!'}
  71. @app.post('/asr/task/submit', tags=['back-end task'])
  72. def task_submit(signature: str, url: str):
  73. json = send_asr_request(url)
  74. task = Task(signature=signature, task_id=json.Data.TaskId, task_result=json.to_json_string(), task_status=1)
  75. insert(task)
  76. return {'code': 0, 'taskId': json.Data.TaskId}
  77. @app.post('/asr/task/result', tags=['back-end task'])
  78. def task_submit(task_id: int):
  79. json = send_task_request(task_id)
  80. task = query(None, None, task_id)[0]
  81. task.task_status = json.Data.Status
  82. task.task_result = json.to_json_string()
  83. try:
  84. if json.Data.Status == 2:
  85. task.word_text = json.Data.ResultDetail[0].FinalSentence
  86. task.word_split = json.Data.ResultDetail[0].SliceSentence
  87. task.word_text_md5 = hashlib.md5(task.word_text.encode('utf-8')).hexdigest()
  88. except:
  89. # 提取原始文本内容和分词内容发生异常,把 task_status 置为 -1
  90. task.task_status = -1
  91. update(task)
  92. return {'code': 0, 'status': json.Data.StatusStr}
  93. @app.post('/asr/task/list', tags=['back-end task'])
  94. def task_submit(task_status: int):
  95. task = query(None, task_status, None)
  96. return {'code': 0, 'data': task}
  97. class BaseResponse(BaseModel):
  98. message: str = Field(..., description='消息')
  99. success: bool = Field(..., description='true or false')
  100. code: int = Field(..., description='')
  101. class TaskDetail(BaseModel):
  102. source_name: str = Field('内部创意', description='数据来源名称')
  103. query_word: str = Field('红包', description='关键词')
  104. stat_date: str = Field('2021-11-11', description='日期')
  105. script_num: str = Field('', description='脚本数量')
  106. task_status: str = Field('执行成功', description='状态')
  107. number: int = Field(0, description='序号')
  108. class ConfigDetail(BaseModel):
  109. config_id: str = Field(..., description="脚本配置id")
  110. query_word_lst: List[str] = Field(..., description="关键词")
  111. create_time: str = Field(..., description="创建时间")
  112. operator: str = Field(..., description="创建人")
  113. number: int = Field(..., description="序号")
  114. user_id: str = Field(..., description="用户id")
  115. class TaskResponse(BaseResponse):
  116. total_num: int = Field(0, description="总个数")
  117. page_num: int = Field(1, description="第几页")
  118. page_size: int = Field(10, description="每页个数")
  119. config_id: str = Field('', description="脚本配置id")
  120. result: List[TaskDetail] = Field(..., description="结果详情")
  121. class ConfigResponse(BaseResponse):
  122. total_num: int = Field(0, description="总个数")
  123. page_num: int = Field(1, description="第几页")
  124. page_size: int = Field(10, description="每页个数")
  125. result: List[ConfigDetail] = Field(..., description="结果详情")
  126. class QueryWordItem(BaseModel):
  127. query_word: str = Field("红包", description="查询词", min_length=1)
  128. stat_date: str = Field("2021-11-16", description="日期", min_length=10, max_length=10)
  129. source_code: int = Field(2, description="数据来源编码{1:'内部创意', 2:'巨量创意', 3:'开眼快创'}")
  130. class ScriptConfigLst(BaseModel):
  131. start_date: Optional[date] = Field(date.today() + timedelta(days=-6), description="开始日期-用于查询")
  132. end_date: Optional[date] = Field(date.today(), description="结束日期-用于查询")
  133. search_word: Optional[str] = Field('', description="关键词-用于查询")
  134. page_num: int = Field(1, description="第几页")
  135. page_size: int = Field(10, description="每页的大小")
  136. class QueryWordTaskInfoLst(BaseModel):
  137. start_date: Optional[date] = Field(date.today() + timedelta(days=-30), description="开始日期-用于查询")
  138. end_date: Optional[date] = Field(date.today(), description="结束日期-用于查询")
  139. search_word: Optional[str] = Field('', description="关键词-用于查询")
  140. page_num: int = Field(1, description="第几页")
  141. page_size: int = Field(10, description="每页的大小")
  142. config_id: Optional[str] = Field('', description="脚本配置id")
  143. source_code: Optional[List[int]] = Field([0], description="数据来源编码{1:'内部创意', 2:'巨量创意', 3:'开眼快创'}")
  144. class AddScriptConfig(BaseModel):
  145. query_word_lst: List[str] = Field(..., description="关键词组")
  146. operator: str = Field(..., description="操作者")
  147. user_id: str = Field(..., description="user_id")
  148. class Config:
  149. schema_extra = {
  150. "example": {
  151. "query_word_lst": ["红包", "淘特"],
  152. "operator": "龙猫",
  153. "user_id": "234d46d1873f4dac85b2a2f9ad541e18"
  154. }
  155. }
  156. @logger.catch
  157. @app.post('/export_script_file/', tags=['front-end interactive'],
  158. description="导出文件",
  159. summary='导出文件',
  160. response_model=BaseResponse
  161. )
  162. def export_script_file(item: List[QueryWordItem]):
  163. try:
  164. video_df = pd.DataFrame()
  165. out_df = pd.DataFrame()
  166. # 1 从数据库获取视频数据
  167. # 如果同一个素材有多个查询词,则合并打上这多个查询词
  168. for obj in item:
  169. query_word = obj.query_word
  170. stat_date = obj.stat_date
  171. source_code = obj.source_code
  172. sql = f"select signature, video_url, query_word, stat_date, {source_code} source_code from {source_name_map[source_code]['table']} " \
  173. f"where query_word = '{query_word}' " \
  174. f"and stat_date = '{stat_date}'"
  175. df = pd.read_sql(sql, ai_word_engine)
  176. video_df = video_df.append(df)
  177. if not video_df.empty:
  178. # 按 'signature' + 'query_word' + 'stat_date' 进行去重
  179. video_df.drop_duplicates(['signature', 'query_word', 'stat_date', 'source_code'], keep='last', inplace=True)
  180. video_query_word_df = video_df.groupby('signature').apply(lambda x: pd.Series({'query_word_lst': x['query_word'].unique(),
  181. 'video_url': x['video_url'].values[0],
  182. 'source_code': x['source_code'].values[0]}))
  183. video_query_word_df.reset_index(inplace=True, drop=False)
  184. # 如果来源==2 (头条巨量引擎),把视频链接替换为永久链接
  185. video_query_word_df['video_url'] = video_query_word_df.apply(
  186. lambda row: toutiao_static_video_url + row['signature'] if row.get('source_code') == 2 else row['video_url'], axis=1)
  187. # 2 根据第一步的视频数据获取脚本
  188. signature_lst = list(video_query_word_df.signature.values) if len(video_query_word_df.signature.values) > 1 \
  189. else list(video_query_word_df.signature.values) * 2
  190. sql = f"select signature, word_text from tb_asr_result where signature in {tuple(signature_lst)}" \
  191. f"and word_text is not null"
  192. script_df = pd.read_sql(sql, ai_word_engine)
  193. out_df = video_query_word_df.merge(script_df, on='signature', how='inner')
  194. # 3 返回流数据
  195. if not out_df.empty:
  196. bio = BytesIO()
  197. writer = pd.ExcelWriter(bio, engine='xlsxwriter')
  198. out_df[['signature', 'query_word_lst', 'word_text', 'video_url']].to_excel(writer, index=False, encoding='utf8mb4')
  199. writer.save()
  200. bio.seek(0)
  201. # 组装header
  202. now_date = date.today().strftime('%Y-%m-%d')
  203. headers = {"content-type": "application/vnd.ms-excel",
  204. "content-disposition": f"attachment;filename={quote('优质素材脚本_')}{now_date}.xlsx"
  205. }
  206. logger.info(f"request body: {item}, message: 数据导出成功")
  207. return StreamingResponse(bio, media_type='xlsx', headers=headers)
  208. else:
  209. logger.info(f"request body: {item}, message: 没有获取到对应的数据")
  210. return {"code": 0,
  211. "message": "没有获取到对应的数据",
  212. "success": True}
  213. except:
  214. logger.error(f"request body: {item}, message: {traceback.format_exc()}")
  215. return {"code": 0,
  216. "message": {traceback.format_exc()},
  217. "success": False}
  218. @logger.catch
  219. @app.post('/get_script_config_lst/', tags=['front-end interactive'], response_model=ConfigResponse,
  220. description="脚本配置列表",
  221. summary='脚本配置列表'
  222. )
  223. def get_script_config_lst(item: ScriptConfigLst):
  224. try:
  225. end_date = item.end_date + timedelta(days=1)
  226. org_df = pd.DataFrame()
  227. sql = f"select * from ctop_ai_script_query_word_config where config_id in " \
  228. f"(select distinct(config_id) config_id from ctop_ai_script_query_word_config " \
  229. f"where start_time >= '{item.start_date}' and start_time < '{end_date}' " \
  230. f"and ('{item.search_word}' = '' or query_word like '%%{item.search_word}%%') ) "
  231. org_df = pd.read_sql(sql, ai_word_engine)
  232. if not org_df.empty:
  233. g_df = org_df.groupby('config_id').apply(lambda x: pd.Series({'query_word_lst': list(x['query_word'].unique()),
  234. 'operator': x['operator'].min(),
  235. 'create_time': str(x['start_time'].min()),
  236. 'user_id': x['user_id'].min()}))
  237. g_df.reset_index(drop=False, inplace=True)
  238. g_df.sort_values(by='create_time', ascending=False, inplace=True)
  239. g_df['number'] = list(range(1, len(g_df) + 1))
  240. total_num = g_df.shape[0]
  241. detail = g_df.iloc[(item.page_num - 1) * item.page_size: item.page_num * item.page_size].to_dict('records')
  242. response = {'code': 0,
  243. "message": "查询成功",
  244. "success": True,
  245. "result": detail,
  246. "total_num": total_num,
  247. "page_num": item.page_num,
  248. "page_size": item.page_size}
  249. logger.info(f"request body: {item}, response body: {response}")
  250. return response
  251. else:
  252. response = {'code': 0,
  253. "message": "没有符合条件的数据",
  254. "success": True,
  255. "result": [],
  256. "total_num": 0,
  257. "page_num": item.page_num,
  258. "page_size": item.page_size}
  259. logger.info(f"request body: {item}, response body: {response}")
  260. return response
  261. except:
  262. response = {"code": -1,
  263. "message": traceback.format_exc(),
  264. "success": False,
  265. "result": None}
  266. logger.error(f"request body: {item}, response body: {response}")
  267. return response
  268. @logger.catch
  269. @app.post('/get_query_word_task_info_lst/', tags=['front-end interactive'], response_model=TaskResponse,
  270. description="脚本数据导出列表",
  271. summary='脚本数据导出列表'
  272. )
  273. def get_query_word_task_info_lst(item: QueryWordTaskInfoLst):
  274. try:
  275. end_date = item.end_date + timedelta(days=1)
  276. source_code_lst = item.source_code * 2 if len(item.source_code) == 1 else item.source_code
  277. df = pd.DataFrame()
  278. if item.config_id != '':
  279. sql = f"select distinct(query_word) query_word from ctop_ai_script_query_word_config where config_id = '{item.config_id}'"
  280. query_word_lst = list(pd.read_sql(sql, ai_word_engine).query_word.values)
  281. if len(query_word_lst) > 0:
  282. query_word_lst = query_word_lst * 2 if len(query_word_lst) == 1 else query_word_lst
  283. sql = f"select * from ctop_ai_query_word_task_record where query_word in {tuple(query_word_lst)}" \
  284. f"and stat_date >= '{item.start_date}' and stat_date < '{end_date}' " \
  285. f"and ('{item.source_code}' = '[0]' or source_code in {tuple(source_code_lst)}) " \
  286. f"and ('{item.search_word}' = '' or query_word = '{item.search_word}')"
  287. df = pd.read_sql(sql, ai_word_engine)
  288. else:
  289. sql = f"select * from ctop_ai_query_word_task_record where " \
  290. f"stat_date >= '{item.start_date}' and stat_date < '{end_date}' " \
  291. f"and ('{item.source_code}' = '[0]' or source_code in {tuple(source_code_lst)}) " \
  292. f"and ('{item.search_word}' = '' or query_word = '{item.search_word}')"
  293. df = pd.read_sql(sql, ai_word_engine)
  294. if not df.empty:
  295. df['source_name'] = df['source_code'].apply(lambda x: source_name_map[x]['name'])
  296. df = df[['source_name', 'query_word', 'stat_date', 'script_num', 'task_status']]
  297. df.sort_values(['stat_date', 'source_name', 'query_word'], ascending=False, inplace=True)
  298. df['number'] = list(range(1, len(df) + 1))
  299. # script_num 字段类型由 np.array 转化为 str 类型,解决返回 np.nan 时, responseModel 验证不通过
  300. df['script_num'] = df['script_num'].astype(pd.Int64Dtype())
  301. df['script_num'] = df['script_num'].astype(str)
  302. df.replace('<NA>', '', inplace=True)
  303. total_num = df.shape[0]
  304. detail = df.iloc[(item.page_num - 1) * item.page_size: item.page_num * item.page_size].to_dict('records')
  305. response = {'code': 0,
  306. "message": "查询成功",
  307. "success": True,
  308. "result": detail,
  309. "total_num": total_num,
  310. "page_num": item.page_num,
  311. "page_size": item.page_size,
  312. "config_id": item.config_id}
  313. logger.info(f"request body: {item}, response body: {response}")
  314. return response
  315. else:
  316. response = {'code': 0,
  317. "message": "没有符合条件的数据",
  318. "success": True,
  319. "result": [],
  320. "total_num": 0,
  321. "page_num": item.page_num,
  322. "page_size": item.page_size,
  323. "config_id": item.config_id}
  324. logger.info(f"request body: {item}, response body: {response}")
  325. return response
  326. except:
  327. response = {"code": -1,
  328. "message": traceback.format_exc(),
  329. "success": False,
  330. "result": None}
  331. logger.error(f"request body: {item}, response body: {response}")
  332. return response
  333. @logger.catch
  334. @app.post('/add_script_config/',
  335. tags=['front-end interactive'],
  336. description="新增脚本配置",
  337. summary='新增脚本配置',
  338. response_model=BaseResponse)
  339. def add_script_config(item: AddScriptConfig):
  340. try:
  341. # 按查询词拆分配置记录
  342. config_id = str(uuid.uuid4())
  343. config_df = pd.DataFrame(data=item.query_word_lst, columns=['query_word'])
  344. config_df['config_id'] = config_id
  345. config_df['operator'] = item.operator
  346. config_df['operate_type'] = 1
  347. config_df['user_id'] = item.user_id
  348. # 新增配置记录插入到 ctop_ai_script_query_word_config
  349. config_df.to_sql(name="ctop_ai_script_query_word_config",
  350. con=ai_word_engine,
  351. if_exists='append',
  352. index=False)
  353. logger.info(f"request body: {item}, code:0, message: add_script_config success")
  354. return {"code": 0,
  355. "message": "add success",
  356. "success": True}
  357. except:
  358. logger.error(f"request body: {item}, code:-1, message: add_script_config fail {traceback.format_exc()}")
  359. return {"code": -1,
  360. "message": traceback.format_exc(),
  361. "success": False}
  362. @logger.catch
  363. @app.post('/get_material_and_script_time_task/',
  364. response_model=BaseResponse,
  365. tags=['back-end task'],
  366. description="获取素材和脚本任务",
  367. summary='获取素材和脚本任务')
  368. def get_material_and_script_time_task():
  369. try:
  370. get_material_and_script()
  371. logger.info(f"{date.today().strftime('%Y-%m-%d')}, 获取素材和脚本任务执行完成.")
  372. return {"code": 0,
  373. "success": True,
  374. "message": f"{date.today().strftime('%Y-%m-%d')},获取素材和脚本任务执行完成."}
  375. except:
  376. logger.error(f"{date.today().strftime('%Y-%m-%d')}, 获取素材和脚本任务执行发生异常. {traceback.format_exc()}")
  377. return {"code": -1,
  378. "success": False,
  379. "message": f"{date.today().strftime('%Y-%m-%d')},获取素材和脚本任务执行发生异常 .{traceback.format_exc()}"}
  380. if __name__ == '__main__':
  381. uvicorn.run(app='main:app', host="0.0.0.0", port=31013, reload=True, debug=True)
  382. # gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker #线上启动命令