【转载】代码:DeepSeek-OCR硅基流动API使用教程:轻松实现高精度OCR识别

📅 发布时间:2026/7/6 16:46:08 👁️ 浏览次数:
【转载】代码:DeepSeek-OCR硅基流动API使用教程:轻松实现高精度OCR识别
import base64 import datetime import re import time import requests from colorama import Fore, Style def deepseek_ocr(image_path): 调用硅基流动API进行OCR识别 :param image_path: 图片文件路径 :return: 识别出的文本列表 url https://api.siliconflow.cn/v1/chat/completions api_key YOUR_API_KEY # 替换为你的API密钥 model deepseek-ai/DeepSeek-OCR # 构建请求内容 payload { model: model, messages: [ { role: user, content: [ { type: image_url, image_url: { url: data:application/pdf;base64, base64.b64encode( open(image_path, rb).read()).decode(utf-8) } }, { type: text, text: image\n|grounding|OCR this image. } ] } ] } headers { Authorization: fBearer {api_key}, Content-Type: application/json } # 重试机制防止网络波动 for i in range(5): try: response requests.post(url, jsonpayload, headersheaders) response.raise_for_status() data response.json() # 检查响应是否包含结果 if choices in data and data[choices]: print(f{Fore.GREEN}✅ OCR 成功{Style.RESET_ALL}) content data[choices][0][message][content] # 提取所有|ref|...|/ref|中的文本 texts re.findall(r\|ref\|(.*?)\|\/ref\|, content) return texts else: print(f{Fore.YELLOW}⚠️ 未获取到识别结果第 {i1} 次重试...{Style.RESET_ALL}) time.sleep(1) except Exception as e: print(f{Fore.RED}❌ 请求异常: {str(e)}第 {i1} 次重试...{Style.RESET_ALL}) time.sleep(1) print(f{Fore.RED} 重试 5 次后仍失败放弃请求{Style.RESET_ALL}) return None if __name__ __main__: start_time datetime.datetime.now() image_path your_image.jpg # 替换为你的图片路径 texts deepseek_ocr(image_path) end_time datetime.datetime.now() if texts: print(f{Fore.GREEN}调用API花费{(end_time - start_time).total_seconds():.2f}秒\n识别结果{texts}{Style.RESET_ALL}) else: print(f{Fore.RED}OCR识别失败{Style.RESET_ALL})注API密钥在硅基流动官网获取https://cloud.siliconflow.cn/me/account/ak原文链接https://blog.csdn.net/qq_58607032/article/details/155609565?fromshareblogdetailsharetypeblogdetailsharerId155609565sharereferPCsharesourceAutumn_horsesharefromfrom_link