mnhkahn commited on
Commit
6d3e196
·
1 Parent(s): d7eebf6

feat: 添加汉字书法识别功能及相关依赖

Browse files

- 新增模型加载、图像预处理和质量评估功能
- 实现基于FastAPI的识别接口和调试接口
- 添加必要的依赖库包括torch和opencv
- 提供健康检查接口和静态文件服务

Files changed (2) hide show
  1. app.py +300 -4
  2. requirements.txt +5 -0
app.py CHANGED
@@ -1,7 +1,303 @@
1
- from fastapi import FastAPI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- app = FastAPI()
4
 
5
  @app.get("/")
6
- def greet_json():
7
- return {"Hello": "World!"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import torch
4
+ import torch.nn as nn
5
+ from torchvision.models import resnet50
6
+ from torchvision.transforms import transforms
7
+ from PIL import Image, ImageOps, ImageEnhance
8
+ from typing import List, Dict
9
+ from fastapi import FastAPI, File, UploadFile, HTTPException, Request
10
+ from fastapi.middleware.cors import CORSMiddleware
11
+ from fastapi.responses import JSONResponse
12
+ import io
13
+ import cv2
14
+ import numpy as np
15
+ import hashlib
16
+ import logging
17
+ from PIL.ExifTags import TAGS
18
+
19
+ # 设置日志
20
+ logging.basicConfig(level=logging.INFO)
21
+ logger = logging.getLogger(__name__)
22
+
23
+ # --- 配置部分 ---
24
+ MODEL_PATH = "best_model.pth"
25
+ MAP_PATH = "char_map.json"
26
+
27
+
28
+ # --- 全局初始化模型(启动时加载一次) ---
29
+ class Recognizer:
30
+ def __init__(self, model_path: str = MODEL_PATH, map_path: str = MAP_PATH):
31
+ if not os.path.exists(model_path) or not os.path.exists(map_path):
32
+ raise FileNotFoundError(
33
+ f"模型文件 '{model_path}' 或字符映射表 '{map_path}' 不存在,"
34
+ "请先运行 train_model.py 进行模型训练。"
35
+ )
36
+
37
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
38
+
39
+ # 加载字符映射
40
+ with open(map_path, "r", encoding="utf-8") as f:
41
+ self.char_to_idx = json.load(f)
42
+ self.idx_to_char = {v: k for k, v in self.char_to_idx.items()}
43
+ num_classes = len(self.char_to_idx)
44
+
45
+ # 构建并加载模型
46
+ self.model = self._get_model(num_classes)
47
+ try:
48
+ ckpt = torch.load(model_path, map_location=self.device, weights_only=True)
49
+ except Exception:
50
+ ckpt = torch.load(model_path, map_location=self.device, weights_only=False)
51
+ if isinstance(ckpt, nn.Module):
52
+ state_dict = ckpt.state_dict()
53
+ elif isinstance(ckpt, dict):
54
+ state_dict = ckpt.get("state_dict", ckpt.get("model_state", ckpt))
55
+ else:
56
+ raise ValueError("不支持的模型文件格式")
57
+ self.model.load_state_dict(state_dict, strict=False)
58
+ self.model.to(self.device)
59
+ self.model.eval()
60
+
61
+ # 定义图像预处理
62
+ self.transform = transforms.Compose(
63
+ [
64
+ transforms.Resize((224, 224)),
65
+ transforms.ToTensor(),
66
+ transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
67
+ ]
68
+ )
69
+
70
+ def _get_model(self, num_classes: int) -> nn.Module:
71
+ model = resnet50(weights=None)
72
+ num_ftrs = model.fc.in_features
73
+ model.fc = nn.Sequential(nn.Dropout(0.3), nn.Linear(num_ftrs, num_classes))
74
+ return model
75
+
76
+ def preprocess_image(self, image_bytes: bytes, user_agent: str = "") -> Image.Image:
77
+ """统一的图像预处理,特别处理移动设备上传的图片"""
78
+ try:
79
+ image = Image.open(io.BytesIO(image_bytes))
80
+
81
+ # 记录原始图像信息用于调试
82
+ logger.info(
83
+ f"原始图像 - 格式: {image.format}, 模式: {image.mode}, 尺寸: {image.size}"
84
+ )
85
+
86
+ # 处理EXIF方向信息(手机照片常有旋转问题)
87
+ try:
88
+ exif = image._getexif()
89
+ if exif:
90
+ for tag, value in exif.items():
91
+ decoded = TAGS.get(tag, tag)
92
+ if decoded == "Orientation":
93
+ if value == 3:
94
+ image = image.rotate(180, expand=True)
95
+ elif value == 6:
96
+ image = image.rotate(270, expand=True)
97
+ elif value == 8:
98
+ image = image.rotate(90, expand=True)
99
+ break
100
+ except Exception as e:
101
+ logger.warning(f"EXIF处理失败: {e}")
102
+
103
+ # 转换为RGB
104
+ if image.mode != "RGB":
105
+ image = image.convert("RGB")
106
+
107
+ # 检测是否为移动设备并应用增强处理
108
+ is_mobile = any(
109
+ mobile_indicator in user_agent.lower()
110
+ for mobile_indicator in ["mobile", "iphone", "android", "ipad"]
111
+ )
112
+
113
+ if is_mobile:
114
+ logger.info("检测到移动设备,应用增强预处理")
115
+ # 增强对比度
116
+ enhancer = ImageEnhance.Contrast(image)
117
+ image = enhancer.enhance(1.2)
118
+
119
+ # 轻微锐化
120
+ enhancer = ImageEnhance.Sharpness(image)
121
+ image = enhancer.enhance(1.1)
122
+
123
+ return image
124
+
125
+ except Exception as e:
126
+ raise ValueError(f"无法处理图片: {e}")
127
+
128
+ def assess_image_quality(self, image: Image.Image) -> Dict:
129
+ """评估图像质量"""
130
+ # 转换为numpy数组进行处理
131
+ img_array = np.array(image)
132
+
133
+ if len(img_array.shape) == 3:
134
+ gray = cv2.cvtColor(img_array, cv2.COLOR_RGB2GRAY)
135
+ else:
136
+ gray = img_array
137
+
138
+ # 计算清晰度(拉普拉斯方差)
139
+ clarity = cv2.Laplacian(gray, cv2.CV_64F).var()
140
+
141
+ # 计算亮度和对比度
142
+ brightness = np.mean(gray)
143
+ contrast = np.std(gray)
144
+
145
+ quality_info = {
146
+ "clarity": float(clarity),
147
+ "brightness": float(brightness),
148
+ "contrast": float(contrast),
149
+ "is_acceptable": clarity > 50 and 30 < brightness < 220,
150
+ }
151
+
152
+ logger.info(f"图像质量评估: {quality_info}")
153
+ return quality_info
154
+
155
+ def recognize(
156
+ self, image_bytes: bytes, top_k: int = 5, user_agent: str = ""
157
+ ) -> List[Dict[str, str]]:
158
+ """
159
+ 识别上传的图像。
160
+
161
+ Args:
162
+ image_bytes: 图片的二进制数据。
163
+ top_k: 返回前k个结果。
164
+ user_agent: 用户代理字符串,用于设备检测
165
+
166
+ Returns:
167
+ 一个字典列表,每个字典包含 `char` 和 `prob` 键。
168
+ """
169
+ # 记录图像哈希用于调试
170
+ image_hash = hashlib.md5(image_bytes).hexdigest()
171
+ logger.info(f"处理图像 - 哈希: {image_hash}, 设备: {user_agent}")
172
+
173
+ # 预处理图像
174
+ image = self.preprocess_image(image_bytes, user_agent)
175
+
176
+ # 评估图像质量
177
+ quality_info = self.assess_image_quality(image)
178
+ if not quality_info["is_acceptable"]:
179
+ logger.warning(f"图像质量可能影响识别: {quality_info}")
180
+
181
+ # 应用模型预处理
182
+ image_tensor = self.transform(image).unsqueeze(0).to(self.device)
183
+
184
+ with torch.no_grad():
185
+ outputs = self.model(image_tensor)
186
+ probabilities = torch.nn.functional.softmax(outputs, dim=1)
187
+ top_probs, top_indices = torch.topk(probabilities, top_k)
188
+
189
+ results = []
190
+ top_probs_np = top_probs.cpu().numpy().flatten()
191
+ top_indices_np = top_indices.cpu().numpy().flatten()
192
+
193
+ for i in range(top_k):
194
+ char_idx = top_indices_np[i]
195
+ char_name = self.idx_to_char.get(char_idx, "?")
196
+ probability = top_probs_np[i]
197
+ results.append({"char": char_name, "prob": f"{probability:.2%}"})
198
+
199
+ logger.info(f"识别结果: {results}")
200
+ return results
201
+
202
+
203
+ # --- FastAPI 应用初始化 ---
204
+ app = FastAPI(
205
+ title="汉字书法字体识别",
206
+ description="上传一张汉字图片,返回识别出的汉字及其置信度。",
207
+ version="1.0.0",
208
+ )
209
+
210
+ # 添加 CORS 中间件
211
+ app.add_middleware(
212
+ CORSMiddleware,
213
+ allow_origins=["*"], # 生产环境请替换为具体域名
214
+ allow_credentials=True,
215
+ allow_methods=["*"],
216
+ allow_headers=["*"],
217
+ )
218
+
219
+ # 初始化识别器(全局单例)
220
+ try:
221
+ recognizer = Recognizer()
222
+ logger.info("模型加载成功,服务已启动")
223
+ except Exception as e:
224
+ logger.error(f"启动失败: {e}")
225
+ recognizer = None
226
+
227
+
228
+ # --- API 路由 ---
229
+ @app.post("/upload", response_model=List[Dict[str, str]])
230
+ async def upload_image(request: Request, file: UploadFile = File(...)):
231
+ """
232
+ 上传图片进行汉字识别。
233
+
234
+ - **file**: 需要识别的图片文件 (jpg, png, etc.)
235
+ """
236
+ if not recognizer:
237
+ raise HTTPException(status_code=503, detail="服务暂不可用,模型文件未找到。")
238
+
239
+ # 检查文件类型
240
+ if not file.content_type.startswith("image/"):
241
+ raise HTTPException(status_code=400, detail="上传的文件必须是图片格式。")
242
+
243
+ try:
244
+ image_bytes = await file.read()
245
+ user_agent = request.headers.get("User-Agent", "")
246
+ results = recognizer.recognize(image_bytes, top_k=5, user_agent=user_agent)
247
+ return results
248
+ except ValueError as ve:
249
+ logger.error(f"图片处理错误: {ve}")
250
+ raise HTTPException(status_code=400, detail=str(ve))
251
+ except Exception as e:
252
+ logger.error(f"识别错误: {e}")
253
+ raise HTTPException(status_code=500, detail=f"服务器内部错误: {e}")
254
+
255
+
256
+ # 调试接口
257
+ @app.post("/debug_upload")
258
+ async def debug_upload(request: Request, file: UploadFile = File(...)):
259
+ """调试接口,返回上传图片的详细信息"""
260
+ try:
261
+ image_bytes = await file.read()
262
+ user_agent = request.headers.get("User-Agent", "")
263
+
264
+ # 使用recognizer的预处理方法来分析图片
265
+ image = recognizer.preprocess_image(image_bytes, user_agent)
266
+ quality_info = recognizer.assess_image_quality(image)
267
+
268
+ debug_info = {
269
+ "file_size": len(image_bytes),
270
+ "file_hash": hashlib.md5(image_bytes).hexdigest(),
271
+ "image_size": image.size,
272
+ "image_mode": image.mode,
273
+ "quality_assessment": quality_info,
274
+ "user_agent": user_agent,
275
+ }
276
+
277
+ return JSONResponse(content=debug_info)
278
+ except Exception as e:
279
+ logger.error(f"调试接口错误: {e}")
280
+ raise HTTPException(status_code=500, detail=str(e))
281
+
282
+
283
+ from fastapi.staticfiles import StaticFiles
284
+
285
+ app.mount("/", StaticFiles(directory="static", html=True), name="web")
286
 
 
287
 
288
  @app.get("/")
289
+ async def root():
290
+ return {"message": "欢迎使用汉字书法识别模型,请使用 POST /upload 接口上传图片。"}
291
+
292
+
293
+ @app.get("/health")
294
+ async def health_check():
295
+ """健康检查接口"""
296
+ status = "healthy" if recognizer else "unhealthy"
297
+ return {"status": status, "model_loaded": recognizer is not None}
298
+
299
+
300
+ if __name__ == "__main__":
301
+ import uvicorn
302
+
303
+ uvicorn.run(app, host="0.0.0.0", port=8000, log_level="info")
requirements.txt CHANGED
@@ -1,2 +1,7 @@
1
  fastapi
2
  uvicorn[standard]
 
 
 
 
 
 
1
  fastapi
2
  uvicorn[standard]
3
+ torch
4
+ torchvision
5
+ Pillow
6
+ opencv-python
7
+ numpy