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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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 convert 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. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelmanage/convert_model")
  168. }
  169. func SaveModel(ctx *context.Context) {
  170. log.Info("save model start.")
  171. JobId := ctx.Query("JobId")
  172. VersionName := ctx.Query("VersionName")
  173. name := ctx.Query("Name")
  174. version := ctx.Query("Version")
  175. label := ctx.Query("Label")
  176. description := ctx.Query("Description")
  177. trainTaskCreate := ctx.QueryBool("trainTaskCreate")
  178. if !trainTaskCreate {
  179. if !ctx.Repo.CanWrite(models.UnitTypeModelManage) {
  180. //ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  181. ctx.JSON(403, ctx.Tr("repo.model_noright"))
  182. return
  183. }
  184. }
  185. if JobId == "" || VersionName == "" {
  186. ctx.Error(500, fmt.Sprintf("JobId or VersionName is null."))
  187. return
  188. }
  189. if name == "" || version == "" {
  190. ctx.Error(500, fmt.Sprintf("name or version is null."))
  191. return
  192. }
  193. err := saveModelByParameters(JobId, VersionName, name, version, label, description, ctx)
  194. if err != nil {
  195. log.Info("save model error." + err.Error())
  196. ctx.Error(500, fmt.Sprintf("save model error. %v", err))
  197. return
  198. }
  199. log.Info("save model end.")
  200. }
  201. func downloadModelFromCloudBrainTwo(modelUUID string, jobName string, parentDir string, trainUrl string) (string, int64, error) {
  202. objectkey := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir), "/")
  203. if trainUrl != "" {
  204. objectkey = strings.Trim(trainUrl[len(setting.Bucket)+1:], "/")
  205. }
  206. modelDbResult, err := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, objectkey, "")
  207. log.Info("bucket=" + setting.Bucket + " objectkey=" + objectkey)
  208. if err != nil {
  209. log.Info("get TrainJobListModel failed:", err)
  210. return "", 0, err
  211. }
  212. if len(modelDbResult) == 0 {
  213. return "", 0, errors.New("cannot create model, as model is empty.")
  214. }
  215. prefix := objectkey + "/"
  216. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(modelUUID) + "/"
  217. size, err := storage.ObsCopyManyFile(setting.Bucket, prefix, setting.Bucket, destKeyNamePrefix)
  218. dataActualPath := setting.Bucket + "/" + destKeyNamePrefix
  219. return dataActualPath, size, nil
  220. }
  221. func downloadModelFromCloudBrainOne(modelUUID string, jobName string, parentDir string, trainUrl string) (string, int64, error) {
  222. modelActualPath := storage.GetMinioPath(jobName, "/model/")
  223. log.Info("modelActualPath=" + modelActualPath)
  224. modelSrcPrefix := setting.CBCodePathPrefix + jobName + "/model/"
  225. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(modelUUID) + "/"
  226. bucketName := setting.Attachment.Minio.Bucket
  227. log.Info("destKeyNamePrefix=" + destKeyNamePrefix + " modelSrcPrefix=" + modelSrcPrefix + " bucket=" + bucketName)
  228. size, err := storage.MinioPathCopy(bucketName, modelSrcPrefix, destKeyNamePrefix)
  229. if err == nil {
  230. dataActualPath := bucketName + "/" + destKeyNamePrefix
  231. return dataActualPath, size, nil
  232. } else {
  233. return "", 0, nil
  234. }
  235. }
  236. func DeleteModelConvert(ctx *context.Context) {
  237. log.Info("delete model convert start.")
  238. id := ctx.Params(":id")
  239. err := models.DeleteModelConvertById(id)
  240. if err != nil {
  241. ctx.JSON(500, err.Error())
  242. } else {
  243. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelmanage/convert_model")
  244. }
  245. }
  246. func StopModelConvert(ctx *context.Context) {
  247. id := ctx.Params(":id")
  248. log.Info("stop model convert start.id=" + id)
  249. }
  250. func DeleteModel(ctx *context.Context) {
  251. log.Info("delete model start.")
  252. id := ctx.Query("ID")
  253. err := deleteModelByID(ctx, id)
  254. if err != nil {
  255. ctx.JSON(500, err.Error())
  256. } else {
  257. ctx.JSON(200, map[string]string{
  258. "result_code": "0",
  259. })
  260. }
  261. }
  262. func deleteModelByID(ctx *context.Context, id string) error {
  263. log.Info("delete model start. id=" + id)
  264. model, err := models.QueryModelById(id)
  265. if !isCanDelete(ctx, model.UserId) {
  266. return errors.New(ctx.Tr("repo.model_noright"))
  267. }
  268. if err == nil {
  269. log.Info("bucket=" + setting.Bucket + " path=" + model.Path)
  270. if strings.HasPrefix(model.Path, setting.Bucket+"/"+Model_prefix) {
  271. err := storage.ObsRemoveObject(setting.Bucket, model.Path[len(setting.Bucket)+1:])
  272. if err != nil {
  273. log.Info("Failed to delete model. id=" + id)
  274. return err
  275. }
  276. }
  277. err = models.DeleteModelById(id)
  278. if err == nil { //find a model to change new
  279. aimodels := models.QueryModelByName(model.Name, model.RepoId)
  280. if model.New == MODEL_LATEST {
  281. if len(aimodels) > 0 {
  282. //udpate status and version count
  283. models.ModifyModelNewProperty(aimodels[0].ID, MODEL_LATEST, len(aimodels))
  284. }
  285. } else {
  286. for _, tmpModel := range aimodels {
  287. if tmpModel.New == MODEL_LATEST {
  288. models.ModifyModelNewProperty(tmpModel.ID, MODEL_LATEST, len(aimodels))
  289. break
  290. }
  291. }
  292. }
  293. }
  294. }
  295. return err
  296. }
  297. func QueryModelByParameters(repoId int64, page int) ([]*models.AiModelManage, int64, error) {
  298. return models.QueryModel(&models.AiModelQueryOptions{
  299. ListOptions: models.ListOptions{
  300. Page: page,
  301. PageSize: setting.UI.IssuePagingNum,
  302. },
  303. RepoID: repoId,
  304. Type: -1,
  305. New: MODEL_LATEST,
  306. })
  307. }
  308. func DownloadMultiModelFile(ctx *context.Context) {
  309. log.Info("DownloadMultiModelFile start.")
  310. id := ctx.Query("ID")
  311. log.Info("id=" + id)
  312. task, err := models.QueryModelById(id)
  313. if err != nil {
  314. log.Error("no such model!", err.Error())
  315. ctx.ServerError("no such model:", err)
  316. return
  317. }
  318. if !isOper(ctx, task.UserId) {
  319. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  320. return
  321. }
  322. path := Model_prefix + models.AttachmentRelativePath(id) + "/"
  323. if task.Type == models.TypeCloudBrainTwo {
  324. downloadFromCloudBrainTwo(path, task, ctx, id)
  325. } else if task.Type == models.TypeCloudBrainOne {
  326. downloadFromCloudBrainOne(path, task, ctx, id)
  327. }
  328. }
  329. func downloadFromCloudBrainOne(path string, task *models.AiModelManage, ctx *context.Context, id string) {
  330. allFile, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, path)
  331. if err == nil {
  332. //count++
  333. models.ModifyModelDownloadCount(id)
  334. returnFileName := task.Name + "_" + task.Version + ".zip"
  335. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+url.QueryEscape(returnFileName))
  336. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  337. w := zip.NewWriter(ctx.Resp)
  338. defer w.Close()
  339. for _, oneFile := range allFile {
  340. if oneFile.IsDir {
  341. log.Info("zip dir name:" + oneFile.FileName)
  342. } else {
  343. log.Info("zip file name:" + oneFile.FileName)
  344. fDest, err := w.Create(oneFile.FileName)
  345. if err != nil {
  346. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  347. ctx.ServerError("download file failed:", err)
  348. return
  349. }
  350. body, err := storage.Attachments.Open(path + oneFile.FileName)
  351. if err != nil {
  352. log.Info("download file failed: %s\n", err.Error())
  353. ctx.ServerError("download file failed:", err)
  354. return
  355. } else {
  356. defer body.Close()
  357. p := make([]byte, 1024)
  358. var readErr error
  359. var readCount int
  360. // 读取对象内容
  361. for {
  362. readCount, readErr = body.Read(p)
  363. if readCount > 0 {
  364. fDest.Write(p[:readCount])
  365. }
  366. if readErr != nil {
  367. break
  368. }
  369. }
  370. }
  371. }
  372. }
  373. } else {
  374. log.Info("error,msg=" + err.Error())
  375. ctx.ServerError("no file to download.", err)
  376. }
  377. }
  378. func downloadFromCloudBrainTwo(path string, task *models.AiModelManage, ctx *context.Context, id string) {
  379. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  380. if err == nil {
  381. //count++
  382. models.ModifyModelDownloadCount(id)
  383. returnFileName := task.Name + "_" + task.Version + ".zip"
  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. } else {
  423. log.Info("error,msg=" + err.Error())
  424. ctx.ServerError("no file to download.", err)
  425. }
  426. }
  427. func QueryTrainJobVersionList(ctx *context.Context) {
  428. log.Info("query train job version list. start.")
  429. JobID := ctx.Query("JobID")
  430. VersionListTasks, count, err := models.QueryModelTrainJobVersionList(JobID)
  431. log.Info("query return count=" + fmt.Sprint(count))
  432. if err != nil {
  433. ctx.ServerError("QueryTrainJobList:", err)
  434. } else {
  435. ctx.JSON(200, VersionListTasks)
  436. }
  437. }
  438. func QueryTrainJobList(ctx *context.Context) {
  439. log.Info("query train job list. start.")
  440. repoId := ctx.QueryInt64("repoId")
  441. VersionListTasks, count, err := models.QueryModelTrainJobList(repoId)
  442. log.Info("query return count=" + fmt.Sprint(count))
  443. if err != nil {
  444. ctx.ServerError("QueryTrainJobList:", err)
  445. } else {
  446. ctx.JSON(200, VersionListTasks)
  447. }
  448. }
  449. func DownloadSingleModelFile(ctx *context.Context) {
  450. log.Info("DownloadSingleModelFile start.")
  451. id := ctx.Params(":ID")
  452. parentDir := ctx.Query("parentDir")
  453. fileName := ctx.Query("fileName")
  454. path := Model_prefix + models.AttachmentRelativePath(id) + "/" + parentDir + fileName
  455. task, err := models.QueryModelById(id)
  456. if err != nil {
  457. log.Error("no such model!", err.Error())
  458. ctx.ServerError("no such model:", err)
  459. return
  460. }
  461. if !isOper(ctx, task.UserId) {
  462. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  463. return
  464. }
  465. if task.Type == models.TypeCloudBrainTwo {
  466. if setting.PROXYURL != "" {
  467. body, err := storage.ObsDownloadAFile(setting.Bucket, path)
  468. if err != nil {
  469. log.Info("download error.")
  470. } else {
  471. //count++
  472. models.ModifyModelDownloadCount(id)
  473. defer body.Close()
  474. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  475. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  476. p := make([]byte, 1024)
  477. var readErr error
  478. var readCount int
  479. // 读取对象内容
  480. for {
  481. readCount, readErr = body.Read(p)
  482. if readCount > 0 {
  483. ctx.Resp.Write(p[:readCount])
  484. //fmt.Printf("%s", p[:readCount])
  485. }
  486. if readErr != nil {
  487. break
  488. }
  489. }
  490. }
  491. } else {
  492. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  493. if err != nil {
  494. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  495. ctx.ServerError("GetObsCreateSignedUrl", err)
  496. return
  497. }
  498. //count++
  499. models.ModifyModelDownloadCount(id)
  500. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  501. }
  502. } else if task.Type == models.TypeCloudBrainOne {
  503. log.Info("start to down load minio file.")
  504. url, err := storage.Attachments.PresignedGetURL(path, fileName)
  505. if err != nil {
  506. log.Error("Get minio get SignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  507. ctx.ServerError("Get minio get SignedUrl failed", err)
  508. return
  509. }
  510. models.ModifyModelDownloadCount(id)
  511. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  512. }
  513. }
  514. func ShowModelInfo(ctx *context.Context) {
  515. ctx.Data["ID"] = ctx.Query("ID")
  516. ctx.Data["name"] = ctx.Query("name")
  517. ctx.Data["isModelManage"] = true
  518. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  519. ctx.HTML(200, tplModelInfo)
  520. }
  521. func ShowModelConvertInfo(ctx *context.Context) {
  522. ctx.Data["ID"] = ctx.Query("ID")
  523. ctx.Data["name"] = ctx.Query("name")
  524. ctx.Data["isModelManage"] = true
  525. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  526. ctx.HTML(200, tplModelConvertInfo)
  527. }
  528. func ShowSingleModel(ctx *context.Context) {
  529. name := ctx.Query("name")
  530. log.Info("Show single ModelInfo start.name=" + name)
  531. models := models.QueryModelByName(name, ctx.Repo.Repository.ID)
  532. userIds := make([]int64, len(models))
  533. for i, model := range models {
  534. model.IsCanOper = isOper(ctx, model.UserId)
  535. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  536. userIds[i] = model.UserId
  537. }
  538. userNameMap := queryUserName(userIds)
  539. for _, model := range models {
  540. value := userNameMap[model.UserId]
  541. if value != nil {
  542. model.UserName = value.Name
  543. model.UserRelAvatarLink = value.RelAvatarLink()
  544. }
  545. }
  546. ctx.JSON(http.StatusOK, models)
  547. }
  548. func queryUserName(intSlice []int64) map[int64]*models.User {
  549. keys := make(map[int64]string)
  550. uniqueElements := []int64{}
  551. for _, entry := range intSlice {
  552. if _, value := keys[entry]; !value {
  553. keys[entry] = ""
  554. uniqueElements = append(uniqueElements, entry)
  555. }
  556. }
  557. result := make(map[int64]*models.User)
  558. userLists, err := models.GetUsersByIDs(uniqueElements)
  559. if err == nil {
  560. for _, user := range userLists {
  561. result[user.ID] = user
  562. }
  563. }
  564. return result
  565. }
  566. func ShowOneVersionOtherModel(ctx *context.Context) {
  567. repoId := ctx.Repo.Repository.ID
  568. name := ctx.Query("name")
  569. aimodels := models.QueryModelByName(name, repoId)
  570. userIds := make([]int64, len(aimodels))
  571. for i, model := range aimodels {
  572. model.IsCanOper = isOper(ctx, model.UserId)
  573. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  574. userIds[i] = model.UserId
  575. }
  576. userNameMap := queryUserName(userIds)
  577. for _, model := range aimodels {
  578. value := userNameMap[model.UserId]
  579. if value != nil {
  580. model.UserName = value.Name
  581. model.UserRelAvatarLink = value.RelAvatarLink()
  582. }
  583. }
  584. if len(aimodels) > 0 {
  585. ctx.JSON(200, aimodels[1:])
  586. } else {
  587. ctx.JSON(200, aimodels)
  588. }
  589. }
  590. func SetModelCount(ctx *context.Context) {
  591. repoId := ctx.Repo.Repository.ID
  592. Type := -1
  593. _, count, _ := models.QueryModel(&models.AiModelQueryOptions{
  594. ListOptions: models.ListOptions{
  595. Page: 1,
  596. PageSize: 2,
  597. },
  598. RepoID: repoId,
  599. Type: Type,
  600. New: MODEL_LATEST,
  601. })
  602. ctx.Data["MODEL_COUNT"] = count
  603. }
  604. func ShowModelTemplate(ctx *context.Context) {
  605. ctx.Data["isModelManage"] = true
  606. repoId := ctx.Repo.Repository.ID
  607. SetModelCount(ctx)
  608. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  609. _, trainCount, _ := models.QueryModelTrainJobList(repoId)
  610. log.Info("query train count=" + fmt.Sprint(trainCount))
  611. ctx.Data["TRAIN_COUNT"] = trainCount
  612. ctx.HTML(200, tplModelManageIndex)
  613. }
  614. func ConvertModelTemplate(ctx *context.Context) {
  615. ctx.Data["isModelManage"] = true
  616. ctx.Data["MODEL_COUNT"] = 0
  617. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  618. ctx.Data["TRAIN_COUNT"] = 0
  619. ShowModelConvertPageInfo(ctx)
  620. ctx.HTML(200, tplModelManageConvertIndex)
  621. }
  622. func isQueryRight(ctx *context.Context) bool {
  623. if ctx.Repo.Repository.IsPrivate {
  624. if ctx.Repo.CanRead(models.UnitTypeModelManage) || ctx.User.IsAdmin || ctx.Repo.IsAdmin() || ctx.Repo.IsOwner() {
  625. return true
  626. }
  627. return false
  628. } else {
  629. return true
  630. }
  631. }
  632. func isCanDelete(ctx *context.Context, modelUserId int64) bool {
  633. if ctx.User == nil {
  634. return false
  635. }
  636. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  637. return true
  638. }
  639. if ctx.Repo.IsOwner() {
  640. return true
  641. }
  642. return false
  643. }
  644. func isOper(ctx *context.Context, modelUserId int64) bool {
  645. if ctx.User == nil {
  646. return false
  647. }
  648. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  649. return true
  650. }
  651. return false
  652. }
  653. func ShowModelConvertPageInfo(ctx *context.Context) {
  654. log.Info("ShowModelConvertInfo start.")
  655. if !isQueryRight(ctx) {
  656. log.Info("no right.")
  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. log.Info("query db error." + err.Error())
  678. ctx.ServerError("Cloudbrain", err)
  679. return
  680. }
  681. userIds := make([]int64, len(modelResult))
  682. for i, model := range modelResult {
  683. model.IsCanOper = isOper(ctx, model.UserId)
  684. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  685. userIds[i] = model.UserId
  686. }
  687. userNameMap := queryUserName(userIds)
  688. for _, model := range modelResult {
  689. value := userNameMap[model.UserId]
  690. if value != nil {
  691. model.UserName = value.Name
  692. model.UserRelAvatarLink = value.RelAvatarLink()
  693. }
  694. }
  695. pager := context.NewPagination(int(count), page, pageSize, 5)
  696. ctx.Data["Page"] = pager
  697. ctx.Data["Tasks"] = modelResult
  698. }
  699. func ShowModelPageInfo(ctx *context.Context) {
  700. log.Info("ShowModelInfo start.")
  701. if !isQueryRight(ctx) {
  702. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  703. return
  704. }
  705. page := ctx.QueryInt("page")
  706. if page <= 0 {
  707. page = 1
  708. }
  709. pageSize := ctx.QueryInt("pageSize")
  710. if pageSize <= 0 {
  711. pageSize = setting.UI.IssuePagingNum
  712. }
  713. repoId := ctx.Repo.Repository.ID
  714. Type := -1
  715. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  716. ListOptions: models.ListOptions{
  717. Page: page,
  718. PageSize: pageSize,
  719. },
  720. RepoID: repoId,
  721. Type: Type,
  722. New: MODEL_LATEST,
  723. })
  724. if err != nil {
  725. ctx.ServerError("Cloudbrain", err)
  726. return
  727. }
  728. userIds := make([]int64, len(modelResult))
  729. for i, model := range modelResult {
  730. model.IsCanOper = isOper(ctx, model.UserId)
  731. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  732. userIds[i] = model.UserId
  733. }
  734. userNameMap := queryUserName(userIds)
  735. for _, model := range modelResult {
  736. value := userNameMap[model.UserId]
  737. if value != nil {
  738. model.UserName = value.Name
  739. model.UserRelAvatarLink = value.RelAvatarLink()
  740. }
  741. }
  742. mapInterface := make(map[string]interface{})
  743. mapInterface["data"] = modelResult
  744. mapInterface["count"] = count
  745. ctx.JSON(http.StatusOK, mapInterface)
  746. }
  747. func ModifyModel(id string, description string) error {
  748. err := models.ModifyModelDescription(id, description)
  749. if err == nil {
  750. log.Info("modify success.")
  751. } else {
  752. log.Info("Failed to modify.id=" + id + " desc=" + description + " error:" + err.Error())
  753. }
  754. return err
  755. }
  756. func ModifyModelInfo(ctx *context.Context) {
  757. log.Info("modify model start.")
  758. id := ctx.Query("ID")
  759. description := ctx.Query("Description")
  760. task, err := models.QueryModelById(id)
  761. if err != nil {
  762. log.Error("no such model!", err.Error())
  763. ctx.ServerError("no such model:", err)
  764. return
  765. }
  766. if !isOper(ctx, task.UserId) {
  767. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  768. //ctx.ServerError("no right.", errors.New(ctx.Tr("repo.model_noright")))
  769. return
  770. }
  771. err = ModifyModel(id, description)
  772. if err != nil {
  773. log.Info("modify error," + err.Error())
  774. ctx.ServerError("error.", err)
  775. } else {
  776. ctx.JSON(200, "success")
  777. }
  778. }
  779. func QueryModelListForPredict(ctx *context.Context) {
  780. repoId := ctx.Repo.Repository.ID
  781. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  782. ListOptions: models.ListOptions{
  783. Page: -1,
  784. PageSize: -1,
  785. },
  786. RepoID: repoId,
  787. Type: -1,
  788. New: -1,
  789. })
  790. if err != nil {
  791. ctx.ServerError("Cloudbrain", err)
  792. return
  793. }
  794. log.Info("query return count=" + fmt.Sprint(count))
  795. nameList := make([]string, 0)
  796. nameMap := make(map[string][]*models.AiModelManage)
  797. for _, model := range modelResult {
  798. if _, value := nameMap[model.Name]; !value {
  799. models := make([]*models.AiModelManage, 0)
  800. models = append(models, model)
  801. nameMap[model.Name] = models
  802. nameList = append(nameList, model.Name)
  803. } else {
  804. nameMap[model.Name] = append(nameMap[model.Name], model)
  805. }
  806. }
  807. mapInterface := make(map[string]interface{})
  808. mapInterface["nameList"] = nameList
  809. mapInterface["nameMap"] = nameMap
  810. ctx.JSON(http.StatusOK, mapInterface)
  811. }
  812. func QueryModelFileForPredict(ctx *context.Context) {
  813. id := ctx.Query("ID")
  814. model, err := models.QueryModelById(id)
  815. if err != nil {
  816. log.Error("no such model!", err.Error())
  817. ctx.ServerError("no such model:", err)
  818. return
  819. }
  820. if model.Type == models.TypeCloudBrainTwo {
  821. prefix := model.Path[len(setting.Bucket)+1:]
  822. fileinfos, _ := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, prefix)
  823. ctx.JSON(http.StatusOK, fileinfos)
  824. }
  825. }
  826. func QueryOneLevelModelFile(ctx *context.Context) {
  827. id := ctx.Query("ID")
  828. parentDir := ctx.Query("parentDir")
  829. model, err := models.QueryModelById(id)
  830. if err != nil {
  831. log.Error("no such model!", err.Error())
  832. ctx.ServerError("no such model:", err)
  833. return
  834. }
  835. if model.Type == models.TypeCloudBrainTwo {
  836. log.Info("TypeCloudBrainTwo list model file.")
  837. prefix := model.Path[len(setting.Bucket)+1:]
  838. fileinfos, _ := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, prefix, parentDir)
  839. ctx.JSON(http.StatusOK, fileinfos)
  840. } else if model.Type == models.TypeCloudBrainOne {
  841. log.Info("TypeCloudBrainOne list model file.")
  842. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  843. fileinfos, _ := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, parentDir)
  844. ctx.JSON(http.StatusOK, fileinfos)
  845. }
  846. }