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

2 years ago
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. package models
  2. import (
  3. "fmt"
  4. "time"
  5. "code.gitea.io/gitea/modules/log"
  6. "code.gitea.io/gitea/modules/setting"
  7. "code.gitea.io/gitea/modules/timeutil"
  8. "xorm.io/builder"
  9. "xorm.io/xorm"
  10. )
  11. type AiModelManage struct {
  12. ID string `xorm:"pk" json:"id"`
  13. Name string `xorm:"INDEX NOT NULL" json:"name"`
  14. ModelType int `xorm:"NULL" json:"modelType"`
  15. Version string `xorm:"NOT NULL" json:"version"`
  16. VersionCount int `xorm:"NOT NULL DEFAULT 0" json:"versionCount"`
  17. New int `xorm:"NOT NULL" json:"new"`
  18. Type int `xorm:"NOT NULL" json:"type"`
  19. Size int64 `xorm:"NOT NULL" json:"size"`
  20. Description string `xorm:"varchar(2000)" json:"description"`
  21. Label string `xorm:"varchar(1000)" json:"label"`
  22. Path string `xorm:"varchar(400) NOT NULL" json:"path"`
  23. DownloadCount int `xorm:"NOT NULL DEFAULT 0" json:"downloadCount"`
  24. Engine int64 `xorm:"NOT NULL DEFAULT 0" json:"engine"`
  25. Status int `xorm:"NOT NULL DEFAULT 0" json:"status"`
  26. StatusDesc string `xorm:"varchar(500)" json:"statusDesc"`
  27. Accuracy string `xorm:"varchar(1000)" json:"accuracy"`
  28. AttachmentId string `xorm:"NULL" json:"attachmentId"`
  29. RepoId int64 `xorm:"INDEX NULL" json:"repoId"`
  30. CodeBranch string `xorm:"varchar(400) NULL" json:"codeBranch"`
  31. CodeCommitID string `xorm:"NULL" json:"codeCommitID"`
  32. UserId int64 `xorm:"NOT NULL" json:"userId"`
  33. IsPrivate bool `xorm:"DEFAULT true" json:"isPrivate"`
  34. UserName string `json:"userName"`
  35. UserRelAvatarLink string `json:"userRelAvatarLink"`
  36. TrainTaskInfo string `xorm:"text NULL" json:"trainTaskInfo"`
  37. CreatedUnix timeutil.TimeStamp `xorm:"created" json:"createdUnix"`
  38. UpdatedUnix timeutil.TimeStamp `xorm:"updated" json:"updatedUnix"`
  39. IsCanOper bool `json:"isCanOper"`
  40. IsCanDelete bool `json:"isCanDelete"`
  41. IsCanDownload bool `json:"isCanDownload"`
  42. }
  43. type AiModelConvert struct {
  44. ID string `xorm:"pk" json:"id"`
  45. Name string `xorm:"INDEX NOT NULL" json:"name"`
  46. Status string `xorm:"NULL" json:"status"`
  47. StatusResult string `xorm:"NULL" json:"statusResult"`
  48. SrcEngine int `xorm:"NOT NULL DEFAULT 0" json:"srcEngine"`
  49. RepoId int64 `xorm:"INDEX NULL" json:"repoId"`
  50. ModelId string `xorm:"NOT NULL" json:"modelId"`
  51. ModelName string `xorm:"NULL" json:"modelName"`
  52. ModelVersion string `xorm:"NOT NULL" json:"modelVersion"`
  53. ModelPath string `xorm:"NULL" json:"modelPath"`
  54. DestFormat int `xorm:"NOT NULL DEFAULT 0" json:"destFormat"`
  55. NetOutputFormat int `xorm:"NULL" json:"netOutputFormat"`
  56. UserId int64 `xorm:"NOT NULL" json:"userId"`
  57. CloudBrainTaskId string `xorm:"NULL" json:"cloudBrainTaskId"`
  58. ModelArtsVersionId string `xorm:"NULL" json:"modelArtsVersionId"`
  59. ContainerID string `json:"containerID"`
  60. ContainerIp string `json:"containerIp"`
  61. RunTime int64 `xorm:"NULL" json:"runTime"`
  62. TrainJobDuration string `json:"trainJobDuration"`
  63. InputShape string `xorm:"varchar(2000)" json:"inputShape"`
  64. InputDataFormat string `xorm:"NOT NULL" json:"inputDataFormat"`
  65. Description string `xorm:"varchar(2000)" json:"description"`
  66. Path string `xorm:"varchar(400) NOT NULL" json:"path"`
  67. CreatedUnix timeutil.TimeStamp `xorm:"created" json:"createdUnix"`
  68. UpdatedUnix timeutil.TimeStamp `xorm:"updated" json:"updatedUnix"`
  69. StartTime timeutil.TimeStamp `json:"startTime"`
  70. EndTime timeutil.TimeStamp `json:"endTime"`
  71. UserName string `json:"userName"`
  72. UserRelAvatarLink string `json:"userRelAvatarLink"`
  73. IsCanOper bool `json:"isCanOper"`
  74. IsCanDelete bool `json:"isCanDelete"`
  75. }
  76. type AiModelQueryOptions struct {
  77. ListOptions
  78. RepoID int64 // include all repos if empty
  79. UserID int64
  80. ModelID string
  81. SortType string
  82. New int
  83. // JobStatus CloudbrainStatus
  84. Type int
  85. Status int
  86. IsOnlyThisRepo bool
  87. IsQueryPrivate bool
  88. }
  89. func (a *AiModelConvert) IsGpuTrainTask() bool {
  90. if a.SrcEngine == 0 || a.SrcEngine == 1 || a.SrcEngine == 4 || a.SrcEngine == 6 {
  91. return true
  92. }
  93. return false
  94. }
  95. func ModelComputeAndSetDuration(task *AiModelConvert, result JobResultPayload) {
  96. if task.StartTime == 0 {
  97. task.StartTime = timeutil.TimeStamp(result.JobStatus.CreatedTime / 1000)
  98. }
  99. if task.EndTime == 0 {
  100. if result.JobStatus.CompletedTime > 0 {
  101. task.EndTime = timeutil.TimeStamp(result.JobStatus.CompletedTime / 1000)
  102. }
  103. }
  104. var d int64
  105. if task.StartTime == 0 {
  106. d = 0
  107. } else if task.EndTime == 0 {
  108. d = time.Now().Unix() - task.StartTime.AsTime().Unix()
  109. } else {
  110. d = task.EndTime.AsTime().Unix() - task.StartTime.AsTime().Unix()
  111. }
  112. if d < 0 {
  113. d = 0
  114. }
  115. task.RunTime = d
  116. task.TrainJobDuration = ConvertDurationToStr(d)
  117. }
  118. func ModelConvertSetDuration(task *AiModelConvert) {
  119. var d int64
  120. if task.StartTime == 0 {
  121. d = 0
  122. } else if task.EndTime == 0 {
  123. d = time.Now().Unix() - task.StartTime.AsTime().Unix()
  124. } else {
  125. d = task.EndTime.AsTime().Unix() - task.StartTime.AsTime().Unix()
  126. }
  127. if d < 0 {
  128. d = 0
  129. }
  130. task.RunTime = d
  131. task.TrainJobDuration = ConvertDurationToStr(d)
  132. }
  133. func UpdateModelConvertModelArts(id string, CloudBrainTaskId string, VersionId string) error {
  134. var sess *xorm.Session
  135. sess = x.ID(id)
  136. defer sess.Close()
  137. re, err := sess.Cols("cloud_brain_task_id,model_arts_version_id").Update(&AiModelConvert{
  138. CloudBrainTaskId: CloudBrainTaskId,
  139. ModelArtsVersionId: VersionId,
  140. })
  141. if err != nil {
  142. return err
  143. }
  144. log.Info("success to update cloud_brain_task_id from db.re=" + fmt.Sprint((re)))
  145. return nil
  146. }
  147. func UpdateModelConvertFailed(id string, status string, statusResult string) error {
  148. var sess *xorm.Session
  149. sess = x.ID(id)
  150. defer sess.Close()
  151. re, err := sess.Cols("status", "status_result").Update(&AiModelConvert{
  152. Status: status,
  153. StatusResult: statusResult,
  154. })
  155. if err != nil {
  156. return err
  157. }
  158. log.Info("success to update cloud_brain_task_id from db.re=" + fmt.Sprint((re)))
  159. return nil
  160. }
  161. func UpdateModelConvertCBTI(id string, CloudBrainTaskId string) error {
  162. var sess *xorm.Session
  163. sess = x.ID(id)
  164. defer sess.Close()
  165. re, err := sess.Cols("cloud_brain_task_id").Update(&AiModelConvert{
  166. CloudBrainTaskId: CloudBrainTaskId,
  167. })
  168. if err != nil {
  169. return err
  170. }
  171. log.Info("success to update cloud_brain_task_id from db.re=" + fmt.Sprint((re)))
  172. return nil
  173. }
  174. func UpdateModelConvert(job *AiModelConvert) error {
  175. return updateModelConvert(x, job)
  176. }
  177. func updateModelConvert(e Engine, job *AiModelConvert) error {
  178. var sess *xorm.Session
  179. sess = e.Where("id = ?", job.ID)
  180. _, err := sess.Cols("status", "train_job_duration", "run_time", "start_time", "end_time", "updated_unix").Update(job)
  181. return err
  182. }
  183. func SaveModelConvert(modelConvert *AiModelConvert) error {
  184. sess := x.NewSession()
  185. defer sess.Close()
  186. re, err := sess.Insert(modelConvert)
  187. if err != nil {
  188. log.Info("insert modelConvert error." + err.Error())
  189. return err
  190. }
  191. log.Info("success to save modelConvert db.re=" + fmt.Sprint((re)))
  192. return nil
  193. }
  194. func SaveModelToDb(model *AiModelManage) error {
  195. sess := x.NewSession()
  196. defer sess.Close()
  197. re, err := sess.Insert(model)
  198. if err != nil {
  199. log.Info("insert error." + err.Error())
  200. return err
  201. }
  202. log.Info("success to save db.re=" + fmt.Sprint((re)))
  203. return nil
  204. }
  205. func QueryModelConvertByName(name string, repoId int64) ([]*AiModelConvert, error) {
  206. sess := x.NewSession()
  207. defer sess.Close()
  208. sess.Select("*").Table(new(AiModelConvert)).
  209. Where("name='" + name + "' and repo_id=" + fmt.Sprint(repoId)).OrderBy("created_unix desc")
  210. aiModelManageConvertList := make([]*AiModelConvert, 0)
  211. err := sess.Find(&aiModelManageConvertList)
  212. if err == nil {
  213. return aiModelManageConvertList, nil
  214. }
  215. return nil, err
  216. }
  217. func QueryModelConvertById(id string) (*AiModelConvert, error) {
  218. sess := x.NewSession()
  219. defer sess.Close()
  220. re := new(AiModelConvert)
  221. isExist, err := sess.Table(new(AiModelConvert)).ID(id).Get(re)
  222. if err == nil && isExist {
  223. return re, nil
  224. }
  225. return nil, err
  226. }
  227. func QueryModelById(id string) (*AiModelManage, error) {
  228. sess := x.NewSession()
  229. defer sess.Close()
  230. re := new(AiModelManage)
  231. isExist, err := sess.Table(new(AiModelManage)).ID(id).Get(re)
  232. if err == nil && isExist {
  233. return re, nil
  234. }
  235. return nil, err
  236. }
  237. func DeleteModelConvertById(id string) error {
  238. sess := x.NewSession()
  239. defer sess.Close()
  240. re, err := sess.Delete(&AiModelConvert{
  241. ID: id,
  242. })
  243. if err != nil {
  244. return err
  245. }
  246. log.Info("success to delete AiModelManageConvert from db.re=" + fmt.Sprint((re)))
  247. return nil
  248. }
  249. func DeleteModelById(id string) error {
  250. sess := x.NewSession()
  251. defer sess.Close()
  252. re, err := sess.Delete(&AiModelManage{
  253. ID: id,
  254. })
  255. if err != nil {
  256. return err
  257. }
  258. log.Info("success to delete from db.re=" + fmt.Sprint((re)))
  259. return nil
  260. }
  261. func ModifyModelDescription(id string, description string) error {
  262. var sess *xorm.Session
  263. sess = x.ID(id)
  264. defer sess.Close()
  265. re, err := sess.Cols("description").Update(&AiModelManage{
  266. Description: description,
  267. })
  268. if err != nil {
  269. return err
  270. }
  271. log.Info("success to update description from db.re=" + fmt.Sprint((re)))
  272. return nil
  273. }
  274. func ModifyModelPrivate(id string, isPrivate bool) error {
  275. var sess *xorm.Session
  276. sess = x.ID(id)
  277. defer sess.Close()
  278. re, err := sess.Cols("is_private").Update(&AiModelManage{
  279. IsPrivate: isPrivate,
  280. })
  281. if err != nil {
  282. return err
  283. }
  284. log.Info("success to update isPrivate from db.re=" + fmt.Sprint((re)))
  285. return nil
  286. }
  287. func ModifyLocalModel(id string, name, label, description string, engine int, isPrivate bool) error {
  288. var sess *xorm.Session
  289. sess = x.ID(id)
  290. defer sess.Close()
  291. re, err := sess.Cols("name", "label", "description", "engine", "is_private").Update(&AiModelManage{
  292. Description: description,
  293. Name: name,
  294. Label: label,
  295. Engine: int64(engine),
  296. IsPrivate: isPrivate,
  297. })
  298. if err != nil {
  299. return err
  300. }
  301. log.Info("success to update description from db.re=" + fmt.Sprint((re)))
  302. return nil
  303. }
  304. func ModifyModelSize(id string, size int64) error {
  305. var sess *xorm.Session
  306. sess = x.ID(id)
  307. defer sess.Close()
  308. re, err := sess.Cols("size").Update(&AiModelManage{
  309. Size: size,
  310. })
  311. if err != nil {
  312. return err
  313. }
  314. log.Info("success to update size from db.re=" + fmt.Sprint((re)))
  315. return nil
  316. }
  317. func ModifyModelStatus(id string, modelSize int64, status int, modelPath string, statusDesc string) error {
  318. var sess *xorm.Session
  319. sess = x.ID(id)
  320. defer sess.Close()
  321. re, err := sess.Cols("size", "status", "path", "status_desc").Update(&AiModelManage{
  322. Size: modelSize,
  323. Status: status,
  324. Path: modelPath,
  325. StatusDesc: statusDesc,
  326. })
  327. if err != nil {
  328. return err
  329. }
  330. log.Info("success to update ModelStatus from db.re=" + fmt.Sprint((re)))
  331. return nil
  332. }
  333. func ModifyModelNewProperty(id string, new int, versioncount int) error {
  334. var sess *xorm.Session
  335. sess = x.ID(id)
  336. defer sess.Close()
  337. re, err := sess.Cols("new", "version_count").Update(&AiModelManage{
  338. New: new,
  339. VersionCount: versioncount,
  340. })
  341. if err != nil {
  342. return err
  343. }
  344. log.Info("success to update new property from db.re=" + fmt.Sprint((re)))
  345. return nil
  346. }
  347. func ModifyModelDownloadCount(id string) error {
  348. sess := x.NewSession()
  349. defer sess.Close()
  350. if _, err := sess.Exec("UPDATE `ai_model_manage` SET download_count = download_count + 1 WHERE id = ?", id); err != nil {
  351. return err
  352. }
  353. return nil
  354. }
  355. func QueryModelByName(name string, repoId int64) []*AiModelManage {
  356. sess := x.NewSession()
  357. defer sess.Close()
  358. sess.Select("*").Table("ai_model_manage").
  359. Where("name='" + name + "' and repo_id=" + fmt.Sprint(repoId)).OrderBy("created_unix desc")
  360. aiModelManageList := make([]*AiModelManage, 0)
  361. sess.Find(&aiModelManageList)
  362. return aiModelManageList
  363. }
  364. func QueryModelByPath(path string) (*AiModelManage, error) {
  365. modelManage := new(AiModelManage)
  366. has, err := x.Where("path=?", path).Get(modelManage)
  367. if err != nil {
  368. return nil, err
  369. }
  370. if !has {
  371. return nil, ErrNotExist{}
  372. }
  373. return modelManage, nil
  374. }
  375. func QueryModel(opts *AiModelQueryOptions) ([]*AiModelManage, int64, error) {
  376. sess := x.NewSession()
  377. defer sess.Close()
  378. var cond = builder.NewCond()
  379. if opts.RepoID > 0 {
  380. cond = cond.And(
  381. builder.Eq{"ai_model_manage.repo_id": opts.RepoID},
  382. )
  383. }
  384. if opts.UserID > 0 {
  385. cond = cond.And(
  386. builder.Eq{"ai_model_manage.user_id": opts.UserID},
  387. )
  388. }
  389. if opts.New >= 0 {
  390. cond = cond.And(
  391. builder.Eq{"ai_model_manage.new": opts.New},
  392. )
  393. }
  394. if len(opts.ModelID) > 0 {
  395. cond = cond.And(
  396. builder.Eq{"ai_model_manage.id": opts.ModelID},
  397. )
  398. }
  399. if (opts.Type) >= 0 {
  400. cond = cond.And(
  401. builder.Eq{"ai_model_manage.type": opts.Type},
  402. )
  403. }
  404. if (opts.Status) >= 0 {
  405. cond = cond.And(
  406. builder.Eq{"ai_model_manage.status": opts.Status},
  407. )
  408. }
  409. if !opts.IsQueryPrivate {
  410. cond = cond.And(
  411. builder.Eq{"ai_model_manage.is_private": false},
  412. )
  413. }
  414. count, err := sess.Where(cond).Count(new(AiModelManage))
  415. if err != nil {
  416. return nil, 0, fmt.Errorf("Count: %v", err)
  417. }
  418. if opts.Page >= 0 && opts.PageSize > 0 {
  419. var start int
  420. if opts.Page == 0 {
  421. start = 0
  422. } else {
  423. start = (opts.Page - 1) * opts.PageSize
  424. }
  425. sess.Limit(opts.PageSize, start)
  426. }
  427. sess.OrderBy("ai_model_manage.created_unix DESC")
  428. aiModelManages := make([]*AiModelManage, 0, setting.UI.IssuePagingNum)
  429. if err := sess.Table("ai_model_manage").Where(cond).
  430. Find(&aiModelManages); err != nil {
  431. return nil, 0, fmt.Errorf("Find: %v", err)
  432. }
  433. return aiModelManages, count, nil
  434. }
  435. func QueryModelConvertCountByRepoID(repoId int64) int64 {
  436. convert := new(AiModelConvert)
  437. total, _ := x.Where("repo_id =?", repoId).Count(convert)
  438. return total
  439. }
  440. func QueryModelConvertByRepoID(repoId int64) ([]*AiModelConvert, error) {
  441. sess := x.NewSession()
  442. defer sess.Close()
  443. var cond = builder.NewCond()
  444. cond = cond.And(
  445. builder.Eq{"ai_model_convert.repo_id": repoId},
  446. )
  447. sess.OrderBy("ai_model_convert.created_unix DESC")
  448. aiModelManageConvert := make([]*AiModelConvert, 0)
  449. if err := sess.Table(new(AiModelConvert)).Where(cond).
  450. Find(&aiModelManageConvert); err != nil {
  451. return nil, fmt.Errorf("Find: %v", err)
  452. }
  453. return aiModelManageConvert, nil
  454. }
  455. func QueryModelConvertByUserID(userID int64) ([]*AiModelConvert, error) {
  456. sess := x.NewSession()
  457. defer sess.Close()
  458. var cond = builder.NewCond()
  459. cond = cond.And(
  460. builder.Eq{"ai_model_convert.user_id": userID},
  461. )
  462. sess.OrderBy("ai_model_convert.created_unix DESC")
  463. aiModelManageConvert := make([]*AiModelConvert, 0)
  464. if err := sess.Table(new(AiModelConvert)).Where(cond).
  465. Find(&aiModelManageConvert); err != nil {
  466. return nil, fmt.Errorf("Find: %v", err)
  467. }
  468. return aiModelManageConvert, nil
  469. }
  470. func QueryModelConvert(opts *AiModelQueryOptions) ([]*AiModelConvert, int64, error) {
  471. sess := x.NewSession()
  472. defer sess.Close()
  473. var cond = builder.NewCond()
  474. if opts.RepoID > 0 {
  475. cond = cond.And(
  476. builder.Eq{"ai_model_convert.repo_id": opts.RepoID},
  477. )
  478. }
  479. if opts.UserID > 0 {
  480. cond = cond.And(
  481. builder.Eq{"ai_model_convert.user_id": opts.UserID},
  482. )
  483. }
  484. count, err := sess.Where(cond).Count(new(AiModelConvert))
  485. if err != nil {
  486. return nil, 0, fmt.Errorf("Count: %v", err)
  487. }
  488. if opts.Page >= 0 && opts.PageSize > 0 {
  489. var start int
  490. if opts.Page == 0 {
  491. start = 0
  492. } else {
  493. start = (opts.Page - 1) * opts.PageSize
  494. }
  495. sess.Limit(opts.PageSize, start)
  496. }
  497. sess.OrderBy("ai_model_convert.created_unix DESC")
  498. aiModelManageConvert := make([]*AiModelConvert, 0, setting.UI.IssuePagingNum)
  499. if err := sess.Table(new(AiModelConvert)).Where(cond).
  500. Find(&aiModelManageConvert); err != nil {
  501. return nil, 0, fmt.Errorf("Find: %v", err)
  502. }
  503. return aiModelManageConvert, count, nil
  504. }