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