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

3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  1. package repo
  2. import (
  3. "archive/zip"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "net/url"
  9. "path"
  10. "regexp"
  11. "strings"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/context"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/notification"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/modules/storage"
  18. "code.gitea.io/gitea/services/cloudbrain/resource"
  19. uuid "github.com/satori/go.uuid"
  20. )
  21. const (
  22. Attachment_model = "model"
  23. Model_prefix = "aimodels/"
  24. tplModelManageIndex = "repo/modelmanage/index"
  25. tplModelManageDownload = "repo/modelmanage/download"
  26. tplModelInfo = "repo/modelmanage/showinfo"
  27. tplCreateLocalModelInfo = "repo/modelmanage/create_local_1"
  28. tplCreateLocalForUploadModelInfo = "repo/modelmanage/create_local_2"
  29. tplCreateOnlineModelInfo = "repo/modelmanage/create_online"
  30. MODEL_LATEST = 1
  31. MODEL_NOT_LATEST = 0
  32. MODEL_MAX_SIZE = 1024 * 1024 * 1024
  33. STATUS_COPY_MODEL = 1
  34. STATUS_FINISHED = 0
  35. STATUS_ERROR = 2
  36. MODEL_LOCAL_TYPE = 1
  37. MODEL_ONLINE_TYPE = 0
  38. )
  39. func saveModelByParameters(jobId string, versionName string, name string, version string, label string, description string, engine int, ctx *context.Context) (string, error) {
  40. aiTask, err := models.GetCloudbrainByJobIDAndVersionName(jobId, versionName)
  41. if err != nil {
  42. aiTask, err = models.GetRepoCloudBrainByJobID(ctx.Repo.Repository.ID, jobId)
  43. if err != nil {
  44. log.Info("query task error." + err.Error())
  45. return "", err
  46. } else {
  47. log.Info("query gpu train task.")
  48. }
  49. }
  50. uuid := uuid.NewV4()
  51. id := uuid.String()
  52. modelPath := id
  53. var lastNewModelId string
  54. var modelSize int64
  55. log.Info("find task name:" + aiTask.JobName)
  56. aimodels := models.QueryModelByName(name, aiTask.RepoID)
  57. if len(aimodels) > 0 {
  58. for _, model := range aimodels {
  59. if model.Version == version {
  60. return "", errors.New(ctx.Tr("repo.model.manage.create_error"))
  61. }
  62. if model.New == MODEL_LATEST {
  63. lastNewModelId = model.ID
  64. }
  65. }
  66. }
  67. cloudType := aiTask.Type
  68. modelSelectedFile := ctx.Query("modelSelectedFile")
  69. //download model zip //train type
  70. if aiTask.ComputeResource == models.NPUResource {
  71. cloudType = models.TypeCloudBrainTwo
  72. } else if aiTask.ComputeResource == models.GPUResource {
  73. cloudType = models.TypeCloudBrainOne
  74. }
  75. spec, err := resource.GetCloudbrainSpec(aiTask.ID)
  76. if err == nil {
  77. specJson, _ := json.Marshal(spec)
  78. aiTask.FlavorName = string(specJson)
  79. }
  80. accuracy := make(map[string]string)
  81. accuracy["F1"] = ""
  82. accuracy["Recall"] = ""
  83. accuracy["Accuracy"] = ""
  84. accuracy["Precision"] = ""
  85. accuracyJson, _ := json.Marshal(accuracy)
  86. log.Info("accuracyJson=" + string(accuracyJson))
  87. aiTask.ContainerIp = ""
  88. aiTaskJson, _ := json.Marshal(aiTask)
  89. isPrivate := ctx.QueryBool("isPrivate")
  90. model := &models.AiModelManage{
  91. ID: id,
  92. Version: version,
  93. VersionCount: len(aimodels) + 1,
  94. Label: label,
  95. Name: name,
  96. Description: description,
  97. New: MODEL_LATEST,
  98. Type: cloudType,
  99. Path: modelPath,
  100. Size: modelSize,
  101. AttachmentId: aiTask.Uuid,
  102. RepoId: aiTask.RepoID,
  103. UserId: ctx.User.ID,
  104. CodeBranch: aiTask.BranchName,
  105. CodeCommitID: aiTask.CommitID,
  106. Engine: int64(engine),
  107. TrainTaskInfo: string(aiTaskJson),
  108. Accuracy: string(accuracyJson),
  109. Status: STATUS_COPY_MODEL,
  110. IsPrivate: isPrivate,
  111. }
  112. err = models.SaveModelToDb(model)
  113. if err != nil {
  114. return "", err
  115. }
  116. if len(lastNewModelId) > 0 {
  117. //udpate status and version count
  118. models.ModifyModelNewProperty(lastNewModelId, MODEL_NOT_LATEST, 0)
  119. }
  120. var units []models.RepoUnit
  121. var deleteUnitTypes []models.UnitType
  122. units = append(units, models.RepoUnit{
  123. RepoID: ctx.Repo.Repository.ID,
  124. Type: models.UnitTypeModelManage,
  125. Config: &models.ModelManageConfig{
  126. EnableModelManage: true,
  127. },
  128. })
  129. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeModelManage)
  130. models.UpdateRepositoryUnits(ctx.Repo.Repository, units, deleteUnitTypes)
  131. go asyncToCopyModel(aiTask, id, modelSelectedFile)
  132. log.Info("save model end.")
  133. notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, id, name, models.ActionCreateNewModelTask)
  134. return id, nil
  135. }
  136. func asyncToCopyModel(aiTask *models.Cloudbrain, id string, modelSelectedFile string) {
  137. if aiTask.ComputeResource == models.NPUResource {
  138. modelPath, modelSize, err := downloadModelFromCloudBrainTwo(id, aiTask.JobName, "", aiTask.TrainUrl, modelSelectedFile)
  139. if err != nil {
  140. updateStatus(id, 0, STATUS_ERROR, modelPath, err.Error())
  141. log.Info("download model from CloudBrainTwo faild." + err.Error())
  142. } else {
  143. updateStatus(id, modelSize, STATUS_FINISHED, modelPath, "")
  144. }
  145. } else if aiTask.ComputeResource == models.GPUResource {
  146. modelPath, modelSize, err := downloadModelFromCloudBrainOne(id, aiTask.JobName, "", aiTask.TrainUrl, modelSelectedFile)
  147. if err != nil {
  148. updateStatus(id, 0, STATUS_ERROR, modelPath, err.Error())
  149. log.Info("download model from CloudBrainOne faild." + err.Error())
  150. } else {
  151. updateStatus(id, modelSize, STATUS_FINISHED, modelPath, "")
  152. }
  153. }
  154. }
  155. func updateStatus(id string, modelSize int64, status int, modelPath string, statusDesc string) {
  156. if len(statusDesc) > 400 {
  157. statusDesc = statusDesc[0:400]
  158. }
  159. err := models.ModifyModelStatus(id, modelSize, status, modelPath, statusDesc)
  160. if err != nil {
  161. log.Info("update status error." + err.Error())
  162. }
  163. }
  164. func SaveNewNameModel(ctx *context.Context) {
  165. if !ctx.Repo.CanWrite(models.UnitTypeModelManage) {
  166. ctx.Error(403, ctx.Tr("repo.model_noright"))
  167. return
  168. }
  169. name := ctx.Query("name")
  170. if name == "" {
  171. ctx.Error(500, fmt.Sprintf("name or version is null."))
  172. return
  173. }
  174. aimodels := models.QueryModelByName(name, ctx.Repo.Repository.ID)
  175. if len(aimodels) > 0 {
  176. ctx.Error(500, ctx.Tr("repo.model_rename"))
  177. return
  178. }
  179. SaveModel(ctx)
  180. ctx.Status(200)
  181. log.Info("save model end.")
  182. }
  183. func SaveLocalModel(ctx *context.Context) {
  184. if !ctx.Repo.CanWrite(models.UnitTypeModelManage) {
  185. ctx.Error(403, ctx.Tr("repo.model_noright"))
  186. return
  187. }
  188. re := map[string]string{
  189. "code": "-1",
  190. }
  191. log.Info("save SaveLocalModel start.")
  192. uuid := uuid.NewV4()
  193. id := uuid.String()
  194. name := ctx.Query("name")
  195. version := ctx.Query("version")
  196. if version == "" {
  197. version = "0.0.1"
  198. }
  199. label := ctx.Query("label")
  200. description := ctx.Query("description")
  201. engine := ctx.QueryInt("engine")
  202. taskType := ctx.QueryInt("type")
  203. isPrivate := ctx.QueryBool("isPrivate")
  204. modelActualPath := ""
  205. if taskType == models.TypeCloudBrainOne {
  206. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(id) + "/"
  207. modelActualPath = setting.Attachment.Minio.Bucket + "/" + destKeyNamePrefix
  208. } else if taskType == models.TypeCloudBrainTwo {
  209. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(id) + "/"
  210. modelActualPath = setting.Bucket + "/" + destKeyNamePrefix
  211. } else {
  212. re["msg"] = "type is error."
  213. ctx.JSON(200, re)
  214. return
  215. }
  216. var lastNewModelId string
  217. repoId := ctx.Repo.Repository.ID
  218. aimodels := models.QueryModelByName(name, repoId)
  219. if len(aimodels) > 0 {
  220. for _, model := range aimodels {
  221. if model.Version == version {
  222. re["msg"] = ctx.Tr("repo.model.manage.create_error")
  223. ctx.JSON(200, re)
  224. return
  225. }
  226. if model.New == MODEL_LATEST {
  227. lastNewModelId = model.ID
  228. }
  229. }
  230. }
  231. model := &models.AiModelManage{
  232. ID: id,
  233. Version: version,
  234. ModelType: MODEL_LOCAL_TYPE,
  235. VersionCount: len(aimodels) + 1,
  236. Label: label,
  237. Name: name,
  238. Description: description,
  239. New: MODEL_LATEST,
  240. Type: taskType,
  241. Path: modelActualPath,
  242. Size: 0,
  243. AttachmentId: "",
  244. RepoId: repoId,
  245. UserId: ctx.User.ID,
  246. Engine: int64(engine),
  247. TrainTaskInfo: "",
  248. Accuracy: "",
  249. Status: STATUS_FINISHED,
  250. IsPrivate: isPrivate,
  251. }
  252. err := models.SaveModelToDb(model)
  253. if err != nil {
  254. re["msg"] = err.Error()
  255. ctx.JSON(200, re)
  256. return
  257. }
  258. if len(lastNewModelId) > 0 {
  259. //udpate status and version count
  260. models.ModifyModelNewProperty(lastNewModelId, MODEL_NOT_LATEST, 0)
  261. }
  262. var units []models.RepoUnit
  263. var deleteUnitTypes []models.UnitType
  264. units = append(units, models.RepoUnit{
  265. RepoID: ctx.Repo.Repository.ID,
  266. Type: models.UnitTypeModelManage,
  267. Config: &models.ModelManageConfig{
  268. EnableModelManage: true,
  269. },
  270. })
  271. deleteUnitTypes = append(deleteUnitTypes, models.UnitTypeModelManage)
  272. models.UpdateRepositoryUnits(ctx.Repo.Repository, units, deleteUnitTypes)
  273. log.Info("save model end.")
  274. notification.NotifyOtherTask(ctx.User, ctx.Repo.Repository, id, name, models.ActionCreateNewModelTask)
  275. re["code"] = "0"
  276. re["id"] = id
  277. ctx.JSON(200, re)
  278. }
  279. func getSize(files []storage.FileInfo) int64 {
  280. var size int64
  281. for _, file := range files {
  282. size += file.Size
  283. }
  284. return size
  285. }
  286. func UpdateModelSize(modeluuid string) {
  287. model, err := models.QueryModelById(modeluuid)
  288. if err == nil {
  289. if model.Type == models.TypeCloudBrainOne {
  290. if strings.HasPrefix(model.Path, setting.Attachment.Minio.Bucket+"/"+Model_prefix) {
  291. files, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, model.Path[len(setting.Attachment.Minio.Bucket)+1:])
  292. if err != nil {
  293. log.Info("Failed to query model size from minio. id=" + modeluuid)
  294. }
  295. size := getSize(files)
  296. models.ModifyModelSize(modeluuid, size)
  297. }
  298. } else if model.Type == models.TypeCloudBrainTwo {
  299. if strings.HasPrefix(model.Path, setting.Bucket+"/"+Model_prefix) {
  300. files, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, model.Path[len(setting.Bucket)+1:])
  301. if err != nil {
  302. log.Info("Failed to query model size from obs. id=" + modeluuid)
  303. }
  304. size := getSize(files)
  305. models.ModifyModelSize(modeluuid, size)
  306. }
  307. }
  308. } else {
  309. log.Info("not found model,uuid=" + modeluuid)
  310. }
  311. }
  312. func SaveModel(ctx *context.Context) {
  313. if !ctx.Repo.CanWrite(models.UnitTypeModelManage) {
  314. ctx.Error(403, ctx.Tr("repo.model_noright"))
  315. return
  316. }
  317. log.Info("save model start.")
  318. JobId := ctx.Query("jobId")
  319. VersionName := ctx.Query("versionName")
  320. name := ctx.Query("name")
  321. version := ctx.Query("version")
  322. label := ctx.Query("label")
  323. description := ctx.Query("description")
  324. engine := ctx.QueryInt("engine")
  325. modelSelectedFile := ctx.Query("modelSelectedFile")
  326. log.Info("engine=" + fmt.Sprint(engine) + " modelSelectedFile=" + modelSelectedFile)
  327. re := map[string]string{
  328. "code": "-1",
  329. }
  330. if JobId == "" || VersionName == "" {
  331. re["msg"] = "JobId or VersionName is null."
  332. ctx.JSON(200, re)
  333. return
  334. }
  335. if modelSelectedFile == "" {
  336. re["msg"] = "Not selected model file."
  337. ctx.JSON(200, re)
  338. return
  339. }
  340. if name == "" || version == "" {
  341. re["msg"] = "name or version is null."
  342. ctx.JSON(200, re)
  343. return
  344. }
  345. id, err := saveModelByParameters(JobId, VersionName, name, version, label, description, engine, ctx)
  346. if err != nil {
  347. log.Info("save model error." + err.Error())
  348. re["msg"] = err.Error()
  349. } else {
  350. re["code"] = "0"
  351. re["id"] = id
  352. }
  353. ctx.JSON(200, re)
  354. log.Info("save model end.")
  355. }
  356. func downloadModelFromCloudBrainTwo(modelUUID string, jobName string, parentDir string, trainUrl string, modelSelectedFile string) (string, int64, error) {
  357. objectkey := strings.TrimPrefix(path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, parentDir), "/")
  358. if trainUrl != "" {
  359. objectkey = strings.Trim(trainUrl[len(setting.Bucket)+1:], "/")
  360. }
  361. prefix := objectkey + "/"
  362. filterFiles := strings.Split(modelSelectedFile, ";")
  363. Files := make([]string, 0)
  364. for _, shortFile := range filterFiles {
  365. Files = append(Files, prefix+shortFile)
  366. }
  367. totalSize := storage.ObsGetFilesSize(setting.Bucket, Files)
  368. if float64(totalSize) > setting.MaxModelSize*MODEL_MAX_SIZE {
  369. return "", 0, errors.New("Cannot create model, as model is exceed " + fmt.Sprint(setting.MaxModelSize) + "G.")
  370. }
  371. modelDbResult, err := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, objectkey, "")
  372. log.Info("bucket=" + setting.Bucket + " objectkey=" + objectkey)
  373. if err != nil {
  374. log.Info("get TrainJobListModel failed:", err)
  375. return "", 0, err
  376. }
  377. if len(modelDbResult) == 0 {
  378. return "", 0, errors.New("Cannot create model, as model is empty.")
  379. }
  380. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(modelUUID) + "/"
  381. size, err := storage.ObsCopyManyFile(setting.Bucket, prefix, setting.Bucket, destKeyNamePrefix, filterFiles)
  382. dataActualPath := setting.Bucket + "/" + destKeyNamePrefix
  383. return dataActualPath, size, nil
  384. }
  385. func downloadModelFromCloudBrainOne(modelUUID string, jobName string, parentDir string, trainUrl string, modelSelectedFile string) (string, int64, error) {
  386. modelActualPath := storage.GetMinioPath(jobName, "/model/")
  387. log.Info("modelActualPath=" + modelActualPath)
  388. modelSrcPrefix := setting.CBCodePathPrefix + jobName + "/model/"
  389. destKeyNamePrefix := Model_prefix + models.AttachmentRelativePath(modelUUID) + "/"
  390. bucketName := setting.Attachment.Minio.Bucket
  391. log.Info("destKeyNamePrefix=" + destKeyNamePrefix + " modelSrcPrefix=" + modelSrcPrefix + " bucket=" + bucketName)
  392. filterFiles := strings.Split(modelSelectedFile, ";")
  393. Files := make([]string, 0)
  394. for _, shortFile := range filterFiles {
  395. Files = append(Files, modelSrcPrefix+shortFile)
  396. }
  397. totalSize := storage.MinioGetFilesSize(bucketName, Files)
  398. if float64(totalSize) > setting.MaxModelSize*MODEL_MAX_SIZE {
  399. return "", 0, errors.New("Cannot create model, as model is exceed " + fmt.Sprint(setting.MaxModelSize) + "G.")
  400. }
  401. size, err := storage.MinioCopyFiles(bucketName, modelSrcPrefix, destKeyNamePrefix, filterFiles)
  402. if err == nil {
  403. dataActualPath := bucketName + "/" + destKeyNamePrefix
  404. return dataActualPath, size, nil
  405. } else {
  406. return "", 0, nil
  407. }
  408. }
  409. func DeleteModelFile(ctx *context.Context) {
  410. log.Info("delete model start.")
  411. id := ctx.Query("id")
  412. fileName := ctx.Query("fileName")
  413. model, err := models.QueryModelById(id)
  414. if err == nil {
  415. if model.ModelType == MODEL_LOCAL_TYPE {
  416. if model.Type == models.TypeCloudBrainOne {
  417. bucketName := setting.Attachment.Minio.Bucket
  418. objectName := model.Path[len(bucketName)+1:] + fileName
  419. log.Info("delete bucket=" + bucketName + " path=" + objectName)
  420. if strings.HasPrefix(model.Path, bucketName+"/"+Model_prefix) {
  421. totalSize := storage.MinioGetFilesSize(bucketName, []string{objectName})
  422. err := storage.Attachments.DeleteDir(objectName)
  423. if err != nil {
  424. log.Info("Failed to delete model. id=" + id)
  425. re := map[string]string{
  426. "code": "-1",
  427. }
  428. re["msg"] = err.Error()
  429. ctx.JSON(200, re)
  430. return
  431. } else {
  432. log.Info("delete minio file size is:" + fmt.Sprint(totalSize))
  433. models.ModifyModelSize(id, model.Size-totalSize)
  434. }
  435. }
  436. } else if model.Type == models.TypeCloudBrainTwo {
  437. bucketName := setting.Bucket
  438. objectName := model.Path[len(setting.Bucket)+1:] + fileName
  439. log.Info("delete bucket=" + setting.Bucket + " path=" + objectName)
  440. if strings.HasPrefix(model.Path, bucketName+"/"+Model_prefix) {
  441. totalSize := storage.ObsGetFilesSize(bucketName, []string{objectName})
  442. err := storage.ObsRemoveObject(bucketName, objectName)
  443. if err != nil {
  444. log.Info("Failed to delete model. id=" + id)
  445. re := map[string]string{
  446. "code": "-1",
  447. }
  448. re["msg"] = err.Error()
  449. ctx.JSON(200, re)
  450. return
  451. } else {
  452. log.Info("delete obs file size is:" + fmt.Sprint(totalSize))
  453. models.ModifyModelSize(id, model.Size-totalSize)
  454. }
  455. }
  456. }
  457. }
  458. }
  459. ctx.JSON(200, map[string]string{
  460. "code": "0",
  461. })
  462. }
  463. func DeleteModel(ctx *context.Context) {
  464. log.Info("delete model start.")
  465. id := ctx.Query("id")
  466. err := deleteModelByID(ctx, id)
  467. if err != nil {
  468. re := map[string]string{
  469. "code": "-1",
  470. }
  471. re["msg"] = err.Error()
  472. ctx.JSON(200, re)
  473. } else {
  474. ctx.JSON(200, map[string]string{
  475. "code": "0",
  476. })
  477. }
  478. }
  479. func deleteModelByID(ctx *context.Context, id string) error {
  480. log.Info("delete model start. id=" + id)
  481. model, err := models.QueryModelById(id)
  482. if !isCanDelete(ctx, model.UserId) {
  483. return errors.New(ctx.Tr("repo.model_noright"))
  484. }
  485. if err == nil {
  486. if model.Type == models.TypeCloudBrainOne {
  487. bucketName := setting.Attachment.Minio.Bucket
  488. log.Info("bucket=" + bucketName + " path=" + model.Path)
  489. if strings.HasPrefix(model.Path, bucketName+"/"+Model_prefix) {
  490. err := storage.Attachments.DeleteDir(model.Path[len(bucketName)+1:])
  491. if err != nil {
  492. log.Info("Failed to delete model. id=" + id)
  493. return err
  494. }
  495. }
  496. } else if model.Type == models.TypeCloudBrainTwo {
  497. log.Info("bucket=" + setting.Bucket + " path=" + model.Path)
  498. if strings.HasPrefix(model.Path, setting.Bucket+"/"+Model_prefix) {
  499. err := storage.ObsRemoveObject(setting.Bucket, model.Path[len(setting.Bucket)+1:])
  500. if err != nil {
  501. log.Info("Failed to delete model. id=" + id)
  502. return err
  503. }
  504. }
  505. }
  506. err = models.DeleteModelById(id)
  507. if err == nil { //find a model to change new
  508. aimodels := models.QueryModelByName(model.Name, model.RepoId)
  509. if model.New == MODEL_LATEST {
  510. if len(aimodels) > 0 {
  511. //udpate status and version count
  512. models.ModifyModelNewProperty(aimodels[0].ID, MODEL_LATEST, len(aimodels))
  513. }
  514. } else {
  515. for _, tmpModel := range aimodels {
  516. if tmpModel.New == MODEL_LATEST {
  517. models.ModifyModelNewProperty(tmpModel.ID, MODEL_LATEST, len(aimodels))
  518. break
  519. }
  520. }
  521. }
  522. }
  523. }
  524. return err
  525. }
  526. func DownloadMultiModelFile(ctx *context.Context) {
  527. log.Info("DownloadMultiModelFile start.")
  528. id := ctx.Query("id")
  529. log.Info("id=" + id)
  530. task, err := models.QueryModelById(id)
  531. if err != nil {
  532. log.Error("no such model!", err.Error())
  533. ctx.ServerError("no such model:", err)
  534. return
  535. }
  536. if !isCanDownload(ctx, task) {
  537. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  538. return
  539. }
  540. path := Model_prefix + models.AttachmentRelativePath(id) + "/"
  541. if task.Type == models.TypeCloudBrainTwo {
  542. downloadFromCloudBrainTwo(path, task, ctx, id)
  543. } else if task.Type == models.TypeCloudBrainOne {
  544. downloadFromCloudBrainOne(path, task, ctx, id)
  545. }
  546. }
  547. func MinioDownloadManyFile(path string, ctx *context.Context, returnFileName string, allFile []storage.FileInfo) {
  548. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+url.QueryEscape(returnFileName))
  549. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  550. w := zip.NewWriter(ctx.Resp)
  551. defer w.Close()
  552. for _, oneFile := range allFile {
  553. if oneFile.IsDir {
  554. log.Info("zip dir name:" + oneFile.FileName)
  555. } else {
  556. log.Info("zip file name:" + oneFile.FileName)
  557. fDest, err := w.Create(oneFile.FileName)
  558. if err != nil {
  559. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  560. ctx.ServerError("download file failed:", err)
  561. return
  562. }
  563. log.Info("minio file path=" + (path + oneFile.FileName))
  564. body, err := storage.Attachments.DownloadAFile(setting.Attachment.Minio.Bucket, path+oneFile.FileName)
  565. if err != nil {
  566. log.Info("download file failed: %s\n", err.Error())
  567. ctx.ServerError("download file failed:", err)
  568. return
  569. } else {
  570. defer body.Close()
  571. p := make([]byte, 1024)
  572. var readErr error
  573. var readCount int
  574. // 读取对象内容
  575. for {
  576. readCount, readErr = body.Read(p)
  577. if readCount > 0 {
  578. fDest.Write(p[:readCount])
  579. }
  580. if readErr != nil {
  581. break
  582. }
  583. }
  584. }
  585. }
  586. }
  587. }
  588. func downloadFromCloudBrainOne(path string, task *models.AiModelManage, ctx *context.Context, id string) {
  589. allFile, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, path)
  590. if err == nil {
  591. //count++
  592. models.ModifyModelDownloadCount(id)
  593. returnFileName := task.Name + "_" + task.Version + ".zip"
  594. MinioDownloadManyFile(path, ctx, returnFileName, allFile)
  595. } else {
  596. log.Info("error,msg=" + err.Error())
  597. ctx.ServerError("no file to download.", err)
  598. }
  599. }
  600. func ObsDownloadManyFile(path string, ctx *context.Context, returnFileName string, allFile []storage.FileInfo) {
  601. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+url.QueryEscape(returnFileName))
  602. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  603. w := zip.NewWriter(ctx.Resp)
  604. defer w.Close()
  605. for _, oneFile := range allFile {
  606. if oneFile.IsDir {
  607. log.Info("zip dir name:" + oneFile.FileName)
  608. } else {
  609. log.Info("zip file name:" + oneFile.FileName)
  610. fDest, err := w.Create(oneFile.FileName)
  611. if err != nil {
  612. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  613. ctx.ServerError("download file failed:", err)
  614. return
  615. }
  616. body, err := storage.ObsDownloadAFile(setting.Bucket, path+oneFile.FileName)
  617. if err != nil {
  618. log.Info("download file failed: %s\n", err.Error())
  619. ctx.ServerError("download file failed:", err)
  620. return
  621. } else {
  622. defer body.Close()
  623. p := make([]byte, 1024)
  624. var readErr error
  625. var readCount int
  626. // 读取对象内容
  627. for {
  628. readCount, readErr = body.Read(p)
  629. if readCount > 0 {
  630. fDest.Write(p[:readCount])
  631. }
  632. if readErr != nil {
  633. break
  634. }
  635. }
  636. }
  637. }
  638. }
  639. }
  640. func downloadFromCloudBrainTwo(path string, task *models.AiModelManage, ctx *context.Context, id string) {
  641. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  642. if err == nil {
  643. //count++
  644. models.ModifyModelDownloadCount(id)
  645. returnFileName := task.Name + "_" + task.Version + ".zip"
  646. ObsDownloadManyFile(path, ctx, returnFileName, allFile)
  647. } else {
  648. log.Info("error,msg=" + err.Error())
  649. ctx.ServerError("no file to download.", err)
  650. }
  651. }
  652. func QueryTrainJobVersionList(ctx *context.Context) {
  653. log.Info("query train job version list. start.")
  654. JobID := ctx.Query("jobId")
  655. if JobID == "" {
  656. JobID = ctx.Query("JobId")
  657. }
  658. VersionListTasks, count, err := models.QueryModelTrainJobVersionList(JobID)
  659. log.Info("query return count=" + fmt.Sprint(count))
  660. if err != nil {
  661. ctx.ServerError("QueryTrainJobList:", err)
  662. } else {
  663. ctx.JSON(200, VersionListTasks)
  664. }
  665. }
  666. func QueryTrainJobList(ctx *context.Context) {
  667. log.Info("query train job list. start.")
  668. repoId := ctx.QueryInt64("repoId")
  669. VersionListTasks, count, err := models.QueryModelTrainJobList(repoId)
  670. log.Info("query return count=" + fmt.Sprint(count))
  671. if err != nil {
  672. ctx.ServerError("QueryTrainJobList:", err)
  673. } else {
  674. ctx.JSON(200, VersionListTasks)
  675. }
  676. }
  677. func QueryTrainModelFileById(ctx *context.Context) ([]storage.FileInfo, error) {
  678. JobID := ctx.Query("jobId")
  679. VersionListTasks, count, err := models.QueryModelTrainJobVersionList(JobID)
  680. if err == nil {
  681. if count == 1 {
  682. task := VersionListTasks[0]
  683. jobName := task.JobName
  684. taskType := task.Type
  685. VersionName := task.VersionName
  686. modelDbResult, err := getModelFromObjectSave(jobName, taskType, VersionName)
  687. return modelDbResult, err
  688. }
  689. }
  690. log.Info("get TypeCloudBrainTwo TrainJobListModel failed:", err)
  691. return nil, errors.New("Not found task.")
  692. }
  693. func getModelFromObjectSave(jobName string, taskType int, VersionName string) ([]storage.FileInfo, error) {
  694. if taskType == models.TypeCloudBrainTwo {
  695. objectkey := path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, VersionName) + "/"
  696. modelDbResult, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, objectkey)
  697. log.Info("bucket=" + setting.Bucket + " objectkey=" + objectkey)
  698. if err != nil {
  699. log.Info("get TypeCloudBrainTwo TrainJobListModel failed:", err)
  700. return nil, err
  701. } else {
  702. return modelDbResult, nil
  703. }
  704. } else if taskType == models.TypeCloudBrainOne {
  705. modelSrcPrefix := setting.CBCodePathPrefix + jobName + "/model/"
  706. bucketName := setting.Attachment.Minio.Bucket
  707. modelDbResult, err := storage.GetAllObjectByBucketAndPrefixMinio(bucketName, modelSrcPrefix)
  708. if err != nil {
  709. log.Info("get TypeCloudBrainOne TrainJobListModel failed:", err)
  710. return nil, err
  711. } else {
  712. return modelDbResult, nil
  713. }
  714. }
  715. return nil, errors.New("Not support.")
  716. }
  717. func QueryTrainModelList(ctx *context.Context) {
  718. log.Info("query train job list. start.")
  719. jobName := ctx.Query("jobName")
  720. taskType := ctx.QueryInt("type")
  721. VersionName := ctx.Query("versionName")
  722. if VersionName == "" {
  723. VersionName = ctx.Query("VersionName")
  724. }
  725. modelDbResult, err := getModelFromObjectSave(jobName, taskType, VersionName)
  726. if err != nil {
  727. log.Info("get TypeCloudBrainTwo TrainJobListModel failed:", err)
  728. ctx.JSON(200, "")
  729. } else {
  730. ctx.JSON(200, modelDbResult)
  731. return
  732. }
  733. }
  734. func DownloadSingleModelFile(ctx *context.Context) {
  735. log.Info("DownloadSingleModelFile start.")
  736. id := ctx.Params(":ID")
  737. parentDir := ctx.Query("parentDir")
  738. fileName := ctx.Query("fileName")
  739. path := Model_prefix + models.AttachmentRelativePath(id) + "/" + parentDir + fileName
  740. task, err := models.QueryModelById(id)
  741. if err != nil {
  742. log.Error("no such model!", err.Error())
  743. ctx.ServerError("no such model:", err)
  744. return
  745. }
  746. if !isCanDownload(ctx, task) {
  747. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  748. return
  749. }
  750. if task.Type == models.TypeCloudBrainTwo {
  751. if setting.PROXYURL != "" {
  752. body, err := storage.ObsDownloadAFile(setting.Bucket, path)
  753. if err != nil {
  754. log.Info("download error.")
  755. } else {
  756. //count++
  757. models.ModifyModelDownloadCount(id)
  758. defer body.Close()
  759. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  760. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  761. p := make([]byte, 1024)
  762. var readErr error
  763. var readCount int
  764. // 读取对象内容
  765. for {
  766. readCount, readErr = body.Read(p)
  767. if readCount > 0 {
  768. ctx.Resp.Write(p[:readCount])
  769. //fmt.Printf("%s", p[:readCount])
  770. }
  771. if readErr != nil {
  772. break
  773. }
  774. }
  775. }
  776. } else {
  777. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  778. if err != nil {
  779. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  780. ctx.ServerError("GetObsCreateSignedUrl", err)
  781. return
  782. }
  783. //count++
  784. models.ModifyModelDownloadCount(id)
  785. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  786. }
  787. } else if task.Type == models.TypeCloudBrainOne {
  788. log.Info("start to down load minio file.")
  789. url, err := storage.Attachments.PresignedGetURL(path, fileName)
  790. if err != nil {
  791. log.Error("Get minio get SignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  792. ctx.ServerError("Get minio get SignedUrl failed", err)
  793. return
  794. }
  795. models.ModifyModelDownloadCount(id)
  796. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  797. }
  798. }
  799. func ShowModelInfo(ctx *context.Context) {
  800. ctx.Data["ID"] = ctx.Query("id")
  801. ctx.Data["name"] = ctx.Query("name")
  802. ctx.Data["isModelManage"] = true
  803. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  804. ctx.HTML(200, tplModelInfo)
  805. }
  806. func QueryModelById(ctx *context.Context) {
  807. id := ctx.Query("id")
  808. model, err := models.QueryModelById(id)
  809. if err == nil {
  810. model.IsCanOper = isOperModifyOrDelete(ctx, model.UserId)
  811. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  812. model.IsCanDownload = isCanDownload(ctx, model)
  813. removeIpInfo(model)
  814. ctx.JSON(http.StatusOK, model)
  815. } else {
  816. ctx.JSON(http.StatusNotFound, nil)
  817. }
  818. }
  819. func ShowSingleModel(ctx *context.Context) {
  820. name := ctx.Query("name")
  821. log.Info("Show single ModelInfo start.name=" + name)
  822. models := models.QueryModelByName(name, ctx.Repo.Repository.ID)
  823. userIds := make([]int64, len(models))
  824. for i, model := range models {
  825. model.IsCanOper = isOperModifyOrDelete(ctx, model.UserId)
  826. model.IsCanDownload = isCanDownload(ctx, model)
  827. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  828. userIds[i] = model.UserId
  829. }
  830. userNameMap := queryUserName(userIds)
  831. for _, model := range models {
  832. removeIpInfo(model)
  833. value := userNameMap[model.UserId]
  834. if value != nil {
  835. model.UserName = value.Name
  836. model.UserRelAvatarLink = value.RelAvatarLink()
  837. }
  838. }
  839. ctx.JSON(http.StatusOK, models)
  840. }
  841. func removeIpInfo(model *models.AiModelManage) {
  842. reg, _ := regexp.Compile(`[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}`)
  843. taskInfo := model.TrainTaskInfo
  844. taskInfo = reg.ReplaceAllString(taskInfo, "")
  845. model.TrainTaskInfo = taskInfo
  846. }
  847. func queryUserName(intSlice []int64) map[int64]*models.User {
  848. keys := make(map[int64]string)
  849. uniqueElements := []int64{}
  850. for _, entry := range intSlice {
  851. if _, value := keys[entry]; !value {
  852. keys[entry] = ""
  853. uniqueElements = append(uniqueElements, entry)
  854. }
  855. }
  856. result := make(map[int64]*models.User)
  857. userLists, err := models.GetUsersByIDs(uniqueElements)
  858. if err == nil {
  859. for _, user := range userLists {
  860. result[user.ID] = user
  861. }
  862. }
  863. return result
  864. }
  865. func ShowOneVersionOtherModel(ctx *context.Context) {
  866. repoId := ctx.Repo.Repository.ID
  867. name := ctx.Query("name")
  868. aimodels := models.QueryModelByName(name, repoId)
  869. userIds := make([]int64, len(aimodels))
  870. for i, model := range aimodels {
  871. model.IsCanOper = isOperModifyOrDelete(ctx, model.UserId)
  872. model.IsCanDownload = isCanDownload(ctx, model)
  873. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  874. userIds[i] = model.UserId
  875. }
  876. userNameMap := queryUserName(userIds)
  877. for _, model := range aimodels {
  878. removeIpInfo(model)
  879. value := userNameMap[model.UserId]
  880. if value != nil {
  881. model.UserName = value.Name
  882. model.UserRelAvatarLink = value.RelAvatarLink()
  883. }
  884. }
  885. if len(aimodels) > 0 {
  886. ctx.JSON(200, aimodels[1:])
  887. } else {
  888. ctx.JSON(200, aimodels)
  889. }
  890. }
  891. func SetModelCount(ctx *context.Context) {
  892. repoId := ctx.Repo.Repository.ID
  893. Type := -1
  894. _, count, _ := models.QueryModel(&models.AiModelQueryOptions{
  895. ListOptions: models.ListOptions{
  896. Page: 1,
  897. PageSize: 2,
  898. },
  899. RepoID: repoId,
  900. Type: Type,
  901. New: MODEL_LATEST,
  902. IsOnlyThisRepo: true,
  903. Status: -1,
  904. })
  905. ctx.Data["MODEL_COUNT"] = count
  906. }
  907. func ShowModelTemplate(ctx *context.Context) {
  908. ctx.Data["isModelManage"] = true
  909. repoId := ctx.Repo.Repository.ID
  910. SetModelCount(ctx)
  911. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  912. _, trainCount, _ := models.QueryModelTrainJobList(repoId)
  913. log.Info("query train count=" + fmt.Sprint(trainCount))
  914. ctx.Data["TRAIN_COUNT"] = trainCount
  915. ctx.HTML(200, tplModelManageIndex)
  916. }
  917. func isQueryRight(ctx *context.Context) bool {
  918. if ctx.Repo.Repository.IsPrivate {
  919. if ctx.Repo.CanRead(models.UnitTypeModelManage) || ctx.User.IsAdmin || ctx.Repo.IsAdmin() || ctx.Repo.IsOwner() {
  920. return true
  921. }
  922. return false
  923. } else {
  924. return true
  925. }
  926. }
  927. func isCanDownload(ctx *context.Context, task *models.AiModelManage) bool {
  928. if ctx.User == nil {
  929. return false
  930. }
  931. isCollaborator, err := ctx.Repo.Repository.IsCollaborator(ctx.User.ID)
  932. if err != nil {
  933. log.Info("query error.")
  934. }
  935. if ctx.User.IsAdmin || ctx.User.ID == task.UserId || isCollaborator {
  936. return true
  937. }
  938. if ctx.Repo.IsOwner() {
  939. return true
  940. }
  941. if !task.IsPrivate {
  942. return true
  943. }
  944. return false
  945. }
  946. func isCanDelete(ctx *context.Context, modelUserId int64) bool {
  947. if ctx.User == nil {
  948. return false
  949. }
  950. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  951. return true
  952. }
  953. if ctx.Repo.IsOwner() {
  954. return true
  955. }
  956. return false
  957. }
  958. func isOperModifyOrDelete(ctx *context.Context, modelUserId int64) bool {
  959. if ctx.User == nil {
  960. return false
  961. }
  962. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  963. return true
  964. }
  965. if ctx.Repo.IsOwner() {
  966. return true
  967. }
  968. return false
  969. }
  970. func ShowModelPageInfo(ctx *context.Context) {
  971. log.Info("ShowModelInfo start.")
  972. if !isQueryRight(ctx) {
  973. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  974. return
  975. }
  976. page := ctx.QueryInt("page")
  977. if page <= 0 {
  978. page = 1
  979. }
  980. pageSize := ctx.QueryInt("pageSize")
  981. if pageSize <= 0 {
  982. pageSize = setting.UI.IssuePagingNum
  983. }
  984. repoId := ctx.Repo.Repository.ID
  985. Type := -1
  986. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  987. ListOptions: models.ListOptions{
  988. Page: page,
  989. PageSize: pageSize,
  990. },
  991. RepoID: repoId,
  992. Type: Type,
  993. New: MODEL_LATEST,
  994. IsOnlyThisRepo: true,
  995. Status: -1,
  996. })
  997. if err != nil {
  998. ctx.ServerError("Cloudbrain", err)
  999. return
  1000. }
  1001. userIds := make([]int64, len(modelResult))
  1002. for i, model := range modelResult {
  1003. model.IsCanOper = isOperModifyOrDelete(ctx, model.UserId)
  1004. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  1005. model.IsCanDownload = isCanDownload(ctx, model)
  1006. userIds[i] = model.UserId
  1007. }
  1008. userNameMap := queryUserName(userIds)
  1009. for _, model := range modelResult {
  1010. removeIpInfo(model)
  1011. value := userNameMap[model.UserId]
  1012. if value != nil {
  1013. model.UserName = value.Name
  1014. model.UserRelAvatarLink = value.RelAvatarLink()
  1015. }
  1016. }
  1017. mapInterface := make(map[string]interface{})
  1018. mapInterface["data"] = modelResult
  1019. mapInterface["count"] = count
  1020. ctx.JSON(http.StatusOK, mapInterface)
  1021. }
  1022. func ModifyModel(id string, description string) error {
  1023. err := models.ModifyModelDescription(id, description)
  1024. if err == nil {
  1025. log.Info("modify success.")
  1026. } else {
  1027. log.Info("Failed to modify.id=" + id + " desc=" + description + " error:" + err.Error())
  1028. }
  1029. return err
  1030. }
  1031. func ModifyModelPrivate(ctx *context.Context) {
  1032. id := ctx.Query("id")
  1033. isPrivate := ctx.QueryBool("isPrivate")
  1034. re := map[string]string{
  1035. "code": "-1",
  1036. }
  1037. task, err := models.QueryModelById(id)
  1038. if err != nil || task == nil {
  1039. re["msg"] = err.Error()
  1040. log.Error("no such model!", err.Error())
  1041. ctx.JSON(200, re)
  1042. return
  1043. }
  1044. if !isOperModifyOrDelete(ctx, task.UserId) {
  1045. re["msg"] = "No right to operation."
  1046. ctx.JSON(200, re)
  1047. return
  1048. }
  1049. err = models.ModifyModelPrivate(id, isPrivate)
  1050. if err == nil {
  1051. re["code"] = "0"
  1052. ctx.JSON(200, re)
  1053. log.Info("modify success.")
  1054. } else {
  1055. re["msg"] = err.Error()
  1056. ctx.JSON(200, re)
  1057. log.Info("Failed to modify.id=" + id + " isprivate=" + fmt.Sprint(isPrivate) + " error:" + err.Error())
  1058. }
  1059. }
  1060. func ModifyModelInfo(ctx *context.Context) {
  1061. log.Info("modify model start.")
  1062. id := ctx.Query("id")
  1063. re := map[string]string{
  1064. "code": "-1",
  1065. }
  1066. task, err := models.QueryModelById(id)
  1067. if err != nil {
  1068. re["msg"] = err.Error()
  1069. log.Error("no such model!", err.Error())
  1070. ctx.JSON(200, re)
  1071. return
  1072. }
  1073. if !isOperModifyOrDelete(ctx, task.UserId) {
  1074. re["msg"] = "No right to operation."
  1075. ctx.JSON(200, re)
  1076. return
  1077. }
  1078. if task.ModelType == MODEL_LOCAL_TYPE {
  1079. name := ctx.Query("name")
  1080. label := ctx.Query("label")
  1081. description := ctx.Query("description")
  1082. engine := ctx.QueryInt("engine")
  1083. aimodels := models.QueryModelByName(name, task.RepoId)
  1084. if aimodels != nil && len(aimodels) > 0 {
  1085. if len(aimodels) == 1 {
  1086. if aimodels[0].ID != task.ID {
  1087. re["msg"] = ctx.Tr("repo.model.manage.create_error")
  1088. ctx.JSON(200, re)
  1089. return
  1090. }
  1091. } else {
  1092. re["msg"] = ctx.Tr("repo.model.manage.create_error")
  1093. ctx.JSON(200, re)
  1094. return
  1095. }
  1096. }
  1097. err = models.ModifyLocalModel(id, name, label, description, engine)
  1098. } else {
  1099. label := ctx.Query("label")
  1100. description := ctx.Query("description")
  1101. engine := task.Engine
  1102. name := task.Name
  1103. err = models.ModifyLocalModel(id, name, label, description, int(engine))
  1104. }
  1105. if err != nil {
  1106. re["msg"] = err.Error()
  1107. ctx.JSON(200, re)
  1108. return
  1109. } else {
  1110. re["code"] = "0"
  1111. ctx.JSON(200, re)
  1112. }
  1113. }
  1114. func QueryModelListForPredict(ctx *context.Context) {
  1115. repoId := ctx.Repo.Repository.ID
  1116. page := ctx.QueryInt("page")
  1117. if page <= 0 {
  1118. page = -1
  1119. }
  1120. pageSize := ctx.QueryInt("pageSize")
  1121. if pageSize <= 0 {
  1122. pageSize = -1
  1123. }
  1124. //IsOnlyThisRepo := ctx.QueryBool("isOnlyThisRepo")
  1125. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  1126. ListOptions: models.ListOptions{
  1127. Page: page,
  1128. PageSize: pageSize,
  1129. },
  1130. RepoID: repoId,
  1131. Type: ctx.QueryInt("type"),
  1132. New: -1,
  1133. Status: 0,
  1134. IsOnlyThisRepo: true,
  1135. })
  1136. if err != nil {
  1137. ctx.ServerError("Cloudbrain", err)
  1138. return
  1139. }
  1140. log.Info("query return count=" + fmt.Sprint(count))
  1141. nameList := make([]string, 0)
  1142. nameMap := make(map[string][]*models.AiModelManage)
  1143. for _, model := range modelResult {
  1144. model.TrainTaskInfo = ""
  1145. model.Accuracy = ""
  1146. //removeIpInfo(model)
  1147. if _, value := nameMap[model.Name]; !value {
  1148. models := make([]*models.AiModelManage, 0)
  1149. models = append(models, model)
  1150. nameMap[model.Name] = models
  1151. nameList = append(nameList, model.Name)
  1152. } else {
  1153. nameMap[model.Name] = append(nameMap[model.Name], model)
  1154. }
  1155. }
  1156. mapInterface := make(map[string]interface{})
  1157. mapInterface["nameList"] = nameList
  1158. mapInterface["nameMap"] = nameMap
  1159. ctx.JSON(http.StatusOK, mapInterface)
  1160. }
  1161. func QueryModelFileForPredict(ctx *context.Context) {
  1162. id := ctx.Query("id")
  1163. if id == "" {
  1164. id = ctx.Query("ID")
  1165. }
  1166. ctx.JSON(http.StatusOK, QueryModelFileByID(id))
  1167. }
  1168. func QueryModelFileByID(id string) []storage.FileInfo {
  1169. model, err := models.QueryModelById(id)
  1170. if err == nil {
  1171. if model.Type == models.TypeCloudBrainTwo {
  1172. prefix := model.Path[len(setting.Bucket)+1:]
  1173. fileinfos, _ := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, prefix)
  1174. return fileinfos
  1175. } else if model.Type == models.TypeCloudBrainOne {
  1176. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  1177. fileinfos, _ := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, prefix)
  1178. return fileinfos
  1179. }
  1180. } else {
  1181. log.Error("no such model!", err.Error())
  1182. }
  1183. return nil
  1184. }
  1185. func QueryOneLevelModelFile(ctx *context.Context) {
  1186. id := ctx.Query("id")
  1187. if id == "" {
  1188. id = ctx.Query("ID")
  1189. }
  1190. parentDir := ctx.Query("parentDir")
  1191. model, err := models.QueryModelById(id)
  1192. if err != nil {
  1193. log.Error("no such model!", err.Error())
  1194. ctx.ServerError("no such model:", err)
  1195. return
  1196. }
  1197. if model.Type == models.TypeCloudBrainTwo {
  1198. log.Info("TypeCloudBrainTwo list model file.")
  1199. prefix := model.Path[len(setting.Bucket)+1:]
  1200. fileinfos, _ := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, prefix, parentDir)
  1201. if fileinfos == nil {
  1202. fileinfos = make([]storage.FileInfo, 0)
  1203. }
  1204. ctx.JSON(http.StatusOK, fileinfos)
  1205. } else if model.Type == models.TypeCloudBrainOne {
  1206. log.Info("TypeCloudBrainOne list model file.")
  1207. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  1208. fileinfos, _ := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, parentDir)
  1209. if fileinfos == nil {
  1210. fileinfos = make([]storage.FileInfo, 0)
  1211. }
  1212. ctx.JSON(http.StatusOK, fileinfos)
  1213. }
  1214. }
  1215. func CreateLocalModel(ctx *context.Context) {
  1216. ctx.Data["isModelManage"] = true
  1217. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  1218. ctx.HTML(200, tplCreateLocalModelInfo)
  1219. }
  1220. func CreateLocalModelForUpload(ctx *context.Context) {
  1221. ctx.Data["uuid"] = ctx.Query("uuid")
  1222. ctx.Data["isModelManage"] = true
  1223. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  1224. ctx.Data["max_model_size"] = setting.MaxModelSize * MODEL_MAX_SIZE
  1225. ctx.HTML(200, tplCreateLocalForUploadModelInfo)
  1226. }
  1227. func CreateOnlineModel(ctx *context.Context) {
  1228. ctx.Data["isModelManage"] = true
  1229. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  1230. ctx.HTML(200, tplCreateOnlineModelInfo)
  1231. }