name_classify_api.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import pandas as pd
  2. import os, time, shutil
  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. app = FastAPI()
  14. app.mount("/data", StaticFiles(directory='./process'), name="static")
  15. class ClassificationRequest(BaseModel):
  16. path: str
  17. client_id: str
  18. one_key: str
  19. name_column: str
  20. api_key: str = "sk-iREtaVNjamaBArOTlc_2BfGFJVPiU-9EjSFMUspIPBT3BlbkFJxS0SMmKZD9L9UumPczee4VKawCwVeGBQAr9MgsWGkA"
  21. proxy: bool = False
  22. chunk_size: int = 100
  23. @app.post("/uploadfile/")
  24. async def create_upload_file(file: UploadFile = File(...), client_id: str = Form(...)):
  25. user_directory = f'{basic_path}/{client_id}'
  26. if not os.path.exists(user_directory):
  27. os.makedirs(user_directory)
  28. os.chmod(user_directory, 0o777) # 设置用户目录权限为777
  29. file_location = os.path.join(user_directory, file.filename)
  30. try:
  31. with open(file_location, "wb+") as file_object:
  32. file_object.write(file.file.read())
  33. os.chmod(file_location, 0o777) # 设置文件权限为777
  34. return JSONResponse(content={
  35. "message": f"文件 '{file.filename}' 上传成功",
  36. "client_id": client_id,
  37. "file_path": file_location
  38. }, status_code=200)
  39. except Exception as e:
  40. return JSONResponse(content={"message": f"发生错误: {str(e)}"}, status_code=500)
  41. @app.post("/classify/")
  42. async def classify_data(request: ClassificationRequest):
  43. try:
  44. current_time = time.time()
  45. TIME_THRESHOLD_FILEPATH = 30 * 24 * 60 * 60
  46. TIME_THRESHOLD_FILE = 10 * 24 * 60 * 60
  47. for root, dirs, files in os.walk(basic_path, topdown=False):
  48. # 删除文件
  49. for file in files:
  50. file_path = os.path.join(root, file)
  51. if current_time - os.path.getmtime(file_path) > TIME_THRESHOLD_FILE:
  52. print(f"删除文件: {file_path}")
  53. os.remove(file_path)
  54. # 删除文件夹
  55. for dir in dirs:
  56. dir_path = os.path.join(root, dir)
  57. if current_time - os.path.getmtime(dir_path) > TIME_THRESHOLD_FILEPATH:
  58. print(f"删除文件夹: {dir_path}")
  59. shutil.rmtree(dir_path)
  60. work_path = f'{basic_path}/{request.client_id}'
  61. if not os.path.exists(work_path):
  62. os.makedirs(work_path, exist_ok=True)
  63. timestamp_str = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
  64. df_origin = pd.read_excel(request.path)
  65. df_origin['name'] = df_origin[request.name_column]
  66. df_origin['classify'] = ''
  67. df_use = df_origin[['name', 'classify']]
  68. deal_result = split_dataframe_to_dict(df_use, request.chunk_size)
  69. # 生成当前时间的时间戳字符串
  70. temp_csv = work_path + '/' + timestamp_str + 'output_temp.csv'
  71. final_file_name, final_file_extension = os.path.splitext(os.path.basename(request.path))
  72. # 添加后缀
  73. final_file = final_file_name + '_classify' + final_file_extension
  74. # 生成新的文件路径
  75. new_file_path = os.path.join(os.path.dirname(request.path), final_file)
  76. if not request.proxy:
  77. print(f'用户{request.client_id}正在使用直连的gpt-API')
  78. client = openai.OpenAI(api_key=request.api_key, base_url=openai_url)
  79. else:
  80. client = openai.OpenAI(api_key=request.api_key, base_url=proxy_url)
  81. for name, value in tqdm(deal_result.items(), desc='Processing', unit='item'):
  82. try:
  83. message = [
  84. {'role':'system', 'content': cls_system_prompt},
  85. {'role':'user', 'content':user_prompt.format(chunk=str(value))}
  86. ]
  87. # result_string = post_openai(message)
  88. response = client.chat.completions.create(model='gpt-4',messages=message)
  89. result_string = response.choices[0].message.content
  90. result = extract_list_from_string(result_string)
  91. if result:
  92. df_output = pd.DataFrame(result)
  93. df_output.to_csv(temp_csv, mode='a', header=True, index=False)
  94. else:
  95. continue
  96. except Exception as e:
  97. print(f'{name}出现问题啦, 错误为:{e} 请自行调试')
  98. if os.path.exists(temp_csv):
  99. df_result = pd.read_csv(temp_csv)
  100. df_final = df_origin.merge(df_result, on='name', how='left').drop_duplicates(subset=[request.one_key,'name'], keep='first')
  101. df_final.to_excel(new_file_path)
  102. return {"message": "分类完成", "output_file": file_base_url + new_file_path.split(basic_path)[1]}
  103. else:
  104. return {"message": "文件没能处理成功"}
  105. except Exception as e:
  106. return {"message": f"处理出现错误: {e}"}
  107. if __name__ == "__main__":
  108. uvicorn.run(app, host="0.0.0.0", port=port)