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

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