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

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