Lua请求文字识别ocr api
1安装Lua下载LuaForWindows_v5.1.5-52.exe按默认安装安装完毕打开cmd可以运行Lua:C:\projectsluaLua 5.1.5 Copyright (C) 1994-2012Lua.org, PUC-Rio2安装dkjsondkjson - JSON Module for Lua下载dkjson.lua获取Lua的加载模块的目录C:\projectslua -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\请求代码如下-- -- 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, {indentfalse}) -- 打印完整的请求数据调试用 -- 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:\projectslua use_api.lua