aiRouter.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import os, json, time, asyncio
  2. from base_config import ai_key, path
  3. from fastapi import APIRouter, BackgroundTasks
  4. from pathlib import Path
  5. from pydantic import BaseModel
  6. from git import Repo
  7. from http import HTTPStatus
  8. from dashscope import Application
  9. from models.aiModels import Scan_Tasks, Commit_Summary_Tasks, File_Summary_Tasks
  10. from models.gitModels import Repos
  11. airouter = APIRouter()
  12. class RequestCommit(BaseModel):
  13. task_id: str
  14. uuid: str
  15. repo_url: str
  16. class RequestScan(BaseModel):
  17. task_id: str
  18. uuid: str
  19. repo_url: str
  20. class RequestFile(BaseModel):
  21. task_id: str
  22. uuid: str
  23. repo_url: str
  24. file_path: str
  25. def generate_repo_path(uuid, repo_url):
  26. repo_name = repo_url.split("/")[-1].replace(".git", "")
  27. base_path = os.path.join(path, uuid)
  28. return os.path.join(base_path, repo_name), repo_name
  29. async def file_summary(content):
  30. response = Application.call(
  31. # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
  32. api_key=ai_key,
  33. app_id='5e3df30ad8bf44b68209e1ef089ff15c',
  34. prompt=content)
  35. if response.status_code == HTTPStatus.OK:
  36. try:
  37. json_data = json.loads(response.output.text)
  38. print(json_data)
  39. except json.JSONDecodeError:
  40. print("返回内容不是有效的 JSON 格式!")
  41. json_data = {"summary": []}
  42. else:
  43. print(f"请求失败: {response.message}")
  44. json_data = {"summary": []}
  45. return json_data
  46. async def commit_summary(content):
  47. response = Application.call(
  48. # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
  49. api_key=ai_key,
  50. app_id='31a822df773248b19c3c9779f41a5507',
  51. prompt=content)
  52. if response.status_code == HTTPStatus.OK:
  53. try:
  54. json_data = json.loads(response.output.text)
  55. print(json_data)
  56. except json.JSONDecodeError:
  57. print("返回内容不是有效的 JSON 格式!")
  58. json_data = {"null": []}
  59. else:
  60. print(f"请求失败: {response.message}")
  61. json_data = {"null": []}
  62. return json_data
  63. def filter_code_files(prompt):
  64. response = Application.call(
  65. # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
  66. api_key=ai_key,
  67. app_id='c1a6dbb6d2314e469bfcbe44c2fe0a5f',
  68. prompt=prompt)
  69. if response.status_code == HTTPStatus.OK:
  70. try:
  71. json_data = json.loads(response.output.text)
  72. print(json_data)
  73. except json.JSONDecodeError:
  74. print("返回内容不是有效的 JSON 格式!")
  75. json_data={"files":[]}
  76. else:
  77. print(f"请求失败: {response.message}")
  78. json_data = {"files": []}
  79. return json_data
  80. def analysis_results(local_path,path):
  81. prompt=""
  82. file_path=os.path.join(local_path,path)
  83. with open(file_path, 'r',encoding="utf8") as f:
  84. for line_num, line in enumerate(f, start=1):
  85. prompt+=f"{line_num}\t{line}"
  86. response = Application.call(
  87. # 若没有配置环境变量,可用百炼API Key将下行替换为:api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中,以减少API Key泄露风险。
  88. api_key=ai_key,
  89. app_id='2f288f146e2d492abb3fe22695e70635', # 替换为实际的应用 ID
  90. prompt=prompt)
  91. if response.status_code == HTTPStatus.OK:
  92. try:
  93. json_data = json.loads(response.output.text)
  94. except json.JSONDecodeError:
  95. print("返回内容不是有效的 JSON 格式!")
  96. print(response.output.text)
  97. json_data={"summary":None}
  98. else:
  99. print(f"请求失败: {response.message}")
  100. json_data = {"summary":None}
  101. json_data["path"]=file_path
  102. return json_data
  103. async def get_filtered_files(folder_path):
  104. base_path = Path(folder_path).resolve()
  105. if not base_path.is_dir():
  106. raise ValueError("无效的目录路径")
  107. file_list = []
  108. for root, dirs, files in os.walk(base_path):
  109. dirs[:] = [d for d in dirs if not d.startswith('.')]
  110. files = [f for f in files if not f.startswith('.')]
  111. for file in files:
  112. abs_path = Path(root) / file
  113. rel_path = abs_path.relative_to(base_path)
  114. file_list.append(str(rel_path))
  115. return file_list
  116. async def process_batch1(batch_files):
  117. """多线程处理单个文件批次的函数"""
  118. try:
  119. js = filter_code_files(str(batch_files))
  120. return js["files"]
  121. except Exception as e:
  122. print(f"处理批次时出错: {e}")
  123. return []
  124. async def get_code_files(path):
  125. file_list = []
  126. files = await get_filtered_files(path)
  127. print(files)
  128. print(f"找到 {len(files)} 个文件")
  129. # 将文件列表分块(每500个一组)
  130. chunks = [files[i * 500: (i + 1) * 500]
  131. for i in range(0, len(files) // 500 + 1)]
  132. # 提交所有批次任务
  133. # futures = [executor.submit(process_batch1, chunk) for chunk in chunks]
  134. tasks = [process_batch1(chunk) for chunk in chunks]
  135. futures = await asyncio.gather(*tasks, return_exceptions=True)
  136. # 实时获取已完成任务的结果
  137. for future in futures[0]:
  138. if isinstance(future, Exception):
  139. print(f"处理出错: {future}")
  140. else:
  141. file_list.append(future)
  142. return file_list
  143. async def process_batch2(local_path,path):
  144. """多线程处理单个文件批次的函数"""
  145. try:
  146. # print(local_path, path)
  147. js = analysis_results(local_path,path)
  148. return js
  149. except Exception as e:
  150. print(11111)
  151. print(f"处理批次时出错: {e}")
  152. return {"summary":None}
  153. async def analysis(local_path, task_id):
  154. file_list = await get_code_files(local_path)
  155. print(file_list)
  156. results = []
  157. tasks = [process_batch2(local_path, file) for file in file_list] # 假设process_batch2已改为异步函数
  158. batch_results = await asyncio.gather(*tasks, return_exceptions=True)
  159. for result in batch_results:
  160. if isinstance(result, Exception):
  161. print(f"处理出错: {result}")
  162. await Scan_Tasks.filter(id=task_id).update(state=3, result={"results": results},
  163. scan_end_time=int(time.time()))
  164. else:
  165. results.append(result)
  166. await Scan_Tasks.filter(id=task_id).update(state=2, result={"results": results},
  167. scan_end_time=int(time.time()))
  168. print("扫描完成")
  169. async def commit_task(content,task_id):
  170. commit_result=await asyncio.gather(commit_summary(content), return_exceptions=True)
  171. if isinstance(commit_result, Exception):
  172. print(f"提交出错: {commit_result}")
  173. else:
  174. print("提交成功")
  175. await Commit_Summary_Tasks.filter(id=task_id).update(result=commit_result[0],end_time=int(time.time()))
  176. async def file_task(file_path,task_id):
  177. with open(file_path, 'r', encoding="utf8") as f:
  178. content = f.read()
  179. file_result = await asyncio.gather(file_summary(content), return_exceptions=True)
  180. if isinstance(file_result, Exception):
  181. print(f"提交出错: {file_result}")
  182. else:
  183. print("提交成功")
  184. await File_Summary_Tasks.filter(id=task_id).update(result=file_result[0], end_time=int(time.time()))
  185. @airouter.post("/scan")
  186. async def scan(request: RequestScan, background_tasks: BackgroundTasks):
  187. local_path, repo_name = generate_repo_path(request.uuid, request.repo_url)
  188. repo = await Repos.get(name=repo_name)
  189. repo_id = repo.id
  190. print(f"开始扫描仓库: {repo_name}")
  191. await Scan_Tasks.filter(id=request.task_id).update(state=1, scan_start_time=int(time.time()))
  192. background_tasks.add_task(analysis, local_path, request.task_id)
  193. return {"code": 200, "msg": "添加扫描任务成功"}
  194. @airouter.post("/summaryCommit")
  195. async def summaryCommit(request: RequestCommit, background_tasks: BackgroundTasks):
  196. local_path, repo_name = generate_repo_path(request.uuid, request.repo_url)
  197. repo=await Repos.get(name=repo_name)
  198. repo_id=repo.id
  199. repo_commit=await Commit_Summary_Tasks.get(id=request.task_id)
  200. repo_commit_hash=repo_commit.repo_hash
  201. print(f"开始提交仓库: {repo_name}")
  202. await Commit_Summary_Tasks.filter(id=request.task_id).update(start_time=int(time.time()))
  203. # commit_content = Repo(local_path).git.log('-1', '-p', '--pretty=format:%h %s')
  204. commit_content = Repo(local_path).git.diff(f"{repo_commit_hash}^", repo_commit_hash)
  205. background_tasks.add_task(commit_task,commit_content, request.task_id)
  206. return {"code": 200, "msg": "添加提交任务成功"}
  207. @airouter.post("/summaryFile")
  208. async def summaryFile(request: RequestFile,background_tasks: BackgroundTasks):
  209. local_path, repo_name = generate_repo_path(request.uuid, request.repo_url)
  210. repo=await Repos.get(name=repo_name)
  211. repo_id = repo.id
  212. await File_Summary_Tasks.filter(id=request.task_id).update(start_time=int(time.time()))
  213. background_tasks.add_task(file_task, request.file_path, request.task_id)
  214. return {"code": 200, "msg": "添加提交任务成功"}