name_classify_api.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. import pandas as pd
  2. import os, time, shutil, sys
  3. import openai
  4. from fastapi import FastAPI, UploadFile, File, Form
  5. from pydantic import BaseModel
  6. from fastapi.responses import JSONResponse
  7. from datetime import datetime
  8. import uvicorn, socket
  9. from tqdm import tqdm
  10. from fastapi.staticfiles import StaticFiles
  11. from config import *
  12. from functions import split_dataframe_to_dict, extract_list_from_string
  13. sys.path.append(os.path.join(os.path.dirname(__file__), 'bert'))
  14. import torch
  15. # from model import BertClassifier
  16. from bert.model import BertClassifier
  17. from transformers import BertTokenizer, BertConfig
  18. app = FastAPI()
  19. app.mount("/data", StaticFiles(directory='./process'), name="static")
  20. class ClassificationRequest(BaseModel):
  21. path: str
  22. client_id: str
  23. one_key: str
  24. name_column: str
  25. api_key: str = "sk-iREtaVNjamaBArOTlc_2BfGFJVPiU-9EjSFMUspIPBT3BlbkFJxS0SMmKZD9L9UumPczee4VKawCwVeGBQAr9MgsWGkA"
  26. proxy: bool = False
  27. chunk_size: int = 100
  28. class ClassificationRequestBert(BaseModel):
  29. path: str
  30. client_id: str
  31. name_column: str
  32. bert_config = BertConfig.from_pretrained(pre_train_model)
  33. # 定义模型
  34. model = BertClassifier(bert_config, len(label_revert_map.keys()))
  35. # 加载训练好的模型
  36. model.load_state_dict(torch.load(model_save_path, map_location=torch.device('cpu')))
  37. model.eval()
  38. tokenizer = BertTokenizer.from_pretrained(pre_train_model)
  39. def bert_predict(text):
  40. token = tokenizer(text, add_special_tokens=True, padding='max_length', truncation=True, max_length=512)
  41. input_ids = token['input_ids']
  42. attention_mask = token['attention_mask']
  43. token_type_ids = token['token_type_ids']
  44. input_ids = torch.tensor([input_ids], dtype=torch.long)
  45. attention_mask = torch.tensor([attention_mask], dtype=torch.long)
  46. token_type_ids = torch.tensor([token_type_ids], dtype=torch.long)
  47. predicted = model(
  48. input_ids,
  49. attention_mask,
  50. token_type_ids,
  51. )
  52. pred_label = torch.argmax(predicted, dim=1).numpy()[0]
  53. return label_revert_map[pred_label]
  54. def predict_excel(file_path, name_col, temp_path, save_path, chunksize=5):
  55. # 初始化变量
  56. error_file_name, error_file_extension = os.path.splitext(os.path.basename(save_path))
  57. # 添加后缀
  58. error_file = error_file_name + '_error' + error_file_extension
  59. origin_csv_file = error_file_name + '_origin.csv'
  60. # 生成新的文件路径
  61. error_file_path = os.path.join(os.path.dirname(save_path), error_file)
  62. origin_csv_path = os.path.join(os.path.dirname(save_path), origin_csv_file)
  63. total_processed = 0
  64. df_origin = pd.read_excel(file_path)
  65. df_error = pd.DataFrame(columns=df_origin.columns)
  66. df_origin.to_csv(origin_csv_path, index=False)
  67. # 按块读取 CSV 文件
  68. for chunk in tqdm(pd.read_csv(origin_csv_path, chunksize=chunksize, iterator=True), desc='Processing', unit='item'):
  69. try:
  70. # 对每个块进行处理
  71. chunk['classify'] = chunk[name_col].apply(bert_predict)
  72. # 增量保存处理结果
  73. if total_processed == 0:
  74. chunk.to_csv(temp_path, mode='w', index=False)
  75. else:
  76. chunk.to_csv(temp_path, mode='a', header=False, index=False)
  77. # 更新已处理的数据量
  78. total_processed += len(chunk)
  79. except Exception as e:
  80. df_error = pd.concat([df_error, chunk])
  81. df_final = pd.read_csv(temp_path)
  82. df_final.to_excel(save_path)
  83. os.remove(origin_csv_path)
  84. if len(df_error) == 0:
  85. return save_path, '', 0
  86. else:
  87. df_error.to_excel(error_file_path)
  88. return save_path, error_file_path, len(df_error)
  89. def remove_files():
  90. current_time = time.time()
  91. TIME_THRESHOLD_FILEPATH = 30 * 24 * 60 * 60
  92. TIME_THRESHOLD_FILE = 10 * 24 * 60 * 60
  93. for root, dirs, files in os.walk(basic_path, topdown=False):
  94. # 删除文件
  95. for file in files:
  96. file_path = os.path.join(root, file)
  97. if current_time - os.path.getmtime(file_path) > TIME_THRESHOLD_FILE:
  98. print(f"删除文件: {file_path}")
  99. os.remove(file_path)
  100. # 删除文件夹
  101. for dir in dirs:
  102. dir_path = os.path.join(root, dir)
  103. if current_time - os.path.getmtime(dir_path) > TIME_THRESHOLD_FILEPATH:
  104. print(f"删除文件夹: {dir_path}")
  105. shutil.rmtree(dir_path)
  106. @app.post("/uploadfile/")
  107. async def create_upload_file(file: UploadFile = File(...), client_id: str = Form(...)):
  108. user_directory = f'{basic_path}/{client_id}'
  109. if not os.path.exists(user_directory):
  110. os.makedirs(user_directory)
  111. os.chmod(user_directory, 0o777) # 设置用户目录权限为777
  112. file_location = os.path.join(user_directory, file.filename)
  113. try:
  114. with open(file_location, "wb+") as file_object:
  115. file_object.write(file.file.read())
  116. os.chmod(file_location, 0o777) # 设置文件权限为777
  117. return JSONResponse(content={
  118. "message": f"文件 '{file.filename}' 上传成功",
  119. "client_id": client_id,
  120. "file_path": file_location
  121. }, status_code=200)
  122. except Exception as e:
  123. return JSONResponse(content={"message": f"发生错误: {str(e)}"}, status_code=500)
  124. @app.post("/classify_openai/")
  125. async def classify_data(request: ClassificationRequest):
  126. try:
  127. remove_files()
  128. work_path = f'{basic_path}/{request.client_id}'
  129. if not os.path.exists(work_path):
  130. os.makedirs(work_path, exist_ok=True)
  131. timestamp_str = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
  132. df_origin = pd.read_excel(request.path)
  133. df_origin['name'] = df_origin[request.name_column]
  134. df_origin['classify'] = ''
  135. df_use = df_origin[['name', 'classify']]
  136. deal_result = split_dataframe_to_dict(df_use, request.chunk_size)
  137. # 生成当前时间的时间戳字符串
  138. temp_csv = work_path + '/' + timestamp_str + 'output_temp.csv'
  139. final_file_name, final_file_extension = os.path.splitext(os.path.basename(request.path))
  140. # 添加后缀
  141. final_file = final_file_name + '_classify' + final_file_extension
  142. # 生成新的文件路径
  143. new_file_path = os.path.join(os.path.dirname(request.path), final_file)
  144. if not request.proxy:
  145. print(f'用户{request.client_id}正在使用直连的gpt-API')
  146. client = openai.OpenAI(api_key=request.api_key, base_url=openai_url)
  147. else:
  148. client = openai.OpenAI(api_key=request.api_key, base_url=proxy_url)
  149. for name, value in tqdm(deal_result.items(), desc='Processing', unit='item'):
  150. try:
  151. message = [
  152. {'role':'system', 'content': cls_system_prompt},
  153. {'role':'user', 'content':user_prompt.format(chunk=str(value))}
  154. ]
  155. # result_string = post_openai(message)
  156. response = client.chat.completions.create(model='gpt-4',messages=message)
  157. result_string = response.choices[0].message.content
  158. result = extract_list_from_string(result_string)
  159. if result:
  160. df_output = pd.DataFrame(result)
  161. df_output.to_csv(temp_csv, mode='a', header=True, index=False)
  162. else:
  163. continue
  164. except Exception as e:
  165. print(f'{name}出现问题啦, 错误为:{e} 请自行调试')
  166. if os.path.exists(temp_csv):
  167. df_result = pd.read_csv(temp_csv)
  168. df_final = df_origin.merge(df_result, on='name', how='left').drop_duplicates(subset=[request.one_key,'name'], keep='first')
  169. df_final.to_excel(new_file_path)
  170. return {"message": "分类完成", "output_file": file_base_url + new_file_path.split(basic_path)[1]}
  171. else:
  172. return {"message": "文件没能处理成功"}
  173. except Exception as e:
  174. return {"message": f"处理出现错误: {e}"}
  175. @app.post("/classify_bert/")
  176. async def classify_data(request: ClassificationRequestBert):
  177. remove_files()
  178. work_path = f'{basic_path}/{request.client_id}'
  179. if not os.path.exists(work_path):
  180. os.makedirs(work_path, exist_ok=True)
  181. final_file_name, final_file_extension = os.path.splitext(os.path.basename(request.path))
  182. # 添加后缀
  183. final_file = final_file_name + '_classify' + final_file_extension
  184. # 生成新的文件路径
  185. new_file_path = os.path.join(os.path.dirname(request.path), final_file)
  186. timestamp_str = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
  187. temp_csv = work_path + '/' + timestamp_str + 'output_temp.csv'
  188. save_path, error_path, error_len = predict_excel(request.path, request.name_column, temp_path=temp_csv ,save_path=new_file_path)
  189. if error_len == 0:
  190. return {"message": "分类完成", "output_file": file_base_url + save_path.split(basic_path)[1]}
  191. else:
  192. return {"message": "分类完成只完成部分", "output_file": file_base_url + save_path.split(basic_path)[1], "output_file_nonprocess":file_base_url + save_path.split(error_path)[1],}
  193. if __name__ == "__main__":
  194. uvicorn.run(app, host="0.0.0.0", port=port)