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

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