audio.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. package controllers
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "gorm.io/gorm"
  7. "io"
  8. "mime/multipart"
  9. "net/url"
  10. "os"
  11. "path"
  12. "path/filepath"
  13. "speechAnalysis/constvar"
  14. "speechAnalysis/extend/code"
  15. "speechAnalysis/extend/util"
  16. "speechAnalysis/models"
  17. "speechAnalysis/pkg/logx"
  18. "speechAnalysis/request"
  19. "speechAnalysis/response"
  20. "speechAnalysis/service"
  21. "speechAnalysis/utils/upload"
  22. "strings"
  23. "time"
  24. )
  25. type AudioCtl struct{}
  26. // Upload
  27. // @Tags 音频
  28. // @Summary 上传音频
  29. // @Accept multipart/form-data
  30. // @Produce application/json
  31. // @Param file formData []file false "多文件上传"
  32. // @Success 200 {object} util.Response "成功"
  33. // @Router /api-sa/v1/audio/upload [post]
  34. func (slf AudioCtl) Upload(c *gin.Context) {
  35. var headers []*multipart.FileHeader
  36. files, _ := c.MultipartForm()
  37. if len(files.File["file"]) > 1 {
  38. headers = files.File["file"]
  39. } else {
  40. util.ResponseFormat(c, code.RequestParamError, "文件需要一一对应")
  41. return
  42. }
  43. audio := &models.Audio{}
  44. for _, header := range headers {
  45. filename := path.Base(header.Filename)
  46. arr := strings.Split(filename, "_")
  47. if len(arr) != 6 {
  48. util.ResponseFormat(c, code.RequestParamError, "文件名称错误")
  49. return
  50. }
  51. _, err := models.NewAudioSearch().SetName(filename).First()
  52. if err != gorm.ErrRecordNotFound {
  53. util.ResponseFormat(c, code.RequestParamError, "重复上传")
  54. return
  55. }
  56. oss := upload.NewOss()
  57. filePath, filename, uploadErr := oss.UploadFile(header)
  58. if uploadErr != nil {
  59. logx.Errorf("upload audio err: %v", err)
  60. util.ResponseFormat(c, code.RequestParamError, "上传失败")
  61. return
  62. }
  63. if filepath.Ext(filename) == ".mp3" || filepath.Ext(filename) == ".wav" {
  64. timeStr := arr[4] + strings.Split(arr[5], ".")[0]
  65. t, err := time.ParseInLocation("20060102150405", timeStr, time.Local)
  66. if err != nil {
  67. util.ResponseFormat(c, code.RequestParamError, "时间格式不对")
  68. return
  69. }
  70. audio.Name = filename
  71. audio.Size = header.Size
  72. audio.FilePath = filePath
  73. audio.AudioStatus = constvar.AudioStatusUploadOk
  74. audio.LocomotiveNumber = arr[0]
  75. audio.TrainNumber = arr[1]
  76. audio.DriverNumber = arr[2]
  77. audio.Station = arr[3]
  78. audio.OccurrenceAt = t
  79. audio.IsFollowed = 0
  80. }
  81. if filepath.Ext(filename) == ".txt" {
  82. audio.TxtFilePath = filePath
  83. //读取filepath文件内容到bts
  84. bts, err := os.ReadFile(filePath)
  85. if err != nil {
  86. util.ResponseFormat(c, code.RequestParamError, "读取文件失败")
  87. return
  88. }
  89. //解析 交路号:123_公里标:321
  90. fileds := string(bts)
  91. arr = strings.Split(fileds, "_")
  92. if len(arr) != 2 {
  93. util.ResponseFormat(c, code.RequestParamError, "文件内容格式不对")
  94. return
  95. } else {
  96. RouteNumber := strings.Split(arr[0], ":")
  97. KilometerMarker := strings.Split(arr[1], ":")
  98. if len(RouteNumber) > 1 && len(KilometerMarker) > 1 {
  99. audio.RouteNumber = RouteNumber[1]
  100. audio.KilometerMarker = KilometerMarker[1]
  101. } else {
  102. util.ResponseFormat(c, code.RequestParamError, "文件内容格式不对")
  103. return
  104. }
  105. }
  106. }
  107. }
  108. if err := models.NewAudioSearch().Create(audio); err != nil {
  109. util.ResponseFormat(c, code.SaveFail, "上传失败")
  110. return
  111. } else {
  112. util.ResponseFormat(c, code.SaveFail, "上传成功")
  113. return
  114. }
  115. go func() {
  116. var trainInfoNames = []string{audio.LocomotiveNumber, audio.TrainNumber, audio.Station}
  117. var (
  118. info *models.TrainInfo
  119. err error
  120. parent models.TrainInfo
  121. )
  122. for i := 0; i < 3; i++ {
  123. name := trainInfoNames[i]
  124. class := constvar.Class(i + 1)
  125. info, err = models.NewTrainInfoSearch().SetName(name).SetClass(class).First()
  126. if err == gorm.ErrRecordNotFound {
  127. info = &models.TrainInfo{
  128. Name: name,
  129. Class: class,
  130. ParentID: parent.ID,
  131. }
  132. _ = models.NewTrainInfoSearch().Create(info)
  133. }
  134. parent = *info
  135. }
  136. }()
  137. }
  138. func (slf AudioCtl) ParamsCheck(filename string) (err error) {
  139. arr := strings.Split(filename, "_")
  140. if len(arr) != 6 {
  141. return errors.New("文件格式错误")
  142. }
  143. return nil
  144. }
  145. // TrainInfoList
  146. // @Tags 音频
  147. // @Summary 获取火车信息
  148. // @Produce application/json
  149. // @Param object query request.GetTrainInfoList true "参数"
  150. // @Success 200 {object} util.ResponseList{data=[]models.TrainInfo} "成功"
  151. // @Router /api-sa/v1/audio/trainInfoList [get]
  152. func (slf AudioCtl) TrainInfoList(c *gin.Context) {
  153. var params request.GetTrainInfoList
  154. if err := c.ShouldBindQuery(&params); err != nil {
  155. util.ResponseFormat(c, code.RequestParamError, err.Error())
  156. return
  157. }
  158. if !params.PageInfo.Check() {
  159. util.ResponseFormat(c, code.RequestParamError, "分页参数错误")
  160. return
  161. }
  162. list, total, err := models.NewTrainInfoSearch().
  163. SetPage(params.Page, params.PageSize).
  164. SetClass(params.Class).
  165. SetParentId(params.ParentID).
  166. Find()
  167. if err != nil {
  168. util.ResponseFormat(c, code.RequestParamError, "查找失败")
  169. return
  170. }
  171. util.ResponseFormatList(c, code.Success, list, total)
  172. }
  173. // List
  174. // @Tags 音频
  175. // @Summary 音频分析检索
  176. // @Produce application/json
  177. // @Param object query request.GetAudioList true "参数"
  178. // @Success 200 {object} util.ResponseList{data=[]models.Audio} "成功"
  179. // @Router /api-sa/v1/audio/list [get]
  180. func (slf AudioCtl) List(c *gin.Context) {
  181. var params request.GetAudioList
  182. if err := c.ShouldBindQuery(&params); err != nil {
  183. util.ResponseFormat(c, code.RequestParamError, err.Error())
  184. return
  185. }
  186. if !params.PageInfo.Check() {
  187. util.ResponseFormat(c, code.RequestParamError, "分页参数错误")
  188. return
  189. }
  190. list, total, err := models.NewAudioSearch().
  191. SetPage(params.Page, params.PageSize).
  192. SetKeyword(params.Keyword).
  193. SetLocomotiveNumber(params.LocomotiveNumber).
  194. SetTrainNumber(params.TrainNumber).
  195. SetDriverNumber(params.DriverNumber).
  196. SetStation(params.StationNumber).
  197. SetBeginTime(params.BeginTime).
  198. SetEndTime(params.EndTime).
  199. SetIsFollowed(params.IsFollowed).
  200. SetAudioStatusList(params.StatusList).
  201. SetOrder("created_at desc").
  202. Find()
  203. if err != nil {
  204. util.ResponseFormat(c, code.RequestParamError, "查找失败")
  205. return
  206. }
  207. util.ResponseFormatList(c, code.Success, list, total)
  208. }
  209. // Process
  210. // @Tags 音频
  211. // @Summary 处理音频
  212. // @Produce application/json
  213. // @Param object body request.ProcessAudio true "参数"
  214. // @Success 200 {object} util.Response "成功"
  215. // @Router /api-sa/v1/audio/process [post]
  216. func (slf AudioCtl) Process(c *gin.Context) {
  217. var params request.ProcessAudio
  218. if err := c.ShouldBind(&params); err != nil {
  219. util.ResponseFormat(c, code.RequestParamError, err.Error())
  220. return
  221. }
  222. err := service.Process(params.ID)
  223. if err != nil {
  224. util.ResponseFormat(c, code.InternalError, err.Error())
  225. return
  226. }
  227. util.ResponseFormat(c, code.UpdateSuccess, "成功")
  228. }
  229. // AudioInfo
  230. // @Tags 音频
  231. // @Summary 音频详情,含解析结果
  232. // @Produce application/json
  233. // @Param object query request.ProcessAudio true "参数"
  234. // @Success 200 {object} util.Response{data=models.Audio} "成功"
  235. // @Router /api-sa/v1/audio/info [get]
  236. func (slf AudioCtl) AudioInfo(c *gin.Context) {
  237. var params request.ProcessAudio
  238. if err := c.ShouldBindQuery(&params); err != nil {
  239. util.ResponseFormat(c, code.RequestParamError, err.Error())
  240. return
  241. }
  242. audio, err := models.NewAudioSearch().SetID(params.ID).First()
  243. if err != nil {
  244. util.ResponseFormat(c, code.InternalError, "请求失败")
  245. return
  246. }
  247. audioText, err := models.NewAudioTextSearch().SetAudioID(audio.ID).First()
  248. if err == nil {
  249. audio.AudioText = audioText.AudioText
  250. }
  251. util.ResponseFormat(c, code.UpdateSuccess, audio)
  252. }
  253. // AudioDownload
  254. // @Tags 音频
  255. // @Summary 音频下载
  256. // @Produce application/json
  257. // @Param object query request.ProcessAudio true "参数"
  258. // @Success 200 {object} util.Response{data=models.Audio} "成功"
  259. // @Router /api-sa/v1/audio/download [get]
  260. func (slf AudioCtl) AudioDownload(c *gin.Context) {
  261. var params request.ProcessAudio
  262. if err := c.ShouldBindQuery(&params); err != nil {
  263. util.ResponseFormat(c, code.RequestParamError, err.Error())
  264. return
  265. }
  266. audio, err := models.NewAudioSearch().SetID(params.ID).First()
  267. if err != nil {
  268. util.ResponseFormat(c, code.InternalError, "查询失败")
  269. return
  270. }
  271. filepath := ""
  272. if params.Filetype == 1 {
  273. filepath = audio.FilePath
  274. c.Header("Content-Type", "audio/mpeg") // 设置音频文件类型
  275. c.Header("Content-Disposition", "attachment; filename="+url.PathEscape(audio.Name)) // 在浏览器中直接打开
  276. }
  277. if params.Filetype == 2 {
  278. filepath = audio.TxtFilePath
  279. //设置Content-Type为txt文件类型,避免中文乱码
  280. c.Header("Content-Type", "text/plain; charset=utf-8")
  281. c.Header("Content-Transfer-Encoding", "binary")
  282. //去掉audio.Name中.之后的内容,只保留文件名称
  283. fileName := strings.Split(audio.Name, ".")[0]
  284. c.Header("Content-Disposition", "attachment; filename="+url.PathEscape(fmt.Sprintf("%s.txt", fileName))) // 在浏览器中直接打开
  285. }
  286. if filepath == "" {
  287. util.ResponseFormat(c, code.InternalError, "查询失败")
  288. return
  289. }
  290. file, err := os.Open(filepath)
  291. if err != nil {
  292. util.ResponseFormat(c, code.InternalError, "文件打开失败")
  293. return
  294. }
  295. defer file.Close()
  296. fileInfo, err := file.Stat()
  297. if err != nil {
  298. util.ResponseFormat(c, code.InternalError, "获取文件信息失败")
  299. return
  300. }
  301. c.Header("Content-Length", fmt.Sprint(fileInfo.Size()))
  302. if _, err := io.Copy(c.Writer, file); err != nil {
  303. util.ResponseFormat(c, code.InternalError, "文件传输失败")
  304. return
  305. }
  306. }
  307. // BatchProcess
  308. // @Tags 音频
  309. // @Summary 批量处理音频
  310. // @Produce application/json
  311. // @Param object body request.BatchProcessAudio true "参数"
  312. // @Success 200 {object} util.Response "成功"
  313. // @Router /api-sa/v1/audio/batchProcess [post]
  314. func (slf AudioCtl) BatchProcess(c *gin.Context) {
  315. var params request.BatchProcessAudio
  316. if err := c.ShouldBind(&params); err != nil {
  317. util.ResponseFormat(c, code.RequestParamError, err.Error())
  318. return
  319. }
  320. var failedNumber int
  321. for _, audioID := range params.IDs {
  322. err := service.Process(audioID)
  323. if err != nil {
  324. logx.Errorf("%v,编号: %v", err.Error(), audioID)
  325. failedNumber++
  326. continue
  327. }
  328. }
  329. if failedNumber == 0 {
  330. util.ResponseFormat(c, code.UpdateSuccess, "成功")
  331. return
  332. } else if failedNumber < len(params.IDs) {
  333. util.ResponseFormat(c, code.RequestParamError, "部分处理失败")
  334. return
  335. } else {
  336. util.ResponseFormat(c, code.RequestParamError, "全部处理失败")
  337. return
  338. }
  339. }
  340. // Delete
  341. // @Tags 音频
  342. // @Summary 删除音频
  343. // @Produce application/json
  344. // @Param object body request.ProcessAudio true "参数"
  345. // @Success 200 {object} util.Response "成功"
  346. // @Router /api-sa/v1/audio/delete [delete]
  347. func (slf AudioCtl) Delete(c *gin.Context) {
  348. var params request.ProcessAudio
  349. if err := c.ShouldBind(&params); err != nil {
  350. util.ResponseFormat(c, code.RequestParamError, err.Error())
  351. return
  352. }
  353. audio, err := models.NewAudioSearch().SetID(params.ID).First()
  354. if err != nil {
  355. util.ResponseFormat(c, code.RequestParamError, "音频不存在")
  356. return
  357. }
  358. if audio.AudioStatus == constvar.AudioStatusProcessing || audio.AudioStatus == constvar.AudioStatusFinish {
  359. util.ResponseFormat(c, code.RequestParamError, "音频正在处理或者处理完成,不可删除")
  360. return
  361. }
  362. err = service.DeleteAudio(params.ID)
  363. if err != nil {
  364. util.ResponseFormat(c, code.InternalError, err.Error())
  365. return
  366. }
  367. go func() {
  368. err = os.Remove(audio.FilePath)
  369. if err != nil {
  370. logx.Warnf("remove file err:%v, file:%v", err, audio.FilePath)
  371. }
  372. }()
  373. util.ResponseFormat(c, code.DeleteSuccess, "成功")
  374. }
  375. // BatchDelete
  376. // @Tags 音频
  377. // @Summary 批量删除音频
  378. // @Produce application/json
  379. // @Param object body request.BatchProcessAudio true "参数"
  380. // @Success 200 {object} util.Response "成功"
  381. // @Router /api-sa/v1/audio/batchDelete [delete]
  382. func (slf AudioCtl) BatchDelete(c *gin.Context) {
  383. var params request.BatchProcessAudio
  384. if err := c.ShouldBind(&params); err != nil {
  385. util.ResponseFormat(c, code.RequestParamError, err.Error())
  386. return
  387. }
  388. audioList, err := models.NewAudioSearch().SetIDs(params.IDs).FindNotTotal()
  389. if err != nil {
  390. util.ResponseFormat(c, code.InternalError, "内部错误")
  391. return
  392. }
  393. for _, audio := range audioList {
  394. if audio.AudioStatus == constvar.AudioStatusProcessing || audio.AudioStatus == constvar.AudioStatusFinish {
  395. util.ResponseFormat(c, code.RequestParamError, "音频正在处理或者处理完成,不可删除")
  396. return
  397. }
  398. }
  399. err = service.BatchDeleteAudio(params.IDs)
  400. if err != nil {
  401. util.ResponseFormat(c, code.InternalError, err.Error())
  402. return
  403. }
  404. go func() {
  405. for _, audio := range audioList {
  406. err = os.Remove(audio.FilePath)
  407. if err != nil {
  408. logx.Warnf("remove file err:%v, file:%v", err, audio.FilePath)
  409. }
  410. }
  411. }()
  412. util.ResponseFormat(c, code.DeleteSuccess, "成功")
  413. }
  414. // Follow
  415. // @Tags 音频
  416. // @Summary 关注/取消关注
  417. // @Produce application/json
  418. // @Param object body request.FollowReq true "参数"
  419. // @Success 200 {object} util.Response{data=response.FollowResp} "成功"
  420. // @Router /api-sa/v1/audio/follow [post]
  421. func (slf AudioCtl) Follow(c *gin.Context) {
  422. var params request.ProcessAudio
  423. if err := c.ShouldBind(&params); err != nil {
  424. util.ResponseFormat(c, code.RequestParamError, err.Error())
  425. return
  426. }
  427. followStatus, err := service.Follow(params.ID)
  428. if err != nil {
  429. util.ResponseFormat(c, code.InternalError, err.Error())
  430. return
  431. }
  432. resp := response.FollowResp{FollowStatus: followStatus}
  433. util.ResponseFormat(c, code.UpdateSuccess, resp)
  434. }
  435. // PreLoadPath
  436. // @Tags 音频自动加载路径
  437. // @Summary 音频自动加载路径
  438. // @Produce application/json
  439. // @Success 200 {object} util.Response{data=response.PreLoadPathResp} "成功"
  440. // @Router /api-sa/v1/audio/preLoadPath [get]
  441. func (slf AudioCtl) PreLoadPath(c *gin.Context) {
  442. //获取PRELOAD_PATH环境变量
  443. preLoadPath := os.Getenv("PRELOAD_PATH")
  444. if len(preLoadPath) == 0 {
  445. preLoadPath = "./preloads"
  446. }
  447. resp := response.PreLoadPathResp{PreLoadPath: preLoadPath}
  448. util.ResponseFormat(c, code.UpdateSuccess, resp)
  449. }