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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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. if model.Type == models.TypeCloudBrainOne {
  429. bucketName := setting.Attachment.Minio.Bucket
  430. log.Info("bucket=" + bucketName + " path=" + model.Path)
  431. if strings.HasPrefix(model.Path, bucketName+"/"+Model_prefix) {
  432. err := storage.Attachments.DeleteDir(model.Path[len(bucketName)+1:])
  433. if err != nil {
  434. log.Info("Failed to delete model. id=" + id)
  435. return err
  436. }
  437. }
  438. } else if model.Type == models.TypeCloudBrainTwo {
  439. log.Info("bucket=" + setting.Bucket + " path=" + model.Path)
  440. if strings.HasPrefix(model.Path, setting.Bucket+"/"+Model_prefix) {
  441. err := storage.ObsRemoveObject(setting.Bucket, model.Path[len(setting.Bucket)+1:])
  442. if err != nil {
  443. log.Info("Failed to delete model. id=" + id)
  444. return err
  445. }
  446. }
  447. }
  448. err = models.DeleteModelById(id)
  449. if err == nil { //find a model to change new
  450. aimodels := models.QueryModelByName(model.Name, model.RepoId)
  451. if model.New == MODEL_LATEST {
  452. if len(aimodels) > 0 {
  453. //udpate status and version count
  454. models.ModifyModelNewProperty(aimodels[0].ID, MODEL_LATEST, len(aimodels))
  455. }
  456. } else {
  457. for _, tmpModel := range aimodels {
  458. if tmpModel.New == MODEL_LATEST {
  459. models.ModifyModelNewProperty(tmpModel.ID, MODEL_LATEST, len(aimodels))
  460. break
  461. }
  462. }
  463. }
  464. }
  465. }
  466. return err
  467. }
  468. func QueryModelByParameters(repoId int64, page int) ([]*models.AiModelManage, int64, error) {
  469. return models.QueryModel(&models.AiModelQueryOptions{
  470. ListOptions: models.ListOptions{
  471. Page: page,
  472. PageSize: setting.UI.IssuePagingNum,
  473. },
  474. RepoID: repoId,
  475. Type: -1,
  476. New: MODEL_LATEST,
  477. Status: -1,
  478. })
  479. }
  480. func DownloadMultiModelFile(ctx *context.Context) {
  481. log.Info("DownloadMultiModelFile start.")
  482. id := ctx.Query("id")
  483. log.Info("id=" + id)
  484. task, err := models.QueryModelById(id)
  485. if err != nil {
  486. log.Error("no such model!", err.Error())
  487. ctx.ServerError("no such model:", err)
  488. return
  489. }
  490. if !isOper(ctx, task.UserId) {
  491. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  492. return
  493. }
  494. path := Model_prefix + models.AttachmentRelativePath(id) + "/"
  495. if task.Type == models.TypeCloudBrainTwo {
  496. downloadFromCloudBrainTwo(path, task, ctx, id)
  497. } else if task.Type == models.TypeCloudBrainOne {
  498. downloadFromCloudBrainOne(path, task, ctx, id)
  499. }
  500. }
  501. func MinioDownloadManyFile(path string, ctx *context.Context, returnFileName string, allFile []storage.FileInfo) {
  502. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+url.QueryEscape(returnFileName))
  503. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  504. w := zip.NewWriter(ctx.Resp)
  505. defer w.Close()
  506. for _, oneFile := range allFile {
  507. if oneFile.IsDir {
  508. log.Info("zip dir name:" + oneFile.FileName)
  509. } else {
  510. log.Info("zip file name:" + oneFile.FileName)
  511. fDest, err := w.Create(oneFile.FileName)
  512. if err != nil {
  513. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  514. ctx.ServerError("download file failed:", err)
  515. return
  516. }
  517. log.Info("minio file path=" + (path + oneFile.FileName))
  518. body, err := storage.Attachments.DownloadAFile(setting.Attachment.Minio.Bucket, path+oneFile.FileName)
  519. if err != nil {
  520. log.Info("download file failed: %s\n", err.Error())
  521. ctx.ServerError("download file failed:", err)
  522. return
  523. } else {
  524. defer body.Close()
  525. p := make([]byte, 1024)
  526. var readErr error
  527. var readCount int
  528. // 读取对象内容
  529. for {
  530. readCount, readErr = body.Read(p)
  531. if readCount > 0 {
  532. fDest.Write(p[:readCount])
  533. }
  534. if readErr != nil {
  535. break
  536. }
  537. }
  538. }
  539. }
  540. }
  541. }
  542. func downloadFromCloudBrainOne(path string, task *models.AiModelManage, ctx *context.Context, id string) {
  543. allFile, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, path)
  544. if err == nil {
  545. //count++
  546. models.ModifyModelDownloadCount(id)
  547. returnFileName := task.Name + "_" + task.Version + ".zip"
  548. MinioDownloadManyFile(path, ctx, returnFileName, allFile)
  549. } else {
  550. log.Info("error,msg=" + err.Error())
  551. ctx.ServerError("no file to download.", err)
  552. }
  553. }
  554. func ObsDownloadManyFile(path string, ctx *context.Context, returnFileName string, allFile []storage.FileInfo) {
  555. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+url.QueryEscape(returnFileName))
  556. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  557. w := zip.NewWriter(ctx.Resp)
  558. defer w.Close()
  559. for _, oneFile := range allFile {
  560. if oneFile.IsDir {
  561. log.Info("zip dir name:" + oneFile.FileName)
  562. } else {
  563. log.Info("zip file name:" + oneFile.FileName)
  564. fDest, err := w.Create(oneFile.FileName)
  565. if err != nil {
  566. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  567. ctx.ServerError("download file failed:", err)
  568. return
  569. }
  570. body, err := storage.ObsDownloadAFile(setting.Bucket, path+oneFile.FileName)
  571. if err != nil {
  572. log.Info("download file failed: %s\n", err.Error())
  573. ctx.ServerError("download file failed:", err)
  574. return
  575. } else {
  576. defer body.Close()
  577. p := make([]byte, 1024)
  578. var readErr error
  579. var readCount int
  580. // 读取对象内容
  581. for {
  582. readCount, readErr = body.Read(p)
  583. if readCount > 0 {
  584. fDest.Write(p[:readCount])
  585. }
  586. if readErr != nil {
  587. break
  588. }
  589. }
  590. }
  591. }
  592. }
  593. }
  594. func downloadFromCloudBrainTwo(path string, task *models.AiModelManage, ctx *context.Context, id string) {
  595. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  596. if err == nil {
  597. //count++
  598. models.ModifyModelDownloadCount(id)
  599. returnFileName := task.Name + "_" + task.Version + ".zip"
  600. ObsDownloadManyFile(path, ctx, returnFileName, allFile)
  601. } else {
  602. log.Info("error,msg=" + err.Error())
  603. ctx.ServerError("no file to download.", err)
  604. }
  605. }
  606. func QueryTrainJobVersionList(ctx *context.Context) {
  607. log.Info("query train job version list. start.")
  608. JobID := ctx.Query("jobId")
  609. if JobID == "" {
  610. JobID = ctx.Query("JobId")
  611. }
  612. VersionListTasks, count, err := models.QueryModelTrainJobVersionList(JobID)
  613. log.Info("query return count=" + fmt.Sprint(count))
  614. if err != nil {
  615. ctx.ServerError("QueryTrainJobList:", err)
  616. } else {
  617. ctx.JSON(200, VersionListTasks)
  618. }
  619. }
  620. func QueryTrainJobList(ctx *context.Context) {
  621. log.Info("query train job list. start.")
  622. repoId := ctx.QueryInt64("repoId")
  623. VersionListTasks, count, err := models.QueryModelTrainJobList(repoId)
  624. log.Info("query return count=" + fmt.Sprint(count))
  625. if err != nil {
  626. ctx.ServerError("QueryTrainJobList:", err)
  627. } else {
  628. ctx.JSON(200, VersionListTasks)
  629. }
  630. }
  631. func QueryTrainModelFileById(ctx *context.Context) ([]storage.FileInfo, error) {
  632. JobID := ctx.Query("jobId")
  633. VersionListTasks, count, err := models.QueryModelTrainJobVersionList(JobID)
  634. if err == nil {
  635. if count == 1 {
  636. task := VersionListTasks[0]
  637. jobName := task.JobName
  638. taskType := task.Type
  639. VersionName := task.VersionName
  640. modelDbResult, err := getModelFromObjectSave(jobName, taskType, VersionName)
  641. return modelDbResult, err
  642. }
  643. }
  644. log.Info("get TypeCloudBrainTwo TrainJobListModel failed:", err)
  645. return nil, errors.New("Not found task.")
  646. }
  647. func getModelFromObjectSave(jobName string, taskType int, VersionName string) ([]storage.FileInfo, error) {
  648. if taskType == models.TypeCloudBrainTwo {
  649. objectkey := path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, VersionName) + "/"
  650. modelDbResult, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, objectkey)
  651. log.Info("bucket=" + setting.Bucket + " objectkey=" + objectkey)
  652. if err != nil {
  653. log.Info("get TypeCloudBrainTwo TrainJobListModel failed:", err)
  654. return nil, err
  655. } else {
  656. return modelDbResult, nil
  657. }
  658. } else if taskType == models.TypeCloudBrainOne {
  659. modelSrcPrefix := setting.CBCodePathPrefix + jobName + "/model/"
  660. bucketName := setting.Attachment.Minio.Bucket
  661. modelDbResult, err := storage.GetAllObjectByBucketAndPrefixMinio(bucketName, modelSrcPrefix)
  662. if err != nil {
  663. log.Info("get TypeCloudBrainOne TrainJobListModel failed:", err)
  664. return nil, err
  665. } else {
  666. return modelDbResult, nil
  667. }
  668. }
  669. return nil, errors.New("Not support.")
  670. }
  671. func QueryTrainModelList(ctx *context.Context) {
  672. log.Info("query train job list. start.")
  673. jobName := ctx.Query("jobName")
  674. taskType := ctx.QueryInt("type")
  675. VersionName := ctx.Query("versionName")
  676. if VersionName == "" {
  677. VersionName = ctx.Query("VersionName")
  678. }
  679. modelDbResult, err := getModelFromObjectSave(jobName, taskType, VersionName)
  680. if err != nil {
  681. log.Info("get TypeCloudBrainTwo TrainJobListModel failed:", err)
  682. ctx.JSON(200, "")
  683. } else {
  684. ctx.JSON(200, modelDbResult)
  685. return
  686. }
  687. }
  688. func DownloadSingleModelFile(ctx *context.Context) {
  689. log.Info("DownloadSingleModelFile start.")
  690. id := ctx.Params(":ID")
  691. parentDir := ctx.Query("parentDir")
  692. fileName := ctx.Query("fileName")
  693. path := Model_prefix + models.AttachmentRelativePath(id) + "/" + parentDir + fileName
  694. task, err := models.QueryModelById(id)
  695. if err != nil {
  696. log.Error("no such model!", err.Error())
  697. ctx.ServerError("no such model:", err)
  698. return
  699. }
  700. if !isOper(ctx, task.UserId) {
  701. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  702. return
  703. }
  704. if task.Type == models.TypeCloudBrainTwo {
  705. if setting.PROXYURL != "" {
  706. body, err := storage.ObsDownloadAFile(setting.Bucket, path)
  707. if err != nil {
  708. log.Info("download error.")
  709. } else {
  710. //count++
  711. models.ModifyModelDownloadCount(id)
  712. defer body.Close()
  713. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  714. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  715. p := make([]byte, 1024)
  716. var readErr error
  717. var readCount int
  718. // 读取对象内容
  719. for {
  720. readCount, readErr = body.Read(p)
  721. if readCount > 0 {
  722. ctx.Resp.Write(p[:readCount])
  723. //fmt.Printf("%s", p[:readCount])
  724. }
  725. if readErr != nil {
  726. break
  727. }
  728. }
  729. }
  730. } else {
  731. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  732. if err != nil {
  733. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  734. ctx.ServerError("GetObsCreateSignedUrl", err)
  735. return
  736. }
  737. //count++
  738. models.ModifyModelDownloadCount(id)
  739. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  740. }
  741. } else if task.Type == models.TypeCloudBrainOne {
  742. log.Info("start to down load minio file.")
  743. url, err := storage.Attachments.PresignedGetURL(path, fileName)
  744. if err != nil {
  745. log.Error("Get minio get SignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  746. ctx.ServerError("Get minio get SignedUrl failed", err)
  747. return
  748. }
  749. models.ModifyModelDownloadCount(id)
  750. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  751. }
  752. }
  753. func ShowModelInfo(ctx *context.Context) {
  754. ctx.Data["ID"] = ctx.Query("id")
  755. ctx.Data["name"] = ctx.Query("name")
  756. ctx.Data["isModelManage"] = true
  757. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  758. ctx.HTML(200, tplModelInfo)
  759. }
  760. func QueryModelById(ctx *context.Context) {
  761. id := ctx.Query("id")
  762. model, err := models.QueryModelById(id)
  763. if err == nil {
  764. model.IsCanOper = isOper(ctx, model.UserId)
  765. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  766. removeIpInfo(model)
  767. ctx.JSON(http.StatusOK, model)
  768. } else {
  769. ctx.JSON(http.StatusNotFound, nil)
  770. }
  771. }
  772. func ShowSingleModel(ctx *context.Context) {
  773. name := ctx.Query("name")
  774. log.Info("Show single ModelInfo start.name=" + name)
  775. models := models.QueryModelByName(name, ctx.Repo.Repository.ID)
  776. userIds := make([]int64, len(models))
  777. for i, model := range models {
  778. model.IsCanOper = isOper(ctx, model.UserId)
  779. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  780. userIds[i] = model.UserId
  781. }
  782. userNameMap := queryUserName(userIds)
  783. for _, model := range models {
  784. removeIpInfo(model)
  785. value := userNameMap[model.UserId]
  786. if value != nil {
  787. model.UserName = value.Name
  788. model.UserRelAvatarLink = value.RelAvatarLink()
  789. }
  790. }
  791. ctx.JSON(http.StatusOK, models)
  792. }
  793. func removeIpInfo(model *models.AiModelManage) {
  794. reg, _ := regexp.Compile(`[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}`)
  795. taskInfo := model.TrainTaskInfo
  796. taskInfo = reg.ReplaceAllString(taskInfo, "")
  797. model.TrainTaskInfo = taskInfo
  798. }
  799. func queryUserName(intSlice []int64) map[int64]*models.User {
  800. keys := make(map[int64]string)
  801. uniqueElements := []int64{}
  802. for _, entry := range intSlice {
  803. if _, value := keys[entry]; !value {
  804. keys[entry] = ""
  805. uniqueElements = append(uniqueElements, entry)
  806. }
  807. }
  808. result := make(map[int64]*models.User)
  809. userLists, err := models.GetUsersByIDs(uniqueElements)
  810. if err == nil {
  811. for _, user := range userLists {
  812. result[user.ID] = user
  813. }
  814. }
  815. return result
  816. }
  817. func ShowOneVersionOtherModel(ctx *context.Context) {
  818. repoId := ctx.Repo.Repository.ID
  819. name := ctx.Query("name")
  820. aimodels := models.QueryModelByName(name, repoId)
  821. userIds := make([]int64, len(aimodels))
  822. for i, model := range aimodels {
  823. model.IsCanOper = isOper(ctx, model.UserId)
  824. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  825. userIds[i] = model.UserId
  826. }
  827. userNameMap := queryUserName(userIds)
  828. for _, model := range aimodels {
  829. removeIpInfo(model)
  830. value := userNameMap[model.UserId]
  831. if value != nil {
  832. model.UserName = value.Name
  833. model.UserRelAvatarLink = value.RelAvatarLink()
  834. }
  835. }
  836. if len(aimodels) > 0 {
  837. ctx.JSON(200, aimodels[1:])
  838. } else {
  839. ctx.JSON(200, aimodels)
  840. }
  841. }
  842. func SetModelCount(ctx *context.Context) {
  843. repoId := ctx.Repo.Repository.ID
  844. Type := -1
  845. _, count, _ := models.QueryModel(&models.AiModelQueryOptions{
  846. ListOptions: models.ListOptions{
  847. Page: 1,
  848. PageSize: 2,
  849. },
  850. RepoID: repoId,
  851. Type: Type,
  852. New: MODEL_LATEST,
  853. Status: -1,
  854. })
  855. ctx.Data["MODEL_COUNT"] = count
  856. }
  857. func ShowModelTemplate(ctx *context.Context) {
  858. ctx.Data["isModelManage"] = true
  859. repoId := ctx.Repo.Repository.ID
  860. SetModelCount(ctx)
  861. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  862. _, trainCount, _ := models.QueryModelTrainJobList(repoId)
  863. log.Info("query train count=" + fmt.Sprint(trainCount))
  864. ctx.Data["TRAIN_COUNT"] = trainCount
  865. ctx.HTML(200, tplModelManageIndex)
  866. }
  867. func isQueryRight(ctx *context.Context) bool {
  868. if ctx.Repo.Repository.IsPrivate {
  869. if ctx.Repo.CanRead(models.UnitTypeModelManage) || ctx.User.IsAdmin || ctx.Repo.IsAdmin() || ctx.Repo.IsOwner() {
  870. return true
  871. }
  872. return false
  873. } else {
  874. return true
  875. }
  876. }
  877. func isCanDelete(ctx *context.Context, modelUserId int64) bool {
  878. if ctx.User == nil {
  879. return false
  880. }
  881. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  882. return true
  883. }
  884. if ctx.Repo.IsOwner() {
  885. return true
  886. }
  887. return false
  888. }
  889. func isOper(ctx *context.Context, modelUserId int64) bool {
  890. if ctx.User == nil {
  891. return false
  892. }
  893. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  894. return true
  895. }
  896. return false
  897. }
  898. func ShowModelPageInfo(ctx *context.Context) {
  899. log.Info("ShowModelInfo start.")
  900. if !isQueryRight(ctx) {
  901. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  902. return
  903. }
  904. page := ctx.QueryInt("page")
  905. if page <= 0 {
  906. page = 1
  907. }
  908. pageSize := ctx.QueryInt("pageSize")
  909. if pageSize <= 0 {
  910. pageSize = setting.UI.IssuePagingNum
  911. }
  912. repoId := ctx.Repo.Repository.ID
  913. Type := -1
  914. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  915. ListOptions: models.ListOptions{
  916. Page: page,
  917. PageSize: pageSize,
  918. },
  919. RepoID: repoId,
  920. Type: Type,
  921. New: MODEL_LATEST,
  922. Status: -1,
  923. })
  924. if err != nil {
  925. ctx.ServerError("Cloudbrain", err)
  926. return
  927. }
  928. userIds := make([]int64, len(modelResult))
  929. for i, model := range modelResult {
  930. model.IsCanOper = isOper(ctx, model.UserId)
  931. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  932. userIds[i] = model.UserId
  933. }
  934. userNameMap := queryUserName(userIds)
  935. for _, model := range modelResult {
  936. removeIpInfo(model)
  937. value := userNameMap[model.UserId]
  938. if value != nil {
  939. model.UserName = value.Name
  940. model.UserRelAvatarLink = value.RelAvatarLink()
  941. }
  942. }
  943. mapInterface := make(map[string]interface{})
  944. mapInterface["data"] = modelResult
  945. mapInterface["count"] = count
  946. ctx.JSON(http.StatusOK, mapInterface)
  947. }
  948. func ModifyModel(id string, description string) error {
  949. err := models.ModifyModelDescription(id, description)
  950. if err == nil {
  951. log.Info("modify success.")
  952. } else {
  953. log.Info("Failed to modify.id=" + id + " desc=" + description + " error:" + err.Error())
  954. }
  955. return err
  956. }
  957. func ModifyModelInfo(ctx *context.Context) {
  958. log.Info("modify model start.")
  959. id := ctx.Query("id")
  960. description := ctx.Query("description")
  961. re := map[string]string{
  962. "code": "-1",
  963. }
  964. task, err := models.QueryModelById(id)
  965. if err != nil {
  966. re["msg"] = err.Error()
  967. log.Error("no such model!", err.Error())
  968. ctx.JSON(200, re)
  969. return
  970. }
  971. if !isOper(ctx, task.UserId) {
  972. re["msg"] = "No right to operation."
  973. ctx.JSON(200, re)
  974. return
  975. }
  976. if task.ModelType == MODEL_LOCAL_TYPE {
  977. name := ctx.Query("name")
  978. label := ctx.Query("label")
  979. description := ctx.Query("description")
  980. engine := ctx.QueryInt("engine")
  981. aimodels := models.QueryModelByName(name, task.RepoId)
  982. if aimodels != nil && len(aimodels) > 0 {
  983. if len(aimodels) == 1 {
  984. if aimodels[0].ID != task.ID {
  985. re["msg"] = ctx.Tr("repo.model.manage.create_error")
  986. ctx.JSON(200, re)
  987. return
  988. }
  989. } else {
  990. re["msg"] = ctx.Tr("repo.model.manage.create_error")
  991. ctx.JSON(200, re)
  992. return
  993. }
  994. }
  995. err = models.ModifyLocalModel(id, name, label, description, engine)
  996. } else {
  997. err = ModifyModel(id, description)
  998. }
  999. if err != nil {
  1000. re["msg"] = err.Error()
  1001. ctx.JSON(200, re)
  1002. return
  1003. } else {
  1004. re["code"] = "0"
  1005. ctx.JSON(200, re)
  1006. }
  1007. }
  1008. func QueryModelListForPredict(ctx *context.Context) {
  1009. repoId := ctx.Repo.Repository.ID
  1010. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  1011. ListOptions: models.ListOptions{
  1012. Page: -1,
  1013. PageSize: -1,
  1014. },
  1015. RepoID: repoId,
  1016. Type: ctx.QueryInt("type"),
  1017. New: -1,
  1018. Status: 0,
  1019. })
  1020. if err != nil {
  1021. ctx.ServerError("Cloudbrain", err)
  1022. return
  1023. }
  1024. log.Info("query return count=" + fmt.Sprint(count))
  1025. nameList := make([]string, 0)
  1026. nameMap := make(map[string][]*models.AiModelManage)
  1027. for _, model := range modelResult {
  1028. removeIpInfo(model)
  1029. if _, value := nameMap[model.Name]; !value {
  1030. models := make([]*models.AiModelManage, 0)
  1031. models = append(models, model)
  1032. nameMap[model.Name] = models
  1033. nameList = append(nameList, model.Name)
  1034. } else {
  1035. nameMap[model.Name] = append(nameMap[model.Name], model)
  1036. }
  1037. }
  1038. mapInterface := make(map[string]interface{})
  1039. mapInterface["nameList"] = nameList
  1040. mapInterface["nameMap"] = nameMap
  1041. ctx.JSON(http.StatusOK, mapInterface)
  1042. }
  1043. func QueryModelFileForPredict(ctx *context.Context) {
  1044. id := ctx.Query("id")
  1045. if id == "" {
  1046. id = ctx.Query("ID")
  1047. }
  1048. ctx.JSON(http.StatusOK, QueryModelFileByID(id))
  1049. }
  1050. func QueryModelFileByID(id string) []storage.FileInfo {
  1051. model, err := models.QueryModelById(id)
  1052. if err == nil {
  1053. if model.Type == models.TypeCloudBrainTwo {
  1054. prefix := model.Path[len(setting.Bucket)+1:]
  1055. fileinfos, _ := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, prefix)
  1056. return fileinfos
  1057. } else if model.Type == models.TypeCloudBrainOne {
  1058. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  1059. fileinfos, _ := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, prefix)
  1060. return fileinfos
  1061. }
  1062. } else {
  1063. log.Error("no such model!", err.Error())
  1064. }
  1065. return nil
  1066. }
  1067. func QueryOneLevelModelFile(ctx *context.Context) {
  1068. id := ctx.Query("id")
  1069. if id == "" {
  1070. id = ctx.Query("ID")
  1071. }
  1072. parentDir := ctx.Query("parentDir")
  1073. model, err := models.QueryModelById(id)
  1074. if err != nil {
  1075. log.Error("no such model!", err.Error())
  1076. ctx.ServerError("no such model:", err)
  1077. return
  1078. }
  1079. if model.Type == models.TypeCloudBrainTwo {
  1080. log.Info("TypeCloudBrainTwo list model file.")
  1081. prefix := model.Path[len(setting.Bucket)+1:]
  1082. fileinfos, _ := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, prefix, parentDir)
  1083. if fileinfos == nil {
  1084. fileinfos = make([]storage.FileInfo, 0)
  1085. }
  1086. ctx.JSON(http.StatusOK, fileinfos)
  1087. } else if model.Type == models.TypeCloudBrainOne {
  1088. log.Info("TypeCloudBrainOne list model file.")
  1089. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  1090. fileinfos, _ := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, parentDir)
  1091. if fileinfos == nil {
  1092. fileinfos = make([]storage.FileInfo, 0)
  1093. }
  1094. ctx.JSON(http.StatusOK, fileinfos)
  1095. }
  1096. }
  1097. func CreateLocalModel(ctx *context.Context) {
  1098. ctx.Data["isModelManage"] = true
  1099. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  1100. ctx.HTML(200, tplCreateLocalModelInfo)
  1101. }
  1102. func CreateLocalModelForUpload(ctx *context.Context) {
  1103. ctx.Data["uuid"] = ctx.Query("uuid")
  1104. ctx.Data["isModelManage"] = true
  1105. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  1106. ctx.HTML(200, tplCreateLocalForUploadModelInfo)
  1107. }
  1108. func CreateOnlineModel(ctx *context.Context) {
  1109. ctx.Data["isModelManage"] = true
  1110. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  1111. ctx.HTML(200, tplCreateOnlineModelInfo)
  1112. }