Skip to content

Instantly share code, notes, and snippets.

@coolicer
Created March 8, 2018 07:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coolicer/023d46b5141675f29a53cb976a5e36c0 to your computer and use it in GitHub Desktop.
Save coolicer/023d46b5141675f29a53cb976a5e36c0 to your computer and use it in GitHub Desktop.
百度文字识别
const Koa = require('koa');
const Router = require('koa-router');
const static = require('koa-static')
const nunjucks = require('koa-nunjucks-2');
const multer = require('koa-multer');
const path = require('path');
const fs = require('fs');
const app = new Koa();
const router = new Router();
const AipOcrClient = require("baidu-aip-sdk").ocr;
const APP_ID = "xxx";
const API_KEY = "xxx";
const SECRET_KEY = "xxx";
const client = new AipOcrClient(APP_ID, API_KEY, SECRET_KEY);
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
const upload = multer({ storage: storage });
router
.get('/', async (ctx, next) => {
await ctx.render('page/index');
})
// fieldname: 'avatar',
// originalname: 'main_icon.png',
// encoding: '7bit',
// mimetype: 'image/png',
// destination: 'uploads/',
// filename: '6d8b3f078e4ca33d4be77b9e92ddce05',
// path: 'uploads/6d8b3f078e4ca33d4be77b9e92ddce05',
// size: 41208
.post('/upload', upload.single('file'), async (ctx, next) => {
let file = ctx.req.file;
ctx.body = {
code: 200,
data: {
url: file.originalname
}
};
})
.get('/ocr/:path', async ctx => {
const options = {};
options["language_type"] = "CHN_ENG";
options["probability"] = "true";
let path = ctx.params.path;
const image = fs.readFileSync('./uploads/' + path).toString("base64");
let result = await client.accurateBasic(image, options)
await ctx.render('page/ocr', { words: result.words_result})
});
app.use(static(
path.join( __dirname, '/uploads')
));
app.use(nunjucks({
ext: 'html',
path: path.join(__dirname, 'view'),
nunjucksConfig: {
trimBlocks: true
}
}));
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(7002, () => {
console.log('server run at http://127.0.0.1:7002');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment