aliyun_ocr.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package services
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "hongze/hz_crm_api/models/cygx"
  6. "io/ioutil"
  7. "net/http"
  8. "strings"
  9. "time"
  10. )
  11. var (
  12. AliyunAppCode = "22553c4ba74545568aba70ac6cfd441d" // AppCode
  13. )
  14. type AliOcrByImageToTextResp struct {
  15. RequestID string `json:"request_id"`
  16. Ret []struct {
  17. Rect struct {
  18. Angle int64 `json:"angle"`
  19. Height int64 `json:"height"`
  20. Left int64 `json:"left"`
  21. Top int64 `json:"top"`
  22. Width int64 `json:"width"`
  23. } `json:"rect"`
  24. Word string `json:"word"`
  25. } `json:"ret"`
  26. Success bool `json:"success"`
  27. }
  28. //func init() {
  29. // AliOcrByImageToText("https://hzstatic.hzinsights.com/cygx/config/a2.jpg")
  30. //}
  31. // 阿里云OCR将图片转文字
  32. func AliOcrByImageToText(imageurl string) (item *AliOcrByImageToTextResp, err error) {
  33. url := "https://tysbgpu.market.alicloudapi.com/api/predict/ocr_general"
  34. method := "POST"
  35. payload := strings.NewReader(`{
  36. "image":"` + imageurl + `"
  37. }`)
  38. client := &http.Client{}
  39. req, err := http.NewRequest(method, url, payload)
  40. if err != nil {
  41. fmt.Println(err)
  42. return
  43. }
  44. req.Header.Add("Authorization", "APPCODE "+AlAppCode)
  45. req.Header.Add("Content-Type", "application/json")
  46. res, err := client.Do(req)
  47. if err != nil {
  48. fmt.Println(err)
  49. return
  50. }
  51. defer res.Body.Close()
  52. body, err := ioutil.ReadAll(res.Body)
  53. if err != nil {
  54. fmt.Println(err)
  55. return
  56. }
  57. err = json.Unmarshal(body, &item)
  58. if err != nil {
  59. fmt.Println(err)
  60. return
  61. }
  62. logItem := new(cygx.AliyunOcrLog)
  63. logItem.ImgUrl = imageurl
  64. logItem.Result = string(body)
  65. logItem.CreateTime = time.Now()
  66. err = cygx.AddAliyunOcrLog(logItem)
  67. return
  68. }