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