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

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. package repo
  2. import (
  3. "archive/zip"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "net/url"
  9. "path"
  10. "strings"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/context"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/notification"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/storage"
  17. uuid "github.com/satori/go.uuid"
  18. )
  19. const (
  20. Model_prefix = "aimodels/"
  21. tplModelManageIndex = "repo/modelmanage/index"
  22. tplModelManageDownload = "repo/modelmanage/download"
  23. tplModelInfo = "repo/modelmanage/showinfo"
  24. MODEL_LATEST = 1
  25. MODEL_NOT_LATEST = 0
  26. )
  27. func saveModelByParameters(jobId string, versionName string, name string, version string, label string, description string, engine int, ctx *context.Context) error {
  28. aiTask, err := models.GetCloudbrainByJobIDAndVersionName(jobId, versionName)
  29. if err != nil {
  30. aiTask, err = models.GetRepoCloudBrainByJobID(ctx.Repo.Repository.ID, jobId)
  31. if err != nil {
  32. log.Info("query task error." + err.Error())
  33. return err
  34. } else {
  35. log.Info("query gpu train task.")
  36. }
  37. }
  38. uuid := uuid.NewV4()
  39. id := uuid.String()
  40. modelPath := id
  41. var lastNewModelId string
  42. var modelSize int64
  43. log.Info("find task name:" + aiTask.JobName)
  44. aimodels := models.QueryModelByName(name, aiTask.RepoID)
  45. if len(aimodels) > 0 {
  46. for _, model := range aimodels {
  47. if model.Version == version {
  48. return errors.New(ctx.Tr("repo.model.manage.create_error"))
  49. }
  50. if model.New == MODEL_LATEST {
  51. lastNewModelId = model.ID
  52. }
  53. }
  54. }
  55. cloudType := aiTask.Type
  56. //download model zip //train type
  57. if cloudType == models.TypeCloudBrainTwo {
  58. modelPath, modelSize, err = downloadModelFromCloudBrainTwo(id, aiTask.JobName, "", aiTask.TrainUrl)
  59. if err != nil {
  60. log.Info("download model from CloudBrainTwo faild." + err.Error())
  61. return err
  62. }
  63. } else if cloudType == models.TypeCloudBrainOne {
  64. var ResourceSpecs *models.ResourceSpecs
  65. json.Unmarshal([]byte(setting.ResourceSpecs), &ResourceSpecs)
  66. for _, tmp := range ResourceSpecs.ResourceSpec {
  67. if tmp.Id == aiTask.ResourceSpecId {
  68. flaverName := ctx.Tr("cloudbrain.gpu_num") + ": " + fmt.Sprint(tmp.GpuNum) + " " + ctx.Tr("cloudbrain.cpu_num") + ": " + fmt.Sprint(tmp.CpuNum) + " " + ctx.Tr("cloudbrain.memory") + "(MB): " + fmt.Sprint(tmp.MemMiB) + " " + ctx.Tr("cloudbrain.shared_memory") + "(MB): " + fmt.Sprint(tmp.ShareMemMiB)
  69. aiTask.FlavorName = flaverName
  70. }
  71. }
  72. modelPath, modelSize, err = downloadModelFromCloudBrainOne(id, aiTask.JobName, "", aiTask.TrainUrl)
  73. if err != nil {
  74. log.Info("download model from CloudBrainOne faild." + err.Error())
  75. return err
  76. }
  77. }
  78. accuracy := make(map[string]string)
  79. accuracy["F1"] = ""
  80. accuracy["Recall"] = ""
  81. accuracy["Accuracy"] = ""
  82. accuracy["Precision"] = ""
  83. accuracyJson, _ := json.Marshal(accuracy)
  84. log.Info("accuracyJson=" + string(accuracyJson))
  85. aiTaskJson, _ := json.Marshal(aiTask)
  86. model := &models.AiModelManage{
  87. ID: id,
  88. Version: version,
  89. VersionCount: len(aimodels) + 1,
  90. Label: label,
  91. Name: name,
  92. Description: description,
  93. New: MODEL_LATEST,
  94. Type: cloudType,
  95. Path: modelPath,
  96. Size: modelSize,
  97. AttachmentId: aiTask.Uuid,
  98. RepoId: aiTask.RepoID,
  99. UserId: ctx.User.ID,
  100. CodeBranch: aiTask.BranchName,
  101. CodeCommitID: aiTask.CommitID,
  102. Engine: int64(engine),
  103. TrainTaskInfo: string(aiTaskJson),
  104. Accuracy: string(accuracyJson),
  105. }
  106. err = models.SaveModelToDb(model)
  107. if err != nil {
  108. return err
  109. }
  110. if len(lastNewModelId) > 0 {
  111. //udpate status and version count
  112. models.ModifyModelNewProperty(lastNewModelId, MODEL_NOT_LATEST, 0)
  113. }
  114. var units []models.RepoUnit
  115. var deleteUnitTypes []models.UnitType
  116. units = append(units, models.RepoUnit{
  117. RepoID: ctx.Repo.Repository.ID,
  118. Type: models.UnitTypeModelManage,
  119. Config: &models.ModelManageConfig{
  120. EnableModelManage: true,
  121. },
  122. })
  123. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeModelManage)
  124. models.UpdateRepositoryUnits(ctx.Repo.Repository, units, deleteUnitTypes)
  125. log.Info("save model end.")
  126. notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, id, name, models.ActionCreateNewModelTask)
  127. return nil
  128. }
  129. func SaveNewNameModel(ctx *context.Context) {
  130. name := ctx.Query("Name")
  131. if name == "" {
  132. ctx.Error(500, fmt.Sprintf("name or version is null."))
  133. return
  134. }
  135. aimodels := models.QueryModelByName(name, ctx.Repo.Repository.ID)
  136. if len(aimodels) > 0 {
  137. ctx.Error(500, ctx.Tr("repo.model_rename"))
  138. return
  139. }
  140. SaveModel(ctx)
  141. ctx.Status(200)
  142. log.Info("save model end.")
  143. }
  144. func SaveModel(ctx *context.Context) {
  145. log.Info("save model start.")
  146. JobId := ctx.Query("JobId")
  147. VersionName := ctx.Query("VersionName")
  148. name := ctx.Query("Name")
  149. version := ctx.Query("Version")
  150. label := ctx.Query("Label")
  151. description := ctx.Query("Description")
  152. engine := ctx.QueryInt("Engine")
  153. trainTaskCreate := ctx.QueryBool("trainTaskCreate")
  154. log.Info("engine=" + fmt.Sprint(engine))
  155. if !trainTaskCreate {
  156. if !ctx.Repo.CanWrite(models.UnitTypeModelManage) {
  157. //ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  158. ctx.JSON(403, ctx.Tr("repo.model_noright"))
  159. return
  160. }
  161. }
  162. if JobId == "" || VersionName == "" {
  163. ctx.Error(500, fmt.Sprintf("JobId or VersionName is null."))
  164. return
  165. }
  166. if name == "" || version == "" {
  167. ctx.Error(500, fmt.Sprintf("name or version is null."))
  168. return
  169. }
  170. err := saveModelByParameters(JobId, VersionName, name, version, label, description, engine, ctx)
  171. if err != nil {
  172. log.Info("save model error." + err.Error())
  173. ctx.Error(500, fmt.Sprintf("save model error. %v", err))
  174. return
  175. }
  176. ctx.Status(200)
  177. log.Info("save model end.")
  178. }
  179. func downloadModelFromCloudBrainTwo(modelUUID string, jobName string, parentDir string, trainUrl string) (string, int64, error) {
  180. objectkey := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir), "/")
  181. if trainUrl != "" {
  182. objectkey = strings.Trim(trainUrl[len(setting.Bucket)+1:], "/")
  183. }
  184. modelDbResult, err := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, objectkey, "")
  185. log.Info("bucket=" + setting.Bucket + " objectkey=" + objectkey)
  186. if err != nil {
  187. log.Info("get TrainJobListModel failed:", err)
  188. return "", 0, err
  189. }
  190. if len(modelDbResult) == 0 {
  191. return "", 0, errors.New("cannot create model, as model is empty.")
  192. }
  193. prefix := objectkey + "/"
  194. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(modelUUID) + "/"
  195. size, err := storage.ObsCopyManyFile(setting.Bucket, prefix, setting.Bucket, destKeyNamePrefix)
  196. dataActualPath := setting.Bucket + "/" + destKeyNamePrefix
  197. return dataActualPath, size, nil
  198. }
  199. func downloadModelFromCloudBrainOne(modelUUID string, jobName string, parentDir string, trainUrl string) (string, int64, error) {
  200. modelActualPath := storage.GetMinioPath(jobName, "/model/")
  201. log.Info("modelActualPath=" + modelActualPath)
  202. modelSrcPrefix := setting.CBCodePathPrefix + jobName + "/model/"
  203. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(modelUUID) + "/"
  204. bucketName := setting.Attachment.Minio.Bucket
  205. log.Info("destKeyNamePrefix=" + destKeyNamePrefix + " modelSrcPrefix=" + modelSrcPrefix + " bucket=" + bucketName)
  206. size, err := storage.MinioPathCopy(bucketName, modelSrcPrefix, destKeyNamePrefix)
  207. if err == nil {
  208. dataActualPath := bucketName + "/" + destKeyNamePrefix
  209. return dataActualPath, size, nil
  210. } else {
  211. return "", 0, nil
  212. }
  213. }
  214. func DeleteModel(ctx *context.Context) {
  215. log.Info("delete model start.")
  216. id := ctx.Query("ID")
  217. err := deleteModelByID(ctx, id)
  218. if err != nil {
  219. ctx.JSON(500, err.Error())
  220. } else {
  221. ctx.JSON(200, map[string]string{
  222. "result_code": "0",
  223. })
  224. }
  225. }
  226. func deleteModelByID(ctx *context.Context, id string) error {
  227. log.Info("delete model start. id=" + id)
  228. model, err := models.QueryModelById(id)
  229. if !isCanDelete(ctx, model.UserId) {
  230. return errors.New(ctx.Tr("repo.model_noright"))
  231. }
  232. if err == nil {
  233. log.Info("bucket=" + setting.Bucket + " path=" + model.Path)
  234. if strings.HasPrefix(model.Path, setting.Bucket+"/"+Model_prefix) {
  235. err := storage.ObsRemoveObject(setting.Bucket, model.Path[len(setting.Bucket)+1:])
  236. if err != nil {
  237. log.Info("Failed to delete model. id=" + id)
  238. return err
  239. }
  240. }
  241. err = models.DeleteModelById(id)
  242. if err == nil { //find a model to change new
  243. aimodels := models.QueryModelByName(model.Name, model.RepoId)
  244. if model.New == MODEL_LATEST {
  245. if len(aimodels) > 0 {
  246. //udpate status and version count
  247. models.ModifyModelNewProperty(aimodels[0].ID, MODEL_LATEST, len(aimodels))
  248. }
  249. } else {
  250. for _, tmpModel := range aimodels {
  251. if tmpModel.New == MODEL_LATEST {
  252. models.ModifyModelNewProperty(tmpModel.ID, MODEL_LATEST, len(aimodels))
  253. break
  254. }
  255. }
  256. }
  257. }
  258. }
  259. return err
  260. }
  261. func QueryModelByParameters(repoId int64, page int) ([]*models.AiModelManage, int64, error) {
  262. return models.QueryModel(&models.AiModelQueryOptions{
  263. ListOptions: models.ListOptions{
  264. Page: page,
  265. PageSize: setting.UI.IssuePagingNum,
  266. },
  267. RepoID: repoId,
  268. Type: -1,
  269. New: MODEL_LATEST,
  270. })
  271. }
  272. func DownloadMultiModelFile(ctx *context.Context) {
  273. log.Info("DownloadMultiModelFile start.")
  274. id := ctx.Query("ID")
  275. log.Info("id=" + id)
  276. task, err := models.QueryModelById(id)
  277. if err != nil {
  278. log.Error("no such model!", err.Error())
  279. ctx.ServerError("no such model:", err)
  280. return
  281. }
  282. if !isOper(ctx, task.UserId) {
  283. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  284. return
  285. }
  286. path := Model_prefix + models.AttachmentRelativePath(id) + "/"
  287. if task.Type == models.TypeCloudBrainTwo {
  288. downloadFromCloudBrainTwo(path, task, ctx, id)
  289. } else if task.Type == models.TypeCloudBrainOne {
  290. downloadFromCloudBrainOne(path, task, ctx, id)
  291. }
  292. }
  293. func MinioDownloadManyFile(path string, ctx *context.Context, returnFileName string, allFile []storage.FileInfo) {
  294. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+url.QueryEscape(returnFileName))
  295. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  296. w := zip.NewWriter(ctx.Resp)
  297. defer w.Close()
  298. for _, oneFile := range allFile {
  299. if oneFile.IsDir {
  300. log.Info("zip dir name:" + oneFile.FileName)
  301. } else {
  302. log.Info("zip file name:" + oneFile.FileName)
  303. fDest, err := w.Create(oneFile.FileName)
  304. if err != nil {
  305. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  306. ctx.ServerError("download file failed:", err)
  307. return
  308. }
  309. log.Info("minio file path=" + (path + oneFile.FileName))
  310. body, err := storage.Attachments.DownloadAFile(setting.Attachment.Minio.Bucket, path+oneFile.FileName)
  311. if err != nil {
  312. log.Info("download file failed: %s\n", err.Error())
  313. ctx.ServerError("download file failed:", err)
  314. return
  315. } else {
  316. defer body.Close()
  317. p := make([]byte, 1024)
  318. var readErr error
  319. var readCount int
  320. // 读取对象内容
  321. for {
  322. readCount, readErr = body.Read(p)
  323. if readCount > 0 {
  324. fDest.Write(p[:readCount])
  325. }
  326. if readErr != nil {
  327. break
  328. }
  329. }
  330. }
  331. }
  332. }
  333. }
  334. func downloadFromCloudBrainOne(path string, task *models.AiModelManage, ctx *context.Context, id string) {
  335. allFile, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, path)
  336. if err == nil {
  337. //count++
  338. models.ModifyModelDownloadCount(id)
  339. returnFileName := task.Name + "_" + task.Version + ".zip"
  340. MinioDownloadManyFile(path, ctx, returnFileName, allFile)
  341. } else {
  342. log.Info("error,msg=" + err.Error())
  343. ctx.ServerError("no file to download.", err)
  344. }
  345. }
  346. func ObsDownloadManyFile(path string, ctx *context.Context, returnFileName string, allFile []storage.FileInfo) {
  347. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+url.QueryEscape(returnFileName))
  348. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  349. w := zip.NewWriter(ctx.Resp)
  350. defer w.Close()
  351. for _, oneFile := range allFile {
  352. if oneFile.IsDir {
  353. log.Info("zip dir name:" + oneFile.FileName)
  354. } else {
  355. log.Info("zip file name:" + oneFile.FileName)
  356. fDest, err := w.Create(oneFile.FileName)
  357. if err != nil {
  358. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  359. ctx.ServerError("download file failed:", err)
  360. return
  361. }
  362. body, err := storage.ObsDownloadAFile(setting.Bucket, path+oneFile.FileName)
  363. if err != nil {
  364. log.Info("download file failed: %s\n", err.Error())
  365. ctx.ServerError("download file failed:", err)
  366. return
  367. } else {
  368. defer body.Close()
  369. p := make([]byte, 1024)
  370. var readErr error
  371. var readCount int
  372. // 读取对象内容
  373. for {
  374. readCount, readErr = body.Read(p)
  375. if readCount > 0 {
  376. fDest.Write(p[:readCount])
  377. }
  378. if readErr != nil {
  379. break
  380. }
  381. }
  382. }
  383. }
  384. }
  385. }
  386. func downloadFromCloudBrainTwo(path string, task *models.AiModelManage, ctx *context.Context, id string) {
  387. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  388. if err == nil {
  389. //count++
  390. models.ModifyModelDownloadCount(id)
  391. returnFileName := task.Name + "_" + task.Version + ".zip"
  392. ObsDownloadManyFile(path, ctx, returnFileName, allFile)
  393. } else {
  394. log.Info("error,msg=" + err.Error())
  395. ctx.ServerError("no file to download.", err)
  396. }
  397. }
  398. func QueryTrainJobVersionList(ctx *context.Context) {
  399. log.Info("query train job version list. start.")
  400. JobID := ctx.Query("JobID")
  401. VersionListTasks, count, err := models.QueryModelTrainJobVersionList(JobID)
  402. log.Info("query return count=" + fmt.Sprint(count))
  403. if err != nil {
  404. ctx.ServerError("QueryTrainJobList:", err)
  405. } else {
  406. ctx.JSON(200, VersionListTasks)
  407. }
  408. }
  409. func QueryTrainJobList(ctx *context.Context) {
  410. log.Info("query train job list. start.")
  411. repoId := ctx.QueryInt64("repoId")
  412. VersionListTasks, count, err := models.QueryModelTrainJobList(repoId)
  413. log.Info("query return count=" + fmt.Sprint(count))
  414. if err != nil {
  415. ctx.ServerError("QueryTrainJobList:", err)
  416. } else {
  417. ctx.JSON(200, VersionListTasks)
  418. }
  419. }
  420. func DownloadSingleModelFile(ctx *context.Context) {
  421. log.Info("DownloadSingleModelFile start.")
  422. id := ctx.Params(":ID")
  423. parentDir := ctx.Query("parentDir")
  424. fileName := ctx.Query("fileName")
  425. path := Model_prefix + models.AttachmentRelativePath(id) + "/" + parentDir + fileName
  426. task, err := models.QueryModelById(id)
  427. if err != nil {
  428. log.Error("no such model!", err.Error())
  429. ctx.ServerError("no such model:", err)
  430. return
  431. }
  432. if !isOper(ctx, task.UserId) {
  433. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  434. return
  435. }
  436. if task.Type == models.TypeCloudBrainTwo {
  437. if setting.PROXYURL != "" {
  438. body, err := storage.ObsDownloadAFile(setting.Bucket, path)
  439. if err != nil {
  440. log.Info("download error.")
  441. } else {
  442. //count++
  443. models.ModifyModelDownloadCount(id)
  444. defer body.Close()
  445. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  446. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  447. p := make([]byte, 1024)
  448. var readErr error
  449. var readCount int
  450. // 读取对象内容
  451. for {
  452. readCount, readErr = body.Read(p)
  453. if readCount > 0 {
  454. ctx.Resp.Write(p[:readCount])
  455. //fmt.Printf("%s", p[:readCount])
  456. }
  457. if readErr != nil {
  458. break
  459. }
  460. }
  461. }
  462. } else {
  463. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  464. if err != nil {
  465. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  466. ctx.ServerError("GetObsCreateSignedUrl", err)
  467. return
  468. }
  469. //count++
  470. models.ModifyModelDownloadCount(id)
  471. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  472. }
  473. } else if task.Type == models.TypeCloudBrainOne {
  474. log.Info("start to down load minio file.")
  475. url, err := storage.Attachments.PresignedGetURL(path, fileName)
  476. if err != nil {
  477. log.Error("Get minio get SignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  478. ctx.ServerError("Get minio get SignedUrl failed", err)
  479. return
  480. }
  481. models.ModifyModelDownloadCount(id)
  482. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  483. }
  484. }
  485. func ShowModelInfo(ctx *context.Context) {
  486. ctx.Data["ID"] = ctx.Query("ID")
  487. ctx.Data["name"] = ctx.Query("name")
  488. ctx.Data["isModelManage"] = true
  489. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  490. ctx.HTML(200, tplModelInfo)
  491. }
  492. func ShowSingleModel(ctx *context.Context) {
  493. name := ctx.Query("name")
  494. log.Info("Show single ModelInfo start.name=" + name)
  495. models := models.QueryModelByName(name, ctx.Repo.Repository.ID)
  496. userIds := make([]int64, len(models))
  497. for i, model := range models {
  498. model.IsCanOper = isOper(ctx, model.UserId)
  499. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  500. userIds[i] = model.UserId
  501. }
  502. userNameMap := queryUserName(userIds)
  503. for _, model := range models {
  504. value := userNameMap[model.UserId]
  505. if value != nil {
  506. model.UserName = value.Name
  507. model.UserRelAvatarLink = value.RelAvatarLink()
  508. }
  509. }
  510. ctx.JSON(http.StatusOK, models)
  511. }
  512. func queryUserName(intSlice []int64) map[int64]*models.User {
  513. keys := make(map[int64]string)
  514. uniqueElements := []int64{}
  515. for _, entry := range intSlice {
  516. if _, value := keys[entry]; !value {
  517. keys[entry] = ""
  518. uniqueElements = append(uniqueElements, entry)
  519. }
  520. }
  521. result := make(map[int64]*models.User)
  522. userLists, err := models.GetUsersByIDs(uniqueElements)
  523. if err == nil {
  524. for _, user := range userLists {
  525. result[user.ID] = user
  526. }
  527. }
  528. return result
  529. }
  530. func ShowOneVersionOtherModel(ctx *context.Context) {
  531. repoId := ctx.Repo.Repository.ID
  532. name := ctx.Query("name")
  533. aimodels := models.QueryModelByName(name, repoId)
  534. userIds := make([]int64, len(aimodels))
  535. for i, model := range aimodels {
  536. model.IsCanOper = isOper(ctx, model.UserId)
  537. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  538. userIds[i] = model.UserId
  539. }
  540. userNameMap := queryUserName(userIds)
  541. for _, model := range aimodels {
  542. value := userNameMap[model.UserId]
  543. if value != nil {
  544. model.UserName = value.Name
  545. model.UserRelAvatarLink = value.RelAvatarLink()
  546. }
  547. }
  548. if len(aimodels) > 0 {
  549. ctx.JSON(200, aimodels[1:])
  550. } else {
  551. ctx.JSON(200, aimodels)
  552. }
  553. }
  554. func SetModelCount(ctx *context.Context) {
  555. repoId := ctx.Repo.Repository.ID
  556. Type := -1
  557. _, count, _ := models.QueryModel(&models.AiModelQueryOptions{
  558. ListOptions: models.ListOptions{
  559. Page: 1,
  560. PageSize: 2,
  561. },
  562. RepoID: repoId,
  563. Type: Type,
  564. New: MODEL_LATEST,
  565. })
  566. ctx.Data["MODEL_COUNT"] = count
  567. }
  568. func ShowModelTemplate(ctx *context.Context) {
  569. ctx.Data["isModelManage"] = true
  570. repoId := ctx.Repo.Repository.ID
  571. SetModelCount(ctx)
  572. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  573. _, trainCount, _ := models.QueryModelTrainJobList(repoId)
  574. log.Info("query train count=" + fmt.Sprint(trainCount))
  575. ctx.Data["TRAIN_COUNT"] = trainCount
  576. ctx.HTML(200, tplModelManageIndex)
  577. }
  578. func isQueryRight(ctx *context.Context) bool {
  579. if ctx.Repo.Repository.IsPrivate {
  580. if ctx.Repo.CanRead(models.UnitTypeModelManage) || ctx.User.IsAdmin || ctx.Repo.IsAdmin() || ctx.Repo.IsOwner() {
  581. return true
  582. }
  583. return false
  584. } else {
  585. return true
  586. }
  587. }
  588. func isCanDelete(ctx *context.Context, modelUserId int64) bool {
  589. if ctx.User == nil {
  590. return false
  591. }
  592. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  593. return true
  594. }
  595. if ctx.Repo.IsOwner() {
  596. return true
  597. }
  598. return false
  599. }
  600. func isOper(ctx *context.Context, modelUserId int64) bool {
  601. if ctx.User == nil {
  602. return false
  603. }
  604. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  605. return true
  606. }
  607. return false
  608. }
  609. func ShowModelPageInfo(ctx *context.Context) {
  610. log.Info("ShowModelInfo start.")
  611. if !isQueryRight(ctx) {
  612. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  613. return
  614. }
  615. page := ctx.QueryInt("page")
  616. if page <= 0 {
  617. page = 1
  618. }
  619. pageSize := ctx.QueryInt("pageSize")
  620. if pageSize <= 0 {
  621. pageSize = setting.UI.IssuePagingNum
  622. }
  623. repoId := ctx.Repo.Repository.ID
  624. Type := -1
  625. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  626. ListOptions: models.ListOptions{
  627. Page: page,
  628. PageSize: pageSize,
  629. },
  630. RepoID: repoId,
  631. Type: Type,
  632. New: MODEL_LATEST,
  633. })
  634. if err != nil {
  635. ctx.ServerError("Cloudbrain", err)
  636. return
  637. }
  638. userIds := make([]int64, len(modelResult))
  639. for i, model := range modelResult {
  640. model.IsCanOper = isOper(ctx, model.UserId)
  641. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  642. userIds[i] = model.UserId
  643. }
  644. userNameMap := queryUserName(userIds)
  645. for _, model := range modelResult {
  646. value := userNameMap[model.UserId]
  647. if value != nil {
  648. model.UserName = value.Name
  649. model.UserRelAvatarLink = value.RelAvatarLink()
  650. }
  651. }
  652. mapInterface := make(map[string]interface{})
  653. mapInterface["data"] = modelResult
  654. mapInterface["count"] = count
  655. ctx.JSON(http.StatusOK, mapInterface)
  656. }
  657. func ModifyModel(id string, description string) error {
  658. err := models.ModifyModelDescription(id, description)
  659. if err == nil {
  660. log.Info("modify success.")
  661. } else {
  662. log.Info("Failed to modify.id=" + id + " desc=" + description + " error:" + err.Error())
  663. }
  664. return err
  665. }
  666. func ModifyModelInfo(ctx *context.Context) {
  667. log.Info("modify model start.")
  668. id := ctx.Query("ID")
  669. description := ctx.Query("Description")
  670. task, err := models.QueryModelById(id)
  671. if err != nil {
  672. log.Error("no such model!", err.Error())
  673. ctx.ServerError("no such model:", err)
  674. return
  675. }
  676. if !isOper(ctx, task.UserId) {
  677. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  678. //ctx.ServerError("no right.", errors.New(ctx.Tr("repo.model_noright")))
  679. return
  680. }
  681. err = ModifyModel(id, description)
  682. if err != nil {
  683. log.Info("modify error," + err.Error())
  684. ctx.ServerError("error.", err)
  685. } else {
  686. ctx.JSON(200, "success")
  687. }
  688. }
  689. func QueryModelListForPredict(ctx *context.Context) {
  690. repoId := ctx.Repo.Repository.ID
  691. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  692. ListOptions: models.ListOptions{
  693. Page: -1,
  694. PageSize: -1,
  695. },
  696. RepoID: repoId,
  697. Type: -1,
  698. New: -1,
  699. })
  700. if err != nil {
  701. ctx.ServerError("Cloudbrain", err)
  702. return
  703. }
  704. log.Info("query return count=" + fmt.Sprint(count))
  705. nameList := make([]string, 0)
  706. nameMap := make(map[string][]*models.AiModelManage)
  707. for _, model := range modelResult {
  708. if _, value := nameMap[model.Name]; !value {
  709. models := make([]*models.AiModelManage, 0)
  710. models = append(models, model)
  711. nameMap[model.Name] = models
  712. nameList = append(nameList, model.Name)
  713. } else {
  714. nameMap[model.Name] = append(nameMap[model.Name], model)
  715. }
  716. }
  717. mapInterface := make(map[string]interface{})
  718. mapInterface["nameList"] = nameList
  719. mapInterface["nameMap"] = nameMap
  720. ctx.JSON(http.StatusOK, mapInterface)
  721. }
  722. func QueryModelFileForPredict(ctx *context.Context) {
  723. id := ctx.Query("ID")
  724. model, err := models.QueryModelById(id)
  725. if err == nil {
  726. if model.Type == models.TypeCloudBrainTwo {
  727. prefix := model.Path[len(setting.Bucket)+1:]
  728. fileinfos, _ := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, prefix)
  729. ctx.JSON(http.StatusOK, fileinfos)
  730. } else if model.Type == models.TypeCloudBrainOne {
  731. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  732. fileinfos, _ := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, prefix)
  733. ctx.JSON(http.StatusOK, fileinfos)
  734. }
  735. } else {
  736. log.Error("no such model!", err.Error())
  737. ctx.ServerError("no such model:", err)
  738. return
  739. }
  740. }
  741. func QueryOneLevelModelFile(ctx *context.Context) {
  742. id := ctx.Query("ID")
  743. parentDir := ctx.Query("parentDir")
  744. model, err := models.QueryModelById(id)
  745. if err != nil {
  746. log.Error("no such model!", err.Error())
  747. ctx.ServerError("no such model:", err)
  748. return
  749. }
  750. if model.Type == models.TypeCloudBrainTwo {
  751. log.Info("TypeCloudBrainTwo list model file.")
  752. prefix := model.Path[len(setting.Bucket)+1:]
  753. fileinfos, _ := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, prefix, parentDir)
  754. ctx.JSON(http.StatusOK, fileinfos)
  755. } else if model.Type == models.TypeCloudBrainOne {
  756. log.Info("TypeCloudBrainOne list model file.")
  757. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  758. fileinfos, _ := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, parentDir)
  759. ctx.JSON(http.StatusOK, fileinfos)
  760. }
  761. }