66 lines
2.5 KiB
Python
66 lines
2.5 KiB
Python
from fastapi import APIRouter, Depends, UploadFile, File
|
||
from app.core.response import success_response, error_response, ResponseModel
|
||
from app.core.ai_client import ai_client
|
||
from app.api.deps import get_current_user
|
||
from app.models.user import UserDB
|
||
import logging
|
||
from app.core.qcloud import qcloud_manager
|
||
|
||
router = APIRouter()
|
||
|
||
@router.post("/extract_pickup_code", response_model=ResponseModel)
|
||
async def extract_pickup_code(
|
||
file: UploadFile = File(...)
|
||
):
|
||
"""从图片中提取取件码"""
|
||
try:
|
||
# 检查文件类型
|
||
if not file.content_type.startswith('image/'):
|
||
return error_response(code=400, message="只能上传图片文件")
|
||
|
||
url = await qcloud_manager.upload_file(file)
|
||
if not url:
|
||
return error_response(code=500, message="上传图片失败")
|
||
|
||
# 调用 AI 客户端提取取件码
|
||
result = await ai_client.extract_pickup_code(url)
|
||
|
||
if "error" in result:
|
||
return error_response(code=500, message=result.get("message", "提取取件码失败"))
|
||
|
||
# 检查是否提取到取件码
|
||
if not result.get("stations") or not any(station.get("pickup_codes") for station in result.get("stations", [])):
|
||
return error_response(code=400, message="提取取件码信息失败")
|
||
|
||
# 格式化输出
|
||
formatted_text = format_pickup_codes(result)
|
||
|
||
# 返回原始数据和格式化文本
|
||
return success_response(data={
|
||
"raw": result,
|
||
"formatted_text": formatted_text
|
||
})
|
||
|
||
except Exception as e:
|
||
logging.exception(f"提取取件码失败: {str(e)}")
|
||
return error_response(code=500, message=f"提取取件码失败: {str(e)}")
|
||
|
||
def format_pickup_codes(result):
|
||
"""将取件码结果格式化为指定格式"""
|
||
formatted_lines = []
|
||
|
||
for station in result.get("stations", []):
|
||
station_name = station.get("name", "未知驿站")
|
||
pickup_codes = station.get("pickup_codes", [])
|
||
|
||
if pickup_codes:
|
||
# 格式化取件码,用 | 分隔
|
||
codes_text = " | ".join(pickup_codes)
|
||
|
||
# 添加驿站和取件码信息
|
||
formatted_lines.append(f"驿站:{station_name}")
|
||
formatted_lines.append(f"取件码:{codes_text}")
|
||
formatted_lines.append("") # 添加空行分隔不同驿站
|
||
|
||
# 合并所有行
|
||
return "\n".join(formatted_lines).strip() |