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