You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ai_model_manage.go 28 kB

3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  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. for _, tmp := range VersionListTasks {
  460. tmp.ContainerIp = ""
  461. }
  462. ctx.JSON(200, VersionListTasks)
  463. }
  464. }
  465. func QueryTrainJobList(ctx *context.Context) {
  466. log.Info("query train job list. start.")
  467. repoId := ctx.QueryInt64("repoId")
  468. VersionListTasks, count, err := models.QueryModelTrainJobList(repoId)
  469. log.Info("query return count=" + fmt.Sprint(count))
  470. if err != nil {
  471. ctx.ServerError("QueryTrainJobList:", err)
  472. } else {
  473. ctx.JSON(200, VersionListTasks)
  474. }
  475. }
  476. func QueryTrainModelList(ctx *context.Context) {
  477. log.Info("query train job list. start.")
  478. jobName := ctx.Query("jobName")
  479. taskType := ctx.QueryInt("type")
  480. VersionName := ctx.Query("VersionName")
  481. if taskType == models.TypeCloudBrainTwo {
  482. objectkey := path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, VersionName) + "/"
  483. modelDbResult, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, objectkey)
  484. log.Info("bucket=" + setting.Bucket + " objectkey=" + objectkey)
  485. if err != nil {
  486. log.Info("get TypeCloudBrainTwo TrainJobListModel failed:", err)
  487. } else {
  488. ctx.JSON(200, modelDbResult)
  489. return
  490. }
  491. } else if taskType == models.TypeCloudBrainOne {
  492. modelSrcPrefix := setting.CBCodePathPrefix + jobName + "/model/"
  493. bucketName := setting.Attachment.Minio.Bucket
  494. modelDbResult, err := storage.GetAllObjectByBucketAndPrefixMinio(bucketName, modelSrcPrefix)
  495. if err != nil {
  496. log.Info("get TypeCloudBrainOne TrainJobListModel failed:", err)
  497. } else {
  498. ctx.JSON(200, modelDbResult)
  499. return
  500. }
  501. }
  502. ctx.JSON(200, "")
  503. }
  504. func DownloadSingleModelFile(ctx *context.Context) {
  505. log.Info("DownloadSingleModelFile start.")
  506. id := ctx.Params(":ID")
  507. parentDir := ctx.Query("parentDir")
  508. fileName := ctx.Query("fileName")
  509. path := Model_prefix + models.AttachmentRelativePath(id) + "/" + parentDir + fileName
  510. task, err := models.QueryModelById(id)
  511. if err != nil {
  512. log.Error("no such model!", err.Error())
  513. ctx.ServerError("no such model:", err)
  514. return
  515. }
  516. if !isOper(ctx, task.UserId) {
  517. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  518. return
  519. }
  520. if task.Type == models.TypeCloudBrainTwo {
  521. if setting.PROXYURL != "" {
  522. body, err := storage.ObsDownloadAFile(setting.Bucket, path)
  523. if err != nil {
  524. log.Info("download error.")
  525. } else {
  526. //count++
  527. models.ModifyModelDownloadCount(id)
  528. defer body.Close()
  529. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  530. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  531. p := make([]byte, 1024)
  532. var readErr error
  533. var readCount int
  534. // 读取对象内容
  535. for {
  536. readCount, readErr = body.Read(p)
  537. if readCount > 0 {
  538. ctx.Resp.Write(p[:readCount])
  539. //fmt.Printf("%s", p[:readCount])
  540. }
  541. if readErr != nil {
  542. break
  543. }
  544. }
  545. }
  546. } else {
  547. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  548. if err != nil {
  549. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  550. ctx.ServerError("GetObsCreateSignedUrl", err)
  551. return
  552. }
  553. //count++
  554. models.ModifyModelDownloadCount(id)
  555. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  556. }
  557. } else if task.Type == models.TypeCloudBrainOne {
  558. log.Info("start to down load minio file.")
  559. url, err := storage.Attachments.PresignedGetURL(path, fileName)
  560. if err != nil {
  561. log.Error("Get minio get SignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  562. ctx.ServerError("Get minio get SignedUrl failed", err)
  563. return
  564. }
  565. models.ModifyModelDownloadCount(id)
  566. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  567. }
  568. }
  569. func ShowModelInfo(ctx *context.Context) {
  570. ctx.Data["ID"] = ctx.Query("ID")
  571. ctx.Data["name"] = ctx.Query("name")
  572. ctx.Data["isModelManage"] = true
  573. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  574. ctx.HTML(200, tplModelInfo)
  575. }
  576. func ShowSingleModel(ctx *context.Context) {
  577. name := ctx.Query("name")
  578. log.Info("Show single ModelInfo start.name=" + name)
  579. models := models.QueryModelByName(name, ctx.Repo.Repository.ID)
  580. userIds := make([]int64, len(models))
  581. for i, model := range models {
  582. model.IsCanOper = isOper(ctx, model.UserId)
  583. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  584. userIds[i] = model.UserId
  585. }
  586. userNameMap := queryUserName(userIds)
  587. for _, model := range models {
  588. removeIpInfo(model)
  589. value := userNameMap[model.UserId]
  590. if value != nil {
  591. model.UserName = value.Name
  592. model.UserRelAvatarLink = value.RelAvatarLink()
  593. }
  594. }
  595. ctx.JSON(http.StatusOK, models)
  596. }
  597. func removeIpInfo(model *models.AiModelManage) {
  598. reg, _ := regexp.Compile(`[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}`)
  599. taskInfo := model.TrainTaskInfo
  600. taskInfo = reg.ReplaceAllString(taskInfo, "")
  601. model.TrainTaskInfo = taskInfo
  602. }
  603. func queryUserName(intSlice []int64) map[int64]*models.User {
  604. keys := make(map[int64]string)
  605. uniqueElements := []int64{}
  606. for _, entry := range intSlice {
  607. if _, value := keys[entry]; !value {
  608. keys[entry] = ""
  609. uniqueElements = append(uniqueElements, entry)
  610. }
  611. }
  612. result := make(map[int64]*models.User)
  613. userLists, err := models.GetUsersByIDs(uniqueElements)
  614. if err == nil {
  615. for _, user := range userLists {
  616. result[user.ID] = user
  617. }
  618. }
  619. return result
  620. }
  621. func ShowOneVersionOtherModel(ctx *context.Context) {
  622. repoId := ctx.Repo.Repository.ID
  623. name := ctx.Query("name")
  624. aimodels := models.QueryModelByName(name, repoId)
  625. userIds := make([]int64, len(aimodels))
  626. for i, model := range aimodels {
  627. model.IsCanOper = isOper(ctx, model.UserId)
  628. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  629. userIds[i] = model.UserId
  630. }
  631. userNameMap := queryUserName(userIds)
  632. for _, model := range aimodels {
  633. removeIpInfo(model)
  634. value := userNameMap[model.UserId]
  635. if value != nil {
  636. model.UserName = value.Name
  637. model.UserRelAvatarLink = value.RelAvatarLink()
  638. }
  639. }
  640. if len(aimodels) > 0 {
  641. ctx.JSON(200, aimodels[1:])
  642. } else {
  643. ctx.JSON(200, aimodels)
  644. }
  645. }
  646. func SetModelCount(ctx *context.Context) {
  647. repoId := ctx.Repo.Repository.ID
  648. Type := -1
  649. _, count, _ := models.QueryModel(&models.AiModelQueryOptions{
  650. ListOptions: models.ListOptions{
  651. Page: 1,
  652. PageSize: 2,
  653. },
  654. RepoID: repoId,
  655. Type: Type,
  656. New: MODEL_LATEST,
  657. Status: -1,
  658. })
  659. ctx.Data["MODEL_COUNT"] = count
  660. }
  661. func ShowModelTemplate(ctx *context.Context) {
  662. ctx.Data["isModelManage"] = true
  663. repoId := ctx.Repo.Repository.ID
  664. SetModelCount(ctx)
  665. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  666. _, trainCount, _ := models.QueryModelTrainJobList(repoId)
  667. log.Info("query train count=" + fmt.Sprint(trainCount))
  668. ctx.Data["TRAIN_COUNT"] = trainCount
  669. ctx.HTML(200, tplModelManageIndex)
  670. }
  671. func isQueryRight(ctx *context.Context) bool {
  672. if ctx.Repo.Repository.IsPrivate {
  673. if ctx.Repo.CanRead(models.UnitTypeModelManage) || ctx.User.IsAdmin || ctx.Repo.IsAdmin() || ctx.Repo.IsOwner() {
  674. return true
  675. }
  676. return false
  677. } else {
  678. return true
  679. }
  680. }
  681. func isCanDelete(ctx *context.Context, modelUserId int64) bool {
  682. if ctx.User == nil {
  683. return false
  684. }
  685. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  686. return true
  687. }
  688. if ctx.Repo.IsOwner() {
  689. return true
  690. }
  691. return false
  692. }
  693. func isOper(ctx *context.Context, modelUserId int64) bool {
  694. if ctx.User == nil {
  695. return false
  696. }
  697. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  698. return true
  699. }
  700. return false
  701. }
  702. func ShowModelPageInfo(ctx *context.Context) {
  703. log.Info("ShowModelInfo start.")
  704. if !isQueryRight(ctx) {
  705. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  706. return
  707. }
  708. page := ctx.QueryInt("page")
  709. if page <= 0 {
  710. page = 1
  711. }
  712. pageSize := ctx.QueryInt("pageSize")
  713. if pageSize <= 0 {
  714. pageSize = setting.UI.IssuePagingNum
  715. }
  716. repoId := ctx.Repo.Repository.ID
  717. Type := -1
  718. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  719. ListOptions: models.ListOptions{
  720. Page: page,
  721. PageSize: pageSize,
  722. },
  723. RepoID: repoId,
  724. Type: Type,
  725. New: MODEL_LATEST,
  726. Status: -1,
  727. })
  728. if err != nil {
  729. ctx.ServerError("Cloudbrain", err)
  730. return
  731. }
  732. userIds := make([]int64, len(modelResult))
  733. for i, model := range modelResult {
  734. model.IsCanOper = isOper(ctx, model.UserId)
  735. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  736. userIds[i] = model.UserId
  737. }
  738. userNameMap := queryUserName(userIds)
  739. for _, model := range modelResult {
  740. removeIpInfo(model)
  741. value := userNameMap[model.UserId]
  742. if value != nil {
  743. model.UserName = value.Name
  744. model.UserRelAvatarLink = value.RelAvatarLink()
  745. }
  746. }
  747. mapInterface := make(map[string]interface{})
  748. mapInterface["data"] = modelResult
  749. mapInterface["count"] = count
  750. ctx.JSON(http.StatusOK, mapInterface)
  751. }
  752. func ModifyModel(id string, description string) error {
  753. err := models.ModifyModelDescription(id, description)
  754. if err == nil {
  755. log.Info("modify success.")
  756. } else {
  757. log.Info("Failed to modify.id=" + id + " desc=" + description + " error:" + err.Error())
  758. }
  759. return err
  760. }
  761. func ModifyModelInfo(ctx *context.Context) {
  762. log.Info("modify model start.")
  763. id := ctx.Query("ID")
  764. description := ctx.Query("Description")
  765. task, err := models.QueryModelById(id)
  766. if err != nil {
  767. log.Error("no such model!", err.Error())
  768. ctx.ServerError("no such model:", err)
  769. return
  770. }
  771. if !isOper(ctx, task.UserId) {
  772. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  773. //ctx.ServerError("no right.", errors.New(ctx.Tr("repo.model_noright")))
  774. return
  775. }
  776. err = ModifyModel(id, description)
  777. if err != nil {
  778. log.Info("modify error," + err.Error())
  779. ctx.ServerError("error.", err)
  780. } else {
  781. ctx.JSON(200, "success")
  782. }
  783. }
  784. func QueryModelListForPredict(ctx *context.Context) {
  785. repoId := ctx.Repo.Repository.ID
  786. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  787. ListOptions: models.ListOptions{
  788. Page: -1,
  789. PageSize: -1,
  790. },
  791. RepoID: repoId,
  792. Type: ctx.QueryInt("type"),
  793. New: -1,
  794. Status: 0,
  795. })
  796. if err != nil {
  797. ctx.ServerError("Cloudbrain", err)
  798. return
  799. }
  800. log.Info("query return count=" + fmt.Sprint(count))
  801. nameList := make([]string, 0)
  802. nameMap := make(map[string][]*models.AiModelManage)
  803. for _, model := range modelResult {
  804. removeIpInfo(model)
  805. if _, value := nameMap[model.Name]; !value {
  806. models := make([]*models.AiModelManage, 0)
  807. models = append(models, model)
  808. nameMap[model.Name] = models
  809. nameList = append(nameList, model.Name)
  810. } else {
  811. nameMap[model.Name] = append(nameMap[model.Name], model)
  812. }
  813. }
  814. mapInterface := make(map[string]interface{})
  815. mapInterface["nameList"] = nameList
  816. mapInterface["nameMap"] = nameMap
  817. ctx.JSON(http.StatusOK, mapInterface)
  818. }
  819. func QueryModelFileForPredict(ctx *context.Context) {
  820. id := ctx.Query("ID")
  821. model, err := models.QueryModelById(id)
  822. if err == nil {
  823. if model.Type == models.TypeCloudBrainTwo {
  824. prefix := model.Path[len(setting.Bucket)+1:]
  825. fileinfos, _ := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, prefix)
  826. ctx.JSON(http.StatusOK, fileinfos)
  827. } else if model.Type == models.TypeCloudBrainOne {
  828. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  829. fileinfos, _ := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, prefix)
  830. ctx.JSON(http.StatusOK, fileinfos)
  831. }
  832. } else {
  833. log.Error("no such model!", err.Error())
  834. ctx.ServerError("no such model:", err)
  835. return
  836. }
  837. }
  838. func QueryOneLevelModelFile(ctx *context.Context) {
  839. id := ctx.Query("ID")
  840. parentDir := ctx.Query("parentDir")
  841. model, err := models.QueryModelById(id)
  842. if err != nil {
  843. log.Error("no such model!", err.Error())
  844. ctx.ServerError("no such model:", err)
  845. return
  846. }
  847. if model.Type == models.TypeCloudBrainTwo {
  848. log.Info("TypeCloudBrainTwo list model file.")
  849. prefix := model.Path[len(setting.Bucket)+1:]
  850. fileinfos, _ := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, prefix, parentDir)
  851. if fileinfos == nil {
  852. fileinfos = make([]storage.FileInfo, 0)
  853. }
  854. ctx.JSON(http.StatusOK, fileinfos)
  855. } else if model.Type == models.TypeCloudBrainOne {
  856. log.Info("TypeCloudBrainOne list model file.")
  857. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  858. fileinfos, _ := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, parentDir)
  859. if fileinfos == nil {
  860. fileinfos = make([]storage.FileInfo, 0)
  861. }
  862. ctx.JSON(http.StatusOK, fileinfos)
  863. }
  864. }