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

3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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. }
  88. func (a *AiModelConvert) IsGpuTrainTask() bool {
  89. if a.SrcEngine == 0 || a.SrcEngine == 1 || a.SrcEngine == 4 || a.SrcEngine == 6 {
  90. return true
  91. }
  92. return false
  93. }
  94. func ModelComputeAndSetDuration(task *AiModelConvert, result JobResultPayload) {
  95. if task.StartTime == 0 {
  96. task.StartTime = timeutil.TimeStamp(result.JobStatus.CreatedTime / 1000)
  97. }
  98. if task.EndTime == 0 {
  99. if result.JobStatus.CompletedTime > 0 {
  100. task.EndTime = timeutil.TimeStamp(result.JobStatus.CompletedTime / 1000)
  101. }
  102. }
  103. var d int64
  104. if task.StartTime == 0 {
  105. d = 0
  106. } else if task.EndTime == 0 {
  107. d = time.Now().Unix() - task.StartTime.AsTime().Unix()
  108. } else {
  109. d = task.EndTime.AsTime().Unix() - task.StartTime.AsTime().Unix()
  110. }
  111. if d < 0 {
  112. d = 0
  113. }
  114. task.RunTime = d
  115. task.TrainJobDuration = ConvertDurationToStr(d)
  116. }
  117. func ModelConvertSetDuration(task *AiModelConvert) {
  118. var d int64
  119. if task.StartTime == 0 {
  120. d = 0
  121. } else if task.EndTime == 0 {
  122. d = time.Now().Unix() - task.StartTime.AsTime().Unix()
  123. } else {
  124. d = task.EndTime.AsTime().Unix() - task.StartTime.AsTime().Unix()
  125. }
  126. if d < 0 {
  127. d = 0
  128. }
  129. task.RunTime = d
  130. task.TrainJobDuration = ConvertDurationToStr(d)
  131. }
  132. func UpdateModelConvertModelArts(id string, CloudBrainTaskId string, VersionId string) error {
  133. var sess *xorm.Session
  134. sess = x.ID(id)
  135. defer sess.Close()
  136. re, err := sess.Cols("cloud_brain_task_id,model_arts_version_id").Update(&AiModelConvert{
  137. CloudBrainTaskId: CloudBrainTaskId,
  138. ModelArtsVersionId: VersionId,
  139. })
  140. if err != nil {
  141. return err
  142. }
  143. log.Info("success to update cloud_brain_task_id from db.re=" + fmt.Sprint((re)))
  144. return nil
  145. }
  146. func UpdateModelConvertFailed(id string, status string, statusResult string) error {
  147. var sess *xorm.Session
  148. sess = x.ID(id)
  149. defer sess.Close()
  150. re, err := sess.Cols("status", "status_result").Update(&AiModelConvert{
  151. Status: status,
  152. StatusResult: statusResult,
  153. })
  154. if err != nil {
  155. return err
  156. }
  157. log.Info("success to update cloud_brain_task_id from db.re=" + fmt.Sprint((re)))
  158. return nil
  159. }
  160. func UpdateModelConvertCBTI(id string, CloudBrainTaskId string) error {
  161. var sess *xorm.Session
  162. sess = x.ID(id)
  163. defer sess.Close()
  164. re, err := sess.Cols("cloud_brain_task_id").Update(&AiModelConvert{
  165. CloudBrainTaskId: CloudBrainTaskId,
  166. })
  167. if err != nil {
  168. return err
  169. }
  170. log.Info("success to update cloud_brain_task_id from db.re=" + fmt.Sprint((re)))
  171. return nil
  172. }
  173. func UpdateModelConvert(job *AiModelConvert) error {
  174. return updateModelConvert(x, job)
  175. }
  176. func updateModelConvert(e Engine, job *AiModelConvert) error {
  177. var sess *xorm.Session
  178. sess = e.Where("id = ?", job.ID)
  179. _, err := sess.Cols("status", "train_job_duration", "run_time", "start_time", "end_time", "updated_unix").Update(job)
  180. return err
  181. }
  182. func SaveModelConvert(modelConvert *AiModelConvert) error {
  183. sess := x.NewSession()
  184. defer sess.Close()
  185. re, err := sess.Insert(modelConvert)
  186. if err != nil {
  187. log.Info("insert modelConvert error." + err.Error())
  188. return err
  189. }
  190. log.Info("success to save modelConvert db.re=" + fmt.Sprint((re)))
  191. return nil
  192. }
  193. func SaveModelToDb(model *AiModelManage) error {
  194. sess := x.NewSession()
  195. defer sess.Close()
  196. re, err := sess.Insert(model)
  197. if err != nil {
  198. log.Info("insert error." + err.Error())
  199. return err
  200. }
  201. log.Info("success to save db.re=" + fmt.Sprint((re)))
  202. return nil
  203. }
  204. func QueryModelConvertById(id string) (*AiModelConvert, error) {
  205. sess := x.NewSession()
  206. defer sess.Close()
  207. sess.Select("*").Table(new(AiModelConvert)).Where("id='" + id + "'")
  208. aiModelManageConvertList := make([]*AiModelConvert, 0)
  209. err := sess.Find(&aiModelManageConvertList)
  210. if err == nil {
  211. if len(aiModelManageConvertList) == 1 {
  212. return aiModelManageConvertList[0], nil
  213. }
  214. }
  215. return nil, err
  216. }
  217. func QueryModelById(id string) (*AiModelManage, error) {
  218. sess := x.NewSession()
  219. defer sess.Close()
  220. sess.Select("*").Table("ai_model_manage").
  221. Where("id='" + id + "'")
  222. aiModelManageList := make([]*AiModelManage, 0)
  223. err := sess.Find(&aiModelManageList)
  224. if err == nil {
  225. if len(aiModelManageList) == 1 {
  226. return aiModelManageList[0], nil
  227. }
  228. } else {
  229. log.Info("error=" + err.Error())
  230. }
  231. return nil, err
  232. }
  233. func DeleteModelConvertById(id string) error {
  234. sess := x.NewSession()
  235. defer sess.Close()
  236. re, err := sess.Delete(&AiModelConvert{
  237. ID: id,
  238. })
  239. if err != nil {
  240. return err
  241. }
  242. log.Info("success to delete AiModelManageConvert from db.re=" + fmt.Sprint((re)))
  243. return nil
  244. }
  245. func DeleteModelById(id string) error {
  246. sess := x.NewSession()
  247. defer sess.Close()
  248. re, err := sess.Delete(&AiModelManage{
  249. ID: id,
  250. })
  251. if err != nil {
  252. return err
  253. }
  254. log.Info("success to delete from db.re=" + fmt.Sprint((re)))
  255. return nil
  256. }
  257. func ModifyModelDescription(id string, description string) error {
  258. var sess *xorm.Session
  259. sess = x.ID(id)
  260. defer sess.Close()
  261. re, err := sess.Cols("description").Update(&AiModelManage{
  262. Description: description,
  263. })
  264. if err != nil {
  265. return err
  266. }
  267. log.Info("success to update description from db.re=" + fmt.Sprint((re)))
  268. return nil
  269. }
  270. func ModifyModelPrivate(id string, isPrivate bool) error {
  271. var sess *xorm.Session
  272. sess = x.ID(id)
  273. defer sess.Close()
  274. re, err := sess.Cols("is_private").Update(&AiModelManage{
  275. IsPrivate: isPrivate,
  276. })
  277. if err != nil {
  278. return err
  279. }
  280. log.Info("success to update isPrivate from db.re=" + fmt.Sprint((re)))
  281. return nil
  282. }
  283. func ModifyLocalModel(id string, name, label, description string, engine int) error {
  284. var sess *xorm.Session
  285. sess = x.ID(id)
  286. defer sess.Close()
  287. re, err := sess.Cols("name", "label", "description", "engine").Update(&AiModelManage{
  288. Description: description,
  289. Name: name,
  290. Label: label,
  291. Engine: int64(engine),
  292. })
  293. if err != nil {
  294. return err
  295. }
  296. log.Info("success to update description from db.re=" + fmt.Sprint((re)))
  297. return nil
  298. }
  299. func ModifyModelSize(id string, size int64) error {
  300. var sess *xorm.Session
  301. sess = x.ID(id)
  302. defer sess.Close()
  303. re, err := sess.Cols("size").Update(&AiModelManage{
  304. Size: size,
  305. })
  306. if err != nil {
  307. return err
  308. }
  309. log.Info("success to update size from db.re=" + fmt.Sprint((re)))
  310. return nil
  311. }
  312. func ModifyModelStatus(id string, modelSize int64, status int, modelPath string, statusDesc string) error {
  313. var sess *xorm.Session
  314. sess = x.ID(id)
  315. defer sess.Close()
  316. re, err := sess.Cols("size", "status", "path", "status_desc").Update(&AiModelManage{
  317. Size: modelSize,
  318. Status: status,
  319. Path: modelPath,
  320. StatusDesc: statusDesc,
  321. })
  322. if err != nil {
  323. return err
  324. }
  325. log.Info("success to update ModelStatus from db.re=" + fmt.Sprint((re)))
  326. return nil
  327. }
  328. func ModifyModelNewProperty(id string, new int, versioncount int) error {
  329. var sess *xorm.Session
  330. sess = x.ID(id)
  331. defer sess.Close()
  332. re, err := sess.Cols("new", "version_count").Update(&AiModelManage{
  333. New: new,
  334. VersionCount: versioncount,
  335. })
  336. if err != nil {
  337. return err
  338. }
  339. log.Info("success to update new property from db.re=" + fmt.Sprint((re)))
  340. return nil
  341. }
  342. func ModifyModelDownloadCount(id string) error {
  343. sess := x.NewSession()
  344. defer sess.Close()
  345. if _, err := sess.Exec("UPDATE `ai_model_manage` SET download_count = download_count + 1 WHERE id = ?", id); err != nil {
  346. return err
  347. }
  348. return nil
  349. }
  350. func QueryModelByName(name string, repoId int64) []*AiModelManage {
  351. sess := x.NewSession()
  352. defer sess.Close()
  353. sess.Select("*").Table("ai_model_manage").
  354. Where("name='" + name + "' and repo_id=" + fmt.Sprint(repoId)).OrderBy("created_unix desc")
  355. aiModelManageList := make([]*AiModelManage, 0)
  356. sess.Find(&aiModelManageList)
  357. return aiModelManageList
  358. }
  359. func QueryModel(opts *AiModelQueryOptions) ([]*AiModelManage, int64, error) {
  360. sess := x.NewSession()
  361. defer sess.Close()
  362. var cond = builder.NewCond()
  363. if opts.RepoID > 0 {
  364. cond = cond.And(
  365. builder.Eq{"ai_model_manage.repo_id": opts.RepoID},
  366. )
  367. }
  368. if opts.UserID > 0 {
  369. cond = cond.And(
  370. builder.Eq{"ai_model_manage.user_id": opts.UserID},
  371. )
  372. }
  373. if opts.New >= 0 {
  374. cond = cond.And(
  375. builder.Eq{"ai_model_manage.new": opts.New},
  376. )
  377. }
  378. if len(opts.ModelID) > 0 {
  379. cond = cond.And(
  380. builder.Eq{"ai_model_manage.id": opts.ModelID},
  381. )
  382. }
  383. if (opts.Type) >= 0 {
  384. cond = cond.And(
  385. builder.Eq{"ai_model_manage.type": opts.Type},
  386. )
  387. }
  388. if (opts.Status) >= 0 {
  389. cond = cond.And(
  390. builder.Eq{"ai_model_manage.status": opts.Status},
  391. )
  392. }
  393. if !opts.IsOnlyThisRepo {
  394. orCon := builder.NewCond()
  395. orCon = orCon.And(builder.Eq{"ai_model_manage.is_private": false})
  396. cond = cond.Or(orCon)
  397. }
  398. count, err := sess.Where(cond).Count(new(AiModelManage))
  399. if err != nil {
  400. return nil, 0, fmt.Errorf("Count: %v", err)
  401. }
  402. if opts.Page >= 0 && opts.PageSize > 0 {
  403. var start int
  404. if opts.Page == 0 {
  405. start = 0
  406. } else {
  407. start = (opts.Page - 1) * opts.PageSize
  408. }
  409. sess.Limit(opts.PageSize, start)
  410. }
  411. sess.OrderBy("ai_model_manage.created_unix DESC")
  412. aiModelManages := make([]*AiModelManage, 0, setting.UI.IssuePagingNum)
  413. if err := sess.Table("ai_model_manage").Where(cond).
  414. Find(&aiModelManages); err != nil {
  415. return nil, 0, fmt.Errorf("Find: %v", err)
  416. }
  417. return aiModelManages, count, nil
  418. }
  419. func QueryModelConvertByRepoID(repoId int64) ([]*AiModelConvert, error) {
  420. sess := x.NewSession()
  421. defer sess.Close()
  422. var cond = builder.NewCond()
  423. cond = cond.And(
  424. builder.Eq{"ai_model_convert.repo_id": repoId},
  425. )
  426. sess.OrderBy("ai_model_convert.created_unix DESC")
  427. aiModelManageConvert := make([]*AiModelConvert, 0)
  428. if err := sess.Table(new(AiModelConvert)).Where(cond).
  429. Find(&aiModelManageConvert); err != nil {
  430. return nil, fmt.Errorf("Find: %v", err)
  431. }
  432. return aiModelManageConvert, nil
  433. }
  434. func QueryModelConvertByUserID(userID int64) ([]*AiModelConvert, error) {
  435. sess := x.NewSession()
  436. defer sess.Close()
  437. var cond = builder.NewCond()
  438. cond = cond.And(
  439. builder.Eq{"ai_model_convert.user_id": userID},
  440. )
  441. sess.OrderBy("ai_model_convert.created_unix DESC")
  442. aiModelManageConvert := make([]*AiModelConvert, 0)
  443. if err := sess.Table(new(AiModelConvert)).Where(cond).
  444. Find(&aiModelManageConvert); err != nil {
  445. return nil, fmt.Errorf("Find: %v", err)
  446. }
  447. return aiModelManageConvert, nil
  448. }
  449. func QueryModelConvert(opts *AiModelQueryOptions) ([]*AiModelConvert, int64, error) {
  450. sess := x.NewSession()
  451. defer sess.Close()
  452. var cond = builder.NewCond()
  453. if opts.RepoID > 0 {
  454. cond = cond.And(
  455. builder.Eq{"ai_model_convert.repo_id": opts.RepoID},
  456. )
  457. }
  458. if opts.UserID > 0 {
  459. cond = cond.And(
  460. builder.Eq{"ai_model_convert.user_id": opts.UserID},
  461. )
  462. }
  463. count, err := sess.Where(cond).Count(new(AiModelConvert))
  464. if err != nil {
  465. return nil, 0, fmt.Errorf("Count: %v", err)
  466. }
  467. if opts.Page >= 0 && opts.PageSize > 0 {
  468. var start int
  469. if opts.Page == 0 {
  470. start = 0
  471. } else {
  472. start = (opts.Page - 1) * opts.PageSize
  473. }
  474. sess.Limit(opts.PageSize, start)
  475. }
  476. sess.OrderBy("ai_model_convert.created_unix DESC")
  477. aiModelManageConvert := make([]*AiModelConvert, 0, setting.UI.IssuePagingNum)
  478. if err := sess.Table(new(AiModelConvert)).Where(cond).
  479. Find(&aiModelManageConvert); err != nil {
  480. return nil, 0, fmt.Errorf("Find: %v", err)
  481. }
  482. return aiModelManageConvert, count, nil
  483. }