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

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