复数JADE盲源分离:从四阶累积量到Python工程实现
2026/9/15 1:42:15
在开始部署DeepSeek-OCR-2模型之前,我们需要准备好基础环境。这个开源OCR模型基于深度学习技术,能够高效识别图片中的文字、表格和公式,并保留原始排版结构。
pip install torch torchvision torchaudio pip install transformers pillow opencv-python pip install python-multipart fastapi uvicornDeepSeek-OCR-2的预训练权重已托管在HuggingFace模型库中,我们可以直接下载使用。
from transformers import AutoModelForSequenceClassification, AutoTokenizer model_name = "deepseek/DeepSeek-OCR-2" model = AutoModelForSequenceClassification.from_pretrained(model_name) tokenizer = AutoTokenizer.from_pretrained(model_name)import torch # 测试输入样例 test_input = tokenizer("测试文本", return_tensors="pt") with torch.no_grad(): output = model(**test_input) print(output)为了便于使用,我们将模型封装为REST API服务,使用FastAPI框架。
from fastapi import FastAPI, UploadFile, File from PIL import Image import io app = FastAPI(title="DeepSeek-OCR-2服务") @app.post("/ocr") async def ocr_recognize(file: UploadFile = File(...)): # 读取上传的图片 image_data = await file.read() image = Image.open(io.BytesIO(image_data)) # 预处理图片 processed_image = preprocess_image(image) # 调用模型识别 result = model_recognize(processed_image) return {"text": result}def preprocess_image(image): # 转换为灰度图 if image.mode != 'L': image = image.convert('L') # 调整大小(保持比例) width, height = image.size if width > 1024 or height > 1024: ratio = min(1024/width, 1024/height) new_size = (int(width*ratio), int(height*ratio)) image = image.resize(new_size, Image.Resampling.LANCZOS) return imagedef model_recognize(image): # 将图片转换为模型输入格式 inputs = processor(images=image, return_tensors="pt") # 调用模型推理 with torch.no_grad(): outputs = model(**inputs) # 后处理 result = post_process(outputs) return result def post_process(outputs): # 解码模型输出 preds = outputs.logits.argmax(-1) text = tokenizer.decode(preds[0]) # 格式化输出 formatted_text = format_text(text) return formatted_textif __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)def detect_tables(image): # 使用OpenCV检测表格线 import cv2 import numpy as np img_array = np.array(image) gray = cv2.cvtColor(img_array, cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray, 50, 150, apertureSize=3) # 检测直线 lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=100, minLineLength=100, maxLineGap=10) return lines@app.post("/batch_ocr") async def batch_ocr(files: List[UploadFile] = File(...)): results = [] for file in files: result = await ocr_recognize(file) results.append(result) return {"results": results}通过以上步骤,我们完成了DeepSeek-OCR-2模型从HuggingFace加载到本地服务封装的完整流程。这个服务可以轻松集成到各种应用中,实现高效的文档识别功能。
获取更多AI镜像
想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。