修改接口
This commit is contained in:
@@ -0,0 +1,87 @@
|
||||
const Router = require('koa-router')
|
||||
const { query } = require('../config/database')
|
||||
const fetch = require('node-fetch')
|
||||
require('dotenv').config()
|
||||
|
||||
const router = new Router()
|
||||
const AI_API_KEY = process.env.DASHSCOPE_API_KEY
|
||||
const AI_API_URL = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions'
|
||||
|
||||
router.post('/barcode', async (ctx) => {
|
||||
try {
|
||||
const { barcode } = ctx.request.body
|
||||
if (!barcode) {
|
||||
ctx.body = { code: 400, message: '请提供条形码' }
|
||||
return
|
||||
}
|
||||
|
||||
const goods = await query(
|
||||
'SELECT * FROM goods WHERE barcode = ? LIMIT 1',
|
||||
[barcode]
|
||||
)
|
||||
|
||||
if (goods.length > 0) {
|
||||
ctx.body = { code: 200, data: goods[0] }
|
||||
} else {
|
||||
ctx.body = { code: 404, message: '未找到该商品' }
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Barcode lookup failed:', error)
|
||||
ctx.body = { code: 500, message: '查询失败' }
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/image', async (ctx) => {
|
||||
try {
|
||||
const { imageData } = ctx.request.body
|
||||
if (!imageData) {
|
||||
ctx.body = { code: 400, message: '请提供图片数据' }
|
||||
return
|
||||
}
|
||||
|
||||
if (!AI_API_KEY) {
|
||||
ctx.body = { code: 500, message: 'AI 识别未配置' }
|
||||
return
|
||||
}
|
||||
|
||||
const response = await fetch(AI_API_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${AI_API_KEY}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: 'qwen-vl-max',
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', text: '请识别这张图片中的商品,返回商品名称。只返回名称,不要其他内容。' },
|
||||
{ type: 'image_url', image_url: { url: imageData } }
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
})
|
||||
|
||||
const result = await response.json()
|
||||
const name = result?.choices?.[0]?.message?.content?.trim() || ''
|
||||
|
||||
const goods = name
|
||||
? await query('SELECT * FROM goods WHERE name LIKE ? LIMIT 5', [`%${name}%`])
|
||||
: []
|
||||
|
||||
ctx.body = {
|
||||
code: 200,
|
||||
data: {
|
||||
message: name ? `识别到: ${name}` : '未识别到商品',
|
||||
goods: goods || []
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Image recognition failed:', error)
|
||||
ctx.body = { code: 500, message: '识别失败' }
|
||||
}
|
||||
})
|
||||
|
||||
module.exports = router.routes()
|
||||
Reference in New Issue
Block a user