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

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