I am trying to develop C# Google Vision API function.
the code is supposed to compile into dll and it should run to do the following steps.
get the image from the image Path.
send the image to Google vision api
Call the document text detection function
get the return value (text string values)
Done
When I run the dll, However, it keeps giving me an throw exception error. I am assuming that the problem is on the google credential but not sure...
Could somebody help me out with this? I don't even know that the var credential = GoogleCredential.FromFile(Credential_Path); would be the right way to call the json file...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Cloud.Vision.V1;
using Google.Apis.Auth.OAuth2;
using Image = Google.Cloud.Vision.V1.Image;
namespace DLL_TEST_NetFramework4._6._1version
{
public class Class1
{
public string doc_text_dection(string GVA_File_Path, string Credential_Path)
{
var credential = GoogleCredential.FromFile(Credential_Path);
//Load the image file into memory
var image = Image.FromFile(GVA_File_Path);
// Instantiates a client
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
TextAnnotation text = client.DetectDocumentText(image);
//Console.WriteLine($"Text: {text.Text}");
return $"Text: {text.Text}";
//return "test image...";
}
}
}
You just need to setup the environment variable GOOGLE_APPLICATION_CREDENTIALS as mentioned here
You mus have to mention you json file name in the environment variable as this.
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "Your_Json_File_Name.json");
Your code would look like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Cloud.Vision.V1;
using Google.Apis.Auth.OAuth2;
using Image = Google.Cloud.Vision.V1.Image;
namespace DLL_TEST_NetFramework4._6._1version
{
public class Class1
{
public string doc_text_dection(string GVA_File_Path, string Credential_Path)
{
//var credential = GoogleCredential.FromFile(Credential_Path);
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "Your_Json_File_Name.json");
//Load the image file into memory
var image = Image.FromFile(GVA_File_Path);
// Instantiates a client
ImageAnnotatorClient client = ImageAnnotatorClient.Create();
TextAnnotation text = client.DetectDocumentText(image);
//Console.WriteLine($"Text: {text.Text}");
return $"Text: {text.Text}";
//return "test image...";
}
}
}
or you can send it through your Credential_Path variable.
for more details please visit Google Vision API Docs
You need to setup your environment in your console with code like this :
Windows Server:
$env:GOOGLE_APPLICATION_CREDENTIALS="File Path"
Linux Server :
export GOOGLE_APPLICATION_CREDENTIALS="File Path"
Hope it helps!
Related
I am trying to use Stanford NLP for .NET. I am very new to this and I am having trouble in loading the models.
I have read the same kind of issue in https://sergey-tihon.github.io/Stanford.NLP.NET//faq.html and in Stanford.NLP for .NET not loading models. But I have no idea where they have saved the "stanford-corenlp-full-2016-10-31" folder.
This is where I have the C# code. C:\Users\Kabi\source\repos\Search\Search
And the stanford-corenlp-full-2017-06-09 folder is here - C:\Users\Kabi\source\repos\Search.
I have extracted the stanford-corenlp-3.8.0-models.jar in C:\Users\Kabi\source\repos\Search\stanford-corenlp-full-2017-06-09
This is my C# code.
Browse.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.IO;
using java.util;
using java.io;
using edu.stanford.nlp.pipeline;
using Console = System.Console;
namespace Search
{
class Browse
{
public void StanfordNLP()
{
// Path to the folder with models extracted from `stanford-corenlp-3.8.0-models.jar`
var jarRoot = #"..\stanford-corenlp-full-2017-06-09";
// Text for processing
var text = "Kosgi Santosh sent an email to Stanford University. He didn't get a reply.";
// Annotation pipeline configuration
var props = new Properties();
props.setProperty("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref");
props.setProperty("ner.useSUTime", "0");
// We should change current directory, so StanfordCoreNLP could find all the model files automatically
var curDir = Environment.CurrentDirectory;
Directory.SetCurrentDirectory(jarRoot);
var pipeline = new StanfordCoreNLP(props);
Directory.SetCurrentDirectory(curDir);
// Annotation
var annotation = new Annotation(text);
pipeline.annotate(annotation);
// Result - Pretty Print
using (var stream = new ByteArrayOutputStream())
{
pipeline.prettyPrint(annotation, new PrintWriter(stream));
Console.WriteLine(stream.toString());
stream.close();
}
}
}
}
How can I properly load the models?
It seems you are not able to locate your modals files try using this :-
I had copied stanford-corenlp-full-2017-06-09 under the root folder of my project i.e. NLP as displayed in image 1 in the picture itself the second one shows how I have extracted the stanford-corenlp-3.8.0-models.jar
The directory Structure of files
after doing so use
var jarRoot = #"......\stanford-corenlp-full-2016-10-31\stanford-corenlp-3.7.0-models";
It works Simply
I need help with this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace kbam_.API
{
class filea
{
public static string filea(string url) //this code right here
{
string contents;
var wc = new System.Net.WebClient();
contents = wc.DownloadString(url);
}
}
}
and yes I am authorized by kesbook uk to use this I'm the owner so I can use what I want http://kesbook.cf/autho
If you are querying a a RESTful API I would suggest using the Restsharp nugget package, it is much easier to use.
i am trying to learn connecting C# to Twitter by using tweetinvi.
i have no problem while connecting with Twitter Key and Twitter Token
then i debug my code, noticed null value on User.GetAuthenticatedUser()
however, i'm already authorize the twitter apps with my own twitter account.
Why does User.GetAuthenticatedUser() return Null Value ?
i got the following picture while trying to pass the error into Message Box
how do i resolve this ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tweetinvi;
namespace Twitdesk
{
public partial class Form1 : Form
{
Cl_Tweetinvi twitinvi;
Command cmd = new Command();
public Form1()
{
InitializeComponent();
twitinvi = new Cl_Tweetinvi();
var AuthenticatedUser = User.GetAuthenticatedUser();
if(AuthenticatedUser == null)
{
var latestException = ExceptionHandler.GetLastException();
MessageBox.Show(latestException.ToString());
Application.Exit();
}
else
{
var settings = AuthenticatedUser.GetAccountSettings();
}
var tweets = Timeline.GetHomeTimeline();
this.Text = cmd.title;
MessageBox.Show("done");
}
}
}
The problem comes from the fact that you have not initialized your credentials.
You need to call Auth.SetUserCredentials("CONSUMER_KEY", "CONSUMER_SECRET", "ACCESS_TOKEN", "ACCESS_TOKEN_SECRET"); before performing any operation.
When you have invoked this line any operation will be using these credentials.
Please take a quick look at the wiki for more information. Or let me know if you still encounter any problem.
Though the problem could be different as the error message seems to indicate that you have a timeout problem. Normally authentication problems return 401 exception.
I have a small problem. I just recently started using Twilio's API to generate a record of messages that was sent to my assigned SID and Auth Token. However my question is how can I generate a text file, based off of what the console writes from the source its addressed to?
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using Twilio;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// Find your Account Sid and Auth Token at twilio.com/user/account
string AccountSid = "X";
string AuthToken = "X";
var twilio = new TwilioRestClient(AccountSid, AuthToken);
// Build the parameters
var options = new MessageListRequest();
options.From = "2015-07-01";
options.To = "2015-07-13";
var messages = twilio.ListMessages(options);
foreach (var message in messages.Messages)
{
Console.WriteLine(message.Body);
Console.Read();
}
}
}
}
Writing to a text file is pretty much boilerplate. The methods are shown here:
https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
Looking at the sample code given on https://azure.microsoft.com/en-us/documentation/articles/hdinsight-hbase-tutorial-get-started/#use-the-net-hbase-rest-api-client-library,
I'm trying to connect to HBase from an MVC Controller as follows:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.HBase.Client;
using org.apache.hadoop.hbase.rest.protobuf.generated;
namespace MyHBaseTest.Controllers
{
[RoutePrefix("api/myhbasetestcontroller")]
public class MyHBaseTestController : ApiController
{
HBaseReader hbase = new HBaseReader();
[HttpGet]
[Route("")]
public IHttpActionResult Index()
{
string clusterURL = "https://<yourHBaseClusterName>.azurehdinsight.net";
string hadoopUsername = "<yourHadoopUsername>";
string hadoopUserPassword = "<yourHadoopUserPassword>";
// Create a new instance of an HBase client.
ClusterCredentials creds = new ClusterCredentials(new Uri(clusterURL), hadoopUsername, hadoopUserPassword);
HBaseClient hbaseClient = new HBaseClient(creds);
// Retrieve the cluster version
var version = hbaseClient.GetVersion();
Console.WriteLine("The HBase cluster version is " + version);
return Ok();
}
}
}
When I try to view the URL /api/myhbasetestcontroller in my browser when it is run in debug mode, it keeps loading the page forever without throwing any exception or anything in Visual Studio. I have waited for 15-20 minutes but nothing changes.
When I put try to do the same in a console application, it gets the version information in a matter of seconds though:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.HBase.Client;
using org.apache.hadoop.hbase.rest.protobuf.generated;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string clusterURL = "https://<yourHBaseClusterName>.azurehdinsight.net";
string hadoopUsername= "<yourHadoopUsername>";
string hadoopUserPassword = "<yourHadoopUserPassword>";
// Create a new instance of an HBase client.
ClusterCredentials creds = new ClusterCredentials(new Uri(clusterURL), hadoopUsername, hadoopUserPassword);
HBaseClient hbaseClient = new HBaseClient(creds);
// Retrieve the cluster version
var version = hbaseClient.GetVersion();
Console.WriteLine("The HBase cluster version is " + version);
}
}
}
I just don't understand how it makes a difference really.
Could you please advice?
Many thanks.
As of today, you need to run your calls on a background thread. I ran into this same exact issue. My calls are consolidated under a single function. I run that function on a background thread and everything works great.
// POST: api/Vizzini
[ResponseType(typeof(string))]
public async Task<IHttpActionResult> GetResponse(string tweet)
{
string s = await Task.Run(() =>
{
return ResponseEngine.GetBestResponse(tweet);
});
return Ok(s);
}
You are using blocking synchronous APIs, which won't work in the context of MVC/Web app (due to using wrong async context by default). You need to use async version of the methods. E.g. for GetVersion use GetVersionAsync.