Code Monkey home page Code Monkey logo

quickstart's Introduction

QuickStart

百度AI平台QuickStart文档配套DEMO程序的python实现

百度EasyDL定制化训练和服务平台配套DEMO程序的python实现

quickstart's People

Contributors

meteorasd555 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

quickstart's Issues

ocr脚本报错,python用的 3.95

C:\Python\Python39\python.exe E:/迅雷下载/QuickStart-master/OCR/main.py
Traceback (most recent call last):
File "E:\迅雷下载\QuickStart-master\OCR\main.py", line 120, in
for words_result in result_json["words_result"]:
KeyError: 'words_result'

示例代码有缺陷

如果图片是非菜品 是没有热量的。
建议main.py的115行进行如下修改
# 打印图片结果 for data in result_json["result"]: print(u" 菜品名称: " + data["name"]) has_calorie = data["has_calorie"]; if(has_calorie): print(u" 菜品热量: " + data["calorie"])

golang 实现版本

package main

import (
	"bufio"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strings"
	"time"
)

var maxLen int = 5 * 1024 * 1024

var API_KEY string = ""

var SECRET_KEY string = ""

var OCR_URL string = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token="

var TOKEN_URL string = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials"

var pdir string

func main() {

	fmt.Printf("Please enter picture directory: ")
	fmt.Scanln(&pdir)

	fd, err := os.ReadDir(pdir)
	if err != nil {
		log.Fatal(err)
	}

	access_token := fetch_token()

	for _, ff := range fd { //遍历目录
		if ff.Type().IsRegular() && !strings.HasSuffix(ff.Name(), ".txt") {
			generalBasic(ff.Name(), access_token)
		}
	}
}

// 通用文字识别(标准版) https://ai.baidu.com/ai-doc/OCR/zk3h7xz52
func generalBasic(name string, access_token string) {

	if pdir == "" {
		pdir = "."
	}

	if access_token == "" {
		log.Fatal("access_token is empty")
	}

	fmt.Println("OCR File[" + filepath.Join(pdir, name) + "]")

	file, _ := os.Open(filepath.Join(pdir, name))
	defer file.Close()

	time.Sleep(2 * time.Second) //qps limit 1

	OCR_URL += access_token
	res, err := http.Post(OCR_URL, "application/x-www-form-urlencoded", strings.NewReader("image="+url.QueryEscape(base64e(file))))
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()
	mapdata := make(map[string]interface{})
	json.NewDecoder(res.Body).Decode(&mapdata)
	if mapdata["words_result_num"] == nil {
		data, _ := ioutil.ReadAll(res.Body)
		fmt.Printf("%s identification failed:%+v\n", file.Name(), data)
		return
	}
	if int(mapdata["words_result_num"].(float64)) == 0 {
		fmt.Println(file.Name() + " identification content is empty...")
		return
	}

	f, err := os.OpenFile(file.Name()+".txt", os.O_RDWR|os.O_CREATE, os.ModePerm)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	w := bufio.NewWriter(f)
	words_result := mapdata["words_result"].([]interface{})

	for _, obj := range words_result {
		m := obj.(map[string]interface{})
		fmt.Fprintln(w, m["words"])
	}
	w.Flush()
}

// 鉴权认证机制 http://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu
// post方式报错:unsupported_grant_type
func fetch_token() string {
	res, err := http.Get(TOKEN_URL + "&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()
	// data, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Fatal(err)
	}
	mapdata := make(map[string]interface{})
	json.NewDecoder(res.Body).Decode(&mapdata)
	// json.Unmarshal(data, &mapdata)
	for key, value := range mapdata {
		// fmt.Println("key:", key, " => value :", value)
		if key == "access_token" {
			return value.(string)
		}
		if key == "error_description" {
			log.Fatal(value)
		}
	}
	return ""
}

// base64 encode
func base64e(file *os.File) string {
	sourcebuffer := make([]byte, maxLen)
	n, _ := file.Read(sourcebuffer)
	return base64.StdEncoding.EncodeToString(sourcebuffer[:n])
}

// base64 decode
func base64d(str string) ([]byte, error) {
	return base64.StdEncoding.DecodeString(str)
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.