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

2 years ago
2 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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  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. isQueryPrivate := isQueryPrivateModel(ctx)
  893. repoId := ctx.Repo.Repository.ID
  894. Type := -1
  895. _, count, _ := models.QueryModel(&models.AiModelQueryOptions{
  896. ListOptions: models.ListOptions{
  897. Page: 1,
  898. PageSize: 2,
  899. },
  900. RepoID: repoId,
  901. Type: Type,
  902. New: MODEL_LATEST,
  903. IsOnlyThisRepo: true,
  904. Status: -1,
  905. IsQueryPrivate: isQueryPrivate,
  906. })
  907. ctx.Data["MODEL_COUNT"] = count
  908. }
  909. func ShowModelTemplate(ctx *context.Context) {
  910. ctx.Data["isModelManage"] = true
  911. repoId := ctx.Repo.Repository.ID
  912. SetModelCount(ctx)
  913. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  914. _, trainCount, _ := models.QueryModelTrainJobList(repoId)
  915. log.Info("query train count=" + fmt.Sprint(trainCount))
  916. ctx.Data["TRAIN_COUNT"] = trainCount
  917. ctx.HTML(200, tplModelManageIndex)
  918. }
  919. func isQueryRight(ctx *context.Context) bool {
  920. if ctx.Repo.Repository.IsPrivate {
  921. if ctx.Repo.CanRead(models.UnitTypeModelManage) || ctx.User.IsAdmin || ctx.Repo.IsAdmin() || ctx.Repo.IsOwner() {
  922. return true
  923. }
  924. return false
  925. } else {
  926. return true
  927. }
  928. }
  929. func isCanDownload(ctx *context.Context, task *models.AiModelManage) bool {
  930. if ctx.User == nil {
  931. return false
  932. }
  933. isCollaborator, err := ctx.Repo.Repository.IsCollaborator(ctx.User.ID)
  934. if err != nil {
  935. log.Info("query error.")
  936. }
  937. isTeamMember, err := ctx.Repo.Repository.IsInRepoTeam(ctx.User.ID)
  938. if err != nil {
  939. log.Info("query IsInRepoTeam error." + err.Error())
  940. }
  941. if ctx.User.IsAdmin || ctx.User.ID == task.UserId || isCollaborator || isTeamMember {
  942. return true
  943. }
  944. if ctx.Repo.IsOwner() {
  945. return true
  946. }
  947. if !task.IsPrivate {
  948. return true
  949. }
  950. return false
  951. }
  952. func isQueryPrivateModel(ctx *context.Context) bool {
  953. if ctx.User == nil {
  954. return false
  955. }
  956. isCollaborator, err := ctx.Repo.Repository.IsCollaborator(ctx.User.ID)
  957. if err != nil {
  958. log.Info("query IsCollaborator error." + err.Error())
  959. }
  960. isTeamMember, err := ctx.Repo.Repository.IsInRepoTeam(ctx.User.ID)
  961. if err != nil {
  962. log.Info("query IsInRepoTeam error." + err.Error())
  963. }
  964. if ctx.User.IsAdmin || isCollaborator || isTeamMember {
  965. return true
  966. }
  967. if ctx.Repo.IsOwner() {
  968. return true
  969. }
  970. return false
  971. }
  972. func isCanDelete(ctx *context.Context, modelUserId int64) bool {
  973. if ctx.User == nil {
  974. return false
  975. }
  976. if ctx.User.ID == modelUserId {
  977. return true
  978. }
  979. return isAdminRight(ctx)
  980. }
  981. func isAdminRight(ctx *context.Context) bool {
  982. if ctx.User.IsAdmin {
  983. return true
  984. }
  985. if ctx.Repo.IsOwner() {
  986. return true
  987. }
  988. permission, err := models.GetUserRepoPermission(ctx.Repo.Repository, ctx.User)
  989. if err != nil {
  990. log.Error("GetUserRepoPermission failed:%v", err.Error())
  991. return false
  992. }
  993. if permission.AccessMode >= models.AccessModeAdmin {
  994. return true
  995. }
  996. return false
  997. }
  998. func isOperModifyOrDelete(ctx *context.Context, modelUserId int64) bool {
  999. if ctx.User == nil {
  1000. return false
  1001. }
  1002. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  1003. return true
  1004. }
  1005. return isAdminRight(ctx)
  1006. }
  1007. func ShowModelPageInfo(ctx *context.Context) {
  1008. log.Info("ShowModelInfo start.")
  1009. if !isQueryRight(ctx) {
  1010. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  1011. return
  1012. }
  1013. page := ctx.QueryInt("page")
  1014. if page <= 0 {
  1015. page = 1
  1016. }
  1017. pageSize := ctx.QueryInt("pageSize")
  1018. if pageSize <= 0 {
  1019. pageSize = setting.UI.IssuePagingNum
  1020. }
  1021. isQueryPrivate := isQueryPrivateModel(ctx)
  1022. repoId := ctx.Repo.Repository.ID
  1023. Type := -1
  1024. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  1025. ListOptions: models.ListOptions{
  1026. Page: page,
  1027. PageSize: pageSize,
  1028. },
  1029. RepoID: repoId,
  1030. Type: Type,
  1031. New: MODEL_LATEST,
  1032. IsOnlyThisRepo: true,
  1033. Status: -1,
  1034. IsQueryPrivate: isQueryPrivate,
  1035. })
  1036. if err != nil {
  1037. ctx.ServerError("Cloudbrain", err)
  1038. return
  1039. }
  1040. userIds := make([]int64, len(modelResult))
  1041. for i, model := range modelResult {
  1042. model.IsCanOper = isOperModifyOrDelete(ctx, model.UserId)
  1043. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  1044. model.IsCanDownload = isCanDownload(ctx, model)
  1045. userIds[i] = model.UserId
  1046. }
  1047. userNameMap := queryUserName(userIds)
  1048. for _, model := range modelResult {
  1049. removeIpInfo(model)
  1050. value := userNameMap[model.UserId]
  1051. if value != nil {
  1052. model.UserName = value.Name
  1053. model.UserRelAvatarLink = value.RelAvatarLink()
  1054. }
  1055. }
  1056. mapInterface := make(map[string]interface{})
  1057. mapInterface["data"] = modelResult
  1058. mapInterface["count"] = count
  1059. ctx.JSON(http.StatusOK, mapInterface)
  1060. }
  1061. func ModifyModel(id string, description string) error {
  1062. err := models.ModifyModelDescription(id, description)
  1063. if err == nil {
  1064. log.Info("modify success.")
  1065. } else {
  1066. log.Info("Failed to modify.id=" + id + " desc=" + description + " error:" + err.Error())
  1067. }
  1068. return err
  1069. }
  1070. func ModifyModelPrivate(ctx *context.Context) {
  1071. id := ctx.Query("id")
  1072. isPrivate := ctx.QueryBool("isPrivate")
  1073. re := map[string]string{
  1074. "code": "-1",
  1075. }
  1076. task, err := models.QueryModelById(id)
  1077. if err != nil || task == nil {
  1078. re["msg"] = err.Error()
  1079. log.Error("no such model!", err.Error())
  1080. ctx.JSON(200, re)
  1081. return
  1082. }
  1083. if !isOperModifyOrDelete(ctx, task.UserId) {
  1084. re["msg"] = "No right to operation."
  1085. ctx.JSON(200, re)
  1086. return
  1087. }
  1088. err = models.ModifyModelPrivate(id, isPrivate)
  1089. if err == nil {
  1090. re["code"] = "0"
  1091. ctx.JSON(200, re)
  1092. log.Info("modify success.")
  1093. } else {
  1094. re["msg"] = err.Error()
  1095. ctx.JSON(200, re)
  1096. log.Info("Failed to modify.id=" + id + " isprivate=" + fmt.Sprint(isPrivate) + " error:" + err.Error())
  1097. }
  1098. }
  1099. func ModifyModelInfo(ctx *context.Context) {
  1100. log.Info("modify model start.")
  1101. id := ctx.Query("id")
  1102. re := map[string]string{
  1103. "code": "-1",
  1104. }
  1105. task, err := models.QueryModelById(id)
  1106. if err != nil {
  1107. re["msg"] = err.Error()
  1108. log.Error("no such model!", err.Error())
  1109. ctx.JSON(200, re)
  1110. return
  1111. }
  1112. if !isOperModifyOrDelete(ctx, task.UserId) {
  1113. re["msg"] = "No right to operation."
  1114. ctx.JSON(200, re)
  1115. return
  1116. }
  1117. if task.ModelType == MODEL_LOCAL_TYPE {
  1118. name := ctx.Query("name")
  1119. label := ctx.Query("label")
  1120. description := ctx.Query("description")
  1121. engine := ctx.QueryInt("engine")
  1122. isPrivate := ctx.QueryBool("isPrivate")
  1123. aimodels := models.QueryModelByName(name, task.RepoId)
  1124. if aimodels != nil && len(aimodels) > 0 {
  1125. if len(aimodels) == 1 {
  1126. if aimodels[0].ID != task.ID {
  1127. re["msg"] = ctx.Tr("repo.model.manage.create_error")
  1128. ctx.JSON(200, re)
  1129. return
  1130. }
  1131. } else {
  1132. re["msg"] = ctx.Tr("repo.model.manage.create_error")
  1133. ctx.JSON(200, re)
  1134. return
  1135. }
  1136. }
  1137. err = models.ModifyLocalModel(id, name, label, description, engine, isPrivate)
  1138. } else {
  1139. label := ctx.Query("label")
  1140. description := ctx.Query("description")
  1141. engine := task.Engine
  1142. name := task.Name
  1143. err = models.ModifyLocalModel(id, name, label, description, int(engine), task.IsPrivate)
  1144. }
  1145. if err != nil {
  1146. re["msg"] = err.Error()
  1147. ctx.JSON(200, re)
  1148. return
  1149. } else {
  1150. re["code"] = "0"
  1151. ctx.JSON(200, re)
  1152. }
  1153. }
  1154. func QueryModelListForPredict(ctx *context.Context) {
  1155. repoId := ctx.Repo.Repository.ID
  1156. page := ctx.QueryInt("page")
  1157. if page <= 0 {
  1158. page = -1
  1159. }
  1160. pageSize := ctx.QueryInt("pageSize")
  1161. if pageSize <= 0 {
  1162. pageSize = -1
  1163. }
  1164. isQueryPrivate := isQueryPrivateModel(ctx)
  1165. //IsOnlyThisRepo := ctx.QueryBool("isOnlyThisRepo")
  1166. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  1167. ListOptions: models.ListOptions{
  1168. Page: page,
  1169. PageSize: pageSize,
  1170. },
  1171. RepoID: repoId,
  1172. Type: ctx.QueryInt("type"),
  1173. New: -1,
  1174. Status: 0,
  1175. IsOnlyThisRepo: true,
  1176. IsQueryPrivate: isQueryPrivate,
  1177. })
  1178. if err != nil {
  1179. ctx.ServerError("Cloudbrain", err)
  1180. return
  1181. }
  1182. log.Info("query return count=" + fmt.Sprint(count))
  1183. nameList := make([]string, 0)
  1184. nameMap := make(map[string][]*models.AiModelManage)
  1185. for _, model := range modelResult {
  1186. model.TrainTaskInfo = ""
  1187. model.Accuracy = ""
  1188. //removeIpInfo(model)
  1189. if _, value := nameMap[model.Name]; !value {
  1190. models := make([]*models.AiModelManage, 0)
  1191. models = append(models, model)
  1192. nameMap[model.Name] = models
  1193. nameList = append(nameList, model.Name)
  1194. } else {
  1195. nameMap[model.Name] = append(nameMap[model.Name], model)
  1196. }
  1197. }
  1198. mapInterface := make(map[string]interface{})
  1199. mapInterface["nameList"] = nameList
  1200. mapInterface["nameMap"] = nameMap
  1201. ctx.JSON(http.StatusOK, mapInterface)
  1202. }
  1203. func QueryModelFileForPredict(ctx *context.Context) {
  1204. id := ctx.Query("id")
  1205. if id == "" {
  1206. id = ctx.Query("ID")
  1207. }
  1208. ctx.JSON(http.StatusOK, QueryModelFileByID(id))
  1209. }
  1210. func QueryModelFileByID(id string) []storage.FileInfo {
  1211. model, err := models.QueryModelById(id)
  1212. if err == nil {
  1213. if model.Type == models.TypeCloudBrainTwo {
  1214. prefix := model.Path[len(setting.Bucket)+1:]
  1215. fileinfos, _ := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, prefix)
  1216. return fileinfos
  1217. } else if model.Type == models.TypeCloudBrainOne {
  1218. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  1219. fileinfos, _ := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, prefix)
  1220. return fileinfos
  1221. }
  1222. } else {
  1223. log.Error("no such model!", err.Error())
  1224. }
  1225. return nil
  1226. }
  1227. func QueryOneLevelModelFile(ctx *context.Context) {
  1228. id := ctx.Query("id")
  1229. if id == "" {
  1230. id = ctx.Query("ID")
  1231. }
  1232. parentDir := ctx.Query("parentDir")
  1233. model, err := models.QueryModelById(id)
  1234. if err != nil {
  1235. log.Error("no such model!", err.Error())
  1236. ctx.ServerError("no such model:", err)
  1237. return
  1238. }
  1239. if model.Type == models.TypeCloudBrainTwo {
  1240. log.Info("TypeCloudBrainTwo list model file.")
  1241. prefix := model.Path[len(setting.Bucket)+1:]
  1242. fileinfos, _ := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, prefix, parentDir)
  1243. if fileinfos == nil {
  1244. fileinfos = make([]storage.FileInfo, 0)
  1245. }
  1246. ctx.JSON(http.StatusOK, fileinfos)
  1247. } else if model.Type == models.TypeCloudBrainOne {
  1248. log.Info("TypeCloudBrainOne list model file.")
  1249. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  1250. fileinfos, _ := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, parentDir)
  1251. if fileinfos == nil {
  1252. fileinfos = make([]storage.FileInfo, 0)
  1253. }
  1254. ctx.JSON(http.StatusOK, fileinfos)
  1255. }
  1256. }
  1257. func CreateLocalModel(ctx *context.Context) {
  1258. ctx.Data["isModelManage"] = true
  1259. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  1260. ctx.HTML(200, tplCreateLocalModelInfo)
  1261. }
  1262. func CreateLocalModelForUpload(ctx *context.Context) {
  1263. ctx.Data["uuid"] = ctx.Query("uuid")
  1264. ctx.Data["isModelManage"] = true
  1265. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  1266. ctx.Data["max_model_size"] = setting.MaxModelSize * MODEL_MAX_SIZE
  1267. ctx.HTML(200, tplCreateLocalForUploadModelInfo)
  1268. }
  1269. func CreateOnlineModel(ctx *context.Context) {
  1270. ctx.Data["isModelManage"] = true
  1271. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  1272. ctx.HTML(200, tplCreateOnlineModelInfo)
  1273. }