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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  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, 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. value := userNameMap[model.UserId]
  584. if value != nil {
  585. model.UserName = value.Name
  586. model.UserRelAvatarLink = value.RelAvatarLink()
  587. }
  588. }
  589. ctx.JSON(http.StatusOK, models)
  590. }
  591. func queryUserName(intSlice []int64) map[int64]*models.User {
  592. keys := make(map[int64]string)
  593. uniqueElements := []int64{}
  594. for _, entry := range intSlice {
  595. if _, value := keys[entry]; !value {
  596. keys[entry] = ""
  597. uniqueElements = append(uniqueElements, entry)
  598. }
  599. }
  600. result := make(map[int64]*models.User)
  601. userLists, err := models.GetUsersByIDs(uniqueElements)
  602. if err == nil {
  603. for _, user := range userLists {
  604. result[user.ID] = user
  605. }
  606. }
  607. return result
  608. }
  609. func ShowOneVersionOtherModel(ctx *context.Context) {
  610. repoId := ctx.Repo.Repository.ID
  611. name := ctx.Query("name")
  612. aimodels := models.QueryModelByName(name, repoId)
  613. userIds := make([]int64, len(aimodels))
  614. for i, model := range aimodels {
  615. model.IsCanOper = isOper(ctx, model.UserId)
  616. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  617. userIds[i] = model.UserId
  618. }
  619. userNameMap := queryUserName(userIds)
  620. for _, model := range aimodels {
  621. value := userNameMap[model.UserId]
  622. if value != nil {
  623. model.UserName = value.Name
  624. model.UserRelAvatarLink = value.RelAvatarLink()
  625. }
  626. }
  627. if len(aimodels) > 0 {
  628. ctx.JSON(200, aimodels[1:])
  629. } else {
  630. ctx.JSON(200, aimodels)
  631. }
  632. }
  633. func SetModelCount(ctx *context.Context) {
  634. repoId := ctx.Repo.Repository.ID
  635. Type := -1
  636. _, count, _ := models.QueryModel(&models.AiModelQueryOptions{
  637. ListOptions: models.ListOptions{
  638. Page: 1,
  639. PageSize: 2,
  640. },
  641. RepoID: repoId,
  642. Type: Type,
  643. New: MODEL_LATEST,
  644. Status: -1,
  645. })
  646. ctx.Data["MODEL_COUNT"] = count
  647. }
  648. func ShowModelTemplate(ctx *context.Context) {
  649. ctx.Data["isModelManage"] = true
  650. repoId := ctx.Repo.Repository.ID
  651. SetModelCount(ctx)
  652. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  653. _, trainCount, _ := models.QueryModelTrainJobList(repoId)
  654. log.Info("query train count=" + fmt.Sprint(trainCount))
  655. ctx.Data["TRAIN_COUNT"] = trainCount
  656. ctx.HTML(200, tplModelManageIndex)
  657. }
  658. func isQueryRight(ctx *context.Context) bool {
  659. if ctx.Repo.Repository.IsPrivate {
  660. if ctx.Repo.CanRead(models.UnitTypeModelManage) || ctx.User.IsAdmin || ctx.Repo.IsAdmin() || ctx.Repo.IsOwner() {
  661. return true
  662. }
  663. return false
  664. } else {
  665. return true
  666. }
  667. }
  668. func isCanDelete(ctx *context.Context, modelUserId int64) bool {
  669. if ctx.User == nil {
  670. return false
  671. }
  672. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  673. return true
  674. }
  675. if ctx.Repo.IsOwner() {
  676. return true
  677. }
  678. return false
  679. }
  680. func isOper(ctx *context.Context, modelUserId int64) bool {
  681. if ctx.User == nil {
  682. return false
  683. }
  684. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  685. return true
  686. }
  687. return false
  688. }
  689. func ShowModelPageInfo(ctx *context.Context) {
  690. log.Info("ShowModelInfo start.")
  691. if !isQueryRight(ctx) {
  692. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  693. return
  694. }
  695. page := ctx.QueryInt("page")
  696. if page <= 0 {
  697. page = 1
  698. }
  699. pageSize := ctx.QueryInt("pageSize")
  700. if pageSize <= 0 {
  701. pageSize = setting.UI.IssuePagingNum
  702. }
  703. repoId := ctx.Repo.Repository.ID
  704. Type := -1
  705. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  706. ListOptions: models.ListOptions{
  707. Page: page,
  708. PageSize: pageSize,
  709. },
  710. RepoID: repoId,
  711. Type: Type,
  712. New: MODEL_LATEST,
  713. Status: -1,
  714. })
  715. if err != nil {
  716. ctx.ServerError("Cloudbrain", err)
  717. return
  718. }
  719. userIds := make([]int64, len(modelResult))
  720. for i, model := range modelResult {
  721. model.IsCanOper = isOper(ctx, model.UserId)
  722. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  723. userIds[i] = model.UserId
  724. }
  725. userNameMap := queryUserName(userIds)
  726. for _, model := range modelResult {
  727. value := userNameMap[model.UserId]
  728. if value != nil {
  729. model.UserName = value.Name
  730. model.UserRelAvatarLink = value.RelAvatarLink()
  731. }
  732. }
  733. mapInterface := make(map[string]interface{})
  734. mapInterface["data"] = modelResult
  735. mapInterface["count"] = count
  736. ctx.JSON(http.StatusOK, mapInterface)
  737. }
  738. func ModifyModel(id string, description string) error {
  739. err := models.ModifyModelDescription(id, description)
  740. if err == nil {
  741. log.Info("modify success.")
  742. } else {
  743. log.Info("Failed to modify.id=" + id + " desc=" + description + " error:" + err.Error())
  744. }
  745. return err
  746. }
  747. func ModifyModelInfo(ctx *context.Context) {
  748. log.Info("modify model start.")
  749. id := ctx.Query("ID")
  750. description := ctx.Query("Description")
  751. task, err := models.QueryModelById(id)
  752. if err != nil {
  753. log.Error("no such model!", err.Error())
  754. ctx.ServerError("no such model:", err)
  755. return
  756. }
  757. if !isOper(ctx, task.UserId) {
  758. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  759. //ctx.ServerError("no right.", errors.New(ctx.Tr("repo.model_noright")))
  760. return
  761. }
  762. err = ModifyModel(id, description)
  763. if err != nil {
  764. log.Info("modify error," + err.Error())
  765. ctx.ServerError("error.", err)
  766. } else {
  767. ctx.JSON(200, "success")
  768. }
  769. }
  770. func QueryModelListForPredict(ctx *context.Context) {
  771. repoId := ctx.Repo.Repository.ID
  772. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  773. ListOptions: models.ListOptions{
  774. Page: -1,
  775. PageSize: -1,
  776. },
  777. RepoID: repoId,
  778. Type: ctx.QueryInt("type"),
  779. New: -1,
  780. Status: 0,
  781. })
  782. if err != nil {
  783. ctx.ServerError("Cloudbrain", err)
  784. return
  785. }
  786. log.Info("query return count=" + fmt.Sprint(count))
  787. nameList := make([]string, 0)
  788. nameMap := make(map[string][]*models.AiModelManage)
  789. for _, model := range modelResult {
  790. if _, value := nameMap[model.Name]; !value {
  791. models := make([]*models.AiModelManage, 0)
  792. models = append(models, model)
  793. nameMap[model.Name] = models
  794. nameList = append(nameList, model.Name)
  795. } else {
  796. nameMap[model.Name] = append(nameMap[model.Name], model)
  797. }
  798. }
  799. mapInterface := make(map[string]interface{})
  800. mapInterface["nameList"] = nameList
  801. mapInterface["nameMap"] = nameMap
  802. ctx.JSON(http.StatusOK, mapInterface)
  803. }
  804. func QueryModelFileForPredict(ctx *context.Context) {
  805. id := ctx.Query("ID")
  806. model, err := models.QueryModelById(id)
  807. if err == nil {
  808. if model.Type == models.TypeCloudBrainTwo {
  809. prefix := model.Path[len(setting.Bucket)+1:]
  810. fileinfos, _ := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, prefix)
  811. ctx.JSON(http.StatusOK, fileinfos)
  812. } else if model.Type == models.TypeCloudBrainOne {
  813. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  814. fileinfos, _ := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, prefix)
  815. ctx.JSON(http.StatusOK, fileinfos)
  816. }
  817. } else {
  818. log.Error("no such model!", err.Error())
  819. ctx.ServerError("no such model:", err)
  820. return
  821. }
  822. }
  823. func QueryOneLevelModelFile(ctx *context.Context) {
  824. id := ctx.Query("ID")
  825. parentDir := ctx.Query("parentDir")
  826. model, err := models.QueryModelById(id)
  827. if err != nil {
  828. log.Error("no such model!", err.Error())
  829. ctx.ServerError("no such model:", err)
  830. return
  831. }
  832. if model.Type == models.TypeCloudBrainTwo {
  833. log.Info("TypeCloudBrainTwo list model file.")
  834. prefix := model.Path[len(setting.Bucket)+1:]
  835. fileinfos, _ := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, prefix, parentDir)
  836. if fileinfos == nil {
  837. fileinfos = make([]storage.FileInfo, 0)
  838. }
  839. ctx.JSON(http.StatusOK, fileinfos)
  840. } else if model.Type == models.TypeCloudBrainOne {
  841. log.Info("TypeCloudBrainOne list model file.")
  842. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  843. fileinfos, _ := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, parentDir)
  844. if fileinfos == nil {
  845. fileinfos = make([]storage.FileInfo, 0)
  846. }
  847. ctx.JSON(http.StatusOK, fileinfos)
  848. }
  849. }