interpreters.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2022 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "fmt"
  17. "path/filepath"
  18. "sync"
  19. "github.com/mattn/go-tflite"
  20. "github.com/lf-edge/ekuiper/internal/conf"
  21. )
  22. var ipManager *interpreterManager
  23. func init() {
  24. path, err := conf.GetDataLoc()
  25. if err != nil {
  26. panic(err)
  27. }
  28. ipManager = &interpreterManager{
  29. registry: make(map[string]*tflite.Interpreter),
  30. path: filepath.Join(path, "uploads"),
  31. }
  32. }
  33. type interpreterManager struct {
  34. sync.Mutex
  35. registry map[string]*tflite.Interpreter
  36. path string
  37. }
  38. func (m *interpreterManager) GetOrCreate(name string) (*tflite.Interpreter, error) {
  39. m.Lock()
  40. defer m.Unlock()
  41. ip, ok := m.registry[name]
  42. if !ok {
  43. mf := filepath.Join(m.path, name+".tflite")
  44. model := tflite.NewModelFromFile(mf)
  45. if model == nil {
  46. return nil, fmt.Errorf("fail to load model: %s", mf)
  47. }
  48. defer model.Delete()
  49. options := tflite.NewInterpreterOptions()
  50. options.SetNumThread(4)
  51. options.SetErrorReporter(func(msg string, user_data interface{}) {
  52. fmt.Println(msg)
  53. }, nil)
  54. defer options.Delete()
  55. ip = tflite.NewInterpreter(model, options)
  56. status := ip.AllocateTensors()
  57. if status != tflite.OK {
  58. ip.Delete()
  59. return nil, fmt.Errorf("allocate failed: %v", status)
  60. }
  61. m.registry[name] = ip
  62. }
  63. return ip, nil
  64. }