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