OCR on Windows Phone 8 WP8 - windows-phone-8

I'm new to the world of programming, and am trying to develop an app that uses OCR.
I want the app to convert a singular receipt into text (nothing too complex).
However my problem is that i'm finding a lack of information for OCR on WP8, and how to implement it.
I would have though that it's a built in function of WP and that information would be easily accessible as to how to implement it.
Anyone know where I could look, or a simple example snippet of code I could use?
Not wanting a subscription based service.

Microsoft recently released the OCR Library for Windows Runtime. Jerry Nixon has posted a video guiding you though it, and there is also an msdn article.
Jerry Nixon's Blog
MSDN

You can try using the same OCR service that the Bing Lens uses. If you haven't tried it: open camera, change lens to bing lens and try it out
The service endpoint is http://ocrrest.bingvision.net/V1. It also gives you information about the location of the detected text with their bounding boxes
Probably some fiddler analysis will help you to send your image in a similar fashion.
I have a little snippet below which expects the image as byte array
public static readonly string ocrServiceUrl = "http://ocrrest.bingvision.net/V1"; // was: "platform.bing.com/ocr/V1";
public static readonly string ocrLanguage = "en";
public static async Task<JsonObject> MakeOcrJSON(byte[] image)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("{0}/Recognize/{1}", ocrServiceUrl, ocrLanguage));
request.Method = "POST";
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(image, 0, image.Length);
}
try
{
using (HttpWebResponse response = (HttpWebResponse) (await request.GetResponseAsync()))
{
using (var responseStream = new StreamReader(response.GetResponseStream()))
{
var json = JsonObject.Parse(responseStream.ReadToEnd());
return json;
}
}
}
catch (WebException we)
{
using (Stream responseStream = we.Response.GetResponseStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(OcrResponse));
OcrResponse ocrResponse = (OcrResponse)serializer.ReadObject(responseStream);
string ErrorMessage = "Unknown Error";
if (ocrResponse.OcrFault.HasValue)
{
ErrorMessage = string.Format(
"HTTP status code: {0} Message: {1}",
ocrResponse.OcrFault.Value.HttpStatusCode,
ocrResponse.OcrFault.Value.Message);
}
throw new Exception(ErrorMessage);
}
}
}

Related

Get Access Token - Design Automation for Revit

I have created the app, was able to debug the source code.
Also received Client ID and Client secret.
I need your help to understand how to get access token.
Basically this part -
enter image description here
It will be really helpful if you can provide a sample code on how to send the HTTP request as I am novice to web API's.
I have added this code to my solution -
enter image description here
enter image description here
Thanks,
STR
Here is a working example, how to obtain an Access token.
You need to add NewtonSoft.Json nuget package to your project to run it.
public class TokenModel
{
[JsonProperty("access_token")]
public string AccessToken;
}
public async Task<string> GetToken()
{
var credentials = new Dictionary<string, string>();
credentials.Add("client_id", "YOUR_CLIENT_ID");
credentials.Add("client_secret", "YOUR_CLIENT_SECRET");
credentials.Add("grant_type", "YOUR_GRANT_TYPE");
credentials.Add("scope", "YOUR_SCOPE");
var content = new FormUrlEncodedContent(credentials);
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("https://developer.api.autodesk.com");
var response = await client.PostAsync("/authentication/v1/authenticate", content);
if (response.IsSuccessStatusCode)
{
var responseData = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<TokenModel>(responseData).AccessToken;
}
}
}
And simple usage:
var token=await GetToken();
It is not perfect, I've tried to simplify all the moments.

Update text block from downloaded text file = RPC_E_WRONG_THREAD WP8.1

I am learning Windows Phone 8.1 development, I have probably done something utterly incorrectly programming wise
The need: I want to download a text file from the web using HttpClient() and display it in the TextBlock1
From variety of tutorials I have found the following:
public async void DownloadDataAsync()
{
string data = "some link to Textfile.txt";
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(data);
HttpContent content = response.Content;
string result = await content.ReadAsStringAsync();
UpdateTextBlock1(result);
}
Then the other functions.
public void UpdateTextBlock1(string result)
{
TextBlock1.Text = result;
}
private void BtnDownloadData_Click(object sender, RoutedEventArgs e)
{
Task t = new Task(DownloadDataAsync);
t.Start();
}
The code starts well enough - on button pressed, I receive RPC_E_WRONG_THREAD.
Is it that I'm trying to call the method when all threads haven't finished? How can I code that efficently so the TextBlock1 is updated with txt data?
Thanks for understanding, baby steps here in programming, and I couldn't find a relevant answer over google. (Maybe I don't yet know how to ask?)
You need to update the textblock on the UI thread like so:
Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
TextBlock1.Text = result;
});
There are many posts on this subject.

Setting Description in Metadata for Google Drive Android API

