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