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 27 kB

4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. package repo
  2. import (
  3. "archive/zip"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "net/url"
  9. "path"
  10. "strings"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/context"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/notification"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/storage"
  17. uuid "github.com/satori/go.uuid"
  18. )
  19. const (
  20. Model_prefix = "aimodels/"
  21. tplModelManageIndex = "repo/modelmanage/index"
  22. tplModelManageDownload = "repo/modelmanage/download"
  23. tplModelInfo = "repo/modelmanage/showinfo"
  24. MODEL_LATEST = 1
  25. MODEL_NOT_LATEST = 0
  26. MODEL_MAX_SIZE = 1024 * 1024 * 1024
  27. )
  28. func saveModelByParameters(jobId string, versionName string, name string, version string, label string, description string, engine int, ctx *context.Context) error {
  29. aiTask, err := models.GetCloudbrainByJobIDAndVersionName(jobId, versionName)
  30. if err != nil {
  31. aiTask, err = models.GetRepoCloudBrainByJobID(ctx.Repo.Repository.ID, jobId)
  32. if err != nil {
  33. log.Info("query task error." + err.Error())
  34. return err
  35. } else {
  36. log.Info("query gpu train task.")
  37. }
  38. }
  39. uuid := uuid.NewV4()
  40. id := uuid.String()
  41. modelPath := id
  42. var lastNewModelId string
  43. var modelSize int64
  44. log.Info("find task name:" + aiTask.JobName)
  45. aimodels := models.QueryModelByName(name, aiTask.RepoID)
  46. if len(aimodels) > 0 {
  47. for _, model := range aimodels {
  48. if model.Version == version {
  49. return errors.New(ctx.Tr("repo.model.manage.create_error"))
  50. }
  51. if model.New == MODEL_LATEST {
  52. lastNewModelId = model.ID
  53. }
  54. }
  55. }
  56. cloudType := aiTask.Type
  57. modelSelectedFile := ctx.Query("modelSelectedFile")
  58. //download model zip //train type
  59. if cloudType == models.TypeCloudBrainTwo {
  60. modelPath, modelSize, err = downloadModelFromCloudBrainTwo(id, aiTask.JobName, "", aiTask.TrainUrl, modelSelectedFile)
  61. if err != nil {
  62. log.Info("download model from CloudBrainTwo faild." + err.Error())
  63. return err
  64. }
  65. } else if cloudType == models.TypeCloudBrainOne {
  66. var ResourceSpecs *models.ResourceSpecs
  67. json.Unmarshal([]byte(setting.ResourceSpecs), &ResourceSpecs)
  68. for _, tmp := range ResourceSpecs.ResourceSpec {
  69. if tmp.Id == aiTask.ResourceSpecId {
  70. flaverName := ctx.Tr("cloudbrain.gpu_num") + ": " + fmt.Sprint(tmp.GpuNum) + " " + ctx.Tr("cloudbrain.cpu_num") + ": " + fmt.Sprint(tmp.CpuNum) + " " + ctx.Tr("cloudbrain.memory") + "(MB): " + fmt.Sprint(tmp.MemMiB) + " " + ctx.Tr("cloudbrain.shared_memory") + "(MB): " + fmt.Sprint(tmp.ShareMemMiB)
  71. aiTask.FlavorName = flaverName
  72. }
  73. }
  74. modelPath, modelSize, err = downloadModelFromCloudBrainOne(id, aiTask.JobName, "", aiTask.TrainUrl, modelSelectedFile)
  75. if err != nil {
  76. log.Info("download model from CloudBrainOne faild." + err.Error())
  77. return err
  78. }
  79. } else if cloudType == models.TypeC2Net {
  80. if aiTask.ComputeResource == models.NPUResource {
  81. modelPath, modelSize, err = downloadModelFromCloudBrainTwo(id, aiTask.JobName, "", aiTask.TrainUrl, modelSelectedFile)
  82. if err != nil {
  83. log.Info("download model from CloudBrainTwo faild." + err.Error())
  84. return err
  85. }
  86. } else if aiTask.ComputeResource == models.GPUResource {
  87. }
  88. }
  89. accuracy := make(map[string]string)
  90. accuracy["F1"] = ""
  91. accuracy["Recall"] = ""
  92. accuracy["Accuracy"] = ""
  93. accuracy["Precision"] = ""
  94. accuracyJson, _ := json.Marshal(accuracy)
  95. log.Info("accuracyJson=" + string(accuracyJson))
  96. aiTaskJson, _ := json.Marshal(aiTask)
  97. model := &models.AiModelManage{
  98. ID: id,
  99. Version: version,
  100. VersionCount: len(aimodels) + 1,
  101. Label: label,
  102. Name: name,
  103. Description: description,
  104. New: MODEL_LATEST,
  105. Type: cloudType,
  106. Path: modelPath,
  107. Size: modelSize,
  108. AttachmentId: aiTask.Uuid,
  109. RepoId: aiTask.RepoID,
  110. UserId: ctx.User.ID,
  111. CodeBranch: aiTask.BranchName,
  112. CodeCommitID: aiTask.CommitID,
  113. Engine: int64(engine),
  114. TrainTaskInfo: string(aiTaskJson),
  115. Accuracy: string(accuracyJson),
  116. }
  117. err = models.SaveModelToDb(model)
  118. if err != nil {
  119. return err
  120. }
  121. if len(lastNewModelId) > 0 {
  122. //udpate status and version count
  123. models.ModifyModelNewProperty(lastNewModelId, MODEL_NOT_LATEST, 0)
  124. }
  125. var units []models.RepoUnit
  126. var deleteUnitTypes []models.UnitType
  127. units = append(units, models.RepoUnit{
  128. RepoID: ctx.Repo.Repository.ID,
  129. Type: models.UnitTypeModelManage,
  130. Config: &models.ModelManageConfig{
  131. EnableModelManage: true,
  132. },
  133. })
  134. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeModelManage)
  135. models.UpdateRepositoryUnits(ctx.Repo.Repository, units, deleteUnitTypes)
  136. log.Info("save model end.")
  137. notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, id, name, models.ActionCreateNewModelTask)
  138. return nil
  139. }
  140. func SaveNewNameModel(ctx *context.Context) {
  141. name := ctx.Query("Name")
  142. if name == "" {
  143. ctx.Error(500, fmt.Sprintf("name or version is null."))
  144. return
  145. }
  146. aimodels := models.QueryModelByName(name, ctx.Repo.Repository.ID)
  147. if len(aimodels) > 0 {
  148. ctx.Error(500, ctx.Tr("repo.model_rename"))
  149. return
  150. }
  151. SaveModel(ctx)
  152. ctx.Status(200)
  153. log.Info("save model end.")
  154. }
  155. func SaveModel(ctx *context.Context) {
  156. log.Info("save model start.")
  157. JobId := ctx.Query("JobId")
  158. VersionName := ctx.Query("VersionName")
  159. name := ctx.Query("Name")
  160. version := ctx.Query("Version")
  161. label := ctx.Query("Label")
  162. description := ctx.Query("Description")
  163. engine := ctx.QueryInt("Engine")
  164. trainTaskCreate := ctx.QueryBool("trainTaskCreate")
  165. modelSelectedFile := ctx.Query("modelSelectedFile")
  166. log.Info("engine=" + fmt.Sprint(engine) + " modelSelectedFile=" + modelSelectedFile)
  167. if !trainTaskCreate {
  168. if !ctx.Repo.CanWrite(models.UnitTypeModelManage) {
  169. //ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  170. ctx.JSON(403, ctx.Tr("repo.model_noright"))
  171. return
  172. }
  173. }
  174. if JobId == "" || VersionName == "" {
  175. ctx.Error(500, fmt.Sprintf("JobId or VersionName is null."))
  176. return
  177. }
  178. if modelSelectedFile == "" {
  179. ctx.Error(500, fmt.Sprintf("Not selected model file."))
  180. return
  181. }
  182. if name == "" || version == "" {
  183. ctx.Error(500, fmt.Sprintf("name or version is null."))
  184. return
  185. }
  186. err := saveModelByParameters(JobId, VersionName, name, version, label, description, engine, ctx)
  187. if err != nil {
  188. log.Info("save model error." + err.Error())
  189. ctx.Error(500, fmt.Sprintf("save model error. %v", err))
  190. return
  191. }
  192. ctx.Status(200)
  193. log.Info("save model end.")
  194. }
  195. func downloadModelFromCloudBrainTwo(modelUUID string, jobName string, parentDir string, trainUrl string, modelSelectedFile string) (string, int64, error) {
  196. objectkey := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir), "/")
  197. if trainUrl != "" {
  198. objectkey = strings.Trim(trainUrl[len(setting.Bucket)+1:], "/")
  199. }
  200. prefix := objectkey + "/"
  201. filterFiles := strings.Split(modelSelectedFile, ";")
  202. Files := make([]string, 0)
  203. for _, shortFile := range filterFiles {
  204. Files = append(Files, prefix+shortFile)
  205. }
  206. totalSize := storage.ObsGetFilesSize(setting.Bucket, Files)
  207. if float64(totalSize) > setting.MaxModelSize*MODEL_MAX_SIZE {
  208. return "", 0, errors.New("Cannot create model, as model is exceed " + fmt.Sprint(setting.MaxModelSize) + "G.")
  209. }
  210. modelDbResult, err := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, objectkey, "")
  211. log.Info("bucket=" + setting.Bucket + " objectkey=" + objectkey)
  212. if err != nil {
  213. log.Info("get TrainJobListModel failed:", err)
  214. return "", 0, err
  215. }
  216. if len(modelDbResult) == 0 {
  217. return "", 0, errors.New("Cannot create model, as model is empty.")
  218. }
  219. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(modelUUID) + "/"
  220. size, err := storage.ObsCopyManyFile(setting.Bucket, prefix, setting.Bucket, destKeyNamePrefix, filterFiles)
  221. dataActualPath := setting.Bucket + "/" + destKeyNamePrefix
  222. return dataActualPath, size, nil
  223. }
  224. func downloadModelFromCloudBrainOne(modelUUID string, jobName string, parentDir string, trainUrl string, modelSelectedFile string) (string, int64, error) {
  225. modelActualPath := storage.GetMinioPath(jobName, "/model/")
  226. log.Info("modelActualPath=" + modelActualPath)
  227. modelSrcPrefix := setting.CBCodePathPrefix + jobName + "/model/"
  228. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(modelUUID) + "/"
  229. bucketName := setting.Attachment.Minio.Bucket
  230. log.Info("destKeyNamePrefix=" + destKeyNamePrefix + " modelSrcPrefix=" + modelSrcPrefix + " bucket=" + bucketName)
  231. filterFiles := strings.Split(modelSelectedFile, ";")
  232. Files := make([]string, 0)
  233. for _, shortFile := range filterFiles {
  234. Files = append(Files, modelSrcPrefix+shortFile)
  235. }
  236. totalSize := storage.MinioGetFilesSize(bucketName, Files)
  237. if float64(totalSize) > setting.MaxModelSize*MODEL_MAX_SIZE {
  238. return "", 0, errors.New("Cannot create model, as model is exceed " + fmt.Sprint(setting.MaxModelSize) + "G.")
  239. }
  240. size, err := storage.MinioCopyFiles(bucketName, modelSrcPrefix, destKeyNamePrefix, filterFiles)
  241. if err == nil {
  242. dataActualPath := bucketName + "/" + destKeyNamePrefix
  243. return dataActualPath, size, nil
  244. } else {
  245. return "", 0, nil
  246. }
  247. }
  248. func DeleteModel(ctx *context.Context) {
  249. log.Info("delete model start.")
  250. id := ctx.Query("ID")
  251. err := deleteModelByID(ctx, id)
  252. if err != nil {
  253. ctx.JSON(500, err.Error())
  254. } else {
  255. ctx.JSON(200, map[string]string{
  256. "result_code": "0",
  257. })
  258. }
  259. }
  260. func deleteModelByID(ctx *context.Context, id string) error {
  261. log.Info("delete model start. id=" + id)
  262. model, err := models.QueryModelById(id)
  263. if !isCanDelete(ctx, model.UserId) {
  264. return errors.New(ctx.Tr("repo.model_noright"))
  265. }
  266. if err == nil {
  267. log.Info("bucket=" + setting.Bucket + " path=" + model.Path)
  268. if strings.HasPrefix(model.Path, setting.Bucket+"/"+Model_prefix) {
  269. err := storage.ObsRemoveObject(setting.Bucket, model.Path[len(setting.Bucket)+1:])
  270. if err != nil {
  271. log.Info("Failed to delete model. id=" + id)
  272. return err
  273. }
  274. }
  275. err = models.DeleteModelById(id)
  276. if err == nil { //find a model to change new
  277. aimodels := models.QueryModelByName(model.Name, model.RepoId)
  278. if model.New == MODEL_LATEST {
  279. if len(aimodels) > 0 {
  280. //udpate status and version count
  281. models.ModifyModelNewProperty(aimodels[0].ID, MODEL_LATEST, len(aimodels))
  282. }
  283. } else {
  284. for _, tmpModel := range aimodels {
  285. if tmpModel.New == MODEL_LATEST {
  286. models.ModifyModelNewProperty(tmpModel.ID, MODEL_LATEST, len(aimodels))
  287. break
  288. }
  289. }
  290. }
  291. }
  292. }
  293. return err
  294. }
  295. func QueryModelByParameters(repoId int64, page int) ([]*models.AiModelManage, int64, error) {
  296. return models.QueryModel(&models.AiModelQueryOptions{
  297. ListOptions: models.ListOptions{
  298. Page: page,
  299. PageSize: setting.UI.IssuePagingNum,
  300. },
  301. RepoID: repoId,
  302. Type: -1,
  303. New: MODEL_LATEST,
  304. })
  305. }
  306. func DownloadMultiModelFile(ctx *context.Context) {
  307. log.Info("DownloadMultiModelFile start.")
  308. id := ctx.Query("ID")
  309. log.Info("id=" + id)
  310. task, err := models.QueryModelById(id)
  311. if err != nil {
  312. log.Error("no such model!", err.Error())
  313. ctx.ServerError("no such model:", err)
  314. return
  315. }
  316. if !isOper(ctx, task.UserId) {
  317. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  318. return
  319. }
  320. path := Model_prefix + models.AttachmentRelativePath(id) + "/"
  321. if task.Type == models.TypeCloudBrainTwo {
  322. downloadFromCloudBrainTwo(path, task, ctx, id)
  323. } else if task.Type == models.TypeCloudBrainOne {
  324. downloadFromCloudBrainOne(path, task, ctx, id)
  325. }
  326. }
  327. func MinioDownloadManyFile(path string, ctx *context.Context, returnFileName string, allFile []storage.FileInfo) {
  328. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+url.QueryEscape(returnFileName))
  329. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  330. w := zip.NewWriter(ctx.Resp)
  331. defer w.Close()
  332. for _, oneFile := range allFile {
  333. if oneFile.IsDir {
  334. log.Info("zip dir name:" + oneFile.FileName)
  335. } else {
  336. log.Info("zip file name:" + oneFile.FileName)
  337. fDest, err := w.Create(oneFile.FileName)
  338. if err != nil {
  339. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  340. ctx.ServerError("download file failed:", err)
  341. return
  342. }
  343. log.Info("minio file path=" + (path + oneFile.FileName))
  344. body, err := storage.Attachments.DownloadAFile(setting.Attachment.Minio.Bucket, path+oneFile.FileName)
  345. if err != nil {
  346. log.Info("download file failed: %s\n", err.Error())
  347. ctx.ServerError("download file failed:", err)
  348. return
  349. } else {
  350. defer body.Close()
  351. p := make([]byte, 1024)
  352. var readErr error
  353. var readCount int
  354. // 读取对象内容
  355. for {
  356. readCount, readErr = body.Read(p)
  357. if readCount > 0 {
  358. fDest.Write(p[:readCount])
  359. }
  360. if readErr != nil {
  361. break
  362. }
  363. }
  364. }
  365. }
  366. }
  367. }
  368. func downloadFromCloudBrainOne(path string, task *models.AiModelManage, ctx *context.Context, id string) {
  369. allFile, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, path)
  370. if err == nil {
  371. //count++
  372. models.ModifyModelDownloadCount(id)
  373. returnFileName := task.Name + "_" + task.Version + ".zip"
  374. MinioDownloadManyFile(path, ctx, returnFileName, allFile)
  375. } else {
  376. log.Info("error,msg=" + err.Error())
  377. ctx.ServerError("no file to download.", err)
  378. }
  379. }
  380. func ObsDownloadManyFile(path string, ctx *context.Context, returnFileName string, allFile []storage.FileInfo) {
  381. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+url.QueryEscape(returnFileName))
  382. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  383. w := zip.NewWriter(ctx.Resp)
  384. defer w.Close()
  385. for _, oneFile := range allFile {
  386. if oneFile.IsDir {
  387. log.Info("zip dir name:" + oneFile.FileName)
  388. } else {
  389. log.Info("zip file name:" + oneFile.FileName)
  390. fDest, err := w.Create(oneFile.FileName)
  391. if err != nil {
  392. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  393. ctx.ServerError("download file failed:", err)
  394. return
  395. }
  396. body, err := storage.ObsDownloadAFile(setting.Bucket, path+oneFile.FileName)
  397. if err != nil {
  398. log.Info("download file failed: %s\n", err.Error())
  399. ctx.ServerError("download file failed:", err)
  400. return
  401. } else {
  402. defer body.Close()
  403. p := make([]byte, 1024)
  404. var readErr error
  405. var readCount int
  406. // 读取对象内容
  407. for {
  408. readCount, readErr = body.Read(p)
  409. if readCount > 0 {
  410. fDest.Write(p[:readCount])
  411. }
  412. if readErr != nil {
  413. break
  414. }
  415. }
  416. }
  417. }
  418. }
  419. }
  420. func downloadFromCloudBrainTwo(path string, task *models.AiModelManage, ctx *context.Context, id string) {
  421. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  422. if err == nil {
  423. //count++
  424. models.ModifyModelDownloadCount(id)
  425. returnFileName := task.Name + "_" + task.Version + ".zip"
  426. ObsDownloadManyFile(path, ctx, returnFileName, allFile)
  427. } else {
  428. log.Info("error,msg=" + err.Error())
  429. ctx.ServerError("no file to download.", err)
  430. }
  431. }
  432. func QueryTrainJobVersionList(ctx *context.Context) {
  433. log.Info("query train job version list. start.")
  434. JobID := ctx.Query("JobID")
  435. VersionListTasks, count, err := models.QueryModelTrainJobVersionList(JobID)
  436. log.Info("query return count=" + fmt.Sprint(count))
  437. if err != nil {
  438. ctx.ServerError("QueryTrainJobList:", err)
  439. } else {
  440. ctx.JSON(200, VersionListTasks)
  441. }
  442. }
  443. func QueryTrainJobList(ctx *context.Context) {
  444. log.Info("query train job list. start.")
  445. repoId := ctx.QueryInt64("repoId")
  446. VersionListTasks, count, err := models.QueryModelTrainJobList(repoId)
  447. log.Info("query return count=" + fmt.Sprint(count))
  448. if err != nil {
  449. ctx.ServerError("QueryTrainJobList:", err)
  450. } else {
  451. ctx.JSON(200, VersionListTasks)
  452. }
  453. }
  454. func QueryTrainModelList(ctx *context.Context) {
  455. log.Info("query train job list. start.")
  456. jobName := ctx.Query("jobName")
  457. taskType := ctx.QueryInt("type")
  458. VersionName := ctx.Query("VersionName")
  459. if taskType == models.TypeCloudBrainTwo {
  460. objectkey := path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, VersionName) + "/"
  461. modelDbResult, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, objectkey)
  462. log.Info("bucket=" + setting.Bucket + " objectkey=" + objectkey)
  463. if err != nil {
  464. log.Info("get TypeCloudBrainTwo TrainJobListModel failed:", err)
  465. } else {
  466. ctx.JSON(200, modelDbResult)
  467. return
  468. }
  469. } else if taskType == models.TypeCloudBrainOne {
  470. modelSrcPrefix := setting.CBCodePathPrefix + jobName + "/model/"
  471. bucketName := setting.Attachment.Minio.Bucket
  472. modelDbResult, err := storage.GetAllObjectByBucketAndPrefixMinio(bucketName, modelSrcPrefix)
  473. if err != nil {
  474. log.Info("get TypeCloudBrainOne TrainJobListModel failed:", err)
  475. } else {
  476. ctx.JSON(200, modelDbResult)
  477. return
  478. }
  479. }
  480. ctx.JSON(200, "")
  481. }
  482. func DownloadSingleModelFile(ctx *context.Context) {
  483. log.Info("DownloadSingleModelFile start.")
  484. id := ctx.Params(":ID")
  485. parentDir := ctx.Query("parentDir")
  486. fileName := ctx.Query("fileName")
  487. path := Model_prefix + models.AttachmentRelativePath(id) + "/" + parentDir + fileName
  488. task, err := models.QueryModelById(id)
  489. if err != nil {
  490. log.Error("no such model!", err.Error())
  491. ctx.ServerError("no such model:", err)
  492. return
  493. }
  494. if !isOper(ctx, task.UserId) {
  495. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  496. return
  497. }
  498. if task.Type == models.TypeCloudBrainTwo {
  499. if setting.PROXYURL != "" {
  500. body, err := storage.ObsDownloadAFile(setting.Bucket, path)
  501. if err != nil {
  502. log.Info("download error.")
  503. } else {
  504. //count++
  505. models.ModifyModelDownloadCount(id)
  506. defer body.Close()
  507. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  508. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  509. p := make([]byte, 1024)
  510. var readErr error
  511. var readCount int
  512. // 读取对象内容
  513. for {
  514. readCount, readErr = body.Read(p)
  515. if readCount > 0 {
  516. ctx.Resp.Write(p[:readCount])
  517. //fmt.Printf("%s", p[:readCount])
  518. }
  519. if readErr != nil {
  520. break
  521. }
  522. }
  523. }
  524. } else {
  525. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  526. if err != nil {
  527. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  528. ctx.ServerError("GetObsCreateSignedUrl", err)
  529. return
  530. }
  531. //count++
  532. models.ModifyModelDownloadCount(id)
  533. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  534. }
  535. } else if task.Type == models.TypeCloudBrainOne {
  536. log.Info("start to down load minio file.")
  537. url, err := storage.Attachments.PresignedGetURL(path, fileName)
  538. if err != nil {
  539. log.Error("Get minio get SignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  540. ctx.ServerError("Get minio get SignedUrl failed", err)
  541. return
  542. }
  543. models.ModifyModelDownloadCount(id)
  544. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  545. }
  546. }
  547. func ShowModelInfo(ctx *context.Context) {
  548. ctx.Data["ID"] = ctx.Query("ID")
  549. ctx.Data["name"] = ctx.Query("name")
  550. ctx.Data["isModelManage"] = true
  551. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  552. ctx.HTML(200, tplModelInfo)
  553. }
  554. func ShowSingleModel(ctx *context.Context) {
  555. name := ctx.Query("name")
  556. log.Info("Show single ModelInfo start.name=" + name)
  557. models := models.QueryModelByName(name, ctx.Repo.Repository.ID)
  558. userIds := make([]int64, len(models))
  559. for i, model := range models {
  560. model.IsCanOper = isOper(ctx, model.UserId)
  561. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  562. userIds[i] = model.UserId
  563. }
  564. userNameMap := queryUserName(userIds)
  565. for _, model := range models {
  566. value := userNameMap[model.UserId]
  567. if value != nil {
  568. model.UserName = value.Name
  569. model.UserRelAvatarLink = value.RelAvatarLink()
  570. }
  571. }
  572. ctx.JSON(http.StatusOK, models)
  573. }
  574. func queryUserName(intSlice []int64) map[int64]*models.User {
  575. keys := make(map[int64]string)
  576. uniqueElements := []int64{}
  577. for _, entry := range intSlice {
  578. if _, value := keys[entry]; !value {
  579. keys[entry] = ""
  580. uniqueElements = append(uniqueElements, entry)
  581. }
  582. }
  583. result := make(map[int64]*models.User)
  584. userLists, err := models.GetUsersByIDs(uniqueElements)
  585. if err == nil {
  586. for _, user := range userLists {
  587. result[user.ID] = user
  588. }
  589. }
  590. return result
  591. }
  592. func ShowOneVersionOtherModel(ctx *context.Context) {
  593. repoId := ctx.Repo.Repository.ID
  594. name := ctx.Query("name")
  595. aimodels := models.QueryModelByName(name, repoId)
  596. userIds := make([]int64, len(aimodels))
  597. for i, model := range aimodels {
  598. model.IsCanOper = isOper(ctx, model.UserId)
  599. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  600. userIds[i] = model.UserId
  601. }
  602. userNameMap := queryUserName(userIds)
  603. for _, model := range aimodels {
  604. value := userNameMap[model.UserId]
  605. if value != nil {
  606. model.UserName = value.Name
  607. model.UserRelAvatarLink = value.RelAvatarLink()
  608. }
  609. }
  610. if len(aimodels) > 0 {
  611. ctx.JSON(200, aimodels[1:])
  612. } else {
  613. ctx.JSON(200, aimodels)
  614. }
  615. }
  616. func SetModelCount(ctx *context.Context) {
  617. repoId := ctx.Repo.Repository.ID
  618. Type := -1
  619. _, count, _ := models.QueryModel(&models.AiModelQueryOptions{
  620. ListOptions: models.ListOptions{
  621. Page: 1,
  622. PageSize: 2,
  623. },
  624. RepoID: repoId,
  625. Type: Type,
  626. New: MODEL_LATEST,
  627. })
  628. ctx.Data["MODEL_COUNT"] = count
  629. }
  630. func ShowModelTemplate(ctx *context.Context) {
  631. ctx.Data["isModelManage"] = true
  632. repoId := ctx.Repo.Repository.ID
  633. SetModelCount(ctx)
  634. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  635. _, trainCount, _ := models.QueryModelTrainJobList(repoId)
  636. log.Info("query train count=" + fmt.Sprint(trainCount))
  637. ctx.Data["TRAIN_COUNT"] = trainCount
  638. ctx.HTML(200, tplModelManageIndex)
  639. }
  640. func isQueryRight(ctx *context.Context) bool {
  641. if ctx.Repo.Repository.IsPrivate {
  642. if ctx.Repo.CanRead(models.UnitTypeModelManage) || ctx.User.IsAdmin || ctx.Repo.IsAdmin() || ctx.Repo.IsOwner() {
  643. return true
  644. }
  645. return false
  646. } else {
  647. return true
  648. }
  649. }
  650. func isCanDelete(ctx *context.Context, modelUserId int64) bool {
  651. if ctx.User == nil {
  652. return false
  653. }
  654. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  655. return true
  656. }
  657. if ctx.Repo.IsOwner() {
  658. return true
  659. }
  660. return false
  661. }
  662. func isOper(ctx *context.Context, modelUserId int64) bool {
  663. if ctx.User == nil {
  664. return false
  665. }
  666. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  667. return true
  668. }
  669. return false
  670. }
  671. func ShowModelPageInfo(ctx *context.Context) {
  672. log.Info("ShowModelInfo start.")
  673. if !isQueryRight(ctx) {
  674. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  675. return
  676. }
  677. page := ctx.QueryInt("page")
  678. if page <= 0 {
  679. page = 1
  680. }
  681. pageSize := ctx.QueryInt("pageSize")
  682. if pageSize <= 0 {
  683. pageSize = setting.UI.IssuePagingNum
  684. }
  685. repoId := ctx.Repo.Repository.ID
  686. Type := -1
  687. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  688. ListOptions: models.ListOptions{
  689. Page: page,
  690. PageSize: pageSize,
  691. },
  692. RepoID: repoId,
  693. Type: Type,
  694. New: MODEL_LATEST,
  695. })
  696. if err != nil {
  697. ctx.ServerError("Cloudbrain", err)
  698. return
  699. }
  700. userIds := make([]int64, len(modelResult))
  701. for i, model := range modelResult {
  702. model.IsCanOper = isOper(ctx, model.UserId)
  703. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  704. userIds[i] = model.UserId
  705. }
  706. userNameMap := queryUserName(userIds)
  707. for _, model := range modelResult {
  708. value := userNameMap[model.UserId]
  709. if value != nil {
  710. model.UserName = value.Name
  711. model.UserRelAvatarLink = value.RelAvatarLink()
  712. }
  713. }
  714. mapInterface := make(map[string]interface{})
  715. mapInterface["data"] = modelResult
  716. mapInterface["count"] = count
  717. ctx.JSON(http.StatusOK, mapInterface)
  718. }
  719. func ModifyModel(id string, description string) error {
  720. err := models.ModifyModelDescription(id, description)
  721. if err == nil {
  722. log.Info("modify success.")
  723. } else {
  724. log.Info("Failed to modify.id=" + id + " desc=" + description + " error:" + err.Error())
  725. }
  726. return err
  727. }
  728. func ModifyModelInfo(ctx *context.Context) {
  729. log.Info("modify model start.")
  730. id := ctx.Query("ID")
  731. description := ctx.Query("Description")
  732. task, err := models.QueryModelById(id)
  733. if err != nil {
  734. log.Error("no such model!", err.Error())
  735. ctx.ServerError("no such model:", err)
  736. return
  737. }
  738. if !isOper(ctx, task.UserId) {
  739. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  740. //ctx.ServerError("no right.", errors.New(ctx.Tr("repo.model_noright")))
  741. return
  742. }
  743. err = ModifyModel(id, description)
  744. if err != nil {
  745. log.Info("modify error," + err.Error())
  746. ctx.ServerError("error.", err)
  747. } else {
  748. ctx.JSON(200, "success")
  749. }
  750. }
  751. func QueryModelListForPredict(ctx *context.Context) {
  752. repoId := ctx.Repo.Repository.ID
  753. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  754. ListOptions: models.ListOptions{
  755. Page: -1,
  756. PageSize: -1,
  757. },
  758. RepoID: repoId,
  759. Type: -1,
  760. New: -1,
  761. })
  762. if err != nil {
  763. ctx.ServerError("Cloudbrain", err)
  764. return
  765. }
  766. log.Info("query return count=" + fmt.Sprint(count))
  767. nameList := make([]string, 0)
  768. nameMap := make(map[string][]*models.AiModelManage)
  769. for _, model := range modelResult {
  770. if _, value := nameMap[model.Name]; !value {
  771. models := make([]*models.AiModelManage, 0)
  772. models = append(models, model)
  773. nameMap[model.Name] = models
  774. nameList = append(nameList, model.Name)
  775. } else {
  776. nameMap[model.Name] = append(nameMap[model.Name], model)
  777. }
  778. }
  779. mapInterface := make(map[string]interface{})
  780. mapInterface["nameList"] = nameList
  781. mapInterface["nameMap"] = nameMap
  782. ctx.JSON(http.StatusOK, mapInterface)
  783. }
  784. func QueryModelFileForPredict(ctx *context.Context) {
  785. id := ctx.Query("ID")
  786. model, err := models.QueryModelById(id)
  787. if err == nil {
  788. if model.Type == models.TypeCloudBrainTwo {
  789. prefix := model.Path[len(setting.Bucket)+1:]
  790. fileinfos, _ := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, prefix)
  791. ctx.JSON(http.StatusOK, fileinfos)
  792. } else if model.Type == models.TypeCloudBrainOne {
  793. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  794. fileinfos, _ := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, prefix)
  795. ctx.JSON(http.StatusOK, fileinfos)
  796. }
  797. } else {
  798. log.Error("no such model!", err.Error())
  799. ctx.ServerError("no such model:", err)
  800. return
  801. }
  802. }
  803. func QueryOneLevelModelFile(ctx *context.Context) {
  804. id := ctx.Query("ID")
  805. parentDir := ctx.Query("parentDir")
  806. model, err := models.QueryModelById(id)
  807. if err != nil {
  808. log.Error("no such model!", err.Error())
  809. ctx.ServerError("no such model:", err)
  810. return
  811. }
  812. if model.Type == models.TypeCloudBrainTwo {
  813. log.Info("TypeCloudBrainTwo list model file.")
  814. prefix := model.Path[len(setting.Bucket)+1:]
  815. fileinfos, _ := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, prefix, parentDir)
  816. ctx.JSON(http.StatusOK, fileinfos)
  817. } else if model.Type == models.TypeCloudBrainOne {
  818. log.Info("TypeCloudBrainOne list model file.")
  819. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  820. fileinfos, _ := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, parentDir)
  821. ctx.JSON(http.StatusOK, fileinfos)
  822. }
  823. }