首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >基于DdddOcr通用验证码离线本地识别SDK搭建个人云打码接口Api

基于DdddOcr通用验证码离线本地识别SDK搭建个人云打码接口Api

原创
作者头像
德宏大魔王
发布2024-09-09 10:47:24
发布2024-09-09 10:47:24
84300
代码可运行
举报
运行总次数:0
代码可运行

允许腾讯云用户UID:2561063转发自腾讯云 https://cloud.tencent.com/developer/user/2561063

前言

最近介绍了一款免费的验证码识别网站,识别效率太低,考虑到ddddocr是开源的,决定搭建搭建一个,发现原作者sml2h3已经推出好久了,但是网上没有宝塔安装的教程,于是本次通过宝塔搭建属于自己的带带弟弟OCR通用验证码离线本地识别

原项目地址:https://github.com/sml2h3/ocr_api_server

说明

本地安装大家应该都会,可是宝塔,我弄了一个下午,尝试了wsgi协议,还有启动方式,虚拟环境等等,宝塔存在很多问题,以下是部分问题的描述:

1、原python管理器下架,有严重bug,没办法进入虚拟目录缺少activity文件,虽然可以创造,但是构建完毕后,ddddocr模块有安装不上,创建时勾选模块可以安装没问题(猜测pip问题)

2、使用新的python管理器,挺好使,但是没有办法挂在持久化命令,终端关掉服务结束,进程守护管理器找不到启动文件(个人怀疑同上缺失activity文件)

于是我修改了作者的代码,使其不需要通过命令进行选择,直接运行,由于我只是用到普通的ocr识别,滑块那些我是关闭的

本次修改代码默认走:

python ocr_server.py --port 9898 --ocr

代码:

代码语言:javascript
代码运行次数:0
运行
复制
import base64
import json

import ddddocr
from flask import Flask, request

app = Flask(__name__)

class Server(object):
    def __init__(self, ocr=True, det=False, old=False):
        self.ocr_option = ocr
        self.det_option = det
        self.old_option = old
        self.ocr = None
        self.det = None
        if self.ocr_option:
            print("ocr模块开启")
            if self.old_option:
                print("使用OCR旧模型启动")
                self.ocr = ddddocr.DdddOcr(old=True)
            else:
                print("使用OCR新模型启动,如需要使用旧模型,请额外添加参数  --old开启")
                self.ocr = ddddocr.DdddOcr()
        else:
            print("ocr模块未开启,如需要使用,请使用参数  --ocr开启")
        if self.det_option:
            print("目标检测模块开启")
            self.det = ddddocr.DdddOcr(det=True)
        else:
            print("目标检测模块未开启,如需要使用,请使用参数  --det开启")

    def classification(self, img: bytes):
        if self.ocr_option:
            return self.ocr.classification(img)
        else:
            raise Exception("ocr模块未开启")

    def detection(self, img: bytes):
        if self.det_option:
            return self.det.detection(img)
        else:
            raise Exception("目标检测模块模块未开启")

    def slide(self, target_img: bytes, bg_img: bytes, algo_type: str):
        dddd = self.ocr or self.det or ddddocr.DdddOcr(ocr=False)
        if algo_type == 'match':
            return dddd.slide_match(target_img, bg_img)
        elif algo_type == 'compare':
            return dddd.slide_comparison(target_img, bg_img)
        else:
            raise Exception(f"不支持的滑块算法类型: {algo_type}")

# 默认值设置
ocr_enabled = True
det_enabled = False
old_model = False

server = Server(ocr=ocr_enabled, det=det_enabled, old=old_model)


def get_img(request, img_type='file', img_name='image'):
    if img_type == 'b64':
        img = base64.b64decode(request.get_data()) 
        try: 
            dic = json.loads(img)
            img = base64.b64decode(dic.get(img_name).encode())
        except Exception as e: 
            pass
    else:
        img = request.files.get(img_name).read()
    return img


def set_ret(result, ret_type='text'):
    if ret_type == 'json':
        if isinstance(result, Exception):
            return json.dumps({"status": 200, "result": "", "msg": str(result)})
        else:
            return json.dumps({"status": 200, "result": result, "msg": ""})
    else:
        if isinstance(result, Exception):
            return ''
        else:
            return str(result).strip()


@app.route('/<opt>/<img_type>', methods=['POST'])
@app.route('/<opt>/<img_type>/<ret_type>', methods=['POST'])
def ocr(opt, img_type='file', ret_type='text'):
    try:
        img = get_img(request, img_type)
        if opt == 'ocr':
            result = server.classification(img)
        elif opt == 'det':
            result = server.detection(img)
        else:
            raise f"<opt={opt}> is invalid"
        return set_ret(result, ret_type)
    except Exception as e:
        return set_ret(e, ret_type)

@app.route('/slide/<algo_type>/<img_type>', methods=['POST'])
@app.route('/slide/<algo_type>/<img_type>/<ret_type>', methods=['POST'])
def slide(algo_type='compare', img_type='file', ret_type='text'):
    try:
        target_img = get_img(request, img_type, 'target_img')
        bg_img = get_img(request, img_type, 'bg_img')
        result = server.slide(target_img, bg_img, algo_type)
        return set_ret(result, ret_type)
    except Exception as e:
        return set_ret(e, ret_type)

@app.route('/ping', methods=['GET'])
def ping():
    return "pong"


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=9898)  # 直接设置端口号

将以上代码替换原项目的ocr_server.py即可

开始

宝塔创建python项目(可在新版网站栏目的python项目创建或者python项目管理器)

安装模块

可以勾选也可以自己在终端安装,这里建议直接勾选(上一步)

代码语言:javascript
代码运行次数:0
运行
复制
pip install -r requirements.txt -i https://pypi.douban.com/simple

启动

运行中即可(注意开放宝塔的安全规则以及服务器端口)

测试Ping

访问http://你的主机:9898/ping

bs4验证码测试

PHP封装

宝塔部署PHP简单方便,将ddddocr封装为一个api供其他文件调用

代码语言:javascript
代码运行次数:0
运行
复制
<?php
header('Content-Type: text/html;charset=utf-8');
header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 设置允许自定义请求头的字段
header("Content-type:text/html;charset=utf-8");//字符编码设置

function callOCR($base64_content) {
    // 设置主机地址
    $host = "http://你的IP:9898";

    // 构建 API URL
    $api_url = $host . "/ocr/b64/text";

    // 使用 cURL 发送 POST 请求
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $api_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $base64_content);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $response = curl_exec($ch);

    // 检查响应状态码
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    curl_close($ch);

    if ($http_code == 200) {
        return $response;
    } else {
        return "Failed to call the API: " . $http_code;
    }
}





// 示例 base64 编码的图片内容
$base64_content = "";

// 调用函数并打印结果
$result = callOCR($base64_content);
echo($result);
?>

调用方法

引入文件 include 'ddddocr.php';

获取验证码

代码语言:javascript
代码运行次数:0
运行
复制
$yzm = callOCR($picture);

提供给项目,实现免验证码登录

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 说明
  • 开始
    • 安装模块
    • 启动
  • 测试Ping
  • bs4验证码测试
  • PHP封装
  • 调用方法
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档