Skip to content
This repository has been archived by the owner on Jul 16, 2022. It is now read-only.

Feat 46 translate object detection function to dotnet #73

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions dotnet/object-detection/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
*.swp
*.*~
project.lock.json
.DS_Store
*.pyc
nupkg/

# Visual Studio Code
.vscode

# Rider
.idea

# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates

# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
build/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
msbuild.log
msbuild.err
msbuild.wrn

# Visual Studio 2015
.vs/

# Cloud Function Archive
code.tar.gz
14 changes: 14 additions & 0 deletions dotnet/object-detection/ObjectDetection.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<RootNamespace>ObjectDetection</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Appwrite" Version="0.2.0" />
<PackageReference Include="Cloudmersive.APIClient.NETCore.ImageRecognition" Version="2.0.6" />
</ItemGroup>

</Project>
78 changes: 78 additions & 0 deletions dotnet/object-detection/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
using Appwrite;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace ObjectDetection
{
class Program
{
static async Task Main(string[] args)
{
var filename = "temp.jpg";

// .NET parser is taking first property starting with "$" as metadata
var jsonSettings = new Newtonsoft.Json.JsonSerializerSettings()
{
MetadataPropertyHandling = Newtonsoft.Json.MetadataPropertyHandling.Ignore
};
var json = Environment.GetEnvironmentVariable("APPWRITE_FUNCTION_EVENT_DATA");

// Triggered by the storage.files.create event
var payload = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(json, jsonSettings);
var fileID = payload["$id"];

// // Setup appwrite client
var client = new Client();
client
.SetEndPoint(Environment.GetEnvironmentVariable("APPWRITE_ENDPOINT"))
.SetProject(Environment.GetEnvironmentVariable("APPWRITE_PROJECT_ID"))
.SetKey(Environment.GetEnvironmentVariable("APPWRITE_API_KEY"))
;

// Get the image file
var storage = new Storage(client);
var result = storage.GetFilePreview(fileID.ToString());

// Read bytes from the url we received
var clientt = new System.Net.WebClient();
clientt.Headers.Add("X-Appwrite-Project", Environment.GetEnvironmentVariable("APPWRITE_PROJECT_ID")); // needed as we only get url string without projectID
var bytes = await clientt.DownloadDataTaskAsync(new Uri(result));
//Save the file to the container
await File.WriteAllBytesAsync(filename, bytes);

// Configure API key authorization: Apikey
var configuration = new Cloudmersive.APIClient.NETCore.ImageRecognition.Client.Configuration();
configuration.ApiKey["Apikey"] = Environment.GetEnvironmentVariable("CLOUDMERSIVE_API_KEY");

// create an instance of the API class
var api_instance = new Cloudmersive.APIClient.NETCore.ImageRecognition.Api.RecognizeApi(configuration);
var image_file = filename; // file | Image file to perform the operation on. Common file formats such as PNG, JPEG are supported.

try
{
//Detect objects including types and locations in an image
var api_response = await api_instance.RecognizeDetectObjectsAsync(File.OpenRead(image_file));
if (api_response.Successful == true)
{
foreach (var item in api_response.Objects)
{
Console.WriteLine(item.ObjectClassName);
}
}
else
{
Console.WriteLine("It failed");
}
}
catch (System.Exception ex)
{
Console.WriteLine($"Exception when calling RecognizeApi->recognize_detect_objects: {ex}");
}
}
}
}
44 changes: 44 additions & 0 deletions dotnet/object-detection/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# 📷 Object Detection using Cloudmersive Vision API
A sample .Net Cloud Function for object detection on an image file uploaded by the user.

## 📝 Environment Variables
Go to Settings tab of your Cloud Function. Add the following environment variables.

* **APPWRITE_ENDPOINT** - Your Appwrite Endpoint
* **APPWRITE_PROJECT_ID** - Your Project ID
* **APPWRITE_API_KEY** - Your Appwrite API key with `files.read` and `files.write` permissions
* **CLOUDMERSIVE_API_KEY** - API key acquired from https://cloudmersive.com. There is free trie.

## 📝 Default Environment Variables
No need to add these variables, these are supplied by Appwrite itself.

* **APPWRITE_FUNCTION_EVENT_DATA** - Your function event payload. This value is available only when your function trigger is 'event'. This variable value contains a string in JSON format with your specific event data.

## 🚀 Building and Packaging

To package this example as a cloud function, follow these steps.

```bash
$ cd demos-for-functions/dotnet/object-detection

$ dotnet publish --runtime linux-x64 --framework net5.0 --no-self-contained
```

* Ensure that your output looks like this
```
StorageCleaner -> ......\demos-for-functions\dotnet\storage-cleaner\bin\Debug\net5.0\linux-x64\StorageCleaner.dll
StorageCleaner -> ......\demos-for-functions\dotnet\storage-cleaner\bin\Debug\net5.0\linux-x64\publish\
```

* Create a tarfile

```bash
$ tar -C bin/Debug/net5.0/linux-x64 -zcvf code.tar.gz publish
```

* Navigate to the Overview Tab of your Cloud Function > Deploy Tag
* Input the command that will run your function (in this case `dotnet ObjectDetection.dll`) as your entrypoint command
* Upload your tarfile
* Click 'Activate'
* Navigate to the Settings Tab of your Cloud Function > Events > select storage.files.create
* (optional) set Timeout to some 30s as function may timeout before fisnishing