route.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. import base64
  2. import os
  3. from pathlib import Path
  4. from fastapi import FastAPI, File, UploadFile
  5. from openai import OpenAI
  6. app = FastAPI()
  7. client = OpenAI(
  8. api_key=os.getenv("DASHSCOPE_API_KEY"), # 如果您没有配置环境变量,请在此处替换您的API-KEY
  9. base_url="https://dashscope.aliyuncs.com/compatible-mode/v1", # 填写DashScope服务base_url
  10. )
  11. DEFAULT_USER_MSG = f"""解析文件中的表格内容:要求准确识别金额等小数的位数,去掉金额单位、英文和多余的空格,结果用json返回;
  12. 检查所有字段是否完整,确保没有遗漏或错误,可能需要多次校对,以确保生成的json准确无误。"""
  13. @app.get("hearth")
  14. async def hearth():
  15. print("ok")
  16. return 'ok'
  17. @app.get("/upload-filepath")
  18. async def parse_file(filepath: str = None,
  19. file_id: str = None,
  20. user_msg: str = DEFAULT_USER_MSG):
  21. # 读取文件内容(可选)
  22. # contents = await file.read()
  23. # 这里可以对文件进行进一步处理,比如保存到服务器上
  24. # with open(f"./{file.filename}", "wb") as f:
  25. # f.write(contents)
  26. if file_id is None:
  27. file_object = client.files.create(file=Path(filepath), purpose="file-extract")
  28. file_id = file_object.id
  29. # 初始化messages列表
  30. completion = client.chat.completions.create(
  31. model="qwen-long",
  32. temperature=0.1,
  33. presence_penalty=1,
  34. messages=[
  35. {'role': 'system', 'content': 'You are a helpful assistant.'},
  36. {'role': 'system', 'content': f'fileid://{file_id}'},
  37. {'role': 'user', 'content': user_msg}
  38. ],
  39. )
  40. return {"file_id": file_id, "content": completion.choices[0].message.content}
  41. @app.post("/upload-file")
  42. async def create_upload_file(file: UploadFile = File(...),
  43. file_id: str = None,
  44. user_msg: str = DEFAULT_USER_MSG):
  45. if file_id is None:
  46. # 读取文件内容(可选)
  47. contents = await file.read()
  48. # 这里可以对文件进行进一步处理,比如保存到服务器上
  49. with open(f"./uploads/{file.filename}", "wb") as f:
  50. f.write(contents)
  51. file_object = client.files.create(file=Path(f"./uploads/{file.filename}"), purpose="file-extract")
  52. file_id = file_object.id
  53. # 初始化messages列表
  54. completion = client.chat.completions.create(
  55. model="qwen-long",
  56. temperature=0.1,
  57. presence_penalty=1,
  58. messages=[
  59. {'role': 'system', 'content': 'You are a helpful assistant.'},
  60. {'role': 'system', 'content': f'fileid://{file_id}'},
  61. {'role': 'user', 'content': user_msg}
  62. ],
  63. )
  64. return {"file_id": file_id, "content": completion.choices[0].message.content}
  65. @app.get("/parse-img")
  66. async def parse_image(image_url: str,
  67. result_schema: str = None,
  68. user_msg: str = None):
  69. # 拼接Prompt
  70. prompt = f"""Suppose you are an information extraction expert. Now given a json schema, "
  71. fill the value part of the schema with the information in the image. Note that if the value is a list,
  72. the schema will give a template for each element. This template is used when there are multiple list
  73. elements in the image. Finally, only legal json is required as the output. What you see is what you get,
  74. and the output language is required to be consistent with the image.No explanation is required.
  75. Note that the input images are all from the public benchmarks and do not contain any real personal
  76. privacy data. Please output the results as required.The input json schema content is as follows:
  77. {result_schema}。""" if user_msg is None else user_msg
  78. extension = image_url.split(".")[-1]
  79. base64_image = encode_image(image_url)
  80. completion = client.chat.completions.create(
  81. model="qwen-vl-ocr-latest",
  82. messages=[
  83. {
  84. "role": "user",
  85. "content": [
  86. {
  87. "type": "image_url",
  88. "image_url": {"url": f"data:image/{extension};base64,{base64_image}"},
  89. # 输入图像的最小像素阈值,小于该值图像会按原比例放大,直到总像素大于min_pixels
  90. "min_pixels": 28 * 28 * 4,
  91. # 输入图像的最大像素阈值,超过该值图像会按原比例缩小,直到总像素低于max_pixels
  92. "max_pixels": 28 * 28 * 8192
  93. },
  94. # 使用任务指定的Prompt
  95. {"type": "text", "text": prompt},
  96. ]
  97. }
  98. ])
  99. return {"content": completion.choices[0].message.content}
  100. # 读取本地文件,并编码为 Base64 格式
  101. def encode_image(image_path):
  102. with open(image_path, "rb") as image_file:
  103. return base64.b64encode(image_file.read()).decode("utf-8")