process.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. package service
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "github.com/fsnotify/fsnotify"
  9. "gorm.io/gorm"
  10. "io"
  11. "log"
  12. "mime/multipart"
  13. "net/http"
  14. "os"
  15. "path/filepath"
  16. "speechAnalysis/conf"
  17. "speechAnalysis/constvar"
  18. "speechAnalysis/models"
  19. "speechAnalysis/pkg/logx"
  20. "strings"
  21. "time"
  22. )
  23. // Response 结构体用于存储响应体的内容
  24. type Response struct {
  25. Code int `json:"code"`
  26. Msg string `json:"msg"`
  27. Result string `json:"result"`
  28. Score float64 `json:"score"`
  29. }
  30. func AnalysisAudio(filename string, targetURL string) (resp Response, err error) {
  31. file, err := os.Open(filename)
  32. if err != nil {
  33. return
  34. }
  35. defer file.Close()
  36. // 创建一个缓冲区来存储表单数据
  37. var requestBody bytes.Buffer
  38. writer := multipart.NewWriter(&requestBody)
  39. // 创建一个表单字段,用于存储文件
  40. fileWriter, err := writer.CreateFormFile("audio", filename)
  41. if err != nil {
  42. return
  43. }
  44. // 将文件内容复制到表单字段中
  45. _, err = io.Copy(fileWriter, file)
  46. if err != nil {
  47. return
  48. }
  49. // 关闭表单写入器,以便写入末尾的边界
  50. writer.Close()
  51. // 创建POST请求,指定URL和请求体
  52. request, err := http.NewRequest("POST", targetURL, &requestBody)
  53. if err != nil {
  54. return
  55. }
  56. // 设置请求头,指定Content-Type为multipart/form-data
  57. request.Header.Set("Content-Type", writer.FormDataContentType())
  58. // 发送请求
  59. client := &http.Client{}
  60. response, err := client.Do(request)
  61. if err != nil {
  62. return
  63. }
  64. defer response.Body.Close()
  65. // 读取响应
  66. body := &bytes.Buffer{}
  67. _, err = io.Copy(body, response.Body)
  68. if err != nil {
  69. return
  70. }
  71. err = json.NewDecoder(body).Decode(&resp)
  72. if err != nil {
  73. return
  74. }
  75. return
  76. }
  77. func Process(audioId uint) (err error) {
  78. audio, err := models.NewAudioSearch().SetID(audioId).First()
  79. if err != nil {
  80. return errors.New("查找音频失败")
  81. }
  82. if audio.AudioStatus != constvar.AudioStatusUploadOk && audio.AudioStatus != constvar.AudioStatusFailed {
  83. return errors.New("状态不正确")
  84. }
  85. err = models.NewAudioSearch().SetID(audioId).UpdateByMap(map[string]interface{}{"audio_status": constvar.AudioStatusProcessing})
  86. if err != nil {
  87. return errors.New("DB错误")
  88. }
  89. go func() {
  90. resp, err := AnalysisAudio(audio.FilePath, conf.AanlysisConf.Url)
  91. if err != nil {
  92. logx.Errorf("err when AnalysisAudio:%v", err)
  93. _ = models.NewAudioSearch().SetID(audioId).UpdateByMap(map[string]interface{}{"audio_status": constvar.AudioStatusFailed})
  94. return
  95. }
  96. if resp.Code != 0 {
  97. logx.Errorf("AnalysisAudio error return:%v", resp)
  98. _ = models.NewAudioSearch().SetID(audioId).UpdateByMap(map[string]interface{}{"audio_status": constvar.AudioStatusFailed})
  99. return
  100. }
  101. logx.Infof("AnalysisAudio result: %v", resp)
  102. words := GetWordFromText(resp.Result, audio)
  103. err = models.WithTransaction(func(db *gorm.DB) error {
  104. err = models.NewAudioSearch().SetOrm(db).SetID(audioId).UpdateByMap(map[string]interface{}{
  105. "audio_status": constvar.AudioStatusFinish,
  106. "score": resp.Score,
  107. "tags": strings.Join(words, ","),
  108. })
  109. if err != nil {
  110. return err
  111. }
  112. err = models.NewAudioTextSearch().SetOrm(db).Save(&models.AudioText{
  113. AudioID: audio.ID,
  114. AudioText: resp.Result,
  115. })
  116. return err
  117. })
  118. if err != nil {
  119. logx.Infof("AnalysisAudio success but update record failed: %v", err)
  120. _ = models.NewAudioSearch().SetID(audioId).UpdateByMap(map[string]interface{}{"audio_status": constvar.AudioStatusFailed})
  121. return
  122. }
  123. }()
  124. return nil
  125. }
  126. func GetWordFromText(text string, audio *models.Audio) (words []string) {
  127. if audio == nil {
  128. return nil
  129. }
  130. wordRecords, err := models.NewWordSearch().SetLocomotiveNumber(audio.LocomotiveNumber).FindNotTotal()
  131. if err != nil || len(wordRecords) == 0 {
  132. return nil
  133. }
  134. for _, v := range wordRecords {
  135. if strings.Contains(text, v.Content) {
  136. words = append(words, v.Content)
  137. }
  138. }
  139. return words
  140. }
  141. func PreLoad(cxt context.Context) {
  142. mkdirErr := os.MkdirAll(conf.LocalConf.PreLoadPath, os.ModePerm)
  143. if mkdirErr != nil {
  144. logx.Errorf("function os.MkdirAll() err:%v", mkdirErr)
  145. }
  146. //文件夹下新增音频文件时触发
  147. watcher, err := fsnotify.NewWatcher()
  148. if err != nil {
  149. log.Fatal(err)
  150. }
  151. defer watcher.Close()
  152. err = watcher.Add(conf.LocalConf.PreLoadPath)
  153. if err != nil {
  154. log.Fatal(err)
  155. }
  156. for {
  157. select {
  158. case <-cxt.Done():
  159. fmt.Println("preload stop")
  160. case event, ok := <-watcher.Events:
  161. if !ok {
  162. continue
  163. }
  164. if event.Op&fsnotify.Create == fsnotify.Create {
  165. // 判断文件类型是否为.mp3或.wav
  166. if filepath.Ext(event.Name) == ".mp3" || filepath.Ext(event.Name) == ".wav" {
  167. // 文件名
  168. fileName := filepath.Base(event.Name)
  169. // 文件大小
  170. bs, _ := os.ReadFile(event.Name)
  171. size := len(bs)
  172. //校验文件命名
  173. arr := strings.Split(fileName, "_")
  174. if len(arr) != 6 {
  175. logx.Errorf(fmt.Sprintf("%s:%s", fileName, "文件名称错误"))
  176. continue
  177. }
  178. timeStr := arr[4] + strings.Split(arr[5], ".")[0]
  179. t, err := time.ParseInLocation("20060102150405", timeStr, time.Local)
  180. if err != nil {
  181. logx.Errorf(fmt.Sprintf("%s:%s", fileName, "时间格式不对"))
  182. }
  183. //查重
  184. _, err = models.NewAudioSearch().SetName(fileName).First()
  185. if err != gorm.ErrRecordNotFound {
  186. logx.Errorf(fmt.Sprintf("%s:%s", fileName, "重复上传"))
  187. continue
  188. }
  189. //将文件移动到uploads文件夹下
  190. src := conf.LocalConf.StorePath + "/" + fileName
  191. err = os.Rename(event.Name, src)
  192. if err != nil {
  193. logx.Errorf(fmt.Sprintf("%s:%s", fileName, "移动文件失败"))
  194. continue
  195. }
  196. audio := &models.Audio{
  197. Name: fileName,
  198. Size: int64(size),
  199. FilePath: src,
  200. AudioStatus: constvar.AudioStatusUploadOk,
  201. LocomotiveNumber: arr[0],
  202. TrainNumber: arr[1],
  203. DriverNumber: arr[2],
  204. Station: arr[3],
  205. OccurrenceAt: t,
  206. IsFollowed: 0,
  207. }
  208. if err = models.NewAudioSearch().Create(audio); err != nil {
  209. logx.Errorf(fmt.Sprintf("%s:%s", fileName, "数据库create失败"))
  210. continue
  211. }
  212. go func() {
  213. var trainInfoNames = []string{arr[0], arr[1], arr[3]} //
  214. var (
  215. info *models.TrainInfo
  216. err error
  217. parent models.TrainInfo
  218. )
  219. for i := 0; i < 3; i++ {
  220. name := trainInfoNames[i]
  221. class := constvar.Class(i + 1)
  222. info, err = models.NewTrainInfoSearch().SetName(name).SetClass(class).First()
  223. if err == gorm.ErrRecordNotFound {
  224. info = &models.TrainInfo{
  225. Name: name,
  226. Class: class,
  227. ParentID: parent.ID,
  228. }
  229. _ = models.NewTrainInfoSearch().Create(info)
  230. }
  231. parent = *info
  232. }
  233. }()
  234. }
  235. }
  236. case err, ok := <-watcher.Errors:
  237. if !ok {
  238. logx.Errorf(err.Error())
  239. }
  240. }
  241. }
  242. }