Mageia commited on
Commit
dcec5ef
·
unverified ·
1 Parent(s): a5dcb7e

feat(api): Shifted gears and added logging 🪵 and CORS! What a ride!

Browse files

- Added logging functionality to the `/ocr` and `/` endpoints in `app.py`. Now we can keep an eye on who's doing what with our awesome API! 👀
- Integrated CORS middleware in `app.py` to allow cross-origin requests. Let's break down those barriers and spread the OCR joy! 🌍 🎉

Files changed (1) hide show
  1. app.py +50 -3
app.py CHANGED
@@ -1,12 +1,28 @@
1
  import base64
 
2
  import os
 
3
 
4
  import torch
5
- from fastapi import FastAPI, File, Form, UploadFile
 
6
  from transformers import AutoModel, AutoTokenizer
7
 
 
 
 
 
8
  app = FastAPI()
9
 
 
 
 
 
 
 
 
 
 
10
  # 初始化模型
11
  model_name = "ucaslcl/GOT-OCR2_0"
12
  device = "cuda" if torch.cuda.is_available() else "cpu"
@@ -44,7 +60,23 @@ async def ocr_process(image_path, got_mode, ocr_color="", ocr_box=""):
44
 
45
 
46
  @app.post("/ocr")
47
- async def ocr_api(image: UploadFile = File(...), got_mode: str = Form(...), ocr_color: str = Form(""), ocr_box: str = Form("")):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  # 保存上传的图片
49
  image_path = f"temp_{image.filename}"
50
  with open(image_path, "wb") as buffer:
@@ -56,9 +88,24 @@ async def ocr_api(image: UploadFile = File(...), got_mode: str = Form(...), ocr_
56
  # 删除临时文件
57
  os.remove(image_path)
58
 
 
 
 
59
  return result
60
 
61
 
62
  @app.get("/")
63
- def read_root():
 
 
 
 
 
 
 
 
 
 
 
 
64
  return {"message": "欢迎使用OCR API"}
 
1
  import base64
2
+ import logging
3
  import os
4
+ from datetime import datetime
5
 
6
  import torch
7
+ from fastapi import FastAPI, File, Form, Request, UploadFile
8
+ from fastapi.middleware.cors import CORSMiddleware
9
  from transformers import AutoModel, AutoTokenizer
10
 
11
+ # 配置日志
12
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
13
+ logger = logging.getLogger(__name__)
14
+
15
  app = FastAPI()
16
 
17
+ # 添加CORS中间件
18
+ app.add_middleware(
19
+ CORSMiddleware,
20
+ allow_origins=["*"],
21
+ allow_credentials=True,
22
+ allow_methods=["*"],
23
+ allow_headers=["*"],
24
+ )
25
+
26
  # 初始化模型
27
  model_name = "ucaslcl/GOT-OCR2_0"
28
  device = "cuda" if torch.cuda.is_available() else "cpu"
 
60
 
61
 
62
  @app.post("/ocr")
63
+ async def ocr_api(request: Request, image: UploadFile = File(...), got_mode: str = Form(...), ocr_color: str = Form(""), ocr_box: str = Form("")):
64
+ # 记录请求信息
65
+ client_host = request.client.host
66
+ user_agent = request.headers.get("user-agent", "Unknown")
67
+ current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
68
+
69
+ log_message = f"""
70
+ 时间: {current_time}
71
+ IP地址: {client_host}
72
+ User-Agent: {user_agent}
73
+ 图片名称: {image.filename}
74
+ OCR模式: {got_mode}
75
+ OCR颜色: {ocr_color}
76
+ OCR边界框: {ocr_box}
77
+ """
78
+ logger.info(log_message)
79
+
80
  # 保存上传的图片
81
  image_path = f"temp_{image.filename}"
82
  with open(image_path, "wb") as buffer:
 
88
  # 删除临时文件
89
  os.remove(image_path)
90
 
91
+ # 记录处理结果
92
+ logger.info(f"OCR处理结果: {result}")
93
+
94
  return result
95
 
96
 
97
  @app.get("/")
98
+ async def read_root(request: Request):
99
+ client_host = request.client.host
100
+ user_agent = request.headers.get("user-agent", "Unknown")
101
+ current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
102
+
103
+ log_message = f"""
104
+ 时间: {current_time}
105
+ IP地址: {client_host}
106
+ User-Agent: {user_agent}
107
+ 访问: 根路径
108
+ """
109
+ logger.info(log_message)
110
+
111
  return {"message": "欢迎使用OCR API"}