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

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