Skip to content

Instantly share code, notes, and snippets.

@mc256
Created December 6, 2019 16:21
Show Gist options
  • Save mc256/1d9ce33207218856c07614fe6a3890b6 to your computer and use it in GitHub Desktop.
Save mc256/1d9ce33207218856c07614fe6a3890b6 to your computer and use it in GitHub Desktop.

Revisions

  1. mc256 created this gist Dec 6, 2019.
    41 changes: 41 additions & 0 deletions torch_example.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@

    private lazy var module: TorchModule = {
    if let filePath = Bundle.main.path(forResource: "model", ofType: "pt"),
    let module = TorchModule(fileAtPath: filePath) {
    return module
    } else {
    fatalError("Can't find the model file!")
    }
    }()

    private lazy var labels: [String] = {
    if let filePath = Bundle.main.path(forResource: "words", ofType: "txt"),
    let labels = try? String(contentsOfFile: filePath) {
    return labels.components(separatedBy: .newlines)
    } else {
    fatalError("Can't find the text file!")
    }
    }()

    override func viewDidLoad() {
    super.viewDidLoad()

    /*
    let image = UIImage(named: "image.png")!
    imageView.image = image
    let resizedImage = image.resized(to: CGSize(width: 224, height: 224))
    guard var pixelBuffer = resizedImage.normalized() else {
    return
    }
    guard let outputs = module.predict(image: UnsafeMutableRawPointer(&pixelBuffer)) else {
    return
    }
    let zippedResults = zip(labels.indices, outputs)
    let sortedResults = zippedResults.sorted { $0.1.floatValue > $1.1.floatValue }.prefix(3)
    var text = ""
    for result in sortedResults {
    text += "\u{2022} \(labels[result.0]) \n\n"
    }
    resultView.text = text
    */
    }