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 15 kB

3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  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. tplModelInfo = "repo/modelmanage/showinfo"
  22. MODEL_LATEST = 1
  23. MODEL_NOT_LATEST = 0
  24. )
  25. func saveModelByParameters(jobId string, versionName string, name string, version string, label string, description string, ctx *context.Context) error {
  26. aiTask, err := models.GetCloudbrainByJobIDAndVersionName(jobId, versionName)
  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.Version == version {
  42. return errors.New(ctx.Tr("repo.model.manage.create_error"))
  43. }
  44. if model.New == MODEL_LATEST {
  45. lastNewModelId = model.ID
  46. }
  47. }
  48. }
  49. cloudType = aiTask.Type
  50. //download model zip //train type
  51. if cloudType == models.TypeCloudBrainTwo {
  52. modelPath, modelSize, err = downloadModelFromCloudBrainTwo(id, aiTask.JobName, "", aiTask.TrainUrl)
  53. if err != nil {
  54. log.Info("download model from CloudBrainTwo faild." + err.Error())
  55. return err
  56. }
  57. }
  58. accuracy := make(map[string]string)
  59. accuracy["F1"] = ""
  60. accuracy["Recall"] = ""
  61. accuracy["Accuracy"] = ""
  62. accuracy["Precision"] = ""
  63. accuracyJson, _ := json.Marshal(accuracy)
  64. log.Info("accuracyJson=" + string(accuracyJson))
  65. aiTaskJson, _ := json.Marshal(aiTask)
  66. model := &models.AiModelManage{
  67. ID: id,
  68. Version: version,
  69. VersionCount: len(aimodels) + 1,
  70. Label: label,
  71. Name: name,
  72. Description: description,
  73. New: MODEL_LATEST,
  74. Type: cloudType,
  75. Path: modelPath,
  76. Size: modelSize,
  77. AttachmentId: aiTask.Uuid,
  78. RepoId: aiTask.RepoID,
  79. UserId: ctx.User.ID,
  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 !ctx.Repo.CanWrite(models.UnitTypeModelManage) {
  106. ctx.ServerError("No right.", errors.New(ctx.Tr("repo.model_noright")))
  107. return
  108. }
  109. if JobId == "" || VersionName == "" {
  110. ctx.Error(500, fmt.Sprintf("JobId or VersionName is null."))
  111. return
  112. }
  113. if name == "" || version == "" {
  114. ctx.Error(500, fmt.Sprintf("name or version is null."))
  115. return
  116. }
  117. err := saveModelByParameters(JobId, VersionName, name, version, label, description, ctx)
  118. if err != nil {
  119. log.Info("save model error." + err.Error())
  120. ctx.Error(500, fmt.Sprintf("save model error. %v", err))
  121. return
  122. }
  123. log.Info("save model end.")
  124. }
  125. func downloadModelFromCloudBrainTwo(modelUUID string, jobName string, parentDir string, trainUrl string) (string, int64, error) {
  126. objectkey := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir), "/")
  127. if trainUrl != "" {
  128. objectkey = strings.Trim(trainUrl[len(setting.Bucket)+1:], "/")
  129. }
  130. modelDbResult, err := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, objectkey, "")
  131. log.Info("bucket=" + setting.Bucket + " objectkey=" + objectkey)
  132. if err != nil {
  133. log.Info("get TrainJobListModel failed:", err)
  134. return "", 0, err
  135. }
  136. if len(modelDbResult) == 0 {
  137. return "", 0, errors.New("cannot create model, as model is empty.")
  138. }
  139. prefix := objectkey + "/"
  140. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(modelUUID) + "/"
  141. size, err := storage.ObsCopyManyFile(setting.Bucket, prefix, setting.Bucket, destKeyNamePrefix)
  142. dataActualPath := setting.Bucket + "/" + destKeyNamePrefix
  143. return dataActualPath, size, nil
  144. }
  145. func DeleteModel(ctx *context.Context) {
  146. log.Info("delete model start.")
  147. id := ctx.Query("ID")
  148. err := deleteModelByID(ctx, id)
  149. if err != nil {
  150. ctx.JSON(500, err.Error())
  151. } else {
  152. ctx.JSON(200, map[string]string{
  153. "result_code": "0",
  154. })
  155. }
  156. }
  157. func isCanDeleteOrDownload(ctx *context.Context, model *models.AiModelManage) bool {
  158. if ctx.User.IsAdmin || ctx.User.ID == model.UserId {
  159. return true
  160. }
  161. if ctx.Repo.IsOwner() {
  162. return true
  163. }
  164. return false
  165. }
  166. func deleteModelByID(ctx *context.Context, id string) error {
  167. log.Info("delete model start. id=" + id)
  168. model, err := models.QueryModelById(id)
  169. if !isCanDeleteOrDownload(ctx, model) {
  170. return errors.New(ctx.Tr("repo.model_noright"))
  171. }
  172. if err == nil {
  173. log.Info("bucket=" + setting.Bucket + " path=" + model.Path)
  174. if strings.HasPrefix(model.Path, setting.Bucket+"/"+Model_prefix) {
  175. err := storage.ObsRemoveObject(setting.Bucket, model.Path[len(setting.Bucket)+1:])
  176. if err != nil {
  177. log.Info("Failed to delete model. id=" + id)
  178. return err
  179. }
  180. }
  181. err = models.DeleteModelById(id)
  182. if err == nil { //find a model to change new
  183. aimodels := models.QueryModelByName(model.Name, model.RepoId)
  184. if model.New == MODEL_LATEST {
  185. if len(aimodels) > 0 {
  186. //udpate status and version count
  187. models.ModifyModelNewProperty(aimodels[0].ID, MODEL_LATEST, len(aimodels))
  188. }
  189. } else {
  190. for _, tmpModel := range aimodels {
  191. if tmpModel.New == MODEL_LATEST {
  192. models.ModifyModelNewProperty(tmpModel.ID, MODEL_LATEST, len(aimodels))
  193. break
  194. }
  195. }
  196. }
  197. }
  198. }
  199. return err
  200. }
  201. func QueryModelByParameters(repoId int64, page int) ([]*models.AiModelManage, int64, error) {
  202. return models.QueryModel(&models.AiModelQueryOptions{
  203. ListOptions: models.ListOptions{
  204. Page: page,
  205. PageSize: setting.UI.IssuePagingNum,
  206. },
  207. RepoID: repoId,
  208. Type: -1,
  209. New: MODEL_LATEST,
  210. })
  211. }
  212. func DownloadMultiModelFile(ctx *context.Context) {
  213. log.Info("DownloadMultiModelFile start.")
  214. id := ctx.Query("ID")
  215. log.Info("id=" + id)
  216. task, err := models.QueryModelById(id)
  217. if err != nil {
  218. log.Error("no such model!", err.Error())
  219. ctx.ServerError("no such model:", err)
  220. return
  221. }
  222. if !isCanDeleteOrDownload(ctx, task) {
  223. ctx.ServerError("no right.", errors.New(ctx.Tr("repo.model_noright")))
  224. return
  225. }
  226. path := Model_prefix + models.AttachmentRelativePath(id) + "/"
  227. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  228. if err == nil {
  229. //count++
  230. models.ModifyModelDownloadCount(id)
  231. returnFileName := task.Name + "_" + task.Version + ".zip"
  232. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+returnFileName)
  233. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  234. w := zip.NewWriter(ctx.Resp)
  235. defer w.Close()
  236. for _, oneFile := range allFile {
  237. if oneFile.IsDir {
  238. log.Info("zip dir name:" + oneFile.FileName)
  239. } else {
  240. log.Info("zip file name:" + oneFile.FileName)
  241. fDest, err := w.Create(oneFile.FileName)
  242. if err != nil {
  243. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  244. ctx.ServerError("download file failed:", err)
  245. return
  246. }
  247. body, err := storage.ObsDownloadAFile(setting.Bucket, path+oneFile.FileName)
  248. if err != nil {
  249. log.Info("download file failed: %s\n", err.Error())
  250. ctx.ServerError("download file failed:", err)
  251. return
  252. } else {
  253. defer body.Close()
  254. p := make([]byte, 1024)
  255. var readErr error
  256. var readCount int
  257. // 读取对象内容
  258. for {
  259. readCount, readErr = body.Read(p)
  260. if readCount > 0 {
  261. fDest.Write(p[:readCount])
  262. }
  263. if readErr != nil {
  264. break
  265. }
  266. }
  267. }
  268. }
  269. }
  270. } else {
  271. log.Info("error,msg=" + err.Error())
  272. ctx.ServerError("no file to download.", err)
  273. }
  274. }
  275. func QueryTrainJobVersionList(ctx *context.Context) {
  276. log.Info("query train job version list. start.")
  277. JobID := ctx.Query("JobID")
  278. VersionListTasks, count, err := models.QueryModelTrainJobVersionList(JobID)
  279. log.Info("query return count=" + fmt.Sprint(count))
  280. if err != nil {
  281. ctx.ServerError("QueryTrainJobList:", err)
  282. } else {
  283. ctx.JSON(200, VersionListTasks)
  284. }
  285. }
  286. func QueryTrainJobList(ctx *context.Context) {
  287. log.Info("query train job list. start.")
  288. repoId := ctx.QueryInt64("repoId")
  289. VersionListTasks, count, err := models.QueryModelTrainJobList(repoId)
  290. log.Info("query return count=" + fmt.Sprint(count))
  291. if err != nil {
  292. ctx.ServerError("QueryTrainJobList:", err)
  293. } else {
  294. ctx.JSON(200, VersionListTasks)
  295. }
  296. }
  297. func DownloadSingleModelFile(ctx *context.Context) {
  298. log.Info("DownloadSingleModelFile start.")
  299. id := ctx.Params(":ID")
  300. parentDir := ctx.Query("parentDir")
  301. fileName := ctx.Query("fileName")
  302. path := Model_prefix + models.AttachmentRelativePath(id) + "/" + parentDir + fileName
  303. if setting.PROXYURL != "" {
  304. body, err := storage.ObsDownloadAFile(setting.Bucket, path)
  305. if err != nil {
  306. log.Info("download error.")
  307. } else {
  308. //count++
  309. models.ModifyModelDownloadCount(id)
  310. defer body.Close()
  311. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  312. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  313. p := make([]byte, 1024)
  314. var readErr error
  315. var readCount int
  316. // 读取对象内容
  317. for {
  318. readCount, readErr = body.Read(p)
  319. if readCount > 0 {
  320. ctx.Resp.Write(p[:readCount])
  321. //fmt.Printf("%s", p[:readCount])
  322. }
  323. if readErr != nil {
  324. break
  325. }
  326. }
  327. }
  328. } else {
  329. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  330. if err != nil {
  331. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  332. ctx.ServerError("GetObsCreateSignedUrl", err)
  333. return
  334. }
  335. //count++
  336. models.ModifyModelDownloadCount(id)
  337. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  338. }
  339. }
  340. func ShowModelInfo(ctx *context.Context) {
  341. ctx.Data["ID"] = ctx.Query("ID")
  342. ctx.Data["name"] = ctx.Query("name")
  343. ctx.Data["isModelManage"] = true
  344. ctx.HTML(200, tplModelInfo)
  345. }
  346. func ShowSingleModel(ctx *context.Context) {
  347. name := ctx.Query("name")
  348. log.Info("Show single ModelInfo start.name=" + name)
  349. models := models.QueryModelByName(name, ctx.Repo.Repository.ID)
  350. userIds := make([]int64, len(models))
  351. for i, model := range models {
  352. model.IsCanOper = isOper(ctx, model.UserId)
  353. userIds[i] = model.UserId
  354. }
  355. userNameMap := queryUserName(userIds)
  356. for _, model := range models {
  357. value := userNameMap[model.UserId]
  358. if value != nil {
  359. model.UserName = value.Name
  360. model.UserRelAvatarLink = value.RelAvatarLink()
  361. }
  362. }
  363. ctx.JSON(http.StatusOK, models)
  364. }
  365. func queryUserName(intSlice []int64) map[int64]*models.User {
  366. keys := make(map[int64]string)
  367. uniqueElements := []int64{}
  368. for _, entry := range intSlice {
  369. if _, value := keys[entry]; !value {
  370. keys[entry] = ""
  371. uniqueElements = append(uniqueElements, entry)
  372. }
  373. }
  374. result := make(map[int64]*models.User)
  375. userLists, err := models.GetUsersByIDs(uniqueElements)
  376. if err == nil {
  377. for _, user := range userLists {
  378. result[user.ID] = user
  379. }
  380. }
  381. return result
  382. }
  383. func ShowOneVersionOtherModel(ctx *context.Context) {
  384. repoId := ctx.Repo.Repository.ID
  385. name := ctx.Query("name")
  386. aimodels := models.QueryModelByName(name, repoId)
  387. userIds := make([]int64, len(aimodels))
  388. for i, model := range aimodels {
  389. model.IsCanOper = isOper(ctx, model.UserId)
  390. userIds[i] = model.UserId
  391. }
  392. userNameMap := queryUserName(userIds)
  393. for _, model := range aimodels {
  394. value := userNameMap[model.UserId]
  395. if value != nil {
  396. model.UserName = value.Name
  397. model.UserRelAvatarLink = value.RelAvatarLink()
  398. }
  399. }
  400. if len(aimodels) > 0 {
  401. ctx.JSON(200, aimodels[1:])
  402. } else {
  403. ctx.JSON(200, aimodels)
  404. }
  405. }
  406. func ShowModelTemplate(ctx *context.Context) {
  407. ctx.Data["isModelManage"] = true
  408. ctx.HTML(200, tplModelManageIndex)
  409. }
  410. func isQueryRight(ctx *context.Context) bool {
  411. if ctx.Repo.Repository.IsPrivate {
  412. if ctx.Repo.CanRead(models.UnitTypeModelManage) || ctx.User.IsAdmin || ctx.Repo.IsAdmin() || ctx.Repo.IsOwner() {
  413. return true
  414. }
  415. return false
  416. } else {
  417. return true
  418. }
  419. }
  420. func isOper(ctx *context.Context, modelUserId int64) bool {
  421. if ctx.User == nil {
  422. return false
  423. }
  424. if ctx.User.IsAdmin || ctx.Repo.IsOwner() || ctx.User.ID == modelUserId {
  425. return true
  426. }
  427. return false
  428. }
  429. func ShowModelPageInfo(ctx *context.Context) {
  430. log.Info("ShowModelInfo start.")
  431. if !isQueryRight(ctx) {
  432. ctx.ServerError("no right.", errors.New(ctx.Tr("repo.model_noright")))
  433. return
  434. }
  435. page := ctx.QueryInt("page")
  436. if page <= 0 {
  437. page = 1
  438. }
  439. pageSize := ctx.QueryInt("pageSize")
  440. if pageSize <= 0 {
  441. pageSize = setting.UI.IssuePagingNum
  442. }
  443. repoId := ctx.Repo.Repository.ID
  444. Type := -1
  445. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  446. ListOptions: models.ListOptions{
  447. Page: page,
  448. PageSize: pageSize,
  449. },
  450. RepoID: repoId,
  451. Type: Type,
  452. New: MODEL_LATEST,
  453. })
  454. if err != nil {
  455. ctx.ServerError("Cloudbrain", err)
  456. return
  457. }
  458. userIds := make([]int64, len(modelResult))
  459. for i, model := range modelResult {
  460. model.IsCanOper = isOper(ctx, model.UserId)
  461. userIds[i] = model.UserId
  462. }
  463. userNameMap := queryUserName(userIds)
  464. for _, model := range modelResult {
  465. value := userNameMap[model.UserId]
  466. if value != nil {
  467. model.UserName = value.Name
  468. model.UserRelAvatarLink = value.RelAvatarLink()
  469. }
  470. }
  471. mapInterface := make(map[string]interface{})
  472. mapInterface["data"] = modelResult
  473. mapInterface["count"] = count
  474. ctx.JSON(http.StatusOK, mapInterface)
  475. }
  476. func ModifyModel(id string, description string) error {
  477. err := models.ModifyModelDescription(id, description)
  478. if err == nil {
  479. log.Info("modify success.")
  480. } else {
  481. log.Info("Failed to modify.id=" + id + " desc=" + description + " error:" + err.Error())
  482. }
  483. return err
  484. }
  485. func ModifyModelInfo(ctx *context.Context) {
  486. log.Info("modify model start.")
  487. id := ctx.Query("ID")
  488. description := ctx.Query("Description")
  489. task, err := models.QueryModelById(id)
  490. if err != nil {
  491. log.Error("no such model!", err.Error())
  492. ctx.ServerError("no such model:", err)
  493. return
  494. }
  495. if !isCanDeleteOrDownload(ctx, task) {
  496. ctx.ServerError("no right.", errors.New(ctx.Tr("repo.model_noright")))
  497. return
  498. }
  499. err = ModifyModel(id, description)
  500. if err != nil {
  501. log.Info("modify error," + err.Error())
  502. ctx.ServerError("error.", err)
  503. } else {
  504. ctx.JSON(200, "success")
  505. }
  506. }