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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. package repo
  2. import (
  3. "archive/zip"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "path"
  9. "strings"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/context"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/setting"
  14. "code.gitea.io/gitea/modules/storage"
  15. uuid "github.com/satori/go.uuid"
  16. )
  17. const (
  18. Model_prefix = "aimodels/"
  19. tplModelManageIndex = "repo/modelmanage/index"
  20. tplModelManageDownload = "repo/modelmanage/download"
  21. tplModelInfo = "repo/modelmanage/showinfo"
  22. MODEL_LATEST = 1
  23. MODEL_NOT_LATEST = 0
  24. )
  25. func saveModelByParameters(jobId string, versionName string, name string, version string, label string, description string, ctx *context.Context) error {
  26. aiTask, err := models.GetCloudbrainByJobIDAndVersionName(jobId, versionName)
  27. //aiTask, err := models.GetCloudbrainByJobID(jobId)
  28. if err != nil {
  29. log.Info("query task error." + err.Error())
  30. return err
  31. }
  32. uuid := uuid.NewV4()
  33. id := uuid.String()
  34. modelPath := id
  35. var lastNewModelId string
  36. var modelSize int64
  37. cloudType := models.TypeCloudBrainTwo
  38. log.Info("find task name:" + aiTask.JobName)
  39. aimodels := models.QueryModelByName(name, aiTask.RepoID)
  40. if len(aimodels) > 0 {
  41. for _, model := range aimodels {
  42. if model.Version == version {
  43. return errors.New(ctx.Tr("repo.model.manage.create_error"))
  44. }
  45. if model.New == MODEL_LATEST {
  46. lastNewModelId = model.ID
  47. }
  48. }
  49. }
  50. cloudType = aiTask.Type
  51. //download model zip //train type
  52. if cloudType == models.TypeCloudBrainTwo {
  53. modelPath, modelSize, err = downloadModelFromCloudBrainTwo(id, aiTask.JobName, "")
  54. if err != nil {
  55. log.Info("download model from CloudBrainTwo faild." + err.Error())
  56. return err
  57. }
  58. }
  59. accuracy := make(map[string]string)
  60. accuracy["F1"] = ""
  61. accuracy["Recall"] = ""
  62. accuracy["Accuracy"] = ""
  63. accuracy["Precision"] = ""
  64. accuracyJson, _ := json.Marshal(accuracy)
  65. log.Info("accuracyJson=" + string(accuracyJson))
  66. aiTaskJson, _ := json.Marshal(aiTask)
  67. //taskConfigInfo,err := models.GetCloudbrainByJobIDAndVersionName(jobId,aiTask.VersionName)
  68. model := &models.AiModelManage{
  69. ID: id,
  70. Version: version,
  71. VersionCount: len(aimodels) + 1,
  72. Label: label,
  73. Name: name,
  74. Description: description,
  75. New: MODEL_LATEST,
  76. Type: cloudType,
  77. Path: modelPath,
  78. Size: modelSize,
  79. AttachmentId: aiTask.Uuid,
  80. RepoId: aiTask.RepoID,
  81. UserId: ctx.User.ID,
  82. UserName: ctx.User.Name,
  83. UserRelAvatarLink: ctx.User.RelAvatarLink(),
  84. CodeBranch: aiTask.BranchName,
  85. CodeCommitID: aiTask.CommitID,
  86. Engine: aiTask.EngineID,
  87. TrainTaskInfo: string(aiTaskJson),
  88. Accuracy: string(accuracyJson),
  89. }
  90. err = models.SaveModelToDb(model)
  91. if err != nil {
  92. return err
  93. }
  94. if len(lastNewModelId) > 0 {
  95. //udpate status and version count
  96. models.ModifyModelNewProperty(lastNewModelId, MODEL_NOT_LATEST, 0)
  97. }
  98. log.Info("save model end.")
  99. return nil
  100. }
  101. func SaveModel(ctx *context.Context) {
  102. log.Info("save model start.")
  103. JobId := ctx.Query("JobId")
  104. VersionName := ctx.Query("VersionName")
  105. name := ctx.Query("Name")
  106. version := ctx.Query("Version")
  107. label := ctx.Query("Label")
  108. description := ctx.Query("Description")
  109. if !ctx.Repo.CanWrite(models.UnitTypeCloudBrain) {
  110. ctx.ServerError("No right.", errors.New(ctx.Tr("repo.model_noright")))
  111. return
  112. }
  113. if JobId == "" || VersionName == "" {
  114. ctx.Error(500, fmt.Sprintf("JobId or VersionName is null."))
  115. return
  116. }
  117. if name == "" || version == "" {
  118. ctx.Error(500, fmt.Sprintf("name or version is null."))
  119. return
  120. }
  121. err := saveModelByParameters(JobId, VersionName, name, version, label, description, ctx)
  122. if err != nil {
  123. log.Info("save model error." + err.Error())
  124. ctx.Error(500, fmt.Sprintf("save model error. %v", err))
  125. return
  126. }
  127. log.Info("save model end.")
  128. }
  129. func downloadModelFromCloudBrainTwo(modelUUID string, jobName string, parentDir string) (string, int64, error) {
  130. objectkey := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir), "/")
  131. modelDbResult, err := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, objectkey, "")
  132. log.Info("bucket=" + setting.Bucket + " objectkey=" + objectkey)
  133. if err != nil {
  134. log.Info("get TrainJobListModel failed:", err)
  135. return "", 0, err
  136. }
  137. if len(modelDbResult) == 0 {
  138. return "", 0, errors.New("cannot create model, as model is empty.")
  139. }
  140. prefix := objectkey + "/"
  141. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(modelUUID) + "/"
  142. size, err := storage.ObsCopyManyFile(setting.Bucket, prefix, setting.Bucket, destKeyNamePrefix)
  143. dataActualPath := setting.Bucket + "/" + destKeyNamePrefix
  144. return dataActualPath, size, nil
  145. }
  146. func DeleteModel(ctx *context.Context) {
  147. log.Info("delete model start.")
  148. id := ctx.Query("ID")
  149. err := deleteModelByID(ctx, id)
  150. if err != nil {
  151. ctx.JSON(500, err.Error())
  152. } else {
  153. ctx.JSON(200, map[string]string{
  154. "result_code": "0",
  155. })
  156. }
  157. }
  158. func isCanDeleteOrDownload(ctx *context.Context, model *models.AiModelManage) bool {
  159. if ctx.User.IsAdmin || ctx.User.ID == model.UserId {
  160. return true
  161. }
  162. if ctx.Repo.IsOwner() {
  163. return true
  164. }
  165. return false
  166. }
  167. func deleteModelByID(ctx *context.Context, id string) error {
  168. log.Info("delete model start. id=" + id)
  169. model, err := models.QueryModelById(id)
  170. if !isCanDeleteOrDownload(ctx, model) {
  171. return errors.New(ctx.Tr("repo.model_noright"))
  172. }
  173. if err == nil {
  174. log.Info("bucket=" + setting.Bucket + " path=" + model.Path)
  175. if strings.HasPrefix(model.Path, setting.Bucket+"/"+Model_prefix) {
  176. err := storage.ObsRemoveObject(setting.Bucket, model.Path[len(setting.Bucket)+1:])
  177. if err != nil {
  178. log.Info("Failed to delete model. id=" + id)
  179. return err
  180. }
  181. }
  182. err = models.DeleteModelById(id)
  183. if err == nil { //find a model to change new
  184. aimodels := models.QueryModelByName(model.Name, model.RepoId)
  185. if model.New == MODEL_LATEST {
  186. if len(aimodels) > 0 {
  187. //udpate status and version count
  188. models.ModifyModelNewProperty(aimodels[0].ID, MODEL_LATEST, len(aimodels))
  189. }
  190. } else {
  191. for _, tmpModel := range aimodels {
  192. if tmpModel.New == MODEL_LATEST {
  193. models.ModifyModelNewProperty(tmpModel.ID, MODEL_LATEST, len(aimodels))
  194. break
  195. }
  196. }
  197. }
  198. }
  199. }
  200. return err
  201. }
  202. func QueryModelByParameters(repoId int64, page int) ([]*models.AiModelManage, int64, error) {
  203. return models.QueryModel(&models.AiModelQueryOptions{
  204. ListOptions: models.ListOptions{
  205. Page: page,
  206. PageSize: setting.UI.IssuePagingNum,
  207. },
  208. RepoID: repoId,
  209. Type: -1,
  210. New: MODEL_LATEST,
  211. })
  212. }
  213. func DownloadMultiModelFile(ctx *context.Context) {
  214. log.Info("DownloadMultiModelFile start.")
  215. id := ctx.Query("ID")
  216. log.Info("id=" + id)
  217. task, err := models.QueryModelById(id)
  218. if err != nil {
  219. log.Error("no such model!", err.Error())
  220. ctx.ServerError("no such model:", err)
  221. return
  222. }
  223. if !isCanDeleteOrDownload(ctx, task) {
  224. ctx.ServerError("no right.", errors.New(ctx.Tr("repo.model_noright")))
  225. return
  226. }
  227. path := Model_prefix + models.AttachmentRelativePath(id) + "/"
  228. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  229. if err == nil {
  230. //count++
  231. models.ModifyModelDownloadCount(id)
  232. returnFileName := task.Name + "_" + task.Version + ".zip"
  233. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+returnFileName)
  234. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  235. w := zip.NewWriter(ctx.Resp)
  236. defer w.Close()
  237. for _, oneFile := range allFile {
  238. if oneFile.IsDir {
  239. log.Info("zip dir name:" + oneFile.FileName)
  240. } else {
  241. log.Info("zip file name:" + oneFile.FileName)
  242. fDest, err := w.Create(oneFile.FileName)
  243. if err != nil {
  244. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  245. ctx.ServerError("download file failed:", err)
  246. return
  247. }
  248. body, err := storage.ObsDownloadAFile(setting.Bucket, path+oneFile.FileName)
  249. if err != nil {
  250. log.Info("download file failed: %s\n", err.Error())
  251. ctx.ServerError("download file failed:", err)
  252. return
  253. } else {
  254. defer body.Close()
  255. p := make([]byte, 1024)
  256. var readErr error
  257. var readCount int
  258. // 读取对象内容
  259. for {
  260. readCount, readErr = body.Read(p)
  261. if readCount > 0 {
  262. fDest.Write(p[:readCount])
  263. }
  264. if readErr != nil {
  265. break
  266. }
  267. }
  268. }
  269. }
  270. }
  271. } else {
  272. log.Info("error,msg=" + err.Error())
  273. ctx.ServerError("no file to download.", err)
  274. }
  275. }
  276. func QueryTrainJobVersionList(ctx *context.Context) {
  277. log.Info("query train job version list. start.")
  278. JobID := ctx.Query("JobID")
  279. VersionListTasks, count, err := models.QueryModelTrainJobVersionList(JobID)
  280. log.Info("query return count=" + fmt.Sprint(count))
  281. if err != nil {
  282. ctx.ServerError("QueryTrainJobList:", err)
  283. } else {
  284. ctx.JSON(200, VersionListTasks)
  285. }
  286. }
  287. func QueryTrainJobList(ctx *context.Context) {
  288. log.Info("query train job list. start.")
  289. repoId := ctx.QueryInt64("repoId")
  290. VersionListTasks, count, err := models.QueryModelTrainJobList(repoId)
  291. log.Info("query return count=" + fmt.Sprint(count))
  292. if err != nil {
  293. ctx.ServerError("QueryTrainJobList:", err)
  294. } else {
  295. ctx.JSON(200, VersionListTasks)
  296. }
  297. }
  298. func DownloadSingleModelFile(ctx *context.Context) {
  299. log.Info("DownloadSingleModelFile start.")
  300. id := ctx.Params(":ID")
  301. parentDir := ctx.Query("parentDir")
  302. fileName := ctx.Query("fileName")
  303. path := Model_prefix + models.AttachmentRelativePath(id) + "/" + parentDir + fileName
  304. if setting.PROXYURL != "" {
  305. body, err := storage.ObsDownloadAFile(setting.Bucket, path)
  306. if err != nil {
  307. log.Info("download error.")
  308. } else {
  309. //count++
  310. models.ModifyModelDownloadCount(id)
  311. defer body.Close()
  312. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  313. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  314. p := make([]byte, 1024)
  315. var readErr error
  316. var readCount int
  317. // 读取对象内容
  318. for {
  319. readCount, readErr = body.Read(p)
  320. if readCount > 0 {
  321. ctx.Resp.Write(p[:readCount])
  322. //fmt.Printf("%s", p[:readCount])
  323. }
  324. if readErr != nil {
  325. break
  326. }
  327. }
  328. }
  329. } else {
  330. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  331. if err != nil {
  332. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  333. ctx.ServerError("GetObsCreateSignedUrl", err)
  334. return
  335. }
  336. //count++
  337. models.ModifyModelDownloadCount(id)
  338. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  339. }
  340. }
  341. func ShowModelInfo(ctx *context.Context) {
  342. ctx.Data["ID"] = ctx.Query("ID")
  343. ctx.Data["name"] = ctx.Query("name")
  344. ctx.Data["isModelManage"] = true
  345. ctx.HTML(200, tplModelInfo)
  346. }
  347. func ShowSingleModel(ctx *context.Context) {
  348. name := ctx.Query("name")
  349. log.Info("Show single ModelInfo start.name=" + name)
  350. models := models.QueryModelByName(name, ctx.Repo.Repository.ID)
  351. ctx.JSON(http.StatusOK, models)
  352. }
  353. func ShowOneVersionOtherModel(ctx *context.Context) {
  354. repoId := ctx.Repo.Repository.ID
  355. name := ctx.Query("name")
  356. aimodels := models.QueryModelByName(name, repoId)
  357. for _, model := range aimodels {
  358. log.Info("model=" + model.Name)
  359. log.Info("model.UserId=" + fmt.Sprint(model.UserId))
  360. model.IsCanOper = isOper(ctx, model.UserId)
  361. }
  362. if len(aimodels) > 0 {
  363. ctx.JSON(200, aimodels[1:])
  364. } else {
  365. ctx.JSON(200, aimodels)
  366. }
  367. }
  368. func ShowModelTemplate(ctx *context.Context) {
  369. ctx.Data["isModelManage"] = true
  370. ctx.HTML(200, tplModelManageIndex)
  371. }
  372. func isQueryRight(ctx *context.Context) bool {
  373. if ctx.Repo.Repository.IsPrivate {
  374. if ctx.Repo.CanRead(models.UnitTypeCloudBrain) || ctx.User.IsAdmin || ctx.Repo.IsAdmin() || ctx.Repo.IsOwner() {
  375. return true
  376. }
  377. return false
  378. } else {
  379. return true
  380. }
  381. }
  382. func isOper(ctx *context.Context, modelUserId int64) bool {
  383. if ctx.User == nil {
  384. return false
  385. }
  386. if ctx.User.IsAdmin || ctx.Repo.IsAdmin() || ctx.Repo.IsOwner() || ctx.User.ID == modelUserId {
  387. return true
  388. }
  389. return false
  390. }
  391. func ShowModelPageInfo(ctx *context.Context) {
  392. log.Info("ShowModelInfo start.")
  393. if !isQueryRight(ctx) {
  394. ctx.ServerError("no right.", errors.New(ctx.Tr("repo.model_noright")))
  395. return
  396. }
  397. page := ctx.QueryInt("page")
  398. if page <= 0 {
  399. page = 1
  400. }
  401. repoId := ctx.Repo.Repository.ID
  402. Type := -1
  403. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  404. ListOptions: models.ListOptions{
  405. Page: page,
  406. PageSize: setting.UI.IssuePagingNum,
  407. },
  408. RepoID: repoId,
  409. Type: Type,
  410. New: MODEL_LATEST,
  411. })
  412. if err != nil {
  413. ctx.ServerError("Cloudbrain", err)
  414. return
  415. }
  416. for _, model := range modelResult {
  417. log.Info("model=" + model.Name)
  418. log.Info("model.UserId=" + fmt.Sprint(model.UserId))
  419. model.IsCanOper = isOper(ctx, model.UserId)
  420. }
  421. mapInterface := make(map[string]interface{})
  422. mapInterface["data"] = modelResult
  423. mapInterface["count"] = count
  424. ctx.JSON(http.StatusOK, mapInterface)
  425. }
  426. func ModifyModel(id string, description string) error {
  427. err := models.ModifyModelDescription(id, description)
  428. if err == nil {
  429. log.Info("modify success.")
  430. } else {
  431. log.Info("Failed to modify.id=" + id + " desc=" + description + " error:" + err.Error())
  432. }
  433. return err
  434. }
  435. func ModifyModelInfo(ctx *context.Context) {
  436. log.Info("modify model start.")
  437. id := ctx.Query("ID")
  438. description := ctx.Query("Description")
  439. task, err := models.QueryModelById(id)
  440. if err != nil {
  441. log.Error("no such model!", err.Error())
  442. ctx.ServerError("no such model:", err)
  443. return
  444. }
  445. if !isCanDeleteOrDownload(ctx, task) {
  446. ctx.ServerError("no right.", errors.New(ctx.Tr("repo.model_noright")))
  447. return
  448. }
  449. err = ModifyModel(id, description)
  450. if err != nil {
  451. log.Info("modify error," + err.Error())
  452. ctx.ServerError("error.", err)
  453. } else {
  454. ctx.JSON(200, "success")
  455. }
  456. }