aliyun.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. package services
  2. import (
  3. "crypto/tls"
  4. "encoding/base64"
  5. "encoding/json"
  6. "fmt"
  7. openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
  8. ocr20191230 "github.com/alibabacloud-go/ocr-20191230/v3/client"
  9. util "github.com/alibabacloud-go/tea-utils/v2/service"
  10. "github.com/alibabacloud-go/tea/tea"
  11. rhttp "github.com/rdlucklib/rdluck_tools/http"
  12. "hongze/hz_crm_api/models/company"
  13. "hongze/hz_crm_api/models/cygx"
  14. "hongze/hz_crm_api/utils"
  15. "io"
  16. "io/ioutil"
  17. "net/http"
  18. "strings"
  19. "time"
  20. )
  21. const (
  22. AlAppKey = "203889624"
  23. AlAppSecret = "voampGGl0yGNx5xA1sZdmZlV2EiBct2P"
  24. AlAppCode = "22553c4ba74545568aba70ac6cfd441d"
  25. )
  26. var (
  27. //文档 https://market.aliyun.com/apimarket/detail/cmapi013591?spm=5176.product-detail.detail.4.6d4f3dcaS0qPFI&endpoint=a3dd145f3865492ba6f02d0c09dd00a1
  28. AliyunOcrBusinessCardCode = "22553c4ba74545568aba70ac6cfd441d" // 阿里云OCR名片识别的code
  29. )
  30. type OcrItem struct {
  31. Image string `json:"image"`
  32. }
  33. type OcrResult struct {
  34. Addr []string `json:"addr"`
  35. Company []string `json:"company"`
  36. Success bool `json:"success"`
  37. TelCell []string `json:"tel_cell"`
  38. Departments []string `json:"departments"`
  39. Name string `json:"name"`
  40. OfficePhoneNumbers []string `json:"office_phone_numbers"`
  41. Titles []string `json:"titles"`
  42. }
  43. // /ocr_business_card.json
  44. func AliyunBusinessCard(imgUrl string) (result *OcrResult, err error) {
  45. postUrl := `https://dm-57.data.aliyun.com/rest/160601/ocr/ocr_business_card.json`
  46. imgBody, err := rhttp.Get(imgUrl)
  47. if err != nil {
  48. return
  49. }
  50. imageBase64 := base64.StdEncoding.EncodeToString(imgBody)
  51. item := new(OcrItem)
  52. item.Image = imageBase64
  53. jsonBody, err := json.Marshal(item)
  54. if err != nil {
  55. fmt.Println("json.Marshal Err:" + err.Error())
  56. return
  57. }
  58. tr := &http.Transport{
  59. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  60. }
  61. client := &http.Client{Transport: tr}
  62. req, err := http.NewRequest("POST", postUrl, strings.NewReader(string(jsonBody)))
  63. if err != nil {
  64. fmt.Println("err:" + err.Error())
  65. return
  66. }
  67. req.Header.Set("Content-Type", "application/json")
  68. req.Header.Set("Authorization", "APPCODE "+AlAppCode)
  69. resp, err := client.Do(req)
  70. if err != nil {
  71. fmt.Println("client.Do Err:" + err.Error())
  72. return
  73. }
  74. fmt.Println("resp")
  75. fmt.Println(resp)
  76. defer resp.Body.Close()
  77. body, err := ioutil.ReadAll(resp.Body)
  78. if err != nil {
  79. fmt.Println("err:" + err.Error())
  80. return
  81. }
  82. fmt.Println("body:", string(body))
  83. utils.FileLog.Info(fmt.Sprintf("aliyun card;imgUrl:%s; Body:%s", imgUrl, string(body)))
  84. err = json.Unmarshal(body, &result)
  85. return
  86. }
  87. // AliyunBusinessCardOcr 阿里云的ocr识别
  88. func AliyunBusinessCardOcr(imgUrl string) (result OcrResult, err error) {
  89. config := &openapi.Config{
  90. // 2、"YOUR_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_SECRET" 的生成请参考https://help.aliyun.com/document_detail/175144.html
  91. // 如果您是用的子账号AccessKey,还需要为子账号授予权限AliyunVIAPIFullAccess,请参考https://help.aliyun.com/document_detail/145025.html
  92. // 您的 AccessKey ID
  93. AccessKeyId: tea.String(utils.AccessKeyId),
  94. // 您的 AccessKey Secret
  95. AccessKeySecret: tea.String(utils.AccessKeySecret),
  96. }
  97. // 3、访问的域名。注意:这个地方需要求改为相应类目的域名,参考:https://help.aliyun.com/document_detail/143103.html
  98. config.Endpoint = tea.String("ocr.cn-shanghai.aliyuncs.com")
  99. // 4、这里只是以ocr为例,其他能力请使用相应类目的包
  100. client, err := ocr20191230.NewClient(config)
  101. if err != nil {
  102. return
  103. }
  104. httpClient := http.Client{}
  105. file, _ := httpClient.Get(imgUrl)
  106. // 5、这里只是以ocr的RecognizeBankCard为例,其他能力请使用相应类目的包和类
  107. recognizeBusinessCardAdvanceRequest := &ocr20191230.RecognizeBusinessCardAdvanceRequest{
  108. ImageURLObject: file.Body,
  109. }
  110. runtime := &util.RuntimeOptions{}
  111. // 6、这里只是以ocr的RecognizeBankCard为例,其他能力请使用相应类目的包和类,注意RecognizeBankCardWithOptions也需要改成对应能力的方法名。方法名是根据能力名称按照一定规范形成的,如能力名称为SegmentCommonImage,对应方法名应该为SegmentCommonImageWithOptions。
  112. recognizeBusinessCardResponse, err := client.RecognizeBusinessCardAdvance(recognizeBusinessCardAdvanceRequest, runtime)
  113. if err != nil {
  114. // 获取整体报错信息
  115. //fmt.Println(err.Error())
  116. utils.FileLog.Info(fmt.Sprintf("aliyun card;imgUrl:%s; err:%s", imgUrl, err))
  117. return
  118. }
  119. // 获取整体结果
  120. //fmt.Println(recognizeBusinessCardResponse)
  121. //// 获取单个字段,这里只是一个例子,具体能力下的字段需要看具体能力的文档
  122. //fmt.Println(recognizeBusinessCardResponse.Body.Data.Name)
  123. // 地址
  124. for _, v := range recognizeBusinessCardResponse.Body.Data.Addresses {
  125. result.Addr = append(result.Addr, *v)
  126. }
  127. // company
  128. for _, v := range recognizeBusinessCardResponse.Body.Data.Companies {
  129. result.Company = append(result.Company, *v)
  130. }
  131. // tel_cell
  132. for _, v := range recognizeBusinessCardResponse.Body.Data.CellPhoneNumbers {
  133. result.TelCell = append(result.TelCell, *v)
  134. }
  135. // Departments
  136. for _, v := range recognizeBusinessCardResponse.Body.Data.Departments {
  137. result.Departments = append(result.Departments, *v)
  138. }
  139. // OfficePhoneNumbers
  140. for _, v := range recognizeBusinessCardResponse.Body.Data.OfficePhoneNumbers {
  141. result.OfficePhoneNumbers = append(result.OfficePhoneNumbers, *v)
  142. }
  143. // Titles
  144. for _, v := range recognizeBusinessCardResponse.Body.Data.Titles {
  145. result.Titles = append(result.Titles, *v)
  146. }
  147. if recognizeBusinessCardResponse.Body.Data.Name != nil {
  148. result.Name = *recognizeBusinessCardResponse.Body.Data.Name
  149. }
  150. result.Success = true
  151. return
  152. }
  153. // 阿里云名片识别返回类
  154. type OcrBusinessCardResult struct {
  155. TelCell []string `json:"tel_cell"`
  156. Success bool `json:"success"`
  157. Name string `json:"name"`
  158. Company []string `json:"company"`
  159. Addr []string `json:"addr"`
  160. Department []string `json:"department"`
  161. Title []string `json:"title"`
  162. RequestID string `json:"request_id"`
  163. Email []string `json:"email"`
  164. TelWork []string `json:"tel_work"`
  165. }
  166. // 阿里云名片识别更换2024-01-02
  167. func AliyunOcrBusinessCard(imageurl string) (result *OcrBusinessCardResult, errMsg string, err error) {
  168. url := "https://bizcard.market.alicloudapi.com/rest/160601/ocr/ocr_business_card.json"
  169. method := "POST"
  170. payload := strings.NewReader(`{
  171. "image":"` + imageurl + `"
  172. }`)
  173. client := &http.Client{}
  174. req, err := http.NewRequest(method, url, payload)
  175. if err != nil {
  176. fmt.Println(err)
  177. return
  178. }
  179. req.Header.Add("Authorization", "APPCODE "+AliyunOcrBusinessCardCode)
  180. req.Header.Add("Content-Type", "application/json")
  181. res, err := client.Do(req)
  182. if err != nil {
  183. fmt.Println(err)
  184. return
  185. }
  186. defer res.Body.Close()
  187. body, err := io.ReadAll(res.Body)
  188. if err != nil {
  189. fmt.Println(err)
  190. return
  191. }
  192. err = json.Unmarshal(body, &result)
  193. if err != nil {
  194. fmt.Println(err)
  195. return
  196. }
  197. //处理返回的手机号格式,并进行数据合并
  198. var telCell []string
  199. if len(result.TelCell) > 0 {
  200. for _, v := range result.TelCell {
  201. telCell = append(telCell, utils.GetArabicNumbers(v))
  202. }
  203. }
  204. if len(result.TelWork) > 0 {
  205. for _, v := range result.TelWork {
  206. telCell = append(telCell, utils.GetArabicNumbers(v))
  207. }
  208. }
  209. result.TelCell = telCell
  210. if len(result.Company) == 0 && len(result.TelCell) == 0 {
  211. errMsg = "OCR识别失败"
  212. } else if len(result.Company) == 0 {
  213. // 获取图片识别客户名称的配置
  214. crmConfig, errCode := company.GetConfigDetailByCode("card_recognition_company_name")
  215. if errCode != nil {
  216. err = errCode
  217. return
  218. }
  219. if crmConfig.ConfigValue == "true" {
  220. errMsg = "名片中未识别到公司名称"
  221. }
  222. } else if len(result.TelCell) == 0 {
  223. // 获取图片识别手机号的配置
  224. crmConfig2, errCode := company.GetConfigDetailByCode("card_recognition_tel")
  225. if errCode != nil {
  226. err = errCode
  227. return
  228. }
  229. if crmConfig2.ConfigValue == "true" {
  230. errMsg = " 名片中未识别到手机号"
  231. }
  232. }
  233. logItem := new(cygx.AliyunOcrLog)
  234. logItem.ImgUrl = imageurl
  235. logItem.Result = string(body)
  236. logItem.CreateTime = time.Now()
  237. err = cygx.AddAliyunOcrLog(logItem)
  238. return
  239. }