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

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