You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ai_model_manage.go 39 kB

3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316
  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 QueryModelByParameters(repoId int64, page int) ([]*models.AiModelManage, int64, error) {
  527. return models.QueryModel(&models.AiModelQueryOptions{
  528. ListOptions: models.ListOptions{
  529. Page: page,
  530. PageSize: setting.UI.IssuePagingNum,
  531. },
  532. RepoID: repoId,
  533. Type: -1,
  534. New: MODEL_LATEST,
  535. Status: -1,
  536. })
  537. }
  538. func DownloadMultiModelFile(ctx *context.Context) {
  539. log.Info("DownloadMultiModelFile start.")
  540. id := ctx.Query("id")
  541. log.Info("id=" + id)
  542. task, err := models.QueryModelById(id)
  543. if err != nil {
  544. log.Error("no such model!", err.Error())
  545. ctx.ServerError("no such model:", err)
  546. return
  547. }
  548. if !isCanDownload(ctx, task) {
  549. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  550. return
  551. }
  552. path := Model_prefix + models.AttachmentRelativePath(id) + "/"
  553. if task.Type == models.TypeCloudBrainTwo {
  554. downloadFromCloudBrainTwo(path, task, ctx, id)
  555. } else if task.Type == models.TypeCloudBrainOne {
  556. downloadFromCloudBrainOne(path, task, ctx, id)
  557. }
  558. }
  559. func MinioDownloadManyFile(path string, ctx *context.Context, returnFileName string, allFile []storage.FileInfo) {
  560. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+url.QueryEscape(returnFileName))
  561. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  562. w := zip.NewWriter(ctx.Resp)
  563. defer w.Close()
  564. for _, oneFile := range allFile {
  565. if oneFile.IsDir {
  566. log.Info("zip dir name:" + oneFile.FileName)
  567. } else {
  568. log.Info("zip file name:" + oneFile.FileName)
  569. fDest, err := w.Create(oneFile.FileName)
  570. if err != nil {
  571. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  572. ctx.ServerError("download file failed:", err)
  573. return
  574. }
  575. log.Info("minio file path=" + (path + oneFile.FileName))
  576. body, err := storage.Attachments.DownloadAFile(setting.Attachment.Minio.Bucket, path+oneFile.FileName)
  577. if err != nil {
  578. log.Info("download file failed: %s\n", err.Error())
  579. ctx.ServerError("download file failed:", err)
  580. return
  581. } else {
  582. defer body.Close()
  583. p := make([]byte, 1024)
  584. var readErr error
  585. var readCount int
  586. // 读取对象内容
  587. for {
  588. readCount, readErr = body.Read(p)
  589. if readCount > 0 {
  590. fDest.Write(p[:readCount])
  591. }
  592. if readErr != nil {
  593. break
  594. }
  595. }
  596. }
  597. }
  598. }
  599. }
  600. func downloadFromCloudBrainOne(path string, task *models.AiModelManage, ctx *context.Context, id string) {
  601. allFile, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, path)
  602. if err == nil {
  603. //count++
  604. models.ModifyModelDownloadCount(id)
  605. returnFileName := task.Name + "_" + task.Version + ".zip"
  606. MinioDownloadManyFile(path, ctx, returnFileName, allFile)
  607. } else {
  608. log.Info("error,msg=" + err.Error())
  609. ctx.ServerError("no file to download.", err)
  610. }
  611. }
  612. func ObsDownloadManyFile(path string, ctx *context.Context, returnFileName string, allFile []storage.FileInfo) {
  613. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+url.QueryEscape(returnFileName))
  614. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  615. w := zip.NewWriter(ctx.Resp)
  616. defer w.Close()
  617. for _, oneFile := range allFile {
  618. if oneFile.IsDir {
  619. log.Info("zip dir name:" + oneFile.FileName)
  620. } else {
  621. log.Info("zip file name:" + oneFile.FileName)
  622. fDest, err := w.Create(oneFile.FileName)
  623. if err != nil {
  624. log.Info("create zip entry error, download file failed: %s\n", err.Error())
  625. ctx.ServerError("download file failed:", err)
  626. return
  627. }
  628. body, err := storage.ObsDownloadAFile(setting.Bucket, path+oneFile.FileName)
  629. if err != nil {
  630. log.Info("download file failed: %s\n", err.Error())
  631. ctx.ServerError("download file failed:", err)
  632. return
  633. } else {
  634. defer body.Close()
  635. p := make([]byte, 1024)
  636. var readErr error
  637. var readCount int
  638. // 读取对象内容
  639. for {
  640. readCount, readErr = body.Read(p)
  641. if readCount > 0 {
  642. fDest.Write(p[:readCount])
  643. }
  644. if readErr != nil {
  645. break
  646. }
  647. }
  648. }
  649. }
  650. }
  651. }
  652. func downloadFromCloudBrainTwo(path string, task *models.AiModelManage, ctx *context.Context, id string) {
  653. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  654. if err == nil {
  655. //count++
  656. models.ModifyModelDownloadCount(id)
  657. returnFileName := task.Name + "_" + task.Version + ".zip"
  658. ObsDownloadManyFile(path, ctx, returnFileName, allFile)
  659. } else {
  660. log.Info("error,msg=" + err.Error())
  661. ctx.ServerError("no file to download.", err)
  662. }
  663. }
  664. func QueryTrainJobVersionList(ctx *context.Context) {
  665. log.Info("query train job version list. start.")
  666. JobID := ctx.Query("jobId")
  667. if JobID == "" {
  668. JobID = ctx.Query("JobId")
  669. }
  670. VersionListTasks, count, err := models.QueryModelTrainJobVersionList(JobID)
  671. log.Info("query return count=" + fmt.Sprint(count))
  672. if err != nil {
  673. ctx.ServerError("QueryTrainJobList:", err)
  674. } else {
  675. ctx.JSON(200, VersionListTasks)
  676. }
  677. }
  678. func QueryTrainJobList(ctx *context.Context) {
  679. log.Info("query train job list. start.")
  680. repoId := ctx.QueryInt64("repoId")
  681. VersionListTasks, count, err := models.QueryModelTrainJobList(repoId)
  682. log.Info("query return count=" + fmt.Sprint(count))
  683. if err != nil {
  684. ctx.ServerError("QueryTrainJobList:", err)
  685. } else {
  686. ctx.JSON(200, VersionListTasks)
  687. }
  688. }
  689. func QueryTrainModelFileById(ctx *context.Context) ([]storage.FileInfo, error) {
  690. JobID := ctx.Query("jobId")
  691. VersionListTasks, count, err := models.QueryModelTrainJobVersionList(JobID)
  692. if err == nil {
  693. if count == 1 {
  694. task := VersionListTasks[0]
  695. jobName := task.JobName
  696. taskType := task.Type
  697. VersionName := task.VersionName
  698. modelDbResult, err := getModelFromObjectSave(jobName, taskType, VersionName)
  699. return modelDbResult, err
  700. }
  701. }
  702. log.Info("get TypeCloudBrainTwo TrainJobListModel failed:", err)
  703. return nil, errors.New("Not found task.")
  704. }
  705. func getModelFromObjectSave(jobName string, taskType int, VersionName string) ([]storage.FileInfo, error) {
  706. if taskType == models.TypeCloudBrainTwo {
  707. objectkey := path.Join(setting.TrainJobModelPath, jobName, setting.OutPutPath, VersionName) + "/"
  708. modelDbResult, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, objectkey)
  709. log.Info("bucket=" + setting.Bucket + " objectkey=" + objectkey)
  710. if err != nil {
  711. log.Info("get TypeCloudBrainTwo TrainJobListModel failed:", err)
  712. return nil, err
  713. } else {
  714. return modelDbResult, nil
  715. }
  716. } else if taskType == models.TypeCloudBrainOne {
  717. modelSrcPrefix := setting.CBCodePathPrefix + jobName + "/model/"
  718. bucketName := setting.Attachment.Minio.Bucket
  719. modelDbResult, err := storage.GetAllObjectByBucketAndPrefixMinio(bucketName, modelSrcPrefix)
  720. if err != nil {
  721. log.Info("get TypeCloudBrainOne TrainJobListModel failed:", err)
  722. return nil, err
  723. } else {
  724. return modelDbResult, nil
  725. }
  726. }
  727. return nil, errors.New("Not support.")
  728. }
  729. func QueryTrainModelList(ctx *context.Context) {
  730. log.Info("query train job list. start.")
  731. jobName := ctx.Query("jobName")
  732. taskType := ctx.QueryInt("type")
  733. VersionName := ctx.Query("versionName")
  734. if VersionName == "" {
  735. VersionName = ctx.Query("VersionName")
  736. }
  737. modelDbResult, err := getModelFromObjectSave(jobName, taskType, VersionName)
  738. if err != nil {
  739. log.Info("get TypeCloudBrainTwo TrainJobListModel failed:", err)
  740. ctx.JSON(200, "")
  741. } else {
  742. ctx.JSON(200, modelDbResult)
  743. return
  744. }
  745. }
  746. func DownloadSingleModelFile(ctx *context.Context) {
  747. log.Info("DownloadSingleModelFile start.")
  748. id := ctx.Params(":ID")
  749. parentDir := ctx.Query("parentDir")
  750. fileName := ctx.Query("fileName")
  751. path := Model_prefix + models.AttachmentRelativePath(id) + "/" + parentDir + fileName
  752. task, err := models.QueryModelById(id)
  753. if err != nil {
  754. log.Error("no such model!", err.Error())
  755. ctx.ServerError("no such model:", err)
  756. return
  757. }
  758. if !isCanDownload(ctx, task) {
  759. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  760. return
  761. }
  762. if task.Type == models.TypeCloudBrainTwo {
  763. if setting.PROXYURL != "" {
  764. body, err := storage.ObsDownloadAFile(setting.Bucket, path)
  765. if err != nil {
  766. log.Info("download error.")
  767. } else {
  768. //count++
  769. models.ModifyModelDownloadCount(id)
  770. defer body.Close()
  771. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  772. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  773. p := make([]byte, 1024)
  774. var readErr error
  775. var readCount int
  776. // 读取对象内容
  777. for {
  778. readCount, readErr = body.Read(p)
  779. if readCount > 0 {
  780. ctx.Resp.Write(p[:readCount])
  781. //fmt.Printf("%s", p[:readCount])
  782. }
  783. if readErr != nil {
  784. break
  785. }
  786. }
  787. }
  788. } else {
  789. url, err := storage.GetObsCreateSignedUrlByBucketAndKey(setting.Bucket, path)
  790. if err != nil {
  791. log.Error("GetObsCreateSignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  792. ctx.ServerError("GetObsCreateSignedUrl", err)
  793. return
  794. }
  795. //count++
  796. models.ModifyModelDownloadCount(id)
  797. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  798. }
  799. } else if task.Type == models.TypeCloudBrainOne {
  800. log.Info("start to down load minio file.")
  801. url, err := storage.Attachments.PresignedGetURL(path, fileName)
  802. if err != nil {
  803. log.Error("Get minio get SignedUrl failed: %v", err.Error(), ctx.Data["msgID"])
  804. ctx.ServerError("Get minio get SignedUrl failed", err)
  805. return
  806. }
  807. models.ModifyModelDownloadCount(id)
  808. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusMovedPermanently)
  809. }
  810. }
  811. func ShowModelInfo(ctx *context.Context) {
  812. ctx.Data["ID"] = ctx.Query("id")
  813. ctx.Data["name"] = ctx.Query("name")
  814. ctx.Data["isModelManage"] = true
  815. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  816. ctx.HTML(200, tplModelInfo)
  817. }
  818. func QueryModelById(ctx *context.Context) {
  819. id := ctx.Query("id")
  820. model, err := models.QueryModelById(id)
  821. if err == nil {
  822. model.IsCanOper = isOperModifyOrDelete(ctx, model.UserId)
  823. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  824. model.IsCanDownload = isCanDownload(ctx, model)
  825. removeIpInfo(model)
  826. ctx.JSON(http.StatusOK, model)
  827. } else {
  828. ctx.JSON(http.StatusNotFound, nil)
  829. }
  830. }
  831. func ShowSingleModel(ctx *context.Context) {
  832. name := ctx.Query("name")
  833. log.Info("Show single ModelInfo start.name=" + name)
  834. models := models.QueryModelByName(name, ctx.Repo.Repository.ID)
  835. userIds := make([]int64, len(models))
  836. for i, model := range models {
  837. model.IsCanOper = isOperModifyOrDelete(ctx, model.UserId)
  838. model.IsCanDownload = isCanDownload(ctx, model)
  839. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  840. userIds[i] = model.UserId
  841. }
  842. userNameMap := queryUserName(userIds)
  843. for _, model := range models {
  844. removeIpInfo(model)
  845. value := userNameMap[model.UserId]
  846. if value != nil {
  847. model.UserName = value.Name
  848. model.UserRelAvatarLink = value.RelAvatarLink()
  849. }
  850. }
  851. ctx.JSON(http.StatusOK, models)
  852. }
  853. func removeIpInfo(model *models.AiModelManage) {
  854. reg, _ := regexp.Compile(`[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}`)
  855. taskInfo := model.TrainTaskInfo
  856. taskInfo = reg.ReplaceAllString(taskInfo, "")
  857. model.TrainTaskInfo = taskInfo
  858. }
  859. func queryUserName(intSlice []int64) map[int64]*models.User {
  860. keys := make(map[int64]string)
  861. uniqueElements := []int64{}
  862. for _, entry := range intSlice {
  863. if _, value := keys[entry]; !value {
  864. keys[entry] = ""
  865. uniqueElements = append(uniqueElements, entry)
  866. }
  867. }
  868. result := make(map[int64]*models.User)
  869. userLists, err := models.GetUsersByIDs(uniqueElements)
  870. if err == nil {
  871. for _, user := range userLists {
  872. result[user.ID] = user
  873. }
  874. }
  875. return result
  876. }
  877. func ShowOneVersionOtherModel(ctx *context.Context) {
  878. repoId := ctx.Repo.Repository.ID
  879. name := ctx.Query("name")
  880. aimodels := models.QueryModelByName(name, repoId)
  881. userIds := make([]int64, len(aimodels))
  882. for i, model := range aimodels {
  883. model.IsCanOper = isOperModifyOrDelete(ctx, model.UserId)
  884. model.IsCanDownload = isCanDownload(ctx, model)
  885. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  886. userIds[i] = model.UserId
  887. }
  888. userNameMap := queryUserName(userIds)
  889. for _, model := range aimodels {
  890. removeIpInfo(model)
  891. value := userNameMap[model.UserId]
  892. if value != nil {
  893. model.UserName = value.Name
  894. model.UserRelAvatarLink = value.RelAvatarLink()
  895. }
  896. }
  897. if len(aimodels) > 0 {
  898. ctx.JSON(200, aimodels[1:])
  899. } else {
  900. ctx.JSON(200, aimodels)
  901. }
  902. }
  903. func SetModelCount(ctx *context.Context) {
  904. repoId := ctx.Repo.Repository.ID
  905. Type := -1
  906. _, count, _ := models.QueryModel(&models.AiModelQueryOptions{
  907. ListOptions: models.ListOptions{
  908. Page: 1,
  909. PageSize: 2,
  910. },
  911. RepoID: repoId,
  912. Type: Type,
  913. New: MODEL_LATEST,
  914. Status: -1,
  915. })
  916. ctx.Data["MODEL_COUNT"] = count
  917. }
  918. func ShowModelTemplate(ctx *context.Context) {
  919. ctx.Data["isModelManage"] = true
  920. repoId := ctx.Repo.Repository.ID
  921. SetModelCount(ctx)
  922. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  923. _, trainCount, _ := models.QueryModelTrainJobList(repoId)
  924. log.Info("query train count=" + fmt.Sprint(trainCount))
  925. ctx.Data["TRAIN_COUNT"] = trainCount
  926. ctx.HTML(200, tplModelManageIndex)
  927. }
  928. func isQueryRight(ctx *context.Context) bool {
  929. if ctx.Repo.Repository.IsPrivate {
  930. if ctx.Repo.CanRead(models.UnitTypeModelManage) || ctx.User.IsAdmin || ctx.Repo.IsAdmin() || ctx.Repo.IsOwner() {
  931. return true
  932. }
  933. return false
  934. } else {
  935. return true
  936. }
  937. }
  938. func isCanDownload(ctx *context.Context, task *models.AiModelManage) bool {
  939. if ctx.User == nil {
  940. return false
  941. }
  942. if ctx.User.IsAdmin || ctx.User.ID == task.UserId {
  943. return true
  944. }
  945. if !task.IsPrivate {
  946. return true
  947. }
  948. return false
  949. }
  950. func isCanDelete(ctx *context.Context, modelUserId int64) bool {
  951. if ctx.User == nil {
  952. return false
  953. }
  954. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  955. return true
  956. }
  957. if ctx.Repo.IsOwner() {
  958. return true
  959. }
  960. return false
  961. }
  962. func isOperModifyOrDelete(ctx *context.Context, modelUserId int64) bool {
  963. if ctx.User == nil {
  964. return false
  965. }
  966. if ctx.User.IsAdmin || ctx.User.ID == modelUserId {
  967. return true
  968. }
  969. return false
  970. }
  971. func ShowModelPageInfo(ctx *context.Context) {
  972. log.Info("ShowModelInfo start.")
  973. if !isQueryRight(ctx) {
  974. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  975. return
  976. }
  977. page := ctx.QueryInt("page")
  978. if page <= 0 {
  979. page = 1
  980. }
  981. pageSize := ctx.QueryInt("pageSize")
  982. if pageSize <= 0 {
  983. pageSize = setting.UI.IssuePagingNum
  984. }
  985. repoId := ctx.Repo.Repository.ID
  986. Type := -1
  987. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  988. ListOptions: models.ListOptions{
  989. Page: page,
  990. PageSize: pageSize,
  991. },
  992. RepoID: repoId,
  993. Type: Type,
  994. New: MODEL_LATEST,
  995. Status: -1,
  996. })
  997. if err != nil {
  998. ctx.ServerError("Cloudbrain", err)
  999. return
  1000. }
  1001. userIds := make([]int64, len(modelResult))
  1002. for i, model := range modelResult {
  1003. model.IsCanOper = isOperModifyOrDelete(ctx, model.UserId)
  1004. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  1005. model.IsCanDownload = isCanDownload(ctx, model)
  1006. userIds[i] = model.UserId
  1007. }
  1008. userNameMap := queryUserName(userIds)
  1009. for _, model := range modelResult {
  1010. removeIpInfo(model)
  1011. value := userNameMap[model.UserId]
  1012. if value != nil {
  1013. model.UserName = value.Name
  1014. model.UserRelAvatarLink = value.RelAvatarLink()
  1015. }
  1016. }
  1017. mapInterface := make(map[string]interface{})
  1018. mapInterface["data"] = modelResult
  1019. mapInterface["count"] = count
  1020. ctx.JSON(http.StatusOK, mapInterface)
  1021. }
  1022. func ModifyModel(id string, description string) error {
  1023. err := models.ModifyModelDescription(id, description)
  1024. if err == nil {
  1025. log.Info("modify success.")
  1026. } else {
  1027. log.Info("Failed to modify.id=" + id + " desc=" + description + " error:" + err.Error())
  1028. }
  1029. return err
  1030. }
  1031. func ModifyModelPrivate(ctx *context.Context) {
  1032. id := ctx.Query("id")
  1033. isPrivate := ctx.QueryBool("isPrivate")
  1034. re := map[string]string{
  1035. "code": "-1",
  1036. }
  1037. task, err := models.QueryModelById(id)
  1038. if err != nil || task == nil {
  1039. re["msg"] = err.Error()
  1040. log.Error("no such model!", err.Error())
  1041. ctx.JSON(200, re)
  1042. return
  1043. }
  1044. if !isOperModifyOrDelete(ctx, task.UserId) {
  1045. re["msg"] = "No right to operation."
  1046. ctx.JSON(200, re)
  1047. return
  1048. }
  1049. err = models.ModifyModelPrivate(id, isPrivate)
  1050. if err == nil {
  1051. re["code"] = "0"
  1052. ctx.JSON(200, re)
  1053. log.Info("modify success.")
  1054. } else {
  1055. re["msg"] = err.Error()
  1056. ctx.JSON(200, re)
  1057. log.Info("Failed to modify.id=" + id + " isprivate=" + fmt.Sprint(isPrivate) + " error:" + err.Error())
  1058. }
  1059. }
  1060. func ModifyModelInfo(ctx *context.Context) {
  1061. log.Info("modify model start.")
  1062. id := ctx.Query("id")
  1063. re := map[string]string{
  1064. "code": "-1",
  1065. }
  1066. task, err := models.QueryModelById(id)
  1067. if err != nil {
  1068. re["msg"] = err.Error()
  1069. log.Error("no such model!", err.Error())
  1070. ctx.JSON(200, re)
  1071. return
  1072. }
  1073. if !isOperModifyOrDelete(ctx, task.UserId) {
  1074. re["msg"] = "No right to operation."
  1075. ctx.JSON(200, re)
  1076. return
  1077. }
  1078. if task.ModelType == MODEL_LOCAL_TYPE {
  1079. name := ctx.Query("name")
  1080. label := ctx.Query("label")
  1081. description := ctx.Query("description")
  1082. engine := ctx.QueryInt("engine")
  1083. aimodels := models.QueryModelByName(name, task.RepoId)
  1084. if aimodels != nil && len(aimodels) > 0 {
  1085. if len(aimodels) == 1 {
  1086. if aimodels[0].ID != task.ID {
  1087. re["msg"] = ctx.Tr("repo.model.manage.create_error")
  1088. ctx.JSON(200, re)
  1089. return
  1090. }
  1091. } else {
  1092. re["msg"] = ctx.Tr("repo.model.manage.create_error")
  1093. ctx.JSON(200, re)
  1094. return
  1095. }
  1096. }
  1097. err = models.ModifyLocalModel(id, name, label, description, engine)
  1098. } else {
  1099. label := ctx.Query("label")
  1100. description := ctx.Query("description")
  1101. engine := task.Engine
  1102. name := task.Name
  1103. err = models.ModifyLocalModel(id, name, label, description, int(engine))
  1104. }
  1105. if err != nil {
  1106. re["msg"] = err.Error()
  1107. ctx.JSON(200, re)
  1108. return
  1109. } else {
  1110. re["code"] = "0"
  1111. ctx.JSON(200, re)
  1112. }
  1113. }
  1114. func QueryModelListForPredict(ctx *context.Context) {
  1115. repoId := ctx.Repo.Repository.ID
  1116. modelResult, count, err := models.QueryModel(&models.AiModelQueryOptions{
  1117. ListOptions: models.ListOptions{
  1118. Page: -1,
  1119. PageSize: -1,
  1120. },
  1121. RepoID: repoId,
  1122. Type: ctx.QueryInt("type"),
  1123. New: -1,
  1124. Status: 0,
  1125. })
  1126. if err != nil {
  1127. ctx.ServerError("Cloudbrain", err)
  1128. return
  1129. }
  1130. log.Info("query return count=" + fmt.Sprint(count))
  1131. nameList := make([]string, 0)
  1132. nameMap := make(map[string][]*models.AiModelManage)
  1133. for _, model := range modelResult {
  1134. removeIpInfo(model)
  1135. if _, value := nameMap[model.Name]; !value {
  1136. models := make([]*models.AiModelManage, 0)
  1137. models = append(models, model)
  1138. nameMap[model.Name] = models
  1139. nameList = append(nameList, model.Name)
  1140. } else {
  1141. nameMap[model.Name] = append(nameMap[model.Name], model)
  1142. }
  1143. }
  1144. mapInterface := make(map[string]interface{})
  1145. mapInterface["nameList"] = nameList
  1146. mapInterface["nameMap"] = nameMap
  1147. ctx.JSON(http.StatusOK, mapInterface)
  1148. }
  1149. func QueryModelFileForPredict(ctx *context.Context) {
  1150. id := ctx.Query("id")
  1151. if id == "" {
  1152. id = ctx.Query("ID")
  1153. }
  1154. ctx.JSON(http.StatusOK, QueryModelFileByID(id))
  1155. }
  1156. func QueryModelFileByID(id string) []storage.FileInfo {
  1157. model, err := models.QueryModelById(id)
  1158. if err == nil {
  1159. if model.Type == models.TypeCloudBrainTwo {
  1160. prefix := model.Path[len(setting.Bucket)+1:]
  1161. fileinfos, _ := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, prefix)
  1162. return fileinfos
  1163. } else if model.Type == models.TypeCloudBrainOne {
  1164. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  1165. fileinfos, _ := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, prefix)
  1166. return fileinfos
  1167. }
  1168. } else {
  1169. log.Error("no such model!", err.Error())
  1170. }
  1171. return nil
  1172. }
  1173. func QueryOneLevelModelFile(ctx *context.Context) {
  1174. id := ctx.Query("id")
  1175. if id == "" {
  1176. id = ctx.Query("ID")
  1177. }
  1178. parentDir := ctx.Query("parentDir")
  1179. model, err := models.QueryModelById(id)
  1180. if err != nil {
  1181. log.Error("no such model!", err.Error())
  1182. ctx.ServerError("no such model:", err)
  1183. return
  1184. }
  1185. if model.Type == models.TypeCloudBrainTwo {
  1186. log.Info("TypeCloudBrainTwo list model file.")
  1187. prefix := model.Path[len(setting.Bucket)+1:]
  1188. fileinfos, _ := storage.GetOneLevelAllObjectUnderDir(setting.Bucket, prefix, parentDir)
  1189. if fileinfos == nil {
  1190. fileinfos = make([]storage.FileInfo, 0)
  1191. }
  1192. ctx.JSON(http.StatusOK, fileinfos)
  1193. } else if model.Type == models.TypeCloudBrainOne {
  1194. log.Info("TypeCloudBrainOne list model file.")
  1195. prefix := model.Path[len(setting.Attachment.Minio.Bucket)+1:]
  1196. fileinfos, _ := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, parentDir)
  1197. if fileinfos == nil {
  1198. fileinfos = make([]storage.FileInfo, 0)
  1199. }
  1200. ctx.JSON(http.StatusOK, fileinfos)
  1201. }
  1202. }
  1203. func CreateLocalModel(ctx *context.Context) {
  1204. ctx.Data["isModelManage"] = true
  1205. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  1206. ctx.HTML(200, tplCreateLocalModelInfo)
  1207. }
  1208. func CreateLocalModelForUpload(ctx *context.Context) {
  1209. ctx.Data["uuid"] = ctx.Query("uuid")
  1210. ctx.Data["isModelManage"] = true
  1211. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  1212. ctx.Data["max_model_size"] = setting.MaxModelSize * MODEL_MAX_SIZE
  1213. ctx.HTML(200, tplCreateLocalForUploadModelInfo)
  1214. }
  1215. func CreateOnlineModel(ctx *context.Context) {
  1216. ctx.Data["isModelManage"] = true
  1217. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  1218. ctx.HTML(200, tplCreateOnlineModelInfo)
  1219. }