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

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