You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ai_model_manage.go 12 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. package repo
  2. import (
  3. "archive/zip"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "path"
  9. "strings"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/context"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/setting"
  14. "code.gitea.io/gitea/modules/storage"
  15. uuid "github.com/satori/go.uuid"
  16. )
  17. const (
  18. Model_prefix = "aimodels/"
  19. tplModelManageIndex = "repo/modelmanage/index"
  20. tplModelManageDownload = "repo/modelmanage/download"
  21. MODEL_LATEST = 1
  22. MODEL_NOT_LATEST = 0
  23. )
  24. func saveModelByParameters(jobId string, versionName string, name string, version string, label string, description string, userId int64, userName string, userHeadUrl string) error {
  25. aiTask, err := models.GetCloudbrainByJobIDAndVersionName(jobId, versionName)
  26. //aiTask, err := models.GetCloudbrainByJobID(jobId)
  27. if err != nil {
  28. log.Info("query task error." + err.Error())
  29. return err
  30. }
  31. uuid := uuid.NewV4()
  32. id := uuid.String()
  33. modelPath := id
  34. var lastNewModelId string
  35. var modelSize int64
  36. cloudType := models.TypeCloudBrainTwo
  37. log.Info("find task name:" + aiTask.JobName)
  38. aimodels := models.QueryModelByName(name, aiTask.RepoID)
  39. if len(aimodels) > 0 {
  40. for _, model := range aimodels {
  41. if model.New == MODEL_LATEST {
  42. lastNewModelId = model.ID
  43. }
  44. }
  45. }
  46. cloudType = aiTask.Type
  47. //download model zip //train type
  48. if cloudType == models.TypeCloudBrainTwo {
  49. modelPath, modelSize, err = downloadModelFromCloudBrainTwo(id, aiTask.JobName, "")
  50. if err != nil {
  51. log.Info("download model from CloudBrainTwo faild." + err.Error())
  52. return err
  53. }
  54. }
  55. accuracy := make(map[string]string)
  56. accuracy["F1"] = ""
  57. accuracy["Recall"] = ""
  58. accuracy["Accuracy"] = ""
  59. accuracy["Precision"] = ""
  60. accuracyJson, _ := json.Marshal(accuracy)
  61. log.Info("accuracyJson=" + string(accuracyJson))
  62. aiTaskJson, _ := json.Marshal(aiTask)
  63. //taskConfigInfo,err := models.GetCloudbrainByJobIDAndVersionName(jobId,aiTask.VersionName)
  64. model := &models.AiModelManage{
  65. ID: id,
  66. Version: version,
  67. VersionCount: len(aimodels) + 1,
  68. Label: label,
  69. Name: name,
  70. Description: description,
  71. New: MODEL_LATEST,
  72. Type: cloudType,
  73. Path: modelPath,
  74. Size: modelSize,
  75. AttachmentId: aiTask.Uuid,
  76. RepoId: aiTask.RepoID,
  77. UserId: userId,
  78. UserName: userName,
  79. UserRelAvatarLink: userHeadUrl,
  80. CodeBranch: aiTask.BranchName,
  81. CodeCommitID: aiTask.CommitID,
  82. Engine: aiTask.EngineID,
  83. TrainTaskInfo: string(aiTaskJson),
  84. Accuracy: string(accuracyJson),
  85. }
  86. err = models.SaveModelToDb(model)
  87. if err != nil {
  88. return err
  89. }
  90. if len(lastNewModelId) > 0 {
  91. //udpate status and version count
  92. models.ModifyModelNewProperty(lastNewModelId, MODEL_NOT_LATEST, 0)
  93. }
  94. log.Info("save model end.")
  95. return nil
  96. }
  97. func SaveModel(ctx *context.Context) {
  98. log.Info("save model start.")
  99. JobId := ctx.Query("JobId")
  100. VersionName := ctx.Query("VersionName")
  101. name := ctx.Query("Name")
  102. version := ctx.Query("Version")
  103. label := ctx.Query("Label")
  104. description := ctx.Query("Description")
  105. if JobId == "" || VersionName == "" {
  106. ctx.Error(500, fmt.Sprintf("JobId or VersionName is null."))
  107. return
  108. }
  109. if name == "" || version == "" {
  110. ctx.Error(500, fmt.Sprintf("name or version is null."))
  111. return
  112. }
  113. err := saveModelByParameters(JobId, VersionName, name, version, label, description, ctx.User.ID, ctx.User.Name, ctx.User.RelAvatarLink())
  114. if err != nil {
  115. log.Info("save model error." + err.Error())
  116. ctx.Error(500, fmt.Sprintf("save model error. %v", err))
  117. return
  118. }
  119. log.Info("save model end.")
  120. }
  121. func downloadModelFromCloudBrainTwo(modelUUID string, jobName string, parentDir string) (string, int64, error) {
  122. objectkey := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir), "/")
  123. modelDbResult, err := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, objectkey, "")
  124. log.Info("bucket=" + setting.Bucket + " objectkey=" + objectkey)
  125. if err != nil {
  126. log.Info("get TrainJobListModel failed:", err)
  127. return "", 0, err
  128. }
  129. if len(modelDbResult) == 0 {
  130. return "", 0, errors.New("cannot create model, as model is empty.")
  131. }
  132. prefix := objectkey + "/"
  133. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(modelUUID) + "/"
  134. size, err := storage.ObsCopyManyFile(setting.Bucket, prefix, setting.Bucket, destKeyNamePrefix)
  135. dataActualPath := setting.Bucket + "/" + destKeyNamePrefix
  136. return dataActualPath, size, nil
  137. }
  138. func DeleteModel(ctx *context.Context) {
  139. log.Info("delete model start.")
  140. id := ctx.Query("ID")
  141. err := DeleteModelByID(id)
  142. if err != nil {
  143. ctx.JSON(500, err.Error())
  144. } else {
  145. ctx.JSON(200, map[string]string{
  146. "result_code": "0",
  147. })
  148. }
  149. }
  150. func DeleteModelByID(id string) error {
  151. log.Info("delete model start. id=" + id)
  152. model, err := models.QueryModelById(id)
  153. if err == nil {
  154. log.Info("bucket=" + setting.Bucket + " path=" + model.Path)
  155. if strings.HasPrefix(model.Path, setting.Bucket+"/"+Model_prefix) {
  156. err := storage.ObsRemoveObject(setting.Bucket, model.Path[len(setting.Bucket)+1:])
  157. if err != nil {
  158. log.Info("Failed to delete model. id=" + id)
  159. return err
  160. }
  161. }
  162. err = models.DeleteModelById(id)
  163. if err == nil { //find a model to change new
  164. if model.New == MODEL_LATEST {
  165. aimodels := models.QueryModelByName(model.Name, model.RepoId)
  166. if len(aimodels) > 0 {
  167. //udpate status and version count
  168. models.ModifyModelNewProperty(aimodels[0].ID, MODEL_LATEST, len(aimodels))
  169. }
  170. }
  171. }
  172. }
  173. return err
  174. }
  175. func QueryModelByParameters(repoId int64, page int) ([]*models.AiModelManage, int64, error) {
  176. return models.QueryModel(&models.AiModelQueryOptions{
  177. ListOptions: models.ListOptions{
  178. Page: page,
  179. PageSize: setting.UI.IssuePagingNum,
  180. },
  181. RepoID: repoId,
  182. Type: -1,
  183. New: MODEL_LATEST,
  184. })
  185. }
  186. func DownloadMultiModelFile(ctx *context.Context) {
  187. log.Info("DownloadMultiModelFile start.")
  188. id := ctx.Query("ID")
  189. log.Info("id=" + id)
  190. task, err := models.QueryModelById(id)
  191. if err != nil {
  192. log.Error("no such model!", err.Error())
  193. ctx.ServerError("no such model:", err)
  194. return
  195. }
  196. path := Model_prefix + models.AttachmentRelativePath(id) + "/"
  197. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  198. if err == nil {
  199. //count++
  200. models.ModifyModelDownloadCount(id)
  201. returnFileName := task.Name + "_" + task.Version + ".zip"
  202. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+returnFileName)
  203. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  204. w := zip.NewWriter(ctx.Resp)
  205. defer w.Close()
  206. for _, oneFile := range allFile {
  207. if oneFile.IsDir {
  208. log.Info("zip dir name:" + oneFile.FileName)
  209. } else {
  210. log.Info("zip file name:" + oneFile.FileName)
  211. fDest, err := w.Create(oneFile.FileName)
  212. if err != nil {
  213. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  214. ctx.ServerError("download file failed:", err)
  215. return
  216. }
  217. body, err := storage.ObsDownloadAFile(setting.Bucket, path+oneFile.FileName)
  218. if err != nil {
  219. log.Info("download file failed: %s\n", err.Error())
  220. ctx.ServerError("download file failed:", err)
  221. return
  222. } else {
  223. defer body.Close()
  224. p := make([]byte, 1024)
  225. var readErr error
  226. var readCount int
  227. // 读取对象内容
  228. for {
  229. readCount, readErr = body.Read(p)
  230. if readCount > 0 {
  231. fDest.Write(p[:readCount])
  232. }
  233. if readErr != nil {
  234. break
  235. }
  236. }
  237. }
  238. }
  239. }
  240. } else {
  241. log.Info("error,msg=" + err.Error())
  242. ctx.ServerError("no file to download.", err)
  243. }
  244. }
  245. func QueryTrainJobVersionList(ctx *context.Context) {
  246. log.Info("query train job version list. start.")
  247. JobID := ctx.Query("JobID")
  248. VersionListTasks, count, err := models.QueryModelTrainJobVersionList(JobID)
  249. log.Info("query return count=" + fmt.Sprint(count))
  250. if err != nil {
  251. ctx.ServerError("QueryTrainJobList:", err)
  252. } else {
  253. ctx.JSON(200, VersionListTasks)
  254. }
  255. }
  256. func QueryTrainJobList(ctx *context.Context) {
  257. log.Info("query train job list. start.")
  258. repoId := ctx.QueryInt64("repoId")
  259. VersionListTasks, count, err := models.QueryModelTrainJobList(repoId)
  260. log.Info("query return count=" + fmt.Sprint(count))
  261. if err != nil {
  262. ctx.ServerError("QueryTrainJobList:", err)
  263. } else {
  264. ctx.JSON(200, VersionListTasks)
  265. }
  266. }
  267. func DownloadSingleModelFile(ctx *context.Context) {
  268. log.Info("DownloadSingleModelFile start.")
  269. id := ctx.Params(":ID")
  270. parentDir := ctx.Query("parentDir")
  271. fileName := ctx.Query("fileName")
  272. path := Model_prefix + models.AttachmentRelativePath(id) + "/" + parentDir + fileName
  273. if setting.PROXYURL != "" {
  274. body, err := storage.ObsDownloadAFile(setting.Bucket, path)
  275. if err != nil {
  276. log.Info("download error.")
  277. } else {
  278. //count++
  279. models.ModifyModelDownloadCount(id)
  280. defer body.Close()
  281. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  282. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  283. p := make([]byte, 1024)
  284. var readErr error
  285. var readCount int
  286. // 读取对象内容
  287. for {
  288. readCount, readErr = body.Read(p)
  289. if readCount > 0 {
  290. ctx.Resp.Write(p[:readCount])
  291. //fmt.Printf("%s", p[:readCount])
  292. }
  293. if readErr != nil {
  294. break
  295. }
  296. }
  297. }
  298. } else {
  299. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  300. if err != nil {
  301. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  302. ctx.ServerError("GetObsCreateSignedUrl", err)
  303. return
  304. }
  305. //count++
  306. models.ModifyModelDownloadCount(id)
  307. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  308. }
  309. }
  310. func ShowSingleModel(ctx *context.Context) {
  311. id := ctx.Params(":ID")
  312. parentDir := ctx.Query("parentDir")
  313. log.Info("Show single ModelInfo start.id=" + id)
  314. task, err := models.QueryModelById(id)
  315. if err != nil {
  316. log.Error("no such model!", err.Error())
  317. ctx.ServerError("no such model:", err)
  318. return
  319. }
  320. log.Info("bucket=" + setting.Bucket + " key=" + task.Path[len(setting.Bucket)+1:])
  321. models, err := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, task.Path[len(setting.Bucket)+1:], parentDir)
  322. if err != nil {
  323. log.Info("get model list failed:", err)
  324. ctx.ServerError("GetObsListObject:", err)
  325. return
  326. } else {
  327. log.Info("get model file,size=" + fmt.Sprint(len(models)))
  328. }
  329. ctx.Data["Dirs"] = models
  330. ctx.Data["task"] = task
  331. ctx.Data["ID"] = id
  332. ctx.HTML(200, tplModelManageDownload)
  333. }
  334. func ShowOneVersionOtherModel(ctx *context.Context) {
  335. repoId := ctx.Repo.Repository.ID
  336. name := ctx.Query("name")
  337. aimodels := models.QueryModelByName(name, repoId)
  338. if len(aimodels) > 0 {
  339. ctx.JSON(200, aimodels[1:])
  340. } else {
  341. ctx.JSON(200, aimodels)
  342. }
  343. }
  344. func ShowModelTemplate(ctx *context.Context) {
  345. ctx.HTML(200, tplModelManageIndex)
  346. }
  347. func ShowModelPageInfo(ctx *context.Context) {
  348. log.Info("ShowModelInfo start.")
  349. page := ctx.QueryInt("page")
  350. if page <= 0 {
  351. page = 1
  352. }
  353. repoId := ctx.Repo.Repository.ID
  354. Type := -1
  355. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  356. ListOptions: models.ListOptions{
  357. Page: page,
  358. PageSize: setting.UI.IssuePagingNum,
  359. },
  360. RepoID: repoId,
  361. Type: Type,
  362. New: MODEL_LATEST,
  363. })
  364. if err != nil {
  365. ctx.ServerError("Cloudbrain", err)
  366. return
  367. }
  368. mapInterface := make(map[string]interface{})
  369. mapInterface["data"] = modelResult
  370. mapInterface["count"] = count
  371. ctx.JSON(http.StatusOK, mapInterface)
  372. }
  373. func ModifyModel(id string, description string) error {
  374. err := models.ModifyModelDescription(id, description)
  375. if err == nil {
  376. log.Info("modify success.")
  377. } else {
  378. log.Info("Failed to modify.id=" + id + " desc=" + description + " error:" + err.Error())
  379. }
  380. return err
  381. }
  382. func ModifyModelInfo(ctx *context.Context) {
  383. log.Info("delete model start.")
  384. id := ctx.Query("ID")
  385. description := ctx.Query("Description")
  386. err := ModifyModel(id, description)
  387. if err == nil {
  388. ctx.HTML(200, "success")
  389. } else {
  390. ctx.HTML(500, "Failed.")
  391. }
  392. }