Is there any way to set the Metadata Description?
https://developer.android.com/reference/com/google/android/gms/drive/Metadata.html#getDescription()
If so, what is the length limit?
I can't see anything in the api: https://developer.android.com/reference/com/google/android/gms/drive/MetadataChangeSet.Builder.html
Unfortunately not at the moment, AFAIK. What I do right now is initializing both GDAA and RESTful API (see the 'trash solution' SO 22295903) like this:
private GoogleApiClient _gac;
private com.google.api.services.drive.Drive _svc;
public GoogleApiClient init(String email){
_gac = new GoogleApiClient.Builder(UT.ACTX).addApi(com.google.android.gms.drive.Drive.API)
.addScope(com.google.android.gms.drive.Drive.SCOPE_FILE).setAccountName(email).build();
com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential crd =
GoogleAccountCredential.usingOAuth2(UT.ACTX,
Arrays.asList(com.google.api.services.drive.DriveScopes.DRIVE_FILE));
crd.setSelectedAccountName(email);
_svc = new com.google.api.services.drive.Drive.Builder(
AndroidHttp.newCompatibleTransport(), new GsonFactory(), crd).build();
return this;
}
You get the description from DGAA (GoogleApiClient _gac above), but update/write it to RESTFul like this (off UI thread):
public void oldDescUpW(String titl, String mime, String desc) {
try {
final FileList gLst = _svc.files().list()
.setQ("title = '"+titl+".jpg' and mimeType = '"+mime+"' and trashed = false")
.setFields("items(id)").execute();
if (gLst.getItems().size() == 1) {
final String sId = gLst.getItems().get(0).getId();
com.google.api.services.drive.model.File body =
new com.google.api.services.drive.model.File();
body.setDescription(desc);
_svc.files().patch(sId, body).execute();
}
} catch (Exception e) {}
}
It is also possible to use 'resource ID' from GDAA to address the file in RESTful, but it is not always immediately available (if the file is created in GDAA). See SO 22874657
DISCLAIMER:
It is a HACK and should not stay alive past GDAA delivery of an alternative.

Error trying to connect to an mvc server on ms-azure from a windows phone 8 app using webapi

I'm a little bit new to all of these technologies so I'll try to be as clear as I can.
I'm writing a windows phone app that sends data in string format to a server:
public class sendDataControl
{
private string response = "";
public void sendToServer(string FullSTR)
{
try
{
WebClient webClient = new WebClient();
Uri uri = new Uri("http://pricequeryserver.azurewebsites.net/api/ReceiptDataService/?incomingdata=");
webClient.UploadStringAsync(uri,FullSTR);
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
}
catch (Exception ex)
...
...
}
}
void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
if (e.Error != null)
{
responseXml=e.Error.Message;
MessageBox.Show(responseXml);
return;
}
else
{
responseXml = e.Result;
}
}
}
The server is an MVC4, basic, with api controller I added, that needs to get the data sent from the mobile.
As a test I'm just getting back a string that I send:
public class ReceiptDataServiceController : ApiController
{
private ReceiptContext db = new ReceiptContext();
...
...
public string GetDataFromMobile(string IncomingData)
{
return IncomingData;
}
}
While running the application I get an error via responseXml:
"The remote server returned an error: NotFound".
The server returns the right answer from all kinds of browsers, while on IIS and on the azure but not from the mobile emulator.
Any suggestions?
If you take a look at the documentation for UploadStringAsync overload you are using, you will notice that it sends data using POST method. While in your controller you have only implemented GET. And for your
You have to use other overload of UploadStringAsync, which lets you specify the HTTP VERB to use. And you must specify GET. Your client code should be converted to:
webClient.UploadStringAsync(uri,"GET", FullSTR);
And the best solution for simple GET operations like your is to actually use DownloadStringAsync:
var fullUri = new Uri("http://pricequeryserver.azurewebsites.net/api/ReceiptDataService/?incomingdata=" + FullStr);
webClient.DownloadStringAsync(fullUri);
Anyway, your question has nothing to do with Windows Azure, thus the removed tag.

apache httpclient- most efficient way to read response

I'm using apache httpcompnonents library for httpclient. I want to use it in a multithreaded application where number of threads are going to be really high and there would be frequent http calls. This is the code I'm using to read the response after execute call.
HttpEntity entity = httpResponse.getEntity();
String response = EntityUtils.toString(entity);
I just want to confirm that is it the most efficient way of reading the response?
Thanks,
Hemant
This in fact represents the most inefficient way of processing an HTTP response.
You most likely want to digest the content of the response into a domain object of a sort. So, what is the point of buffering it in-memory in a form of a string?
The recommended way to deal with response processing is by using a custom ResponseHandler that can process the content by streaming it directly from the underlying connection. The added benefit of using a ResponseHandler is that it completely relieves from dealing with connection release and resource deallocation.
EDIT: modified the sample code to use JSON
Here's an example of it using HttpClient 4.2 and Jackson JSON processor. Stuff is assumed to be your domain object with JSON bindings.
ResponseHandler<Stuff> rh = new ResponseHandler<Stuff>() {
#Override
public Stuff handleResponse(
final HttpResponse response) throws IOException {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() >= 300) {
throw new HttpResponseException(
statusLine.getStatusCode(),
statusLine.getReasonPhrase());
}
HttpEntity entity = response.getEntity();
if (entity == null) {
throw new ClientProtocolException("Response contains no content");
}
JsonFactory jsonf = new JsonFactory();
InputStream instream = entity.getContent();
// try - finally is not strictly necessary here
// but is a good practice
try {
JsonParser jsonParser = jsonf.createParser(instream);
// Use the parser to deserialize the object from the content stream
return stuff;
} finally {
instream.close();
}
}
};
DefaultHttpClient client = new DefaultHttpClient();
Stuff mystuff = client.execute(new HttpGet("http://somehost/stuff"), rh);