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

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