Lua请求文字识别ocr api

1,安装Lua

下载 LuaForWindows_v5.1.5-52.exe

按默认安装

安装完毕,打开cmd可以运行Lua:

C:\projects>lua

Lua 5.1.5 Copyright (C) 1994-2012 Lua.org, PUC-Rio

>

2,安装dkjson

dkjson - JSON Module for Lua

下载dkjson.lua

获取Lua的加载模块的目录

C:\projects>lua -e "print(package.path)"

;.\?.lua;C:\Program Files (x86)\Lua\5.1\lua\?.lua;C:\Program Files (x86)\Lua\5.1\lua\?\init.lua;C:\Program Files (x86)\Lua\5.1\?.lua;C:\Program Files (x86)\Lua\5.1\?\init.lua;C:\Program Files (x86)\Lua\5.1\lua\?.luac

选择其中一个,所以把dkjson.lua复制到:

C:\Program Files (x86)\Lua\5.1\lua\

请求代码如下:

Lua 复制代码
-- ==============================================================================
-- API文档:https://market.shiliuai.com/doc/advanced-general-ocr
-- 支持免费在线体验
-- API文档清晰,提供多种接入语言示例(如python、js、C#、java、php等),以及自动化脚本语言(如天诺、懒人精灵、按键精灵、易语言、EasyClick、触动精灵等)
-- ==============================================================================


local http = require("socket.http")
local ltn12 = require("ltn12")
local base64 = require("base64")
local json = require("dkjson")


-- 设置UTF-8编码输出
if package.config:sub(1,1) == "\\" then
    os.execute("chcp 65001 > nul")
    io.stdout:setvbuf("no")
end


-- 请求接口
local URL = "http://ocr-api.shiliuai.com/api/general_ocr/v1"


-- 图片转base64
local function get_base64(file_path)
    local file = io.open(file_path, "rb")
    if not file then
        return nil, "Unable to open file"
    end
    local data = file:read("*all")
    file:close()
    local b64 = base64.encode(data)
    return b64
end


local function demo(appcode, file_path)
    -- 请求头
    local headers = {
        ["Authorization"] = "APPCODE " .. appcode,
        ["Content-Type"] = "application/json",
        ["Accept"] = "application/json",
        ["Connection"] = "close"  -- 明确关闭连接
    }


    -- 请求体
    local b64, err = get_base64(file_path)
    if not b64 then
        print("Error:", err)
        return
    end


    local data = {
        ["image_base64"] = b64
    }
    local json_data = json.encode(data, {indent=false})


    -- 打印完整的请求数据(调试用)
    -- print("[DEBUG] Request Headers:", json.encode(headers))
    -- print("[DEBUG] Request Body (first 100 chars):", json_data:sub(1, 100))


    -- 手动设置 Content-Length
    headers["Content-Length"] = #json_data


    -- 请求
    local response_body = {}
    local res, code, response_headers = http.request{
        url = URL,
        method = "POST",
        headers = headers,
        source = ltn12.source.string(json_data),
        sink = ltn12.sink.table(response_body),
        timeout = 30,
        chunked = false  -- 禁用分块传输
    }


    -- 检查响应是否有效
    if code ~= 200 then
        print("[ERROR] HTTP Code:", code)
        print("[ERROR] Response Body:", table.concat(response_body))
        return
    end


    -- 合并响应体
    local response_text = table.concat(response_body)
    print("[DEBUG] Response:", response_text)


    -- 解析JSON响应
    local content, pos, err = json.decode(response_text, 1, nil)
    if err then
        print("[ERROR] Fail to decode JSON:", err)
        return
    end


    -- 处理识别结果
    if content and content.code == 200 and content.data then
        print("=== 识别结果 ===")
        for i, item in ipairs(content.data.content) do
            print(string.format("%d. text: %s", i, item.text))
            print(string.format("   prob: %.2f%%", item.prob * 100))
        end
    else
        print("[ERROR] API返回异常:", content and content.message or "未知错误")
    end


end



-- 主程序
local appcode = "你的APPCODE"
local file_path = "图片路径"
demo(appcode, file_path)

其中,appcode需要到market.shiliuai.com申请。

运行方式:

C:\projects>lua use_api.lua

相关推荐
Jason_zhao_MR2 小时前
基于米尔RK3576核心板的国产割草机器人解决方案
大数据·linux·人工智能·单片机·物联网·机器人·嵌入式
蓉蓉的数码视界2 小时前
则成电子26年一季报:AI+汽车电子双轮驱动成效显著,营收增长26.68%
大数据·人工智能·汽车
SuAluvfy2 小时前
从“C端AI”到“B端AI”:做事还是作诗?
人工智能·chatgpt
AI生产力指南2 小时前
泛微·易秒办集成OpenClaw机器人:打造“能说会做”的智能助手
运维·网络·人工智能
沫儿笙2 小时前
安川机器人气保焊智能节气阀
人工智能·机器人
嵌入式小企鹅2 小时前
算力价值重估、AI编程模型齐开源、RISC-V融资15亿
人工智能·学习·ai·程序员·risc-v·前沿科技·太空算力
小小王app小程序开发2 小时前
AI 智能体小程序玩法分析:2026 千亿 AI 风口,冠品科技赋能低门槛落地
人工智能·科技·小程序
Dotrust东信创智2 小时前
告别脚本依赖:AI 具身智能重构智能座舱 HMI 测试新范式
人工智能·重构
yyk的萌2 小时前
Spring AI + 智谱大模型实战:打造有记忆功能的智能天气助手
java·人工智能·spring·agent·spring ai