Skip to content

Instantly share code, notes, and snippets.

@vade
Created September 21, 2021 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vade/ca264c8d60d91f02d3c647f8047ad29d to your computer and use it in GitHub Desktop.
Save vade/ca264c8d60d91f02d3c647f8047ad29d to your computer and use it in GitHub Desktop.
Swift API Server
//
// main.swift
// SynopsisAPIServer
//
// Created by vade on 4/12/21.
//
import Foundation
import Swifter
import CoreML
import Vision
func resizedImage(image:CGImage, for size: CGSize) -> CGImage? {
let context = CGContext(data: nil,
width: Int(size.width),
height: Int(size.height),
bitsPerComponent: 32,
bytesPerRow: 32 * 4 * Int(size.width),
space: CGColorSpace(name: CGColorSpace.sRGB)!,
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipLast.rawValue)
.union(.floatComponents).rawValue )
context?.interpolationQuality = .low
context?.draw(image, in: CGRect(origin: .zero, size: size))
guard let scaledImage = context?.makeImage() else { return nil }
return scaledImage
}
do {
let server = HttpServer()// demoServer(try String.File.currentWorkingDirectory())
server.listenAddressIPv4 = "10.0.1.156"
try server.start()
let config = MLModelConfiguration()
config.computeUnits = .all
var model:YOUR_CORE_ML_MODEL!
do {
model = try YOUR_CORE_ML_MODEL(configuration: config)
}
catch {
print("error loading model")
}
let analysis_queue = DispatchQueue.init(label: "analysis_queue")
server["/testAfterBaseRoute"] = { request in
return .ok(.htmlBody("ok !"))
}
server.POST["/api/v1/analyze_image"] = { request in
// print("got request")
var response = ""
for multipart in request.parseMultiPartFormData() {
guard let name = multipart.name, let fileName = multipart.fileName, let contentType = multipart.headers["content-type"] else { continue }
let body = multipart.body
let imageData = Data(body)
let provider = CGDataProvider(data: imageData as CFData)
var image:CGImage? = nil
if contentType == "image/png" {
image = CGImage(pngDataProviderSource: provider!, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
}
else if content == "image/jpeg" {
image = CGImage(jpegDataProviderSource: provider!, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
}
guard let img = image else {
print("no image bailing")
continue
}
guard let smallimg = resizedImage(image: img, for: CGSize(width: REQUIRED_IMAGE_WIDTH, height:REQUIRED_IMAGE_HEIGHT)) else {
print ("Cant resize image")
continue
}
// do {
//
//// analysis_queue.sync {
let semapher = DispatchSemaphore(value: 1)
DispatchQueue.main.async {
do {
// print("making input")
let input = try CinemaNet_3_15_5Input(ImageWith:smallimg)
let prediction = try model.prediction(input: input)
print(prediction.shot_type)
// print("running inference")
// print("fimished inference")
semapher.signal()
}
catch
{
print("error")
semapher.signal()
}
}
semapher.wait()
response += "Name: \(name) File name: \(fileName) Size: \(multipart.body.count)<br>"
}
print(response)
return HttpResponse.ok(.htmlBody(response))
}
if #available(OSXApplicationExtension 10.10, *) {
try server.start(9080, forceIPv4: true)
} else {
// Fallback on earlier versions
}
print("Server has started ( port = \(try server.port()) ). Try to connect now...")
RunLoop.main.run()
} catch {
print("Server start error: \(error)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment