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

3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  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.AiModelManageConvert{
  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.Query("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 DeleteModel(ctx *context.Context) {
  248. log.Info("delete model start.")
  249. id := ctx.Query("ID")
  250. err := deleteModelByID(ctx, id)
  251. if err != nil {
  252. ctx.JSON(500, err.Error())
  253. } else {
  254. ctx.JSON(200, map[string]string{
  255. "result_code": "0",
  256. })
  257. }
  258. }
  259. func deleteModelByID(ctx *context.Context, id string) error {
  260. log.Info("delete model start. id=" + id)
  261. model, err := models.QueryModelById(id)
  262. if !isCanDelete(ctx, model.UserId) {
  263. return errors.New(ctx.Tr("repo.model_noright"))
  264. }
  265. if err == nil {
  266. log.Info("bucket=" + setting.Bucket + " path=" + model.Path)
  267. if strings.HasPrefix(model.Path, setting.Bucket+"/"+Model_prefix) {
  268. err := storage.ObsRemoveObject(setting.Bucket, model.Path[len(setting.Bucket)+1:])
  269. if err != nil {
  270. log.Info("Failed to delete model. id=" + id)
  271. return err
  272. }
  273. }
  274. err = models.DeleteModelById(id)
  275. if err == nil { //find a model to change new
  276. aimodels := models.QueryModelByName(model.Name, model.RepoId)
  277. if model.New == MODEL_LATEST {
  278. if len(aimodels) > 0 {
  279. //udpate status and version count
  280. models.ModifyModelNewProperty(aimodels[0].ID, MODEL_LATEST, len(aimodels))
  281. }
  282. } else {
  283. for _, tmpModel := range aimodels {
  284. if tmpModel.New == MODEL_LATEST {
  285. models.ModifyModelNewProperty(tmpModel.ID, MODEL_LATEST, len(aimodels))
  286. break
  287. }
  288. }
  289. }
  290. }
  291. }
  292. return err
  293. }
  294. func QueryModelByParameters(repoId int64, page int) ([]*models.AiModelManage, int64, error) {
  295. return models.QueryModel(&models.AiModelQueryOptions{
  296. ListOptions: models.ListOptions{
  297. Page: page,
  298. PageSize: setting.UI.IssuePagingNum,
  299. },
  300. RepoID: repoId,
  301. Type: -1,
  302. New: MODEL_LATEST,
  303. })
  304. }
  305. func DownloadMultiModelFile(ctx *context.Context) {
  306. log.Info("DownloadMultiModelFile start.")
  307. id := ctx.Query("ID")
  308. log.Info("id=" + id)
  309. task, err := models.QueryModelById(id)
  310. if err != nil {
  311. log.Error("no such model!", err.Error())
  312. ctx.ServerError("no such model:", err)
  313. return
  314. }
  315. if !isOper(ctx, task.UserId) {
  316. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  317. return
  318. }
  319. path := Model_prefix + models.AttachmentRelativePath(id) + "/"
  320. if task.Type == models.TypeCloudBrainTwo {
  321. downloadFromCloudBrainTwo(path, task, ctx, id)
  322. } else if task.Type == models.TypeCloudBrainOne {
  323. downloadFromCloudBrainOne(path, task, ctx, id)
  324. }
  325. }
  326. func downloadFromCloudBrainOne(path string, task *models.AiModelManage, ctx *context.Context, id string) {
  327. allFile, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, path)
  328. if err == nil {
  329. //count++
  330. models.ModifyModelDownloadCount(id)
  331. returnFileName := task.Name + "_" + task.Version + ".zip"
  332. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+url.QueryEscape(returnFileName))
  333. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  334. w := zip.NewWriter(ctx.Resp)
  335. defer w.Close()
  336. for _, oneFile := range allFile {
  337. if oneFile.IsDir {
  338. log.Info("zip dir name:" + oneFile.FileName)
  339. } else {
  340. log.Info("zip file name:" + oneFile.FileName)
  341. fDest, err := w.Create(oneFile.FileName)
  342. if err != nil {
  343. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  344. ctx.ServerError("download file failed:", err)
  345. return
  346. }
  347. body, err := storage.Attachments.Open(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. } else {
  371. log.Info("error,msg=" + err.Error())
  372. ctx.ServerError("no file to download.", err)
  373. }
  374. }
  375. func downloadFromCloudBrainTwo(path string, task *models.AiModelManage, ctx *context.Context, id string) {
  376. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  377. if err == nil {
  378. //count++
  379. models.ModifyModelDownloadCount(id)
  380. returnFileName := task.Name + "_" + task.Version + ".zip"
  381. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+url.QueryEscape(returnFileName))
  382. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  383. w := zip.NewWriter(ctx.Resp)
  384. defer w.Close()
  385. for _, oneFile := range allFile {
  386. if oneFile.IsDir {
  387. log.Info("zip dir name:" + oneFile.FileName)
  388. } else {
  389. log.Info("zip file name:" + oneFile.FileName)
  390. fDest, err := w.Create(oneFile.FileName)
  391. if err != nil {
  392. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  393. ctx.ServerError("download file failed:", err)
  394. return
  395. }
  396. body, err := storage.ObsDownloadAFile(setting.Bucket, path+oneFile.FileName)
  397. if err != nil {
  398. log.Info("download file failed: %s\n", err.Error())
  399. ctx.ServerError("download file failed:", err)
  400. return
  401. } else {
  402. defer body.Close()
  403. p := make([]byte, 1024)
  404. var readErr error
  405. var readCount int
  406. // 读取对象内容
  407. for {
  408. readCount, readErr = body.Read(p)
  409. if readCount > 0 {
  410. fDest.Write(p[:readCount])
  411. }
  412. if readErr != nil {
  413. break
  414. }
  415. }
  416. }
  417. }
  418. }
  419. } else {
  420. log.Info("error,msg=" + err.Error())
  421. ctx.ServerError("no file to download.", err)
  422. }
  423. }
  424. func QueryTrainJobVersionList(ctx *context.Context) {
  425. log.Info("query train job version list. start.")
  426. JobID := ctx.Query("JobID")
  427. VersionListTasks, count, err := models.QueryModelTrainJobVersionList(JobID)
  428. log.Info("query return count=" + fmt.Sprint(count))
  429. if err != nil {
  430. ctx.ServerError("QueryTrainJobList:", err)
  431. } else {
  432. ctx.JSON(200, VersionListTasks)
  433. }
  434. }
  435. func QueryTrainJobList(ctx *context.Context) {
  436. log.Info("query train job list. start.")
  437. repoId := ctx.QueryInt64("repoId")
  438. VersionListTasks, count, err := models.QueryModelTrainJobList(repoId)
  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 DownloadSingleModelFile(ctx *context.Context) {
  447. log.Info("DownloadSingleModelFile start.")
  448. id := ctx.Params(":ID")
  449. parentDir := ctx.Query("parentDir")
  450. fileName := ctx.Query("fileName")
  451. path := Model_prefix + models.AttachmentRelativePath(id) + "/" + parentDir + fileName
  452. task, err := models.QueryModelById(id)
  453. if err != nil {
  454. log.Error("no such model!", err.Error())
  455. ctx.ServerError("no such model:", err)
  456. return
  457. }
  458. if !isOper(ctx, task.UserId) {
  459. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  460. return
  461. }
  462. if task.Type == models.TypeCloudBrainTwo {
  463. if setting.PROXYURL != "" {
  464. body, err := storage.ObsDownloadAFile(setting.Bucket, path)
  465. if err != nil {
  466. log.Info("download error.")
  467. } else {
  468. //count++
  469. models.ModifyModelDownloadCount(id)
  470. defer body.Close()
  471. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  472. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  473. p := make([]byte, 1024)
  474. var readErr error
  475. var readCount int
  476. // 读取对象内容
  477. for {
  478. readCount, readErr = body.Read(p)
  479. if readCount > 0 {
  480. ctx.Resp.Write(p[:readCount])
  481. //fmt.Printf("%s", p[:readCount])
  482. }
  483. if readErr != nil {
  484. break
  485. }
  486. }
  487. }
  488. } else {
  489. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  490. if err != nil {
  491. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  492. ctx.ServerError("GetObsCreateSignedUrl", err)
  493. return
  494. }
  495. //count++
  496. models.ModifyModelDownloadCount(id)
  497. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  498. }
  499. } else if task.Type == models.TypeCloudBrainOne {
  500. log.Info("start to down load minio file.")
  501. url, err := storage.Attachments.PresignedGetURL(path, fileName)
  502. if err != nil {
  503. log.Error("Get minio get SignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  504. ctx.ServerError("Get minio get SignedUrl failed", err)
  505. return
  506. }
  507. models.ModifyModelDownloadCount(id)
  508. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  509. }
  510. }
  511. func ShowModelInfo(ctx *context.Context) {
  512. ctx.Data["ID"] = ctx.Query("ID")
  513. ctx.Data["name"] = ctx.Query("name")
  514. ctx.Data["isModelManage"] = true
  515. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  516. ctx.HTML(200, tplModelInfo)
  517. }
  518. func ShowModelConvertInfo(ctx *context.Context) {
  519. ctx.Data["ID"] = ctx.Query("ID")
  520. ctx.Data["name"] = ctx.Query("name")
  521. ctx.Data["isModelManage"] = true
  522. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  523. ctx.HTML(200, tplModelConvertInfo)
  524. }
  525. func ShowSingleModel(ctx *context.Context) {
  526. name := ctx.Query("name")
  527. log.Info("Show single ModelInfo start.name=" + name)
  528. models := models.QueryModelByName(name, ctx.Repo.Repository.ID)
  529. userIds := make([]int64, len(models))
  530. for i, model := range models {
  531. model.IsCanOper = isOper(ctx, model.UserId)
  532. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  533. userIds[i] = model.UserId
  534. }
  535. userNameMap := queryUserName(userIds)
  536. for _, model := range models {
  537. value := userNameMap[model.UserId]
  538. if value != nil {
  539. model.UserName = value.Name
  540. model.UserRelAvatarLink = value.RelAvatarLink()
  541. }
  542. }
  543. ctx.JSON(http.StatusOK, models)
  544. }
  545. func queryUserName(intSlice []int64) map[int64]*models.User {
  546. keys := make(map[int64]string)
  547. uniqueElements := []int64{}
  548. for _, entry := range intSlice {
  549. if _, value := keys[entry]; !value {
  550. keys[entry] = ""
  551. uniqueElements = append(uniqueElements, entry)
  552. }
  553. }
  554. result := make(map[int64]*models.User)
  555. userLists, err := models.GetUsersByIDs(uniqueElements)
  556. if err == nil {
  557. for _, user := range userLists {
  558. result[user.ID] = user
  559. }
  560. }
  561. return result
  562. }
  563. func ShowOneVersionOtherModel(ctx *context.Context) {
  564. repoId := ctx.Repo.Repository.ID
  565. name := ctx.Query("name")
  566. aimodels := models.QueryModelByName(name, repoId)
  567. userIds := make([]int64, len(aimodels))
  568. for i, model := range aimodels {
  569. model.IsCanOper = isOper(ctx, model.UserId)
  570. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  571. userIds[i] = model.UserId
  572. }
  573. userNameMap := queryUserName(userIds)
  574. for _, model := range aimodels {
  575. value := userNameMap[model.UserId]
  576. if value != nil {
  577. model.UserName = value.Name
  578. model.UserRelAvatarLink = value.RelAvatarLink()
  579. }
  580. }
  581. if len(aimodels) > 0 {
  582. ctx.JSON(200, aimodels[1:])
  583. } else {
  584. ctx.JSON(200, aimodels)
  585. }
  586. }
  587. func SetModelCount(ctx *context.Context) {
  588. repoId := ctx.Repo.Repository.ID
  589. Type := -1
  590. _, count, _ := models.QueryModel(&models.AiModelQueryOptions{
  591. ListOptions: models.ListOptions{
  592. Page: 1,
  593. PageSize: 2,
  594. },
  595. RepoID: repoId,
  596. Type: Type,
  597. New: MODEL_LATEST,
  598. })
  599. ctx.Data["MODEL_COUNT"] = count
  600. }
  601. func ShowModelTemplate(ctx *context.Context) {
  602. ctx.Data["isModelManage"] = true
  603. repoId := ctx.Repo.Repository.ID
  604. SetModelCount(ctx)
  605. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  606. _, trainCount, _ := models.QueryModelTrainJobList(repoId)
  607. log.Info("query train count=" + fmt.Sprint(trainCount))
  608. ctx.Data["TRAIN_COUNT"] = trainCount
  609. ctx.HTML(200, tplModelManageIndex)
  610. }
  611. func ConvertModelTemplate(ctx *context.Context) {
  612. ctx.Data["isModelManage"] = true
  613. ctx.Data["MODEL_COUNT"] = 0
  614. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  615. ctx.Data["TRAIN_COUNT"] = 0
  616. ctx.HTML(200, tplModelManageConvertIndex)
  617. }
  618. func isQueryRight(ctx *context.Context) bool {
  619. if ctx.Repo.Repository.IsPrivate {
  620. if ctx.Repo.CanRead(models.UnitTypeModelManage) || ctx.User.IsAdmin || ctx.Repo.IsAdmin() || ctx.Repo.IsOwner() {
  621. return true
  622. }
  623. return false
  624. } else {
  625. return true
  626. }
  627. }
  628. func isCanDelete(ctx *context.Context, modelUserId int64) bool {
  629. if ctx.User == nil {
  630. return false
  631. }
  632. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  633. return true
  634. }
  635. if ctx.Repo.IsOwner() {
  636. return true
  637. }
  638. return false
  639. }
  640. func isOper(ctx *context.Context, modelUserId int64) bool {
  641. if ctx.User == nil {
  642. return false
  643. }
  644. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  645. return true
  646. }
  647. return false
  648. }
  649. func ShowModelConvertPageInfo(ctx *context.Context) {
  650. log.Info("ShowModelConvertInfo start.")
  651. if !isQueryRight(ctx) {
  652. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  653. return
  654. }
  655. page := ctx.QueryInt("page")
  656. if page <= 0 {
  657. page = 1
  658. }
  659. pageSize := ctx.QueryInt("pageSize")
  660. if pageSize <= 0 {
  661. pageSize = setting.UI.IssuePagingNum
  662. }
  663. repoId := ctx.Repo.Repository.ID
  664. modelResult, count, err := models.QueryModelConvert(&models.AiModelQueryOptions{
  665. ListOptions: models.ListOptions{
  666. Page: page,
  667. PageSize: pageSize,
  668. },
  669. RepoID: repoId,
  670. })
  671. if err != nil {
  672. ctx.ServerError("Cloudbrain", err)
  673. return
  674. }
  675. userIds := make([]int64, len(modelResult))
  676. for i, model := range modelResult {
  677. model.IsCanOper = isOper(ctx, model.UserId)
  678. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  679. userIds[i] = model.UserId
  680. }
  681. userNameMap := queryUserName(userIds)
  682. for _, model := range modelResult {
  683. value := userNameMap[model.UserId]
  684. if value != nil {
  685. model.UserName = value.Name
  686. model.UserRelAvatarLink = value.RelAvatarLink()
  687. }
  688. }
  689. ctx.Data["Tasks"] = modelResult
  690. }
  691. func ShowModelPageInfo(ctx *context.Context) {
  692. log.Info("ShowModelInfo start.")
  693. if !isQueryRight(ctx) {
  694. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  695. return
  696. }
  697. page := ctx.QueryInt("page")
  698. if page <= 0 {
  699. page = 1
  700. }
  701. pageSize := ctx.QueryInt("pageSize")
  702. if pageSize <= 0 {
  703. pageSize = setting.UI.IssuePagingNum
  704. }
  705. repoId := ctx.Repo.Repository.ID
  706. Type := -1
  707. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  708. ListOptions: models.ListOptions{
  709. Page: page,
  710. PageSize: pageSize,
  711. },
  712. RepoID: repoId,
  713. Type: Type,
  714. New: MODEL_LATEST,
  715. })
  716. if err != nil {
  717. ctx.ServerError("Cloudbrain", err)
  718. return
  719. }
  720. userIds := make([]int64, len(modelResult))
  721. for i, model := range modelResult {
  722. model.IsCanOper = isOper(ctx, model.UserId)
  723. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  724. userIds[i] = model.UserId
  725. }
  726. userNameMap := queryUserName(userIds)
  727. for _, model := range modelResult {
  728. value := userNameMap[model.UserId]
  729. if value != nil {
  730. model.UserName = value.Name
  731. model.UserRelAvatarLink = value.RelAvatarLink()
  732. }
  733. }
  734. mapInterface := make(map[string]interface{})
  735. mapInterface["data"] = modelResult
  736. mapInterface["count"] = count
  737. ctx.JSON(http.StatusOK, mapInterface)
  738. }
  739. func ModifyModel(id string, description string) error {
  740. err := models.ModifyModelDescription(id, description)
  741. if err == nil {
  742. log.Info("modify success.")
  743. } else {
  744. log.Info("Failed to modify.id=" + id + " desc=" + description + " error:" + err.Error())
  745. }
  746. return err
  747. }
  748. func ModifyModelInfo(ctx *context.Context) {
  749. log.Info("modify model start.")
  750. id := ctx.Query("ID")
  751. description := ctx.Query("Description")
  752. task, err := models.QueryModelById(id)
  753. if err != nil {
  754. log.Error("no such model!", err.Error())
  755. ctx.ServerError("no such model:", err)
  756. return
  757. }
  758. if !isOper(ctx, task.UserId) {
  759. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  760. //ctx.ServerError("no right.", errors.New(ctx.Tr("repo.model_noright")))
  761. return
  762. }
  763. err = ModifyModel(id, description)
  764. if err != nil {
  765. log.Info("modify error," + err.Error())
  766. ctx.ServerError("error.", err)
  767. } else {
  768. ctx.JSON(200, "success")
  769. }
  770. }
  771. func QueryModelListForPredict(ctx *context.Context) {
  772. repoId := ctx.Repo.Repository.ID
  773. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  774. ListOptions: models.ListOptions{
  775. Page: -1,
  776. PageSize: -1,
  777. },
  778. RepoID: repoId,
  779. Type: -1,
  780. New: -1,
  781. })
  782. if err != nil {
  783. ctx.ServerError("Cloudbrain", err)
  784. return
  785. }
  786. log.Info("query return count=" + fmt.Sprint(count))
  787. nameList := make([]string, 0)
  788. nameMap := make(map[string][]*models.AiModelManage)
  789. for _, model := range modelResult {
  790. if _, value := nameMap[model.Name]; !value {
  791. models := make([]*models.AiModelManage, 0)
  792. models = append(models, model)
  793. nameMap[model.Name] = models
  794. nameList = append(nameList, model.Name)
  795. } else {
  796. nameMap[model.Name] = append(nameMap[model.Name], model)
  797. }
  798. }
  799. mapInterface := make(map[string]interface{})
  800. mapInterface["nameList"] = nameList
  801. mapInterface["nameMap"] = nameMap
  802. ctx.JSON(http.StatusOK, mapInterface)
  803. }
  804. func QueryModelFileForPredict(ctx *context.Context) {
  805. id := ctx.Query("ID")
  806. model, err := models.QueryModelById(id)
  807. if err != nil {
  808. log.Error("no such model!", err.Error())
  809. ctx.ServerError("no such model:", err)
  810. return
  811. }
  812. if model.Type == models.TypeCloudBrainTwo {
  813. prefix := model.Path[len(setting.Bucket)+1:]
  814. fileinfos, _ := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, prefix)
  815. ctx.JSON(http.StatusOK, fileinfos)
  816. }
  817. }
  818. func QueryOneLevelModelFile(ctx *context.Context) {
  819. id := ctx.Query("ID")
  820. parentDir := ctx.Query("parentDir")
  821. model, err := models.QueryModelById(id)
  822. if err != nil {
  823. log.Error("no such model!", err.Error())
  824. ctx.ServerError("no such model:", err)
  825. return
  826. }
  827. if model.Type == models.TypeCloudBrainTwo {
  828. log.Info("TypeCloudBrainTwo list model file.")
  829. prefix := model.Path[len(setting.Bucket)+1:]
  830. fileinfos, _ := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, prefix, parentDir)
  831. ctx.JSON(http.StatusOK, fileinfos)
  832. } else if model.Type == models.TypeCloudBrainOne {
  833. log.Info("TypeCloudBrainOne list model file.")
  834. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  835. fileinfos, _ := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, parentDir)
  836. ctx.JSON(http.StatusOK, fileinfos)
  837. }
  838. }