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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 JobId == "" || VersionName == "" {
  110. ctx.Error(500, fmt.Sprintf("JobId or VersionName is null."))
  111. return
  112. }
  113. if name == "" || version == "" {
  114. ctx.Error(500, fmt.Sprintf("name or version is null."))
  115. return
  116. }
  117. err := saveModelByParameters(JobId, VersionName, name, version, label, description, ctx)
  118. if err != nil {
  119. log.Info("save model error." + err.Error())
  120. ctx.Error(500, fmt.Sprintf("save model error. %v", err))
  121. return
  122. }
  123. log.Info("save model end.")
  124. }
  125. func downloadModelFromCloudBrainTwo(modelUUID string, jobName string, parentDir string) (string, int64, error) {
  126. objectkey := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir), "/")
  127. modelDbResult, err := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, objectkey, "")
  128. log.Info("bucket=" + setting.Bucket + " objectkey=" + objectkey)
  129. if err != nil {
  130. log.Info("get TrainJobListModel failed:", err)
  131. return "", 0, err
  132. }
  133. if len(modelDbResult) == 0 {
  134. return "", 0, errors.New("cannot create model, as model is empty.")
  135. }
  136. prefix := objectkey + "/"
  137. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(modelUUID) + "/"
  138. size, err := storage.ObsCopyManyFile(setting.Bucket, prefix, setting.Bucket, destKeyNamePrefix)
  139. dataActualPath := setting.Bucket + "/" + destKeyNamePrefix
  140. return dataActualPath, size, nil
  141. }
  142. func DeleteModel(ctx *context.Context) {
  143. log.Info("delete model start.")
  144. id := ctx.Query("ID")
  145. err := DeleteModelByID(id)
  146. if err != nil {
  147. ctx.JSON(500, err.Error())
  148. } else {
  149. ctx.JSON(200, map[string]string{
  150. "result_code": "0",
  151. })
  152. }
  153. }
  154. func DeleteModelByID(id string) error {
  155. log.Info("delete model start. id=" + id)
  156. model, err := models.QueryModelById(id)
  157. if err == nil {
  158. log.Info("bucket=" + setting.Bucket + " path=" + model.Path)
  159. if strings.HasPrefix(model.Path, setting.Bucket+"/"+Model_prefix) {
  160. err := storage.ObsRemoveObject(setting.Bucket, model.Path[len(setting.Bucket)+1:])
  161. if err != nil {
  162. log.Info("Failed to delete model. id=" + id)
  163. return err
  164. }
  165. }
  166. err = models.DeleteModelById(id)
  167. if err == nil { //find a model to change new
  168. if model.New == MODEL_LATEST {
  169. aimodels := models.QueryModelByName(model.Name, model.RepoId)
  170. if len(aimodels) > 0 {
  171. //udpate status and version count
  172. models.ModifyModelNewProperty(aimodels[0].ID, MODEL_LATEST, len(aimodels))
  173. }
  174. }
  175. }
  176. }
  177. return err
  178. }
  179. func QueryModelByParameters(repoId int64, page int) ([]*models.AiModelManage, int64, error) {
  180. return models.QueryModel(&models.AiModelQueryOptions{
  181. ListOptions: models.ListOptions{
  182. Page: page,
  183. PageSize: setting.UI.IssuePagingNum,
  184. },
  185. RepoID: repoId,
  186. Type: -1,
  187. New: MODEL_LATEST,
  188. })
  189. }
  190. func DownloadMultiModelFile(ctx *context.Context) {
  191. log.Info("DownloadMultiModelFile start.")
  192. id := ctx.Query("ID")
  193. log.Info("id=" + id)
  194. task, err := models.QueryModelById(id)
  195. if err != nil {
  196. log.Error("no such model!", err.Error())
  197. ctx.ServerError("no such model:", err)
  198. return
  199. }
  200. path := Model_prefix + models.AttachmentRelativePath(id) + "/"
  201. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  202. if err == nil {
  203. //count++
  204. models.ModifyModelDownloadCount(id)
  205. returnFileName := task.Name + "_" + task.Version + ".zip"
  206. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+returnFileName)
  207. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  208. w := zip.NewWriter(ctx.Resp)
  209. defer w.Close()
  210. for _, oneFile := range allFile {
  211. if oneFile.IsDir {
  212. log.Info("zip dir name:" + oneFile.FileName)
  213. } else {
  214. log.Info("zip file name:" + oneFile.FileName)
  215. fDest, err := w.Create(oneFile.FileName)
  216. if err != nil {
  217. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  218. ctx.ServerError("download file failed:", err)
  219. return
  220. }
  221. body, err := storage.ObsDownloadAFile(setting.Bucket, path+oneFile.FileName)
  222. if err != nil {
  223. log.Info("download file failed: %s\n", err.Error())
  224. ctx.ServerError("download file failed:", err)
  225. return
  226. } else {
  227. defer body.Close()
  228. p := make([]byte, 1024)
  229. var readErr error
  230. var readCount int
  231. // 读取对象内容
  232. for {
  233. readCount, readErr = body.Read(p)
  234. if readCount > 0 {
  235. fDest.Write(p[:readCount])
  236. }
  237. if readErr != nil {
  238. break
  239. }
  240. }
  241. }
  242. }
  243. }
  244. } else {
  245. log.Info("error,msg=" + err.Error())
  246. ctx.ServerError("no file to download.", err)
  247. }
  248. }
  249. func QueryTrainJobVersionList(ctx *context.Context) {
  250. log.Info("query train job version list. start.")
  251. JobID := ctx.Query("JobID")
  252. VersionListTasks, count, err := models.QueryModelTrainJobVersionList(JobID)
  253. log.Info("query return count=" + fmt.Sprint(count))
  254. if err != nil {
  255. ctx.ServerError("QueryTrainJobList:", err)
  256. } else {
  257. ctx.JSON(200, VersionListTasks)
  258. }
  259. }
  260. func QueryTrainJobList(ctx *context.Context) {
  261. log.Info("query train job list. start.")
  262. repoId := ctx.QueryInt64("repoId")
  263. VersionListTasks, count, err := models.QueryModelTrainJobList(repoId)
  264. log.Info("query return count=" + fmt.Sprint(count))
  265. if err != nil {
  266. ctx.ServerError("QueryTrainJobList:", err)
  267. } else {
  268. ctx.JSON(200, VersionListTasks)
  269. }
  270. }
  271. func DownloadSingleModelFile(ctx *context.Context) {
  272. log.Info("DownloadSingleModelFile start.")
  273. id := ctx.Params(":ID")
  274. parentDir := ctx.Query("parentDir")
  275. fileName := ctx.Query("fileName")
  276. path := Model_prefix + models.AttachmentRelativePath(id) + "/" + parentDir + fileName
  277. if setting.PROXYURL != "" {
  278. body, err := storage.ObsDownloadAFile(setting.Bucket, path)
  279. if err != nil {
  280. log.Info("download error.")
  281. } else {
  282. //count++
  283. models.ModifyModelDownloadCount(id)
  284. defer body.Close()
  285. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  286. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  287. p := make([]byte, 1024)
  288. var readErr error
  289. var readCount int
  290. // 读取对象内容
  291. for {
  292. readCount, readErr = body.Read(p)
  293. if readCount > 0 {
  294. ctx.Resp.Write(p[:readCount])
  295. //fmt.Printf("%s", p[:readCount])
  296. }
  297. if readErr != nil {
  298. break
  299. }
  300. }
  301. }
  302. } else {
  303. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  304. if err != nil {
  305. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  306. ctx.ServerError("GetObsCreateSignedUrl", err)
  307. return
  308. }
  309. //count++
  310. models.ModifyModelDownloadCount(id)
  311. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  312. }
  313. }
  314. func ShowModelInfo(ctx *context.Context) {
  315. ctx.Data["ID"] = ctx.Query("ID")
  316. ctx.Data["name"] = ctx.Query("name")
  317. ctx.HTML(200, tplModelInfo)
  318. }
  319. func ShowSingleModel(ctx *context.Context) {
  320. name := ctx.Query("name")
  321. log.Info("Show single ModelInfo start.name=" + name)
  322. models := models.QueryModelByName(name, ctx.Repo.Repository.ID)
  323. ctx.JSON(http.StatusOK, models)
  324. }
  325. func ShowOneVersionOtherModel(ctx *context.Context) {
  326. repoId := ctx.Repo.Repository.ID
  327. name := ctx.Query("name")
  328. aimodels := models.QueryModelByName(name, repoId)
  329. if len(aimodels) > 0 {
  330. ctx.JSON(200, aimodels[1:])
  331. } else {
  332. ctx.JSON(200, aimodels)
  333. }
  334. }
  335. func ShowModelTemplate(ctx *context.Context) {
  336. ctx.HTML(200, tplModelManageIndex)
  337. }
  338. func ShowModelPageInfo(ctx *context.Context) {
  339. log.Info("ShowModelInfo start.")
  340. page := ctx.QueryInt("page")
  341. if page <= 0 {
  342. page = 1
  343. }
  344. repoId := ctx.Repo.Repository.ID
  345. Type := -1
  346. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  347. ListOptions: models.ListOptions{
  348. Page: page,
  349. PageSize: setting.UI.IssuePagingNum,
  350. },
  351. RepoID: repoId,
  352. Type: Type,
  353. New: MODEL_LATEST,
  354. })
  355. if err != nil {
  356. ctx.ServerError("Cloudbrain", err)
  357. return
  358. }
  359. mapInterface := make(map[string]interface{})
  360. mapInterface["data"] = modelResult
  361. mapInterface["count"] = count
  362. ctx.JSON(http.StatusOK, mapInterface)
  363. }
  364. func ModifyModel(id string, description string) error {
  365. err := models.ModifyModelDescription(id, description)
  366. if err == nil {
  367. log.Info("modify success.")
  368. } else {
  369. log.Info("Failed to modify.id=" + id + " desc=" + description + " error:" + err.Error())
  370. }
  371. return err
  372. }
  373. func ModifyModelInfo(ctx *context.Context) {
  374. log.Info("delete model start.")
  375. id := ctx.Query("ID")
  376. description := ctx.Query("Description")
  377. err := ModifyModel(id, description)
  378. if err == nil {
  379. ctx.HTML(200, "success")
  380. } else {
  381. ctx.HTML(500, "Failed.")
  382. }
  383. }