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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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. if model.New == MODEL_LATEST {
  185. aimodels := models.QueryModelByName(model.Name, model.RepoId)
  186. if len(aimodels) > 0 {
  187. //udpate status and version count
  188. models.ModifyModelNewProperty(aimodels[0].ID, MODEL_LATEST, len(aimodels))
  189. }
  190. }
  191. }
  192. }
  193. return err
  194. }
  195. func QueryModelByParameters(repoId int64, page int) ([]*models.AiModelManage, int64, error) {
  196. return models.QueryModel(&models.AiModelQueryOptions{
  197. ListOptions: models.ListOptions{
  198. Page: page,
  199. PageSize: setting.UI.IssuePagingNum,
  200. },
  201. RepoID: repoId,
  202. Type: -1,
  203. New: MODEL_LATEST,
  204. })
  205. }
  206. func DownloadMultiModelFile(ctx *context.Context) {
  207. log.Info("DownloadMultiModelFile start.")
  208. id := ctx.Query("ID")
  209. log.Info("id=" + id)
  210. task, err := models.QueryModelById(id)
  211. if err != nil {
  212. log.Error("no such model!", err.Error())
  213. ctx.ServerError("no such model:", err)
  214. return
  215. }
  216. if !isCanDeleteOrDownload(ctx, task) {
  217. ctx.ServerError("no right.", errors.New(ctx.Tr("repo.model_noright")))
  218. return
  219. }
  220. path := Model_prefix + models.AttachmentRelativePath(id) + "/"
  221. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  222. if err == nil {
  223. //count++
  224. models.ModifyModelDownloadCount(id)
  225. returnFileName := task.Name + "_" + task.Version + ".zip"
  226. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+returnFileName)
  227. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  228. w := zip.NewWriter(ctx.Resp)
  229. defer w.Close()
  230. for _, oneFile := range allFile {
  231. if oneFile.IsDir {
  232. log.Info("zip dir name:" + oneFile.FileName)
  233. } else {
  234. log.Info("zip file name:" + oneFile.FileName)
  235. fDest, err := w.Create(oneFile.FileName)
  236. if err != nil {
  237. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  238. ctx.ServerError("download file failed:", err)
  239. return
  240. }
  241. body, err := storage.ObsDownloadAFile(setting.Bucket, path+oneFile.FileName)
  242. if err != nil {
  243. log.Info("download file failed: %s\n", err.Error())
  244. ctx.ServerError("download file failed:", err)
  245. return
  246. } else {
  247. defer body.Close()
  248. p := make([]byte, 1024)
  249. var readErr error
  250. var readCount int
  251. // 读取对象内容
  252. for {
  253. readCount, readErr = body.Read(p)
  254. if readCount > 0 {
  255. fDest.Write(p[:readCount])
  256. }
  257. if readErr != nil {
  258. break
  259. }
  260. }
  261. }
  262. }
  263. }
  264. } else {
  265. log.Info("error,msg=" + err.Error())
  266. ctx.ServerError("no file to download.", err)
  267. }
  268. }
  269. func QueryTrainJobVersionList(ctx *context.Context) {
  270. log.Info("query train job version list. start.")
  271. JobID := ctx.Query("JobID")
  272. VersionListTasks, count, err := models.QueryModelTrainJobVersionList(JobID)
  273. log.Info("query return count=" + fmt.Sprint(count))
  274. if err != nil {
  275. ctx.ServerError("QueryTrainJobList:", err)
  276. } else {
  277. ctx.JSON(200, VersionListTasks)
  278. }
  279. }
  280. func QueryTrainJobList(ctx *context.Context) {
  281. log.Info("query train job list. start.")
  282. repoId := ctx.QueryInt64("repoId")
  283. VersionListTasks, count, err := models.QueryModelTrainJobList(repoId)
  284. log.Info("query return count=" + fmt.Sprint(count))
  285. if err != nil {
  286. ctx.ServerError("QueryTrainJobList:", err)
  287. } else {
  288. ctx.JSON(200, VersionListTasks)
  289. }
  290. }
  291. func DownloadSingleModelFile(ctx *context.Context) {
  292. log.Info("DownloadSingleModelFile start.")
  293. id := ctx.Params(":ID")
  294. parentDir := ctx.Query("parentDir")
  295. fileName := ctx.Query("fileName")
  296. path := Model_prefix + models.AttachmentRelativePath(id) + "/" + parentDir + fileName
  297. if setting.PROXYURL != "" {
  298. body, err := storage.ObsDownloadAFile(setting.Bucket, path)
  299. if err != nil {
  300. log.Info("download error.")
  301. } else {
  302. //count++
  303. models.ModifyModelDownloadCount(id)
  304. defer body.Close()
  305. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  306. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  307. p := make([]byte, 1024)
  308. var readErr error
  309. var readCount int
  310. // 读取对象内容
  311. for {
  312. readCount, readErr = body.Read(p)
  313. if readCount > 0 {
  314. ctx.Resp.Write(p[:readCount])
  315. //fmt.Printf("%s", p[:readCount])
  316. }
  317. if readErr != nil {
  318. break
  319. }
  320. }
  321. }
  322. } else {
  323. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  324. if err != nil {
  325. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  326. ctx.ServerError("GetObsCreateSignedUrl", err)
  327. return
  328. }
  329. //count++
  330. models.ModifyModelDownloadCount(id)
  331. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  332. }
  333. }
  334. func ShowModelInfo(ctx *context.Context) {
  335. ctx.Data["ID"] = ctx.Query("ID")
  336. ctx.Data["name"] = ctx.Query("name")
  337. ctx.HTML(200, tplModelInfo)
  338. }
  339. func ShowSingleModel(ctx *context.Context) {
  340. name := ctx.Query("name")
  341. log.Info("Show single ModelInfo start.name=" + name)
  342. models := models.QueryModelByName(name, ctx.Repo.Repository.ID)
  343. ctx.JSON(http.StatusOK, models)
  344. }
  345. func ShowOneVersionOtherModel(ctx *context.Context) {
  346. repoId := ctx.Repo.Repository.ID
  347. name := ctx.Query("name")
  348. aimodels := models.QueryModelByName(name, repoId)
  349. if len(aimodels) > 0 {
  350. ctx.JSON(200, aimodels[1:])
  351. } else {
  352. ctx.JSON(200, aimodels)
  353. }
  354. }
  355. func ShowModelTemplate(ctx *context.Context) {
  356. ctx.HTML(200, tplModelManageIndex)
  357. }
  358. func isQueryRight(ctx *context.Context) bool {
  359. if ctx.Repo.Repository.IsPrivate {
  360. if ctx.User.IsAdmin || ctx.Repo.IsAdmin() || ctx.Repo.IsOwner() {
  361. return true
  362. }
  363. return false
  364. } else {
  365. return true
  366. }
  367. }
  368. func ShowModelPageInfo(ctx *context.Context) {
  369. log.Info("ShowModelInfo start.")
  370. if !isQueryRight(ctx) {
  371. ctx.ServerError("no right.", errors.New(ctx.Tr("repo.model_noright")))
  372. return
  373. }
  374. page := ctx.QueryInt("page")
  375. if page <= 0 {
  376. page = 1
  377. }
  378. repoId := ctx.Repo.Repository.ID
  379. Type := -1
  380. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  381. ListOptions: models.ListOptions{
  382. Page: page,
  383. PageSize: setting.UI.IssuePagingNum,
  384. },
  385. RepoID: repoId,
  386. Type: Type,
  387. New: MODEL_LATEST,
  388. })
  389. if err != nil {
  390. ctx.ServerError("Cloudbrain", err)
  391. return
  392. }
  393. mapInterface := make(map[string]interface{})
  394. mapInterface["data"] = modelResult
  395. mapInterface["count"] = count
  396. ctx.JSON(http.StatusOK, mapInterface)
  397. }
  398. func ModifyModel(id string, description string) error {
  399. err := models.ModifyModelDescription(id, description)
  400. if err == nil {
  401. log.Info("modify success.")
  402. } else {
  403. log.Info("Failed to modify.id=" + id + " desc=" + description + " error:" + err.Error())
  404. }
  405. return err
  406. }
  407. func ModifyModelInfo(ctx *context.Context) {
  408. log.Info("delete model start.")
  409. id := ctx.Query("ID")
  410. description := ctx.Query("Description")
  411. err := ModifyModel(id, description)
  412. if err == nil {
  413. ctx.HTML(200, "success")
  414. } else {
  415. ctx.HTML(500, "Failed.")
  416. }
  417. }