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 36 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
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206
  1. package repo
  2. import (
  3. "archive/zip"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "net/url"
  9. "path"
  10. "regexp"
  11. "strings"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/context"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/notification"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/modules/storage"
  18. "code.gitea.io/gitea/services/cloudbrain/resource"
  19. uuid "github.com/satori/go.uuid"
  20. )
  21. const (
  22. Attachment_model = "model"
  23. Model_prefix = "aimodels/"
  24. tplModelManageIndex = "repo/modelmanage/index"
  25. tplModelManageDownload = "repo/modelmanage/download"
  26. tplModelInfo = "repo/modelmanage/showinfo"
  27. tplCreateLocalModelInfo = "repo/modelmanage/create_local_1"
  28. tplCreateLocalForUploadModelInfo = "repo/modelmanage/create_local_2"
  29. tplCreateOnlineModelInfo = "repo/modelmanage/create_online"
  30. MODEL_LATEST = 1
  31. MODEL_NOT_LATEST = 0
  32. MODEL_MAX_SIZE = 1024 * 1024 * 1024
  33. STATUS_COPY_MODEL = 1
  34. STATUS_FINISHED = 0
  35. STATUS_ERROR = 2
  36. MODEL_LOCAL_TYPE = 1
  37. MODEL_ONLINE_TYPE = 0
  38. )
  39. func saveModelByParameters(jobId string, versionName string, name string, version string, label string, description string, engine int, ctx *context.Context) (string, error) {
  40. aiTask, err := models.GetCloudbrainByJobIDAndVersionName(jobId, versionName)
  41. if err != nil {
  42. aiTask, err = models.GetRepoCloudBrainByJobID(ctx.Repo.Repository.ID, jobId)
  43. if err != nil {
  44. log.Info("query task error." + err.Error())
  45. return "", err
  46. } else {
  47. log.Info("query gpu train task.")
  48. }
  49. }
  50. uuid := uuid.NewV4()
  51. id := uuid.String()
  52. modelPath := id
  53. var lastNewModelId string
  54. var modelSize int64
  55. log.Info("find task name:" + aiTask.JobName)
  56. aimodels := models.QueryModelByName(name, aiTask.RepoID)
  57. if len(aimodels) > 0 {
  58. for _, model := range aimodels {
  59. if model.Version == version {
  60. return "", errors.New(ctx.Tr("repo.model.manage.create_error"))
  61. }
  62. if model.New == MODEL_LATEST {
  63. lastNewModelId = model.ID
  64. }
  65. }
  66. }
  67. cloudType := aiTask.Type
  68. modelSelectedFile := ctx.Query("modelSelectedFile")
  69. //download model zip //train type
  70. if aiTask.ComputeResource == models.NPUResource {
  71. cloudType = models.TypeCloudBrainTwo
  72. } else if aiTask.ComputeResource == models.GPUResource {
  73. cloudType = models.TypeCloudBrainOne
  74. spec, err := resource.GetCloudbrainSpec(aiTask.ID)
  75. if err == nil {
  76. flaverName := "GPU: " + fmt.Sprint(spec.AccCardsNum) + "*" + spec.AccCardType + ",CPU: " + fmt.Sprint(spec.CpuCores) + "," + ctx.Tr("cloudbrain.memory") + ": " + fmt.Sprint(spec.MemGiB) + "GB," + ctx.Tr("cloudbrain.shared_memory") + ": " + fmt.Sprint(spec.ShareMemGiB) + "GB"
  77. aiTask.FlavorName = flaverName
  78. }
  79. }
  80. accuracy := make(map[string]string)
  81. accuracy["F1"] = ""
  82. accuracy["Recall"] = ""
  83. accuracy["Accuracy"] = ""
  84. accuracy["Precision"] = ""
  85. accuracyJson, _ := json.Marshal(accuracy)
  86. log.Info("accuracyJson=" + string(accuracyJson))
  87. aiTask.ContainerIp = ""
  88. aiTaskJson, _ := json.Marshal(aiTask)
  89. model := &models.AiModelManage{
  90. ID: id,
  91. Version: version,
  92. VersionCount: len(aimodels) + 1,
  93. Label: label,
  94. Name: name,
  95. Description: description,
  96. New: MODEL_LATEST,
  97. Type: cloudType,
  98. Path: modelPath,
  99. Size: modelSize,
  100. AttachmentId: aiTask.Uuid,
  101. RepoId: aiTask.RepoID,
  102. UserId: ctx.User.ID,
  103. CodeBranch: aiTask.BranchName,
  104. CodeCommitID: aiTask.CommitID,
  105. Engine: int64(engine),
  106. TrainTaskInfo: string(aiTaskJson),
  107. Accuracy: string(accuracyJson),
  108. Status: STATUS_COPY_MODEL,
  109. }
  110. err = models.SaveModelToDb(model)
  111. if err != nil {
  112. return "", err
  113. }
  114. if len(lastNewModelId) > 0 {
  115. //udpate status and version count
  116. models.ModifyModelNewProperty(lastNewModelId, MODEL_NOT_LATEST, 0)
  117. }
  118. var units []models.RepoUnit
  119. var deleteUnitTypes []models.UnitType
  120. units = append(units, models.RepoUnit{
  121. RepoID: ctx.Repo.Repository.ID,
  122. Type: models.UnitTypeModelManage,
  123. Config: &models.ModelManageConfig{
  124. EnableModelManage: true,
  125. },
  126. })
  127. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeModelManage)
  128. models.UpdateRepositoryUnits(ctx.Repo.Repository, units, deleteUnitTypes)
  129. go asyncToCopyModel(aiTask, id, modelSelectedFile)
  130. log.Info("save model end.")
  131. notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, id, name, models.ActionCreateNewModelTask)
  132. return id, nil
  133. }
  134. func asyncToCopyModel(aiTask *models.Cloudbrain, id string, modelSelectedFile string) {
  135. if aiTask.ComputeResource == models.NPUResource {
  136. modelPath, modelSize, err := downloadModelFromCloudBrainTwo(id, aiTask.JobName, "", aiTask.TrainUrl, modelSelectedFile)
  137. if err != nil {
  138. updateStatus(id, 0, STATUS_ERROR, modelPath, err.Error())
  139. log.Info("download model from CloudBrainTwo faild." + err.Error())
  140. } else {
  141. updateStatus(id, modelSize, STATUS_FINISHED, modelPath, "")
  142. }
  143. } else if aiTask.ComputeResource == models.GPUResource {
  144. modelPath, modelSize, err := downloadModelFromCloudBrainOne(id, aiTask.JobName, "", aiTask.TrainUrl, modelSelectedFile)
  145. if err != nil {
  146. updateStatus(id, 0, STATUS_ERROR, modelPath, err.Error())
  147. log.Info("download model from CloudBrainOne faild." + err.Error())
  148. } else {
  149. updateStatus(id, modelSize, STATUS_FINISHED, modelPath, "")
  150. }
  151. }
  152. }
  153. func updateStatus(id string, modelSize int64, status int, modelPath string, statusDesc string) {
  154. if len(statusDesc) > 400 {
  155. statusDesc = statusDesc[0:400]
  156. }
  157. err := models.ModifyModelStatus(id, modelSize, status, modelPath, statusDesc)
  158. if err != nil {
  159. log.Info("update status error." + err.Error())
  160. }
  161. }
  162. func SaveNewNameModel(ctx *context.Context) {
  163. if !ctx.Repo.CanWrite(models.UnitTypeModelManage) {
  164. ctx.Error(403, ctx.Tr("repo.model_noright"))
  165. return
  166. }
  167. name := ctx.Query("name")
  168. if name == "" {
  169. ctx.Error(500, fmt.Sprintf("name or version is null."))
  170. return
  171. }
  172. aimodels := models.QueryModelByName(name, ctx.Repo.Repository.ID)
  173. if len(aimodels) > 0 {
  174. ctx.Error(500, ctx.Tr("repo.model_rename"))
  175. return
  176. }
  177. SaveModel(ctx)
  178. ctx.Status(200)
  179. log.Info("save model end.")
  180. }
  181. func SaveLocalModel(ctx *context.Context) {
  182. if !ctx.Repo.CanWrite(models.UnitTypeModelManage) {
  183. ctx.Error(403, ctx.Tr("repo.model_noright"))
  184. return
  185. }
  186. re := map[string]string{
  187. "code": "-1",
  188. }
  189. log.Info("save SaveLocalModel start.")
  190. uuid := uuid.NewV4()
  191. id := uuid.String()
  192. name := ctx.Query("name")
  193. version := ctx.Query("version")
  194. if version == "" {
  195. version = "0.0.1"
  196. }
  197. label := ctx.Query("label")
  198. description := ctx.Query("description")
  199. engine := ctx.QueryInt("engine")
  200. taskType := ctx.QueryInt("type")
  201. modelActualPath := ""
  202. if taskType == models.TypeCloudBrainOne {
  203. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(id) + "/"
  204. modelActualPath = setting.Attachment.Minio.Bucket + "/" + destKeyNamePrefix
  205. } else if taskType == models.TypeCloudBrainTwo {
  206. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(id) + "/"
  207. modelActualPath = setting.Bucket + "/" + destKeyNamePrefix
  208. } else {
  209. re["msg"] = "type is error."
  210. ctx.JSON(200, re)
  211. return
  212. }
  213. var lastNewModelId string
  214. repoId := ctx.Repo.Repository.ID
  215. aimodels := models.QueryModelByName(name, repoId)
  216. if len(aimodels) > 0 {
  217. for _, model := range aimodels {
  218. if model.Version == version {
  219. re["msg"] = ctx.Tr("repo.model.manage.create_error")
  220. ctx.JSON(200, re)
  221. return
  222. }
  223. if model.New == MODEL_LATEST {
  224. lastNewModelId = model.ID
  225. }
  226. }
  227. }
  228. model := &models.AiModelManage{
  229. ID: id,
  230. Version: version,
  231. ModelType: 1,
  232. VersionCount: len(aimodels) + 1,
  233. Label: label,
  234. Name: name,
  235. Description: description,
  236. New: MODEL_LATEST,
  237. Type: taskType,
  238. Path: modelActualPath,
  239. Size: 0,
  240. AttachmentId: "",
  241. RepoId: repoId,
  242. UserId: ctx.User.ID,
  243. Engine: int64(engine),
  244. TrainTaskInfo: "",
  245. Accuracy: "",
  246. Status: STATUS_FINISHED,
  247. }
  248. err := models.SaveModelToDb(model)
  249. if err != nil {
  250. re["msg"] = err.Error()
  251. ctx.JSON(200, re)
  252. return
  253. }
  254. if len(lastNewModelId) > 0 {
  255. //udpate status and version count
  256. models.ModifyModelNewProperty(lastNewModelId, MODEL_NOT_LATEST, 0)
  257. }
  258. var units []models.RepoUnit
  259. var deleteUnitTypes []models.UnitType
  260. units = append(units, models.RepoUnit{
  261. RepoID: ctx.Repo.Repository.ID,
  262. Type: models.UnitTypeModelManage,
  263. Config: &models.ModelManageConfig{
  264. EnableModelManage: true,
  265. },
  266. })
  267. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeModelManage)
  268. models.UpdateRepositoryUnits(ctx.Repo.Repository, units, deleteUnitTypes)
  269. log.Info("save model end.")
  270. notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, id, name, models.ActionCreateNewModelTask)
  271. re["code"] = "0"
  272. re["id"] = id
  273. ctx.JSON(200, re)
  274. }
  275. func getSize(files []storage.FileInfo) int64 {
  276. var size int64
  277. for _, file := range files {
  278. size += file.Size
  279. }
  280. return size
  281. }
  282. func UpdateModelSize(modeluuid string) {
  283. model, err := models.QueryModelById(modeluuid)
  284. if err == nil {
  285. if model.Type == models.TypeCloudBrainOne {
  286. if strings.HasPrefix(model.Path, setting.Attachment.Minio.Bucket+"/"+Model_prefix) {
  287. files, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, model.Path[len(setting.Attachment.Minio.Bucket)+1:])
  288. if err != nil {
  289. log.Info("Failed to query model size from minio. id=" + modeluuid)
  290. }
  291. size := getSize(files)
  292. models.ModifyModelSize(modeluuid, size)
  293. }
  294. } else if model.Type == models.TypeCloudBrainTwo {
  295. if strings.HasPrefix(model.Path, setting.Bucket+"/"+Model_prefix) {
  296. files, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, model.Path[len(setting.Bucket)+1:])
  297. if err != nil {
  298. log.Info("Failed to query model size from obs. id=" + modeluuid)
  299. }
  300. size := getSize(files)
  301. models.ModifyModelSize(modeluuid, size)
  302. }
  303. }
  304. } else {
  305. log.Info("not found model,uuid=" + modeluuid)
  306. }
  307. }
  308. func SaveModel(ctx *context.Context) {
  309. if !ctx.Repo.CanWrite(models.UnitTypeModelManage) {
  310. ctx.Error(403, ctx.Tr("repo.model_noright"))
  311. return
  312. }
  313. log.Info("save model start.")
  314. JobId := ctx.Query("jobId")
  315. VersionName := ctx.Query("versionName")
  316. name := ctx.Query("name")
  317. version := ctx.Query("version")
  318. label := ctx.Query("label")
  319. description := ctx.Query("description")
  320. engine := ctx.QueryInt("engine")
  321. modelSelectedFile := ctx.Query("modelSelectedFile")
  322. log.Info("engine=" + fmt.Sprint(engine) + " modelSelectedFile=" + modelSelectedFile)
  323. re := map[string]string{
  324. "code": "-1",
  325. }
  326. if JobId == "" || VersionName == "" {
  327. re["msg"] = "JobId or VersionName is null."
  328. ctx.JSON(200, re)
  329. return
  330. }
  331. if modelSelectedFile == "" {
  332. re["msg"] = "Not selected model file."
  333. ctx.JSON(200, re)
  334. return
  335. }
  336. if name == "" || version == "" {
  337. re["msg"] = "name or version is null."
  338. ctx.JSON(200, re)
  339. return
  340. }
  341. id, err := saveModelByParameters(JobId, VersionName, name, version, label, description, engine, ctx)
  342. if err != nil {
  343. log.Info("save model error." + err.Error())
  344. re["msg"] = err.Error()
  345. } else {
  346. re["code"] = "0"
  347. re["id"] = id
  348. }
  349. ctx.JSON(200, re)
  350. log.Info("save model end.")
  351. }
  352. func downloadModelFromCloudBrainTwo(modelUUID string, jobName string, parentDir string, trainUrl string, modelSelectedFile string) (string, int64, error) {
  353. objectkey := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir), "/")
  354. if trainUrl != "" {
  355. objectkey = strings.Trim(trainUrl[len(setting.Bucket)+1:], "/")
  356. }
  357. prefix := objectkey + "/"
  358. filterFiles := strings.Split(modelSelectedFile, ";")
  359. Files := make([]string, 0)
  360. for _, shortFile := range filterFiles {
  361. Files = append(Files, prefix+shortFile)
  362. }
  363. totalSize := storage.ObsGetFilesSize(setting.Bucket, Files)
  364. if float64(totalSize) > setting.MaxModelSize*MODEL_MAX_SIZE {
  365. return "", 0, errors.New("Cannot create model, as model is exceed " + fmt.Sprint(setting.MaxModelSize) + "G.")
  366. }
  367. modelDbResult, err := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, objectkey, "")
  368. log.Info("bucket=" + setting.Bucket + " objectkey=" + objectkey)
  369. if err != nil {
  370. log.Info("get TrainJobListModel failed:", err)
  371. return "", 0, err
  372. }
  373. if len(modelDbResult) == 0 {
  374. return "", 0, errors.New("Cannot create model, as model is empty.")
  375. }
  376. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(modelUUID) + "/"
  377. size, err := storage.ObsCopyManyFile(setting.Bucket, prefix, setting.Bucket, destKeyNamePrefix, filterFiles)
  378. dataActualPath := setting.Bucket + "/" + destKeyNamePrefix
  379. return dataActualPath, size, nil
  380. }
  381. func downloadModelFromCloudBrainOne(modelUUID string, jobName string, parentDir string, trainUrl string, modelSelectedFile string) (string, int64, error) {
  382. modelActualPath := storage.GetMinioPath(jobName, "/model/")
  383. log.Info("modelActualPath=" + modelActualPath)
  384. modelSrcPrefix := setting.CBCodePathPrefix + jobName + "/model/"
  385. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(modelUUID) + "/"
  386. bucketName := setting.Attachment.Minio.Bucket
  387. log.Info("destKeyNamePrefix=" + destKeyNamePrefix + " modelSrcPrefix=" + modelSrcPrefix + " bucket=" + bucketName)
  388. filterFiles := strings.Split(modelSelectedFile, ";")
  389. Files := make([]string, 0)
  390. for _, shortFile := range filterFiles {
  391. Files = append(Files, modelSrcPrefix+shortFile)
  392. }
  393. totalSize := storage.MinioGetFilesSize(bucketName, Files)
  394. if float64(totalSize) > setting.MaxModelSize*MODEL_MAX_SIZE {
  395. return "", 0, errors.New("Cannot create model, as model is exceed " + fmt.Sprint(setting.MaxModelSize) + "G.")
  396. }
  397. size, err := storage.MinioCopyFiles(bucketName, modelSrcPrefix, destKeyNamePrefix, filterFiles)
  398. if err == nil {
  399. dataActualPath := bucketName + "/" + destKeyNamePrefix
  400. return dataActualPath, size, nil
  401. } else {
  402. return "", 0, nil
  403. }
  404. }
  405. func DeleteModel(ctx *context.Context) {
  406. log.Info("delete model start.")
  407. id := ctx.Query("id")
  408. err := deleteModelByID(ctx, id)
  409. if err != nil {
  410. re := map[string]string{
  411. "code": "-1",
  412. }
  413. re["msg"] = err.Error()
  414. ctx.JSON(200, re)
  415. } else {
  416. ctx.JSON(200, map[string]string{
  417. "code": "0",
  418. })
  419. }
  420. }
  421. func deleteModelByID(ctx *context.Context, id string) error {
  422. log.Info("delete model start. id=" + id)
  423. model, err := models.QueryModelById(id)
  424. if !isCanDelete(ctx, model.UserId) {
  425. return errors.New(ctx.Tr("repo.model_noright"))
  426. }
  427. if err == nil {
  428. log.Info("bucket=" + setting.Bucket + " path=" + model.Path)
  429. if model.Type == models.TypeCloudBrainOne {
  430. if strings.HasPrefix(model.Path, setting.Bucket+"/"+Model_prefix) {
  431. err := storage.Attachments.DeleteDir(model.Path[len(setting.Bucket)+1:])
  432. if err != nil {
  433. log.Info("Failed to delete model. id=" + id)
  434. return err
  435. }
  436. }
  437. } else if model.Type == models.TypeCloudBrainTwo {
  438. if strings.HasPrefix(model.Path, setting.Bucket+"/"+Model_prefix) {
  439. err := storage.ObsRemoveObject(setting.Bucket, model.Path[len(setting.Bucket)+1:])
  440. if err != nil {
  441. log.Info("Failed to delete model. id=" + id)
  442. return err
  443. }
  444. }
  445. }
  446. err = models.DeleteModelById(id)
  447. if err == nil { //find a model to change new
  448. aimodels := models.QueryModelByName(model.Name, model.RepoId)
  449. if model.New == MODEL_LATEST {
  450. if len(aimodels) > 0 {
  451. //udpate status and version count
  452. models.ModifyModelNewProperty(aimodels[0].ID, MODEL_LATEST, len(aimodels))
  453. }
  454. } else {
  455. for _, tmpModel := range aimodels {
  456. if tmpModel.New == MODEL_LATEST {
  457. models.ModifyModelNewProperty(tmpModel.ID, MODEL_LATEST, len(aimodels))
  458. break
  459. }
  460. }
  461. }
  462. }
  463. }
  464. return err
  465. }
  466. func QueryModelByParameters(repoId int64, page int) ([]*models.AiModelManage, int64, error) {
  467. return models.QueryModel(&models.AiModelQueryOptions{
  468. ListOptions: models.ListOptions{
  469. Page: page,
  470. PageSize: setting.UI.IssuePagingNum,
  471. },
  472. RepoID: repoId,
  473. Type: -1,
  474. New: MODEL_LATEST,
  475. Status: -1,
  476. })
  477. }
  478. func DownloadMultiModelFile(ctx *context.Context) {
  479. log.Info("DownloadMultiModelFile start.")
  480. id := ctx.Query("id")
  481. log.Info("id=" + id)
  482. task, err := models.QueryModelById(id)
  483. if err != nil {
  484. log.Error("no such model!", err.Error())
  485. ctx.ServerError("no such model:", err)
  486. return
  487. }
  488. if !isOper(ctx, task.UserId) {
  489. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  490. return
  491. }
  492. path := Model_prefix + models.AttachmentRelativePath(id) + "/"
  493. if task.Type == models.TypeCloudBrainTwo {
  494. downloadFromCloudBrainTwo(path, task, ctx, id)
  495. } else if task.Type == models.TypeCloudBrainOne {
  496. downloadFromCloudBrainOne(path, task, ctx, id)
  497. }
  498. }
  499. func MinioDownloadManyFile(path string, ctx *context.Context, returnFileName string, allFile []storage.FileInfo) {
  500. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+url.QueryEscape(returnFileName))
  501. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  502. w := zip.NewWriter(ctx.Resp)
  503. defer w.Close()
  504. for _, oneFile := range allFile {
  505. if oneFile.IsDir {
  506. log.Info("zip dir name:" + oneFile.FileName)
  507. } else {
  508. log.Info("zip file name:" + oneFile.FileName)
  509. fDest, err := w.Create(oneFile.FileName)
  510. if err != nil {
  511. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  512. ctx.ServerError("download file failed:", err)
  513. return
  514. }
  515. log.Info("minio file path=" + (path + oneFile.FileName))
  516. body, err := storage.Attachments.DownloadAFile(setting.Attachment.Minio.Bucket, path+oneFile.FileName)
  517. if err != nil {
  518. log.Info("download file failed: %s\n", err.Error())
  519. ctx.ServerError("download file failed:", err)
  520. return
  521. } else {
  522. defer body.Close()
  523. p := make([]byte, 1024)
  524. var readErr error
  525. var readCount int
  526. // 读取对象内容
  527. for {
  528. readCount, readErr = body.Read(p)
  529. if readCount > 0 {
  530. fDest.Write(p[:readCount])
  531. }
  532. if readErr != nil {
  533. break
  534. }
  535. }
  536. }
  537. }
  538. }
  539. }
  540. func downloadFromCloudBrainOne(path string, task *models.AiModelManage, ctx *context.Context, id string) {
  541. allFile, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, path)
  542. if err == nil {
  543. //count++
  544. models.ModifyModelDownloadCount(id)
  545. returnFileName := task.Name + "_" + task.Version + ".zip"
  546. MinioDownloadManyFile(path, ctx, returnFileName, allFile)
  547. } else {
  548. log.Info("error,msg=" + err.Error())
  549. ctx.ServerError("no file to download.", err)
  550. }
  551. }
  552. func ObsDownloadManyFile(path string, ctx *context.Context, returnFileName string, allFile []storage.FileInfo) {
  553. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+url.QueryEscape(returnFileName))
  554. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  555. w := zip.NewWriter(ctx.Resp)
  556. defer w.Close()
  557. for _, oneFile := range allFile {
  558. if oneFile.IsDir {
  559. log.Info("zip dir name:" + oneFile.FileName)
  560. } else {
  561. log.Info("zip file name:" + oneFile.FileName)
  562. fDest, err := w.Create(oneFile.FileName)
  563. if err != nil {
  564. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  565. ctx.ServerError("download file failed:", err)
  566. return
  567. }
  568. body, err := storage.ObsDownloadAFile(setting.Bucket, path+oneFile.FileName)
  569. if err != nil {
  570. log.Info("download file failed: %s\n", err.Error())
  571. ctx.ServerError("download file failed:", err)
  572. return
  573. } else {
  574. defer body.Close()
  575. p := make([]byte, 1024)
  576. var readErr error
  577. var readCount int
  578. // 读取对象内容
  579. for {
  580. readCount, readErr = body.Read(p)
  581. if readCount > 0 {
  582. fDest.Write(p[:readCount])
  583. }
  584. if readErr != nil {
  585. break
  586. }
  587. }
  588. }
  589. }
  590. }
  591. }
  592. func downloadFromCloudBrainTwo(path string, task *models.AiModelManage, ctx *context.Context, id string) {
  593. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  594. if err == nil {
  595. //count++
  596. models.ModifyModelDownloadCount(id)
  597. returnFileName := task.Name + "_" + task.Version + ".zip"
  598. ObsDownloadManyFile(path, ctx, returnFileName, allFile)
  599. } else {
  600. log.Info("error,msg=" + err.Error())
  601. ctx.ServerError("no file to download.", err)
  602. }
  603. }
  604. func QueryTrainJobVersionList(ctx *context.Context) {
  605. log.Info("query train job version list. start.")
  606. JobID := ctx.Query("jobId")
  607. if JobID == "" {
  608. JobID = ctx.Query("JobId")
  609. }
  610. VersionListTasks, count, err := models.QueryModelTrainJobVersionList(JobID)
  611. log.Info("query return count=" + fmt.Sprint(count))
  612. if err != nil {
  613. ctx.ServerError("QueryTrainJobList:", err)
  614. } else {
  615. ctx.JSON(200, VersionListTasks)
  616. }
  617. }
  618. func QueryTrainJobList(ctx *context.Context) {
  619. log.Info("query train job list. start.")
  620. repoId := ctx.QueryInt64("repoId")
  621. VersionListTasks, count, err := models.QueryModelTrainJobList(repoId)
  622. log.Info("query return count=" + fmt.Sprint(count))
  623. if err != nil {
  624. ctx.ServerError("QueryTrainJobList:", err)
  625. } else {
  626. ctx.JSON(200, VersionListTasks)
  627. }
  628. }
  629. func QueryTrainModelFileById(ctx *context.Context) ([]storage.FileInfo, error) {
  630. JobID := ctx.Query("jobId")
  631. VersionListTasks, count, err := models.QueryModelTrainJobVersionList(JobID)
  632. if err == nil {
  633. if count == 1 {
  634. task := VersionListTasks[0]
  635. jobName := task.JobName
  636. taskType := task.Type
  637. VersionName := task.VersionName
  638. modelDbResult, err := getModelFromObjectSave(jobName, taskType, VersionName)
  639. return modelDbResult, err
  640. }
  641. }
  642. log.Info("get TypeCloudBrainTwo TrainJobListModel failed:", err)
  643. return nil, errors.New("Not found task.")
  644. }
  645. func getModelFromObjectSave(jobName string, taskType int, VersionName string) ([]storage.FileInfo, error) {
  646. if taskType == models.TypeCloudBrainTwo {
  647. objectkey := path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, VersionName) + "/"
  648. modelDbResult, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, objectkey)
  649. log.Info("bucket=" + setting.Bucket + " objectkey=" + objectkey)
  650. if err != nil {
  651. log.Info("get TypeCloudBrainTwo TrainJobListModel failed:", err)
  652. return nil, err
  653. } else {
  654. return modelDbResult, nil
  655. }
  656. } else if taskType == models.TypeCloudBrainOne {
  657. modelSrcPrefix := setting.CBCodePathPrefix + jobName + "/model/"
  658. bucketName := setting.Attachment.Minio.Bucket
  659. modelDbResult, err := storage.GetAllObjectByBucketAndPrefixMinio(bucketName, modelSrcPrefix)
  660. if err != nil {
  661. log.Info("get TypeCloudBrainOne TrainJobListModel failed:", err)
  662. return nil, err
  663. } else {
  664. return modelDbResult, nil
  665. }
  666. }
  667. return nil, errors.New("Not support.")
  668. }
  669. func QueryTrainModelList(ctx *context.Context) {
  670. log.Info("query train job list. start.")
  671. jobName := ctx.Query("jobName")
  672. taskType := ctx.QueryInt("type")
  673. VersionName := ctx.Query("versionName")
  674. if VersionName == "" {
  675. VersionName = ctx.Query("VersionName")
  676. }
  677. modelDbResult, err := getModelFromObjectSave(jobName, taskType, VersionName)
  678. if err != nil {
  679. log.Info("get TypeCloudBrainTwo TrainJobListModel failed:", err)
  680. ctx.JSON(200, "")
  681. } else {
  682. ctx.JSON(200, modelDbResult)
  683. return
  684. }
  685. }
  686. func DownloadSingleModelFile(ctx *context.Context) {
  687. log.Info("DownloadSingleModelFile start.")
  688. id := ctx.Params(":ID")
  689. parentDir := ctx.Query("parentDir")
  690. fileName := ctx.Query("fileName")
  691. path := Model_prefix + models.AttachmentRelativePath(id) + "/" + parentDir + fileName
  692. task, err := models.QueryModelById(id)
  693. if err != nil {
  694. log.Error("no such model!", err.Error())
  695. ctx.ServerError("no such model:", err)
  696. return
  697. }
  698. if !isOper(ctx, task.UserId) {
  699. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  700. return
  701. }
  702. if task.Type == models.TypeCloudBrainTwo {
  703. if setting.PROXYURL != "" {
  704. body, err := storage.ObsDownloadAFile(setting.Bucket, path)
  705. if err != nil {
  706. log.Info("download error.")
  707. } else {
  708. //count++
  709. models.ModifyModelDownloadCount(id)
  710. defer body.Close()
  711. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  712. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  713. p := make([]byte, 1024)
  714. var readErr error
  715. var readCount int
  716. // 读取对象内容
  717. for {
  718. readCount, readErr = body.Read(p)
  719. if readCount > 0 {
  720. ctx.Resp.Write(p[:readCount])
  721. //fmt.Printf("%s", p[:readCount])
  722. }
  723. if readErr != nil {
  724. break
  725. }
  726. }
  727. }
  728. } else {
  729. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  730. if err != nil {
  731. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  732. ctx.ServerError("GetObsCreateSignedUrl", err)
  733. return
  734. }
  735. //count++
  736. models.ModifyModelDownloadCount(id)
  737. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  738. }
  739. } else if task.Type == models.TypeCloudBrainOne {
  740. log.Info("start to down load minio file.")
  741. url, err := storage.Attachments.PresignedGetURL(path, fileName)
  742. if err != nil {
  743. log.Error("Get minio get SignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  744. ctx.ServerError("Get minio get SignedUrl failed", err)
  745. return
  746. }
  747. models.ModifyModelDownloadCount(id)
  748. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  749. }
  750. }
  751. func ShowModelInfo(ctx *context.Context) {
  752. ctx.Data["ID"] = ctx.Query("id")
  753. ctx.Data["name"] = ctx.Query("name")
  754. ctx.Data["isModelManage"] = true
  755. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  756. ctx.HTML(200, tplModelInfo)
  757. }
  758. func QueryModelById(ctx *context.Context) {
  759. id := ctx.Query("id")
  760. model, err := models.QueryModelById(id)
  761. if err == nil {
  762. model.IsCanOper = isOper(ctx, model.UserId)
  763. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  764. removeIpInfo(model)
  765. ctx.JSON(http.StatusOK, model)
  766. } else {
  767. ctx.JSON(http.StatusNotFound, nil)
  768. }
  769. }
  770. func ShowSingleModel(ctx *context.Context) {
  771. name := ctx.Query("name")
  772. log.Info("Show single ModelInfo start.name=" + name)
  773. models := models.QueryModelByName(name, ctx.Repo.Repository.ID)
  774. userIds := make([]int64, len(models))
  775. for i, model := range models {
  776. model.IsCanOper = isOper(ctx, model.UserId)
  777. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  778. userIds[i] = model.UserId
  779. }
  780. userNameMap := queryUserName(userIds)
  781. for _, model := range models {
  782. removeIpInfo(model)
  783. value := userNameMap[model.UserId]
  784. if value != nil {
  785. model.UserName = value.Name
  786. model.UserRelAvatarLink = value.RelAvatarLink()
  787. }
  788. }
  789. ctx.JSON(http.StatusOK, models)
  790. }
  791. func removeIpInfo(model *models.AiModelManage) {
  792. reg, _ := regexp.Compile(`[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}`)
  793. taskInfo := model.TrainTaskInfo
  794. taskInfo = reg.ReplaceAllString(taskInfo, "")
  795. model.TrainTaskInfo = taskInfo
  796. }
  797. func queryUserName(intSlice []int64) map[int64]*models.User {
  798. keys := make(map[int64]string)
  799. uniqueElements := []int64{}
  800. for _, entry := range intSlice {
  801. if _, value := keys[entry]; !value {
  802. keys[entry] = ""
  803. uniqueElements = append(uniqueElements, entry)
  804. }
  805. }
  806. result := make(map[int64]*models.User)
  807. userLists, err := models.GetUsersByIDs(uniqueElements)
  808. if err == nil {
  809. for _, user := range userLists {
  810. result[user.ID] = user
  811. }
  812. }
  813. return result
  814. }
  815. func ShowOneVersionOtherModel(ctx *context.Context) {
  816. repoId := ctx.Repo.Repository.ID
  817. name := ctx.Query("name")
  818. aimodels := models.QueryModelByName(name, repoId)
  819. userIds := make([]int64, len(aimodels))
  820. for i, model := range aimodels {
  821. model.IsCanOper = isOper(ctx, model.UserId)
  822. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  823. userIds[i] = model.UserId
  824. }
  825. userNameMap := queryUserName(userIds)
  826. for _, model := range aimodels {
  827. removeIpInfo(model)
  828. value := userNameMap[model.UserId]
  829. if value != nil {
  830. model.UserName = value.Name
  831. model.UserRelAvatarLink = value.RelAvatarLink()
  832. }
  833. }
  834. if len(aimodels) > 0 {
  835. ctx.JSON(200, aimodels[1:])
  836. } else {
  837. ctx.JSON(200, aimodels)
  838. }
  839. }
  840. func SetModelCount(ctx *context.Context) {
  841. repoId := ctx.Repo.Repository.ID
  842. Type := -1
  843. _, count, _ := models.QueryModel(&models.AiModelQueryOptions{
  844. ListOptions: models.ListOptions{
  845. Page: 1,
  846. PageSize: 2,
  847. },
  848. RepoID: repoId,
  849. Type: Type,
  850. New: MODEL_LATEST,
  851. Status: -1,
  852. })
  853. ctx.Data["MODEL_COUNT"] = count
  854. }
  855. func ShowModelTemplate(ctx *context.Context) {
  856. ctx.Data["isModelManage"] = true
  857. repoId := ctx.Repo.Repository.ID
  858. SetModelCount(ctx)
  859. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  860. _, trainCount, _ := models.QueryModelTrainJobList(repoId)
  861. log.Info("query train count=" + fmt.Sprint(trainCount))
  862. ctx.Data["TRAIN_COUNT"] = trainCount
  863. ctx.HTML(200, tplModelManageIndex)
  864. }
  865. func isQueryRight(ctx *context.Context) bool {
  866. if ctx.Repo.Repository.IsPrivate {
  867. if ctx.Repo.CanRead(models.UnitTypeModelManage) || ctx.User.IsAdmin || ctx.Repo.IsAdmin() || ctx.Repo.IsOwner() {
  868. return true
  869. }
  870. return false
  871. } else {
  872. return true
  873. }
  874. }
  875. func isCanDelete(ctx *context.Context, modelUserId int64) bool {
  876. if ctx.User == nil {
  877. return false
  878. }
  879. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  880. return true
  881. }
  882. if ctx.Repo.IsOwner() {
  883. return true
  884. }
  885. return false
  886. }
  887. func isOper(ctx *context.Context, modelUserId int64) bool {
  888. if ctx.User == nil {
  889. return false
  890. }
  891. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  892. return true
  893. }
  894. return false
  895. }
  896. func ShowModelPageInfo(ctx *context.Context) {
  897. log.Info("ShowModelInfo start.")
  898. if !isQueryRight(ctx) {
  899. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  900. return
  901. }
  902. page := ctx.QueryInt("page")
  903. if page <= 0 {
  904. page = 1
  905. }
  906. pageSize := ctx.QueryInt("pageSize")
  907. if pageSize <= 0 {
  908. pageSize = setting.UI.IssuePagingNum
  909. }
  910. repoId := ctx.Repo.Repository.ID
  911. Type := -1
  912. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  913. ListOptions: models.ListOptions{
  914. Page: page,
  915. PageSize: pageSize,
  916. },
  917. RepoID: repoId,
  918. Type: Type,
  919. New: MODEL_LATEST,
  920. Status: -1,
  921. })
  922. if err != nil {
  923. ctx.ServerError("Cloudbrain", err)
  924. return
  925. }
  926. userIds := make([]int64, len(modelResult))
  927. for i, model := range modelResult {
  928. model.IsCanOper = isOper(ctx, model.UserId)
  929. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  930. userIds[i] = model.UserId
  931. }
  932. userNameMap := queryUserName(userIds)
  933. for _, model := range modelResult {
  934. removeIpInfo(model)
  935. value := userNameMap[model.UserId]
  936. if value != nil {
  937. model.UserName = value.Name
  938. model.UserRelAvatarLink = value.RelAvatarLink()
  939. }
  940. }
  941. mapInterface := make(map[string]interface{})
  942. mapInterface["data"] = modelResult
  943. mapInterface["count"] = count
  944. ctx.JSON(http.StatusOK, mapInterface)
  945. }
  946. func ModifyModel(id string, description string) error {
  947. err := models.ModifyModelDescription(id, description)
  948. if err == nil {
  949. log.Info("modify success.")
  950. } else {
  951. log.Info("Failed to modify.id=" + id + " desc=" + description + " error:" + err.Error())
  952. }
  953. return err
  954. }
  955. func ModifyModelInfo(ctx *context.Context) {
  956. log.Info("modify model start.")
  957. id := ctx.Query("id")
  958. description := ctx.Query("description")
  959. re := map[string]string{
  960. "code": "-1",
  961. }
  962. task, err := models.QueryModelById(id)
  963. if err != nil {
  964. re["msg"] = err.Error()
  965. log.Error("no such model!", err.Error())
  966. ctx.JSON(200, re)
  967. return
  968. }
  969. if !isOper(ctx, task.UserId) {
  970. re["msg"] = "No right to operation."
  971. ctx.JSON(200, re)
  972. return
  973. }
  974. if task.ModelType == MODEL_LOCAL_TYPE {
  975. name := ctx.Query("name")
  976. label := ctx.Query("label")
  977. description := ctx.Query("description")
  978. engine := ctx.QueryInt("engine")
  979. aimodels := models.QueryModelByName(name, task.RepoId)
  980. if aimodels != nil && len(aimodels) > 0 {
  981. if len(aimodels) == 1 {
  982. if aimodels[0].ID != task.ID {
  983. re["msg"] = ctx.Tr("repo.model.manage.create_error")
  984. ctx.JSON(200, re)
  985. return
  986. }
  987. } else {
  988. re["msg"] = ctx.Tr("repo.model.manage.create_error")
  989. ctx.JSON(200, re)
  990. return
  991. }
  992. }
  993. err = models.ModifyLocalModel(id, name, label, description, engine)
  994. } else {
  995. err = ModifyModel(id, description)
  996. }
  997. if err != nil {
  998. re["msg"] = err.Error()
  999. ctx.JSON(200, re)
  1000. return
  1001. } else {
  1002. re["code"] = "0"
  1003. ctx.JSON(200, re)
  1004. }
  1005. }
  1006. func QueryModelListForPredict(ctx *context.Context) {
  1007. repoId := ctx.Repo.Repository.ID
  1008. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  1009. ListOptions: models.ListOptions{
  1010. Page: -1,
  1011. PageSize: -1,
  1012. },
  1013. RepoID: repoId,
  1014. Type: ctx.QueryInt("type"),
  1015. New: -1,
  1016. Status: 0,
  1017. })
  1018. if err != nil {
  1019. ctx.ServerError("Cloudbrain", err)
  1020. return
  1021. }
  1022. log.Info("query return count=" + fmt.Sprint(count))
  1023. nameList := make([]string, 0)
  1024. nameMap := make(map[string][]*models.AiModelManage)
  1025. for _, model := range modelResult {
  1026. removeIpInfo(model)
  1027. if _, value := nameMap[model.Name]; !value {
  1028. models := make([]*models.AiModelManage, 0)
  1029. models = append(models, model)
  1030. nameMap[model.Name] = models
  1031. nameList = append(nameList, model.Name)
  1032. } else {
  1033. nameMap[model.Name] = append(nameMap[model.Name], model)
  1034. }
  1035. }
  1036. mapInterface := make(map[string]interface{})
  1037. mapInterface["nameList"] = nameList
  1038. mapInterface["nameMap"] = nameMap
  1039. ctx.JSON(http.StatusOK, mapInterface)
  1040. }
  1041. func QueryModelFileForPredict(ctx *context.Context) {
  1042. id := ctx.Query("id")
  1043. if id == "" {
  1044. id = ctx.Query("ID")
  1045. }
  1046. ctx.JSON(http.StatusOK, QueryModelFileByID(id))
  1047. }
  1048. func QueryModelFileByID(id string) []storage.FileInfo {
  1049. model, err := models.QueryModelById(id)
  1050. if err == nil {
  1051. if model.Type == models.TypeCloudBrainTwo {
  1052. prefix := model.Path[len(setting.Bucket)+1:]
  1053. fileinfos, _ := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, prefix)
  1054. return fileinfos
  1055. } else if model.Type == models.TypeCloudBrainOne {
  1056. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  1057. fileinfos, _ := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, prefix)
  1058. return fileinfos
  1059. }
  1060. } else {
  1061. log.Error("no such model!", err.Error())
  1062. }
  1063. return nil
  1064. }
  1065. func QueryOneLevelModelFile(ctx *context.Context) {
  1066. id := ctx.Query("id")
  1067. if id == "" {
  1068. id = ctx.Query("ID")
  1069. }
  1070. parentDir := ctx.Query("parentDir")
  1071. model, err := models.QueryModelById(id)
  1072. if err != nil {
  1073. log.Error("no such model!", err.Error())
  1074. ctx.ServerError("no such model:", err)
  1075. return
  1076. }
  1077. if model.Type == models.TypeCloudBrainTwo {
  1078. log.Info("TypeCloudBrainTwo list model file.")
  1079. prefix := model.Path[len(setting.Bucket)+1:]
  1080. fileinfos, _ := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, prefix, parentDir)
  1081. if fileinfos == nil {
  1082. fileinfos = make([]storage.FileInfo, 0)
  1083. }
  1084. ctx.JSON(http.StatusOK, fileinfos)
  1085. } else if model.Type == models.TypeCloudBrainOne {
  1086. log.Info("TypeCloudBrainOne list model file.")
  1087. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  1088. fileinfos, _ := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, parentDir)
  1089. if fileinfos == nil {
  1090. fileinfos = make([]storage.FileInfo, 0)
  1091. }
  1092. ctx.JSON(http.StatusOK, fileinfos)
  1093. }
  1094. }
  1095. func CreateLocalModel(ctx *context.Context) {
  1096. ctx.Data["isModelManage"] = true
  1097. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  1098. ctx.HTML(200, tplCreateLocalModelInfo)
  1099. }
  1100. func CreateLocalModelForUpload(ctx *context.Context) {
  1101. ctx.Data["uuid"] = ctx.Query("uuid")
  1102. ctx.Data["isModelManage"] = true
  1103. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  1104. ctx.HTML(200, tplCreateLocalForUploadModelInfo)
  1105. }
  1106. func CreateOnlineModel(ctx *context.Context) {
  1107. ctx.Data["isModelManage"] = true
  1108. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  1109. ctx.HTML(200, tplCreateOnlineModelInfo)
  1110. }