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

相关推荐
迷渡15 分钟前
聊一聊 Bun 用 Rust 重写这件事
开发语言·后端·rust
王中阳Go18 分钟前
秒杀、分库分表、全链路追踪:一个电商微服务的架构全拆解
后端·go
吴佳浩18 分钟前
OpenClaw最严厉的父亲- 使用优化建议
人工智能·llm·agent
正儿八经的少年25 分钟前
Spring Boot 两种激活配置方式的作用与区别
java·spring boot·后端
安吉升科技28 分钟前
ai双目智能客流摄像头是什么?有哪些作用呢?
人工智能
大势智慧36 分钟前
大势智慧与您相约2026世界无人机大会暨UASE无人机展
人工智能·无人机·趋势·未来·低空经济·空间智能·世界无人机大会
云烟成雨TD38 分钟前
Spring AI Alibaba 1.x 系列【52】Interrupts 中断机制:节点执行前后静态中断
java·人工智能·spring
回家路上绕了弯1 小时前
AgentScope Java实战博客:从入门到落地,解锁智能代理开发新范式
后端
疯狂成瘾者1 小时前
Spring Boot 项目中的 SMTP 邮件验证码服务技术解析
java·spring boot·后端
阿苟1 小时前
消息队列重点详解
后端·面试