I am going to compare some emotion detection applications. I want to design a simple C# application to test emotion for large number of images using build-in code or built-in libraries. Can we download c# code for emotion detection from google cloud api?
Yes, you can. It has two ways either parse json response or you can use following method of native c# code.
For more detail visit
https://cloud.google.com/vision/docs/libraries#client-libraries-usage-csharp
using Google.Cloud.Vision.V1;
using System;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
// Instantiates a client
var client = ImageAnnotatorClient.Create();
// Load the image file into memory
var image = Image.FromFile("wakeupcat.jpg");
// Performs label detection on the image file
var response = client.DetectLabels(image);
foreach (var annotation in response)
{
if (annotation.Description != null)
Console.WriteLine(annotation.Description);
}
}
}
}
Related
I am trying to find the best way to see the last date a subscription in a topic was accessed via c# (SDK or otherwise) i.e. to purge the queue if not accessed in over x hours. I know there is that functionality built into the service bus explorer but have not been able to find any SDK functionality. If anyone could point me in the right direction it would be appreciated.
Please see the code below. It uses Azure.Messaging.ServiceBus SDK. The properties you're interested in is available in SubscriptionRuntimeProperties class.
using System;
using System.Threading.Tasks;
using Azure.Messaging.ServiceBus.Administration;
namespace ConsoleApp1
{
class Program
{
static async Task Main(string[] args)
{
string connectionString =
"connection-string";
string topicName = "topic-name";
string subscriptionName = "subscription-name";
ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClient(connectionString);
var result = await administrationClient.GetSubscriptionRuntimePropertiesAsync(topicName, subscriptionName);
Console.WriteLine(result.Value.AccessedAt.ToString("yyyy-MM-ddTHH:mm:ss"));
}
}
}
I'm trying to get Google Vision API to work with my project but having trouble. I keep getting the following error:
Grpc.Core.RpcException: 'Status(StatusCode=PermissionDenied, Detail="This API method requires billing to be enabled
I've created a service account, billing is enabled and I have the .json file. I've got the Environment variable for my account for GOOGLE_APPLICATION_CREDENTIALS pointing to the .json file.
I've yet to find a solution to my problem using Google documentation or checking StackOverFlow.
using Google.Cloud.Vision.V1;
using System;
using System.Collections.Generic;
namespace Vision
{
internal static class GoogleVision
{
public static EntityAnnotation[] GetAnnotations(EventManager em, string filePath, string EventNr)
{
{
ImageAnnotatorClient Client = ImageAnnotatorClient.Create();
Image Image = Google.Cloud.Vision.V1.Image.FromFile(filePath);
IReadOnlyList<EntityAnnotation> Response = Client.DetectLabels(Image);
EntityAnnotation[] annotations = new EntityAnnotation[Response.Count];
for (int i = 0; i < annotations.Length; i++)
{
annotations[i] = Response[i];
}
return annotations;
}
}
}
}
Not sure why but by setting the environment variable in the code rather than manually with windows, it fixed the problem.
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "thejsonfile");
is there any way or any DLL by which i can get location or coordinates of the first letter or alphabet found using OCR in windows form application C# without performing OCR on the whole document?
As i have used Aspose and tesseract Dll to perform OCR on image.it takes time while extracting text as it reads all the text but i want to just read the first word and get the coordinate of the first letter extracted. i have to implement it in windows form application using C#. please help.
Thanks in advance.!
Just as a disclaimer this answer is about a paid software toolkit and I work for the company.
You can check out the LEADTOOLS SDK which has the segmentation algorithm that I mentioned in my comment to zone the document and then find the top-left most zone of text and perform OCR on those bounds.
I wrote a console application to show an example of how to achieve this using the LEADTOOLS OCR NuGet:
https://www.nuget.org/packages/Leadtools.Ocr/
using Leadtools;
using Leadtools.Codecs;
using Leadtools.ImageProcessing.Core;
using Leadtools.Ocr;
using System;
using System.Linq;
namespace FindFirstZone
{
class Program
{
static IOcrEngine ocrEngine;
static RasterCodecs codecs;
static void Main(string[] args)
{
Initialize();
var image = codecs.Load(#"randomtext.png");
LeadRect rect = FindFirstZone(image);
DoOcr(image, rect);
Console.ReadLine();
}
static void Initialize()
{
RasterSupport.SetLicense(#"C:\LEADTOOLS 20\Common\License\LEADTOOLS.LIC",
System.IO.File.ReadAllText(#"C:\LEADTOOLS 20\Common\License\LEADTOOLS.LIC.KEY"));
codecs = new RasterCodecs();
ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD, false);
ocrEngine.Startup(null, null, null, null);
}
static LeadRect FindFirstZone(RasterImage img)
{
AutoZoningCommand autoZoningCommand = new AutoZoningCommand(
AutoZoningOptions.DetectAccurateZones |
AutoZoningOptions.DetectText |
AutoZoningOptions.DontAllowOverlap);
autoZoningCommand.Run(img);
if (autoZoningCommand.Zones != null && autoZoningCommand.Zones.Count > 0)
{
var sortedList = autoZoningCommand.Zones.OrderBy(z => z.Bounds.Top)
.ThenBy(z => z.Bounds.Left).ToList();
return sortedList[0].Bounds;
}
else
throw new Exception("No Zones");
}
static void DoOcr(RasterImage image, LeadRect rect)
{
using (var ocrPage = ocrEngine.CreatePage(image, OcrImageSharingMode.None))
{
ocrPage.Zones.Add(new OcrZone()
{
Bounds = rect,
ZoneType = OcrZoneType.Text,
});
ocrPage.Recognize(null);
Console.WriteLine(ocrPage.GetText(-1));
}
}
}
}
I tested this with some random text I generated (test image here) and here is the output from this program:
Fowl it heaven second don't thing won't third cattle from. Had said
fill brought evening, a said great him
I have these requirements coming from client every week for some new logic or verification. For which I have to code new logic (basically some if-else and loops) and launch a new build for him. I want to avoid it by simply coding my logic in visual studio then writing a utility to export it to XML or something and send it to client via e-mail. He just have to place this file in some appropriate folder and the application will behave considering this logic.
Please suggest some solutions. My platform is C# Asp.Net.
Thanks
Using .NET 4.6 and the NuGetPackage Microsoft.CodeAnalysis.Scripting you could implement a scripting engine to run your c# code residing in a textfile without building an assembly.
Install NuGet Package:
Install-Package Microsoft.CodeAnalysis.Scripting.CSharp
Implement TestClass with some basic C#-Code-Content:
class Program
{
static void Main(string[] args)
{
TestScript();
}
private static async void TestScript()
{
// Code snippet: a class with one string-property.
string codeContent = #" using System;
public class ScriptedClass
{
public string HelloWorld { get; set; }
public ScriptedClass()
{
HelloWorld = ""Hello Roslyn!"";
}
}
new ScriptedClass().HelloWorld";
// Instanciate CSharpScriptEngine
var engine = new CSharpScriptEngine();
// Execute code and return string property (HelloWorld)
var scriptingState = await engine.ExecuteAsync(codeContent);
// Print return value from CSharpScript
Console.WriteLine("Returned from CSharpScript: {0}", scriptingState.ReturnValue);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
}
Implement a ScriptingEngine:
internal sealed class CSharpScriptEngine
{
public async Task<ScriptState<object>> ExecuteAsync(string codeContent)
{
// Add references from calling assembly
ScriptOptions options = ScriptOptions.Default.AddReferences(Assembly.GetExecutingAssembly());
// Run codeContent with given options
return await CSharpScript.RunAsync(codeContent, options);
}
}
Read ScriptCode from textfile:
So basically you could read some csharpcode from a textfile of your choice and run them on the fly:
private static async void TestScript()
{
// Read in script file
string codeContent = File.ReadAllText(#"C:\Temp\CSharpScriptTest.cs");
var engine = new CSharpScriptEngine();
// Run script
var scriptingState = await engine.ExecuteAsync(codeContent);
Console.WriteLine("Returned from CSharpScript: {0}", scriptingState.ReturnValue);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
In case you are wondering how all of this works under the hood, Roslyn will create a so called submission from your script code. A submission is an in memory assembly containing the types generated around your script code, which can be identified among the assemblies in the current AppDomain by a ℛ prefix in the name.
The precise implementation details are not important here (though, for example, scriptcs heavily relies on understanding in detail how Roslyn works to provide its extra features), but it's important to know that submissions can be chained together. When they are chained, variables, methods or classes defined in an earlier submission are available to use in subsequent submissions, creating a feature of a C# REPL (read-evaluate-print loop).
C# and Visual Basic - Use Roslyn to Write a Live Code Analyzer for Your API
Hope it helps
I have Solr server running (on Linux box, not that it matter), it is loaded with 2M documents and search works fine in Java.
I need however to write C# (client) program to query it. I downloaded Solr.NET but I am confused what to begin with. Solutions included with it do not compile, and browsing through C# it does not look like the program is doing what I need to do.
Does anyone have a sort of Hello World program for Solr.NET in C#? Below I will publish Java version of what I and looking for, C# version anyone? Oh, and please, what minimum set of assemblies do I need to include into such simple client program? Thank you
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
public class SolrHeloWorld // Java
{
public static void main(String[] args)
{
// Connect to server
SolrServer solr = new HttpSolrServer ("http://192.168.1.211:8983/solr/collection1");
// Query for search term 'banana'
SolrQuery query = new SolrQuery();
query.setQuery("banana");
query.setStart(0);
query.setRows(50);
query.set("defType", "edismax");
try
{
QueryResponse response = solr.query(query);
// Print results
SolrDocumentList results = response.getResults();
for (int i = 0; i < results.size(); i++)
{
System.out.println(results.get(i));
}
}
catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
}
}
}
As suggested I have take another closer look at documentation for Solr.NET. Still, I wasn’t able to figure out which assemblies are missing in solutions that came with download so they still do not compile! More importantly it does not appear that you can write bare bone program that simply prints JSON without NHibernate, defining class mapping and all that.
Never the less, it is not that hard to write simple Hello World client program in C# that queries Solr. And it does not require Solr.NET at all! Here is the one that uses HttpWebRequest and JSON serializer/deserializer to simply print JSON of all documents returned by query
using System;
using System.Net;
using System.IO;
using System.Web.Script.Serialization; // Require adding System.Web.Extentions.dll
class SolrHeloWorld // C#
{
static void Main()
{
Uri uri = new Uri("http://192.168.1.211:8983/solr/collection1/select?q=banana&start=0&rows=50&wt=json&indent=true&defType=edismax");
WebRequest request = HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Get;
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string jsonResponse = reader.ReadToEnd();
response.Close();
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(jsonResponse);
dynamic dd = jsonObject["response"]["docs"];
Object[] results = (Object[])dd;
foreach (Object res in results)
{
Console.WriteLine(serializer.Serialize(res));
}
}
}
There is a course in Pluralsight that gets you started with Solr and SolrNet. The last module is about SolrNet specifically:
http://www.pluralsight.com/courses/enterprise-search-using-apache-solr