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

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