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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. sess.ID(id)
  221. //sess.Select("*").Table(new(AiModelConvert)).Where("id='" + id + "'")
  222. aiModelManageConvertList := make([]*AiModelConvert, 0)
  223. err := sess.Find(&aiModelManageConvertList)
  224. if err == nil {
  225. if len(aiModelManageConvertList) == 1 {
  226. return aiModelManageConvertList[0], nil
  227. }
  228. }
  229. return nil, err
  230. }
  231. func QueryModelById(id string) (*AiModelManage, error) {
  232. sess := x.NewSession()
  233. defer sess.Close()
  234. sess.Select("*").Table("ai_model_manage").
  235. Where("id='" + id + "'")
  236. aiModelManageList := make([]*AiModelManage, 0)
  237. err := sess.Find(&aiModelManageList)
  238. if err == nil {
  239. if len(aiModelManageList) == 1 {
  240. return aiModelManageList[0], nil
  241. }
  242. } else {
  243. log.Info("error=" + err.Error())
  244. }
  245. return nil, err
  246. }
  247. func DeleteModelConvertById(id string) error {
  248. sess := x.NewSession()
  249. defer sess.Close()
  250. re, err := sess.Delete(&AiModelConvert{
  251. ID: id,
  252. })
  253. if err != nil {
  254. return err
  255. }
  256. log.Info("success to delete AiModelManageConvert from db.re=" + fmt.Sprint((re)))
  257. return nil
  258. }
  259. func DeleteModelById(id string) error {
  260. sess := x.NewSession()
  261. defer sess.Close()
  262. re, err := sess.Delete(&AiModelManage{
  263. ID: id,
  264. })
  265. if err != nil {
  266. return err
  267. }
  268. log.Info("success to delete from db.re=" + fmt.Sprint((re)))
  269. return nil
  270. }
  271. func ModifyModelDescription(id string, description string) error {
  272. var sess *xorm.Session
  273. sess = x.ID(id)
  274. defer sess.Close()
  275. re, err := sess.Cols("description").Update(&AiModelManage{
  276. Description: description,
  277. })
  278. if err != nil {
  279. return err
  280. }
  281. log.Info("success to update description from db.re=" + fmt.Sprint((re)))
  282. return nil
  283. }
  284. func ModifyModelPrivate(id string, isPrivate bool) error {
  285. var sess *xorm.Session
  286. sess = x.ID(id)
  287. defer sess.Close()
  288. re, err := sess.Cols("is_private").Update(&AiModelManage{
  289. IsPrivate: isPrivate,
  290. })
  291. if err != nil {
  292. return err
  293. }
  294. log.Info("success to update isPrivate from db.re=" + fmt.Sprint((re)))
  295. return nil
  296. }
  297. func ModifyLocalModel(id string, name, label, description string, engine int, isPrivate bool) error {
  298. var sess *xorm.Session
  299. sess = x.ID(id)
  300. defer sess.Close()
  301. re, err := sess.Cols("name", "label", "description", "engine", "is_private").Update(&AiModelManage{
  302. Description: description,
  303. Name: name,
  304. Label: label,
  305. Engine: int64(engine),
  306. IsPrivate: isPrivate,
  307. })
  308. if err != nil {
  309. return err
  310. }
  311. log.Info("success to update description from db.re=" + fmt.Sprint((re)))
  312. return nil
  313. }
  314. func ModifyModelSize(id string, size int64) error {
  315. var sess *xorm.Session
  316. sess = x.ID(id)
  317. defer sess.Close()
  318. re, err := sess.Cols("size").Update(&AiModelManage{
  319. Size: size,
  320. })
  321. if err != nil {
  322. return err
  323. }
  324. log.Info("success to update size from db.re=" + fmt.Sprint((re)))
  325. return nil
  326. }
  327. func ModifyModelStatus(id string, modelSize int64, status int, modelPath string, statusDesc string) error {
  328. var sess *xorm.Session
  329. sess = x.ID(id)
  330. defer sess.Close()
  331. re, err := sess.Cols("size", "status", "path", "status_desc").Update(&AiModelManage{
  332. Size: modelSize,
  333. Status: status,
  334. Path: modelPath,
  335. StatusDesc: statusDesc,
  336. })
  337. if err != nil {
  338. return err
  339. }
  340. log.Info("success to update ModelStatus from db.re=" + fmt.Sprint((re)))
  341. return nil
  342. }
  343. func ModifyModelNewProperty(id string, new int, versioncount int) error {
  344. var sess *xorm.Session
  345. sess = x.ID(id)
  346. defer sess.Close()
  347. re, err := sess.Cols("new", "version_count").Update(&AiModelManage{
  348. New: new,
  349. VersionCount: versioncount,
  350. })
  351. if err != nil {
  352. return err
  353. }
  354. log.Info("success to update new property from db.re=" + fmt.Sprint((re)))
  355. return nil
  356. }
  357. func ModifyModelDownloadCount(id string) error {
  358. sess := x.NewSession()
  359. defer sess.Close()
  360. if _, err := sess.Exec("UPDATE `ai_model_manage` SET download_count = download_count + 1 WHERE id = ?", id); err != nil {
  361. return err
  362. }
  363. return nil
  364. }
  365. func QueryModelByName(name string, repoId int64) []*AiModelManage {
  366. sess := x.NewSession()
  367. defer sess.Close()
  368. sess.Select("*").Table("ai_model_manage").
  369. Where("name='" + name + "' and repo_id=" + fmt.Sprint(repoId)).OrderBy("created_unix desc")
  370. aiModelManageList := make([]*AiModelManage, 0)
  371. sess.Find(&aiModelManageList)
  372. return aiModelManageList
  373. }
  374. func QueryModelByPath(path string) (*AiModelManage, error) {
  375. modelManage := new(AiModelManage)
  376. has, err := x.Where("path=?", path).Get(modelManage)
  377. if err != nil {
  378. return nil, err
  379. }
  380. if !has {
  381. return nil, ErrNotExist{}
  382. }
  383. return modelManage, nil
  384. }
  385. func QueryModel(opts *AiModelQueryOptions) ([]*AiModelManage, int64, error) {
  386. sess := x.NewSession()
  387. defer sess.Close()
  388. var cond = builder.NewCond()
  389. if opts.RepoID > 0 {
  390. cond = cond.And(
  391. builder.Eq{"ai_model_manage.repo_id": opts.RepoID},
  392. )
  393. }
  394. if opts.UserID > 0 {
  395. cond = cond.And(
  396. builder.Eq{"ai_model_manage.user_id": opts.UserID},
  397. )
  398. }
  399. if opts.New >= 0 {
  400. cond = cond.And(
  401. builder.Eq{"ai_model_manage.new": opts.New},
  402. )
  403. }
  404. if len(opts.ModelID) > 0 {
  405. cond = cond.And(
  406. builder.Eq{"ai_model_manage.id": opts.ModelID},
  407. )
  408. }
  409. if (opts.Type) >= 0 {
  410. cond = cond.And(
  411. builder.Eq{"ai_model_manage.type": opts.Type},
  412. )
  413. }
  414. if (opts.Status) >= 0 {
  415. cond = cond.And(
  416. builder.Eq{"ai_model_manage.status": opts.Status},
  417. )
  418. }
  419. if !opts.IsQueryPrivate {
  420. cond = cond.And(
  421. builder.Eq{"ai_model_manage.is_private": false},
  422. )
  423. }
  424. count, err := sess.Where(cond).Count(new(AiModelManage))
  425. if err != nil {
  426. return nil, 0, fmt.Errorf("Count: %v", err)
  427. }
  428. if opts.Page >= 0 && opts.PageSize > 0 {
  429. var start int
  430. if opts.Page == 0 {
  431. start = 0
  432. } else {
  433. start = (opts.Page - 1) * opts.PageSize
  434. }
  435. sess.Limit(opts.PageSize, start)
  436. }
  437. sess.OrderBy("ai_model_manage.created_unix DESC")
  438. aiModelManages := make([]*AiModelManage, 0, setting.UI.IssuePagingNum)
  439. if err := sess.Table("ai_model_manage").Where(cond).
  440. Find(&aiModelManages); err != nil {
  441. return nil, 0, fmt.Errorf("Find: %v", err)
  442. }
  443. return aiModelManages, count, nil
  444. }
  445. func QueryModelConvertCountByRepoID(repoId int64) int64 {
  446. convert := new(AiModelConvert)
  447. total, _ := x.Where("repo_id =?", repoId).Count(convert)
  448. return total
  449. }
  450. func QueryModelConvertByRepoID(repoId int64) ([]*AiModelConvert, error) {
  451. sess := x.NewSession()
  452. defer sess.Close()
  453. var cond = builder.NewCond()
  454. cond = cond.And(
  455. builder.Eq{"ai_model_convert.repo_id": repoId},
  456. )
  457. sess.OrderBy("ai_model_convert.created_unix DESC")
  458. aiModelManageConvert := make([]*AiModelConvert, 0)
  459. if err := sess.Table(new(AiModelConvert)).Where(cond).
  460. Find(&aiModelManageConvert); err != nil {
  461. return nil, fmt.Errorf("Find: %v", err)
  462. }
  463. return aiModelManageConvert, nil
  464. }
  465. func QueryModelConvertByUserID(userID int64) ([]*AiModelConvert, error) {
  466. sess := x.NewSession()
  467. defer sess.Close()
  468. var cond = builder.NewCond()
  469. cond = cond.And(
  470. builder.Eq{"ai_model_convert.user_id": userID},
  471. )
  472. sess.OrderBy("ai_model_convert.created_unix DESC")
  473. aiModelManageConvert := make([]*AiModelConvert, 0)
  474. if err := sess.Table(new(AiModelConvert)).Where(cond).
  475. Find(&aiModelManageConvert); err != nil {
  476. return nil, fmt.Errorf("Find: %v", err)
  477. }
  478. return aiModelManageConvert, nil
  479. }
  480. func QueryModelConvert(opts *AiModelQueryOptions) ([]*AiModelConvert, int64, error) {
  481. sess := x.NewSession()
  482. defer sess.Close()
  483. var cond = builder.NewCond()
  484. if opts.RepoID > 0 {
  485. cond = cond.And(
  486. builder.Eq{"ai_model_convert.repo_id": opts.RepoID},
  487. )
  488. }
  489. if opts.UserID > 0 {
  490. cond = cond.And(
  491. builder.Eq{"ai_model_convert.user_id": opts.UserID},
  492. )
  493. }
  494. count, err := sess.Where(cond).Count(new(AiModelConvert))
  495. if err != nil {
  496. return nil, 0, fmt.Errorf("Count: %v", err)
  497. }
  498. if opts.Page >= 0 && opts.PageSize > 0 {
  499. var start int
  500. if opts.Page == 0 {
  501. start = 0
  502. } else {
  503. start = (opts.Page - 1) * opts.PageSize
  504. }
  505. sess.Limit(opts.PageSize, start)
  506. }
  507. sess.OrderBy("ai_model_convert.created_unix DESC")
  508. aiModelManageConvert := make([]*AiModelConvert, 0, setting.UI.IssuePagingNum)
  509. if err := sess.Table(new(AiModelConvert)).Where(cond).
  510. Find(&aiModelManageConvert); err != nil {
  511. return nil, 0, fmt.Errorf("Find: %v", err)
  512. }
  513. return aiModelManageConvert, count, nil
  514. }